INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to make Android app requiring camera support to run on Samsung Galaxy Mini and similar devices? I have found out that Android app that has requirement `android.permission.CAMERA` will not even show up in Android Market for device like Samsung Galaxy Mini. I think it is because Samsung Galaxy Mini has only fixed-focus camera. Has anyone created app with camera requirements and has successfully deployed it on Android Market where it is possible to install it on Samsung Galaxy Mini ? I still think there must be way around to do it. Thank you for any help.
Ok, more and more googling and I have came up with this line adding to AndroidManifest.xml: <uses-feature android:name="android.hardware.camera.autofocus" android:required="false" /> But it requires to use minSDK=7
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, android, google play" }
Are there any naming conventions for command line arguments? Am reviewing a command line driven Java application with command line switches in lower camel case like this: myapp aSwitch anotherSwitch aThirdSwitch Am thinking all lower case and leading hyphens may be preferable: myapp -aswitch -anotherswitch -athirdswitch ...or perhaps: myapp -a-switch -another-switch -a-third-switch ... or maybe: myapp --a-switch --another-switch --a-third-switch But struggling to come up with a compelling justification. Would like to follow current conventions and be cross-platform compatible, at least for Windows/Linux. Grateful for advice on what is the most commonly used convention out of these - and any reasoning behind it.
Apache Commons CLI has a description of the commonly used convention. it is also a good parser for such use cases
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 15, "tags": "java, command line, cross platform, case sensitive, conventions" }
Create postgres database from pony ORM Is it possible to create a new database from pony ORM? We couldn't find it within pony ORM docs, it's always assumed the database exists or is using SQLite file. We would like to create a testing database and drop it afterwards.
No. Per: < Supported databases If you look at the .bind() API for the various databases, SQLite is the only one with create_db. This is because in SQLite creating a database is just creating a single file. The other engines need to go through their own program to initialize a database. You will need to create an independent script that creates the database.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, postgresql, ponyorm" }
Split string by space and strip newline char I have a string that looks like: d4 c3 b2 a1 02 00 04 00 00 00 00 00 00 00 00 00 ff ff 00 00 01 00 00 00 00 00 00 00 00 00 00 00 36 00 00 00 36 00 00 00 00 1c 23 10 f8 f1 00 1b 17 01 10 20 08 00 45 00 00 28 df 27 40 00 80 06 2b 87 c7 08 1a 0a 0a 05 05 0a 5c ea 5c ea c2 1f There are many more lines that I skipped. I want to put each of the numbers in a list. When I use `.split`, it returns me a list of not just numbers, but also spaces and `\n`'s, because there are two spaces in the middle of the matrix and there are newlines at the end of each line. So I got: ['d4', 'c3', 'b2', 'a1', '02', '00', '04', '00', '', '00', …, '\nff', 'ff', '00'…] How can I get just the numbers to be in the list, not anything else?
If you use `.split(" ")`, then your program will split on every single space, and not on any other whitespace. If you use `.split()` instead, the program will take into account multiple spaces, newlines, tabs and all other forms of whitespace. That should get you what you're looking for. >>> teststr = "a v w ef sdv \n wef" >>> print(teststr) a v w ef sdv wef >>> teststr.split() ['a', 'v', 'w', 'ef', 'sdv', 'wef'] >>> teststr.split(" ") ['a', '', '', 'v', 'w', '', '', 'ef', 'sdv', '', '', '\n', '', '', 'wef']
stackexchange-stackoverflow
{ "answer_score": 41, "question_score": 10, "tags": "python, string, split" }
How do I find licenses of all installed ruby gems? For legal needs, I need to document all the installed gems and their licences on our instances. The `gem list` command lists all the gems. Is there a programmatic way to also list the licenses?
**From the Rails console:** For some Gems, which have its license information included inside its spec, you can display them running this from the _rails console_ : Gem.loaded_specs.each do |name, spec| puts "#{name}: #{spec.license}" end or **From your linux bash terminal:** for i in `gem list | cut -d" " -f1`; do echo "$i :" ; gem spec $i license; done
stackexchange-stackoverflow
{ "answer_score": 30, "question_score": 8, "tags": "ruby" }
How to see other participants in Outlook 2007 appointments? When I receive an invitation for an appointment (sorry don't know if that the right Outlook-term, I only have the German version here) I see the list of participants. Once I accept it, I no longer see who was/is invited. When my accept message gets sent, I see in that sent folder message from that time who is in/out, etc. But it's not updated when other participants accept/deny the invitation. Can this be enabled somewhere to see either the original list of persons who were invited _or_ who who've accepted/denied the invitation?
I think you just open the appointment up and click "Scheduling" (or rather the appropriate German equivalent name) on the ribbon. It should then show the current state of attendees, along with their free/busy info. This is also useful when arranging a meeting, because you can see everyone's free/busy info to see when people are available and avoid clashes.
stackexchange-superuser
{ "answer_score": 13, "question_score": 14, "tags": "microsoft outlook 2007" }
Is it possible to show more entries of the same entry type as the current entry? I'm creating a tumblr-esque blog with a bunch of different entry types. One of the entry types will be named "Image". When I'm on the entry page for an "Image" entry, I'd like to be able to show 10 more entries with the same "Image" entry type. Is this possible?
You can get the entry’s current type handle via `entry.type`, and craft.entries supports a `type` param for finding entries of a given type, so you can plug those two together: {% set otherEntries = craft.entries.section('blog').type(entry.type) %}
stackexchange-craftcms
{ "answer_score": 5, "question_score": 6, "tags": "entry type" }
Apache Ambari patch information How do you know which files need to be patched when Apache Ambari issues are resolved and a patch (ie. a diff) is attached to the corresponding JIRA issue? There is no description in the ticket as to which files need to be patched.
The patch file contains all that information in the form of a diff. This includes which files were modified, what lines of code changed in that file, and how that line changed. Typically you would want to checkout the source code, apply the patch, and then build the project. If it's a change to a script or a configuration file you can just make those changes in an existing environment.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "apache, hadoop, ambari" }
Finding the dimension of a handle 'If M is a manifold together with a (k-1) sphere embedded in its boundary .... we attach a k handle...' - mathworld.wolfram.com/Handle.html The figure in < says "A 3 ball with three 1 handles attached." A 2-1 sphere is embedded in the boundary of the three ball, so shouldn't it be a 2 handle instead?
The $3$-ball, $M$, is a $3$-manifold, a solid ball. The handles you see in the image are $1$\- handles, $I \times D^2$. The boundary of each handle is a pair of $D^2$s, one on each end which are attached to the boundary of $M$, and an $S^1 \times I$ which is not attached to $M$. Each such handle is attached along two disks in the boundary, $\partial M$, so that attachment map $f$ has image $S^{1-1} \times D^{3-1} \simeq S^0 \times D^2$, the disjoint union of a pair of $2$-disks, which you can see actually is the attachment region in the boundary of the $3$-ball.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "general topology" }
Firefox DevTools (XHR) XMLHttpRequest pretty-print The Firebug extension isn't being developed, so I have started use Firefox DevTools. I have problem with unreadable request-response XML, because both strings are one-line string.![Firefox DevTools]( Firebug shows request-response XML nicer. ![enter image description here]( Any idea how to show pretty-print XML in Firefox DevTools?
The DevTools don't have this feature yet (as of Firefox 51.0.1). It's requested in bug 1247392, though.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "firefox, xmlhttprequest, firebug, firefox developer tools" }
Power BI returning value >0 for when dividing by 0 Trying to calculate YTD Percent off an imported data set, but receiving a value >0 for division where there is no budget or expenditure. I have tried both of the following dax measures to calculate that column: Percent = divide(Actuals[Actuals],Budget[Budget]) Percent = IFERROR(Acutals[Acutals]/Budget[Budget], blank()) See photo here: !Data Output
It appears that these aren't exactly zero just very small (possibly due to floating-point error or something similar). So it isn't actually dividing zeros. One option to avoid this would be to round your numbers to some number of decimal places before trying to divide. E.g. Percent = DIVIDE ( ROUND ( Actuals[Actuals], 2 ), ROUND ( Budget[Budget], 2 ) )
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "powerbi, dax, powerbi desktop, divide by zero" }
Times loop does not work I wrote a simple helper for my rails application: def calendar_build 5.times do whole_cal end end def whole_cal content_tag(:div, :class => "row") do small_cal + big_cal end end def small_cal content_tag(:div, :class => "col-xs-2 token-text") do concat(content_tag(:p, "15.20")) end end def big_cal content_tag(:div, :class => "col-xs-10 weite_cal") do concat(content_tag(:input,"", class: "form-control input-sm pa")) end end How you can see i try to generate 5 `whole_cal`: def calendar_build 5.times do whole_cal end end But in my view this only displays `5` why? Thanks
Couldn't you do `whole_cal*5`? String multiplication works in general.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails, ruby on rails 3" }
Sound stopped working after upgrading to Linux 5.4 (Intel HD Audio) After upgrading from Linux 5.3 to Linux v5.4.2 on Arch Linux, all of my audio stopped working. The only thing I see in Gnome 3’s Sound settings is “Dummy Output” and `aplay --list-pcm` says: “No card(s) found.” and running `alsactl init` says: “alsactl: init:1759: No soundcards found.” I’ve tried many solutions already.
Here is how I was able to resolve this: 1. `sudo vim /etc/default/grub` 2. Find `GRUB_CMDLINE_LINUX_DEFAULT` and add `snd_hda_intel.dmic_detect=0` to the end of it. (ex: `GRUB_CMDLINE_LINUX_DEFAULT="loglevel=3 snd_hda_intel.dmic_detect=0"`) 3. `sudo grub-mkconfig -o /boot/grub/grub.cfg` 4. Reboot the system.
stackexchange-superuser
{ "answer_score": 25, "question_score": 9, "tags": "linux, audio, arch linux, sound card, pulse audio" }
View WYSIWYG Content I am sure this is a very basic question. I'm using a WYSIWYG editor to enter content and save it to the database. When I load that content to the web page, it shows as plain text and the browser doesn't render the html tags correctly. It just shows up as <p>This is some text</p> This is my first interaction with a WYSIWYG editor. Thanks for your help!
PHP : {{ $data }} Use : <?php echo $data ?>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, wysiwyg" }
How could user cancel the consent during the sign-in I develop a program to sign in azure users,during the sign in,user need to consent the permission,but after that,how would a user revoke the consent? On azure portal,I can't find somewhere user can revoke the permission. I am new to azure,any help is appreciate.
You could revoke individual user consent through the My Apps Portal(< . On that portal , for apps where you individually consented as a user, you can click "Remove" which will revoke consent for the application. I would highly recommend you read this blog which explain more about revoking consent for Azure Active Directory Applications . This article also includes scenario for using the Azure Portal to remove tenant wide consent.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "azure, azure active directory" }
Powershell: Searching for Caps by regex So based on my testing using `[A-Z]` is worthless when looking for caps. So here's the deal, I have a string with three characters. I need to make sure that all three of those characters are capital letters. I've searched stackoverflow and the web and tried this: PS M:\> 'ADV' -match '[A-Z]{3}' True PS M:\> 'adv' -match '[A-Z]{3}' True PS M:\> 'A' -match '[a-z]' True PS M:\> 'adv' -match '[A-Z]' True This makes no sense to me! Why isn't the casing working?
Got bitten by this myself recently. Powershell will do a case insensitive match by default. You need to use `-cmatch` instead: [PS] > 'A' -cmatch '[a-z]' False [PS] > 'adv' -cmatch '[A-Z]{3}' False
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "regex, powershell" }
Screen flashes when loading new scene I have a level selection menu, inside this I have buttons to load my scene levels. I am using the next method to switch the scenes: UnityEngine.SceneManagement.SceneManager.LoadScene(); The problem is that I have dark-gray faders in my scene and when I load the different scenes the screen flashes white. Instead of staying in the same dark-gray tone like I would want it. I will gladly supply any further information that you need. Does anyone know a solution?
The last frame of the previous scene is contiguous with the first frame of the next scene so one needs to ensure that there is nothing in either frame that could make a visible difference e.g. resetting the state of something like a material colour via a script called from an Awake function.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, unity3d" }
Simple way to package a UWP C++ application for running on a clean Windows 10 machine? I have just built my first UWP C++ example using Visual Studio. It works when I launch it from within studio, but the generated release .exe doesn't even work on this very machine where I built it - I get the following error: > This application can only run in the context of an app container. But even if it did run here, there's a question of packing necessary .dlls and such. I checked this MSDN article, but it describes a complicated process with signing with a certificate that I don't have, and I don't even have `.Appx` yet (don't see how to make it). I'm not releasing the app anywhere, I just need to run it on my other Win 10 PC. What's the simplest way?
The simple way to build an app that can be deployed anywhere is to create a store package from project > Store > create app package ![create package]( Select "no" to create a test package and follow the instructions. Once the build completes, the output folder will contain the appx and an installation script named "Add-AppDevPackage.ps1" to deploy the appx on Windows 10 desktop. To start the script, right-click on it and select "run with PowerShell". ![files listing]( The script will deploy on the host your application and all its dependencies.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "visual studio 2015, uwp" }
Inserting streaming data into an Amazon Redshift cluster I am trying to direct insert sparkstream data into an Amazon Redshift cluster but am not able to find right way. Below is the code that i got but its first inserting into S3 then copying to Redshift:. #REDSHIFT_JDBC_URL = "jdbc:redshift://%s:5439/%s" % (REDSHIFT_SERVER, DATABASE) df.write \ .format("com.databricks.spark.redshift") \ .option("url", REDSHIFT_JDBC_URL) \ .option("dbtable", TABLE_NAME) \ .option("tempdir", "s3n://%s:%s@%s" % (ACCESS_KEY, SECRET, S3_BUCKET_PATH)) \ .mode("overwrite") \ .save() Does it impact streaming or insertion performance? Or any other way to do it?
The Redshift data source for Spark that you are using writes data to Redshift by writing the data to a temporary file on S3 then uses the Redshift COPY command to load the data into Redshift. The COPY command requires the data to be in a file on S3, this is to most efficient way to load data into Redshift so what your code is currently doing appears to be correct. See also: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "amazon web services, spark streaming, amazon redshift" }
Ruby threads not good enough? How is that JRuby's support for multithreading is any better than regular Ruby's support for it? What's wrong with threads in plain old Ruby?
"Normal" ruby (or mri) has a great big lock that prevents more than one thread from running ruby code at a time (known as the GIL or GVL). Rubinius and jruby don't have this lock. In ruby 1.8.x the threads were green threads too, but as of ruby 1.9 ruby threads are mapped to native threads. The GVL stops you from gaining much benefit though. Native extensions can run code outside of the lock so that, for example, multiple MySQL queries can run simultaneously from different threads but they can't call into the regular ruby api when they don't hold the lock
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ruby, multithreading, jruby" }
mySQL to replace all strings no matter field name? I have this query but I want to change the strings in every field_name found instead of manually changing this. How I can do this ? update TABLE_NAME set FIELD_NAME = replace(FIELD_NAME, ‘find this string’, ‘replace found string with this string’);
Then you have to specify all fieldnames. Example UPDATE tableName SET field1 = REPLACE(field1, 'oldstring', 'newstring'), field2 = REPLACE(field2, 'oldstring', 'newstring'), field3 = REPLACE(field3, 'oldstring', 'newstring'), fieldN = REPLACE(fieldN, 'oldstring', 'newstring')
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "mysql" }
Multiple directives asking for new/isolated scope - Angular Material tabs I'm getting this error: Multiple directives [ngController, mdTab (module: material.components.tabs)] asking for new/isolated scope on: <md-tab label="Usuários" ng-controller="AccountCompanySearchController"> With the following code: <md-tab label="Usuários" ng-controller="AccountCompanySearchController"> <md-content class="md-padding"> </md-content> </md-tab> That doesn't happen when ng-controller is in the md-content directive. Obviously there is a conflict with md-tab directive. Is there a possible fix for this? Thank you guys.
The issue is that ng-controller creates an isolated scope. This is mentioned in the official Angular documentation. Your third party component also creates an isolated scope as they probably require for the component to be able to store variables without polluting your scope data. The solution is to not put them on the same element. Or better yet do not use ng-controller. Here is dome additional reading as to why not use it <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "angularjs, angular material" }
Foreach while adding items to the looping collection This is the situation: I'm browsing through some code and I wondered if the following statement takes a reference of the selected collection or a copy with which it replaces the original object when the foreach loop finishes. If the first, will it take the new found pages and join them in the loop? foreach(Page page in Pages) { page.AddRange(RetrieveSubPages(page.Id)); } Edit: I'm sorry, I made a typo. It should be this: foreach(Page page in pages) { pages.AddRange(RetrieveSubPages(page.Id)); } What i tried to say is that if i add some objects to the enumerating collection, will it join those objects in the foreach?
In response to you question, it does not make a copy. It creates an enumerator and iterates through the collection. If the collection is changed while this enumeration is happening, in the foreach itself, or asynchronously, you will get an exception: An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Collection was modified; enumeration operation may not execute. You can, use a temporary collection and join the two afterwards, or just not use an enumerator. for (int i = 0; i < pages.Count; i++) { test.AddRange(RetrieveSubPages(pages[i].Id)); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c#, .net" }
python: output a list to a csv file I am trying to write `my_list` to a csv file like below: import csv myfile = open('my_list.csv', 'w') wr = csv.writer(myfile) print(len(my_list)) wr.writerow(my_list) `my_list` has length 1000. Then the output of the above code is: 1000 10001 The output `my_list.csv` looks fine. But I am wondering why it print out `10001` on the screen? What does it mean?
It looks like you are doing this in the Python console. When you print `len(my_list)`, it will print 1000. Next, you use `wr.writerow()`. It will write the row to the file and then return the current position in the file. Since it just wrote 1000 lines, the file position is at 1001 so that the next line written will not overwrite anything. In the Python console, the value that is returned is printed. If you were to execute a file with the same script, you wouldn't see that number.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python 3.x, csv" }
Why can't xlrd library in Python open xlsx file? I'm trying to read .xlsx file with Python. However I noticed that popular library xlrd doesn't work with .xlsx files. Here is the example with error message I'm getting: import xlrd if __name__ == '__main__': loc = ("./excel_file.xlsx") wb = xlrd.open_workbook(loc) I'm getting the following error message while trying to run the code above: Traceback (most recent call last): File "/Users/username/projects/excel_processing_example/main.py", line 15, in <module> wb = xlrd.open_workbook(loc) File "/Users/username/projects/excel_processing_example/venv/lib/python3.8/site-packages/xlrd/__init__.py", line 170, in open_workbook raise XLRDError(FILE_FORMAT_DESCRIPTIONS[file_format]+'; not supported') xlrd.biffh.XLRDError: Excel xlsx file; not supported Is there a reason why xlsx files are not supported by the xlrd library?
From PyPI: > xlrd is a library for reading data and formatting information from Excel files in the historical `.xls` format. The choice was made in 2020 to just focus on the `.xls` format, as they didn't want to replicate the work being done by the excellent `openpyxl` project.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, xlsx, xlrd" }
PHP Contact form Validation? I have a website with a contact form, when I submit the details I get an error message about deprecated `eregi()` on line. This is the block of code that seems to be having a problem. I don't know php, so could anyone give a hand? if (email_is_valid($youremail) && !eregi("\r",$youremail) && !eregi("\n",$youremail) && $yourname != "" && $yourmessage != "" && substr(md5($user_answer),5,10) === $answer) { mail($to,$subject,$message,$headers); $yourname = ''; $youremail = ''; $yourmessage = ''; echo '<p style="color: #200041; text-align: center;">'.$contact_submitted.'</p>'; }
`eregi()` is deprecated. So you can use `preg_match()` And your code will be <?php if (email_is_valid($youremail) && $yourname != "" && $yourmessage != "" && substr(md5($user_answer),5,10) == '$answer') { mail($to,$subject,$message,$headers); $yourname = ''; $youremail = ''; $yourmessage = ''; echo '<p style="color: #200041; text-align: center;">'.$contact_submitted.'</p>'; } else { echo '<p style="color: red; text-align: center;">Error</p>'; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php" }
How to install PyQt5 in Python 3 (Ubuntu 14.04) I need to port some code that's Python2+PyQt4 to Python3+PyQt5. I started installing pip3 sudo apt-get install python3-pip Works great. Tried sudo pip3 install PyQt5 Downloading/unpacking PyQt5 Could not find any downloads that satisfy the requirement PyQt5 Cleaning up... No distributions at all found for PyQt5 Online I find the following steps: < But they are too many. What's the easiest way to Install PyQt5 along with Python3 in Ubuntu 14.04 ?
Why not simply install it via apt-get? sudo apt-get install python3-pyqt5 Otherwise you'd have to compile PyQt (and potentially Qt) by hand, which is cumbersome.
stackexchange-stackoverflow
{ "answer_score": 66, "question_score": 30, "tags": "python 3.x, ubuntu 14.04, pyqt5" }
grepl filter in R program Trying to filter the rows which contains only the word DEV but the below is pulling wrong matches like SEV HEV and BEV as well Data Airport_ID<-c("3001","3002","3003","3004") Airport_Name<-c("Adelaide DEV DTSUpdated","Brisbane HEV Land Airport Land ADTS", "Washington SEV INC Airport DTSUpdated","DALLAS Airport BEV INCUpdated") dfu<-data.frame(Airport_ID,Airport_Name) Filter Code Filter_Data <- dfu %>% dplyr::filter(grepl(" \\DEV\\ ",Airport_Name)) Intended Output: 3001 Adelaide DEV DTSUpdated
Just use library(dplyr) dfu |> filter(grepl("DEV" , Airport_Name , fixed = T)) * output Airport_ID Airport_Name 1 3001 Adelaide DEV DTSUpdated
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r, grepl" }
Ajax Long Poll ,PHP or Python which uses least Memory? Which Language would be better to implement long ajax poll, i heard php uses more memory in long ajax poll, is that correct?
If you want to do long polling, go for Node.js It can handle thousands of requests on very low hardware config. If you know Python, you can use Tornado or Twister for long polling application.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "php, python" }
How to use array variable in array? I have an array and I want to put same array and other array inside of the first array. var arr=["a","b","c",arr,arr2]; var arr2=["a","b"]; var arr3=[]; arr3=arr[3]; When I print out arr, I can see `["a","b","c",,]` But if I print out arr3, The result is undefined. How can I fix it?
You need to do this in the right order: var arr1 = []; var arr2 = [ "a", "b" ]; // Now arr1 and arr2 are defined so you can throw them into another array: var arr3 = [ "a", "b", "c", arr1, arr2 ];
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, arrays" }
Compare two objects and extract the ones that have same Key in javascript I have the following two objects var productionTime= [ {Rob3: 20}, {Rob8: 100}, {Rob4: 500}, {Rob1: 100}, {Rob5: 500} ]; var Busytime= [ {Rob4: 10}, {Rob3: 200}, {Rob8: 100}, {Rob5: 200}, {Rob1: 100} ]; Now I want to divide each item in 'productionTime' by its respective 'BusyTime' which have the same key. For example productionTime.Rob3 should be divided by BusyTime.Rob3 and productionTime.Rob8 should be divided by BusyTime.Rob8 and so on. How can I do this with array.find() or array.filter() in javascript/nodejs? P.S: I know i can do it by using two nested forEach loops but that is I guess very slow
You could use a hash table and a single loop for every array. var productionTime = [{ Rob3: 20 }, { Rob8: 100 }, { Rob4: 500 }, { Rob1: 100 }, { Rob5: 500 }]; busytime = [{ Rob4: 10 }, { Rob3: 200 }, { Rob8: 100 }, { Rob5: 200 }, { Rob1: 100 }], hash = Object.create(null); busytime.forEach(function (o) { var key = Object.keys(o)[0]; hash[key] = o[key]; }); productionTime.forEach(function (o) { var key = Object.keys(o)[0]; o[key] /= hash[key]; }); console.log(productionTime); .as-console-wrapper { max-height: 100% !important; top: 0; }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "javascript, arrays, node.js, object, javascript objects" }
Node promisify, await and return callback properties is there a way I can convert the `jsonwebtoken` package `verify` method so it works in this way? `const { err, decoded } = await jwtPromise(post.journey_token, 'test');` I have managed to convert it to a promise, but this want's to use `.then`, however I don't want to do it this way. Currently `err` and `decoded` is undefined. Here is the full code, can this be done? import jwt from 'jsonwebtoken'; import util from 'util'; export const store: APIGatewayProxyHandler = async ({body}) => { const post = JSON.parse(body); const jwtPromise = util.promisify(jwt.verify); if (post.journey_token) { const { err, decoded } = await jwtPromise(post.journey_token, 'test'); console.log(decoded, err); }
You can convert any asynchronous function to return what you want. You can do so by wrapping it in another function which returns a promise, which instead of rejecting in case of an error always resolves to an object containing both an error and a result key. function promisify(asyncFunction) { return function (...args_) { return new Promise(function (resolve, reject) { function cb(error, result) { resolve({ error, result }) } var args = [ ...args_, cb ] asyncFunction(...args) }) } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "node.js, jwt, es6 promise" }
Rails 4 link_to option to include data i have a link as follows <a title="" class="btn btn-default btn-icon btn-xs tip" href="#" data-original-title="Edit"><i class="fa fa-pencil"></i></a> what i have tried? <%= link_to "<i class="fa fa-pencil"></i>".html_safe, edit_admin_category_path(category), :class => 'btn btn-default btn-icon btn-xs tip', :data => {:original-title=>"Edit"} %> Error: /Users/harshamv/Sites/nomad/app/views/admin/categories/index.html.erb:28: syntax error, unexpected tIDENTIFIER, expecting ')' Is there a way to use link_to without have to use the following format <%= link_to(@profile) do %> <strong><%= @profile.name %></strong> -- <span>Check it out!</span> <% end %>
Your approach will work, it's just a syntax error where you need to fix the double quotes. <%= link_to "<i class='fa fa-pencil'></i>".html_safe, edit_admin_category_path(category), :class => 'btn btn-default btn-icon btn-xs tip', :data => {:original-title=>"Edit"} %> You could also use `content_tag` which is a little cleaner <%= link_to content_tag(:li, '', class: 'fa fa-pencil'), edit_admin_category_path(category), :class => 'btn btn-default btn-icon btn-xs tip', :data => {:original-title=>"Edit"} %>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, hyperlink" }
Yii2 Button url to folder I want to create a button which opens a pdf. This pdf is in another folder, but I can't reach this folder. Can somebody help me, I'm quite new to this. Here is my Button: $button = Html::a('Geef document weer', ['/uploads/documenten/' . $model->documents[0]->location . '/' . $model->documents[0]->file . $model->documents[0]->format], ['class' => 'btn btn-primary btn-xs', 'target' => '_blank']);
Don't use hash notation but specify the link and in 'yourPath' set the proper value $button = Html::a('Geef document weer', 'yourPath/uploads/documenten/' . $model->documents[0]->location . '/' . $model->documents[0]->file . $model->documents[0]->format, ['class' => 'btn btn-primary btn-xs', 'target' => '_blank']); or use @web alias $button = Html::a('Geef document weer', Url::to('@web/uploads/documenten/') . $model->documents[0]->location . '/' . $model->documents[0]->file . $model->documents[0]->format, ['class' => 'btn btn-primary btn-xs', 'target' => '_blank']);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php, url, pdf, button, yii2" }
Using Tcl info procs return value given that not_there isn't a proc I would expect [info procs not_there] eq "" to return 0, but I'm seeing empty command name "" could someone explain my conceptual error?
This statement of yours: [info procs not_there] eq "" will first have `info procs not_there` evaluated by the Tcl interpreter. Next the interpreter will evaluate the equivalent of this statement: "" eq "" ...where the first word `""` is not a valid command. In the Tcl statements, the first word must always be a command. command arg arg arg... What you're missing is using the `expr` command at the beginning expr {"" eq ""} --> 1 expr {[info procs not_there] eq ""} --> 1 By the way, the `expr` is implied in the conditional argument of the `if` statement: if {[info procs not_there] eq ""} { puts "This is not a proc" }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "error handling, syntax error, runtime error, tcl" }
Is there a quick way to change the keys and foreign keys of my database during the development stage with script Is there a quick script I can use in SQL Server to change the ID from int to unique identifier without physically going through and doing it manually. I have contemplated code gen to achieve this, but I would have thought using TSQL would be the quickest if possible that is!
You could do it with a script. ALTER TABLE x ADD COLUMN y uniqueIdentifier null GO UPDATE TABLE x SET y = NEWID() --Or NEWSEQUENTIALID() if its safe GO ALTER TABLE x ALTER COLUMN y uniqueIdentifier NOT NULL GO ALTER TABLE x DROP CONSTRAINT PK_PrimaryKeyConstraintName GO ALTER TABLE x DROP COLUMN PrimaryKeyColumn GO ALTER TABLE x ADD CONSTRAINT PK_NewPrimaryKeyConstraint PRIMARY KEY CLUSTERED ( y ASC ) GO Note that this wont deal with your foreign key constraints and will break, if you have foreign key constraints this gets interesting, but I'm sure you can see the pattern.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, sql server, tsql" }
Mapping attributes to values in vector I'm working with a dataframe where each column has different attributes. Is it possible to map specified attributes to the vector? For context, you might expect to see this situation where you have raw data and labeled data in the form of a vector and a label attribute. Here is an example with the desired outcome: foo = c(2,1,3,3,2,1) attr(foo, "mylevels") = c(1,2,3) attr(foo, "mylabels") = c("Red", "Blue", "Green") ## foo ## [1] 1 2 3 3 2 1 ## attr(,"mylevels") ## [1] 1 2 3 ## attr(,"mylabels") ## [1] "Red" "Blue" "Green" ## attributes(foo) ## $mylevels ## [1] 1 2 3 ## $mylabels ## [1] "Red" "Blue" "Green" The goal is something like: foo[attr(foo, "mylabels")] #(which doesn't work) "Blue" "Red" "Green" "Green" "Blue" "Red"
We can either convert the 'foo' to `factor` and specify the `levels` as.character(factor(foo, labels=c("Red", "Blue", "Green"))) Or use the 'foo' as numeric index for the `attr` attr(foo, "mylabels")[foo]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r, attributes" }
invoking android to send an e-mail on given time without opening app I am making a app which requires me to schedule task. My user can schedule an e-mail body, subject,recipient e-mail address etc and those datas will be saved in internal DB. They will also specify the time and date on which they want the app should send the e-mail and inform them afterwards. I know about AlarmManager but not sure if this can be accomplished with it. Please suggest. Is there any third party library for that?
You can use AlarmManager to schedule work in background and Check the system date and time with user set date and time. if they met the information then use this example to send email via background in android.(I do not give you source code because AlarmManager and mail code in internet) example to send email in background
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, email, alarmmanager, schedule" }
Passing parameter into Cypher query node_auto_index I'm trying to pass a parameter into the Cypher query node_auto_index without any luck. DecisionRepository.class: @Query("START d=node:node_auto_index(':text') MATCH (d:Decision) RETURN d") List<Decision> searchDecisions(String text); Usage: List<Decision> searchDecisions = decisionRepository.searchDecisions("name:aDbma~ OR name:mosyl~"); Is it possible and if so where I'm wrong ?
Use query parameters START d=node:node_auto_index({myLuceneQuery}) RETURN d; Then send `"name:aDbma~ OR name:mosyl~"` as `{myLuceneQuery}`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "neo4j, cypher, spring data" }
How to set background color to the content area in UIScrollView? I am using an `UIScrollView` in my application, my requirement is I have to add background color to the `UIScrollView` but when user drags at the extreme top or at the extreme bottom the area other than the content/out side the content which shows in the scroll view should be shown with different color just like in `UIWebView`. In web view if we drag down at the top or drap up at the bottom it will show default background image/gray color and the web view content background color is diff(default white).Can anyone help me in achieving this. thank you.
The trick is to add subviews to the ScrollView that sit above and below the content. This way, they only appear when the content is dragged up or down. UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, -200, scroll.bounds.size.width, 200)]; [topView setBackgroundColor:[UIColor darkGrayColor]]; [scroll addSubview:topView]; [topView release]; UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, scroll.bounds.size.height, scroll.bounds.size.width, 200)]; [bottomView setBackgroundColor:[UIColor darkGrayColor]]; [scroll addSubview:bottomView]; [bottomView release];
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 2, "tags": "iphone, ios, ipad, uiscrollview, uiscrollviewdelegate" }
Laravel Sail on Windows Subsystem for Linux (wsl) I was trying to create a new laravel app with laravel sail and I ran the following command on ubuntu 20.0.4: * * * curl -s | bash * * * But I got the following message: docker: invalid reference format: repository name must be lowercase. See 'docker run --help'. bash: line 16: cd: example-app: No such file or directory Get started with: cd example-app && ./vendor/bin/sail up * * * Here is a screen shot (No folder is created)
You are using a directory with capitals and spaces, i.e: `Sennay Files`. Use a different directory or rename it to: `Sennay_Files`. You are working on the Windows file system from within WSL (i.e. /mnt/c). This will cause a significant performance hit, and issues like the one you are experiancing, consider using the WSL file system. You can change to the WSL file system by typing cd ~
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "laravel, docker, windows subsystem for linux, laravel sail" }
Finding Taylor series for a complex logarithm branch **The Problem:** Find the Taylor series for the logarithm branch $0<\arg(z)<2 π$ in powers of $z+2$ **My resolution** : The method I've used to come up with an answer was integration of a known series. I know that the series of $f(z)= 1/z$ around the point $z=-2$ is $\sum_{n=0}^{∞} \frac{-(z+2)^n}{2^{n+1}}$ which converges if $|z+2|<2$ So by doing this I have: $\frac{1}{z}$ = $\sum_{n=0}^{∞} \frac{-(z+2)^n}{2^{n+1}}$ Since I know that $1/z$ is an antiderivative of $\log(z)$ when $0<\arg(z)<2\pi$ (a branch is specified), I can integrate both sides of the equation to obtain: $\log_0(z)= \sum_{n=0}^{∞} \frac{-(z+2)^{n+1}}{(n+1)(2^{n+1})}$ My main questions are: -Is this approach a correct one? -What would change If I had a different branch of $log(z)$ ? Thank you.
Answering your second question: For any branch of $\log z$, $$(\log z)’=\frac1z$$ which is single-valued. Thus, if $$\log z=\sum^\infty_{n=0}a_n (z-c)^n$$ we expect $(\log z)’=\sum^\infty_{n=1}a_n\cdot n (z-c)^{n-1}$ should be independent of choice of branch. In other words, $a_1,a_2,...$ remain the same even if you change your choice of branch. The choice of branch can only affects $a_0$, which can be uniquely determined by evaluating $\log c=\ln|c|+i\arg c$, with the $\arg c$ that fits with the choice of branch. * * * For the first question: Substitute in $z=-2$ into your series, and you will obtain $\log_0(-2)=0$, which is absurd. You made a mistake: missing the integration constant.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "complex analysis, complex numbers, taylor expansion" }
Select id from table admin with PHP and MySQL i need help with php code trying to retrieve all information from a table using the username that is logged in. So here is a example: Bob logs in with his username & password He then comes to a members only section In this section it displays his results from the admin table which will show: username & password Hope this makes sence, I am using a session()
It is not that hard to accomplish. You basically had the answer in your comment. <?php $query = "select * from table_name where username = '". $_SESSION['username'] . "'"; $result = mysql_query($query); while($row = mysql_fetch_array($query)) { $password = $row['password'] } // Then do your output of information ?>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "php, mysql, sql, database, authentication" }
Repetition of formulas in nodes of Semantic Tableau I'm studying Propositional and First Order Logic and I have to practice with the Tableaux Method in order to check satisfiability of a formula. I create new nodes of the tree by using the Completion Rules in a straightforward way, but I have a doubt about it. Everytime I have a new node, I repeat some of the previous node's formulas. I make an example: I have this block: ![Tableaux with branches]( Is it legit to repeat the two "or" formulas again in the two new branches? I rewrite them because in this way I don't forget to use them, it is only for my comfort. Thanks in advance.
You have two options: 1. Either you do what you do, which is to copy all of the remaining statements into the branches below. The disadvantage of this is that you have to copy all those statements (i.e. it will be more work) 2. You don't copy the statements, but when you apply a tree rule on any of the remaining statements, you have to make sure to put the result in all of the branches under it. The disadvantage of this is that you have to be a bit more careful in making sure that indeed you do this. So yes, what you do is fine, but not necessary, as long as you are careful!
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "propositional calculus, first order logic, decision trees" }
Repaint never reaches paintComponent(); I'm back with a problem about java-graphics by swing... I want to paint some stuff at a jframe, here is the code: PaintUtil-class: public class PaintUtil extends JPanel{ public PaintUtil(){ this.setFocusable(true); this.requestFocus(); } @Override public void paintComponent(Graphics g){ super.paintComponent(g); System.out.println("Repainted"); g.drawstuff... } } Main-class: public static PaintUtil util = new PaintUtil(); JFrame frame = new JFrame(); frame.setSize(500,600); frame.setRezisable(false); frame.add(util); frame.setDefaultCloseOperation( 3 ); frame.getContentPane().setColor(Color.BLACK); setup(); //This add some buttons frame.setVisible(true); util.repaint(); //not working util.paintComponent(frame.getGraphics()); //works Can you guys help me?
> There is no error, no message in the console, just nothing frame.setLayout(null); Don't use a null layout. Swing was designed to be used with layout managers. Get rid of that statement. By default the size of your panel is (0, 0) so there is nothing to paint. You will need to override the `getPreferredSize()` method of your panel so the layout manager can do its job. Read the section from the Swing tutorial on Custom Painting for more information and working examples.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "java, swing, graphics, repaint" }
How can I help to participate in data collection or research work as a field researcher? To clarify my question, due to length limitations in question part. For PHD, Researcher allowed to take part as research subject for data collection/analysis? How to include personal accounts of/experiences of a research phenomenon? Thoughts/decision making processes when playing a specific game on world class level? This then mean a specific game where there are limited /very few really have mastered the game and subjects are not easily contactable. Also potential research participants are a handful 5 to 12. To explain. If a researcher want to ask how tennis players think his accessibility to the top 20 of the world tennis players are really only 20 and not just anyone around the corner that wannabee play tennis.
The first step before starting a PhD would be to find a potential supervisor who has some expertise in the research domain (not necessarily the specific topic). First there will be some discussion with this supervisor about the exact research topic and the motivations for the research: a PhD student's expertise in a particular topic is not enough to justify research on this topic, there must be some scientific reasons why this topic is a relevant research area. Then you will see with your supervisor about the best method(s) to achieve these research goals. Imho it's unlikely that a supervisor would agree with a method which involves you as a subject, but I'm not at all in this kind of domain. In any case your expertise would certainly be useful in contacting subjects and targeting the right research questions.
stackexchange-academia
{ "answer_score": 0, "question_score": 0, "tags": "phd, research process, thesis" }
Mixing ActiveRecord find Conditions I want to find records on a combination of created_on >= some date AND name IN some list of names. For ">=" I'd have to use sql condition. For "IN" I'd have to use a hash of conditions where the key is :name and the value is the array of names. Is there a way to combine the two?
You can use named scopes in rails 2.1 and above Class Test < ActiveRecord::Base named_scope :created_after_2005, :conditions => "created_on > 2005-01-01" named_scope :named_fred, :conditions => { :name => "fred"} end then you can do Test.created_after_2005.named_fred Or you can give named_scope a lambda allowing you to pass in arguments Class Test < ActiveRecord::Base named_scope :created_after, lambda { |date| {:conditions => ["created_on > ?", date]} } named_scope :named, lambda { |name| {:conditions => {:name => name}} } end then you can do Test.created_after(Time.now-1.year).named("fred")
stackexchange-stackoverflow
{ "answer_score": 28, "question_score": 10, "tags": "ruby on rails, ruby, activerecord" }
how to get user to input a range from a dialog box so i need to get a range from the user, how is it possible to query the user to select a range, something like" dim x as range x = getrange("Select Range to Compare") msgbox "The range selected is " & x is there a way to do this?
You may try something like this. Tweak it as per your requirement. Sub AskUserToSelectARangeToWorkWith() Dim Rng As Range On Error Resume Next Set Rng = Application.InputBox("Select a Range to compare.", "Select A Range!", Type:=8) If Rng Is Nothing Then MsgBox "You didn't select a Range.", vbCritical, "No Range Selected!" Exit Sub End If MsgBox "The Range selected is " & Rng.Address(0, 0) End Sub
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "vba, excel" }
Passing a list of numbers to a function in C++ without building array first? I'm trying to build a function that accepts an array in the following manner: int inCommon = findCommon({54,56,2,10}, 4); int findCommon(int nums[], int len){ for(int i=0; i<len; i++) cout<<nums[i]<<endl; return 1; } Note, that's not actually what my function does, but I do loop through the array. I'm just trying to determine if it's possible to pass an array like {54,56,2,10} instead of having to create an array and pass it? (like this: int theArray[]= {54,56,2,10}; int inCommon = findCommon(theArray,4);
This is not possible at the time. However, in the next C++ standard C++0x, this will be done using initalizer lists: int findCommon(std::initializer_list<int> nums) { std::initializer_list<int>::iterator it; for (it = nums.begin() ; it != nums.end() ; ++it) { std::cout << *it << std::endl; } return 1; } See this presentation from Bjarne Stroustrup, and this article from Wikipedia If you want to try C++0x features, you can check the last versions of gcc, that supports some of them.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "c++, arrays, function" }
run a cron job only once Hi I have to restart Apache from rails controller I tried to do that with `%x{}` and `system` commands but it fails so I decided to do it with cron Is it possible to make cron task that will be executed only once ?
The run once version of cron is called `at`. See < for an explanation, and note that specifying "now" as the time causes it to run immediately.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "ruby on rails, cron" }
Apple Push Notification Service - Does iOS keep an open connection to every registered APNS server? If I understand correctly, each application that registers as an APNS provider, basically forces the iPhone to keep a live connection to a specific server. If so, doesn't it mean that the more apps I use (that register APNS), the more battery drain I will experience? Would it not be wiser of Apple to allow developers to tap into a big server cluster that will distribute notifications to all devices in the world?
I always thought the Push Notification would work through SMS. But that wouldn't work with devices that do not have a phone system but Wifi only. But in any case, even if iOS just polls, I'd think that it's all going to one central server (pool) from Apple, which will manage all requests as the message center. This isn't a proper answer, just assumptions, but maybe someone else can confirm this or at least show where I'm wrong.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "ios, apple push notifications" }
Count users where subscription end within month Linq c# I just want to count users where their subscription end date is within the coming month: int Count = oUsers .Where(x => 0 < x.SubscriptionEnddate.Value.Subtract(DateTime.Now).Days < 30) .Count(); But its not working. What I want to do is **0 < Value < 30**.
Use `&&`. Period. It is where it is designed for. You can circumvent this by creating a `Between` extension method, or concatenate two `Where` clauses, but really, why trade that over `&&`. But if you insist: int c = oUsers .Select(x=> x.SubscriptionEnddate.Value.Subtract(DateTime.Now.AddDays(30)).Days) .Where(d => 0 < d) .Where(d => d < 30) .Count();
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c#, .net, linq" }
Problem clearing HTML textarea field in FireFox using jQuery We're trying to clear a textarea in a form using jQuery. It works in Safari and Chrome, but not in Firefox. The problem in FireFox is that it is clearing the text in the source (according to firebug) but not in the normal browser display. The code we are using is: $("#text_areas_id").val(""); Is anyone aware of a bug in Firefox 4 with this? Our guess is that we need to somehow re-render the textarea for firefox after we change its vallue. We read some people had similar problems in Opera and fixed it by setting the css of the text area to display:block, but we didn't have any luck with this. We are using FireFox 4.01 on Mac & Firebug 1.7.0 Thanks for any assistance you can offer!
I have just tried your solution in Firefox 4.0.1 and seems to work: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jquery, firefox, textarea" }
как экранировать текст полученный с CKEditor как можно экранировать данные полученные с ckeditor, затем передать через json Js: var editor = $(this).find(".custom-tabs__textarea").attr("id"), txt = CKEDITOR.instances[editor].getData(), tabsName.push({ text: txt }); вот такое получаеться на выходе сейчас: ![введите сюда описание изображения](
Самый простой способ, если вы хотите получить на выходе читаемую строку без спецсимволов. tabsName = [] var txt = document.createElement('div'); txt.innerHTML = "&#39;"; // CKEDITOR.instances[editor].getData() это тут пропишите. tabsName.push({ text: txt.innerText }); alert(tabsName[0].text)
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, ckeditor" }
How to port fork() to Vxwork i am porting program from GNU/Linux to VxWorks, i am having a problem regarding to `fork()` and i can't find alternatives ; VxWork's API provide two useful calls `taskSpawn( )` and `rtpSpawn( )` to spwan RTP/Task but these API do NOT duplicate the calling process (fork does). does anyone have idea about porting/workaround fork() to Vxworks? VxWorks API Reference
If I remember my vxWork correctly - you can't. fork() requires virtual memory management, something I believe VxWorks 5.5 does not provide, at least not the full semantics needed to implement fork. (it was added in vxwork 6 though if I am not mistaken).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c, linux, porting, embedded linux, vxworks" }
User name as Watermark Ok, I searched the internet and stackoverflow but I just can't seem to find an answer for my problem. I need to watermark images uploaded by users dynamically, but I don't want just text applied on an image. I need a real watermark like this: !alt text The only way I can achieve this effect is by using Photoshop, adding shadow and decreasing the filling to 0%. But if my site is visited by 200 users who upload their images, I just can't make for everyone of them a new PNG file with their user name. That's why I'm looking for a dynamic solution for this problem. I already found classes how to add a png file as a watermark to images, but like I said before this won't work if my site is visited by a lot of users. I hope someone knows a way how to solve this and get the same effect on images dynamically. Thank you very much.
The documentation of the ImageMagick image processing library includes such a transparent watermark example. Even if you would like to use GD instead of ImageMagick, it might give you an idea of how to do it.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 6, "tags": "php, image processing, gd, imagick" }
EditText loses focus on Scroll in RecyclerView I have a `RecyclerView` which have `EditText` as its list items. When i scroll the `RecyclerView`, the `EditText` loses focus when the item goes off screen. So the focus does not remain on the `EditText` when it comes back on the screen on scroll. I want the focus to remain on the same item. For that i also tried storing `position` of the item on focus and reassigning the focus in `onBindViewHolder`. But that slow downs the scrolling. I also tried this with `ListView` but there is another kind of `focus` related problem. Focus jumps there. Have searched for this lot on SO and Googled a lot. but always found answers like `android:focusableInTouchMode="true"` and `android:descendantFocusability="afterDescendants"` which does not work. Any help would be highly appreciated.
The whole point of a `RecyclerView` is to reuse the views so that the phone doesn't have to keep all the rows in memory at once and doesn't have to be constantly destroying and creating views. When your `EditText` leaves the screen, the phone takes that view, resets its contents and moves it to the bottom of the incoming view stack. ![RecyclerView diagram]( This means that once your `EditText` leaves the screen it no longer exists. It cannot keep focus because it is removed from the layout. The only way around this would be what you mentioned, which is storing the position, checking when that position comes onscreen, and manually restoring focus.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 9, "tags": "java, android, listview, android recyclerview, setfocus" }
Box.Net users-on-behalf-of-enterprise-user working In Box developer document they ask to contact them with the API key generated. Reference: < Is there is any api(Java) to get the other users mail box with the admin credential.
The primary purpose of "on-behalf-of" is to make calls on behalf of your company's users as an administrator. A great use case is if you'd like to prepopulate your new hire's account with a set of folders before they start on day 1. In order to get the listing of enterprise users in your account, you would use the following API call if you are an administrator: < This is currently not built into the Java SDK, but it is open source if you want to submit a pull request to it to add the functionality.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "box api" }
Foreach over certain part of a loop Let's say I have the following `String` array. String[] arr = {"Index0", "Index1", "Index2", "Index3",..."Index n"}; I can iterate over the **entire** array using: for (String eachElement : arr){ //Do something } But what if I wanted to do a `foreach` over a certain part of the array. I know that I can do something like this with a for loop: int startingIndex = 1; int endingIndex = 3; for (int i = startingIndex; i < endingIndex; i++){ //Do something } Is there a way I could do something similar using `foreach` loop?
you can use for(String eachIndex : Arrays.copyOfRange(arr, startingIndex, endingIndex)){ //Do something }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "java, arrays, foreach" }
What php framework should I learn? I have been making web applications for a couple years with the standard php/html/javascript/css. I have recently started using jquery with javascript and that made me realize how great frameworks can be. I am looking into learning a php framework and am not sure where to start. So far I have read about Zend Framework and Symfony and they both sound good but also look hard to learn. Which framework is best for beginners that will also aid in learning proper MVC structure.
You won't get very far on other people's personal preferences (the answers you'll find here). Instead dive into a couple and choose one you like. Think about it like shopping for a car. Shop around, test drive, find one you enjoy and is reasonably well supported.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php" }
When I login then error will be ocuurred "It was not possible to parse your key, reason". (Laravel api) `{"message": "It was not possible to parse your key, reason: "}` I also tried `composer update` command and `composer require` laravel/passport and `php artisan passport:install`. But the same error is still occurring. Please suggest me what is the solution for this error.
If I changed the version of PHP and it's work.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "laravel, authentication, laravel passport" }
Simple second order differential equation of the form $f''(x)+ h(x) = 0$ **The problem is as follows:** The movement equation for a pendulum for some mass hanging in a weightless thread with the length $L$ is as follows: $$\frac{d^2a}{dt^2} + \frac{g}{L}\sin(a) = 0$$ Where $a$ is the starting angle (in radians) and $g$ is the acceleration of gravity. Determine the position of the pendulum after a second if $L = 0.2$m and if the starting angle of the pendulum is $3$ degrees and the velocity is $0$m/s. You may also use the approximation $\sin(a) = a$. **My thoughts on it** Well, why not just move over the $(g/L)\sin(a)$ term to the right hand side and find the indefinite integral of both sides twice? I'm pretty sure that's not what you're supposed to do however and I'm frankly stumped. All the problems I've done so far has been of the form $f''(x) + f'(x) + f(x) = 0$. **The answer provided is:** $a = (\pi/60)\cos\sqrt{5g}$ which is approximately $2.26$ degrees.
Using the small angle approximation i.e $\sin a \approx a$ we find $$ \ddot{a} + \sqrt{\frac{g}{L}}a = 0 $$ solutions to the above have the form $$ a(t) = A\sin\left(\sqrt{\frac{g}{L}}t\right) + B\cos\left(\sqrt{\frac{g}{L}}t\right) $$ and now we can place i.c into the solution $$ \dot{a} = A\sqrt{\frac{g}{L}}\cos\left(\sqrt{\frac{g}{L}}t\right) - B\sqrt{\frac{g}{L}}\sin\left(\sqrt{\frac{g}{L}}t\right) $$ at $t=0$ we find $$ \dot{a}(t=0)= A\sqrt{\frac{g}{L}} = 0 \implies A = 0 $$ thus the solution is of the form $$ a(t) = B\cos\left(\sqrt{\frac{g}{L}}t\right) $$ now since we have $a = 3^{\circ} = \frac{180^{\circ}}{60^{\circ}} = \frac{\pi}{60}$ we find $$ a(t=0) = B = \frac{\pi}{60} $$ therefore we have the solution $$ a(t) = \frac{\pi}{60}\cos\left(\sqrt{\frac{g}{L}}t\right) $$ now we need to find $a(t=1)$ plugging that in, and $L=0.2$, we find $$ a(t=1) = \frac{\pi}{60}\cos\left(\sqrt{\frac{g}{0.2}}\right) = \frac{\pi}{60}\cos\left(\sqrt{5g}\right) $$
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "calculus, ordinary differential equations" }
About digamma function Show that $F(z)$ has the series expansion $\displaystyle F(z)=-\gamma + \sum_{n=2}^{\infty }(-1)^n\zeta (n)z^{n-1}$ where $\displaystyle \zeta (n)$ is the Riemann zeta function.
We start with the identity of the digamma function > $$ \psi(z+1) = -\gamma + \sum_{n=1}^{\infty}\frac{z}{n(n+z)}\quad z\neq 0,-1,-2,-3,\dots$$ which implies that $$ \psi(z+1) = -\gamma + \sum_{n=1}^{\infty}\frac{z}{n^2}\left(1+\frac{z}{n}\right)^{-1} $$ $$ = -\gamma + \sum_{n=1}^{\infty}\frac{z}{n^2}\sum_{m=0}^{\infty}\frac{(-z)^m}{n^m}= -\gamma + \sum_{m=0}^{\infty}(-1)^m {z^{m+1}}\sum_{n=1}^{\infty}\frac{1}{n^{m+2}}$$ $$ = -\gamma + \sum_{m=0}^{\infty}(-1)^m \zeta(m+2){z^{m+1}} $$ > $$ \implies \psi(z+1) = -\gamma + \sum_{m=2}^{\infty}(-1)^m \zeta(m){z^{m-1}}. $$
stackexchange-math
{ "answer_score": 4, "question_score": 5, "tags": "special functions" }
How do I create a list from raw_input in Python 2.7.2? I have to write a program that accepts a sequence of average daily temperatures and put those temperatures into a list, but I can't figure out how. What I tried below does not work. Instead of giving me a list it just gives me the last input. def main(): #create a list to store the temperatures. tempList = [] while True: dailyTemp = raw_input( "Enter average daily temperature or -100 to quit: ") # assign dailyTemo to tempList list tempList = [dailyTemp] print tempList if dailyTemp == '-100': break main()
To append to a list, you have to do `templist.append('thingtoappend')`. In your case, you'd want something like this: tempList = [] while True: dailyTemp = raw_input("Enter average daily temperature or -100 to quit: ") tempList = tempList.append(dailyTemp) What the code that you posted does instead is, it says that the temperature that the user entered, _is_ the list - so each time they enter a new temperature, it replaces the last one they entered.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "python 2.7" }
How to read and manipulate a HTML document exported from Microsoft Word? I have a Microsoft Word Doc that was saved as a .htm web page. Below is the code I have. My question is how can I get the text from the document, and append it to a string. I noticed that the paragraph is set to a tag `<p class=MsoNormal>` so any suggestions. The string I want to append it to is documentText String documentText = ""; FileInputStream fileInput = null; BufferedInputStream myBuffer = null; DataInputStream dataInput = null; fileInput = new FileInputStream(selectedFile); myBuffer = new BufferedInputStream(fileInput); dataInput = new DataInputStream(myBuffer); while (dataInput.available() != 0){ System.out.println(dataInput.readLine()); }
Take a look at libraries such as HTML Parser and Jericho HTML Parser or use the native HTMLEditorKit.Parser \+ HTMLEditorKit.ParserCallback approach suggested on this answer.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, ms word, html parsing" }
Store specific value from csv into variable using powershell I have a csv file that looks like this "NumberofNullAsOfDates" "0" I would like to check if there is a 0 or any other value there. This is currently the powershell code I have but it doesn't seem to work out so well. $testNum = @() $testNum += Import-Csv craneAudit.csv $testNum[1] How could I make this work so that $testNum only contains "0" (without quotes)
You can cast the value to int: $intValue = [int]$testNum[1]
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "arrays, powershell, csv" }
Send data to apple watch I have apple watch series 4 and an iPhone. I want to send data like links,images,text to my watch. Usually I emailed these data to myself and open it on my watch . > Is there any efficient way to do it ? Any app or something ? My watch is constantly connected with iPhone via Bluetooth.
A simpler method would be to use Messages to send a message to yourself with the text, links, and images. They would show up as notifications on the watch making it easy to tap into them - instead of having to open up Mail, find the right mail, open attachment, etc.
stackexchange-apple
{ "answer_score": 2, "question_score": 1, "tags": "iphone, ios, apple watch, watchos" }
Why does pow output 0 even when using %f? I am completely new to c, so I was trying to use the pow function as I'm following a tutorial. On the tutorial (and I followed the code exactly as they wrote it), their output is correct, but all I get is 0.000000. Does anyone know why this happened? #include <stdio.h> #include <stdlib.h> int main() { printf("%f", pow(4, 3)); return 0; } Output 0.000000
Insert `#include <math.h>`, turn on warnings in your compiler, pay attention to warning messages, and promote warnings to errors. Without `<math.h>`, `pow` is not declared, and `pow(4, 3)` passes arguments as `int`. `pow` needs its arguments passed as `double`, the behavior when they are passed as `int` is not defined by the C standard. Further, the return type of `pow` will be assumed to be `int`, but the actual return type is `double`, and the behavior of the function call with this mismatch is also not defined. And passing an `int` value for a `printf` conversion of `%f` also has behavior not defined by the C standard.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 0, "tags": "c, pow" }
Story Identification: Novel/Short Story set in space with a mesh-like satellite I remember reading this at my local library whilst I waited for my brother. I think it was in a book with a few other short stories. What I can remember: * Some sort of mesh/net/grid shaped satellite orbiting earth, and it was malfunctioning. I'm pretty sure it was a communication satellite of some form. * It has two protagonists in their teens. I don't know how or why they were in space, but they were. * They fix the satellite against some guy's orders to stay away from it. * I think they 'live' in space, i.e. they haven't come for a trip from Earth, they actually live on a space station nearby the mesh (I remember this because they travel to it from wherever they are). * There were some bad guy(s) causing the malfunction. It was a pretty worn book, so I'm thinking it was written earlier than the 90s (I read it in 98/99).
This sounds like _The Planetoid Grid_ by Nicholas Marrat, published in the anthology _A Book of Boys' Stories_ by Robert Bateman and Nicholas Marrat, which was not exclusively science fiction. The boys were "Space born scouts" named Bluey and Tinder. Two other plot details that I remember: * One of the boys uses the phrase "go swallow a spheroid" as an insult. * The satellite used rubies to transmit sound at the speed of light, and was malfunctioning because the bad guys were stealing them.
stackexchange-scifi
{ "answer_score": 4, "question_score": 6, "tags": "story identification, short stories, space" }
keep x rows and delete all from csv file I want to be able to specify how many rows I want to keep and delete the rest, also preserving the header. I found some code which let's you delete the first 5 rows but how can I make it do what I want? with open ('myfile.csv', 'wb') as outfile: outfile.writelines(data_in[1]) outfile.writelines(data_in[5:]) For example if I have this CSV 6.5, 5.4, 0, 000 6.5, 5.4, 1, 610 1.2, 4.0, 0, 530 3.2, 5.4, 1, 330 4.2, 3.0, 0, 320 5.5, 2.3, 1, 780 1.3, 4.4, 0, 520 5.3, 1.0, 0, 420 I just want to specify a number to my script... let's say (2) and it will KEEP 2 rows and remove all others output would become: 6.5, 5.4, 0, 000 6.5, 5.4, 1, 610 Can i also make it save it with a different name?
If you first read your original CSV-file into variable `data_in` with commands with open('my_original_file.csv') as inp: data_in = inp.readlines() you may continue: n = int(input("How many rows after header you want to write: ")) with open('myfile.csv', 'w') as outfile: outfile.writelines(data_in[:n+1]) This will write * the header row — `data_in[0]`, and * subsequent n rows — `data_in[1]` to `data_in[n]`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, pandas, csv" }
Same instance with two ids in Spring Is there any way to use two different ids for referring to the same instance in a Spring context? What I'm trying to find is a way for aliasing the bean id, for a singleton scope.
< **Bean Names** section > the name attribute may be used. Also note that name accepts an array of Strings. This is in order to allow for specifying multiple names (i.e., aliases) for a single bean. @Bean(name={"b1","b2"}) // bean available as 'b1' and 'b2', but not 'myBean' public MyBean myBean() { // instantiate and configure MyBean obj return obj; }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, spring" }
Default Eclipse Theme for Android Development Spinners? The color of my Spinner widgets change from phone to phone based on there settings,I would like to keep them the same between all phones and I would like to have it be the default eclipse uses in its emulators the color is silverish. Can you please let me know how to apply this specific theme to my Spinner in xml. Thanks in advance.
download the images used in for the spinner from the android source code: spinner_press.9.png, spinner_select.9.png, spinner_normal.9.png then create selector using those. this is the default selector: <selector xmlns:android=" <item android:state_pressed="true" android:drawable="@drawable/spinner_press" /> <item android:state_pressed="false" android:state_focused="true" android:drawable="@drawable/spinner_select" /> <item android:drawable="@drawable/spinner_normal" /> </selector>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "android, xml, android xml" }
What's the best way to implement AutoComplete in the server? This question is easy people. Make autocomplete beautiful in the client side of a web app is simple. There are a lot of plugins. But, in the backside, in the server side, what's the best way to do it? I don't like the idea to hit the DB with each keypressed by the user. I've been thinking about sphinx, or some full-text search engine running parallel from your site. For example, if i have a PHP (high traffic) web site, i can create a parallel python script that get http requests from my "autocomplete textboxes". Then, when a user is pressing a key in the client side, the AJAX requests are directed to that python script that can use a special strategy. What's your aproach? Some conventions: * Try not to hit the DB. I mean, get the request and do something SELECT * FROM foo WHERE bar LIKE "req%" is not a good answer. It may be a good strategy, but i know how to do it.* * Replicated data can be a good choice.
I do agree that you need to have some better solution. Apache solr has a "suggestion" feature that you can use pretty well. If your data set is small then put all the data in memory and just do a simple loop. On the front end, I recommend using setTimeout() to wait for about 200ms before firing the ajax call. If in that 200ms, another keystroke is triggered, then cancel the last timeout and start another one. This is a really clean solution where it wouldn't hit the db with each keystroke. I have used it in the past and it works really well. This explains solr with jquery and how to create an autocomplete really well. <
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "database, performance, optimization, autocomplete, full text search" }
Build debian preseed after the options selected on a normal installation Is there any way to build the pre-seed file based on the options I've chosen manually, instead of writing one from scratch?
You can use a command like `debconf-get-selections --installer` on a installed system to dump most of the configuration used to build that system. This file probably will need to be adjusted a bit, but it will give you a pretty good starting point. * <
stackexchange-superuser
{ "answer_score": 2, "question_score": 0, "tags": "debian, unattended" }
Evaluating $\int_2^4\frac{\arctan x}{\log x}dx$ I've been trying to improve my integration techniques, and I came up with the following integral which I thought I could solve with Feynman Integration $$I=\int_2^4\frac{\arctan x}{\log x}dx$$ Here's what I've tried so far: $$F(a)=\int_2^4\frac{\arctan(x^a)}{\log x}dx$$ $$F'(a)=\int_2^4\frac{\partial}{\partial a}\frac{\arctan(x^a)}{\log x}dx$$ $$F'(a)=\int_2^4\frac{x^a}{x^{2a}+1}dx$$ $x=\tan u$: $$F'(a)=\int_{\arctan2}^{\arctan4}\frac{\tan^au\sec^2u}{\tan^{2a}u+1}du$$ $$F'(a)=\int_{\arctan2}^{\arctan4}\frac{\frac{\sin^au}{\cos^{a+2}u}}{\frac{\sin^{2a}u}{\cos^{2a}u}+1}du$$ $$F'(a)=\int_{\arctan2}^{\arctan4}\frac{\sin^au\cos^{2a}u}{\cos^{a+2}u(\sin^{2a}u+\cos^{2a}u)}du$$ $$F'(a)=\int_{\arctan2}^{\arctan4}\frac{\sin^au\cos^{a-2}u}{\sin^{2a}u+\cos^{2a}u}du$$ Which I don't know how to handle. How do I integrate this? Thanks.
NOTE: The following is a partial but incomplete answer. * * * Consider $$F(a) = \int_2^4 \frac{\arctan(x)}{\ln(x)}x^a\,dx.$$ Then $$\frac{d}{da}F(a) = \int_2^4 \frac{\partial}{\partial a} \frac{\arctan(x)}{\ln(x)}x^a\,dx = \int_2^4 \arctan(x) x^{a}\,dx .$$ Note that $$\int \arctan(x) x^{a}\,dx = \frac{\arctan(x) x^{a+1}}{a+1} - \frac{1}{a+1}\int \frac{x^{a+1}}{1+x^2}\,dx.$$ From Wolfram alpha%2F\(1%2Bx%5E2\)+from+2+to+4), we have $$\int \frac{x^{a+1}}{1+x^2}\,dx = \frac{1}{2} i^{-a} \left( B(-4; \frac{a}{2}+1,0) - B(-16; \frac{a}{2}+1,0) \right)$$ where $B(z;a,b)$ is the incomplete Beta function. Then we have $$\frac{d}{da}F(a) = \frac{\arctan(4)4^{a+1} - \arctan(2)2^{a+1}}{a+1} - \frac{i^{-a}}{2(a+1)}\left( B(-4; \frac{a}{2}+1,0) - B(-16; \frac{a}{2}+1,0) \right).$$
stackexchange-math
{ "answer_score": 4, "question_score": 1, "tags": "real analysis, integration, definite integrals" }
How to secure an array field so Parse users can add objects without allowing malicious changes? I understand the concept of only allowing Parse users to access to their own data. But how do you secure fields where you want users to have the ability to add or join, but not the ability to delete or make other changes? Let's say you wanted users to have the ability to join a group or post in a thread. They would need write access to these objects, but wouldn't that open up potential malicious activity. How should I go about securing these fields?
You put this data in an object with 'public' read and master only write status, so no user can write directly to it, but any user you need to can read from it. The read status could also be by role, or specified users. Now you create a cloud function to do the writing. That cloud function does whatever validation you need, checking the logged in user and any parameters that are passed and then updates the object, because it has access to `useMasterKey` so it can have the required privilege.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, objective c, parse platform" }
sql query to view the associations I attended an interview recently and they gave me the following scenario in SQL: **Employee table:** Employee{ empId, name } **Department Table:** Department{ depId, depName } **Employee Department Table:** EmployeeDepartment{ empId depId } I was asked to print the result with the following details : EmpID EmpName DepName DepID I could not think of any solution there. I tried going thru some SO answers but could not understand how they work. Some answers suggest the usage of EXISTS and some use JOINS. But I still can't figure out how this is supposed to work. Can anyone please tell me how to write the sql query to achieve this with and without the association table ? Specifically without using any JOINS?
select e.EmpID ,e.EmpName ,d.DepName ,d.DepID from EmployeeDepartment ed inner join Employee e on ed.EmpID = e.EmpID inner join Department d on ed.DepID=d.DepID I can't see why you would use no joins, The solution below still joins, just in a silly way: select ed.EmpID ,(select top 1 EmpName from Employee e where e.Empid=ed.Empid) EmpName ,ed.DepId ,(select top 1 DepName from Department d where d.DepId=ed.DepId) DepName from EmployeeDepartment ed
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql" }
How Many Starttest() and StopTest() can I have in One Test Class? The concept of testing org is still very new to me. I don't think I fully understand it. But can I've more than one StartTest() and StopTest() in my test class as my test requires many cases to ensure my codes have coverage? @isTest private class TestSFParSched_Class{ //Case1 static testmethod1 void test() { test.StartTest(); test.StopTest(); } //Case2 static testmethod2 void test() { test.StartTest(); test.StopTest(); } } Thanks
You can have one `StartTest` / `StopTest` per test method. Each test method is executed independently. They may be on the same class but they share nothing and do not see side effects from each other. You can have many test methods in any test class 99.9% of the time. The 0.1% allows for features like `Queueable` interface that currently require their own class. There are two main use cases for `StartTest` / `StopTest`. 1. `StartTest` resets all governor limits. In this way you can set up your test data and still clearly determine the impact of your functionality on relevant governor limits. 2. `StopTest` forces asynchronous calls to execute. Using this method will allow you to guarantee an asynchronous call or batch has run. There are also stylistic benefits; for AAA style tests (Arrange, Act, Assert) it is a great way to identify where the Act happens. This helps a reader to know what you intend to test.
stackexchange-salesforce
{ "answer_score": 24, "question_score": 10, "tags": "unit test, scheduled apex" }
What can be the causes of $(document).on( "click") not firing? I have a fairly large script and am trying to find out, why $(document).on( "click", function( event ) { alert("hello"); } Is not firing. Is there an easier way to find out why this is not working than removing all other click bindings throughout the script? Also, I have heard that namespacing is a nice way of keeping event bindings restrictive to a certain plugin. If so, how would I have to setup event bindings for certain event groups? Do I just replace `click` with `click.thisGroup`?
Without a complete code, I can only guess some possibilities.: 1. syntax error; you are not closing your handler function definition on your sample code 2. the element you are clicking has a call to `stopPropagation()` or `stopImmediatePropagation()` which prevents bubbling to document thus preventing your on event attached to document
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jquery, events, jquery events" }
How does Azure Bot Channel Registration authenticate my Teams app When I create a Bot Channels Registration service in Azure, and then create a Teams app that will use that, how is the Bot Channel Registration being informed what apps it should allow to go through?
It does not authenticate the MS Teams app. Any app can point to any Bot Channels Registration or Azure Bot, it's up to the bot backend to validate the source of the message if desired. Like using one of the links in the comments of the previous answer.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "botframework, microsoft teams, azure bot service" }
Extract partial text from element link with python/selenium In the below HTML, my goal is to return **zzde7e35d-8d9d-4763-95d2-9198684abb12** <div class = container> <a class="Blue-Button" data-type="patch" data-disable-with="Waiting" href="/market/opening/zzde7e35d-8d9d-4763-95d2-9198684abb12">Yes</a> </div> The problem is, I can't even seem to locate the URL within the div from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager link = example.url driver.get(link) URL = driver.find_element_by_xpath('//a[contains(@href,"market")]') print(URL) Printing the above, I seem to get a bunch of random characters unrelated to the HTML at all, let alone the URL in question. If it simplifies the issue, the number of characters that are returned will always be the same length, is indexing an easy work around?
If you want to get the `href` you need to use `get_attribute('href')` this will give you `/market/opening/zzde7e35d-8d9d-4763-95d2-9198684abb12` and then split() this and you will get the last element. link = example.url driver.get(link) URL = driver.find_element_by_xpath('//a[contains(@href,"market")]') print(URL.get_attribute('href').split("/")[-1]) Output: zzde7e35d-8d9d-4763-95d2-9198684abb12
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, selenium, selenium chromedriver" }
Getting "Field data loading is forbidden" when trying to aggregate I'm trying to do a simple unique aggregation, but getting this error: java.lang.IllegalStateException: Field data loading is forbidden on eid this is my query: POST /logstash-2016.06.*/Nginx/_search { "query": { "bool": { "filter": [ { "term": { "pid": "1" } }, { "term": { "cvprogress": "0" } }, { "range" : { "ServerTime" : { "gte" : "2016-06-28T00:00:00" } } } ] } }, "aggs": { "distinct_colors" : { "cardinality" : { "field" : "eid" } } } }
After going through the entire thread at < what worked was adding .raw like this: "aggs": { "distinct_colors" : { "cardinality" : { "field" : "eid.raw" } } }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "elasticsearch" }
If Kira is killing criminals, why did crime persist? In death note, Kira (all those who killed criminals for Light) started to kill criminals in order to build his utopian crime free world. It is understandable why crime would persist in the beginning, but after a year or so why didn't most crime cease? Surely if you know that if you commit a crime and know you're going to die, you would be less likely to commit that crime? Was there a reason as to why crime persisted?
The same reasons that crime persists even in regions where the punishment is torture, maiming, and death: 1. Some believe that their crimes are justified, so they won't be punished. 2. Some believe they won't get caught, so the severity of the punishment is irrelevant. 3. Some commit crimes on a whim, without any thought of consequence. 4. Some have no choice (or believe they have no choice) but to commit a crime. 5. Some believe that their crime (such as revenge killing) is worth suffering any penalty. The list goes on, but it boils down to this: there are billions of people on the planet, and the human brain is very quick to toss rationality out the window in many circumstances, so there are going to be many people behaving irrationally at any given moment; no threat can change that.
stackexchange-scifi
{ "answer_score": 11, "question_score": 4, "tags": "death note" }
Creating progress bar for file upload and moving it to Amazon server I am working on image upload functionality in PHP where i will show the upload progress bar using **`swfuploader`** while uploading. But the problem is after uploading the image, i am creating some thumbnail of the image uploaded(which will take some negotiable time) and moving the original image to Amazon server. But the progress bar showing is only for uploading to our server and not for uploading to amazon server. What i need is a way to show the progress bar which should includes the moving of the image to _Amazon server_ also. Any suggestions on this would be greatly appreciated.
Pipe Viewer will let you monitor the progress of almost any process. From that you can feed the progress into a display of your choice, I'd suggest jQuery Progress Bar as it is very versatile, easy to set up and has plenty of example tutorials in case you get stuck
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php, amazon s3" }
A word for eating and drinking, and a word for taking a substance Is there a single word that describes act of drinking and/or eating? And is there a single word that describes the act of taking a substance?
The most common word for it is consume \- to eat or drink something Try ingest \- it means to take (food, drink, or another substance) into the body by swallowing, eating or absorbing it.
stackexchange-english
{ "answer_score": 9, "question_score": 4, "tags": "single word requests" }
moving vector from class (vs 2013 compiler) I want to move vector from class class Data { public: std::vector<int> && getValues() {return std::move(values);} private: std::vector<int> values; }; I use vs2013 complier and, as i know, it does not support ref-qualifiers. How can I move safety? Data d; std::vector<int> v1; std::vector<int> v2; ... v1=d.getValues(); //i want copy v2=std::move(d.getValues()); // i want move
Just return by normal reference: class Data { public: const std::vector<int>& getValues() const {return values;} std::vector<int>& getValues() {return values;} // And if you really want to move member, you may do std::vector<int> takeValues() {return std::move(values);} private: std::vector<int> values; }; Then you may use Data d; std::vector<int> v1; std::vector<int> v2; //... v1 = d.getValues(); // copy v2 = std::move(d.getValues()); // move // Or alternatively: v2 = d.takeValues(); // move
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c++, visual studio 2013, move semantics" }
Join expression not supported - VBA error I have the following VBA script: Private Sub CmbTermLookup_AfterUpdate() Dim BusinessTerm As Integer Dim SqlString As String If IsNull(Me!CmbTermLookup) Then Me!CmbTermLookup = "" Else BusinessTerm = Me!CmbTermLookup End If SqlString = "SELECT TblBusinessTerm.BusinessTermID, TblBusinessTerm.BusinessTerm, TblField.FieldID, TblField.FieldName," _ & " TblField.FieldDescr, TblField.TableID" _ & " FROM TblBusinessTerm INNER JOIN TblField ON TblBusinessTerm.BusinessTermID = " & BusinessTerm Me.RecordSource = SqlString End Sub I get the error - JOIN EXPRESSION NOT SUPPORTED. When I run the sqlstring in a query though it works. Any ideas why? Thank you
You need to specify a field in each of the two tables to join the tables on, and then you need to specify a `WHERE` clause if you only want certain records: SqlString = "SELECT TblBusinessTerm.BusinessTermID, TblBusinessTerm.BusinessTerm, TblField.FieldID, TblField.FieldName," _ & " TblField.FieldDescr, TblField.TableID" _ & " FROM TblBusinessTerm INNER JOIN TblField ON TblBusinessTerm.BusinessTermID = TblField.BusinessTermID " _ & " WHERE TblBusinessTerm.BusinessTermID = " & BusinessTerm
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "vba, ms access" }
How to call from code like that button clicked? I have in code implement `ActionListener` for `JToggleButton`. How to call from code like that button clicked? (similar in javascript from code I can do `$('button').click();`) How to do this in Java?
For `JButton` we have `button.doClick()`, inherited from `AbstractButton`. So, we should have `doClick()` for `JToggleButton()` as well, since that is also derived from `AbstractButton`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "java, swing, action, jbutton, actionlistener" }
сгруппировать столбец в массив Postgresql Цитата есть таблица id_m (int), id_t (int) которая обеспечивает связь многие-ко-многим. Нужно выбрать id_m у которых id_t полностью пересекаются с заданными в запросе. например: id_m | id_t ------------- 1 | 1 1 | 2 3 | 1 в ответ должен попасть id_m=1 при запросе id_t = {1,2} (и не попасть id_m=3, потому что у него нет id_t=2) Как это лучше сделать? сначала подумал можно сделать таблицу id_m | array(id_t) as t а потом сравнить два массива - t и {1,2} Но тут вопрос - как составить запрос, который бы собрал соответствующие id_t в массив. или может какой-то более элегантный способ
select id_m from some_m2m group by id_m having array_agg(id_t) = '{1, 2}';
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "sql, массивы, postgresql" }
Passing data in application/x-www-form-urlencoded in HttpClient * Passing data from **POSTMAN** as **x-www-form-urlencoded** * Key and values are as follows: data : P1;P2 format : json Corresponding curl code from POSTMAN curl --location --request POST ' \ --header 'content-type: application/x-www-form-urlencoded' \ --data-urlencode 'data=P1;P2' \ How to send the data as x-www-form-urlencoded on HttpClient?
1. Use < for curl commands to C# code using (var httpClient = new HttpClient()) { using (var request = new HttpRequestMessage(new HttpMethod("POST"), " { var contentList = new List<string>(); contentList.Add($"data={Uri.EscapeDataString("P1;P2")}"); contentList.Add($"format={Uri.EscapeDataString("json")}"); request.Content = new StringContent(string.Join("&", contentList)); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); var response = await httpClient.SendAsync(request); } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -2, "tags": "asp.net core, httpclient, x www form urlencoded" }
How to put constant in an array in php I need to get the count of the authors on the WordPress page. First of all, this question does not touch WordPress syntax or something more about this CMS. The question is strictly about `php` algorithms. So, I have the `10` elements get by the method `foreach`. And now I must put they in the array `$getcount` to get they count by array method `count` in `php` language. For some reasons method `count` does not work, because I always get the `else` result. <?php foreach ($coauthors_meta as $key ) : $getcount = array($key); if (count($getcount) > 1) echo '<div class="privv">Hello!</div>'; else echo 'Empty'; <?php endforeach; ?> P.S. Array method `foreach ($coauthors_meta as $key )` work fine and dispay all authors on the page. So the problem is hidding in other thing.
You are creating an array with one element every time and then checking to see if it has more than one element. <?php foreach ($coauthors_meta as $key ) : $getcount = array($key); // << always makes an array with one element // count will always be 1 so the else condition will always happen if (count($getcount) > 1) echo '<div class="privv">Hello!</div>'; else echo 'Empty'; <?php endforeach; ?> Change : $getcount = array($key); To $getcount[] = $key;
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": -1, "tags": "php, arrays, wordpress" }
eslint - how to set the sourceType for a specific file Is there a way in eslint to set the sourceType within the file similar to the rules and environment settings? Something like /*eslint sourceType: "module"*/ does not seen work
One of the team members of eslint confirmed that this is currently not supported and the only way to set the sourceType currently is by using the configuration files.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 14, "tags": "javascript, eslint" }
What is the ^@ symbol at the end of my output txt file? I wrote c++ code to read from a text file and then bash code to output it to another file (specifically './executable &> output.txt'). When I print it on the command line it looks fine, but when I check the output file, it has a '^@' symbol at the end of it.
You have a bug in your program, it's writing a nul character at the end of your file. Then whatever tool you use to check the output is using: caret notation for non-printable characters. * `^@` is the notation for the nul character. We cannot tell more without seeing the code.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "c++, bash, terminal" }
Who decided the default shell prompts in Linux? There are a couple of defaults in the standard Linux shell, bash, that I think need some history brought out. This question is about the prompt. The default prompt in bash in many Linux distros is `[\u@\h \W]\$` For those who can't parse that, it looks like this for a typical user: [staticsan@walcen files]$ _ The biggest problem with this is that it only tells you the name of the current directory. "files" could just as easily be `/var/www/files/` as `/home/staticsan/files` (and that's a simple example). A full path makes more sense, so I have to change it every time I setup a new box or create a new user. So why is the default set to what it is?
The answer is simple — it's a relic of times where terminals were 80 characters wide. Look at your own example — username & host occupies already 16 chars. With additional brackets and spaces there's 20 chars already, and we haven't counted the directory name yet. And the directories can have pretty long names, too. Your example path counts 21 chars and it's only three directories deep. In such case, on 80-char terminal that prompt will occupy half of the screen width. Of course, today terminals are wider and that's why many users & distros switch to longer prompts. But there's still some which use a narrower prompt to leave the user more space to type.
stackexchange-serverfault
{ "answer_score": 6, "question_score": 3, "tags": "linux, bash, prompt" }
Creating parse tree to determine correctness of the LL Grammar given I am have a program that will currently generate a output of tokens that is to be used for a input on this next program. It is going to be checking the correctness of the syntax of the code. I am running into issues on how I would start converting this grammar to a usable program. Below is the grammar use, how would I start going about making this. Or where are good resources to help myself learn the basics of creating my own parser. This implementation is going to be using Java, so if you could have answers corresponding to java's implementation, that would be swell > program → stmt_list $$$ > > stmt_list → stmt stmt_list | ε > > stmt → id = expr | input id | print expr > > expr → term term_tail > > term_tail → add op term term_tail | ε > > term → factor fact_tail > > fact_tail → mult_op fact fact_tail | ε > > factor → ( expr ) | number | id > > add_op → + | - > > mult_op → * | / | // | %
You should start by reading the Syntax Analysis chapter of **Compilers - Principles, Techniques, and Tools** , also known as the dragon book. The steps for checking the output tokens are: * Build the **First** and **Follow** sets. * Construct the _predictive parsing table_. * Check for multiple productions in the same table cell(A conflict) All of these steps can be found in the dragon book perfectly explained with their respective algorithms. I hope this helps. This is actually just a step before a parse, so if you got to the point of being able to check if the grammar is **LL(1)** , I recommend implementing the parse algorithm, which is just having a stack where you push non-terminals and refer to the table to produce the _AST_.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, parsing, compiler construction, context free grammar, left recursion" }
Converting all elements to strings in a list of list in Python I have a list of list which has both integers and strings inside it as their values. Now I want to convert all the values to string. My list of list looks like : (say `final_rule`) [[3, '*', 1, 4, 1], [1, 2, '*', 2, 1], ['*', '*', 3, 4, 1], [2, 2, '*', 2, 1]] And I am trying to produce an output as: [['3', '*', '1', '4', '1'], ['1', '2', '*', '2', '1'], ['*', '*', '3', '4', '1'], ['2', '2', '*', '2', '1']] I am trying the below code: new_list=[] for list_ in final_rule: #print("list_:",list_) [str(i) for i in list_] new_list.append(i) return new_list
lst = [[3, '*', 1, 4, 1], [1, 2, '*', 2, 1], ['*', '*', 3, 4, 1], [2, 2, '*', 2, 1]] list(list(map(str, terms)) for terms in lst)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
Menu of header is not on the gray bar in IE i have problems with IE8 : < Website header is not on the right position. If you open it in chrome or FF it works. 2nd problem: white area is not 960 width....
You need to properly contain your content inside your `#nav` div, you can do that by triggering the hasLayout effect on it, like so: #nav { zoom:1; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css" }
Finding the max and min in dictionary as tuples python so given this dictionary i'm trying to find the max value and min value {'Female' :[18,36,35,49,19],'Male' :[23,22,6,36,46]} the output should be in tuples for example key: (min,max) Female: (18,49) Male: (6,46)
{key:(max(d[key]),min(d[key])) for key in d} This will return {'Female': (49, 18), 'Male': (46, 6)}
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, python 3.x" }
How to enter "+" as a value in excel I need to enter the following text in a cell: +A It is important that it be without quotes. The problem is that it is reading it as a formula and automatically turning it into `=+A` and reading it as a formula. I do not want to enter this as a formula as it will give me the result `#NAME?` result. How can I accomplish this?
Simple add a single quote before: '+A
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -4, "tags": "excel" }
h2 outerWidth in IE 7 is shorter than IE 8 I have encountered a problem today when i imeplement a correction in our project. What i found is that the outerWidth for h2 in IE 7 is shorter than in IE8 (FF, Chrome etc). Here is my code: var h2width = $('.test h2').outerWidth(true) h2width is 135px in IE8 and 78px in IE7. Do you have any ideas for that? Thanks in advance! Edit : For prevent this problem, i have added the code for differenciate the browsers. if ($.browser.msie && $.browser.version.substr(0, 1) <= 7) { var h2width = $('.test h2').outerWidth(true) + 57; } else { var h2width = $('.test h2').outerWidth(true); }
Browsers render HTML differently so this isn´t that strange. Use Firebug or other development tool to view the actual size of your `h2` tag. They are most likely different. Also notice that your selector `$('.test h2')` returns a collection of matched elements.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, width" }