id
stringlengths
3
6
prompt
stringlengths
100
55.1k
response_j
stringlengths
30
18.4k
27993
I am trying to make a plugin which lists all users from a database with for each user a button to send an email to them. So the only way I can get with their username their email adress is to use the $POST which is given after the button is clicked. With their username I can search the db table to retreive the email. The problem here is that the page will reload and the function wp\_mail is called before the pluggable.php has loaded its functions. Here is the post: ``` if ($_POST) { sendEmail(current(array_keys($_POST))); echo "<script type='text/javascript'>alert('Email is sent!')</script>"; } ``` And here is the function: ``` function sendEmail($username) { global $wpdb; $user = $wpdb->get_row("SELECT email, firstname from wp_site_users WHERE username ='" . $username ."'" , ARRAY_A); $mail = $wpdb->get_row("SELECT * from wp_send_email WHERE id='1'", ARRAY_A); $to = $user['email']; $subject = 'Hello!'; $message = $mail['header'] . $user['firstname'] ."\n"; $message .= $mail['content'] . $username . "\n"; $message .= $mail['footer']; $headers = 'From: '.'test@test.com'."\r\n"; echo $to . "<br>" . $subject . "<br>" . $message . "<br>" . $headers; wp_mail($to, $subject, $message, $headers); } ``` I've tried to add `add_action( 'plugins_loaded', 'sendEmail' );` at the header but that doesn't seem to work. Any ideas?
Without using `typedef` or `using` then it's not possible to access to the container's type. However you can specialize the `bar` function where you know what the container's type is. ``` template<> void bar<Parent::Inner>() { // Here, you know what the parent is } ```
28134
I want to organize my Scala packages and love how Python solves this issue with `pip`. **Can you recommend a similar tool for the management of Scala packages?** **EDIT:** I am looking for an easy installation of new packages with all it's dependencies like ``` >>> pip install <a_package> # installs a_package with all dependencies. ```
The most directly similar is probably [Scala Build Tool](http://www.scala-sbt.org/). Specifically, [Library Dependencies](http://www.scala-sbt.org/release/docs/Getting-Started/Library-Dependencies.html). The Java ecosystem includes many libraries and build tools, Scala is built on Java. So you gain the ability to leverage things like - * [Maven](http://maven.apache.org/) * [Gradle](http://www.gradle.org/) * [Scala Build Tool](http://www.scala-sbt.org/) Further, because everything is run inside a virtual machine; there is no "system" level install. You can start with your [CLASSPATH](http://www.scalaclass.com/node/10) and for more investigate [class loading](http://www.developer.com/java/other/article.php/2248831/Java-Class-Loading-The-Basics.htm). ``` #!/bin/sh # From http://www.scalaclass.com/node/10 - CLASSPATH L=`dirname $0`/../lib cp=`echo $L/*.jar|sed 's/ /:/g'` exec scala -classpath "$cp" "$0" "$@" !# import com.my.Goodness val goodness = new Goodness world.hello ```
28275
I use FME a lot for manipulation of spatial data, and would like to leverage it's Python library, fmeobjects in PyQgis. If I run the following in my standard Python IDE it works fine: ``` import sys sys.path.append("C:\\Program Files (x86)\\fme\\fmeobjects\\python27") import fmeobjects ``` But the exact same code, when run in PyQgis, throws ImportError: DLL load failed: The specified module could not be found. In actual fact, fmeobjects is a .pyd file. I don't know if that's the problem, as my understanding is that pyd and dll are analogous to each other. How can I get fmeobjects to import into PyQgis?
2016 update! Been trying to get this to work myself and thought I'd put what I've researched so far. This is done on Windows 10. For Linux users - try [this](https://knowledge.safe.com/questions/21273/run-fmeobjects-on-linux.html) if you're encountering problems. Warning: For those wanting to integrate FME 2016 into python qgis, know that it isn't as easy as 'pip install fmeobjects' :) --- Step 1 Locate your fmeobjects.pyd file. This I think is the hardest part really! See [here](https://stackoverflow.com/questions/8822335/what-do-the-python-file-extensions-pyc-pyd-pyo-stand-for) for an intro to .pyd files. It's basically a Python Windows DLL file. For Python 2.7 the file should be at: ``` C:\apps\FME2016\fmeobjects\python27\fmeobjects.pyd ``` QGIS doesn't use Python3 yet as of now, but if it does in upcoming QGIS 3 version, you should use: ``` C:\apps\FME2016\fmeobjects\python34\fmeobjects.pyd ``` For me, the file was located at D:\apps\FME2016\fmeobjects\python27\fmeobjects.pyd. So search around until you find that file. --- Step 2 Next, let's import the fmeobjects module! The most official documentation I can find is [here](https://knowledge.safe.com/articles/302/errors-fmeworkspacerunner-python-errors-fmeobjects.html), note that it refers to FME 2015, but it should work on 2016. In 'theory', the following code should work: ``` import sys sys.path.append("C:\\apps\\FME2016\\fmeobjects\\python27") import fmeobjects ``` **Advanced** If you are getting the error "ImportError: DLL load failed: The specified module could not be found", see [here](https://gis.stackexchange.com/a/19259/78212). Now, if you're keen, you can go to <http://www.dependencywalker.com/>, download the application (it's portable) and search for your fmeobjects.pyd file, and run it [![fmeobjects.pyd in dependencywalker](https://i.stack.imgur.com/QYFos.png)](https://i.stack.imgur.com/QYFos.png) [![fmeobjects.pyd in dependencywalker](https://i.stack.imgur.com/N5pWs.png)](https://i.stack.imgur.com/N5pWs.png) See how fme.dll, fmepython27.dll, fmeutil.dll and rwtool\_fme.dll are yellow in the second image? Those are missing dependencies not in our sys.path. Those four files appear to located in a higher level directory (D:\apps\FME2016\ in my case). So we add that top-level directory to our sys.path, and also cd (change directory) to where fme is located so that fmeobjects will load properly. The python script thus becomes: ``` import os import sys sys.path.append("C:\\apps\\FME2016\\fmeobjects\\python27") sys.path.append("C:\\apps\\FME2016\\") #add this os.chdir("C:\\apps\\FME2016\\") #do this too (somehow needed) import fmeobjects ``` --- Step 3 Verify that things work. ``` licMan = fmeobjects.FMELicenseManager() # Print FME license type. print 'FME License Type :', licMan.getLicenseType() # FME license property names. ``` Note: if you get the error "FMEException: FMEException: -1:" here, I think that means your python script is not running on the same machine as FME Desktop. E.g. your code is on your local drive but FME is installed on a server. --- Step 4 [Run a workbench](https://knowledge.safe.com/questions/2030/run-workbench-from-external-python.html)! ``` worker = fmeobjects.FMEWorkspaceRunner() worker.run('D:/fme/Workspaces/test.fmw') ``` --- Step 5 Immerse yourself in the [API](http://docs.safe.com/fme/html/FME_Objects_Python_API/index.html). --- Personally, I run my script over and over again alot, so I have some if-then statements and try-except stuff: ``` import sys fmePydPath = "C:\\apps\\FME2016\\fmeobjects\\python27" #fme file path fmePath = "C:\\apps\\FME2016\\" if fmePydPath not in sys.path: sys.path.append(fmePydPath) #prevents too much appending if fmePath not in sys.path: sys.path.append(fmePath) os.chdir(fmePath) import fmeobjects #Verifies that things work licMan = fmeobjects.FMELicenseManager() # Print FME license type. print 'FME License Type :', licMan.getLicenseType() # FME license property names. #Runs a workspace (.fmw) file try: worker = fmeobjects.FMEWorkspaceRunner() worker.run('D:/fme/Workspaces/test.fmw') except fmeobjects.FMEException, err: print "FMEException: %s" % err ```
28424
Could anybody provide an example how to get the attributes of selected features? I tried the following code in the Python Console : but I'm stuck at the point where I'd like to get the attributes: ```py from qgis.utils import iface canvas = iface.mapCanvas() cLayer = canvas.currentLayer() selectList = [] if cLayer: count = cLayer.selectedFeatureCount() print (count) selectedList = layer.selectedFeaturesIds() for f in selectedList: # This is where I'm stuck # As I don't know how to get the Attributes of the features ```
This will work: ```py layer = iface.activeLayer() features = layer.selectedFeatures() for f in features: print f.attributeMap() ``` In PyQGIS 3: ```py layer = iface.activeLayer() features = layer.selectedFeatures() for f in features: # refer to all attributes print (f.attributes()) # results in [3, 'Group 1', 4.6] for f in features: # refer to a specific values of a field index print(f.attribute(1)) # results in Group 1 ```
28737
I was just watching a History Channel documentary [on YouTube](http://www.youtube.com/watch?v=R6JOMvOwECo) called "Kingjongilia" about people who have managed to escape North Korea. Having visited South Korea a bunch of times now, I realize I didn't notice any kind of museum on these people and their plight. Googling for one now isn't helping much either. **Is there such a museum somewhere in South Korea?**
Unfortunately, I do not have a positive answer to this question. I have been looking around the web for a few days now and I am almost sure there is no such museum. I have been through the [list of museums in South Korea](http://en.wikipedia.org/wiki/List_of_museums_in_South_Korea) with the help of Google Translate but with no luck. There is not even one comment about such a museum in any website. I think I can safely say such a museum does NOT exist in South Korea.
29411
I'm bit confused with how MessageContract Attribute works in WCF. When I put the MessageContract the proxy shows two parameters instead of 1. e.g. ``` GetResultResponse GetOperation(GetResultRequest request) [MessageContract] public class GetResultRequest { [MessageHeader] public Header Header { get; set; } [MessageBodyMember] public List<Person> PersonList { get; set; } } ``` The proxy generates this method signature: ``` GetOperation(ref Header, List<Person> personList) ``` When I remove MEssageContract Attributes: Proxy Generates correct signatures: ``` GetOperation(GetResultRequest request) ``` Could anyone please confirm if this is the expected behavour?
That is default behavior. When you generate proxy it doesn't create message contracts by default. You can turn this on in [advanced configuration](http://msdn.microsoft.com/en-us/library/bb514724.aspx) in *Add Service reference* (by checking *Always generate message contracts*) or by `/messageContract` switch in [svcutil](http://msdn.microsoft.com/en-us/library/aa347733.aspx). Once you turn it on you will get methods with single message contract parameter as you have on the service.
29510
My program generates doc file on browser and i want to save this file to my C drive dynamically ``` string filename = "fileName"; Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename= " + filename +".doc" ); Response.Charset = ""; Response.ContentType = "application/vnd.ms-word "; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); GridView1.AllowPaging = false; GridView1.DataBind(); GridView1.RenderControl(hw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); ```
You cannot decide for the user where to save the file. User decides that.
30027
We are working with Python 3, where we have a list of datetimes, which looks like this: ``` first_datetime = {2019-08-08 14:00:00, 2019-08-08 14:10:00, 2019-08-08 14:20:00, 2019-08-08 14:30:00, 2019-08-08 14:40:00, 2019-08-08 14:50:00, 2019-08-08 15:00:00} ``` What we want is to only append datetimes, where minutes in datetime is either 00, 20 or 40, into a new list. Therefore above list should look like: ``` new_datetime_list = {2019-08-08 14:00:00, 2019-08-08 14:20:00, 2019-08-08 14:40:00, 2019-08-08 15:00:00} ``` Our program looks like following: ``` for i in range(len(first_datetime)): time = datetime.datetime.strptime(first_datetime[i], '%Y-%m-%d %H:%M:%S') if time != x: new_datetime_list.append(first_datetime[i]) ``` We imagine that we could do something like: ``` for i in range(len(first_datetime)): time = datetime.datetime.strptime(first_datetime[i], '%Y-%m-%d %H:%M:%S') if time != x and time != CAN'T CONTAIN 10, 30, 50 IN MINUTES: new_datetime_list.append(first_datetime[i]) ``` Although we dont know how to to the above, hence we are posting this post.
You can check the minutes using `time.minute in [0, 20, 40]`, so your snippet of code could look like ```py for i in range(len(first_datetime)): time = datetime.datetime.strptime(first_datetime[i], '%Y-%m-%d %H:%M:%S') if time != x and time.minute in [0, 20, 40]: new_datetime_list.append(first_datetime[i]) ``` (I have kept the `time != x` condition, not sure if you need it for something else you didn't mention) btw you can simplify the way you iterate through the array without using indexes like this: ```py for str_datetime in first_datetime: time = datetime.datetime.strptime(str_datetime, '%Y-%m-%d %H:%M:%S') if time != x and time.minute in [0, 20, 40]: new_datetime_list.append(str_datetime) ```
30171
I want to write an JUnit @Rule (version 4.10) to setup some objects (an Entity Manager) and make them available in the test, by "injecting" it into an variable. Something like this: ``` public class MyTestClass() { @Rule MyEntityManagerInjectRule = new MyEntityManagerInjectRule(): //MyEntityManagerInjectRule "inject" the entity manager EntityManger em; @Test... } ``` The Problem is that I do not know how to get the current instance of `MyTestClass` in the MyEntityManagerInjectRule (extends TestRule), because it has only one method. `Statement apply(Statement base, Description description);` Within Description there is only the class MyTestClass but not the instance used for the test. An alternative would be using org.junit.rules.MethodRule but this is deprecated. Before and After are not sufficient for this task, because then I would need to copy the code to the tests, and they are more or less deprecated too. (See Block4JClassRunner.withBefores / withAfters). So my question in how could I access the test class instance without using deprecated stuff.
How about: ``` public class MyTestClass() { @Rule public TestRule MyEntityManagerInjectRule = new MyEntityManagerInjectRule(this); // pass instance to constructor //MyEntityManagerInjectRule "inject" the entity manager EntityManger em; @Test... } ``` Just add the test class instance to the constructor for the `@Rule`. Just be careful of the order of assignment.
30634
For example, I have a 100 row table with a `varchar` column. I run these queries: ``` SELECT count(*) FROM myTable WHERE myText LIKE '%hello%' SELECT count(*) FROM myTable WHERE myText NOT LIKE '%hello%' ``` I am not getting a total count of 100. It is not picking up some of the rows for some reason. Why would this be happening?
Check for `NULL` values, neither `LIKE` nor `NOT LIKE` will count these.
30736
we have an app running in bluemix under two different routes: myapp.shortname.com myapp.reallyreallyreallyreallylongname.com but the SSO service does not work with myapp.shortname.com giving an error: > > CWOAU0062E: The OAuth service provider could not redirect the request > because the redirect URI was not valid. Contact your system > administrator to resolve the problem. > > > is it possible to support two routes or do we now have to run two NodeJS apps?
That's easy, just define a dictionary which maps characters to their replacement. ``` >>> replacers = {'A':'Z', 'T':'U', 'H':'F'} >>> inp = raw_input() A T H X >>> ''.join(replacers.get(c, c) for c in inp) 'Z U F X' ``` I don't know where exactly you want to go and whether case-sensitivity matters, or if there's a more general rule to determine the replacement character that you did not tell us - but this should get you started. *edit*: an explanation was requested: `(replacers.get(c, c) for c in inp)` is a generator which spits out the following items for the example input: ``` >>> [replacers.get(c, c) for c in inp] ['Z', ' ', 'U', ' ', 'F', ' ', 'X'] ``` For each character `c` in the input string `inp` we ge the replacement character from the `replacers` dictionary, or the character itself if it cannot be found in the dictionary. The default value is the second argument passed to `replacers.get`. Finally, `''.join(some_iterable)` builds a string from all the items of an iterable (in our case, the generator), glueing them together with the string `join` is being called on in between. Example: ``` >>> 'x'.join(['a', 'b', 'c']) 'axbxc' ``` In our case, the string is empty, which has the effect of simply concatenating all the items in the iterable.
30774
I'm reaching out to see if the community can help identify a book (or series of books) from my childhood in the 80s. To the best of my recollection, the stories were about a family of vampires - but they may have been nonspecific "monsters." I believe one among them was considered very handsome because he looked almost human (speculation: implying the others had varying levels of disfigurement from their vampirism/monster-ness) Wracking my brain for further plot details, the only strand I can eke out is possibly that the family of vampires wanted to take over the world, but one among them had misgivings; that's bordering on mistaken memory, though, I'm running on empty for more plot detail. I remember thinking for the longest time that it was one of Roald Dahl's works; the tone of the story and artwork *felt* very Dahl-esque, but his bibliography reveals the work I'm referencing is not his. The work was aimed at the 6 - 10 age group, not really up to YA. I'm also fairly sure this was a series of books, not just one. The artwork was sporadic, i.e. it wasn't a-picture-a-page type of story. I read the book in English, which I'm almost sure was it original language of publication; very likely it was by an English author. I doubt the work was from before the 70s, and it would not have been from the 90s. I've trawled the internet searching for various permutations and combinations of vampire/family/80s/children's book to no avail. I didn't think this work was that obscure, but it apparently is; I'm hoping someone out there might have ideas what this may be.
I think that this may be a book by Angela Sommer-Bodenburg. Originally published in 1986 as My Friend The Vampire, it was apparently republished In 2005 under the title The Little Vampire, possibly to tie in with the movie made based on it. That was the first of a series so you might have read a later one possibly. Blurb from Amazon as follows: Tony, a 9-year-old horror story addict is delighted when a little vampire called Rudolph lands on his windowsill one evening, and together, the two have a series of hilarious adventures involving visits to Rudolph’s home—The Vampire Family Vault—where Tony narrowly escapes the clutches of Great-Aunt Dorothy. From my memory, it had a very Dahl feel to the writing, and the artwork (which was sporadic) was something of a cross between Dahl and Gorey. I haven’t read it in over thirty years, but I recall the two kids becoming friends, the vampire kid bringing the human kid home, and the human kid dressing as a vampire and having to hide from the aunt, who keeps wandering around saying how she can smell a human.
31068
I am mixing C with C++ source code using GNU. `_Decimal64` is recognised fine in C, but not in C++. C++ complains `error: '_Decimal64' does not name a type`. Is there any way I can fix this? Should I consider it a compiler bug? **Update 20-Mar-2017 18:19**: None of the answers meet my requirements so far. I don't want to use the `decimal64` C++ class, I want to use the `_Decimal64` C type. My project is mostly written in C, but I want to slowly introduce C++ code. Here, for example, is part of `cell.h`: ``` union vals { num c_n; //double c_d; char *c_s; long c_l; int c_i; struct rng c_r; }; ``` It is made use of in `cells.c`, which of course is C code. `num` is defined in `numeric.h`: ``` #pragma once #ifdef __cplusplus #define USE_DECIMAL 0 #else #define USE_DECIMAL 1 #endif #if USE_DECIMAL typedef _Decimal64 num; #define NUM_HUNDREDTH 0.01DL #define NUM_TEN 10.0DL #else typedef double num; #define NUM_HUNDREDTH 0.01 #define NUM_TEN 10.0 #endif ``` Notice that I have use `typedef double num` to get a compile on the C++ side. C++ doesn't actually `num` type, but it is inevitably included because it needs some of the functionality in the C files. It's faking it, of course.`num` isn't a double, it's really a `_Decimal64`. I'm asking how I can get around this kludge.
For C++ "decimal64" use `std::decimal::decimal64` the standard says: <https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.6/a00454.html>
31322
**Note:** Before marking this question as duplicate, please verify that the other question answers the topic for this setup: * OS: Windows 10, 64-bit * Python version: 3.6 or higher * Python Compiler: Nuitka, development version 0.5.30rc5 * MSVC compiler: Visual Studio 2017 Community, vcvars64.bat 1. How I build my exe --------------------- I'll first explain how I build my executable. Suppose I have a folder with a simple python script that I want to build: [![enter image description here](https://i.stack.imgur.com/xRSni.png)](https://i.stack.imgur.com/xRSni.png) The `buildscript.py` looks like this: ``` ##################################################### # NUITKA BUILD SCRIPT # ##################################################### # Author: Matic Kukovec # Date: April 2018 import os import platform NUITKA = "C:/Python36/Scripts/nuitka3-script.py" # Path where my nuitka3-script.py is CWD = os.getcwd().replace("\\", "/") MSVC = "C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Auxiliary/Build/vcvars64.bat" PYTHON_VERSION = "3.6" PYTHON_EXE_PATH= "C:/Python36/python.exe" NUMBER_OF_CORES_FOR_COMPILATION = 1 # 1 is the safest choice, but you can try more # Generate command command = '"{}" amd64 &'.format(MSVC) command += "{} ".format(PYTHON_EXE_PATH) command += "{} ".format(NUITKA) command += "--python-version={} ".format(PYTHON_VERSION) command += "--output-dir={}/output ".format(CWD) command += "--verbose " command += "--jobs={} ".format(NUMBER_OF_CORES_FOR_COMPILATION) command += "--show-scons " # command += "--windows-disable-console " # command += "--icon={}/myicon.ico ".format(CWD) command += "--standalone " # command += "--run " command += "{}/cubeimporter.py ".format(CWD) os.system(command) print("END") ``` 2. Result of the build ---------------------- After the build finishes, the folder looks like this (see picture below). As you can see, there are plenty of other files sitting next to the executable. I can see `.dll` and `.pyd` files. [![enter image description here](https://i.stack.imgur.com/KYc3j.png)](https://i.stack.imgur.com/KYc3j.png) 3. Desired result ----------------- I wish I could build just a standalone executable. No dll- or other files needed. When I put the executable on a thumb drive and stick it into another computer (running Windows 10, 64-bit), it should just work. Even if there is no Python installed on that computer. Is this possible with Nuitka? If no, is it possible with another Python compiler? Please provide all the steps needed, one-by-one :-)
Easier than Nuitka for a single executable is e.g. PyInstaller: `pyinstaller --onefile program.py` (to disable the console window for GUI applications add the `-w` option). To create a single executable with Nuitka, you can create a SFX archive from the generated files. You can run Nuitka with the `--standalone` option which generates a `program_dist` directory. Create then a 7-Zip SFX config file `config.txt`: `;!@Install@!UTF-8! GUIMode="2" ExecuteFile="%%T/program_dist/program.exe" ;!@InstallEnd@!` Then get the 7-Zip SFX from <https://github.com/chrislake/7zsfxmm> (from releases – `7zsd_extra_171_3901.7z`) and unpack the `7zsd_All_x64.sfx` file. Pack then the `program_dist` with 7-Zip (so the folder is included in the archive) to program.7z. Then, an SFX can be created with `copy /b 7zsd_All_x64.sfx + config.txt + program.7z single_executable.exe`. On Unix, you can also create yourself an SFX if you create a tar archive and append it to a shell script which extract it and unpack it, for details see <https://www.linuxjournal.com/node/1005818>.
31495
I've got a working migration on dev and I'm trying to migrate in test. `rake:migrate` works up until the latest migration that I added today. I was running `db:migrate` and it the output was inclusive of the latest migration. I have also confirmed that the table in question exists in my local DB. When I tried to run `rake test:functionals ...` I get the following: ``` You have 1 pending migrations: 20130506153458 AddProcessingErrorsTable Run `rake db:migrate` to update your database then try again. ``` So I ended up running the following command and getting the appropriate output I wanted: ``` rake db:migrate:redo VERSION=20130506153458 RAILS_ENV=test == AddProcessingErrorsTable: reverting ===================== -- drop_table("processing_errors") -> 0.0098s == AddProcessingErrorsTable: reverted (0.0098s) ============ == AddProcessingErrorsTable: migrating ===================== -- create_table(:processing_errors) -> 0.0185s == AddProcessingErrorsTable: migrated (0.0195s) ============ ``` I still get the same error message when I try run the tests now: ``` You have 1 pending migrations: 20130506153458 AddProcessingErrorsTable Run `rake db:migrate` to update your database then try again. ``` Thanks for any help you can give me.
Usually you don't have to migrate your test database. It sounds like the development database is not migrated yet. Every time you are running your tests, the development schema is used as a basis for testing db. Try migrating your development database before running tests: ``` rake db:migrate ``` Maybe that's it.
31608
The following code defines my Bitmap: ``` Resources res = context.getResources(); mBackground = BitmapFactory.decodeResource(res, R.drawable.background); // scale bitmap int h = 800; // height in pixels int w = 480; // width in pixels // Make sure w and h are in the correct order Bitmap scaled = Bitmap.createScaledBitmap(mBackground, w, h, true); ``` ... And the following code is used to execute/draw it (the unscaled Bitmap): ``` canvas.drawBitmap(mBackground, 0, 0, null); ``` My question is, how might I set it to draw the scaled Bitmap returned in the form of `Bitmap scaled`, and not the original?
Define a new class member variable: `Bitmap mScaledBackground;` Then, assign your newly created scaled bitmap to it: `mScaledBackground = scaled;` Then, call in your draw method: `canvas.drawBitmap(mScaledBackground, 0, 0, null);` Note that it is not a good idea to hard-code screen size in the way you did in your snippet above. Better would be to fetch your device screen size in the following way: ``` int width = getWindowManager().getDefaultDisplay().getWidth(); int height = getWindowManager().getDefaultDisplay().getHeight(); ``` And it would be probably better not to declare a new bitmap for the only purpose of drawing your original background in a scaled way. Bitmaps consume a lot of precious resources, and usually a phone is limited to a few MB of Bitmaps you can load before your app ungracefully fails. Instead you could do something like this: ``` Rect src = new Rect(0, 0, bitmap.getWidth() - 1, bitmap.getHeight() - 1); Rect dest = new Rect(0, 0, width - 1, height - 1); canvas.drawBitmap(mBackground, src, dest, null); ```
31684
I'm considering a passive solar radiant heating installation in the Chicago area and was wondering if it would be feasible to store enough water/energy to support heating for most of the night. The house already has a gas central furnace, and can serve as backup, but the winter bills have been as high as $300-400 (for about 300 to 400 therms) during last year's expensive gas rates. Roughly how much water might be needed to keep ~2000 sqft heated when it's 0 outside overnight in a below average insulated house? Orders of magnitude would be good enough of an estimate. I'm really just looking to understand if this is feasible. If this would require a basement swimming pool, obviously it's not. Also, since the PEX would be installed on the unfinished basement ceiling, I'm a bit concerned about the basement heating up too much. I assume there are ways to shield the basement from the radiant heat via some form of heat reflectors under the PEX?
You could use a plug cutter to remove the screw and surrounding wood. ![Typical plug cutter](https://i.stack.imgur.com/UK8as.jpg)
32269
[![enter image description here](https://i.stack.imgur.com/tVxUX.png)](https://i.stack.imgur.com/tVxUX.png) I'm using ggplot and I get those weird horizontal lines out of geom\_bar. I cannot provide a minimal working example: the same code works with few observations and it relies on data I am importing and transforming. However, I can show the relevant line of codes and cross my fingers someone ran into this issue: ``` ggplot(data) + geom_bar(aes(x=Horizon, y=Importance, fill=Groups), position='fill', stat='identity') + theme_timeseries2() + scale_fill_manual(values=c('#1B9E77', 'orange2', 'black', 'red2', 'blue4')) + xlab('') + ylab('') ``` My personal function, `theme_timeseries2()` isn't the source of the problem: it happens even if I stop after geom\_bar. I checked for missing values in `Importance` and every other column of my data frame and there are none. It's also very odd: the white lines aren't the same on the zoomed page as in the plot window of RStudio. They do print in .png format when I save the file, so there really is something going on with those horizontal bars. Any theory about why `geom_bar()` does this would be highly appreciated.
I'm guessing the lines are due to a plotting bug between observations that go into each bar. (That could be related to the OS, the graphics device, and/or how ggplot2 interacts with them...) I expect it'd go away if you summarized before ggplot2, e.g.: ``` library(dplyr); data %>% count(Horizon, Groups, wt = Importance, name = "Importance") %>% ggplot() + geom_col(aes(x = Horizon, y= Importance, fill = Groups), position = "fill") + .... ```
32460
I am in the final stages of my PhD and have been applying for postdocs for the last six months. Recently, I heard back from the job I applied for, we had a phone interview and he was very happy with my experience and skills. In fact he was looking for a new postdoc with the same experience what I did in my PhD. We communicated through emails in a very friendly way and he invited me to visit his lab. We scheduled the visit but he wanted to talk to my references before that. He sent an email to my present PhD supervisor and asked him what would be a good time to talk over the phone. My supervisor didn't reply to him for at least a couple of weeks. I know this because every week, I used to get an email from him to remind my PhD supervisor to reply to his email. Finally, my PhD supervisor replied and they talked over the phone. The potential postdoc mentor suddenly took a U-turn after that. He said i may not be a good fit and he will stop this right here. I am really freaking out in this situation. I initially had problems with my PhD advisor because he is very aggressive and loves to make racist jokes. But I managed to handle his sense of humor and aggression. But I feel like he is racially prejudiced to me and will spoil my whole career.
I will share some information with you, based on two things you mentioned: > > a) You said your advisor is very aggressive and loves to make racist jokes > > > b) You suspect your advisor soured your postdoc application through negative remarks to your prospective employer > > > This sounds like a situation which *might* be investigatable by the Office for Civil Rights (OCR), if your PhD institution receives any federal funds. If you decide you would like this investigated by OCR, you would need to file a complaint within 6 months of becoming aware of alleged discrimination. A complaint of this kind can be filed by an individual working alone without a lawyer. You might be able to find a lawyer would would help you with the complaint pro bono (free) or with a reduced cost. It would be helpful to cite as much specific information about (a) as possible. However, you can send the complaint letter quickly and then submit more specific information subsequently. It can be helpful to file these complaints quickly rather than not quickly, because some regional OCR offices are extremely backed up. If OCR feels that your complaint letter fits with their purview, and meets some other basic requirements, but your letter doesn't include specific information such as dates of incidents and descriptions of incidents, then you will be asked to provide specifics. If you want to learn more about this: <https://www2.ed.gov/about/offices/list/ocr/docs/howto.html> The part I feel most unsure about is the employment aspect. However, the How-To page I linked to mentions > > Some of the civil rights laws enforced by OCR also extend to employment. > > > Each university has an office that addresses discrimination issues, so you could in principle bring the issue to them. However, many people have found it more effective to either go ahead and file with OCR, or draft an OCR complaint and share the draft with the institution (as a draft). Alternatively, you could instead try an **informal approach**: make an appointment with a department administrator and share your concern. The response you get could help you decide about next steps. Here's a relatively gentle way of starting such a conversation: > > I had a job interview that seemed to be going great --until suddenly it wasn't going great any more. I'd like to get some constructive feedback so that I can do better in subsequent interviews. But it would be awkward for me to ask my advisor directly for feedback. (Answer truthfully but with a very neutral tone if you're asked why.) Can you help facilitate me getting some constructive feedback from Prof. So-and-So (your advisor)? > > > If you're part of a graduate student union, it might be helpful to bring the problem to them to see if they can provide support. --- \*\*11/25 additional notes 11/25: 1. Your university may have an all-purpose grievance procedure that can be used in general situations, even when there's no alleged racial discrimination. 2. In the answer I wrote yesterday I was only providing information. Now I'll provide a couple of strategy notes. If I were in your shoes I would probably start with the informal approach I outlined yesterday, and try to keep it in the department. I'd avoid using any language that might alarm the department administration, and keep the tone very calm and neutral. But at the same time, I'd be working quietly on collecting evidence and witnesses, and starting to draft a complaint. Putting the facts down on paper can be an extremely useful exercise. 3. I recommend that you avoid escalating your concern beyond your department. But if your university chooses to do so, I'd recommend you do one of the following, pretty quickly: (a) find an ally or a lawyer (b) submit a complaint to OCR (c) submit a draft OCR complaint to your university Reason: some universities play hard ball. It would be safest to protect yourself in case your university turns out to be one of those. If I had strong evidence for the racism allegations, and did not have an ally or a lawyer, I would likely go with (c). A draft complaint could give you some useful leverage. When OCR investigates, it requires that the university submit a lot of documentary evidence (both about your particular situation, and also about its policies and procedures), and it conducts interviews. Institutions generally find this onerous and often would prefer to resolve the potential complainant's concerns pretty quickly, in order to prevent an OCR complaint from being filed. Note that filing an OCR complaint provides protection against retaliation. Note also that it can be a frustratingly slow process. Therefore it would be good to try to get your goals clear before you talk to anyone. I imagine your goals at this point are 1. Graduate 2. Get a post-doc I hope you find a good administrator in your department.
32843
I tried to find this in the relevant RFC, [IETF RFC 3986](https://www.rfc-editor.org/rfc/rfc3986), but couldn't figure it. Do URIs for HTTP allow Unicode, or non-ASCII of any kind? Can you please cite the section and the RFC that supports your answer. *NB: For those who might think this is not programming related - it is. It's related to an ISAPI filter I'm building.* --- **Addendum** I've read section 2.5 of RFC 3986. But RFC 2616, which I believe is the current HTTP protocol, predates 3986, and for that reason I'd suppose it cannot be compliant with 3986. Furthermore, even if or when the HTTP RFC is updated, there still will be the issue of rationalization - in other words, *does an HTTP URI support ALL of the RFC3986 provisos, including whatever is appropriate to include non US-ASCII characters?*
Here is an example: ☃.net. In terms of the relevant section of RFC 3986, I think you are looking at [2.5](https://www.rfc-editor.org/rfc/rfc3986#section-2.5). EDIT: Apparently stack overflow doesn't detect this as a proper URL. You'll have to copy&paste into your browser.
33365
The following doesn't compile ``` public static T Retrieve<T>(this NameValueCollection collection, String key) where T : Object { if (collection.AllKeys.Contains(key)) { try { val = (T)Convert.ChangeType((object)collection[key], typeof(T)); } catch { } } return val; } ``` because the Constraint cannot be the object class. So is there a way to contrain T for anything that can be set to a null?
``` where T : class ``` Your current constraint, `where T : Object` says "anything which is or inherits from System.Object", which is: everything. All types, including Int32 and String, inherit from System.Object. So constraining on Object would do nothing. Edit: as usual, Eric shines a light on this [in a far more accurate way](http://blogs.msdn.com/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx): > > "in C# every type derives from object". Not true! The way to correct this myth is to simply replace "derives from" with "is convertible to", and to ignore pointer types: **every non-pointer type in C# is convertible to object.** > > >
33416
I am pretty new to TestNG framework. I did download TestNG from the link <http://beust.com/eclipse>. Post this I created a new Java Project named as MyProject and a new TestNG class file "NewTest". I did write a small piece of Code with @Test annotation to launch Firefox browser and navigate to Google. I tried searching the web for possible solutions to sort this issue but I am not able to find the low level steps on how this can be corrected. Please help. **Output** ``` org.testng.TestNGException: Cannot find class in classpath: NewTest at org.testng.xml.XmlClass.loadClass(XmlClass.java:81) at org.testng.xml.XmlClass.init(XmlClass.java:73) at org.testng.xml.XmlClass.<init>(XmlClass.java:59) at org.testng.xml.TestNGContentHandler.startElement(TestNGContentHandler.java:582) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(Unknown Source) at javax.xml.parsers.SAXParser.parse(Unknown Source) at org.testng.xml.XMLParser.parse(XMLParser.java:39) at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:16) at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:9) at org.testng.xml.Parser.parse(Parser.java:170) at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:305) at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:109) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81) ``` [![enter image description here](https://i.stack.imgur.com/OTbaZ.png)](https://i.stack.imgur.com/OTbaZ.png)
You just need to append an `'m'` to each time and the `strptime` will parse it. Oneliner -------- ``` list(map(lambda s: datetime.strptime(s+'m', '%I:%M%p'), s) for s in (s.strip().split('-') for s in l) ``` Output (*redacted for clarity*): ``` [[datetime(…, 06, 0), datetime(…, 11, 0)], [datetime(…, 19, 0), datetime(…, 23, 0)], [datetime(…, 09, 0), datetime(…, 16, 0)], [datetime(…, 09, 0), datetime(…, 16, 0)], [datetime(…, 10, 0), datetime(…, 16, 0)], [datetime(…, 10, 0), datetime(…, 15, 0)]] ``` Readable -------- ``` def parse(times): split_times = (s.strip().split('-') for s in times) parsed_times = [] for time_group in split_times: parsed_group = [] for time_str in time_group: parsed_time = datetime.strptime(time_str + 'm', '%I:%M%p') parsed_group.append(parsed_time) parsed_times.append(parsed_group) return parsed_times ```
33784
I have a class with a private static method with an optional parameter. How do I invoke it from another class via Reflection? There is a similar [question](https://stackoverflow.com/questions/135443/how-do-i-use-reflection-to-invoke-a-private-method-in-c), but it does not address static method or optional parameters. ``` public class Foo { private static void Bar(string key = "") { // do stuff } } ``` How do I invoke `Foo.Bar("test")` and `Foo.Bar()` (e.g. without passing the optional parameter)?
Optional parameter values in C# are compiled by injection those values at the callsite. I.e. even though your code is ``` Foo.Bar() ``` The compiler actually generates a call like ``` Foo.Bar("") ``` When finding the method you need to treat the optional parameters as regular parameters. ``` var method = typeof(Foo).GetMethod("Bar", BindingFlags.Static | BindingFlags.NonPublic); ``` If you know exactly what values you want to invoke the method with you can do: ``` method.Invoke(obj: null, parameters: new object[] { "Test" }); ``` If you only have some of the parameters and want to honor the values of the default ones you have to inspect the method's [`ParameterInfo`](http://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo.aspx) objects to see if the parameters are optional and what those values are. For example to print out the default values of those parameters you could use the following code: ``` foreach (ParameterInfo pi in method.GetParameters()) { if (pi.IsOptional) { Console.WriteLine(pi.Name + ": " + pi.DefaultValue); } } ```
34372
I have this part of query: ``` IF(orders = NULL OR orders = '', "value1', 'value2') ``` which works with empty cells but not with null ones, any help? When it's NULL it doesn't make anything but when it's '' it runs the query
It's spelled `orders is NULL` (not `orders = NULL`).
34725
I'm trying to send to a ArrayList Strings that come from the user input: ``` private static void adicionarReserva() { Scanner adiciona = new Scanner(System.in); System.out.println("Numero da pista: "); int nPista = adiciona.nextInt(); System.out.println("Numero de jogadores: "); int nJogadores = adiciona.nextInt(); System.out.println("Data Inicio: "); String data_inicio = adiciona.next(); Reservas reserva = new Reservas(nPista, data_inicio); ArrayList<Jogadores> nome_jogador = new ArrayList(); for (int i=1;i<=nJogadores;i++) { System.out.println("Nome Jogador: "); String nome = adiciona.next(); nome_jogador.add(nome); } reserva.addJogadores(nome_jogador); } ``` In my Class called: Reservas, i have this: ``` public void addJogadores(Jogadores lista_jogadores) { this.lista_jogadores.add(lista_jogadores); } ``` But i have this error: ``` nome_jogador.add(nome); ``` > > The method add(Jogadores) in the type ArrayList is not applicable for the arguments (String) > > > And this one: ``` reserva.addJogadores(nome_jogador); ``` > > The method addJogadores(Jogadores) in the type Reservas is not applicable for the arguments (ArrayList) > > > Any one can help me out?
It's very meaningful error you're getting. This is your `ArrayList`: ``` ArrayList<Jogadores> nome_jogador = new ArrayList(); ↑ ``` What are you trying to insert to it? a `String`, but it suppose to have `Jogadores` in it. Now look at your `addJogadores` method signature: ``` public void addJogadores(Jogadores lista_jogadores) ↑ ``` It accepts `Jogadoers` object and not an `ArrayList`.
34956
This is a sample of the code that I am using to instantiate a JFrame: ``` public class TestFrame{ public static void main(String[] args){ JFrame frame = new JFrame(); Insets insets = frame.getInsets(); frame.setSize(new Dimension(insets.right + insets.left + 400, insets.bottom + insets.top + 400)); System.out.println(String.format("Top = %d \nBottom = %d \nLeft = %d \n Right = %d", insets.top, insets.bottom, insets.left, insets.right)); frame.setResizable(false); frame.setVisible(true); } } ``` The frame is displaying fine but all of the insets seem to be equal to zero. I need to know the size of the title bar on top because I want a Content Pane of size 400x400 exactly. I tested it on multiple platforms and the same thing happens on windows and on mac. What am I doing wrong ?
1. If you want your content pane to be precisely 400x400, then I would consider setting its preferredSize to 400x400 (although I don't like to force preferred size, on a content pane, it may be acceptable, in some cases). 2. After setting that preferred size and before showing the frame, call `pack()` on the frame. This is the cleanest and easiest solution, and you don't have to care about border insets.
35217
PS E:\React Native\contacts> npm i @react-navigation/native npm WARN jscodeshift@0.11.0 requires a peer of @babel/preset-env@^7.1.6 but none is installed. You must install peer dependencies yourself. npm WARN react-native@0.64.2 requires a peer of react@17.0.1 but none is installed. You must install peer dependencies yourself. npm WARN react-shallow-renderer@16.14.1 requires a peer of react@^16.0.0 || ^17.0.0 but none is installed. You must install peer dependencies yourself. npm WARN react-test-renderer@17.0.1 requires a peer of react@17.0.1 but none is installed. You must install peer dependencies yourself. npm WARN tsutils@3.21.0 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself. npm WARN use-subscription@1.5.1 requires a peer of react@^16.8.0 || ^17.0.0 but none is installed. You must install peer dependencies yourself. npm WARN @react-navigation/native@5.9.4 requires a peer of react@\* but none is installed. You must install peer dependencies yourself. npm WARN @react-navigation/core@5.15.3 requires a peer of react@\* but none is installed. You must install peer dependencies yourself. npm ERR! code ENOENT npm ERR! syscall rename npm ERR! path E:\React Native\contacts\node\_modules@react-navigation\core\node\_modules\react-is npm ERR! dest E:\React Native\contacts\node\_modules@react-navigation\core\node\_modules.react-is.DELETE npm ERR! errno -4058 npm ERR! enoent ENOENT: no such file or directory, rename 'E:\React Native\contacts\node\_modules@react-navigation\core\node\_modules\react-is' -> 'E:\React Native\contacts\node\_modules@react-navigation\core\node\_modules.react-is.DELETE' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Hello\AppData\Roaming\npm-cache\_logs\2021-06-10T04\_29\_31\_173Z-debug.log
The reason behind this is that npm deprecated [auto-installing of peerDependencies] since npm@3, so required peer dependencies like babel-core and webpack must be listed explicitly in your `package.json.` All that you need to do is to install babel-core. <https://github.com/npm/npm/issues/6565>
35237
I am trying to ultimately use php's `shell_exec` function to create new Linux users. I am, however, running into problems even with the debugging. Here is my code ``` <?PHP function adduser($username,$password,$server){ try{ //3 debug statements $output=shell_exec("pwd"); echo $output; shell_exec("touch test.txt"); //3 debug statements are requested by Christian echo '<pre>'; print_r(execute('pwd')); print_r(execute('touch test.txt')); //actuall code $output=shell_exec("ssh root@$server \"adduser $username; echo $password | passwd $username --stdin\""); } catch(Exception $e){ echo 'could not add user '.$e->getMessage(); } } $servers = array('192.168.1.8'); foreach($servers as $server){ echo $_GET['USER']." ".$_GET['PASSWORD']; adduser($_GET['USER'],$_GET['PASSWORD'],$server); } ``` The `try-catch` statements don't do anything, leading me to believe that shell errors are not propagated as PHP errors (Python is this way also). The line `$output=shell_exec("pwd")` returns the correct directory. The line `shell_exec("touch test.txt")`, however, fails to create th file test.txt (even if I give the full path '/home/user/.../test.txt'). Needless to say, the actual code for adding users does not work also. **EDIT** I managed to fix some of the code. The `touch test.txt` error was as a result of insufficient permissions. Apache logs in with user www-data, I simply created a home folder for that user, and made sure to touch a file in that home folder. The addition of the three debug statements, as per Christian's requests, are however causing problems now. **EDIT** Upon further inspection, it has to do with the inability to ssh as root when logging in as user www-data. `ssh -v` returns `debug1: read_passphrase: can't open /dev/tty: No such device or address`. My guess is that ssh is asking that generic "would you like to permanently add xxx to known\_hosts" but I can't respond. Is there anyway to manually add a user to the known hosts list?
a) This is true, if the class defines *other* constructors - thereby suppressing generation of a default constructor. ``` struct Foo { Foo(int n) : mem(n) {} int mem; }; ``` This class can't be value-initialized. b) If the class has *no* constructors defined, value-initialization will simply value-initialize all sub-objects (base classes and non-static members) ``` struct Foo { Foo() : mem(0) {} int mem; }; struct Bar { Foo f; }; ``` Value-initialization of `Bar` simply means that the `f` member will be value-initialized. See e.g. [What do the following phrases mean in C++: zero-, default- and value-initialization?](https://stackoverflow.com/questions/1613341/what-do-the-following-phrases-mean-in-c-zero-default-and-value-initializati)
35409
I am reading a Codeigniter book, it said like this, > > When using the keywords TRUE,FALSE, and NULL in your > application, you should always write > them in Uppercase letters. > > > Why does Codeigniter need all the keywords write as uppercase letters?
CodeIgniter/PHP does not require that you write those words in uppercase letters of not. However it is [CodeIgniter's Coding Style](http://codeigniter.com/user_guide/general/styleguide.html) to write them like this. CodeIgniter has been developing following that Coding Style, so if you want your code to look like CodeIgniter's, then you should follow that as well... Also if you want to share any of your work with the CodeIgniter community then it will be written how they would expect. See [Coding Conventions](http://en.wikipedia.org/wiki/Coding_standard)
35608
i'm trying to catch an discord.js error This error pops up when internet is off, but i want some clean code instead this messy one... How can i catch this? I did really try everything.. code: ``` (node:11052) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc ordapp.com at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26) (Use `node --trace-warnings ...` to show where the warning was created) (node:11052) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To termin ate the node process on unhandled promise rejection, use the CLI flag `--unhandl ed-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejecti ons_mode). (rejection id: 2) (node:11052) [DEP0018] DeprecationWarning: Unhandled promise rejections are depr ecated. In the future, promise rejections that are not handled will terminate th e Node.js process with a non-zero exit code. ``` i did try this at the very top : ``` process.on('uncaughtException', function (err) { //console.log('### BIG ONE (%s)', err); console.log("555") }); ``` aswell this one : ``` client.on('error', error => { if (error.code === 'ENOTFOUND') { console.log(no internet!!) } }); ``` I also did try this to see where its from, but nothing shows up its still the same ``` try { var err = new Error("my error"); Error.stackTraceLimit = infinity; throw err; } catch(e) { console.log("Error stack trace limit: ") console.log(Error.stackTraceLimit); } ``` ``` Error stack trace limit: 10 (node:11008) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc ordapp.com ``` here is the code i use for now what gives the error. i just want to catch the error in something like this: (No connection) ``` const Discord = require('discord.js') const client = new Discord.Client({ autoReconnect: true }); const opn = require('opn') const getJSON = require('get-json') const request = require('request'); const config = require("./config/config.json"); const pushbullet = require("./config/pushbullet.json"); const addons = require("./config/addons.json"); const Registration = require("./config/Reg.json"); client.on('uncaughtException', function (err) { //console.log('### BIG ONE (%s)', err); console.log("555") }); client.login(config.Settings[0].bot_secret_token); ```
I'm not sure I fully understand your use case, the way I'd model the relationship between your types is something like the following ```js type Season = | "winter" | "spring" | "summer" | "fall" type Month = | "January" | "February" | "March" | "April" | "May" | "June" | "July" | "August" | "September" | "October" | "November" | "December" type SeasonStruct = { temperature: number startMonth: Month } type Seasons = { [K in Season]: SeasonStruct } const seasons: Seasons = { winter: { temperature: 5, startMonth: "December" }, spring: { temperature: 20, startMonth: "March" }, summer: { temperature: 30, startMonth: "June" }, fall: { temperature: 15, startMonth: "September" }, } ``` This should give you enough building blocks to represent everything you need in your domain, hope it helps.
35770
Well so I'm trying to parse a bit of JSon. I succeeded to parse: Member.json: ``` {"member":{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":"peter@adress.com "}} ``` but what if I need to parse: ``` {"Members":[{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":‌​‌​"peter@adress.com"},{"id":645231,"name":"Bill","profileIconId":123,"age":56,"em‌​ai‌​l":"bill@adress.com"}]} ``` Ofcourse I searched the web, I think, I need to use "List<>" here `private List<memberProfile> member;`but how do I "get" this from my main class?? I used this to parse the first string: memeberClass.java ``` public class memberClass { private memberProfile member; public memberProfile getMember() { return member; } public class memberProfile{ int id; String name; int profileIconId; int age; String email; //Getter public int getId() { return id; } public String getName() { return name; } public int getProfileIconId() { return profileIconId; } public int getAge() { return age; } public String getEmail() { return email; } } } ``` memberToJava.java ``` public class memberToJava { public static void main(String[] args) { Gson gson = new Gson(); try { BufferedReader br = new BufferedReader(new FileReader("...Member.json")); //convert the json string back to object memberClass memberObj = gson.fromJson(br, memberClass.class); System.out.println("Id: " + memberObj.getMember().getId()); System.out.println("Namw: " + memberObj.getMember().getName()); System.out.println("ProfileIconId: " + memberObj.getMember().getProfileIconId()); System.out.println("Age: " + memberObj.getMember().getAge()); System.out.println("Email: " + memberObj.getMember().getEmail()); } catch (IOException e) { e.printStackTrace(); } } } ```
Start new `Activity` and give `overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);` where zoom\_enter.xml has ``` <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/decelerate_interpolator"> <scale android:fromXScale="2.0" android:toXScale="1.0" android:fromYScale="2.0" android:toYScale="1.0" android:pivotX="50%p" android:pivotY="50%p" android:duration="@android:integer/config_mediumAnimTime" /> </set> ``` and zoom\_exit has ``` <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/decelerate_interpolator" android:zAdjustment="top"> <scale android:fromXScale="1.0" android:toXScale="2.0" android:fromYScale="1.0" android:toYScale="2.0" android:pivotX="50%p" android:pivotY="50%p" android:duration="@android:integer/config_mediumAnimTime" /> <alpha android:fromAlpha="1.0" android:toAlpha="0" android:duration="@android:integer/config_mediumAnimTime"/> </set> ``` keep both of these file in /res/anim/ folder.
36070
I have 3 tables: Posts, Tags and Post\_tag. The last one is just a pivot table: Posts: ``` +-------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | title | varchar(60) | NO | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +-------------+------------------+------+-----+---------+----------------+ ``` Tags: ``` +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | varchar(50) | NO | | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +------------+------------------+------+-----+---------+----------------+ ``` Post\_tag: ``` +------------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+-------+ | post_id | int(10) unsigned | YES | MUL | NULL | | | tag_id | int(10) unsigned | YES | MUL | NULL | | | created_at | timestamp | YES | | NULL | | | updated_at | timestamp | YES | | NULL | | +------------+------------------+------+-----+---------+-------+ ``` Models are correct. **Problem:** I'm getting this error in the posts/index.blade.php file: ``` Undefined property: stdClass::$tags (View: D:\laragon\www\laravel\resources\views\posts\index.blade.php) ``` In the posts/index.blade.php I have this @foreach inside a `@foreach ($posts as $post)` to list the tags a post belongs to. ``` @foreach($post->tags as $tag) <a class="btn btn-sm btn-info" href="/tag/{{ $tag->id }}"> <span>{{ $tag->name }}</span> </a> @endforeach ``` The previous @foreach only works if the controller sends `$posts = Post::all()` However I can only send to the view some rows with some conditions (Published, author id, etc.). So I have this in the controller: ``` $posts = DB::table('posts') ->orderBy('posts.created_at', 'desc') ->where('town_id', '=', $request->session()->get('citySelected')->id) ->paginate(10); ``` I even tried to set up the joins: ``` $posts = DB::table('posts') ->join('post_tag', 'posts.id', '=', 'post_tag.post_id') ->join('tags', 'post_tag.tag_id', '=', 'tags.id') ->orderBy('posts.created_at', 'desc') ->where('town_id', '=', $request->session()->get('citySelected')->id) ->paginate(10); ``` But neither works, make me think DB::table only brings the parent objects but not the child objects. Any ideas? Thanks.
You can load posts with related tags by using [`with`](https://laravel.com/docs/5.5/eloquent-relationships#eager-loading) method: ``` $posts = Post::with('tags') ->where('town_id', session('citySelected')->id) ->latest() ->paginate(10); ``` Then you'll be able to do this: ``` @foreach ($posts as $post) @foreach($post->tags as $tag) <a class="btn btn-sm btn-info" href="/tag/{{ $tag->id }}"> <span>{{ $tag->name }}</span> </a> @endforeach @endforeach ```
36084
Assuming this table with nearly 5 000 000 rows ``` CREATE TABLE `author2book` ( `author_id` int(11) NOT NULL, `book_id` int(11) NOT NULL, KEY `author_id_INDEX` (`author_id`), KEY `paper_id_INDEX` (`book_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ``` is it possible to add a primary index column `id` with `autoincrement` as first place? I expect something like this: ``` CREATE TABLE `author2book` ( `id` int(11) NOT NULL AUTO_INCREMENT, <<<< This is what I try to achieve! `author_id` int(11) NOT NULL, `book_id` int(11) NOT NULL, KEY `author_id_INDEX` (`author_id`), KEY `paper_id_INDEX` (`book_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ``` Is this possible? Edit: I should mention, that I'd like the added column to be populated.
Create a new table with the structure you want and the auto-incrementing key, and then insert all of the records from this table into that new table... then drop (or rename) the original table, and rename the new table to the original name. ``` insert into newTable (author_id, book_id) select * from author2book ``` newTable will then contain your desired output.
36805
En *La escuadra chilena en México* (1971) está reproducido un documento del Archivo General de Indias «sobre la captura de la "Cazadora" por la goleta "Chilena"» que léese así: > > Noticia de los individuos que tomaron partido en la goleta *Chilena*, Corsario. > > > * Primer guardia, Juan Portugues > * Marinero, José Portugues > * Mozo, Pedro Lamas > * Fd. José Moya > * Fd. José Ma. Tauma > * Fd. José Marcial, Acapulqueño > * Fd. Estanislao Fernandez > * José del Carmen, Esclavo > > > Corrijos, marzo 21 de 1819 — Manuel Ceballos > > > En este sitio: <https://studylib.es/doc/8407490/lopez-urrutia---portal-barcos-do-brasil> puede encontrarse el listado en cuestión en la página 80 (páginas 116/117 del libro) [![foto 1](https://i.stack.imgur.com/GrTs0.png)](https://i.stack.imgur.com/GrTs0.png) [![foto 2](https://i.stack.imgur.com/3VRmo.png)](https://i.stack.imgur.com/3VRmo.png) ¿Qué será **Fd.**?
La sigla "Fd." parece corresponder al rango de > > "Fuerza de desembarco" o su equivalente "infante de marina" > > > La literatura naval bélica comprende elementos de asalto anfibio (agua y tierra) para lo cual hay una categoría especial de infantería de marina(una especie de soldado de tierra en la flota) para las operaciones al llegar a las costas. La sigla aparece constar en varios documentos sobre el tema naval/militar (mencionado en [éste](https://i.stack.imgur.com/nw3JX.png) o [aquí](https://armada.defensa.gob.es/archivo/mardigitalrevistas/boletininfanteria/2008/200804.pdf#page=70)) La lectura somera del documento referido (sobre acciones marinas de corsarios chilenos y argentinos a principios de 1800) da un contexto del sentido militar de esa goleta, por lo que es perfectamente entendible que se refiere al uso de soldados de tierra (con lo que poder interpretar a "Fd." como 'fuerza de desembarco') [![enter image description here](https://i.stack.imgur.com/IUN5q.png)](https://i.stack.imgur.com/IUN5q.png) Esto encontré en el [Reglamento: abreviaturas y signos convencionales para uso de las Fuerzas Armadas](https://books.google.com.ar/books?id=HnKkp6Ygou8C&focus=searchwithinvolume&q=%22Fd%22) [![abreviación militar de FD](https://i.stack.imgur.com/QIBWO.png)](https://i.stack.imgur.com/QIBWO.png) Véase esta cita [![*mención a fuerzas de desembarco*](https://i.stack.imgur.com/nw3JX.png)](https://i.stack.imgur.com/nw3JX.png)
36916
``` SELECT SQL_NO_CACHE TIME_FORMAT(ADDTIME(journey.departure , SEC_TO_TIME(SUM(link2.elapsed))), '%H:%i') AS departure FROM journey JOIN journey_day ON journey_day.journey = journey.code JOIN pattern ON pattern.code = journey.pattern JOIN service ON service.code = pattern.service JOIN link ON link.section = pattern.section AND link.stop = "370023591" JOIN link link2 ON link2.section = pattern.section AND link2.id <= link.id WHERE journey_day.day = 6 GROUP BY journey.id ORDER BY journey.departure ``` The above query takes 1-2 seconds to run. I need to reduce this to roughly 100ms. Please note that I understand the `service` table hasn't been used in the query, but that is just to simplify the question. ![enter image description here](https://i.stack.imgur.com/oODnc.png) Any ideas how I can speed this up? I can see that the link table is using filesort, is this causing the slowness in the query?
As the error tells you R requires at least one of the three options, e.g., ``` Rserve(args="--no-save") ```
37343
I am trying to pull data from my populated javascript table. How do I pull the value from a javascript row? I am using ``` for (var i = 0; i < rowCount; i++) { var row = table.rows[i]; //This is where I am having trouble var chkboxIndicator = row.cells[0].childNodes[1]; alert(chkboxIndicator); // if (chkboxIndicator == indicator && Checkbox.checked == false) { table.deleteRow(i); rowCount--; i--; } } ``` which has an alert message of "undefined". I tried .value and .text as well and no progress. How do I get the text from the childNodes?
jQuery is an option because it makes event handling consistent across browsers, however, writing a simple function that does it is across all browsers in a concise manner is fairly trivial too, so just for this widget I wouldn't recommend creating a dependency on jQuery. Oh, and think of the input type as a widget or component with a decent public interface that you can just instantiate and embed in any page that needs it. Take a look at how most web calendaring solutions like Google Calendar achieve it, since they need to account for periodical events too, and still keep it simple for the end users. They have a solution to the UI problem of getting really complex recurring times such as: * Every 5 years on July 13 * Every 2 months on the second Tuesday * Weekly on Tuesday, Wednesday * Every 4 days in a simple manner for an end user. Here are a few examples: **Yearly repetition with a custom step size** [alt text http://img17.imageshack.us/img17/8122/picture1be.png](http://img17.imageshack.us/img17/8122/picture1be.png) **Monthly repetition with a custom step size on a certain day of the month** [alt text http://img706.imageshack.us/img706/8036/picture2so.png](http://img706.imageshack.us/img706/8036/picture2so.png) Use a self-contained script file that contains the widget, let's say `ScheduleWidget.js` that you can reference on each page that needs it, or maybe it gets bundled in a minified/packed script, so all pages have access to it. Keep the interface simple, so with minimal effort it can be inserted into any DOM element. ``` var widget = new ScheduleWidget(); var container = document.getElementById("scheduleContainer"); // getElement() returns the root DOM node of the dynamically constructed widget. container.appendChild(widget.getElement()); ``` When the `ScheduleWidget` object is instantiated, it sets up all event bindings so list selection, changes, etc. trigger a change in the logic/UI as needed.
37480
Okay, so I have an image for a background that has 1px of a blur filter in the CSS. That works. *Then*, I added a CSS :hover selector to a *new* CSS rule that changes the blur filter to 0. When I hover over it on the browser, however, it doesn't change the blur at all! (I went into Google Chrome Inspect Element and used the handy feature of forcing the :hover selector, and then it worked. So I know it's not the CSS that's buggy.) How can I get this to work? It's a blur filter on a div in a header. Any ideas? ``` <header> <div id="bgimage"></div> <nav> <a href="home.html" title="Click to go to the homepage.">Home</a> <span class="divider">-</span> <a href="cakes.html" title="Click to see types of cakes.">Types of Cake</a> </nav> <h1>Cakes</h1> </header> body header { width:100%; text-align:center; box-shadow:0 4px 4px 4px rgba(0,0,0,0.2); z-index:4; position:relative; background-color:linear-gradient(CornFlowerBlue,RoyalBlue); } body header div#bgimage { background-attachment:fixed; background-position:center; background-size:cover; background-image:url(hydrangea-cakes-2.jpg); filter:blur(1px); position:absolute; width:100%; height:100%; } ``` The important parts of the HTML are the header and the div id="bgimage"
You haven't already added the `:hover` pseudo-class. ```css #bgimage:hover { /* the styles you want to display on hover */ } ```
37662
I have spent way to much time trying to figure this out.... looking a dozens of other answers. I have table in SQL Server with a column of type `Char(32) NULL`. All items in the table column are only `char(9)`, but I have blanks in the remaining spots (when running `select ascII(right(myField, 1))` there is a 32 in there). I have tried a replace, tried to update the field from a tempTable tried to delete and update from tempTbl..... everytime I select... the fields are still 30 in length. Is there a way to remove all of the extra spaces? or is this just the way the `CHAR` fields always work? I have tried: ``` UPDATE table SET myfield = rtrim(replace(myField , char(160), char(32))) UPDATE mytable SET myField = REPLACE(RTRIM(LTRIM(myField )), CHAR(32), '') ```
You must distinguish between * strings with **fixed width** and * strings with **variable width**. In your case you are dealing with a fixed width. That means, that the string is always padded to its defined length. *Fixed-width-strings* live together with datetime or int values *within* the row. If you define your column as `VARCHAR(32)` (meaning *variable characters*), the "32" is just limiting the max length. These values are stored (in most cases) somewhere *outside of the row's storage space*, while there's *only a pointer* to the actual storage place *within* the row. Fixed lenghts are slightly faster then variable strings. But in most cases I'd advise to prefer the `VARCHAR(x)`. Check this out: ``` DECLARE @fix CHAR(32)='test'; DECLARE @variable VARCHAR(32)='test'; SELECT LEN(@fix),DATALENGTH(@fix) ,LEN(@variable),DATALENGTH(@variable) ``` Which results in ``` 4,32,4,4 ``` * The **`LEN()`-function does not count the trailing spaces** * The **`DATALENGTH()`-function gives you the space actually used**.
38015
I have a asn.1 file whose content is unknown as I am unable to read it properly. I found some answer in stackoverflow but i have some doubt regarding this. ``` public static void main(String[] args) throws IOException { ASN1InputStream ais = new ASN1InputStream( new FileInputStream(new File("asnfile"))); while (ais.available() > 0){ DERObject obj = ais.readObject(); System.out.println(ASN1Dump.dumpAsString(obj, true)); //System.out.println(CustomTreeNode.dumpAsString(obj)); } ais.close(); } ``` The output of the code looks like below: ``` > 00 > Tagged [0] IMPLICIT > DER Sequence > Tagged [0] IMPLICIT > DER Octet String[1] > 00 > Tagged [1] IMPLICIT > DER Octet String[8] > 15051312215238f6 !R8 > Tagged [2] IMPLICIT > DER Octet String[8] > 53968510617268f0 Sarh > Tagged [3] IMPLICIT ``` I think it is not the actual format. How can I read the file and what are the jars required to add in my project to read the file.
You appear to be using the Bouncy Castle ASN1 reading class. That is a very well-regarded library; it's quite unlikely that it produces the wrong answer. So, it seems, the answer to your question is that you are already using the right tool. Why don't you find a tool that just dumps ASN.1 files outside of Java and compare your results to that.
38168
I'm wondering how to use `RequireJS` with `JS` libraries like: *html5shiv* and *retina.js*, libraries like these don't need to be use the way we use jquery or something else. We just need to include it. I'm currently using it an ugly way: ``` require(["html5shiv"], function () { //doing nothing here.. }); ``` Any answers would be appreciated
You are forgetting that the divs are part of the DOM tree now, you either target them as well or you remove them. ``` div { counter-increment: chapter; counter-reset: section; } div:before { content: "Chapter " counter(chapter) " "; } ```
38367
Extent report version - 3.0 Language - Java and TestNG classes I have a class - ExtentManager.java ``` package framewrk; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; public class ExtentManager { private static ExtentReports extent; private static ExtentTest test; private static ExtentHtmlReporter htmlReporter; private static String filePath = "./extentreport.html"; public static ExtentReports GetExtent(){ extent = new ExtentReports(); htmlReporter = new ExtentHtmlReporter(filePath); // make the charts visible on report open htmlReporter.config().setChartVisibilityOnOpen(true); // report title String documentTitle = prop.getProperty("documentTitle", "aventstack - Extent"); htmlReporter.config().setDocumentTitle(documentTitle); } public static ExtentTest createTest(String name, String description){ test = extent.createTest(name, description); return test; } public static ExtentTest createTest(String name){ test = extent.createTest(name, ""); return test; } } ``` and 2 testNG classes as follows TC1.java ``` package framewrk; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.Status; public class TC1 { static ExtentReports extent; static ExtentTest test; @BeforeClass public void setup(){ extent = ExtentManager.GetExtent(); } @Test public void OpenUT(){ test = extent.createTest("Testing how fail works"); test.log(Status.INFO, "fail check started"); test.fail("Test fail"); } @AfterClass public void tear() { extent.flush(); } } ``` TC2.java ``` package framewrk; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.Status; public class TC2 { static ExtentReports extent; static ExtentTest test; @BeforeClass public void setup(){ extent = ExtentManager.GetExtent(); } @Test public void OpenUT(){ test = extent.createTest("Testing how pass works"); test.log(Status.INFO, "pass check started"); test.pass("Passed"); } @AfterClass public void tear() { extent.flush(); } } ``` If run these 2 test cases, I am getting only last testcase result, for the 1st testcase result, it's not displayed on the extent report. Note that there is not append parameter for extent report 3.0. How to get all test case results on extent report? [![Only last test case result shown, how to get all tests results](https://i.stack.imgur.com/OfkZR.png)](https://i.stack.imgur.com/OfkZR.png)
In the above approach, you are creating a new extent report in each Class. That is why you are getting only the latest executed test result. You can create a common superclass for both TC1 and TC2 classes. In the superclass you can create @AfterClass and @BeforeClass functions. Then it should work. Hope it helps!
38381
### Requirements [Word frequency algorithm for natural language processing](https://stackoverflow.com/questions/90580/word-frequency-algorithm-for-natural-language-processing) ### Using Solr While the answer for that question is excellent, I was wondering if I could make use of all the time I spent getting to know SOLR for my NLP. I thought of SOLR because: 1. It's got a bunch of tokenizers and performs a lot of NLP. 2. It's pretty use to use out of the box. 3. It's restful distributed app, so it's easy to hook up 4. I've spent some time with it, so using could save me time. ### Can I use Solr? Although the above reasons are good, I don't know SOLR THAT well, so I need to know if it would be appropriate for my requirements. ### Ideal Usage Ideally, I'd like to configure SOLR, and then be able to send SOLR some text, and retrieve the indexed tonkenized content. ### Context I'm working on a small component of a bigger recommendation engine.
I guess you can use Solr and combine it with other tools. Tokenization, stop word removal, stemming, and even synonyms come out of the box with Solr. If you need named entity recognition or base noun-phrase extraction, you need to use [OpenNLP](http://opennlp.sourceforge.net/) or an equivalent tool as a pre-processing stage. You will probably need term vectors for your retrieval purposes. [Integrating Apache Mahout with Apache Lucene and Solr](http://www.lucidimagination.com/blog/2010/03/16/integrating-apache-mahout-with-apache-lucene-and-solr-part-i-of-3/) may be useful as it discusses Lucene and Solr integration with a machine learning (including recommendation) engine. Other then that, feel free to ask further more specific questions.
38386
I'm trying to write a piece of code for encrypting/decrypting data (e.g. passwords) which will be stored in DB. The goal is that data can be used in C++, PHP and Java. The problem is I’m not getting same encrypted data in C++ and PHP (I’m not dealing with Java jet). C++ code: ``` void CSSLtestDlg::TryIt() { CString msg, tmp; /* A 256 bit key */ unsigned char *key = (unsigned char *)"01234567890123456789012345678901"; /* A 128 bit IV */ unsigned char *iv = (unsigned char *)"01234567890123456"; /* Message to be encrypted */ unsigned char *plaintext = (unsigned char *)"Some_plain_text"; msg = "Original text is: Some_plain_text"; /* Buffer for ciphertext. Ensure the buffer is long enough for the * ciphertext which may be longer than the plaintext, dependant on the * algorithm and mode */ unsigned char ciphertext[128]; /* Buffer for the decrypted text */ unsigned char decryptedtext[128]; int decryptedtext_len, ciphertext_len; /* Initialise the library */ ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); OPENSSL_config(NULL); /* Encrypt the plaintext */ ciphertext_len = encryptIt (plaintext, strlen ((char *)plaintext), key, iv, ciphertext); ciphertext[ciphertext_len] = '\0'; tmp.Format("\nEncrypted text (in HEX) is: %s", StrToHex(ciphertext)); msg += tmp; /* Decrypt the ciphertext */ decryptedtext_len = decryptIt(ciphertext, ciphertext_len, key, iv, decryptedtext); /* Add a NULL terminator. We are expecting printable text */ decryptedtext[decryptedtext_len] = '\0'; tmp.Format("\nDecrypted text is: %s", decryptedtext); msg += tmp; AfxMessageBox(msg); /* Clean up */ EVP_cleanup(); ERR_free_strings(); } int CSSLtestDlg::encryptIt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) { EVP_CIPHER_CTX *ctx; int len; int ciphertext_len; /* Create and initialise the context */ if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors(); /* Initialise the encryption operation. IMPORTANT - ensure you use a key * and IV size appropriate for your cipher * In this example we are using 256 bit AES (i.e. a 256 bit key). The * IV size for *most* modes is the same as the block size. For AES this * is 128 bits */ if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) handleErrors(); /* Provide the message to be encrypted, and obtain the encrypted output. * EVP_EncryptUpdate can be called multiple times if necessary */ if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) handleErrors(); ciphertext_len = len; /* Finalise the encryption. Further ciphertext bytes may be written at * this stage. */ if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors(); ciphertext_len += len; /* Clean up */ EVP_CIPHER_CTX_free(ctx); return ciphertext_len; } int CSSLtestDlg::decryptIt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext) { EVP_CIPHER_CTX *ctx; int len; int plaintext_len; /* Create and initialise the context */ if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors(); /* Initialise the decryption operation. IMPORTANT - ensure you use a key * and IV size appropriate for your cipher * In this example we are using 256 bit AES (i.e. a 256 bit key). The * IV size for *most* modes is the same as the block size. For AES this * is 128 bits */ if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) handleErrors(); /* Provide the message to be decrypted, and obtain the plaintext output. * EVP_DecryptUpdate can be called multiple times if necessary */ if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) handleErrors(); plaintext_len = len; /* Finalise the decryption. Further plaintext bytes may be written at * this stage. */ if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors(); plaintext_len += len; /* Clean up */ EVP_CIPHER_CTX_free(ctx); return plaintext_len; } ``` Result: ``` Original text is: Some_plain_text Encrypted text (in HEX) is: 39D35A2E6EF8F8E36F3BC1FD8B6B32 Decrypted text is: Some_plain_text ``` PHP code: ``` $key = "01234567890123456789012345678901"; $iv = "01234567890123456"; $msg = "Some_plain_text"; if(function_exists('openssl_encrypt')) { echo("Original text is:" . $msg . "<br>"); $encrypted_msg = openssl_encrypt($msg, "aes-256-cbc", $key, OPENSSL_RAW_DATA, $iv); if ($encrypted_msg == FALSE) $log->logDebug("openssl_encrypt error!"); else { echo("Encrypted text (in HEX) is:" . strToHex($encrypted_msg) . "<br>"); $decrypted_msg = openssl_decrypt($encrypted_msg, "aes-256-cbc", $key, OPENSSL_RAW_DATA , $iv); echo("Decrypted text is:" . $decrypted_msg . "<br>"); } } else echo("openssl_encrypt doesn't exists!<br>"); function strToHex($string) { $hex = ''; for ($i=0; $i<strlen($string); $i++) { $ord = ord($string[$i]); $hexCode = dechex($ord); $hex .= substr('0'.$hexCode, -2); } return strToUpper($hex); } ``` Result: ``` Original text is:Some_plain_text Encrypted text (in HEX) is:39D35A2E6EF8F8E36F3BC1FD8B06B302 Decrypted text is:Some_plain_text ``` So I’m getting 39D35A2E6EF8F8E36F3BC1FD8B6**B32** (C++) opposite to 39D35A2E6EF8F8E36F3BC1FD8B06**B302** (PHP). In the end a HEX data is going to be stored in DB and retrieved later on. Thanks in advance for all the help and sorry for my bad language.
So the problem was in C++ code in StrToHex() function (which I forget to post in original question) so here it is: ``` CString StrToHex(unsigned char* str) { CString tmp; CString csHexString; int nCount = strlen((char *)str); for( int nIdx =0; nIdx < nCount; nIdx++ ) { int n = str[nIdx]; //tmp.Format( _T("%X"), n ); --> this is wrong tmp.Format( _T("%02X"), n ); // --> this is OK csHexString += tmp; } return csHexString; } ```
38736
Consider the following query... ``` SELECT * ,CAST( (CurrentSampleDateTime - PreviousSampleDateTime) AS FLOAT ) * 24.0 * 60.0 AS DeltaMinutes FROM ( SELECT C.SampleDateTime AS CurrentSampleDateTime ,C.Location ,C.CurrentValue ,( SELECT TOP 1 Previous.SampleDateTime FROM Samples AS Previous WHERE Previous.Location = C.Location AND Previous.SampleDateTime < C.SampleDateTime ORDER BY Previous.SampleDateTime DESC ) AS PreviousSampleDateTime FROM Samples AS C ) AS TempResults ``` Assuming all things being equal such as indexing, etc is this the most efficient way of achieving the above results? That is using a SubQuery to retrieve the last record? Would I be better off creating a cursor that orders by Location, SampleDateTime and setting up variables for CurrentSampleDateTime and PreviousSampleDateTime...setting the Previous to the Current at the bottom of the while loop? I'm not very good with CTE's is this something that could be accomplished more efficiently with a CTE? If so what would that look like? I'm likely going to have to retrieve PreviousValue along with Previous SampleDateTime in order to get an average of the two. Does that change the results any. Long story short what is the best/most efficient way of holding onto the values of a previous record if you need to use those values in calculations on the current record? ----UPDATE I should note that I have a clustered index on Location, SampleDateTime, CurrentValue so maybe that is what is affecting the results more than anything. with 5,591,571 records my query (the one above) on average takes 3 mins and 20 seconds The CTE that Joachim Isaksson below on average is taking 5 mins and 15 secs. Maybe it's taking longer because it's not using the clustered index but is using the rownumber for the joins? I started testing the cursor method but it's already at 10 minutes...so no go on that one. I'll give it a day or so but think I will accept the CTE answer provided by Joachim Isaksson just because I found a new method of getting the last row. Can anyone concur that it's the index on Location, SampleDateTime, CurrentValue that is making the subquery method faster? I don't have SQL Server 2012 so can't test the LEAD/LAG method. I'd bet that would be quicker than anything I've tried assuming Microsoft implemented that efficiently. Probably just have to swap a pointer to a memory reference at the end of each row.
OK - so I've done some more research and I have most of the answers now. First of all, a correction. Addresses are not obtained via `PD` with DHCP. That is how DHCP servers obtain a network prefix to use for the DHCP clients they host. There is another DHCP server which deals with handing out these prefixes. Thus, `PD` can be ignored as a method for obtaining IP addresses. --- **Question 1a/b: Is there really no fall back here?** Answer: There is no automated fallback mechanism. One can be implemented, but it would be custom. **Question 2: Is this also an NS message?** Answer: Yes **Question 3: It is possible to have more than one address for the interface. In fact, at the end of the above process, a single interface will have 2 addresses - a link-local one and a global unicast one. Is it possible to get additional addresses for this interface using SLAAC? Or must another method (e.g. DHCPv6) be used?** Answer: Multiple addresses can be generated with SLAAC. A client can use the Router Advertisements from multiple routers, and each router may advertise multiple prefixes. Each prefix can be used by the host to create a global unicast address. **Question 8 (modified): How do I detect SLAAC generated addresses? Is there some field in the messages I can use to regenerate the complete IP address? I will already have the prefix, but the interface ID is unknown.** Answer: The only way to detect them is to listen for `NS` messages. Since these messages are optional, there is no guaranteed way to detect SLAAC generated addresses. --- I still don't have answers for questions 4-7, but I am not too concerned with them at the moment. Thanks!!
38829
For some reason I'm getting this error: > > Uncaught ReferenceError: $stateProvider is not defined > > > even though `angular-ui-router.js` is being loaded fine. Here is my code ``` (function () { var mod = angular.module('MyApp', ['ui.router']); debugger; mod.config(['$stateProvider', '$locationProvider', function ($stateProvider, $locationProvider) { $stateProvider.state('product', { url: "/home/product", views: { "view1": { templateUrl: "/Angular/Components/Products/Products.html", controller: "Ctr_Products", } } }); $locationProvider.html5Mode({ enabled: true, requireBase: false }); }]); ```
I had a similar problem, when doing apt-get upgrade... The problem is that apt-get was trying to use python2.7, but the symlink was pointing to python3.4: ``` debian:/usr/bin# cat /etc/debian_version 8.10 debian:/usr/bin# ll /usr/bin/python lrwxrwxrwx 1 root root 18 Feb 26 17:02 /usr/bin/python -> /usr/bin/python3.4 ``` Fixed it by creating a new symlink ``` debian:/usr/bin# rm /usr/bin/python debian:/usr/bin# ln -s /usr/bin/python2.7 /usr/bin/python ```
38853
I've a problem with my sendto function in my code, when I try to send a raw ethernet packet. I use a Ubuntu 12.04.01 LTS, with two tap devices connected over two vde\_switches and a dpipe Example: my send programm create the packet like below, the programm is binded by the socket from tap0 and send the packet to tap1. On tap1 one receiver wait for all packets on socket. My raw ethernet packet looks so: *destination Addr* \_\_*\_*\_*source Addr* \_\_*\_*\_\_*\_*\_\_\_ *type/length* \_\_*\_**data* *00:00:01:00:00:00****\_*\_\_***00:00:01:00:00:01****\_*\_\_\_** length in Byte***\_*\_***some data* Example packet to send: ``` 00:00:01:00:00:00 00:00:01:00:00:01 (length in byte) (Message)test ``` but my programm generate two packets, when I look in wireshark: first packet is an IPX packet and [Malformed Packet] and looks like in hex (data = test) ``` 00 04 00 01 00 06 00 00 01 00 00 01 00 00 00 01 74 65 73 74 00 Linux cooked capture Packet type: sent by us (4) Link-layer address type: 1 Link-layer address length: 6 Source: 00:00:01:00:00:01 Protocol: Raw 802.3 (0x0001) [Malformed Packet: IPX] ``` second packet unknown protocol ``` 00 00 00 01 00 06 00 00 01 00 00 01 00 00 31 00 74 65 73 74 00 Linux cooked capture Packet type: Unicast to us (0) Link-layer address type: 1 Link-layer address length: 6 Source: 00:00:01:00:00:01 Protocol: Unknown (0x3100) Data Data: 7465737400 [Length: 5] ``` outcut from my source code ``` sock_desc = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); /*struct for sending*/ sock_addr.sll_family = AF_PACKET; sock_addr.sll_protocol = htons(ETH_P_802_3); sock_addr.sll_ifindex = if_nametoindex(argv[1]); sock_addr.sll_hatype = ARPHRD_ETHER; //Ethernet 10Mbps sock_addr.sll_pkttype = PACKET_HOST; // Paket zu irgendjemand sock_addr.sll_halen = ETH_ALEN; //6 Oktets in einer ethernet addr /*MAC Length 8 Oktets*/ sock_addr.sll_addr[0] = frame.src_mac[0]; sock_addr.sll_addr[1] = frame.src_mac[1]; sock_addr.sll_addr[2] = frame.src_mac[2]; sock_addr.sll_addr[3] = frame.src_mac[3]; sock_addr.sll_addr[4] = frame.src_mac[4]; sock_addr.sll_addr[5] = frame.src_mac[5]; /*not in use*/ sock_addr.sll_addr[6] = 0x00; sock_addr.sll_addr[7] = 0x00; memset(buffer, '0', sizeof(char)*ETH_FRAME_LEN); /*set the frame header*/ /*build RAW Ethernet packet*/ buffer[0] = frame.dest_mac[0]; buffer[1] = frame.dest_mac[1]; buffer[2] = frame.dest_mac[2]; buffer[3] = frame.dest_mac[3]; buffer[4] = frame.dest_mac[4]; buffer[5] = frame.dest_mac[5]; buffer[6] = frame.src_mac[0]; buffer[7] = frame.src_mac[1]; buffer[8] = frame.src_mac[2]; buffer[9] = frame.src_mac[3]; buffer[10] = frame.src_mac[4]; buffer[11] = frame.src_mac[5]; while(frame.data[0] != '*'){ printf("Input: "); scanf("%s", frame.data); tempLength = 0; while(frame.data[tempLength] != '\0'){ tempLength++; } input = 0; for(sendLen = 14;sendLen <= (14+tempLength);sendLen++){ buffer[sendLen] = frame.data[input]; input++; } sprintf(convLen,"%x", (14 + input)); buffer[12] = convLen[0]; buffer[13] = convLen[1]; length_in_byte = sendto(sock_desc, buffer, 14+input,0,(struct sockaddr*) &sock_addr,sizeof(struct sockaddr_ll)); if(length_in_byte <= 0){ printf("Error beim Senden"); }else{ printf("\n"); printf("src: %02x:%02x:%02x:%02x:%02x:%02x\t->\tdest: %02x:%02x:%02x:%02x:%02x:%02x\n",frame.src_mac[0],frame.src_mac[1],frame.src_mac[2],frame.src_mac[3],frame.src_mac[4],frame.src_mac[5],frame.dest_mac[0],frame.dest_mac[1],frame.dest_mac[2],frame.dest_mac[3],frame.dest_mac[4],frame.dest_mac[5]); printf("Data: %s\n", frame.data); } } ``` please i need some help to find my mistake. Thank you forward.
Just use a standard javascript object: ``` var dictionary = {};//create new object dictionary["key1"] = value1;//set key1 var key1 = dictionary["key1"];//get key1 ``` NOTE: You can also get/set any "keys" you create using dot notation (i.e. `dictionary.key1`) --- You could take that further if you wanted specific functions for it... ``` function Dictionary(){ var dictionary = {}; this.setData = function(key, val) { dictionary[key] = val; } this.getData = function(key) { return dictionary[key]; } } var dictionary = new Dictionary(); dictionary.setData("key1", "value1"); var key1 = dictionary.getData("key1"); ```
38997
[Here](https://www.youtube.com/watch?v=LOoM3qlpYuU&list=PLHXZ9OQGMqxcJXnLr08cyNaup4RDsbAl1&index=12) (and [*here*](http://lie.math.okstate.edu/%7Ebinegar/2233/2233-l31.pdf)), I saw an equation for a horizontal frictionless harmonic oscillator (a mass on a spring) that was suddenty hit by a hummer (i.e. the duration of the hit goes to zero). The equation looks like this (neglecting the coefficients): $$x'' + x = \delta\_{\pi}(t)$$ *My question* is how to derive it. --- *Some clarification* of what I'm specifically interested in. I know how to derive the left hand side but I want to know how do we end up having Dirac delta on the right hand side. Normally, we would draw a free body diagram for the mass and write down the second Newton's law in projections on the horizontal axis $x$. Thus, for the moment of the hammer hit we have: [![enter image description here](https://i.stack.imgur.com/OGywp.png)](https://i.stack.imgur.com/OGywp.png) $$ma = F\_{spring} - F\_{hammer}$$ $$x''-\frac{k}{m} x = - \frac{1}{m} F\_{hammer}$$ At this point, we've derived the left hand side. How do we convert the right hand side to a Dirac delta containing function? As I understand, the second Newton's law that I have written works only for the moment of the hammer hit. That's because $F\_{hammer}$ exists only at the moment of the hammer hit - say - at $t=0$. In other words, $F\_{hammer} (t)$ looks like this: [![enter image description here](https://i.stack.imgur.com/LqOhv.png)](https://i.stack.imgur.com/LqOhv.png) In order to use our equation for all the values on the $t$ axis, we have to "expand" $F\_{hammer} (t)$ to the entire $t$ axis. I believe that Dirac delta has something to do with that. I.e. Dirac delta converts our plot to the following one: [![enter image description here](https://i.stack.imgur.com/vGSRy.png)](https://i.stack.imgur.com/vGSRy.png) I'm very curious about the essence of the mathematical trick that expands the function $F\_{hammer}$ which exists only at one point to the entire $t$ axis.
You seem to be new to the concept of the $\delta$-function. Therefore I will try to motivate this now. Let's hit the oscillator body with a hammer made of soft rubber. The force-time graph will look like this: [![enter image description here](https://i.stack.imgur.com/DRkCp.png)](https://i.stack.imgur.com/DRkCp.png) The force is non-zero for a short time, while the hammer is in touch with the oscillator body. The rubber is compressed first, and then bounces back to its original shape. The momentum transferred from the hammer to the oscillator body can be calculated by $$\int\_{-\infty}^{+\infty} F\_\text{hammer}(t)\ dt = P$$ Now let's hit it with a hammer made of hard steel. Then the force-time graph will look like this: [![enter image description here](https://i.stack.imgur.com/X06Sq.png)](https://i.stack.imgur.com/X06Sq.png) The situation is similar to the situation above, except that the hitting time is even shorter, and the force during this time is even larger. But the transferred momentum is still the same: $$\int\_{-\infty}^{+\infty} F\_\text{hammer}(t)\ dt = P$$ Now let's use an infinitely hard hammer (of course such a thing doesn't really exist, but let's do it anyway). The hitting time is zero now, and the hitting force during this time is infinitely high. We write the force now using the [Dirac delta function](https://en.wikipedia.org/wiki/Dirac_delta_function) as: $$F\_\text{hammer}(t)=P\ \delta(t)$$ Once again the transferred momentum is the same (now by definition of the $\delta$-function): $$\int\_{-\infty}^{+\infty} F\_\text{hammer}(t)\ dt = \int\_{-\infty}^{+\infty} P\ \delta(t)\ dt = P\ \underbrace{\int\_{-\infty}^{+\infty}\delta(t)\ dt}\_{=1} = P$$ The [$\delta$-function](https://en.wikipedia.org/wiki/Dirac_delta_function) is just a mathematical idealization (originally invented by physicists) for modeling infinitely narrow and high spikes.
39079
Let $X\_1,...,X\_n$ be mutually independent RVs. Suppose $X\_i \perp \mathcal F $ for $1\ \leq \forall i \leq n$. How can I show that: $$\sigma (X\_1,...,X\_n) \perp \mathcal F$$ ? What I have tried: $\sigma (X\_1...X\_n) = \sigma(\cup\_{i=1} ^n \sigma(X\_i))$ holds. I think I need some Dynkin's lemma-ish argument but can't see how.
I doubt the conclusion. I remember that there is something like "pairwise independent does not imply independent". More precisely, let $X\_1$, $X\_2$, $X\_3$ be random variables such that for any $i\neq j$, $X\_i$ and $X\_j$ are independent. However, $X\_1$, $X\_2$, $X\_3$ need not be independent. If my memory is correct, we put $\mathcal{F}=\sigma(X\_3)$, then we will arrive a contradiction. You may consult any textbook or search "pairwise independent does not imply independent". I remember that there is such a counter-example: There is a probability space $(\Omega,\mathcal{F},P)$ and $A\_{i}\in\mathcal{F}$, for $i=1,2,3$ such that $P(A\_{i}A\_{j})=P(A\_{i})P(A\_{j})$ whenever $i\neq j$. However, $P(A\_{1}A\_{2}A\_{3})\neq P(A\_{1})P(A\_{2})P(A\_{3})$. Then we define $X\_{i}=1\_{A\_{i}}$, for $i=1,2,$ and define $\mathcal{G}=\sigma(X\_{3})$. Obviously, $X\_{1}$ and $X\_{2}$ are independent and $X\_{i}\perp\mathcal{G}$. However, it is false that $\sigma(X\_{1},X\_{2})\perp\mathcal{G}$. For, if it is true, then $A\_{1}A\_{2}\in\sigma(X\_{1},X\_{2})$ and $A\_{3}\in\mathcal{G}$, then $P(A\_{1}A\_{2}A\_{3})=P(A\_{1}A\_{2})P(A\_{3})=P(A\_{1})P(A\_{2})P(A\_{3})$.
39133
I am trying to convert a bitcoin address and have the following code from here ([Calculate Segwit address from public address](https://bitcoin.stackexchange.com/questions/65404/calculate-segwit-address-from-public-address), 2nd answer): ``` Step1: $ printf 1L88S26C5oyjL1gkXsBeYwHHjvGvCcidr9 > adr.txt Step2: $ printf $( cat adr.txt | sed 's/[[:xdigit:]]\{2\}/\\x&/g' ) >adr.hex Step3: $ openssl dgst -sha256 -binary <adr.hex >tmp_sha256.hex Step4: $ openssl dgst -ripemd160 <tmp_sha256.hex ## result should be: 56379c7bcd6b41188854e74169f844e8676cf8b8 ``` Now I want to do this in Java. I currently have the following code. No matter what I try, I dont get the correct result. :( ``` String address = "1L88S26C5oyjL1gkXsBeYwHHjvGvCcidr9"; // step 1 System.out.println("address: " + address); String addressHex = toHex(address); System.out.println("address hex: " + addressHex); byte[] addressBytes = addressHex.getBytes(StandardCharsets.UTF_8); // step 2 MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(addressBytes); // step 3 RIPEMD160Digest digest2 = new RIPEMD160Digest(); // steps 4 digest2.update(hash, 0, hash.length); byte[] out = new byte[20]; digest2.doFinal(out, 0); System.out.println("result: " + bytesToHex(out)); // = 62ab42cba5d2632d1350fafb2587f5d2ece445d3 // should be 56379c7bcd6b41188854e74169f844e8676cf8b8 ``` Output: ``` address: 1L88S26C5oyjL1gkXsBeYwHHjvGvCcidr9 address hex: 314c383853323643356f796a4c31676b58734265597748486a764776436369647239 result: 62ab42cba5d2632d1350fafb2587f5d2ece445d3 ``` Can someone help me? I think the problem is somewhere doing the conversion String/hex/byte ...? I tried really hard, but cannot find the correct way to do it. I also tried to convert the address to hex and after that to bytes, but doesnt work neither. :/ // updated post ... still doesnt show the correct result :/ // update2: ``` byte[] address = ("1L88S26C5oyjL1gkXsBeYwHHjvGvCcidr9").getBytes(); System.out.println("address byte array: " + address); String addressHex = bytesToHex(address); System.out.println("address hex: " + addressHex); byte[] addressBytes = addressHex.getBytes(); MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(addressBytes); RIPEMD160Digest digest2 = new RIPEMD160Digest(); digest2.update(hash, 0, hash.length); byte[] out = new byte[20]; digest2.doFinal(out, 0); System.out.println("result: " + bytesToHex(out)); ``` Output ``` address byte array: [B@108c4c35 address hex: 314c383853323643356f796a4c31676b58734265597748486a764776436369647239 result: 62ab42cba5d2632d1350fafb2587f5d2ece445d3 ```
Payment routing could handle this. Any business has operational costs and will have to make outgoing payments. If your concern is that channels will mostly consist of payments in a single direction (i.e. from customers to larger businesses), and that this will lead to a high frequency of channel closings or on-chain settlements, then we can consider the theory of [Six Degrees of Separation](https://en.wikipedia.org/wiki/Six_degrees_of_separation). The theory of Six Degrees of Separation postulates "that all living things and everything else in the world are six or fewer steps away from each other". In regards to the Lightning Network, we can postulate the theory that any user will be able to pay any other user through approximately six other users. So if you have a source of incoming payments on the Lightning network (i.e. your wage), and the larger business has outgoing payments (i.e. their employee's wages), then through the six degrees of separation you may be able to pay the larger business through already existing payment channels you have open with your contacts. Successful payment routing should ensure that payment channels operate bidirectionally and that payment channel closing or on-chain settlement should be of a low relative frequency. **Edit: Put Alternatively** Customers may never directly make payment channels with large businesses, but instead create routed payments through payment channels they have open with exchanges or other Lightning Network intermediaries. Users may create payment channels with an exchange. A large business may create a payment channel with the same exchange. Users make payments to the large business routed through the payment channels they have open with the exchange. The large business decides to sell some bitcoin through the exchange. It makes a payment using the payment channel it already has open with the exchange. This process continues indefinitely such that there is a bidirectional flow of bitcoin along the open payment channels.
39458
The GFI in our bathroom was tripping somewhat frequently when my wife used the blow dryer. Other than the vanity light there were not other things operating on this circuit. If the GFI did not trip, the plug to the hair dryer would be quite hot to the touch. To my limited knowledge, a danger sign. After a ridiculous quote by an electrician to diagnosis the problem, I decided to watch some you tube videos. I bought a GFI tester and the outlet was hooked up correctly. However, I noticed that the circuit had a 20a breaker, but the GFI was 15a. So first step, I replaced it with a new 20a GFI. After testing all symptoms were gone. No hot hair dryer plug and no tripping. I checked the other GFIs despite them working correctly. All were 15a GFIs but on a 20a circuit. One was the kitchen which get used very heavily. I went ahead and replaced them all, just to be safe but it left me with some questions: 1. How bad is it to have a 15a GFI on a 20a circuit? 2. Do you think that the problem in our bathroom was just a bad GFI? Related to the mismatch in circuit and outlet rating? Or something else?
My understanding is that you can have multiple 15 amp outlets on a 20 Amp circuit but not just one. GFCI's trip on a fault, not an overload so the existing GFCI was probably going bad. Hair dryers can easily use 15 amps and that would heat up the plug a bit. If the GFCI outlet was old and had been used a lot, the plug might not have been as tight as it should be but not enough to arc but would heat up more.
39655
[![enter image description here](https://i.stack.imgur.com/Xx84o.png)](https://i.stack.imgur.com/Xx84o.png)I am working on Firstcry .com website for automation. After searched for Shoes int he search box, I need to scroll down to the bottom of the page to click "View All products" link. BUt scrolling is not happening.. what should be done... attached my code and screenshot for reference.. ``` [public void f(String s) { String ExpecTitle = "Kids Footwear - Buy Baby Booties, Boys Shoes, Girls Sandals Online India"; Actions builder = new Actions(Driver); Driver.get("https://www.firstcry.com/"); String Viewall = "/html/body/div\[6\]/div\[2\]/div\[2\]/div\[2\]/div\[8\]/div\[2\]/span/a"; String MainTitle = Driver.getTitle(); System.out.println("Main title is " + MainTitle); WebElement SearchBox = Driver.findElement(By.id("search_box")); SearchBox.clear(); WebElement SearchBox2 = Driver.findElement(By.id("search_box")); SearchBox2.sendKeys(s); // SearchBox.sendKeys(Keys.ENTER); //wait.until(ExpectedConditions.stalenessOf(Driver.findElement(By.cssSelector(".search-button")))); Driver.findElement(By.cssSelector(".search-button")).click(); String ActTitle = Driver.getTitle(); System.out.println("The page title is " + ActTitle); Driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS); if(ActTitle.contains("Kids Footwear")){ System.out.println("Inside the if condition"); js.executeScript("window.scrollTo(0, document.body.scrollHeight)"); WebElement viewALL = Driver.findElement(By.xpath(Viewall)); // js.executeScript("arguments\[0\].scrollIntoView();", viewALL); Driver.findElement(By.xpath(Viewall)).click(); System.out.println("View"); // WebElement viewAll = Driver.findElement(By.xpath("/html/body/div\[6\]/div\[2\]/div\[2\]/div\[2\]/div\[8\]/div\[2\]/span/a")); // js.executeScript("arguments\[0\].scrollIntoView(true);", viewAll); // wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a\[contains(text(),'View All Products')\]"))); // viewAll.click(); } WebElement element = Driver.findElement(By.cssSelector(".sort-select-content")); element.click(); builder.moveToElement(element).perform(); { WebElement elem = Driver.findElement(By.linkText("Price")); elem.click(); // builder.moveToElement(elem).perform(); } //Driver.findElement(By.linkText("Price")).click(); }][1] ```
After searching for Shoes in the search box and selecting the first suggestion, to scroll down to the bottom of the page to click on the element with text as **View All Products** you need to induce [WebDriverWait](https://stackoverflow.com/questions/48989049/selenium-how-selenium-identifies-elements-visible-or-not-is-is-possible-that-i/48990165#48990165) for the `elementToBeClickable()` and you can use the following [xpath](/questions/tagged/xpath "show questions tagged 'xpath'") based [Locator Strategies](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890): ``` driver.get("https://www.firstcry.com/"); WebElement searchBox = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='search_box']"))); searchBox.clear(); searchBox.sendKeys("Shoes"); new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='searchlist']/ul/li/span"))).click(); ((JavascriptExecutor)driver).executeScript("return arguments[0].scrollIntoView(true);", new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[text()='View All Products']")))); new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='View All Products']"))).click(); ```
39685
It's very strange, I cannot find any **standard** way with Ruby to copy a directory recursively while dereferencing symbolic links. The best I could find is `FindUtils.cp_r` but it only supports dereferencing the root src directory. `copy_entry` is the same although documentation falsely shows that it has an option `dereference`. In source it is `dereference_root` and it does only that. Also I can't find a **standard** way to recurse into directories. If nothing good exists, I can write something myself but wanted something simple and tested to be portable across Windows and Unix.
The standard way to recurse into directories is to use the [Find](http://www.ruby-doc.org/stdlib-2.1.2/libdoc/find/rdoc/index.html) class but I think you're going to have to write something. The built-in [FileUtils](http://www.ruby-doc.org/stdlib-2.1.2/libdoc/fileutils/rdoc/index.html) methods are building blocks for normal operations but your need is not normal. I'd recommend looking at the [Pathname](http://www.ruby-doc.org/stdlib-2.1.2/libdoc/pathname/rdoc/index.html) class which comes with Ruby. It makes it easy to walk directories using [`find`](http://www.ruby-doc.org/stdlib-2.1.2/libdoc/pathname/rdoc/Pathname.html#method-i-find), look at the type of the file and dereference it if necessary. In particular [`symlink?`](http://www.ruby-doc.org/stdlib-2.1.2/libdoc/pathname/rdoc/Pathname.html#method-i-symlink-3F) will tell you if a file is a soft-link and [`realpath`](http://www.ruby-doc.org/stdlib-2.1.2/libdoc/pathname/rdoc/Pathname.html#method-i-realpath) will resolve the link and return the path to the real file. For instance I have a soft-link in my home directory from `.vim` to `vim`: ``` vim = Pathname.new ENV['HOME'] + '/.vim' => #<Pathname:/Users/ttm/.vim> vim.realpath => #<Pathname:/Users/ttm/vim> ``` Pathname is quite powerful, and I found it very nice when having to do some major directory traversals and working with soft-links. The docs say: > > The goal of this class is to manipulate file path information in a neater way than standard Ruby provides. [...] > > > All functionality from File, FileTest, and some from Dir and FileUtils is included, in an unsurprising way. It is essentially a facade for all of these, and more. > > > If you use `find`, you'll probably want to implement the `prune` method which is used to skip entries you don't want to recurse into. I couldn't find it in Pathname when I was writing code so I added it using something like: ``` class Pathname def prune Find.prune end end ```
39801
I have a table within a form. The table contains some form fields, but there are form fields outside of the table (but still within the form) too. I know that Enter and Return are traditionally used to submit a form via the keyboard, but I want to stop this behaviour for fields within the table. For example, if I focus a field within the table and hit Enter/Return, nothing happens. If I focus a field outside of the table (but still within the form) then for it to submit as normal. I have a jQuery plugin that targets this table. Simplified, this is what I've tried this far: ``` base.on('keydown', function(e) { if (e.keyCode == 13) { e.stopPropagation(); return false; } }); ``` Where `base` is the table jQuery object. This is within my plugin's `init` method. However, hitting Enter still submits the form. Where am I going wrong? **EDIT:** Some simplified HTML: ``` <form method="" action=""> <input type="text" /><!--this should still submit on Enter--> <table> <tbody> <tr> <td> <input type="text" /><!--this should NOT submit on Enter--> </td> </tr> </tbody> </table> </form> ```
``` base.keypress(function(e) { var code = e.keyCode || e.which; if(code == 13) return false; }); ``` or for only inputs: ``` $(':input', base).keypress(function(e) { var code = e.keyCode || e.which; if(code == 13) return false; }); ```
40118
> > Theorem: > > > Let M be a topological manifold and let U be any open subset of M, with the subspace topology. Then U is a topological manifold. > > > Now, the only problem I face is showing that U is locally euclidean. > > Recall: Locally euclidean > > > A topological space U is locally euclidean if, $\exists n \in \mathbb{Z}^{+}, \forall \bar{u} \in U$, there exists an open set $\alpha \subseteq U$ containing $\bar{u}$ homeomorphic to some open set $\beta \subseteq \mathbb{R}^{n}$ > > > Any help is appreciated.
(y-np+0.5 #continuous correction )/(npq^1/2) <(9.5-7.5)/2.5 =0.8 so result is Pr(Y>9.5)=1-Φ(0.8)=1-0.788=0.212
40222
I am using this code for uploading image. I have given write permission to the folder where image will be stored. Following is my code: ``` Dim con As New System.Data.SqlClient.SqlConnection("Data Source=Biplob-PC\SQLEXPRESS; database =a;Integrated Security=True") Dim smemberid As Integer Dim photoid As Integer Sub bindphoto() 'What directory are we interested in? Dim mycommand As New SqlCommand("SELECT * FROM Photo WHERE MemberID = '" & smemberid & "' ORDER BY PhotoID", con) con.Open() dlFileList.DataSource = mycommand.ExecuteReader dlFileList.DataBind() con.Close() End Sub Sub memberid() Dim cmd As New SqlCommand("SELECT MemberID From Memberlist WHERE UserName = '" & Session("uName") & "'", con) Dim r As SqlDataReader con.Open() r = cmd.ExecuteReader If r.HasRows Then r.Read() smemberid = r("MemberID").ToString End If r.Close() con.Close() End Sub Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) If flupload.HasFile = False Then Label1.Text = "Please select a picture from your computer" Exit Sub End If If flupload.FileName.GetType.ToString = "jpg" Then Label1.Text = "Hurrey" Exit Sub End If 'Has the file been uploaded properly? If Not flupload.PostedFile Is Nothing Then 'Save the filename if it has a filename and exists... Dim imageToBeResized As System.Drawing.Image = System.Drawing.Image.FromStream(flupload.PostedFile.InputStream) Dim imageHeight As Integer = imageToBeResized.Height Dim imageWidth As Integer = imageToBeResized.Width Dim maxHeight As Integer = 98 Dim maxWidth As Integer = 98 imageHeight = (imageHeight * maxWidth) / imageWidth imageWidth = maxWidth Try If flupload.PostedFile.FileName.Trim().Length > 0 And _ flupload.PostedFile.ContentLength > 0 Then photoid = (New Random).Next Dim objstream As Stream = flupload.PostedFile.InputStream Dim objimage As System.Drawing.Image = System.Drawing.Image.FromStream(objstream) If objimage.RawFormat.Equals(ImageFormat.Gif) Or objimage.RawFormat.Equals(ImageFormat.Jpeg) Or objimage.RawFormat.Equals(ImageFormat.Png) Then Dim strBaseDir As New DirectoryInfo((Request.PhysicalApplicationPath) + "images\gallery\") If imageHeight > maxHeight Then imageWidth = (imageWidth * maxHeight) / imageHeight imageHeight = maxHeight End If Dim bitmap As New Bitmap(imageToBeResized, imageWidth, imageHeight) Dim stream As System.IO.MemoryStream = New MemoryStream() bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg) stream.Position = 0 Dim strFileName As String = _ Path.GetFileName(flupload.PostedFile.FileName) bitmap.Save(((Request.PhysicalApplicationPath) + "images\gallery\thumbs\") & photoid & ".jpg") bigimage() 'File has been saved! Dim mycommand As New SqlCommand("Insert chairperson (memberid,name,period,achieve,imageurl,other) Values ( '" & smemberid & "','" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & photoid & "','" & TextBox4.Text & "' )", con) con.Open() mycommand.ExecuteNonQuery() con.Close() Label1.Text = "File has been successfully uploaded" Else Label1.Text = "Sorry, File format not supported." End If End If Catch ex As Exception Label1.Text = ex.Message End Try Else Label1.Text = "<hr /><p>Enter a filename to upload!" End If End Sub Sub bigimage() Dim imageToBeResized As System.Drawing.Image = System.Drawing.Image.FromStream(flupload.PostedFile.InputStream) Dim imageHeight As Integer = imageToBeResized.Height Dim imageWidth As Integer = imageToBeResized.Width Dim maxHeight As Integer = 450 Dim maxWidth As Integer = 450 imageHeight = (imageHeight * maxWidth) / imageWidth imageWidth = maxWidth Dim objstream As Stream = flupload.PostedFile.InputStream Dim objimage As System.Drawing.Image = System.Drawing.Image.FromStream(objstream) If objimage.RawFormat.Equals(ImageFormat.Gif) Or objimage.RawFormat.Equals(ImageFormat.Jpeg) Or objimage.RawFormat.Equals(ImageFormat.Png) Then Dim strBaseDir As New DirectoryInfo((Request.PhysicalApplicationPath) + "images\gallery\") If imageHeight > maxHeight Then imageWidth = (imageWidth * maxHeight) / imageHeight imageHeight = maxHeight End If Dim bitmap As New Bitmap(imageToBeResized, imageWidth, imageHeight) Dim stream As System.IO.MemoryStream = New MemoryStream() bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg) stream.Position = 0 Dim strFileName As String = _ Path.GetFileName(flupload.PostedFile.FileName) bitmap.Save(((Request.PhysicalApplicationPath) + "images\gallery\") & photoid & ".jpg") End If End Sub Sub deleteg(ByVal s As Object, ByVal f As DataListCommandEventArgs) Dim photographid As String photographid = dlFileList.DataKeys.Item(f.Item.ItemIndex).ToString Dim mycommand As New SqlCommand("DELETE FROM Photo WHERE PhotoID = '" & photographid & "'", con) con.Open() mycommand.ExecuteNonQuery() con.Close() bindphoto() Label1.Text = "File has been deleted succefully" End Sub ```
You'll need to do it yourself, including the controls. You might use the transparent controls here: <http://brandonwalkin.com/bwtoolkit/>
40562
I want to design a widget of shape of a chat bubble where one corner is pinned and its height should adjust to the lines of the text? For now I'm using ClipRRect widget with some borderRadius. But I want one corner pinned. Any suggestions ? [![Chat bubble shape](https://i.stack.imgur.com/sfSuW.png)](https://i.stack.imgur.com/sfSuW.png) **UPDATE** I know this can be done using a stack but I'm looking for a better solution since I have to use it many times in a single view and using many stacks might affect the performs. ( correct me here if I'm wrong )
For someone who want this get done with library. You can add `bubble: ^1.1.9+1` (Take latest) package from pub.dev and wrap your message with Bubble. ``` Bubble( style: right ? styleMe : styleSomebody, //Your message content child here... ) ``` Here `right` is boolean which tells the bubble is at right or left, Write your logic for that and add the style properties `styleMe` and `styleSomebody` inside your widget as shown below. Change style according to your theme. ``` double pixelRatio = MediaQuery.of(context).devicePixelRatio; double px = 1 / pixelRatio; BubbleStyle styleSomebody = BubbleStyle( nip: BubbleNip.leftTop, color: Colors.white, elevation: 1 * px, margin: BubbleEdges.only(top: 8.0, right: 50.0), alignment: Alignment.topLeft, ); BubbleStyle styleMe = BubbleStyle( nip: BubbleNip.rightTop, color: Colors.grey, elevation: 1 * px, margin: BubbleEdges.only(top: 8.0, left: 50.0), alignment: Alignment.topRight, ); ```
41136
With regards to the below code, I am trying to return a variable from inside of loop. I am calling the loop from inside of a function, however when the script is run I get "Uncaught ReferenceError: newVar is not defined". Could someone explain why the value isn't being returned? <https://jsfiddle.net/95nxwxf4/> ``` <p class="result"></p> var testVar = [0,1,2]; var loopFunction = function loopFunction() { for (var j=0;j<testVar.length;j++) { if (testVar[j]===1) { var newVar = testVar[j]; return newVar; } } return false; }; var privateFunction = (function privateFunction() { loopFunction(); document.querySelector('.result').innerHTML = newVar; })(); ```
You need to assign the value returned from `loopFunction`: ``` var privateFunction = (function privateFunction() { var newVar = loopFunction(); document.querySelector('.result').innerHTML = newVar; })(); ``` Edit: This is because the `newVar` assigned in `loopFunction` is scoped to that function, meaning it only exists inside that function.
41500
sorry about the code it is sloppy right now because I've been trying to fix it. Im using a function from another file to remove even numbers from my list but after I call the function the list returns empty. ``` from usefullFunctions import * def main (): mylist1 = uRandomList(10,0,15) listLength = len(mylist1) print("list1 contains %s numbers " % listLength) print (mylist1) evenOut = removeEven(mylist1) print (mylist1) main() ``` These are the two functions that I am calling from the other file. ``` def removeEven(listIn): result = [] i = 0 while i < len(listIn): if (i % 2 ) == 0: listIn.pop(i) else: i = i + 1 return result ``` ``` def uRandomList (num, minValue, maxValue): result = [] for i in range (num): d1 = randint(minValue, maxValue) if d1 not in result: result.append(d1) return result ``` I'm just trying to get it to remove even numbers from the list so that I can print it with the even numbers removed. Thank you for your help in advance. Fixed function ``` def removeEven(listIn): i = 0 while i < len(listIn): if listIn[i] % 2 == 0: listIn.pop(i) else: i = i + 1 return ```
Its either a subquery or a group by query. Cant tell without the schema. Add the table definitions to your question and it will likely be a simple answer, unless this is already enough information. As a completely guessed view of your data, it will be: ``` select CourseNumber,CourseName,Department,count(*) as NumberSections from course join section on section.courseid=course.courseid group by CourseNumber,CourseName,Department ``` I'm really going out on a limb here though!!
41751
Trying to convert some code, but for all my googling I can't figure out how to convert this bit. ``` float fR = fHatRandom(fRadius); float fQ = fLineRandom(fAngularSpread ) * (rand()&1 ? 1.0 : -1.0); float fK = 1; ``` This bit ``` (rand()&1 ? 1.0 : -1.0); ``` I can't figure out.
It's 1 or -1 with 50/50 chance. An equivalent C# code would be: ``` ((new Random().Next(0, 2)) == 0) ? 1.0 : -1.0; ``` `Next(0,2)` will return either 0 or 1. If the code gets called a lot you should store the instance of `Random` and re-use it. When you create a new instance of `Random` it gets initialized with a seed that determines the sequence of pseudo-random numbers. In order to have better "randomness" you shouldn't re-initialize the random sequence often.
42045
Please see link below for a sample. Depending on a condition (text) in column A, cell E1 & E2 should auto-populate. This should depend on the condition (text) in column A and total in E5 etc. [Google Docs sample](https://docs.google.com/spreadsheets/d/1IbUthijitKFUsdY-eV9upWNcWhP7AvAGRR842WpkWW8/edit?usp=sharing)
**Method 1: use SUMIF()** Cell E1: `=SUMIF(A5:A,"ORDER",E5:E)` Cell E2: `=SUMIF(A5:A,"SALE",E5:E)` --- **Method 2: use SUMIFS()** Cell E1: `=SUMIFS(E5:E,A5:A,"ORDER")` Cell E2: `=SUMIFS(E5:E,A5:A,"SALE")` --- **Method 3: Use SUM() and FILTER()** Cell E1: `=SUM(FILTER(E5:E,A5:A="ORDER"))` Cell E2: `=SUM(FILTER(E5:E,A5:A="SALE"))` --- **Method 4: Use QUERY() for all type in column A** Cell D1 (need Clear all value in Range D1:E3): `=QUERY(A4:E,"select A,sum(E) where A!='' group by A label A 'Type',sum(E) 'Total'")` --- > > Bonus: in cell E5 you can use ArrayFormula > > > Cell E5 (need Clear all value in Range E5:E): `=ArrayFormula(IF(A5:A<>"",B5:B*C5:C+D5:D,""))` **Function References** * [SUMIF](https://support.google.com/docs/answer/3093583?hl=en) * [FILTER](https://support.google.com/docs/answer/3093197?hl=en) * [Query](https://support.google.com/docs/answer/3093343?hl=en)
42336
I have a collection of data like so ``` Programme title | Episode | Subtitle | Performers | Description ``` Initially I normalised this into two table like so ``` PROGRAMME progid | progtitle | description EPISODE epid | progid | episode | subtitle | description ``` I'm thinking I'd like to represent the performers in another table though, but not sure how to represent it. From what I can tell the following relationships exist * One to Many: A programme can have many performers * One to Many: A performer could feature in many programmes I'm not sure how I would represent this? **EDIT** Ah I see so I'd actually have tables like this for example? ``` PERFORMER performerid | performer PROGRAMME progid | progtitle | description EPISODE epid | progid | episode | subtitle | description PROG_PERFORMER progid | performerid ```
It's many-to-many. One performer can be in multiple programs, and one program can have multiple performers. There's plenty of information on the net (and in textbooks) about setting up many-to-may relationships. One such resource is here: <http://www.tekstenuitleg.net/en/articles/software/database-design-tutorial/many-to-many.html> Really, though it should be * A Program has a one-many relationship with episodes * An episode has a many-many relationship with performers. This is enough to create a query that will list all performer/show/episode relationships.
42566
As title, I use C to do this job between two programs in Linux system. But, I encounter some problem. Assuming that I have a server write data to FIFO in ten rounds, and the client will read each round data and write another FIFO to feed back to server. The client will block in each round until that the server writer data in. However, my client program can't do this. I use `fopen` to open the FIFO and `fgets` to read data. It seems not to block to wait data write in. client code: ``` FILE *fp_R,*fp_W; char temp[100]; fp_R = fopen(FIFO_R,"rb"); fp_W = fopen(FIFO_W,"wb"); for ( i = 0 ; i < 10 ; i ++ ) { fgets(temp, 100, fp_R); Handle Data; fprintf(fp_W,DATA); } ``` I want to `fgets` to wait for server writing data in, so that I can handle each round Thanks for anyone help
as TonyB said, the `fopen()` function will return a file pointer `FILE*` ``` FILE *fp_R, *fp_W; char temp[100]; fp_R = fopen(FIFO_R,"rb"); fp_W = fopen(FIFO_W,"wb"); for ( i = 0 ; i < 10 ; i ++ ) { char* ret = fgets(temp, 100, fp_R); while(ret == null) { Sleep(1); } Handle Data; fprintf(fp_W,DATA); } ```
43006
A PDF output is obtained by compiling the following code. ``` \documentclass{article} \usepackage{xcolor} \usepackage{listings} \lstset { language={[LaTeX]TeX}, numbers=left, numbersep=1em, numberstyle=\tiny, frame=single, framesep=\fboxsep, framerule=\fboxrule, rulecolor=\color{red}, xleftmargin=\dimexpr\fboxsep+\fboxrule\relax, xrightmargin=\dimexpr\fboxsep+\fboxrule\relax, breaklines=true, basicstyle=\small\tt, keywordstyle=\color{blue}, commentstyle=\color[rgb]{0.13,0.54,0.13}, backgroundcolor=\color{yellow!10}, tabsize=2, columns=flexible, morekeywords={maketitle}, } \begin{document} \begin{lstlisting} \documentclass{article} \usepackage{listings} \title{Sample Document} \author{John Smith} \date{\today} \begin{document} \maketitle Hello World! % This is a comment. \end{document} \end{lstlisting} \end{document} ``` I attempted to copy the code only inside Acrobat Reader. Unfortunately, the line numbers also got copied as shown on the following screen shot. ![enter image description here](https://i.stack.imgur.com/SyOza.png) The line numbers are useful, but readers want not to copy them. Is there a LaTeX trick to prevent a PDF viewer from copying the line number?
This solution is *very* similar to that contained in [How to make text copy in PDF previewers ignore lineno line numbers?](https://tex.stackexchange.com/questions/30783/5764) `\protect`ing the [`accsupp`](http://ctan.org/pkg/accsupp) is the only requirement, perhaps due to the nature in which [`listings`](http://ctan.org/pkg/listings) treats *everything*: ![enter image description here](https://i.stack.imgur.com/lUb2w.png) ``` \documentclass{article} \usepackage{xcolor}% http://ctan.org/pkg/xcolor \usepackage{listings}% http://ctan.org/pkg/listings \usepackage{accsupp}% http://ctan.org/pkg/accsupp \renewcommand{\thelstnumber}{% Line number printing mechanism \protect\BeginAccSupp{ActualText={}}\arabic{lstnumber}\protect\EndAccSupp{}% } \lstset { language={[LaTeX]TeX}, numbers=left, numbersep=1em, numberstyle=\tiny, frame=single, framesep=\fboxsep, framerule=\fboxrule, rulecolor=\color{red}, xleftmargin=\dimexpr\fboxsep+\fboxrule\relax, xrightmargin=\dimexpr\fboxsep+\fboxrule\relax, breaklines=true, basicstyle=\small\tt, keywordstyle=\color{blue}, commentstyle=\color[rgb]{0.13,0.54,0.13}, backgroundcolor=\color{yellow!10}, tabsize=2, columns=flexible, morekeywords={maketitle}, } \begin{document} \begin{lstlisting} \documentclass{article} \usepackage{listings} \title{Sample Document} \author{John Smith} \date{\today} \begin{document} \maketitle Hello World! % This is a comment. \end{document} \end{lstlisting} \end{document} ```
43126
I have a Common Stock certificate for 310 shares of Antares Resources Corporation issued March 24, 1997. The corporate seal shows a 1958 date. I believe the company changed its name and ticker symbol and may have been delisted at some point. Is the company still in business and is there any value in the shares I have?
Antares Resources was delisted from Nasdaq in Feb 1997 due to it having too low a price (it closed at $1.375 on 4 Feb 1997). It then went and traded as an OTC stock and did not make any SEC filings until 2006 (apart from a minor filing for issue of securities to employees). In 19976 SEC queried them about not reporting but there doesn't appear to be any response. In 2006 the company issued a report, but this was issued by a Chapter 11 (Bankruptcy) Trustee, with no further filings, with practically zero cash balance, so this company would seem to be defunct with no return to shareholders. Sources: Stock data from Norgate Data <https://norgatedata.com/> SEC filings by Antares Resources <https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000065202&owner=exclude&count=40>
43208
I have to handle some strings, I should put them **N** positions to left to organize the string. Here's my code for while: ``` private String toLeft() { String word = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Example byte lpad = 2; // Example StringBuilder sb = new StringBuilder(); for (int i = 0; i < word.length(); i++) { sb.append((char) (word.charAt(i) - lpad)); } return sb.toString(); } ``` It's working for inputs that don't have to move many times... So, the problem is that when the number N of positions to move is a little bit large (like 10), it returns me non letters, like in the example below, what can I do to prevent it? Ex.: `ABCDEFGHIJKLMNOPQRSTUVWXYZ` if I move each char 10 positions to left it returns `789:;<=>?@ABCDEFGHIJKLMNOP` while it must return `QRSTUVWXYZABCDEFGHIJKLMNOP`. ### Some inputs and their expected outputs: * `VQREQFGT // 2 positions to left == TOPCODER` * `ABCDEFGHIJKLMNOPQRSTUVWXYZ // 10 positions to left == QRSTUVWXYZABCDEFGHIJKLMNOP` * `LIPPSASVPH // 4 positions to left == HELLOWORLD`
I think you have misunderstood what your (homework?) requirements are asking you to do. Lets look at your examples: > > VQREQFGT // 2 positions to left == TOPCODER > > > Makes sense. Each character in the output is two characters before the corresponding input. But read on ... > > ABCDEFGHIJKLMNOPQRSTUVWXYZ // 10 positions to left == QRSTUVWXYZABCDEFGHIJKLMNOP > > > Makes no sense (literally). The letter `Q` is not 10 characters before `A` in the alphabet. There is no letter in the alphabet that is before `A` in the alphabet. OK so how do you get from `A` to `Q` in 10 steps? Answer ... you wrap around! `A`, `Z`, `Y`, `X`, `W`, `V`, `U`, `T`, `S`, `R`, `Q` ... 10 steps: count them. So what the requirement is actually asking for is N characters to the left *with wrap around*. Even if they don't state this clearly, it is the only way that the examples "work". But you just implemented N characters to the left *without* wrap around. You need to implement the wrap around. (I won't show you how, but there lots of ways to do it.) --- There's another thing. The title of the question says "Decrement only letters" ... which implies to me that your requirement is saying that characters that are not letters should not be decremented. However, in your code you are decrementing *every* character in the input, whether or not it is a letter. (The fix is simple ... and you should work it out for yourself.)
43690
I don't understand how to run c++ code in java using JNI. I think there's some error in the makefile, I think some lib are missing. I have this code in java class: ``` private native void getCanny(long mat); getCanny(mat.getNativeObjAddr()); ``` and the Mat2Image.h generated: ``` /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class Mat2Image */ #ifndef _Included_Mat2Image #define _Included_Mat2Image #ifdef __cplusplus extern "C" { #endif /* * Class: Mat2Image * Method: getCanny * Signature: (J)V */ JNIEXPORT void JNICALL Java_Mat2Image_getCanny (JNIEnv *, jobject, jlong); #ifdef __cplusplus } #endif #endif ``` and this is the .cpp I've made: ``` #include "Mat2Image.h" #include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/imgproc.hpp> JNIEXPORT void JNICALL Java_Mat2Image_getCanny (JNIEnv * env, jobject obj, jlong matr){ cv::Mat* frame=(cv::Mat*)matr; cv::cvtColor(*frame, *frame, CV_BGR2GRAY); cv::GaussianBlur(*frame, *frame, cv::Size(7,7), 1.5, 1.5); cv::Canny(*frame, *frame, 0, 30, 3); } ``` and this is my makefile: ``` # Define a variable for classpath CLASS_PATH = ../bin # Debug: -g3=compile with extra debugg infos. -ggdbg3=include things like macro defenitions. -O0=turn off optimizations. DEBUGFLAGS = -g3 -ggdb3 -O0 CFLAGS = $(DEBUGFLAGS) # Define a virtual path for .class in the bin directory vpath %.class $(CLASS_PATH) all : libMat.so # $@ matches the target, $< matches the first dependancy libMat.so : libMat.o g++ $(CFLAGS) -W -shared -o $@ $< # $@ matches the target, $< matches the first dependancy libMat.o : Mat2Image.cpp Mat2Image.h g++ $(CFLAGS) -fPIC -I/usr/lib/jvm/jdk1.8.0_111/include -I/usr/lib/jvm/jdk1.8.0_111/include/linux -c $< -o $@ # $* matches the target filename without the extension # manually this would be: javah -classpath ../bin HelloJNI HelloJNI.h : Mat2Image.class javah -classpath $(CLASS_PATH) $* clean : rm -f Mat2Image.h libMat.o libMat.so ``` but when I try to run the method I have this error: ``` /usr/lib/jvm/jdk1.8.0_111/bin/java: symbol lookup error: /home/buzzo/Downloads/helloJni-master/jni/libMat.so: undefined symbol: _ZN2cv8cvtColorERKNS_11_InputArrayERKNS_12_OutputArrayEii ``` I think the problem is the makefile, how can I edit it?
The missing part was `env: flex` So, the right yaml file should look like this: ``` runtime: python threadsafe: yes env: flex entrypoint: gunicorn -b :$PORT main:app runtime_config: python_version: 3 handlers: - url: .* script: main.app ```
43755
I got this error while debugging in SSIS: > > > > > > Error: 0xC0049064 at Data Flow Task, Derived Column [70]: An error occurred while attempting to perform a type cast. > > Error: 0xC0209029 at Data Flow Task, Derived Column [70]: SSIS Error Code DTS\_E\_INDUCEDTRANSFORMFAILUREONERROR. The "component "Derived Column" (70)" failed because error code 0xC0049064 occurred, and the error row disposition on "output column "EVENT\_DT" (118)" specifies failure on error. An error occurred on the specified object of the specified component. There may be error messages posted before this with more information about the failure. > > Error: 0xC0047022 at Data Flow Task: SSIS Error Code DTS\_E\_PROCESSINPUTFAILED. The ProcessInput method on component "Derived Column" (70) failed with error code 0xC0209029. The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running. There may be error messages posted before this with more information about the failure. > > Error: 0xC0047021 at Data Flow Task: SSIS Error Code DTS\_E\_THREADFAILED. Thread "WorkThread0" has exited with error code 0xC0209029. There may be error messages posted before this with more information on why the thread has exited. > > Information: 0x40043008 at Data Flow Task, DTS.Pipeline: Post Execute phase is beginning. > > Information: 0x40043009 at Data Flow Task, DTS.Pipeline: Cleanup phase is beginning. > > Information: 0x4004300B at Data Flow Task, DTS.Pipeline: "component "DataReaderDest" (143)" wrote 0 rows. > > Task failed: Data Flow Task > > Warning: 0x80019002 at Package: SSIS Warning Code DTS\_W\_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (4) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors. > > SSIS package "Package.dtsx" finished: Failure. > > > > > > > > > My expression is: ``` (DT_DBTIMESTAMP)(SUBSTRING(EVENT_D,7,4) + "-" + SUBSTRING(EVENT_D,4,2) + "-" + SUBSTRING(EVENT_D,1,2) + EVENT_T) ``` My original data are in this sequence: ``` EVENT_D: DD/MM/YYYY EVENT_T: HH:MM:SS ``` Any help are appreciated. I have try changing my expression numerous time but still fails.
I suspect that there are some date time values which are not in the correct format .So SSIS throws error while parsing them . In order to find to incorrect date time value from your source table try to redirect the error rows from `Derived Transformation` and check the incorrect data using a data viewer The problem with substring values are if the string data are not in the correct format then the `Derived Transformation` will throw error . 1. In your OLEDB source component try to write the sql and get only the correct datetime values Ex: ``` Select col1, case when isDate(EVENT_D) = 1 THEN EVENT_D ELSE NULL END as [EVENT_D], Col2,EVENT_T,other columns from yourTable ``` in your derived transformations use your code to convert into `DT_DBTIMESTAMP` type . 1. Else Try to use a script component and parse the `EVENT_D` and `EVENT_T` values and convert to datetime values. No need to use Derived column with all those `substring` values create a `New Output column` `Valid_D` with the datatype as `DT_DBTIMESTAMP`.Select the 2 input columns EVENT\_D and EVENT\_T in the `available input Columns` in `Script Transformation Editor` VB.NET code ``` Dim result As DateTime If DateTime.TryParseExact(Row.EVENT_D, "dd/MM/yyyy", Nothing, Globalization.DateTimeStyles.None, result) Then Row.ValidD = result.Add (TimeSpan .Parse (Row.EventT ) ); End If ``` C# code ``` DateTime result; if (DateTime.TryParseExact(Row.EventD, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None,out result)) { Row.ValidD = result.Add (TimeSpan .Parse (Row.EventT ) ); } ``` Now you can use Valid\_D column which is of DateTime type in your subsequent transformations `Update` : The problem with your syntax is you cannot add date+ time in the string format . You need to `parse` individually both EVENT\_D and EVENT\_T . ``` (DT_DBTIMESTAMP)(SUBSTRING(EVENT_D,7,4) + "-" + SUBSTRING(EVENT_D,4,2) + "-" + SUBSTRING(EVENT_D,1,2) + EVENT_T) So your syntax is not valid. ``` The `isDate` function shows NULL for `30/04/2012` because as per MSDN ``` The return value of ISDATE depends on the settings set by SET DATEFORMAT, SET LANGUAGE and Configure the default language Server Configuration Option. ``` but it returns 1 for the value `01/05/2012` and `02/05/2012` because it takes as MM/dd/YYYY so the 1st date is Jan 5th 2012 instead of May 1st 2012 So the soultion is use script component and parse these values into valid date and time and then use it in your subsequent transformations . Please check my script transformation code above ``` Update 2: ``` I think your using SSIS 2005 .The code should be ``` Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer) Dim result As DateTime If DateTime.TryParseExact(Row.EVENTD, "dd/MM/yyyy", Nothing, Globalization.DateTimeStyles.None, result) Then Row.ValidD = result.Add(TimeSpan.Parse(Row.EVENTT)) End If End Sub ``` after Script transformation ,you don't need to use Derived component .The result obtained in the column Valid\_D contains the valid value which is of `datetime` format
43855
Do you know any PDF reader which remembers the last page for each document? The usage scenario should be something like this: * A new PDF file is loaded into the reader * The PDF file is opened on page 0 * Reading, reading, reading ... Reading finished at page 37. * Reader closed ... * The same PDF file is loaded into the reader * The PDF File is opened on page 37 I don't need multiple bookmarks. Just one is enough. Any tips?
[Evince](http://projects.gnome.org/evince/) does that...it's for Linux, but hey you never said anything about the OS: ;)
44396
I am getting "can only concatenate list (not "MultiValue") to list" highlighting map (float portion, while running below resampling, this code is very commonly used throughout image segmentation like lungs etc, I am thinking maybe this is issue with Python 3 and was working for earlier versions, any help is much appreciated: ``` id = 0 imgs_to_process = np.load(output_path+'fullimages_{}.npy'.format(id)) def resample(image, scan, new_spacing=[1,1,1]): # Determine current pixel spacing spacing = map(float, ([scan[0].SliceThickness] + scan[0].PixelSpacing)) spacing = np.array(list(spacing)) resize_factor = spacing / new_spacing new_real_shape = image.shape * resize_factor new_shape = np.round(new_real_shape) real_resize_factor = new_shape / image.shape new_spacing = spacing / real_resize_factor image = scipy.ndimage.interpolation.zoom(image, real_resize_factor) return image, new_spacing print ("Shape before resampling\t", imgs_to_process.shape) imgs_after_resamp, spacing = resample(imgs_to_process, patient, [1,1,1]) print ("Shape after resampling\t", imgs_after_resamp.shape) ```
Change ``` spacing = map(float, ([scan[0].SliceThickness] + scan[0].PixelSpacing)) ``` To ``` spacing = map(float, ([scan[0].SliceThickness] + list(scan[0].PixelSpacing))) ``` Basically scan[0].PixelSpacing is a MultiValue and need to be converted into list before concatenation to another list.
44452
Updated with actual JSON Response, Messed up last time. It is my second day with JSON, and i am stuck at the first step of my project. i created a wcf rest service which gives this test json response. ``` [{ "busyEndTime":"\/Date(928164000000-0400)\/", "busyStartTime":"\/Date(928164000000-0400)\/", "endGradient":1.26743233E+15, "startGradient":1.26743233E+15, "status":"String content" ``` }] i am trying to read the content of this output and use the content for various other purposes. By content i am referring to the "busyEndTime, busyStartTime" values etc. I have tried numerous examples on the net, but my bad luck continues, following are the ways i tried to read the above, but failed. ``` $('#btnGetTime').click(function () { $.ajax({ cache: false, type: "GET", async: false, url: serviceAddress, dataType: "application/json; charset=utf-8", data: "{}", success: function (student) { ``` \*\**\**\*\**\**\*\**\**\*\**\**\*\**\**\*\**\**\* Try 1 ``` var obj = jQuery.parseJSON(student); for (var i = 0; i < obj.length; i++) { alert(obj[i]); } ``` \*\**\**\*\**\**\*\**\**\* Try 2 ``` var obj = eval("(" + student + ")"); for (var i = 0; i < obj.length; i++) { alert(obj[i]); } ``` \*\**\**\*\**\**\*\**\**\*\**\**\*\*Try 3 ``` success: test(student) ....... ..... function test(jObject) { var jArrayObject = jObject if (jObject.constructor != Array) { jArrayObject = new Array(); jArrayObject[0] = jObject; } ``` \*\**\**\*\**\**\*\**\**\*\*\*\*\*Try 4 ``` success: test(student) ....... ..... function test(jObject) { var jArrayObject = jObject for (var i = 1, n = jObject.length; i < n; ++i) { var element = jObject[i]; ................ .................... } ``` \*\**\**\*\**\**\*\**\**\*\**\**\*\*\* Try5 ``` $.each(jArrayObject, function (key, value) { alert(key + ": " + value); }); ``` --- I would really appreciate if some one could guide step by step, of how to read the JSON response like i have above and iterate over the array that the response contains and finally use the content that lies in the array, at least alert the key value pairs. A quick response is all i want, i am loosing interest in jquery with each passing minute. :(
**Update**: Now that you've posted the actual JSON text, here's an example of using it: ``` $.getJSON(url, function(data) { // jQuery will deserialize it into an object graph for // us, so our `data` is now a JavaScript object -- // in this case, an array. Show how many entries we got. display("Data received, data.length = " + data.length); // Show the start and end times of each entry $.each(data, function(index) { display("Entry " + index + ": Start = " + this.busyStartTime + ", end = " + this.busyEndTime); }); }); ``` [Live copy](http://jsbin.com/obama4/4) Output: ``` Loading JSON from /aduji4/4... Data received, data.length = 1 Entry 0: Start = /Date(928164000000-0400)/, end = /Date(928164000000-0400)/ ``` Note that the dates aren't automagically handled unless you use a "reviver" with the JSON parser that understands that particular date format. JSON has no date format of its own, but it has this concept of a "reviver" that can be used during the deserialization process to pre-process values. jQuery's own JSON parser doesn't have the "reviver" feature, but you can download ones that do (there are three on [Douglas Crockford's github page](https://github.com/douglascrockford/JSON-js/) — Crockford being the inventor of JSON). Then you'd tell jQuery *not* to parse the JSON, and instead do it explicitly yourself. That would look like this: ``` // Start loading the JSON data $.ajax({ url: url, dataType: "text", // Tell jQuery not to try to parse it success: function(data) { // `data` contains the string with the JSON text. // Deserialize it. jQuery's own JSON parser doesn't // have the "reviver" concept, but this is where you // would use one that does, giving it the reviver. data = $.parseJSON(data); // Now we have the object graph (an array in this // case), show how many entries it has. display("Data received, data.length = " + data.length); // Show the start and end times of each entry $.each(data, function(index) { display("Entry " + index + ": Start = " + this.busyStartTime + ", end = " + this.busyEndTime); }); }, error: function() { display("Error loading JSON"); } }); ``` [Live copy](http://jsbin.com/obama4/6) ...except of course you'd use some other JSON parser rather than `$.parseJSON`. --- **Original answer**: ### The problem > > i created a wcf rest service which gives this test json response. > > > That's not JSON. You can read up on JSON [here](http://json.org), and you can validate your JSON strings [here](http://jsonlint.com). I'm not quite sure what it is. It looks a lot like XML, but like someone took the XML from a tree viewer or something (those `-` symbols next to the beginnings of elements). Below, I'll show what that data might look like in JSON, how you would work with it, and then if you want to work with XML instead, the same example using XML data. ### Your data in JSON format Here's an idea of what that might look like in JSON: ``` { "ArrayOfBusyDateTime": [ { "busyEndTime": "2011-04-20T10:30:00", "busyStartTime": "2011-04-20T10:00:00", "endGradient": 0, "startGradient": 0, "status": "busy" }, { "busyEndTime": "2011-04-20T13:00:00", "busyStartTime": "2011-04-20T12:00:00", "endGradient": 0, "startGradient": 0, "status": "busy" } ] } ``` Note that the types (element names) have gone, because JSON has no concept of element names. (If you want them, you can create a key that holds the relevant information.) So each of the two entries in the array is a `busyDateTime` by virtue purely of being in the `ArrayOfBusyDateTime`. But one of the things about JSON is that it's very malleable, so you may prefer to do it slightly differently. ### Working with that JSON data Here's an example of using that data: ``` $.getJSON(url, function(data) { // jQuery will deserialize it into an object graph for // us, so our `data` is now a JavaScript object. // Show how many entries we got in the array: display("Data received, ArrayOfBusyDateTime.length = " + data.ArrayOfBusyDateTime.length); // Show the start and end times of each entry $.each(data.ArrayOfBusyDateTime, function(index) { display("Entry " + index + ": Start = " + this.busyStartTime + ", end = " + this.busyEndTime); }); }); ``` [Live copy](http://jsbin.com/obama4) Output: ``` Loading JSON from /aduji4... Data received, ArrayOfBusyDateTime.length = 2 Entry 0: Start = 2011-04-20T10:00:00, end = 2011-04-20T10:30:00 Entry 1: Start = 2011-04-20T12:00:00, end = 2011-04-20T13:00:00 ``` ### XML For completeness, if your data really is XML, like this: ``` <ArrayOfBusyDateTime xmlns="http://schemas.datacontract.org/2004/07/RestServiceTest" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <BusyDateTime> <busyEndTime>2011-04-20T10:30:00</busyEndTime> <busyStartTime>2011-04-20T10:00:00</busyStartTime> <endGradient>0</endGradient> <startGradient>0</startGradient> <status>busy</status> </BusyDateTime> <BusyDateTime> <busyEndTime>2011-04-20T13:00:00</busyEndTime> <busyStartTime>2011-04-20T12:00:00</busyStartTime> <endGradient>0</endGradient> <startGradient>0</startGradient> <status>busy</status> </BusyDateTime> </ArrayOfBusyDateTime> ``` ### Working with XML data: ...then here's how you might work with that: ``` $.ajax({ url: url, dataType: "xml", success: function(data) { // jQuery will deserialize it for us, so our // `data` is now an XML document. Wrap a jQuery // instance around it to make it easy to work with. data = $(data); // Show how many entries we got in the array var busyDateTimes = data.find("BusyDateTime"); display("Data received, ArrayOfBusyDateTime length = " + busyDateTimes.length); // Show the start and end times of each entry busyDateTimes.each(function(index) { // In this loop, `this` will be the raw XML // element; again wrap a jQuery object around // it for convenience var $this = $(this); display("Entry " + index + ": Start = " + $this.find("busyStartTime").text() + ", end = " + $this.find("busyEndTime").text()); }); }, error: function() { display("Error loading XML"); } }); ``` [Live copy](http://jsbin.com/obama4/2) ...although I don't work with XML much, could be some efficiencies to be had (seems like a lot of wrapping things up in jQuery instances). Output: ``` Loading JSON from /aduji4/2... Data received, ArrayOfBusyDateTime length = 2 Entry 0: Start = 2011-04-20T10:00:00, end = 2011-04-20T10:30:00 Entry 1: Start = 2011-04-20T12:00:00, end = 2011-04-20T13:00:00 ```
44531
I want the item to be replaced with an another item when the overridden function fires. ```java @Override public ActionResultType itemInteractionForEntity(ItemStack stack, PlayerEntity playerIn, LivingEntity target, Hand hand) { if (!playerIn.world.isRemote()) { // Replace an item with xyz } return super.itemInteractionForEntity(stack, playerIn, target, hand); } ``` How can I achieve this? Note: I'm using MCP mappings.
* Have you called the function yet? * Don't use `list` as a name of the variable * Update the function to return `True` only when all elements have a perfect square. code: ``` num_list = [4, 9, 16] def check_is_quadratic(x): result = [] for i in x: if math.sqrt(i).is_integer(): result.append(True) else: result.append(False) return all(result) print(check_is_quadratic(num_list)) ``` output: > > > ``` > > print(check_is_quadratic([4, 9, 16])) > True > > print(check_is_quadratic([4, 8, 16])) > False > > ``` > > --- UPDATE code with list comprehension: ``` num_list = [4, 8, 16] result = [math.sqrt(num).is_integer() for num in num_list] print(result) print(all(result)) ``` output: ``` > [True, False, True] > False ```
44735
I want to compare two datagridviews, and use the `Except` method on the `IEnumerable` interface, in order to know the difference among them. One example of my datagridviews: ``` DG1 idProduct Item 1 Item A 1 Item B 2 Item C 2 Item D DG2 idProduct Item Price IdSupplier 1 Item A 10.00 1 1 Item B 20.00 1 2 Item C 30.00 1 2 Item D 40.00 1 1 Item A 20.00 3 1 Item B 30.00 3 2 Item C 40.00 3 2 Item D 50.00 3 ``` So, I have tried to put the data from `dgv1` into an array, and the data from `dgv2` into an dynamic array, cause I want a list for each `IdSupplier` (in case, 1, 3) and compare them with the except method. My code is: ``` Imports System.Data.SqlClient Imports System.Data Imports datagridviewTota.DataSet1TableAdapters Imports System.Collections.Generic Imports System.Collections.ArrayList Imports System.Collections.CollectionBase Public Class form1 Public itemArray() Public ItemListArray() Public Shared j As Integer Private sub main () (…) Dim ds1 As New DataSet Dim item As List(Of String) = New List(Of String) Dim Id As Integer Dim dr As DataRow Dim dr1 As DataRow Dim itemList As List(Of String) = New List(Of String) Dim idSuppliers () as integer ReDim itemArray(j) ‘ j represents the numbers of elements in idSuppliers() (third column of dg2) Try //create an array for the dgv1// For Each row As DataGridViewRow In dgv1.Rows item = dgv1.Rows(row.Index).Cells(1).Value itemList.Add(item) Next Dim itemListArray = itemList.toArray() //create a dynamic array for the dgv2 by filtering for each idSuppliers, put the values from the second column into a list and convert each list into a dynamic array// For Each element In idSuppliers Dim dv As New DataView() dv = New DataView(ds1.Tables("idProduct")) With dv .RowFilter = "idSupplier = " & element & " " End With dgv2.DataSource = dv For Each row As DataGridViewRow In dgv2.Rows Id = dgv2.Rows(row.Index).Cells(3).Value If Id = element Then item = dgv2.Rows(row.Index).Cells(1).Value itemList.Add(item) End If Next itemArray(i) = itemList.ToArray() itemList.clear() i = i + 1 Next end sub ``` So, I have tried the `IEnumerable.Except`, but it seems that my `itemArray()` is a object, cause I got the message `"System.linq.Enumerable+<ExceptIterator>d_99'1[System.Object]"`, when I try to try to cast `exceptItems`, as follows: ``` Dim exceptItems = itemListArray.Except(itemArray(2)) ``` I also have tried: ``` Dim onlyInFirstSet As IEnumerable(Of String) = itemListArray.Except(itemArray(2)) Dim output As New System.Text.StringBuilder For Each str As String In onlyInFirstSet output.AppendLine(str) Next MsgBox(output.ToString()) ``` And know I get the err. number 13. I think the problem is that I have to convert `itemArray()` into an `IEnumerable`, is there any way that I could do this without major changes in my code?
Font size does not depend on button height. If you set it too small to fit the text, you will get the result you observe **EDIT** `wrap_content` would usually do the trick, however Button class sets some layout parameters like margin, background so it takes more space. You may get rid of Button and use i.e. `TextView` class, styled by hand to match your design. `onClickListener` will work perfectly fine with it and you will get result you want and full control over your button **EDIT 2** As this is bit related - there's AutoFitTextView widget on Github that deals with automatic text size scalling: <https://github.com/grantland/android-autofittextview>
45179
I'm using MVC4, .NET 4.5, VS2012, C#, Razor I need the public IP of client on my website. To clarify, i need the kind of IP that whatismyip shows. I know about querying whatismyip's automation page. But, I need to obtain the IP myself rather than using some other website for it. Following is my present code. Controller ```cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Net; using System.IO; using System.Web.Routing; using System.Net.Sockets; using System.Text; namespace abc { public class GetIP : Controller { public ActionResult GetIP() { ViewBag.ip1 = string.Empty; ViewBag.ip2 = string.Empty; ViewBag.defaultgateway = string.Empty; ViewBag.ip4 = string.Empty; ViewBag.dnsServer = string.Empty; ViewBag.ip6 = string.Empty; ViewBag.server_IPv6_address = string.Empty; if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null) ViewBag.ip1 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"]; if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) ViewBag.ip2 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); if (System.Web.HttpContext.Current.Request.UserHostAddress.Length != 0) ViewBag.defaultgateway = System.Web.HttpContext.Current.Request.UserHostAddress; if (System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null) ViewBag.ip4 = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); if (System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"] != null) ViewBag.dnsServer = System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"].ToString(); if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"] != null) ViewBag.ip6 = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"].ToString(); ViewBag.server_IPv6_address = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString(); if (Request.ServerVariables["X-Forwarded-For"] != null) ViewBag.ip8 = Request.ServerVariables["X-Forwarded-For"]; return View(); } } } ``` View ```html Your IP address<br /> Ip1 : @ViewBag.ip1<br /> Ip2 : @ViewBag.ip2<br /> Default Gateway : @ViewBag.defaultgateway<br /> Ip4 : @ViewBag.ip4<br /> DNS Server : @ViewBag.dnsServer<br /> IP6 : @ViewBag.ip6<br /> @*Server's IPv6 Address : @ViewBag.server_IPv6_address*@ IP8 : @ViewBag.ip8<br /> ``` When I put this code on the server, and go the the appropriate url, I get the following result. ![enter image description here](https://i.stack.imgur.com/R7V4K.png) And when I go to whatismyip, say I get 123.45.67.89 for example. Why is it that whatismyip can find my IP address but my server can't with all the headers that i have checked. I have also read somewhere about `System.Net.Sockets` class but i don't know if that would help or what. Please help. **EDIT** : Apparently this is a problem with the server configuration. When I put the same code on a different server, it works perfectly. Thanks for your help guys!
There is a [winsorize function in scipy.stats.mstats](http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.mstats.winsorize.html) which you might consider using. Note however, that it returns slightly different values than `winsorize_series`: ``` In [126]: winsorize_series(pd.Series(range(20), dtype='float'))[0] Out[126]: 0.95000000000000007 In [127]: mstats.winsorize(pd.Series(range(20), dtype='float'), limits=[0.05, 0.05])[0] Out[127]: 1.0 ``` --- Using `mstats.winsorize` instead of `winsorize_series` is maybe (depending on N, M, P) ~1.5x faster: ``` import numpy as np import pandas as pd from scipy.stats import mstats def using_mstats_df(df): return df.apply(using_mstats, axis=0) def using_mstats(s): return mstats.winsorize(s, limits=[0.05, 0.05]) N, M, P = 10**5, 10, 10**2 dates = pd.date_range('2001-01-01', periods=N//P, freq='D').repeat(P) df = pd.DataFrame(np.random.random((N, M)) , index=dates) df.index.names = ['DATE'] grouped = df.groupby(level='DATE') ``` --- ``` In [122]: %timeit result = grouped.apply(winsorize_df) 1 loops, best of 3: 17.8 s per loop In [123]: %timeit mstats_result = grouped.apply(using_mstats_df) 1 loops, best of 3: 11.2 s per loop ```
45996
The Riemann zeta function $ζ(s)$ is defined for all complex numbers $s ≠ 1$ with a simple pole at $s = 1$. It has zeros at the **negative even integers**, i.e., at $s = −2, −4, −6, ...$. My question: How one can obtain these roots.
These roots arise from that the Riemann zeta function satisfies the following *functional equation* $$ \zeta(s)=2^s \pi^{s-1} sin(\frac{\pi s}{2}) \Gamma(1-s)\zeta(1-s) $$ Thus, when s=-2n, we get that $$ \zeta(-2n)=2^{-2n} \pi^{-(2n+1)} sin(-n\pi ) \Gamma(1+2n)\zeta(1+2n) $$ which gives us $$ \zeta(-2n) = 0 $$ as $sin(-n \pi)=0 $ and $\Gamma(1+2n) $ is finite for all n $\in \mathbb{Z}^+ $.
46065
I'd like to disable the NVidia GTX 750M GPU on my MacBook Pro 15" (Retina, Mid 2014, Mac OS X 10.10 Yosemite). I know I can use GfxCardStatus but I read I could have a more permanent solution by changing some EFI flag. **My question is:** * **How can I disable the discrete GPU from EFI?** I assume this is persistent across multiple reboots. I'd also want to know how to undo it if needed. Update: The question is basically whether the command mentioned in [GfxCardStatus github issue comment here](https://github.com/codykrieger/gfxCardStatus/issues/184#issuecomment-68181412) is correct or not, and how to undo it if it doesn't work. . An answer to this alone is a correct answer, but it'll be awesome if you can also tell me: * If you force integrated graphics in GfxCardStatus, Mac OS X (up to Yosemite at least) doesn't allow you to use multiple monitors (even though the built in Iris Pro can do it). If I disable the discrete GPU from EFI, will macOS think that the integrated GPU is the one installed and will it let me use multiple monitors with it? * I heard that the same EFI setting is responsible for not even showing the integrated GPU to other operating systems than macOS and you have to trick it somehow to think it's macOS. Is that true? And if yes, how to do that?
### Your Dilemma I'm in full sympathy with your wish "save on battery and reduce heat, without paying the noise cost" of using the discrete graphics card inside a MacBook Pro. ### Warning Before you do anything which will disable your display, please make sure you are able to [log in to your MacBook Pro using SSH](https://bluishcoder.co.nz/articles/mac-ssh.html) so that you can undo your handiwork. While screen sharing with all graphic cards disabled will probably work at some default resolution, I wouldn't bet my computer on it. ### Answers > > What will happen if I permanently disable the discrete nVidia graphics card from EFI? Will Mac OS think integrated GPU is the one installed and let me use multiple monitors with it? > > > You will lose any ability to use an external monitor (under any OS). The external graphics port(s) are wired to the discrete graphics chip. My own MacBook Pro 2011 runs at a stable 60 degrees even under load with minimal fan noise when using the built-in Intel graphics and spikes to full fans (in the 4000 to 6000 RPM range) when under load with the discrete 6750. The problem is real. I too wanted to be able to only use the built-in graphics and drive an external monitor. No way, no how. > > Is it true that the same EFI doesn't even show the integrated GPU to other OSes than Mac OSes and you have to trick it somehow to think it's Mac OS? > > > Yes, it's true. The Intel GPU gets switched off by the MacBook Pro 11,3's EFI if you boot anything but Mac OS X. You have [four choices](https://github.com/0xbb/gpu-switch) if you want to use the integrated Intel chip under alternative OS: > > 1. rEFInd version 0.10.0 or above (recommended): <http://www.rodsbooks.com/refind> > > > Recent versions of rEFInd have the "apple\_set\_os" hack built-in. You can enable it by setting the spoof\_osx\_version option in your refind.conf. > > > 2. apple\_set\_os.efi: <https://github.com/0xbb/apple_set_os.efi> > 3. a patched GRUB: > <https://lists.gnu.org/archive/html/grub-devel/2013-12/msg00442.html> > <https://wiki.archlinux.org/index.php/MacBookPro11,x#Getting_the_integrated_intel_card_to_work_on_11.2C3> > 4. a patched Kernel: <https://www.marc.info/?l=grub-deavel&m=141586614924917&w=2> > > > Be careful to plan ahead. If you don't prepare, you will face a powered-down integrated graphics card and a black screen. Of course you can always go back and boot Mac OS X and start again. The simplest of the choices above would be number two - to replace the Apple EFI. Unfortunately, it's the one which could leave you unable to boot up at all at some future date. Apple does not like people to play with EFI and reserves the right to [brick your device](http://www.forbes.com/sites/ewanspence/2016/02/06/what-caused-iphone-error-53/) for doing so. If you had Apple Care and were still in the warranty period, you might find a shoulder somewhere to cry on. Might. When you change EFI, you also take [security risks](https://reverse.put.as/2015/05/29/the-empire-strikes-back-apple-how-your-mac-firmware-security-is-completely-broken/), i.e. you may make it easier to hack your machine. You need to be able to update to the latest EFI which would remove your patch. Option one, **rEFInd** puts itself between boot and EFI, which leaves considerable scope for something to go wrong and for you to be left with a brick and a long hard trail back to a working computer. How serious are these issues? Many MacBook Pro owners have [lost their hard drive](http://www.rodsbooks.com/refind/installing.html#osx) to rEFInd: > > Numerous rEFIt bug reports indicate disk corruption problems on disks over about 500 GiB....I strongly recommend that you not type `sudo bless --info` to check the status of your installation if you have such a disk, or even if you suspect you might have such a disk. (I've seen Advanced Format disks as small as 320 GB.) > > > Option three is relatively easy. Patching grub is a process with which any early Hackintosh owner is quite familiar. Patching Grub works and is easily undoable as the changes are not made at the firmware level. If you patch grub conservatively, the additional grub code is [only enabled by holding option/alt on boot](https://wiki.archlinux.org/index.php/MacBookPro11,x#Using_the_MacBook.27s_native_EFI_bootloader_.28recommended.29). ### Conclusion If you prefer using your computer to repairing it, Cody Krieger's gfxCardStatus in its out-of-the-box configuration looks more and more attractive. If you really want to force gfxCardStatus to run at start Mr. Krieger has participated in [an illuminating conversation](https://github.com/codykrieger/gfxCardStatus/issues/150), which has led to switchGPU. [switchGPU](https://github.com/joachimroeleveld/switchGPU) presets gfxCardStatus to either discrete or integrated graphics early enough that you can run on integrated graphics when your discrete GPU would otherwise overheat and crash. gfxCardStatus continues to operate normally (i.e. you can switch back to discrete GPU after boot using the gfxCardStatus menu item). There's no reason to install switchGPU unless you have [serious hardware issues](http://www.mbp2011.com/) with your discrete GPU which mean you need to keep it turned off all the time. ### Coda On reflection, my own situation with the integrated AMD 6750 is bad enough (so hot and loud even after thermal repasting) that I will avail myself of Apple's extended [warranty repair program for 2011 MacBook Pro](http://www.apple.com/support/macbookpro-videoissues/) with AMD graphics. Marco Arment was probably right to [turn in his 2011 2.2 GHz MBP with 6750 for the 2.0 GHz version with 6490](https://marco.org/2011/09/20/heat-and-fan-issues-with-2011-15-inch-macbook-pro). While I considered doing the same thing at the time, I would have had to ship my MBP overseas to change it. Sadly the Retina MacBook Pros appear to continue to [suffer the same heat and noise issues](https://marco.org/2011/09/20/heat-and-fan-issues-with-2011-15-inch-macbook-pro). My girlfriend's 2013 MacBook Pro with only integrated graphics behaves much better. Over heat and noise issues with quad core MBP workstations, I've given up and bought two Mac Pros (a 2006 and a 2009), upgraded the CPUs to eight core and six core respectively. The 2006 with Apple AMD 5870 installed is nearly silent (much quieter than the 2009) and multitasks better than the MBP 15". The two silver towers (home and office) cost less combined than a single new MacBook Pro. For now I'm running the 2011 MBP 15" on integrated graphics only as a carry around (no external monitor). --- This solution targets MBP 15" 2014 Retina model. My own interest in disabling the discrete GPU was for a MBP 17" 2011 model. As an important piece of software for me required Mojave, I recently revisited disabling the discrete GPU. gfxCardStatus doesn't work in Mojave (it will show information but not reliably disable the discrete GPU). Setting an NVRAM variable worked (`nvram fa4ce28d-b62f-4c99-9cc3-6815686e30f9:gpu-power-prefs=%01%00%00%00`). An NVRAM variable also [enabled open clamshell mode on a MBP 16"](https://apple.stackexchange.com/a/427956/69259) which I have here for testing. Setting an NVRAM variable seems to be a the best and safest way to solve serious graphic card issues on MacBooks. The full NVRAM solution for the MBP 2011 family was carefully [investigated and documented by Luis Puerto](https://luispuerto.net/blog/2017/12/11/disconnecting-the-dgpu-in-a-late-2011-macbook-pro-third-way/). I've successfully executed this solution. In case Luis's site is down, a [similar post but wordier is on AskDifferent](https://apple.stackexchange.com/a/295805/69259).
46344
I can't select look up field in my SharePoint 2013 List. also I can't filter base on a Look up field. for example I have List with Name Test and this list has fields: Title, Company, Province the Company and Province is look up fields I want to filter based on Province which is a look up field using REST query it gives error: my query: ``` https://TestServer/sites/AIB/OBC/_api/web/lists/getByTitle('Test')/items?$select=Province/Title&$expand=Province&$filter=Province/Title eq 'ABC' ``` it gives error when I put the URL in My browser for testing it gives the blow error: ``` <m:message xml:lang="en-US">The field or property 'Province' does not exist.</m:message> ``` How to filter based on a look up field in SharePoint 2013 REST ?
How to filter by lookup field value using SharePoint REST --------------------------------------------------------- Assume a `Contacts` list that contains a lookup field named `Province` **Option 1** When a lookup column is being added into list, its `ID` become accessible automatically via REST. For example, when the field named `Province` is added into List, `Province Id` could be set or get via `ProvinceId` property of List Item. The following query demonstrate how to filter list items by *lookup field Id* (`Province Id` in our case): ``` /_api/web/lists/GetByTitle('<list title>')/items?$filter=LookupField eq <ProvinceId> ``` where `<ProvinceId>` is a province id **Option 2** In order to filter by *lookup value*, the query should contain `$expand` query option to retrieve projected fields (like `Province Title`). The following example demonstrates how to filter by *lookup field value* (by `Province Title` in our case): ``` /_api/web/lists/GetByTitle('Contacts')/items?$select=Province/Title&$expand=Province&$filter=Province/Title eq <ProvinceTitle> ``` where `<ProvinceTitle>` is a `Title` of Province
46798
I have channels table: ``` +----+-------------------+---------+ | id | sort | bouquet | +----+-------------------+---------+ | 1 | ["1","2","3","4"] | ["1"] | | 2 | ["4"] | ["4"] | +----+-------------------+---------+ ``` And need to remove "2" value from id 1 so i need to get this: ``` +----+-------------------+---------+ | id | sort | bouquet | +----+-------------------+---------+ | 1 | ["1","3","4"] | ["1"] | +----+-------------------+---------+ ``` I try using this query: ``` SELECT id, sort, bouquet, JSON_REMOVE(sort, '$."2"') FROM channels WHERE id=1; ``` But value is not removed if i use '$[2]' then value is removed but i need to remove by value not index...does anyone knows how to remove from json array specific value?
Try: ```sql SELECT `id`, `sort`, `bouquet`, JSON_REMOVE(`sort`, JSON_UNQUOTE( JSON_SEARCH(`sort`, 'one', 2) )) FROM `channels` WHERE `id` = 1; ``` See [db-fiddle](https://www.db-fiddle.com/f/i9Lcw5BTdTtsjgtPHohAMq/3).
47836
The external API that my application is using, sometimes returns no values for one of the float64 fields. When that happens, I cannot unmarshal the rest of the document. Here is the sample code in Go playground: <http://play.golang.org/p/Twv8b6KCtw> ``` package main import ( "encoding/xml" "fmt" ) func main() { type Result struct { XMLName xml.Name `xml:"Person"` Grade float64 `xml:"grade"` Name string `xml:"name"` } data := ` <Person> <grade/> <name>Jack</name> </Person> ` var v Result err := xml.Unmarshal([]byte(data), &v) if err != nil { fmt.Printf("error: %v", err) return } fmt.Printf("name: %s\n", v.Name) } ``` If I change float64 in line 12 to string, it will work. Any idea how I can get a workaround for this? Should I just define every field as string and do the conversion manually?
Is this what you are looking for? ``` SELECT DATEDIFF(`pro_masastr`, NOW()) as DiffDate FROM `i2n_profiler_users` WHERE `userid` = 725; ``` This is no need for the additional subquery. Note thate `datediff()` is `expr1 - expr2`, so you might want the arguments in the other order: ``` SELECT DATEDIFF(now(), `pro_masastr`) as DiffDate FROM `i2n_profiler_users` WHERE `userid` = 725; ```
47845
Can anyone tell me how to solve these things? 1.if the list is pressed, I'd like to change the background color of the list beige(#FFF5E7) to white(#FBFBFB) 2.Also, I'd like to change the read value of the Object fales to true with useState Problem is that if I pressed the list, whole background color of the list will be changed. index.tsx ``` import React, { useState } from 'react'; import { Text, View, TouchableOpacity, FlatList } from 'react-native'; import { useNavigation } from '@react-navigation/native'; import { DETAIL } from '../../sample'; import { Object } from './sample'; export default function sample() { const [state, setState] = useState(Object); const navigation = useNavigation(); let Element; const renderItem = ({ item }) => { const readState = () => { navigation.navigate(NOTICE_DETAIL); const readValue = [...state]; let value = { ...readValue[0] }; value.read = true; readValue[0] = value; setState(readValue); }; if (state[0].read) { Element = ( <TouchableOpacity onPress={readState}> <View style={[styles.row, { backgroundColor: '#FBFBFB' }]}> <View style={styles.container}> <View style={styles.end}> <Text style={styles.text}>{item.text}</Text> <Text style={styles.time}>{item.time}</Text> </View> <Text style={styles.content}>{item.content}</Text> </View> </View> </TouchableOpacity> ); } else { Element = ( <TouchableOpacity onPress={readState}> <View style={[styles.row, { backgroundColor: '#FFF5E7' }]}> <View style={styles.container}> <View style={styles.end}> <Text style={styles.text}>{item.text}</Text> <Text style={styles.time}>{item.time}</Text> </View> <Text style={styles.content}>{item.content}</Text> </View> </View> </TouchableOpacity> ); } return Element; }; } return ( <View style={{ flex: 1 }}> <FlatList extraData={Object} data={Object} renderItem={renderItem} /> </View> ); } ``` Object.ts ``` export const Object = [ { id: 1, text: 'testtesttest', content: 'testtesttest' read: false }, { id: 2, text: 'testtesttest', content: 'testtesttest' read: false } id: 3, text: 'testtesttest', content: 'testtesttest' read: false } ] ```
One way using `heapq.nlargest`: ``` from heapq import nlargest df["col2"] = df["col2"].apply(lambda x: nlargest(2, x, key=d.get)) print(df) ``` Output: ``` col1 col2 0 A [x, y] 1 B [z] 2 C [q, p] 3 D [q, t] ```
47860
I want to do parser, which will print out expressions into steps of their calculation. And when I compile my code, I cannot solve these problem. I always get error ``` code.l:13:1: error: expected expression before '=' token yylval.name = strdup(yytext); ^ code.l:18:1: error: expected expression before '=' token yylval.name = strdup(yytext); ^ ``` I tried a lot of different things, what I thought were a problem, but was unsuccessful. code.l ```c %{ #include <stdio.h> #include <string.h> #include "Assignment.tab.h" %} %% " " ; "\t" ; [a-zA-Z]+ { yylval.name = strdup(yytext); return(ID); } [0-9]+ { yylval.name = strdup(yytext); return(NUM); } [-+=()*/\n] { return yytext[0]; } . { yyerror("unknown character"); } %% ``` code.y ```c %{ #include<stdio.h> int temp = 0; %} %start list %union { char *name; } %token <name> ID %token <name> NUM %type <name> list stat expr %left '+' '-' %left '*' '/' %left UMINUS %% list: | list stat '\n' | list error '\n' { yyerrok; } ; stat: expr { printf("stat:t = (%s)\n:stat",$1); } | ID '=' expr { printf("stat:(%s) = (%s):stat", $1, $3); } ; expr: '(' expr ')' { $$ = $2; } | expr '*' expr { printf("t = (%s) * (%s)", $1, $3); $$ = "t"; } | expr '/' expr { printf("t = (%s) / (%s)", $1, $3); $$ = "t"; } | expr '+' expr { printf("t = (%s) + (%s)", $1, $3); $$ = "t"; } | expr '-' expr { printf("t = (%s) - (%s)", $1, $3); $$ = "t"; } | '-' expr %prec UMINUS { printf("t = -(%s)", $2); $$ = "t"; } | ID { $$ = $1; } | NUM { $$ = $1; } ; %% main() { return(yyparse()); } yyerror(s) char *s; { fprintf(stderr, "%s\n",s); } yywrap() { return(1); } ``` I do not need solution for my end project, I just need to find what is causing the error. Any idea is helpful. EDIT: Assignment.tab.h file ```c #ifndef YY_YY_ASSIGNMENT_TAB_H_INCLUDED # define YY_YY_ASSIGNMENT_TAB_H_INCLUDED /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { ID = 258, NUM = 259, UMINUS = 260 }; #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE { /* Line 2058 of yacc.c */ #line 10 "Assignment.y" char *name; /* Line 2058 of yacc.c */ #line 67 "Assignment.tab.h" } YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 #endif extern YYSTYPE yylval; #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (void); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ #endif /* !YY_YY_ASSIGNMENT_TAB_H_INCLUDED */ ```
The action in a lex rule must start on the same line as the pattern. So you need to write, for example ``` [a-zA-Z]+ { yylval.name = strdup(yytext); return(ID); } ``` For what it's worth, this requirement is clearly stated in the [flex manual section on the format of an input file](http://westes.github.io/flex/manual/Rules-Section.html): > > The rules section of the flex input contains a series of rules of the form: > > > > ``` > pattern action > > ``` > > where the pattern must be unindented and the action must begin on the same line. > > > This restriction is, as far as I know, present in all lex implementations, although the consequences differ. I quoted the Flex manual because I find it to be more readable than the Posix description, and it also describes the many useful flex-only features.
47881
My conection string was ``` string connStr = @"Data Source=(local)\SQLEXPRESS Initial Catalog=University11; Integrated Security=True"; ``` But then I copied my database to ``` C:\Users\Чак\Desktop\ботанизм\ООП\coursework.start\CourseWorkFinal\CourseWorkFinal\ ``` And set it as the way in connection string ``` string connStr = @"Data Source=C:\Users\Чак\Desktop\ботанизм\ООП\coursework.start\CourseWorkFinal\CourseWorkFinal\; Initial Catalog=University11; Integrated Security=True"; ``` But in that case I had an exception ``` A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) ``` What correct connection string do I need?
The connection string (`Data Source=(local)\SQLEXPRESS`...) is intended for hiding the physical location of the database files when you decide to move files. No matter where your files are, the programs that use your database should not care, because logically it's the same database. When you move your DB files, you need to re-point your SQL Express database to the new location, and keep the connection string intact.
49099
So my htaccess lines look like this: ``` RewriteRule ^meniu/([a-zA-Z0-9]+)/$ produse.php?categorie=$1 RewriteRule ^meniu/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/$ produse.php?categorie=$1&produs=$2 ``` * www.mysite.com/meniu/pizza/ works * www.mysite.com/meniu/pizza/Quatro\_Formaggi/ **doesn't** work, it displays 404 not found.
Your URL has the `underscore` character `www.mysite.com/meniu/pizza/Quatro_Formaggi/` so just add the `_` to the `RewriteRule` to match it ``` RewriteRule ^meniu/([a-zA-Z0-9]+)/$ produse.php?categorie=$1 RewriteRule ^meniu/([a-zA-Z0-9]+)/([a-zA-Z0-9_]+)/$ produse.php?categorie=$1&produs=$2 ```
49171
I am currently using Python to create a program that accepts user input for a two digit number and will output the numbers on a single line. For Example: My program will get a number from the user, lets just use 27 I want my program to be able to print "The first digit is 2" and "The second digit is 7" I know I will have to use modules (%) but I am new to this and a little confused!
Try this: ``` val = raw_input("Type your number please: ") for i, x in enumerate(val, 1): print "#{0} digit is {1}".format(i, x) ```
51074
So I'm new to MVC4 and C#, I have been designing this website for about 2 weeks now and there have not been any issues with the intelisense. For 2 days now Visual studio is telling me that @Viewbag and other @ commands are not part of my project and i may be missing something or it tells me that Viewbag doesn't exist in the current context. I'm unsure how to fix this ( i have restarted the project and the machine im working on ) still showing up underlined and tells me it doesn't exists in the context Since I'm still new when i look / try new code this is very difficult since *everything* is wrong.. > > Example Images : > > > ![enter image description here](https://i.stack.imgur.com/o8d42.png) ![enter image description here](https://i.stack.imgur.com/juvau.png) ![enter image description here](https://i.stack.imgur.com/ZUXUf.png) ![enter image description here](https://i.stack.imgur.com/6DR6y.png) The long error you can barely read states that > > System.Web.WebPages.Html.htmlHelper' does not contain a definition for 'Actionlink' .... missing assembly reference ? > > > I get this error for any @codes in the Razor view aswell exept C# @'s > > WebConfig File > > > ``` <?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings> <add name="DefaultConnection" connectionString="Server=ANE-SQL\ANESQLSERVER;Database=OilGas;User Id=software;Password=GLvp$102;" providerName="System.Data.SqlClient" /> </connectionStrings> <appSettings> <add key="webpages:Version" value="2.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="PreserveLoginUrl" value="true" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <system.web> <customErrors mode="RemoteOnly"></customErrors> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="180" /> </authentication> <pages> <namespaces> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Optimization" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> </namespaces> </pages> </system.web> <system.webServer> <!--<modules runAllManagedModulesForAllRequests="true" />--> <validation validateIntegratedModeConfiguration="false" /> <handlers> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" /> <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" /> <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.3.0.0" newVersion="1.3.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters> <parameter value="v11.0" /> </parameters> </defaultConnectionFactory> </entityFramework> </configuration> ```
Make sure you have specified the Razor version you are using in the `appSettings` of your web.config: ``` <appSettings> <add key="webpages:Version" value="2.0.0.0" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> ``` Also make sure that your views are in their standard locations (a.k.a. the `~/Views` folder).
51479
I am trying to check a condition using the logical or operator and seems like I am doing that wrong. It works of course if it is just 1, but when I add other values it seems to be incorrect as in below. How do I make this work to check if it's more than one. Does something go in quotes instead? ```js if (data.Items.find((item) => item.OrgUnit?.Id === (parseInt(match))).Role.Id === 110 || 120 || 130 || 140) { alert = "test" } ```
You can't compare against multiple values like that. You could use `Array#includes` instead. ``` if([110 , 120 , 130 ,140].includes(data.Items.find((item) => item.OrgUnit?.Id === (parseInt(match))).Role.Id)){ } ```
51908
I have 2 `DropDownList`s with same contents (i.e. finance, marketing, promotion). I want to remove already-selected values from the rest of the list. Example: If I select "finance" for the 1st list, it should be removed on other list; the 2nd list should only display "marketing" and "promotion". However, the current code still display all values on other list when whatever value is selected on the 1st one. **ASP.NET Page** ``` <asp:DataList ID="dldepart" runat="server" RepeatDirection="Horizontal" RepeatColumns="4" Height="343px" Width="1572px" onitemdatabound="dldepart_ItemDataBound"> <ItemTemplate> <asp:DropDownList ID="ddlist" runat="server" AutoPostBack="true" onselectedindexchanged="ddlist_SelectedIndexChanged"> </asp:DropDownList> <asp:CheckBoxList ID="CheckBoxList1" runat="server"> </asp:CheckBoxList> </ItemTemplate> </asp:DataList> ``` **ASP.NET C# Code** ``` private void BindCheckBoxList() { DataSet ds = new DataSet(); DataTable dt = new DataTable(); SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\database\personal.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); try { con.Open(); SqlCommand Cmd = new SqlCommand("SELECT distinct depart FROM datalist", con); SqlDataAdapter Da = new SqlDataAdapter(Cmd); Da.Fill(dt); if (dt.Rows.Count > 0) { dldepart.DataSource = dt; dldepart.DataBind(); } } catch (System.Data.SqlClient.SqlException ex) { string msg = "Fetch Error:"; msg += ex.Message; throw new Exception(msg); } finally { con.Close(); } } protected void dldepart_ItemDataBound(object sender, DataListItemEventArgs e) { DropDownList ddlist = (DropDownList)e.Item.FindControl("ddlist"); DataSet ds = new DataSet(); DataTable dt = new DataTable(); SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\database\personal.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); try { con.Open(); SqlCommand Cmd = new SqlCommand("SELECT distinct depart FROM datalist", con); SqlDataAdapter Da = new SqlDataAdapter(Cmd); /**codes that i used to repeat datalist **/ Da.Fill(dt); if (dt.Rows.Count > 0) { ddlist.DataSource=dt; ddlist.DataTextField="depart"; ddlist.DataValueField="depart"; ddlist.DataBind(); ddlist.Items.Insert(0, "Select"); ddlist.Items.FindByText("Select").Value = Convert.ToString(0); } } catch (System.Data.SqlClient.SqlException ex) { } finally { con.Close(); } } ``` **On SelectedIndexChange** ``` protected void ddlist_SelectedIndexChanged(object sender, EventArgs e) { DataListItem dlitem = (DataListItem)((DropDownList)sender).Parent; CheckBoxList CheckBoxList1 = (CheckBoxList)dlitem.FindControl("CheckBoxList1"); DropDownList ddlist = (DropDownList)dlitem.FindControl("ddlist"); // DataBoundControl DataSource = (DataBind)dldepart.FindControl("DataSource"); DataSet ds = new DataSet(); DataTable dt = new DataTable(); SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\database\personal.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); try { con.Open(); SqlCommand Cmd = new SqlCommand("SELECT Id,subDepatment FROM datalist where depart='" + ddlist.SelectedItem.Text + "'", con); SqlDataAdapter Da = new SqlDataAdapter(Cmd); Da.Fill(dt); if (dt.Rows.Count > 0) { CheckBoxList1.DataSource = dt; CheckBoxList1.DataTextField = "subDepatment"; // the items to be displayed in the list items CheckBoxList1.DataValueField = "Id"; // the id of the items displayed CheckBoxList1.DataBind(); } } catch (System.Data.SqlClient.SqlException ex) { } finally { con.Close(); } } ```
You have a several syntax error in your code. Maybe this is not an answer, but for code formatting, I need to be use the answer box. There is an unopened `*/` after ``` $this->db->join('job_title jt', 'j.job_title = jt.id', 'INNER'); ``` You are closing the string here: ``` $this->db->select('e.fname,e.lname,e.nik,e.id, jt.name AS jabatan, ar.nik, ar.nilai', ``` so there will be syntax error too. You have error in your sql, there is an unnecessary `,` at the end of your first query, and the quotes are wrong also: ``` $this->db->select("e.fname,e.lname,e.nik,e.id, jt.name AS jabatan, ar.nik, ar.nilai, DATEPART (year, 'ar.tanggal') AS 'ar.tahun', DATEPART(month, 'ar.tanggal') AS 'ar.bulan', DATEPART(year, 'es.date_nilai') AS 'es.tahun'"); ``` And you need to wrap your conditions at here: ``` $this->db->where("('ar.tahun', 'es.tahun') && ('ar.bulan', 'es.bulan')"); ```
52115
I am setting a `TextBox` controls value via an ajax post. ``` $('#txtSite').val(msg.d.SiteName); ``` This is working and the value of the `TextBox` is altered correctly. But, when I come to posting the information to the database, the `txtSite.Text` value is empty!! Any ideas? Am I going mad? Code to populate the `TextBox`: ``` $.ajax({ type:"POST", url: "MyPage.aspx/ValidateSite", data: "{ siteID: '" + $('#txtSiteID').val() + "' }", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { if (msg.d != null) { $('#txtSite').val(msg.d.SiteName); // It's definitely doing this } else { $('#txtSite').val(''); } }, error: function(msg) { } }); ``` Code to save to the server (all connectivity etc. is correct and working). This code is in an ASP button click event: ``` SqlCommand cmd = new SqlCommand("INSERT INTO [Sites] ([SiteName]) VALUES ('" + txtSite.Text + "')", conn); cmd.ExecuteNonQuery(); ``` The `TextBox` is defined like so: ``` <asp:TextBox ID="txtSite" runat="server" AutoComplete="off" TabIndex="4" MaxLength="50" Style="width: 230px" Enabled="false" CssClass="FormDisabledTextWithSmallHeight" /> ``` I have also tried changing my JQuery to use plain Javascript instead and doing this: ``` document.getElementById("txtSite").value = msg.d.SiteName; ``` Still returns me an empty value.
You have your textbox set to `Enabled="false"` which renders in the browser with a `disabled="disabled"`. **[Disabled form inputs are not submitted.](http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlcontrol.disabled.aspx)** The solution is either to make the textbox enabled and read-only: ``` txtSite.Enabled = true; txtSite.Attributes.Add("readonly", "readonly"); //on prerender event or somewhere else ``` or to use a different element set with `runat="server"`, like a `<asp:HiddenField />` and update both the textbox and the alternate element with your AJAX call: ``` success: function(msg) { if (msg.d != null) { $('#txtSite').val(msg.d.SiteName); $('#hiddenInput').val(msg.d.SiteName); } else { $('#txtSite').val(''); } } ```
52550
Hi i am getting a null pointer exception while running my application.. Here is my code : ProductAdapter.java ``` public class ProductAdapter extends BaseAdapter { Context context; List<Product> products = new ArrayList<Product>(); private boolean showCheckbox; public ProductAdapter(Context context, List<Product> products, boolean showCheckbox) { super(); this.context = context; this.products = products; this.showCheckbox = showCheckbox; } @Override public int getCount() { // TODO Auto-generated method stub return products.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return products.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null){ LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.new_item, null); } Product myProduct = products.get(position); TextView title = (TextView) convertView.findViewById(R.id.txt_title); title.setText(myProduct.getTitle()); TextView cost = (TextView) convertView.findViewById(R.id.txt_cost); cost.setText(myProduct.getCost()); ImageView image = (ImageView) convertView.findViewById(R.id.imageView1); CheckBox selectBox = (CheckBox) convertView.findViewById(R.id.CheckBoxSelect1); if(!showCheckbox){ selectBox.setVisibility(View.GONE); } else{ if(myProduct.selected == true) selectBox.setChecked(true); else selectBox.setChecked(false); } return convertView; } } ``` Here is my layout xml file new\_item.xml ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/txt_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/txt_cost" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> <CheckBox android:id="@+id/CheckBoxSelect1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> ``` Here i am getting a nullpointer exception please help me out. Here is my logcat. ``` 09-26 16:37:23.894: D/AndroidRuntime(2611): Shutting down VM 09-26 16:37:23.894: W/dalvikvm(2611): threadid=1: thread exiting with uncaught exception (group=0x409951f8) 09-26 16:37:23.904: E/AndroidRuntime(2611): FATAL EXCEPTION: main 09-26 16:37:23.904: E/AndroidRuntime(2611): java.lang.NullPointerException 09-26 16:37:23.904: E/AndroidRuntime(2611): at com.shoppingcart.ProductAdapter.getView(ProductAdapter.java:59) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.AbsListView.obtainView(AbsListView.java:2033) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.ListView.makeAndAddView(ListView.java:1772) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.ListView.fillDown(ListView.java:672) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.ListView.fillFromTop(ListView.java:732) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.ListView.layoutChildren(ListView.java:1625) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.AbsListView.onLayout(AbsListView.java:1863) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.View.layout(View.java:11158) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.ViewGroup.layout(ViewGroup.java:4197) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1628) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1486) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.LinearLayout.onLayout(LinearLayout.java:1399) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.View.layout(View.java:11158) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.ViewGroup.layout(ViewGroup.java:4197) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.FrameLayout.onLayout(FrameLayout.java:431) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.View.layout(View.java:11158) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.ViewGroup.layout(ViewGroup.java:4197) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1628) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1486) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.LinearLayout.onLayout(LinearLayout.java:1399) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.View.layout(View.java:11158) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.ViewGroup.layout(ViewGroup.java:4197) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.widget.FrameLayout.onLayout(FrameLayout.java:431) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.View.layout(View.java:11158) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.ViewGroup.layout(ViewGroup.java:4197) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1462) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2382) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.os.Handler.dispatchMessage(Handler.java:99) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.os.Looper.loop(Looper.java:137) 09-26 16:37:23.904: E/AndroidRuntime(2611): at android.app.ActivityThread.main(ActivityThread.java:4340) 09-26 16:37:23.904: E/AndroidRuntime(2611): at java.lang.reflect.Method.invokeNative(Native Method) 09-26 16:37:23.904: E/AndroidRuntime(2611): at java.lang.reflect.Method.invoke(Method.java:511) 09-26 16:37:23.904: E/AndroidRuntime(2611): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 09-26 16:37:23.904: E/AndroidRuntime(2611): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 09-26 16:37:23.904: E/AndroidRuntime(2611): at dalvik.system.NativeStart.main(Native Method) ``` Thank You. here is my Logcat. ``` 09-26 16:58:35.205: D/AndroidRuntime(2749): Shutting down VM 09-26 16:58:35.205: W/dalvikvm(2749): threadid=1: thread exiting with uncaught exception (group=0x409951f8) 09-26 16:58:35.225: E/AndroidRuntime(2749): FATAL EXCEPTION: main 09-26 16:58:35.225: E/AndroidRuntime(2749): java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.ImageView 09-26 16:58:35.225: E/AndroidRuntime(2749): at com.shoppingcart.ProductAdapter.getView(ProductAdapter.java:66) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.AbsListView.obtainView(AbsListView.java:2033) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.ListView.makeAndAddView(ListView.java:1772) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.ListView.fillDown(ListView.java:672) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.ListView.fillFromTop(ListView.java:732) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.ListView.layoutChildren(ListView.java:1625) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.AbsListView.onLayout(AbsListView.java:1863) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.View.layout(View.java:11158) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.ViewGroup.layout(ViewGroup.java:4197) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1628) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1486) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.LinearLayout.onLayout(LinearLayout.java:1399) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.View.layout(View.java:11158) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.ViewGroup.layout(ViewGroup.java:4197) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.FrameLayout.onLayout(FrameLayout.java:431) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.View.layout(View.java:11158) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.ViewGroup.layout(ViewGroup.java:4197) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1628) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1486) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.LinearLayout.onLayout(LinearLayout.java:1399) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.View.layout(View.java:11158) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.ViewGroup.layout(ViewGroup.java:4197) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.widget.FrameLayout.onLayout(FrameLayout.java:431) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.View.layout(View.java:11158) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.ViewGroup.layout(ViewGroup.java:4197) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1462) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2382) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.os.Handler.dispatchMessage(Handler.java:99) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.os.Looper.loop(Looper.java:137) 09-26 16:58:35.225: E/AndroidRuntime(2749): at android.app.ActivityThread.main(ActivityThread.java:4340) 09-26 16:58:35.225: E/AndroidRuntime(2749): at java.lang.reflect.Method.invokeNative(Native Method) 09-26 16:58:35.225: E/AndroidRuntime(2749): at java.lang.reflect.Method.invoke(Method.java:511) 09-26 16:58:35.225: E/AndroidRuntime(2749): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 09-26 16:58:35.225: E/AndroidRuntime(2749): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 09-26 16:58:35.225: E/AndroidRuntime(2749): at dalvik.system.NativeStart.main(Native Method) ```
There's some more documentation on the CHM format here: <http://www.russotto.net/chm/chmformat.html> which might help you to write your own decoding code if you're not willing to use a library to do it. Alternatively, there are plenty of freely downloadable decoders that will convert CHM back to HTML - have you considered decoding offline and simply including the decoded files in your application?
52612
So today I opened my email and found another email from a recruiter who clearly did not look at my resume or any details about me. Here is the email (with [PII](https://en.wikipedia.org/wiki/Personal_data) removed): > > Hi, > > > My name is [redacted], I’m a Technical Recruiter for [redacted]. I’m > reaching out because, I believe your professional experience and > background is a great fit for a Sr. Business Analyst role I currently > have open with a Fortune financial institution in [redacted]. The > client is looking to fill this position as soon as possible, I look > forward to hearing from you! > > > We do offer a $500 dollar cash referral bonus for anyone you refer who > gets the job, if you’re not interested yourself! > > > Best Regards, [redacted] > > > So the position is for a Senior Business Analyst for a "Fortune financial institution". I've seen many variations on this -- Fortune 500, Fortune 100, Fortune 50 -- but never just a "Fortune" company. So if the recruiter had actually looked at my resume or whatever profile he found from whatever job website I'm on, he would see that I briefly held a 6-month contract Business Analyst position as a trainee, not even as a full fledged BA. This was in 2015, and I haven't held any further Business Analyst positions since then. Clearly, I am not going to be qualified for a Senior Business Analyst position. I receive many emails like this where it is obvious that the recruiter is just spamming the position to as many people as possible in case something sticks. **But my question is, what is the best method for reacting to this sort of email from a recruiter who has not reviewed my profile or resume?** I am not interested in even attempting to apply for the position, and I'm fairly new to the area (moved here at the end of the aforementioned BA contract), so I wouldn't have any referrals either. I've typically just ignored these emails, but should I be responding in some way to preserve some semblance of a professional relationship for future job searches? @MonkeyZeus Thanks for the dupe target, but I would say this is different enough to remain independent. That link is about the same recruiter sending multiple emails about the same job, whereas this question is about receiving large amounts of recruiter emails from multiple recruiters and companies for positions that are not well-suited for the intended email recipient. I believe this question has received a strong amount of good answers enough that it can be helpful for others -- even expanding beyond the intended focus of US workers.
Ignore it, unfortunately it's par for the course when looking for jobs or signing up to recruitment websites. If you respond to them negatively then you run the risk of them not contacting you in the future even for relevant positions.
52891
I have an Android game that uses the Libgdx game engine. I have an Android activity (mAndroidLauncher) that extends Libgdx's AndroidApplication class. There is a method that creates an Android alert dialog: ``` mAndroidLauncher.runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(mAndroidLauncher.getContext()); builder.setTitle("Notice"); builder.setMessage("Alert!!!"); builder.setNeutralButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //OK } }); AlertDialog dialog = builder.create(); dialog.show(); } }); ``` I have a crash in the Google Play Developer Console as follows: ``` java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() at android.os.Handler.<init>(Handler.java:208) at android.os.Handler.<init>(Handler.java:122) at android.app.Dialog.<init>(Dialog.java:109) at android.app.AlertDialog.<init>(AlertDialog.java:114) at android.app.AlertDialog$Builder.create(AlertDialog.java:931) at com.google.android.gms.common.e.a(Unknown Source) at com.google.android.gms.common.e.a(Unknown Source) at com.my.game.l.a(Unknown Source) at com.my.game.l.g(Unknown Source) at com.my.game.l.c(Unknown Source) at com.my.game.a.b(Unknown Source) at com.my.game.b.f.a(Unknown Source) at com.my.game.q.b(Unknown Source) at com.badlogic.gdx.backends.android.i.onDrawFrame(Unknown Source) at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1557) at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1263) ``` This is the only place in my app that I use an AlertDialog, that is why I am confident that this is the method that is causing the crash. Why would runOnUiThread cause this error? Do I need to do anything else to make sure the AlertDialog is built from a thread with a looper? EDIT: Thanks CommonsWare. The error is indeed coming from Google Play Services. Specifically I had a call to gameHelper.beginUserInitiatedSignIn() which was not wrapped in runOnUiThread(). Although, strangely, this didn't cause an error for all phones
It looks like [this](https://sqa.stackexchange.com/questions/10450/selenium-sendkeys-not-completing-data-entry-before-moving-to-next-field) is a common issue. Before trying the workarounds, as a sanity check, make sure that the input field is ready to receive input by the time you are sending keys. You could also try clearing the field before calling SendKeys. I am assuming that you are seeing your string truncated, and not characters missing or being prefixed with some artifact (like placeholder text or leftover input from a previous test). Some workarounds if that didn't work: 1. Set the value of the input field using JavaScript, instead of calling SetKeys. On some websites where I do this, the input value actually won't be recognized unless I also trigger an input changed event. Example in C#. Hopefully, the only change you need is to make ExecuteScript be executeScript instead. ``` driver.ExecuteScript("var exampleInput = document.getElementById('exampleInput'); exampleInput.value = '" + testInputValue + "'; exampleInput.dispatchEvent(new Event('change'));"); ``` You could, of course, split this up into two lines, one to set the value, and the second to dispatch the event. 2. Send each key individually. This is a workaround I've seen a couple of times from the threads about this issue. ``` for (var i = 0; i < first_name.length; i++) { name_field.sendKeys(first_name.charAt(i)); } ``` <https://github.com/angular/protractor/issues/3196> <https://github.com/angular/protractor/issues/2019> etc. etc. More threads can be found by a simple search of "webdriver sendkeys does not wait for all the keys" if you want to look for other possible solutions to your issue.
53902
Does anyone have any advice on how one might georeference/orthorectify oblique imagery taken over the open ocean from a manned aircraft? The aircraft will have an RTK-enabled GNSS/INS onboard. I was thinking we could use the timestamps to link the position of the aircraft with the imagery. However, this is only one piece of the puzzle, as we would need to stretch the image to fit it into its position on the ground. Since we will know the position, heading and height of the aircraft and the angle at which the images are being taken, surely we have all the information we need, but how would it work in practice?
Orthorectification consists of two image adjustments corresponding to the sensor model and the terrain relief. Over the ocean you should be able to ignore the latter because the ocean is defined as 'sea level' so ellipsoidal height is sufficient. [OSSIM has a utility](https://trac.osgeo.org/ossim/wiki/orthorectification) to produce orthos which allows for ignoring DTM elevation relief, so with the right inputs this should be able to create orthos over the ocean. Two issues will be: * creating a sensor model to supply the correct inputs, and * validating the orthophoto mosaic results
54021
i have some code that sets user's properties like so: ``` us = new UserSession(); us.EmailAddr = emailAddr; us.FullName = fullName; us.UserROB = GetUserROB(uprUserName); us.UserID = GetUserID(uprUserName); us.UserActive = GetUserActive(uprUserName); ``` where `GetUserROB`, `GetUserID` and `GetUserActive` all look similar like so: ``` private static string GetUserActive(string userName) { using (Entities ctx = CommonSERT.GetContext()) { var result = (from ur in ctx.datUserRoles where ur.AccountName.Equals(userName, StringComparison.CurrentCultureIgnoreCase) select new { Active = ur.active }).FirstOrDefault(); if (result != null) return result.Active; else return "N"; } } ``` it works, but i dont think it's the right way here. how can i assign userROB, ID and Active properties all in one LINQ call? without having to have 3 separate functions to do this?
You can create a method that accepts a `UserSession` object as parameter, then set all three properties in it. I changed your `GetUserActive` a bit here: ``` private static void GetUserData(string userName, UserSession user) { using (Entities ctx = CommonSERT.GetContext()) { var result = (from ur in ctx.datUserRoles where ur.AccountName.Equals(userName, StringComparison.CurrentCultureIgnoreCase) select new { Active = ur.active, ID = ur.ID, //...select all properties from the DB }).FirstOrDefault(); if (result != null) user.UserActive = result.Active; user.UserID = result.ID; //..set all properties of "user" object } } ```
54130
I have built Boost in Release configuration and have staged it into one folder. Now when I add Boost libraries into project and try to build it in Debug configuration - linker fails because there are no Debug versions libraries. Is there a way to make MSVC 9.0 use Release version of libraries when building Debug configuration? Of course, there is an easy soultion - build Debug version of Boost. But I am just curious.
You can do two things: * Build the debug version for boost (this is the best option). * Add debugging symbols to your release build. You can't use the release version of boost with your debug build because boost depends on the CRT, which is different in debug/release builds.
54255
I keep getting an "invalid syntax" notification around `room105` ``` *room15 = room("Check out the lab") room15.setDescription("You look around the lab. You find nothing of importance, really." room105 = room("Continue to look around") room105.setDescription("You still don't find anything.") room16 = room("Go back up trapdoor and into the sweet room") room16.setDescription("You go up the ladder and into the room, only to find... The leader! He becomes startled, and begins to come at you!") room106 = room("Talk to him") room106.setDescription("you attempt to speak with the leader, but he comes at you too fast, and kills you. GAME OVER.") room106.setFunction(lambda: lockroom (room16))* ``` I'm trying to make a text adventure. When I tested it before, it worked perfectly, now, as soon as I put in the `room105` bit, I'm getting a bunch of errors.
``` *room15 = room("Check out the lab") room15.setDescription("You look around the lab. You find nothing of importance, really." room105 = room("Continue to look around") ``` You are missing a closing parenthesis on the second line.
54447
I am quite a newbie with wpf...any help will be appreciated. I started a small project with a listview that displays content from MySQL. So far I had no problems except a column that has 2 items in it. I need to **separate each item in its own column.** It was easy to do with date and time but this one is beyond my skills. The display of the listview is like that (I can't post images yet): **Date |Time |CallerID |From|To |Duration** **10 June 2015 |22:45|"alex" <210555555>|101 |201|234** The `CallerID` column contains the two values with distinct "" and <>. I need to separate as I did with `Date` and `Time`. Thanks for any help. ``` <ListView x:Name="Datalist" Grid.Column="1" Grid.Row="4" ItemsSource="{Binding Path=DS}" Background="White" Foreground="Black" FontSize="16" Grid.ColumnSpan="4" FontFamily="Segoe UI" Margin="1,0,8,0"> <ListView.View> <GridView AllowsColumnReorder="False"> <GridViewColumn Header="Date" DisplayMemberBinding="{Binding Path=calldate,StringFormat={}{0:dd MMMM yyyy}}"/> <GridViewColumn Header="Time" DisplayMemberBinding="{Binding Path=calldate,StringFormat={}{0:HH:mm:ss}}"/> <GridViewColumn Header="CallerID" DisplayMemberBinding="{Binding Path=clid}"/> <GridViewColumn Header="From" DisplayMemberBinding="{Binding Path=src}"/> <GridViewColumn Header="To" DisplayMemberBinding="{Binding Path=dst}"/> <GridViewColumn Header="Duration" DisplayMemberBinding="{Binding duration}" /> </GridView> </ListView.View> </ListView> private void OnLoad(object sender, RoutedEventArgs e) { string cs = @"server=192.168.1.123;userid=alex; password=r3s3ll3r;database=asteriskcdrdb"; MySqlConnection conn = null; MySqlDataReader rdr = null; try { conn = new MySqlConnection(cs); conn.Open(); string stm = "(SELECT * FROM cdr ORDER BY uniqueid DESC LIMIT 1000)"; mySqlDataAdapter = new MySqlDataAdapter(stm, cs); mySqlDataAdapter.Fill(DS); Datalist.ItemsSource = DS.DefaultView; } catch (MySqlException ex) { MessageBox.Show("Error: {0}", ex.ToString()); } finally { if (rdr != null) { rdr.Close(); } if (conn != null) { conn.Close(); } } } ```
Something like this might work if you want the horizontal column ordering reversed: ``` <div class="row"> <div class="col-xs-5 col-sm-push-7"> This should show on right </div> <div class="col-xs-7 col-sm-pull-5"> This should show on left </div> </div> ``` Here is a [JSFiddle demo](http://jsfiddle.net/cpdrdehg/).
54807
I am using `OAuth 2.0` for authorization according to this documentation :(<https://developers.vendhq.com/documentation/oauth.html#oauth>) and having this error: > > "error": "invalid\_request", "error\_description": "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"grant\_type\" parameter." > > > **Request** Method : **POST** ``` Content-Type: application/x-www-form-urlencoded URL : https://{domain_prefix}.vendhq.com/api/1.0/token ``` **Parameters :** ``` code = {code} client_id = {app_id} client_secret = {app_secret} grant_type = authorization_code redirect_uri = {redirect_uri} ```
As per the [RFC6749, section 4.1.3](https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3), the encoded body of a POST request should look like `code={code}&client_id={app_id}&client_secret={app_secret}&grant_type=authorization_code&redirect_uri={redirect_uri}`. Example: > > grant\_type=authorization\_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect\_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb&client\_id=CLIENT\_ID\_1234&client\_secret=CLIENT\_SECRET > > > Do not forget to encode the redirect Uri: `http://foo.bar/` => `http%3A%2F%2Ffoo.bar%2F` Concerning the authentication error, it may be because the authorization server do not support client secret in post request (or your client is not allowed to use it). Then try to add the Authorization header with basic authentication scheme. The value of this header is `Basic {ENCODED_AUTHENTICATION}` with `{ENCODED_AUTHENTICATION} =base64(client_id + ':' + client_secret)` With this header, the `client_id` and `client_secret` in the post request have to be removed. Your request parameters become `code={code}&grant_type=authorization_code&redirect_uri={redirect_uri}`.
54836
See comments for question. Remove N elements selectively (Condition is that list element matches 'remove') ``` List<String> mylist = new ArrayList<>(); mylist.add("remove"); mylist.add("all"); mylist.add("remove"); mylist.add("remove"); mylist.add("good"); mylist.add("remove"); // Remove first X "remove". // if X is 2, then result list should be "all, remove, good, remove" // Use java 8 features only, possibly single line code. // Please don't answer with looping, iterating, if conditions etc. // Answer should use JDK 8 new features. ```
How about this: ``` List<String> filter(List<String> mylist, int x){ AtomicInteger index = new AtomicInteger(0); mylist.removeIf(p -> p.equals("remove") && index.getAndIncrement() < x); return myList; } ``` With x=0, it prints: > > [remove, all, remove, remove, good, remove] > > > With x=1, it prints: > > [all, remove, remove, good, remove] > > > With x=2, it prints: > > [all, remove, good, remove] > > > With x=3, it prints: > > [all, good, remove] > > >
54956
I am designing a threaded message display for a PHP/MySQL application - like comments on Slashdot or Youtube - and am wondering how I should go about ordering the comments and separating it into pages so that you can have, say, 20 comments to a page but still have them nested. Comments in my app can be nested unlimited levels, and this structure is represented using what I believe is an Adjacency Relation table, a separate table containing a row for each pair that has any ascendent/descendent relationship. That relationship table has CHILDID, PARENTID and LEVEL where a level of 2 means "great-grandparent", and so on. My question is one of both usability for the end user, and of practicality of constructing an efficient DB query. I have considered these options: * Splitting results into pages by date, regardless of position in the tree, so that all comments within a certain date range will appear together even if they don't appear with their parents. Any comment which was posted at a similar time to its parent will appear on the same page and in those cases we can display them 'nested', but there will be comments that are orphaned from their parents. This is probably acceptable - it is the way things are done in YouTube comments - a comment made much later than its parent will not appear on the same page as its parent (if the parent is not on the latest page), but instead appear with the other newest comments. * Retrieving the nodes in order like you would traverse a tree. This gives priority to the tree structure rather than the date, though siblings can still be sorted by date. The benefit to this is that replies are always placed with their parent (the comment they are in reply to) even if that parent is a number of pages from the most recent comments. This is how things are done on apps such as the icanhascheezburger blog. I don't like a few things about it, like the way that everyone is tempted to add a reply to whatever is the biggest tree branch. * The third option is to do like Slashdot does, where it doesn't separate comments into pages, but has one big tree - in order to keep the page size manageable it starts culling low-rating comments instead. I think the first would be the simplest DB query given my relation table but would be open to other ideas. Some such systems, of all three kinds, limit the nesting level in some way - this is easy enough to do, once we have recursed over X levels everything else can be combined together as if they are siblings. For example, YouTube comments only render to one level. Other systems sometimes say "nesting level exceeded" after 5 or so levels.
I assume that the reason you want nested comments at all is because your users tend to want to read through a single thread of interest at a time. That is, you have reason to believe users will create threads of coherent chains of thought, and/or what gets discussed in one thread will interest some users but not others. If that’s the case, I don’t know why you would ever want to arbitrarily split a thread across pages by date (Option 1). Using a single page with culling of low-rated comments (Option 3) seems a little harsh and may discourage users from posting comments. That may be a good thing if you’ve got an audience mass like SlashDot, but it may be undesirable for sites with more typical visitation rates. Perhaps you can have something like Option 2, with all threads on the same page, but if a thread starts getting too long, it gets rolled up into a single link that takes the user to a page dedicated to that thread. Alternatively, long threads can be reduced to just display their subject lines and authors, each which in turn link to the appropriate place in a dedicated page for the thread. I suspect the tendency for users to post irrelevant comments in the largest thread is a product of users not wanting to be bothered with scrolling around to find the end of the thread, or find a thread that’s more suitable. By automatically compacting long threads, leaving the root of all threads displayed on a single page of manageable length, users can easily scan for a thread of interest and add to it if desired.
55010
I just implemented jwt-simple,on my backend in nodejs.i want to expire token by given time. ``` var jwt = require('jwt-simple'); Schema.statics.encode = (data) => { return JWT.encode(data, CONSTANT.ADMIN_TOKEN_SECRET, 'HS256'); }; Schema.statics.decode = (data) => { return JWT.decode(data, CONSTANT.ADMIN_TOKEN_SECRET); }; ``` **how to add expires time in jwt-simple**
There is no default `exp`. Two ways you can add it mannually: 1. With plain js: iat: Math.round(Date.now() / 1000), exp: Math.round(Date.now() / 1000 + 5 \* 60 \* 60) 2. With `moment.js`: iat: moment().unix(), exp: moment().add(5, 'hours').unix() [Source](https://github.com/hokaccha/node-jwt-simple/issues/50) from original Github repository.
55412
I was puzzled to find out the definition of “discursus” incidentally in Readers Plus English Japanese Dictionary, one of the best-selling English Japanese dictionaries, which is published by Kenkyusha, a well-reputed foreign language dictionary publisher in Japan. It defines ‘discursus’ as; n. 理路整然たる討議、説明 (logically consistent and well-organized discussion or explanation), while it defines ‘discursive’ as; a. digressive. One’s sentences and stories passing from one thing to another; ranging over a wide field. To me, it’s strange that ‘discursus’ and ‘discursive” both of which are considered to be cognates derived from Latin `discurro’ meaning ‘running about’ come up in the reverse meaning: ‘discursus= logically consistent and well-organized” and ‘discursive =digressive, loose thinking.’ So I consulted with other English Dictionaries. All CED, OED, Merriam-Webster define “discursive’ in the same way as “digressive; Passing from one thing to another; ranging over a wide field," but none of them provides definition of ‘discursus.’ Spellchecker keeps trying to correct “discursus” into “discourse” while I’m typing this question. However, Wikitionary and Dictionary.com. carry the heading of ‘discursus’ with the same definition as an uncountable noun; (Logic) Argumentation; ratiocination; discursive reasoning. Google NGram shows that compared with a notable rise of the currency of ‘discursive’ (0.000669585% in 2007), the incidence of ‘discursus’ is negligibly low (0.0000009975%). Do you think the definition of Readers Plus English Japanese Dictionary of “discursus” is appropriate? Depending on your input, I’d like to request the editor of the dictionary to re-edit the definition of the word.
[Discursus](http://dictionary.reference.com/browse/discursus), ([Ngram](https://books.google.com/ngrams/graph?content=discursus%2C&year_start=1800&year_end=2000&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Cdiscursus%3B%2Cc0)) is a formal, uncommon term used with the below definitions (actually a Latin term). I think that your Reader Plus Japanese Dictionary gives an appropriate definition of it: > > * n. (Logic) Argumentation; ratiocination; discursive reasoning. > * n. argument. > > > Discursus: > > * In his five-volume **[Discursus](http://encyclopedia.thefreedictionary.com/Discursus+academici+de+iure+publico) academici de iure publico** (1615–1623), Arumaeus pioneered public law as a distinct field of study. Influenced by Dutch humanism, his methodical analysis of the constitutional law of the Holy Roman Empire focused no longer on Roman law but on Imperial sources of public law, such as Imperial basic laws and electoral capitulations. > > > [Discourse:](http://www.thefreedictionary.com/Discourse) as you note is the more commonly used term which derives form 'discursus': > > * n. > 1. A formal, lengthy discussion of a subject, either written or spoken. > 2. Archaic The process or power of reasoning. > > > [Discursive](http://www.thefreedictionary.com/Discursive) (adj.) [Medieval Latin **discursvus**, from Latin discursus], means also 'disgressive' and , I think, it is clearly related to its Latin origin. > > * 1. Covering a wide field of subjects; rambling. > 2. Proceeding to a conclusion through reason rather than intuition. > > > Source:<http://dictionary.reference.com/browse/discursus> Source:<http://www.finedictionary.com/Discursus.html>