INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Re-enable TeamViewer autostart on Xubuntu 16.10 Once I disabled manually the auto-execution of TeamViewer at the boot time of my Xubuntu System (like suggested here) using: sudo systemctl disable teamviewerd.service How I can reactivate again it? Is it enough to run the following command? sudo systemctl enable teamviewerd.service I am asking it because I do not want to damage my OS using `sudo`.
Yes, running `systemctl enable` will enable a service, in this case `teamviewerd.service` which will allow you to remote in using Team Viewer even when the application itself isn't running.
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "xubuntu, startup, autostart, teamviewer" }
How do I serialize my result from my .each function? I have been searching for hours for answers to my problem. I'm not sure im searching for the right method but here goes anyway. I want to serialize the result i get from this: $('div.text').each(function () { console.log($(this).attr('name') + ": " + $(this).text()); }); and put it serialized into my ajax: $.ajax({ type: 'POST', url: 'send-exec.php', data: string, success: function (data) { if (data === 'success') { console.log('success'); } else { console.log('fail'); } } }); The information that I get in the console is exactly right but i don't know how to get this serialized and working with the POST function.
I would suggest creating an object and not worrying about serializing the string yourself. The error in your serializing is that the `:` should be `=` and you would need to add `&` to separate each one. Passing an object to `data` in $.ajax is more convenient and jQuery will serialize it for you var post_data ={}; $('div.text').each(function () { post_data[$(this).attr('name')] = $(this).text(); }); $.ajax({ type: 'POST', url: 'send-exec.php', data: post_data, .... })
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "jquery, ajax, serialization" }
Ruby command line script: Trying to pass variable in switch case I'm creating a ruby command line tool which has a switch case statement, I'd like to pass through variables on this switch case statement for example: input = gets.chomp case input when 'help' display_help when 'locate x, y' # this is the bit i'm stuck on find_location(x, y) when 'disappear s' disappear_timer(s) when 'exit' exit else puts "incorrect input" end Essentially I want the user to be able to type in `locate 54, 30` or `sleep 5000` and then call a function which handles the number they passed. I was wondering how I can either pass arguments from the user in a switch statement like this for my command line tool like this?
Use `Regexp` matcher inside `when`: when /locate \d+, \d+/ find_location *input.scan(/\d+/).map(&:to_i) Here we basically match whatever is `locate` followed by digits, comma, space, digits. If matched, we extract the digits from the string with `String#scan` and then convert to `Integer`s, finally passing them as an argument to `find_location` method.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ruby, regex" }
Why conflicting types for function is giving error in Clang? ![enter image description here]( I have seen a similar question like this on this site, and everyone basically said to change the function's name that was in conflict with `stdio.h`. However, I have changed every function's name multiple times and it still gives me this error. But why?
**Never post the code in the image**. The problem is that you call functions that `main()` hasn't seen before, so do: float getCelcious(void); int main(void) { ... } float getCelcious(void) { ... } Take a look here please: Function Declaration and Function Prototypes.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c, clang" }
git hook post-receive not working I trying to deploy some PHP code to the server with Git. I am using a GoDaddy server. I have created the _bare_ repository. In the `hooks` folder, I created a `post-receive` file and wrote the following code in it. #!/bin/sh GIT_WORK_TREE=/home/domain/public_html/website git checkout -f I want the git repo to move the source code that I have just pushed to the website directory in `public_html`. I changed the permission to `0775`. However, my `website` directory still remains empty. What should I do?
Perhaps it's because you spelled "`post-recieve`" wrong? It should be `post-receive` (note the i and e after the c).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "git, shell, deployment, web deployment" }
How do I add a Rich Text Field to a Custom Sitefinity Widget? How do I go about adding a RichText field to a custom Sitefinity Widget? I am using Sitefinity version 12.2 and mvc. If there are any examples that I am not finding, please link me to them! Thank you!
I've updated the previous Gist to include a content block editor in the mvc widget designer: < Check the new RichText property.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net mvc, widget, sitefinity, richtext" }
Static Formulas in Excel I have a formula in excel that looks like such: `=COUNTIF(Imports!$B$2:$B$999,"1")` It works like I want it to but part of my manipulation of the spreadsheet requires me to insert new columns in the sheet that formula is referencing. When I do that it changes the formula from column B to column C which is actually not what I want. I want it to reference column B no matter what. How would I achieve this in Excel? Thank you!
Use `INDIRECT` to reference range from its text address: =COUNTIF(INDIRECT("Imports!$B$2:$B$999"),"1")
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "excel, static, formula, countif" }
XML file creation using XElement from Class Properties I got a `List<Foo> fooList` of the class Foo which has several properties Property01 Property02 Property03 I want to create an XML like <Foos> <Foo> <Property01>value1</Property01> <Property02<value2</Property02> <Property03<value3</Property03> </Foo> <Foo> <Property01>value1</Property01> <Property02<value2</Property02> <Property03<value3</Property03> </Foo> </Foos> I tried new XElement ("Foos", fooList.Select (Foo => new XElement ("Foo", new XElement("Property01",Foo.Property01), new XElement("Property02",Foo.Property02), new XElement("Property03",Foo.Property03), ) ) ) But the Lambda expression works only for one Property.
Your code creates the expected XML. Maybe the problem is the last comma? new XElement ("Foos", fooList.Select (Foo => new XElement ("Foo", new XElement("Property01",Foo.Property01), new XElement("Property02",Foo.Property02), new XElement("Property03",Foo.Property03) // deleted comma ) ) )
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "c#, xml, lambda" }
Calculated Column Working Not Working I have a calculated column that worked in SharePoint 2007, 2010, 2013, and 2016. But now in SharePoint 2019 the calculated column is not appearing right in the column instead of showing the employees email address as a hyperlink it now shows the DIV tag info Is this SharePoint 2019? Why is this not working? =CONCATENATE("<DIV><a href='","mailto:",[E-Mail],"'>",[Full Name (First M.I. Last)],"</a></DIV>")
Sadly I think that is the way it is headed. According to this article, the June 2017 update for SP 2013 and 2016 included a switch called **CustomMarkupInCalculatedFieldDisabled**. It allowed your administrator to choose if HTML would show up for calculated fields. I can't find complete documentation, but searches seem to suggest that the switch is no longer available in 2019.
stackexchange-sharepoint
{ "answer_score": 1, "question_score": 1, "tags": "javascript, 2016, calculated column, 2019" }
Expression expected near left join... where am i wrong in this query please select `tbl_users`.`username`, `tbl_users`.`users_id`, `tbl_users`.`profile_picture`, (select count(users_id) from tbl_movies_comments where users_id = `tbl_users`.`users_id`) as UsersCommentsCount, (select count(users_id) from tbl_movies_reviews where users_id = `tbl_users`.`users_id`) as UserReviewsCount left join `tbl_movies_comments` on `tbl_users`.`users_id` = `tbl_movies_comments`.`users_id` left join `tbl_movies_reviews` on `tbl_users`.`users_id` = `tbl_movies_reviews`.`users_id` group by `tbl_users`.`username`, `tbl_users`.`users_id`, `tbl_users`.`profile_picture`, `tbl_movies_comments`.`users_id`, `tbl_movies_reviews`.`users_id`
There is no FROM clause in your query. SELECT ... FROM `tbl_users` LEFT JOIN ...
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql" }
Если введен пароль Одна строка, если в неё введен правильный пароль, перенаправить по ссылке
если мои телепатические способности меня не подводят, то алгоритм решения следующий: 1. Есть такое событие keyup. При вводе пароля в input-e срабатывает это событие 2. При каждом нажатии клавиши берем пароль и ajax-ом отправляем его на сервер и получаем ответ правильный пароль или нет 3. Если правильный, редиректим на нужную страницу с помощью location
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ссылки, пароль" }
Regex: Words with spaces into string array I have strings that I'm printing as: $string = "winter coats gloves hats blankets sleeping bags tarps milk magnesia shoes boots art"; That I need to regex into a string array, like: $newString = array ('winter','coats','gloves','hats','blankets','sleeping','bags','tarps','milk','magnesia','shoes','boots','art'); The challenge is, how to add only `'` on each end, while `','` to replace the spaces... So far I have this, which doesn't work... $string = str.replace(/\s+/g, '','',$string);
If I don't misunderstand you, simply: $array = explode(' ', $string); This will create a string array out of your string. explode() in PHP Manual What you have tried does not work because it is Javascript. If you clarify a bit what you're trying to achieve exactly, and how Javascript comes into the picture, we could help further.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, regex, arrays, string" }
What would be faster: addition w/ loop or w/o loop? What would be faster: addition w/ loop or w/o loop (C#)? I mean int a=0; for (int i=1;i<4;i++) a+=2*i; or int a=0; a+=2*1; a+=2*2; a+=2*3;
For this progression, n | 0 | 1 | 2 | 3 | 4 | 5 -------------------------------- a | 0 | 2 | 6 | 12 | 20 | 30 the closed form is, a = n(1+n); this will always be more efficient than any brute force approach. If efficiency doesn't matter then the closed form is still easier to read. If you don't have the time to work out the closed form, for all but the shortest iterations, the loop is less typing. That's why we have them in the language, right?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c#, loops, optimization" }
syntax for SOCKS proxy in apt.conf I want to add SOCKS proxy settings to /etc/apt/apt.conf. What is the syntax for it? Is it same as http and ftp syntax? Thanks.
A possible solution can be to use `tsocks`, an application that can redirect the network traffic through a socks proxy. Install `tsocks` package, modify `/etc/tsocks.conf` to set address and port number of your socks proxy, and run: $ sudo -s # tsocks apt-get update # tsocks apt-get dist-upgrade # exit $ or $ sudo -s # . tsocks -on # apt-get update # apt-get dist-upgrade # . tsocks -off # not really necessary, given the exit # exit $ You can think to a number of options, to simplify and automate its use. Don't forget the leading dot, the Manpage has more deatails on this. **Edit** : a shorter way to use it: $ sudo tsocks apt-get update $ sudo tsocks apt-get dist-upgrade
stackexchange-askubuntu
{ "answer_score": 36, "question_score": 42, "tags": "apt, proxy" }
"Corrupt member variable name" in PHP trying to access to a static function "Corrupt member variable name" exception is throw trying to access to a static function: class CachedSettings { static private $c; static private function getCacheInstance() { if(!isset(self::$c)) self::$c = phpFastCache(); return self::$c; } static public function getGroup($groupName) { $cache = CachedSettings::getCacheInstance(); ... I've tried with `self::`, with the same result. Looks like it's not a very common error. Any idea?
So, I don't see anything wrong but you might want to check out your PHP version. They recently released 5.6.x. If your localhost is different version than your server or whatever, this might be the issue. 1. Install PHP 5.6.X: `curl -s | bash -s 5.6` 2. Edit ~/.bash_profile: `open -a TextEdit ~/.bash_profile` 3. Add path at bottom of .bash_profile: `export PATH=/usr/local/php5/bin:$PATH` 4. Make bash_profile finalized: `source ~/.bash_profile` 5. Double check PHP 5.6.X is working: `php -v` If you need some more assistance on upgrading Hope this helps,
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "php, static, runtime error" }
Return mechanism about epoll_wait I've seen all epoll exmaples using `epoll_wait` like int i, n; ... n = epoll_wait(epfd, events, MAX_EVENTS, -1); for (i = 0; i < n; ++i) { do_something_with(events[i]); } I change it to int i; ... for (i = 0; i < epoll_wait(epfd, events, MAX_EVENTS, -1); ++i) { do_something_with(events[i]); } When a socket connect to this program and send something, `epoll_wait` would return only once, with the connecting action, but unable to read after that (previous version, twice, connect and read). What's the magic with it? The complete C code is at < Python client is import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 4999)) s.sendall('hello') s.close()
The changed version calls epoll_wait for every loop iteration so you are blocking again after processing only one event. You have to call epoll_wait once up front and then do the loop.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c, epoll" }
Question: How to prove this inequality I have to prove this inequality. $$\sqrt[n]{n} - 1 \lt \sqrt{\dfrac 2n} ~~\mbox{for}~~ n \gt 2$$ So far I reached this result: $$n^{\dfrac {n+2}{n}} - n^{\dfrac {n+1}{n}} + n - n^{\dfrac {n+1}{n}} \lt 2$$
In the (using the binomial theorem) expansion of $$\left(1 + \sqrt{\frac{2}{n}} \right)^n$$ there is $1$, and there is $${n \choose 2} \left( \sqrt{\frac{2}{n}}\right)^2 = n-1$$ and other $>0$ terms. So $\left(1 + \sqrt{\frac{2}{n}} \right)^n > n-1 + 1 = n$.
stackexchange-math
{ "answer_score": 5, "question_score": 1, "tags": "algebra precalculus, inequality" }
Do I need a free builder in order to build a Builder's Hut? I'll add 500 gems to my account and build a Builder's Hut, however both my builders are building something at the moment. I'm not sure if I need one to be free (as in not building something). Do I need a free builder in order to build a Builder's Hut?
You don't need a free builder. You just have to place the Builder's Hut, and it will be built immediately, just like walls, but unlike walls, Builder's Huts don't require a free builder.
stackexchange-gaming
{ "answer_score": 6, "question_score": 1, "tags": "clash of clans" }
Did any major European country stay neutral during the Napoleonic Wars? During World Wars I and II, many countries managed to stay neutral, like Spain and Switzerland. Was there any major country (e.g. not a city-state or a micronation) that did the same during the Napoleonic Wars?
I just performed some Google search that gave me the map of Europe during Napoleonic wars. Here goes the reproduction from Wikipedia: !enter image description here See the image in other resolutions here: Europe 1812 map en.png So, in Europe, in 1812, there were the following countries: 1. Great Britain - fought 2. Portugal - fought 3. Spain - fought 4. Papal States - fought 5. Kingdom of Naples - fought 6. German States - if treated as a whole (Confederation of the Rhine), fought 7. Austria - fought 8. Denmark + Norway - fought 9. Switzerland - fought 10. Prussia - fought 11. Sweden - fought 12. Duchy of Warsaw - fought 13. Ottoman Empire - fought 14. Russia - fought 15. Holland - fought I think doing just simple googling would help. Please remember that Napoleonic Wars was not one war and countries (except Great Britain) did not fight in each of them.
stackexchange-history
{ "answer_score": 12, "question_score": 6, "tags": "europe, 19th century, napoleonic wars" }
Sending Jquery UI slider values to database I have a ui slider element that I am using to let people rate a product, the purpose is to have this slider along with a button to insert the value into a MySQL table (sort of voting) my slider looks like $("#slider-range-max4").slider({ range: "max", min: 1, max: 10, value: 0, slide: function (event, ui) { $("#slider-range-max-amount4").text(ui.value); } }); $("#slider-range-max-amount1").text($("#slider-range-max1").slider("value")); How can I use a button to send the value selected by the user to mysql, do I have to embed the code into a form ? Thanks
use ajax like bellow and send the value to php $(function() { $( "#slider-range-max" ).slider({ range: "max", min: 1, max: 10, value: 2, slide: function( event, ui ) { $( "#amount" ).val( ui.value ); } }); $( "#amount" ).val( $( "#slider-range-max" ).slider( "value" ) ); $.ajax({ type:"POST", url:"your.php", data:"vote="+$( "#slider-range-max" ).slider( "value" ), success:function(response){ alert(voted); } }) }); In PHP <?php $vote=""; if(isset($_POST['vote'])){$vote=$_POST['vote']} //now do your job with MySql here ?>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery ui, jquery slider" }
Passing arguments in Python and its hierarchy Is there any hierarchy to pass arguments in python..? >>>def anyFun(a,tuple,dictionary) Should we pass int/str then tuple and then dictionary. >>>def anyFun1(dictionary,tuple,a) Should we pass int/str then dictionary and then tuple >>>def anyFun2(tuple,a,dictionary) Should we pass tuple then int/str and then dictionary. or we can pass the arguments in python as in other programming languages. Please help me on this .
My experience is python is quite limited. But as far as I know, the order you pass the arguments to a function won't really 'cause any major effects.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python 2.7" }
prepareForSegue not working as expected I have set up a view in which a user can pick a photo and then use it as their profile picture. Once they picked the image a UIImageView is supposed to be updated. I use the prepareForSegue method in order to pass the information on to the view controller which contains the image view. However, the image never gets updated when I pass something forwards. This is my code: -(void)prepareForSegue(UIStoryboardSegue *)segue sender:(id)sender{ if ([[segue identifier] isEqualToString:@"UploadSuccessSegue"]) { UploadSuccessViewController *usv = (UploadSuccessViewController *) [segue destinationViewController]; usv.bookView.image = self.uploadedImage.image; } } Any help help would be greatly appreciated.
Yep, GTSouza hit the nail on the head. So you want to create a property to hold your `UIImage` reference in `UploadSuccessViewController.h`, e.g.: @property (nonatomic, strong) IUImage *bookImage; then your prepareForSegue can populate it: -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([[segue identifier] isEqualToString:@"UploadSuccessSegue"]) { UploadSuccessViewController *usv = [segue destinationViewController]; usv.bookImage = self.uploadedImage.image; } } Then the `UploadSuccessViewController` `viewDidLoad` can use it: self.bookView.image = self.bookImage;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "iphone, ios" }
Compare two List<string> using LINQ in C# What is the best way to compare two lists based on **values** , **order** and the **number of values**. So all of the lists below should be different. var list1 = new List<string> { "1", "2" }; var list2 = new List<string> { "2", "1" }; var list3 = new List<string> { "1", "2", "3" };
How about using `SequenceEqual`. See < var a = new [] { "1", "2", "3" }; var b = new [] { "1", "2" }; var c = new [] { "2", "1" }; Console.WriteLine(a.SequenceEqual(b)); // false Console.WriteLine(a.SequenceEqual(c)); // false Console.WriteLine(c.SequenceEqual(b)); // false It comes from the namespace `System.Linq` and can be used on any `IEnumerable`. You can also pass it an `IEqualityComparer` to for example also do: var d = new [] { "a", "B" }; var e = new [] { "A", "b" }; Console.WriteLine(d.SequenceEqual(e, StringComparer.OrdinalIgnoreCase)); // true
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "c#, linq, list" }
What is the purpose of express in socket.io? I apologize for this novice question, what is the purpose of express in socket.io and why we need to require express in creating chat application?.can we just use socket.io API to create chat application ? Thank you in advance.
Express is an micro-framework for creating Web Applications with Node.js. You could think of it as a "Ruby on Rails" extremely lightweight alternative. You use it with Socket.io because you normally need a base for starting creating an web app. Express is usually the common choice, but there are others like Sails.js. You could use plain Node.js API to create an application with Socket.io too.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, express, socket.io" }
F# command-line compiler: setting the CPU architecture Is it possible to compile an F# program from the command line for a specific architecture, _without a project file or using MSBUILD_?
`--platform:[x86|Itanium|x64|anycpu]` For example: `fsc --platform:x86 ...` See here for the full set of options.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": ".net, f#, x86, x86 64" }
The file name does not save to database I have a form for inserting new article .my problem is in saving the full path of picture to database.The picture is successfully uploaded to a folder and I can get the path of picture without its name and extension.can you tell me what is wrong with my code? Thanks. I take the upload path with this function: $path=dirname($_SERVER['SCRIPT_FILENAME']).'/upload'; $data=array('upload_data'=>$this->upload->data()); $upload_path=$path.$data['upload_data']['file_name']; when I echo the echo $data['upload_data']['file_name']; it shows nothing.
Finally I use this way to save the full path of uploaded image to database: $path=dirname($_SERVER['SCRIPT_FILENAME'])."/upload/".$_FILES['pic']['name']; now it works well.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "codeigniter, upload" }
Bring an Activity to the front using Android TaskManager I am running into an issue with bring up an `Activity` to the front. 1. When the app is launched the user sets some time (Activity 1) 2. Now the app shows a count down time with time decreasing (Activity 2) 3. Now I press the home button. 4. Choose Task Manager, select my app shown in the list and select "Switch To" to bring the app to the front, instead of Activity 2 it ends up on the Activity Screen 1. What can I do so the task manager switches to the most recent `Activity`?
Make sure you are not using FLAG_NEW_TASK when launching Activity 2.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "android, taskmanager" }
Which memory is being dereferenced by a struct pointer? So I'm trying to understand how pointers work, especially with structs. Here's the code I'm trying to understand struct Node { int val; }; int main() { Node* a = (Node*) malloc (sizeof(Node)); printf("%p\n", a); printf("%p\n", &(a->val)); printf("%p\n", *a); } From my understanding if I print a, it would print the memory address of what was reserved by malloc. But I couldn't figure out which memory was being printed if I dereferenced a. Here's the output. 00000000001C5D40 00000000001C5D40 00000000001C0150 I expected `*a` to be dereferencing the address of the first attribute. But as the output shows, it's not. So which memory is being dereferenced?
`*a` is the `struct Node` that `a` is pointing to. `printf("%p\n", *a);` passes the entire value of the `struct Node`. The “value” of a structure is an aggregate value composed of the values of all its members. In this case, there is just one member. And, since you did not assign any values to the member, its value is _indeterminate_. However, for `%p`, you are intended to pass a pointer to `printf` (specifically a pointer of type `void *`). When you do not, the C standard does not define the behavior. The argument-passing mechanism may go awry in various ways. It might format the value in the member `val` as if it were a pointer and print that. Or it might print some unrelated data that happened to be a register where `printf` expected to find the pointer it should have been passed. Or your program could crash.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c, pointers, struct" }
Painting rusty metal This is about 8" of metal crown molding that got rusty because water penetrated to it. I fixed the roof leak and am now repairing the inside. What can I do to prime this rusty peace of metal (maybe remove the rust?) so that it gets painted over, preferably with no or little recognition? ![enter image description here](
There are rusty metal primers available that will keep the rust from being any kind of problem. It is available in spray and brush on. Typically you will need to wire brush off any loose rust/material and paint it with that primer. After it dries the recommended time, it can be painted over with your color matched finish paint.
stackexchange-diy
{ "answer_score": 2, "question_score": 0, "tags": "painting, rust removal, rust" }
How can I set the urlseen label of biblatex? I'd like to set the default _visited on <date>_ to _accessed on <date>_ (as per my teacher's specifications). I believe I need to change the `urlseen` label to accomplish this. Is changing the `urlseen` label the way to go, and if so, how can I do this?
I found out that you can change the localization keys as described in Guidelines for customizing biblatex styles: \DefineBibliographyStrings{english}{% urlseen = {accessed on}, } See also the `biblatex` documentation under `4.9.2.15 Labels`.
stackexchange-tex
{ "answer_score": 10, "question_score": 10, "tags": "biblatex, urls" }
Selecting student language in Racket source code I am trying to write a source file for DrRacket that specifies one of the languages from **How to Design Programs Teaching Languages** (see the Racket documentation). I know I can select such a language in the DrRacket menu, but I would like to specify it using a `#lang` directive and have DrRacket recognize the language automatically. I cannot find any documentation about the strings that I need to use instead of `racket` in the initial line #lang racket Where can I find the documentation on this? Or can these languages only be selected from DrRacket's menu?
You should be able to use #lang htdp/bsl (or `htdp/bsl+`, `htdp/isl`, `htdp/isl+`, or `htdp/asl`) but it's "not in a complete shape, yet".
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 7, "tags": "racket, htdp" }
How to solve ADB error [INSTALL_FAILED_UID_CHANGED] on non-rooted phone? I get the error using the Android Studio (but I get the same if I use ADB from command line). Every solution I found says that I need to delete the installation folder on the phone: adb shell rm -r /data/data/com.example.my but I get a `permission denied` error. So what can I do on non rooted device? (I can't delete the folder from device file browser, the folder /data is empty) The app is **not listed** in the Android app manager adb uninstall com.example.my gives Failure
Unfortunately the only fix I have found for a non-rooted phone is to wipe the device and start again. The reason this is happening will be because the folder still exists with one file that wasn't deleted.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android, apk, adb" }
Знаки препинания. **Идет ли дождь, или светит солнце — ему всё равно.** Все ли знаки поставлены верно?
На мой взгляд, все верно. Запятая перед _или_ стоит, так как предложение сложное. Первый компонент (до тире) и последняя часть связаны бессоюзной связью, вторая часть имеет значение следствия.
stackexchange-rus
{ "answer_score": 2, "question_score": 0, "tags": "пунктуация" }
Can we identify Paul Benacerraf in these photos This question is about Paul Benacerraf, who worked on the philosophy of mathematics, and wrote the 1965 essay _What numbers could not be_ (see: Benacerraf's identification problem). He was at Princeton in the 1960s up to the end of the '00s, and presumably appears in at least one of the following two photos from 1968 and 1979 respectively. ![Princeton Philosophy department 1968]( Source ![Princeton Philosophy department 1979]( Source My question is, can we identify Benacceraf in either of these photos? My purpose is to use a picture of him roughly contemporaneous with the essay in a seminar for undergraduate students.
The site has legends that identify him: 4th of back row in 1968, 3rd of front row in 1979.
stackexchange-hsm
{ "answer_score": 5, "question_score": 4, "tags": "mathematicians, philosophy of science, set theory" }
Using a Pepper as the index to insert a salt In this question on this board the author of the selected answer states the following. > If you, as an attacker, manage to extract hashes and salts from a database, you probably either find a way to extract the password hashing algorithm of the website or you just create a new account with a known password, extract the hash and salt for it and brute force the algorithm that was used to compose the final hash - ckck Knowing this if we were to hard code the positioning of our salt it is just as good as placing it at the end of the password. But if we were to generate a pepper limited to the length of our password would placing our salt at that index be any better? The server will know the password so it only has to do maybe 10 or so more hash's that already only take milliseconds so it shouldn't impact login time that much.
As the scenario states, it is reasonable to assume that an attacker capable of extracting hashed from the database is also capable of obtaining the code that does the hashing. Your approach may hinder an unskilled attacker, but once they have the encryption code it is trivial to alter their cracking tool to match your algorithm. The best defence against offline brute force attacks is using a time costly algorithm like bcrypt or scrypt
stackexchange-security
{ "answer_score": 0, "question_score": -1, "tags": "encryption, passwords, hash, salt, pepper" }
Jenkins can not clone Git repository I am using GitLab and I can't cloned Git repository in Jenkins when I paste it I get this error ![enter image description here]( Can anybody help me please Edit 1: to answer to first answer ![enter image description here](
You forgot the "\git.exe" at the end of "Path to Git executable".
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, git, jenkins, gitlab" }
Translate String to operation in javascript Is there a way to translate something like the following logical operation (which uses a string due to user input)? Or will I have to check for every possibility? (> < => == =< etc.) var x = 5; var y = 3; var operator = '>' if (x operator y) doSomething(); | | v if (x > y) doSomething();
You could use eval, providing you know that it is evil. Though you should definitely check if the input is valid, for example checking if it only contains the '><=' characters.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, coffeescript, logical operators" }
Integrate MFA with ADFS with SharePoint FBA authentication, Windows authentication We have a SharePoint 2016 environment with form-based and windows authentication users. We want to integrate Azure MFA as an additional authentication method for the users. When we try to install Azure MFA on our servers we notice that providing activation on-premise MFA installation is stopped by Microsoft in July 2019. Any suggestions to complete this would be really helpful for us.
On-premises MFA server is deprecated in favor of Azure Cloud MFA. Only the existing customers that activated MFA Server before July 1, 2019 can download the latest version, future updates, and generate activation credentials as usual. You need to federate your SharePoint server with ADFS and configure Azure MFA as authentication provider with AD FS. Kindly check this link for more information.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sharepoint, adfs, multi factor authentication" }
Rotate UIView with offset I am writing a MonoTouch iOS application. I have a group of 4 UIButtons on my main View. They are more or less in a horizontal row. I want to rotate them by an angle (between -90 and +90 degrees) as a group with the right most button being the "anchor" for the group of buttons. I can't figure out how to do this. One thing I tried was I put these buttons inside of a UIView and then set the Transform to a CGAffineTransform.MakeRotation, but it rotates around the center of the UIView. I also tried making this parent UIView be wider than it needed to be so that the right most button in the group was in the center of the UIView. This worked for the rotation, but then the large blank section that was the right half of the parent UIView covers up other buttons that are on my main View that I need to be visible. So my question is how do rotate UIButtons of a UIView where the rotation is around a point that is NOT the center of the UIButton or UIView?
You can change the AnchorPoint of the view's layer, along with the Position to compensate for the shift due to setting the AnchorPoint. For example, say you had a view named ButtonGroup containing the buttons. The following code would rotate them 90 degrees about the lower left corner of the view: ButtonGroup.Layer.Position = new PointF(ButtonGroup.Frame.Left, ButtonGroup.Frame.Bottom); ButtonGroup.Layer.AnchorPoint = new PointF (0,1); ButtonGroup.Layer.AffineTransform = CGAffineTransform.MakeRotation((float)Math.PI/-2);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "uiview, xamarin.ios, uibutton, rotation" }
how to add value after every 2 elements in Python List? I want to add a specific value after every two elements in List. Ex: zz = ['a','b','c','d','f'] i want to add the word: "Hero" and the final look will be : zz = ['a','b','Hero','c','d','Hero','f'] i tried to use function insert to put an value in a specific index but it doesnt work this is my code: zz = ['a','b','c','d','f'] count = 0 for x in zz: if count == 2: zz.insert(count,"Carlos") print(x) count+=1 i think it is far away from the solution im still newbie in python
**You can try this:** letters = ['a','b','c','d','f'] n = 2 word = 'Hero' val_list = [x for y in (letters[i:i+n] + [word] * (i < len(letters) - n) for i in range(0, len(letters), n)) for x in y] print(val_list) > Here, used nested comprehensions to flatten a list of lists(`[item for subgroup in groups for item in subgroup]`), sliced in groups of `n` with `word` added if less than `n` from end of list. **Another alternative:** letters = ['a','b','c','d','f'] n = 2 word = 'Hero' for i in range(n, len(letters) + n, n + 1): letters.insert(i, word) print ( letters ) **Output:** ['a', 'b', 'Hero', 'c', 'd', 'Hero', 'f']
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "python" }
how arrayDeque.peek() Method in java working with while loop import java.util.ArrayDeque; class Main { public static void main(String[] args) { ArrayDeque<Integer> arrayDeque = new ArrayDeque<>(); arrayDeque.push(10); arrayDeque.push(11); arrayDeque.push(15); arrayDeque.push(20); arrayDeque.push(200); arrayDeque.add(700); while (arrayDeque.peek() != null) { System.out.println(arrayDeque.pop() + " "); } } } Good Day .. I have a question regarding the peek() method in ArrayDeque Class .. all the method will do is retrieve the head of the arrayDeque without removing it. so if that is the case how it's working perfectly without going for an infinite loop .. I mean who told the Method to look for the Next element after each complete loop.
There is no infinite loop because the condition in the whole loop will be false when the queue is empty. while (arrayDeque.peek() != null) When `pop` removes the last element, `arrayDeque.peek()` will return null and that's the end.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java" }
Simple inequality, proof There is a following inequality $$\frac{x_{1}^{2}+x_{2}^{2}+...+x_{n}^{2}}{n}\geq\frac{x_{1}^{2}+x_{2}^{2}+...+x_{n}^{2}+2x_{1}x_{2}+...+2x_{1}x_{n}+2x_{2}x_{3}+...+2x_{2}x_{n}+...+2x_{n-1}x_{n}}{n^{2}}.$$ In my opinion, it is held for all $x_i>0$. It can be rewritten to the following form \begin{eqnarray*} \frac{n-1}{n}\frac{x_{1}^{2}+x_{2}^{2}+...+x_{n}^{2}}{n} & \geq & \frac{2x_{1}x_{2}+...+2x_{1}x_{n}+2x_{2}x_{3}+...+2x_{2}x_{n}+...+2x_{n-1}x_{n}}{n^{2}},\\\ x_{1}^{2}+x_{2}^{2}+...+x_{n}^{2} & \geq & \frac{2x_{1}x_{2}+...+2x_{1}x_{n}+2x_{2}x_{3}+...+2x_{2}x_{n}+...+2x_{n-1}x_{n}}{\left(n-1\right)}. \end{eqnarray*} However, how to proof the last inequlity? I used \begin{eqnarray*} x_{1}^{2}+x_{2}^{2}+...+x_{n}^{2} & \geq & \frac{2}{n-1}\frac{n!}{\left(n-2\right)!2!}E(x_{i}x_{j}),\\\ x_{1}^{2}+x_{2}^{2}+...+x_{n}^{2} & \geq & nE(x_{i}x_{j}) \end{eqnarray*} which may not be correct. However, there must be a more rigorous and simple proof.
The inequality can be rewritten as: \begin{align*} \sum_{i=1}^n x_i^2\geq \frac{(\sum_{i=1}^nx_i)^2}{n} \end{align*} Let us fix $\sum_{i=1}^n x_i = c$. Then, the problem: \begin{align*} \mbox{minimize} &\sum_{i=1}^n x_i^2 \\\ \mbox{subject to} &\; \\\ &\sum_{i=1}^n x_i = c,\\\ & x_i \geq 0, \end{align*} has the solution $c^2/n$, when $x_1=x_2=...=x_n=c/n$. Now, it follows that \begin{align*} \sum_{i=1}^n x_i^2 \geq \frac{c^2}{n} = \frac{(\sum_ i x_i)^2}{n} \end{align*}
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "proof verification" }
Market link giving Error 404 Iam using all the below links on Mobile browser but they ar given "not found Error 404". market://details?id=<appMarketUidString> name> name>" how to resolve this.
Your links look correct, but when you go to open them on your phone, make sure to open them with the Market App, because the mobile browser (or any other browser for that matter) does not open them properly.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, google play" }
jQuery.ajax File Upload We have a modal form with an input of type file. We want to upload the file to the server when the user clicks 'Save'. We don't want to actually refresh the page, but simply close the modal. Can we upload a file via $.ajax? Otherwise, what tools are available for uploading files behind the scenes?
`$.ajax()` will work, but you'll do best to specify a POST. See the answer here: Sending multipart/formdata with jQuery.ajax Also, this jquery plugin supports file uploads: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net mvc 3, jquery, file upload, modal dialog" }
How to get a margin right value of a centered div (margin 0 auto) in mozilla I tried the following code and it works on Chrome, Opera, IE9+ but not on Mozilla HTML <div class="centered"></div> <span class="value"></span> CSS .centered {width:300px;height:300px;background:yellow;margin:0 auto;} JS $('.value').text($('.centered').css('margin-right')); Fiddle: < I just want to get the value of margin right of a centered element(with margin: 0 auto) Any ideas?
You can do it like this $('.offsetLeft').text($('.centered').offset().left);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery" }
naming convention for class in java - all caps How do you name a class when it's all caps in Java? For example, if I want to create a class to select certain people to be VIP. Should I name the class "VIPSelector" or "VipSelector"? Thanks!
Both of your options work. The main goal with classes is to have them start with an Upper Case. So, VIPSelector and VipSelector both work. This convention is mostly used to get rid of a common mistake that you can find in OOP which is when you can't make the difference between a class and a method. Imagine having a class object called "student", to initiate it, it would be student s = new student(); That looks a lot like a method and this is why, by convention, we put the first letter in upper case.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 5, "tags": "java, class, naming, conventions" }
Two way synchronization with SSIS? Can I use SQL Server Integration Services (SSIS) to create a two-way synchronization between tables in two different databases? I am using SQL Server 2008 R2. If it is possible, then how do I handle synchronization conflicts?
I would say that it is definitely possible. I am not sure that it would be the best option and any synchronization conflicts will need to be handled explicitly by your programming. I would consult MSDN first and read up on High availability solutions and Disaster Recovery before I went any further. MSDN High Availability Overview Disaster Recovery Sql Server Installation Planning
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "sql server, ssis, sql server 2008 r2" }
If I target .NET 2.0, can I still get runtime features from newer versions? I'm pretty pleased with targeting .NET 2.0 for my XNA games on the basis that it is more widely available (and I can still use nice C# 3.0 language features). But I recently came across an article saying that the .NET 3.5 SP1 JIT added inlining of value-type methods (something that, as a game developer, I use a lot of). So my question is this: If my project targets .NET 2.0, and the user happens to have .NET 3.5 SP1 installed, will my program use the newer JIT? (And what about the .NET 4.0 JIT and versions beyond that?)
Yes it will use it. The JIT is part of the CLR and .NET 2.0 and 3.5 SP1 use the same version of the CLR. .NET 3.5 SP1 brought improvements to the CLR compared to .NET 2.0 but it stays compatible. As far as .NET 4.0 and higher is concerned than it is another CLR version that your program won't use.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": ".net, .net 3.5, .net 2.0, runtime, jit" }
Charles ssl certificate download failed "due to network failures" The Charles SSL/HTTPS proxying was working fine on my Samsung Galaxy S5 phone. I remove the certificate while not debugging because the phone warns me about the connection being monitored by a third party. Now when I attempt to re-download the certificate from < I get a charles-proxy-ssl-proxying-certificate.pem download failed due to network failures error: ![charles-proxy-ssl-proxying-certificate.pem download failed due to network failures.]( The phone is set up to use the Charles proxy. HTTP traffic can be inspected in Charles. I'm running Charles 3.11.4 but I've also tested with 3.11.2. The phone is running Android 5.0 I tested with an LG Nexus 5 and the certificate downloaded and installed without any problems.
It's Chrome Mobile - try a different browser, Dolphin worked fine. Yet another thing Google broke in Chrome Mobile.
stackexchange-stackoverflow
{ "answer_score": 26, "question_score": 32, "tags": "android, ssl, https, proxy, charles proxy" }
Isole Ip address from dhcp-range I would like to extract the Bcast Ip Address from dhcp-range line which is specified in the server configuration file. dhcp-range=192.168.42.1,192.168.42.253,255.255.255.0,192.168.42.255,24h I would like to store in a variable 192.168.42.255 Actually I am using DNSMASQ_DIR="dnsmasq.conf" if [ -e "$DNSMASQ_DIR" ]; then BcastAddress=`sed -n 3p $DNSMASQ_DIR | awk '{print $1}'` b=${BcastAddress:53:66} echo $BcastAddress echo $b else echo "file not exists" fi which returns : dhcp-range=192.168.42.1,192.168.42.253,255.255.255.0,192.168.42.255,24h 192.168.42.255,24h I don't understand why ,24h is included. At the same time, I think that my method will be not efficient if the other IP addresses change. Is there a more efficient way to resolve my issue ?
If you want to do it in `awk` $ echo "dhcp-range=192.168.42.1,192.168.42.253,255.255.255.0,192.168.42.255,24h" | awk -F, '{print $4}' 192.168.42.255 **Simplified version of your code** You can even simplify the entire script using awk as $ awk -F, '/^dhcp-range/{print $4}' dnsmasq.conf 192.168.42.255 * `-F,` sets the field seperator as `,` * `/^dhcp-range/` selects line starting with `dhcp-range` * `print $4` prints the fourth column` **OR** $ awk -F, 'NR==3{print $4}' dnsmasq.conf 192.168.42.255 * `NR==3` selects the third line
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "regex, bash, variables, sed" }
What are Proceedings-published posters? For me it's not clearly described what **proceedings-published posters** are. Here is a CFP...
I've not heard the term before, but the description seems clear enough from their website: > Participants submitting proceedings-published posters/demos are required to submit a short paper of 2 pages describing the poster/demo content ... If accepted, this short paper will be published in the proceedings of the conference. In other words, they will publish an associated short paper in the proceedings as well as displaying the poster. This is distinguished from the other option for a paper, which will be displayed, but _not_ have anything published in the proceedings.
stackexchange-academia
{ "answer_score": 6, "question_score": 1, "tags": "poster" }
When do I need a contextual filter vs. a relationship? Can someone explain the **functional** difference between contextual filters and relationships? I understand that a relationship is a table join, and a contextual filter is passing parameters to the view. Both adjust view data. **How would you describe when each should be used?** I have been building complex views for a few months now, but sometimes I still don't have an intuition for what I need - I generally have to find a tutorial on exactly what I am trying to do, and I think it stems from not really understanding these two capabilities. * * * Edit: Thanks for all the answers helping to describe the SQL building. On that topic, I found this advice very helpful.
Just think of it terms of SQL: * a 'relationship' is a `JOIN` on another table * a 'filter' (contextual or not) is a `WHERE` clause. 'Contextual' just means the parameter comes from the current context, e.g. part of the URL, something in the session, etc
stackexchange-drupal
{ "answer_score": 13, "question_score": 5, "tags": "views" }
How to change the name of Struts-config.xml using web.xml? I want to change the name of `struts.config.xml` file to another name something like `abc.xml` using the `web.xml`. Is it possible to rename the `struts.config.xml` using the `web.xml` file or any other way to rename it?
You can just rename the file itself, it should be in your `WEB-INF` folder together with the `web.xml` file. You also need to do a small change in the `web.xml` file (abc.xml below). <init-param> <param-name>config</param-name> <param-value>/WEB-INF/abc.xml</param-value> </init-param>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, struts 1" }
In dalvik, what expression will generate instructions 'not-int' and 'const-string/jumbo'? I am new on learning dalvik, and I want to dump out every instruction in dalvik. But there are still 3 instructions I can not get no matter how I write the code. They are 'not-int', 'not-long', 'const-string/jumbo'. I written like this to get 'not-int' but failed: int y = ~x; Dalvik generated an 'xor x, -1' instead. and I know 'const-string/jumbo' means that there is more than 65535 strings in the code and the index is 32bit. But when I decleared 70000 strings in the code, the compiler said the code was too long. So the question is: how to get 'not-int' and 'const-string/jumbo' in dalvik by java code?
`const-string/jumbo` is easy. As you noted, you just need to define more than 65535 strings, and reference one of the later ones. They don't all need to be in a single class file, just in the same DEX file. Take a look at dalvik/tests/056-const-string-jumbo, in particular the "build" script that generates a Java source file with a large number of strings. As far as `not-int` and `not-long` go, I don't think they're ever generated. I ran `dexdump -d` across a pile of Android 4.4 APKs and didn't find a single instance of either.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, android, dalvik, instructions" }
NuGet Restore Failing to See that Packages are not Installed Our CI server fails to restore our NuGet packages when attempting to build a project. It thinks they are already installed. Here are the logs: ` build 16-Apr-2015 12:56:38 C:\build-dir\IOP-IOL-JOB1>nuget restore IOHandlerLibrary.sln -NoCache build 16-Apr-2015 12:56:39 All packages listed in packages.config are already installed. ` What causes NuGet to believe that the packages are installed? Is it something in the solution or in the project file?
NuGet will check the packages directory for the solution when it restores. It checks that this packages directory contains the .nupkg and manifest file for the NuGet package and if so it believes the NuGet package is already installed locally. The message is indicating that the packages are already available in the solution packages directory. Possibly because your build server is not cleaning the existing directory when it checks out the source code and is checking out the source code to the same directory each time.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 14, "tags": "visual studio, nuget, bamboo" }
How can I install the latest apt package for Cockpit with apt? I'm running 18.04TLS, and have Cockpit version 164-1. If I go to < I see there's a new package 170-1, but I can't install it, because it is not Stable. Is there any workaround to use these packages to install the new version? I don't want to build it from source.
Thanks to the explanation by @muru, it turned out, that Ubuntu freezes all software at the time of the release, so no updates on the main channel. However, in 18.04 backports are enabled by default, so it is easy to install any further updates without any change to default apt settings: sudo apt install cockpit/bionic-backports
stackexchange-askubuntu
{ "answer_score": 5, "question_score": 1, "tags": "apt" }
JavaFX package change betwwen jre 1.7 and 1.8 I am a bit confused. In Oracle jre 1.7, we have the package com.sun.webpane.webkit and in oracle JRE 1.8, we have com.sun.webkit (no webpane) How are we supposed to handle such change so that an application works on both environment, any best practises ? Thanks
You should not use `com.sun` classes in your code. Such classes are not part of the public API which is supported by Oracle or the OpenJDK for the JDK and JavaFX. Oracle makes no guarantees that `com.sun` classes will be backwards compatible between releases. Oracle do guarantee that the public APIs, e.g., `java.*` and `javafx.*` will be backwards compatible between releases. So stick to using only supported public APIs in your code and your code should work much better across different Java releases. For the particular control you are trying to utilize (the webkit implementation embedded in JavaFX), the public API for that is the `javafx.scene.web.WebView` API.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, javafx, backwards compatibility" }
In MVP can the model be shared by the BLL I read the following really good and informative article on MVP: MVP Building from scratch. Referring to the below architecture diagram (taken from the post): 1. i wanted to know if the model classes defined in the presentation layer will be shared in the BLL layer as well. Should these classes form part of separate project which will then be referenced in the BLL. 2. Also will not the service layer user the model class to transfer data to & from the BLL. !enter image description here
Depending on your architecture. You are referring to mobile object (not mobile device) or simply entity.. its possible if you place it in your common project/library that can reference by your BLL, DAL, and other projects like your service… there are certain rules when grouping common objects, be sure objects in common lib are very basic objects and helper classes, NO UI library references because this will break the essence of your common library. If your BLL, DAL, has constraint referencing the Entity (this happens when you place your entity object in your BLL or DAL), create interface of that entity and place it in your common library and use this as parameter instead of entity object… On service, I use interface for mocking… Interface allows you to do horizontal testing (mocking) because you could create mock objects using interface... Hope I answer your questions…
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "mvp, n tier architecture, business logic layer" }
sed: remove whole words containg a character class I'd like to remove any word which contains a non alpha char from a text file. e.g "ok 0bad ba1d bad3 4bad4 5bad5bad5" should become "ok" I've tried using echo "ok 0bad ba1d bad3 4bad4 5bad5bad5" | sed 's/\b[a-zA-Z]*[^a-zA-Z]\+[a-zA-Z]*\b/ /g'
Using `awk`: s="ok 0bad ba1d bad3 4bad4 5bad5bad5" awk '{ofs=""; for (i=1; i<=NF; i++) if ($i ~ /^[[:alpha:]]+$/) {printf "%s%s", ofs, $i; ofs=OFS} print ""}' <<< "$s" ok This `awk` command loops through all words and if word matches the regex `/^[[:alpha:]]+$/` then it writes to standard out. `(i<NF)?OFS:RS` is a short cut to add `OFS` if current field no is less than `NF` otherwise it writes `RS`. Using `grep` \+ `tr` together: s="ok 0bad ba1d bad3 4bad4 5bad5bad5" r=$(grep -o '[^ ]\+' <<< "$s"|grep '^[[:alpha:]]\+$'|tr '\n' ' ') echo "$r" ok First `grep -o` breaks the string into individual words. 2nd grep only searches for words with alphabets only. ANd finally `tr` translates `\n` to space.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "linux, bash, command line, awk, sed" }
openmp on for loop I have the following code: for(i=0; i<num1; i++) { j=i%num2; a[j]=do_compute(j); } Let's assume num2 << num1. If I wanted to use omp for, is there any need to use j as private? i.e. as follows: #pragma omp parallel private(i,j) { #pragma omp for for(i=0; i<num1; i++) { j=i%num2; a[j]=do_compute(j); } } or would this suffice: #pragma omp parallel { #pragma omp for for(i=0; i<num1; i++) { j=i%num2; a[j]=do_compute(j); } } Thanks.
If j is only used in the scope of the loop, I'd do the following: [...] unsigned int i; #pragma omp parallel for for(i = 0; i < num1; ++i) { unsigned int j = i % num2; a[j] = do_compute(j); } [...] not trying to be picky here, but given that `do_compute` is deterministic and has no side-effects, you'd be better off with just using [...] unsigned int i; #pragma omp parallel for for(i = 0; i < num2; ++i) a[i] = do_compute(i); [...]
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c, openmp" }
how to get the days of 2,3,4 months in javascript I want to get the days of more then 1 month if pass 2 , 3 ,4 as number of month to the function, I want to get total number of days from today function get_days_in_month(months){ days_in_month = new Date(); var y = days_in_month.getFullYear(); var m = days_in_month.getMonth(); if(months==1){ return new Date(y,m+1,0).getDate(); } if(months==2){ // need to write code or some other logic } } Thanks for help in advance
Use a `for` loop: var total = 0; for (i = 1; i <= months; i++) { total += new Date(y, m + i, 0).getDate(); } return total; **JSFiddle demo**.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript" }
Запятая перед союзом "и" + "что" Друзья! Подскажите, пожалуйста, нужна ли запятая в заголовке к одной статье DW. Выходит, что в примере ниже — две грамматических основы? _Действительно ли Лукашенко не боится коронавируса(,) и что скрывают в Беларуси?_ Благодарю.
Автор имеет право не ставить в вопросительном предложении соответствующего знака, но он всё же (где-то в тёмных глубинах постфрейдовского сознания) подразумевается, нет? У нас и есть две грамматические основы, но запятая не ставится ввиду объединённости их общей (проглоченной) вопросительной интонацией. **Запятая не ставится...** > ...если части сложносочиненного предложения представляют собой побудительные, вопросительные или восклицательные предложения; объединяющей здесь оказывается интонация, а в побудительных предложениях могут быть и общие частицы: _Где будет собрание и кто его председатель?_ — общая вопросительная интонация; _Как тихо вокруг и как чисто звездное небо!_ — общая восклицательная интонация; _Пусть светит солнце и птицы поют!_ — общая частица.
stackexchange-rus
{ "answer_score": 3, "question_score": 2, "tags": "пунктуация, запятые, союзы, ссп" }
Is there an industry-specific term for the animated logo that precedes a movie studio’s films? Most studio films begin with an animated sequence that shows off the studio’s logo. For example, the 20th Century Fox “searchlights” or the Universal Studios Earth orbit. Is there an industry-specific term for this type of animated logo?
As per Wikipedia: > A **production logo** , **vanity card** , **vanity plate** , or **vanity logo** is a logo used by movie studios and television production companies to brand what they produce and to determine the production company and the distributor of a television show or film. Production logos are usually seen at the beginning of a theatrical movie or video game (an **" opening logo"**), or at the end of a television program or TV movie (a **" closing logo"**).
stackexchange-movies
{ "answer_score": 5, "question_score": 1, "tags": "terminology" }
A framework / model for regression when each input come naturally with a prior on output? I have a physical problem in which I want to map x to y. I plan to use GPs for this regression. The question is: if each x in my data comes with a prior on y values, how can I model this? what framework should I use and how should I approach it? Any suggestions, links, ideas are appreciated. Note: the prior on y that comes with each x is vital to determine y. Same thing when I will be doing prediction in future, the x's will come with priors on y, and I want to use that. EDIT: some wanted a concrete example: It is really complicated in its original form, but here's a toy example carrying same idea, this is a table with columns x, prior on y, actual y. x, prior on y, actual y * * * 1 [1, 5] 2.2 2 [0.3, 0.8] 0.7 3 [2.5, 5.8] 5
If I understand it correctly, what you want is a GP regression, but instead of the observed variables being drawn from a normal distribution around the true deterministic function, you expect them to be drawn from a truncated normal distribution. The truncation points are then taken as data. I am not aware of any software that would fit such a model out of the box, but you can use Stan, and combine the Latent variable GP example with the truncated data example. Note however that Gaussian processes can be tricky to fit well (see Mike Betancourt's case study on the subject). If GPs turn out to be tricky, you can use splines instead (e.g. as in this case study ). Splines are less appealing theoretically, but in my experience are much easier to fit. Hope that helps.
stackexchange-stats
{ "answer_score": 1, "question_score": 0, "tags": "regression, bayesian, multiple regression, gaussian process" }
How to make fasterxml ObjectMapper work with codehaus annotations I'm using the `ObjectMapper` class from the `fasterxml` package (`com.fasterxml.jackson.databind.ObjectMapper`) to serialize some POJOs. The problem I'm facing is that all the annotations in the POJOs are from the older codehaus library. The `fasterxml` `ObjectMapper` is not recognizing the codehaus jackson annotations. One possible solution is to update the annotations in the POJO to `fasterxml`, but the POJOs are provided by a third party, hence I cannot modify it. How can I solve this problem?
You can provide your own AnnotationIntrospector to process old annotation. ObjectMapper mapper = new ObjectMapper(); mapper.setAnnotationIntrospector(new MyAnnotationIntrospector()); You can also checkout the jackson-legacy-introspector listed on the jackson github. It's an existing implementation of AnnotationIntrospector for old annotations.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "java, json, jackson" }
The polynomial ring in two variables is a free module over the ring of symmetric polynomials Let $B=k[x,y]$, and $A$ is the subring of symmetric polynomials which means $g(x,y)=g(y,x)$. Show that $B$ is a free $A$-module with basis $\\{1,x\\}$. Any hints please!
$$f(x,y)=\dfrac{xf(y,x)-yf(x,y)}{x-y}+x\dfrac{f(x,y)-f(y,x)}{x-y}$$ and this representation is unique.
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "abstract algebra, polynomials, modules" }
How to set username and password in JBoss Unfortunately their Wiki is down for maintenance and the web is not being helpful. How do I add a new user to JBoss so I can login. In Tomcat you change the tomcat-users.xml file. There seems to be a similarly located and titled file called login-config.xml in the config folder of jboss. Is it something to do with this file or something else altogether.
It's in the users.properties file within jboss\server\default\conf\props
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "authentication, jboss" }
Continuous piping in bash program I'm looking for a way to pipe text continuously into a process like `write`. I do **not** want to buffer and pipe it all at once. This is my bash script so far: #!/bin/bash for i in `seq 1 10`; do echo $i | write user done The problem is that `write` gets opened and closed `i` times. Does anyone know how I can keep it alive while looping?
Sure, just move the pipe outside the loop: #!/bin/bash for i in `seq 1 10`; do echo "$i" done | write user As you've tagged with bash, I would suggest using a brace expansion `for i in {1..10}` rather than calling `seq`. If the numbers are variable, you can use something like `for (( i = a; i < b; ++i ))`.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "bash" }
null pointer exception in below code In below code last sop is not printed having String A=null; if (A.contains("xyz")) { System.out.println("loop1"); } System.out.println(A);
Since A is null above code will throw a NullPointerException(NPE) which is a RuntimeException. The exception will be thrown when any invocation is performed on null, in your case a contains method call. A.contains("xyz")
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "java" }
Please retry: error (invalid JSON mapping) for Json { "type": "file", "enabled": true, "connection": "classpath:///", "config": null, "workspaces": { "jsonfiles": { "location": "C:\Users\mypc\Desktop\JSON", "writable": true, "defaultInputFormat": null } }, "formats": { "json": { "type": "json", "extensions": [ "json" ] } } } I get the error below when updating the configuration of storage plugin: > Please retry: error (invalid JSON mapping) How can i solve this?
Here, in your json data location path is causing error. JSON causes parsing error with backslash. Use `\\` instead of `\` as below. `"location": "C:\\Users\\mypc\\Desktop\\JSON"`
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "json, apache drill" }
Can you believe php -m says yes and phpinfo() says no? This is my php.ini extension_dir = "ext" extension=php_tidy.dll [Tidy] ;tidy.default_config = /usr/local/lib/php/default.tcfg tidy.clean_output = Off **Can you belive when I type`php -m`, I get tidy in the list but when I check the `phpinfo()` function, there is no mention about tidy ?** And when I write `$tidy = new tidy;` in a php file, I get this error `Fatal error: Class 'tidy' not found in E:\DEV\WWW\lexique\load.php on line 32`. (The application worked fine under a previous install) PHP 5.4.15 Apache 2.4
I have resolved it adding the PHP folder to the PATH and restarting the computer.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "php, installation, tidy" }
* on the linux command line I am making a little calculator in C, and i want to pass simple arithmetic formulae to my program. But it really does not like me passing character '*' to my program. Why not? And how can I work around this without changing the asterix to something else? Thanks
The character `*` is the shell's trigger for expanding matching filenames. There are several ways to deal with it: * Escape it when typing `mycalc 5 \* 3` * Place the whole expression in quotes and make sure the calculator's parser works that way: `myprog "5 * 3"` * Don't use the command line: use your own input instead.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 5, "tags": "c, linux" }
How to check if an arbitrary number of matlab.unittest.constraints is satisfied by a cell array? I have a cell array of matlab.unittest.constraints and a cell array of values. I'd like to see if the values match the constraints (respectively). Of course, I can just use a for cycle, something like the following code: satisfied = zeros(1,argLength); for i=1:argLength satisfied(i) = satisfiedBy(cons{i}, val{i}); end; answer = all(satisfied); but knowing MATLAB, there must be a way to condense all that into a single line, I just don't know it. I compare the lengths of the arrays beforehand and return false if they're not equal.
Here is a possible CELLFUN statement: satisfied = cellfun(@satisfiedBy, cons, val); Make sure `satisfiedBy` returns only single numeric/logical value.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "matlab" }
Adding input data from a textbox to a confirmation message in JavaScript I am trying to get a confirmation box to display my input data from a textbox, but instead of whatever I put in, the confirmation box displays "null" where the input is supposed to be. Please help. I tried adding .val() to name in the confirmation box, but no luck. JSFiddle HTML: First Name: <input type="text" id="namebox"> <input type="submit" id="submitbutton" onClick="confirmFunc()"> JS: function confirmFunc() { var name = document.getElementById("#namebox"); confirm("Please confirm that the following name is correct: " +name); };
use this function confirmFunc() { var name = document.getElementById("namebox").value; confirm("Please confirm that the following name is correct: " +name); };
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, html, forms, null, confirmation" }
How to backup an AppEngine site? So, you build a great shiny cloudy 2.0 website on top of AppEngine, with thousands upon thousands of images saved into the datastore and gigs of data at the blobstore. How do you backup them?
use google app engine data export <
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 14, "tags": "python, google app engine, backup" }
How to generate an IBM Cloud token from an API Key I have generated an API key for IBM Cloud, how do I programmatically generate a token from the API key?
Here is a curl request to do that. curl --location --request POST ' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --header 'Authorization: Basic Yng6Yng=' \ --data-urlencode 'apikey=xxx' \ --data-urlencode 'response_type=cloud_iam' \ --data-urlencode 'grant_type=urn:ibm:params:oauth:grant-type:apikey' Replace `xxx` with your API key. The basic authorization is base64 encoded with a username of `bx` and a password of `bx`. The response looks like the following: { "access_token": "bearer token", "refresh_token": "refresh token", "token_type": "Bearer", "expires_in": 3600, "expiration": 1581031424, "scope": "ibm openid" }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ibm cloud, ibm cloud infrastructure, ibm cloud kubernetes, ibm cloud iam" }
Расположить элементы в круге Элементы расположены по кругу, с наездом друг на друга. Как сделать так что бы каждый элементы был выше предыдущего но ниже следующего. Сейчас получается что первый элемент либо выше двух соседних либо ниже. Пример Красный квадрат должен быть выше черного, но ниже зеленого
<
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "html, css" }
MFCでの標準タイマーの精度をあげる方法ありますか? MFC 1015 \-- 2015/02/01 -- 11
> 1015 Windows OS15.6Windows 7 > > `timeBeginPeriod` Microsoft "Timers, Timer Resolution, and Development of Efficient Code"(docx) `QueryPerformanceCounter`(QPC) QPC…Windows OS QPCMSDN "Acquiring high-resolution time stamps"
stackexchange-ja_stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "windows, c++, mfc" }
Delete file in windows 7 using VB.NET I have written following code in vb.net to delete the file. If File.Exists(strPath & "\ReportEng.ini") = True Then File.SetAttributes(strPath & "\ReportEng.ini", FileAttributes.Normal) File.Delete(strPath & "\ReportEng.ini") End If File.Copy("\\192.168.0.1\SAP_Shared\AddonExtra\ReportEng.ini", strPath & "\ReportEng.ini") This code works perfectly in windows xp. But in Windows 7,I can not delete it. This OS is hectic OS from developer's point of view. Some or other problem occurs and Microsoft has not considered the developer while building this OS. How do I delete file in Windows 7 ?
You don't need to delete the file: there is an overload File.Copy Method (String, String, Boolean) which allows overwriting. You didn't say what error you get. I suspect it is because the user doesn't have write access to the directory. You should probably be using a subdirectory of the directory returned by `Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)` or maybe `.LocalApplicationData`, and definitely not the directory containing the program. Also, using `Path.Combine(strPath, "ReportEng.ini")` is how you're meant to combine paths - it'll take care of, e.g., the trailing path separator for you.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "windows, vb.net, delete file" }
Non-block file systems I was wandering if there is a filesystem that is non-block based. Every system I know stores or retrieves chunks of fixed size (the blocks, or clusters). Is there a filesystem that will allow to write or read a single byte, in the context of external storage, as hard disk, flash memory etc? I googled around, but I could't find anything conclusive. Thanks.
There's a good reason you won't find it: none of these underlying storage technologies support byte addressing. Flash drives and hard drives connected with SATA or SCSI are all divided into either 512-byte sectors or 4 KiB sectors. Even if you need only one byte from a sector, you have to read the whole thing. Part of what a filesystem does is provide an abstraction on top of these different storage technologies.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "filesystems, block device" }
How can I receive percent encoded slashes with Django on App Engine? I'm using Django with Google's App Engine. I want to send information to the server with percent encoded slashes. A request like `http:/localhost/turtle/waxy%2Fsmooth` that would match against a URL like `r'^/turtle/(?P<type>([A-Za-z]|%2F)+)$'`. The request gets to the server intact, but sometime before it is compared against the regex the %2F is converted into a forward slash. What can I do to stop the %2Fs from being converted into forward slashes? Thanks!
`os.environ['PATH_INFO']` is decoded, so you lose that information. Probably `os.environ['REQUEST_URI']` is available, and if it is available it is not decoded. Django only reads PATH_INFO. You could probably do something like: request_uri = environ['REQUEST_URI'] request_uri = re.sub(r'%2f', '****', request_uri, re.I) environ['PATH_INFO'] = urllib.unquote(request_uri) Then all cases of %2f are replaced with `****` (or whatever you want to use).
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 11, "tags": "python, django, google app engine" }
How to write all socket.io server console text into txt file? My socket server shuts down sometimes and I can't check why because there is no txt log where i could check last error messages, maybe there is way to write it in txt file after shutting down?
Invoke your program in the following way: `node myserver.js 2> error_log.txt` When the program closes the error_log txt will have all messages, including the error message that made the program crash written in it. To also get all console.log messages you can do `node myserver.js > error_log.txt > 2>&1` (I used this command in the bash console on windows)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, socket.io" }
MySQL: How to store/retrieve artist information? It's very confusing; it seems like I'll need to have at least one many-to-many relationship. 1. A track might be sung by 2+ artist - how can I store that in the database? 2. While showing that track, I want link to each artist so that when users click the track it opens that artist's profile page. Can anyone provide me with some assistance in designing a class or classes to accomplish this?
Try something like that tblSongs SongId Title YearProduced etc. tblArtist ArtistId Name ProfilePage etc.. tblSongArtists SongId ArtistId Then your queries could look something like SELECT Title, YearProduced, Name, ProfilePage FROM tblSongs S LEFT OUTER JOIN tblSongArtists SA ON SA.SongId = S.SongId LEFT OUTER JOIN tblArtists A ON A.ArtistId = SA.ArtistId WHERE Title = 'I got the blues' -- .... ORDER BY SongId -- or Song Title (*) (*) order by clause is in case the search criteria produces more than one song, and if you wish to keep the artists for a given song in sequence. Such a query produces multiple rows for a song with several artists, one row per artists, the values of the columns from tblSongs being repeated.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, sql, mysql" }
Convert mysql query to Laravel's DB:Query Builder I tried this on database using SQL tool. It's working perfectly. But Now i Am struggling to Implement it to my DB: query Builder.Any help or suggestions will be grateful for me. If more details need please comment..I will follow next SELECT u.*, (6371 * acos(cos(radians(22.559648)) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(88.415552)) + sin(radians(22.559648)) * sin(radians(`lat`)))) AS distances FROM users AS u JOIN locations AS l ON `u`.`location_id` = `l`.`id` HAVING distances < 32.688888 ORDER BY distances DESC
@JinalSomaiya I changed following things and work fine. ->having('distances', '<', 32.688888]) to ->having('distances', '<', [32.688888]) and ->join('locations as l', 'l.id', '=', 'users. location_id') to ->join('locations as l', 'users.location_id', '=', 'l.id') Final Query: **Edit** DB::table('users') ->join('locations as l', 'users.location_id', '=', 'l.id') ->select('users.*', DB::raw('(6371 * acos(cos(radians(22.559648)) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(88.415552)) + sin(radians(22.559648)) * sin(radians(`lat`)))) as distances')) ->having('distances', '<', 32.688888) ->orderBy('distances', 'DESC') ->get();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "laravel, query builder, laravel query builder" }
CSS on bootstrap tables not working I use following css in my table: .lh1 { line-height: 50px; } And my table looks like this: <table class="table table-bordered lh lh1"> .. .. .. </table> But no matter which value I use for line-height, my table doesn't change at all. Other .css in this table is working fine. What could be the cause of that problem?
You need to do it like this. CSS .lh1 > tbody > tr > td { line-height: 50px; } your CSS is not overwriting the bootstrap CSS. Here is the demo
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css, twitter bootstrap, html table" }
What is the difference between ConnectController and ProviderSigninController in spring-social? I am new to spring-social framework and trying to implement the login functionality for my portal using spring-social. I read the documentation but i am still a little confused. Both controllers are used to establish a connection with the service provider? Is there any advantage of using ProviderSigninController over ConnectController or vice versa? What are the advantages?
The difference is in the results: 1. After using ConnectController you will have an OAuth2 access token to interact with a provider on behalf of a user. 2. After using ProviderSigninController you will have the same things + user will be signed into your application using local account (linked to OAuth credentials). If corresponding local account does not exists before this step then it may be created too. So for example if you want 'Sign in with Twitter' button then ProviderSigninController better fit your needs.
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 8, "tags": "spring social" }
How do I change mirrors in Ubuntu Server from regional to main? I have a Lucid Server (10.04) set up and I would like to change the mirror from US (or any other country) to the Main Ubuntu Mirror. For example my two first entries in sources.list are: deb lucid main restricted deb-src lucid main restricted In a Desktop environment I would select the main mirror like this: !Software Sources But how do I do that from the terminal as I don't have a graphical environment installed!
Open your `sources.list` file using your favorite text editor, e.g. sudo nano /etc/apt/sources.list Locate the text ` and replace it with `
stackexchange-askubuntu
{ "answer_score": 176, "question_score": 136, "tags": "server, command line, software sources, apt mirror" }
Windows 7 Family pack upgrade with Windows XP Home OEM I currently am running Windows 7 RC (Build 7100) ~~2~~ and want to make the jump to Windows 7. I was looking at the Windows 7 Home Premium Family pack and from what I understand it is identical to the Windows 7 Home Premium DVD, just with three licenses, correct? Anyway, my computer came with Windows XP Home SP2, which I would assume is OEM, I have a Dell OS reinstallation disk, which, as far as I can tell is just the Windows XP CD with a different label, and that it doesn't ask for a CD-key. Would I be able to perform a clean install with the Windows 7 Home Premium Family Pack media? Would it simply ask for (and accept) my OEM disk, or would I have to reinstall XP first before I perform the clean install (I read somewhere that the upgrade editions look for previous versions of Windows on your hard drive), or would it view my existing RC ~~2~~ install as a previous version? Is this even possible? Thanks
Windows 7 won't ask for your old media to do a clean install with upgrade media. You need to either install Windows XP and then upgrade (which will force you to choose a clean install) or you need to follow the directions on Paul Thurrott's site on how to clean install using upgrade media.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "windows 7" }
Can I use an exception with a database query? Is it possible to use an exception at the end of a mysql query instead of die()? I'd like to throw an exception and log it instead of killing the script. Would it be done like: mysql_query(...) or throw new exception()??
This is the way I normally do it. I have my database in a wrapper class, so `$this` simply refers to the wrapper. private function throwException($query = null) { $msg = mysql_error().". Query was:\n\n".$query. "\n\nError number: ".mysql_errno(); throw new Exception($msg); } public function query($query_string) { $this->queryId = mysql_query($query_string); if (! $this->queryId) { $this->throwException($query_string); } return $this->queryId; } That packages it all up with a nice error message for me, so I can see the problem query. You could keep it much simpler of course, and do: mysql_query($sql) or throw new Exception("Problem with query: ".$sql);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "php" }
How to delete media file from res/raw folder? I have a media file under my `res/raw` folder and after the app installed I need to delete this file. How to do it? I know that I can download this file after install and then delete or any other ways, but I need this file to be build. I see only option to make it build in put it to `res` folder. But because of size 100Mb I don't wan't to hold it, so I need to remove it. I am not sure that it is even possible
> How to do it? That is not possible. Resources and assets are packaged in the APK and are read-only. They cannot be modified or deleted.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "android" }
Make BigDecimal truncate instead of round I'm using BigDecimal to deal with positive numbers in my app, and I want to make it truncate decimals after the 4th one. I seem to almost find what I wanted with RoundingMode.DOWN, but there's some issue when the BigDecimal is created from a double. For example: System.out.println("123.11119 = " + new BigDecimal("123.11119").setScale(4, RoundingMode.DOWN)); //Print 123.1111 which is exactly what I want System.out.println("123.1111 = " + new BigDecimal("123.1111").setScale(4, RoundingMode.DOWN)); //So does this one HOWEVER, the following prints `123.1110` which is NOT what I want at all: System.out.println("123.1111 = " + new BigDecimal(123.1111d).setScale(4, RoundingMode.DOWN));
This is because of representation problem. The value 123.1111d in reality can be something like 123.111091231918498. That why it is recommended to use string constructor when you want to have exact values.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "java, double, rounding, bigdecimal" }
How can I change a value in consul K/V Store from Spring Boot app I use Consul's Key/Value Store as a PropertySource in a Spring Boot 2 app. (org.springframework.cloud:spring-cloud-starter-consul-config) I can read the properties from the K/V Store with @ConfigurationProperties and even update them with @RefreshScope when I change the value via the Consul web interface. But I do have some dynamic properties which can change in the application. How do I propagate these changes to Consul, so that the values are actually changed. I tried to use the Setter for the property but that did not change the value in Consul.
Use this code to set KV values. Create private variable. @Autowired private ConsulClient consulClient; change KVs using setKVValue() method. consulClient.setKVValue("key", "value")
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "java, spring boot, consul" }
fatal error: unexpectedly found nil while unwrapping an Optional value swift error I am writing a simple program that shows and takes away images and I keep getting the error fatal error: unexpectedly found nil while unwrapping an Optional value Here is my code: @IBAction func BeginButton(sender: AnyObject) { self.Retry.hidden = false self.Begin.hidden = true self.Logo.hidden = true self.GameOver.hidden = false self.ScoreBoard.hidden = false } @IBAction func RetryButton(sender: AnyObject) { self.Begin.hidden = false self.Retry.hidden = true self.Logo.hidden = false self.GameOver.hidden = true self.ScoreBoard.hidden = true } Please help me!
You need to connect your IBOutlets (self.Retry, self.Begin, ...) with the corresponding views in Interface Builder. Right now, one or more of them are `nil`. Here's a detailed explanation from Apple: <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "xcode, swift" }
is there any way to determine width and height of rgb values array? I have RGB values array with raw size each time. I'm trying to determine which width/height it would be more suitable for it. The idea is, I'm getting raw files and I want to display file data as BMP image (e.g Hex Workshop got that feature which called Data Visualizer) Any suggestions? Regards.
Find the divisors of the pixel array size. For instance, if your array contains 243 pixels, divisors are 1, 3, 9, 27, 81 and 243. It means that your image is either 1x243, 3x81, 9x27, 27x9, 81x3 or 243x1. You can only guess which is the good one by analyzing image content, vertical or horizontal features, recurring patterns, common aspect ratio, etc.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, image processing, rgb" }
How to write optional parameter in $.getJSON I used $.getJSON to retrieve the data from my database. If the parameter dID is not null, then there is one parameter like : $.getJSON(urlGetProByDep, { depID: dID }, function (data) { //blah blah blah }); But if both dID and cID are not null so the function will use 2 parameter as below : $.getJSON(urlGetProByDep, { depID : dID,catID : cID }, function (data) { //blah blah blah }); Could anyone tell me how can I change the paramter in {....} due to the value of dID and cID. Thanks so much.
var data = {}; if(dID) { data.depID = dID; } if(cID) { data.catID = cID; } $.getJSON(urlGetProByDep, data, function (data) { //blah blah blah });
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, jquery" }
In a list of data frames, calculate proportion of these that meets a condition I have a list of data frames (`gtf`) and I would like to calculate what proportion of each of these data frames have 0's at a set of coordinates [i,j] (coordinates [i,j] == 0). i.e. if I have 500 data frames and 120 of them have 0 at coordinates [1,1], then the function would return 120/500. Eventually, I would like my function to return a data frame where the columns correspond to the columns of `gtf` and the values are the proportions of data frames that had 0's in the corresponding coordinates. Here is a recreation of `gtf`: x = matrix(c(1,0), 6,6) x = as.data.frame(x) y = matrix(c(0,1), 6,6) y = as.data.frame(x) gtf = list(x,y,x,y) Here is what I have tried: for (i in seq_along(gtf)) for (j in seq_along(gtf[[i]])) if (gtf[[i]][1,j] == 0) tf[[i]] <- TRUE
We convert the `list` elements to logical matrix using `==`, `Reduce` it to a single dataset by adding the corresponding 'i,j' elements and divide by the `length` of the `list` Reduce(`+`, lapply(gtf, `==`, 0))/length(gtf)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "r, loops, indexing, bioinformatics" }
Check if iframe has specific id using JQuery I have a function to call another function inside am iFrame like this: function globalFunc(value) { //select and add ID to the iFrame const preloading_iFrame = $("iframe[src*=' preloading_iFrame.attr("id","preloadingID"); // call iframe's function document.getElementById('preloadingID').contentWindow.iframeFunc(value); } Since I want to execute the `globalFunc` multiple times, I was wondering if we can bypass adding `id` to the iframe after the first time it has been added. Something like check if iframe has the `preloadingID` as the `id` then don't add it again! Is there any solution?
There's no need to add the ID. You have a reference to the element already, just use that. function globalFunc(value) { //select and add ID to the iFrame const preloading_iFrame = $("iframe[src*=' // call iframe's function preloading_iFrame[0].contentWindow.iframeFunc(value); } Indexing a jQuery collection returns the corresponding DOM elements.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery" }
How to disable drop for all elements of page except 2 div I have a page (created not by me) with two divs. This divs contains some span elements, they can be drag&dropped between this divs. This functionality implemented using jQuery draggable and droppable function. But user is able to drop span element not only at div, but at any place of page. Question is: how can I prevent this? I need to disable dropping span at any place except this divs. Dragged span should return to place where it was taken. Can I make it with JQuery?
Set the `revert` option of the draggables to `invalid` so that they return to their original position if not dropped on a compatible droppable. The droppables should also have the `accept` option suitably set to accept the draggables.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, drag and drop" }
Proving an invariant relationship Two particles, moving at relativistic speeds in the x direction, are observed to have energies E1 and E2, and momenta p1 and p2 in frame A. Frame B moves at relativistic speed v relative to frame A, also in the x direction. The particle energies and momenta in frame B are E1′ , E2′ , p′1 and p′2. How do I proof the following relationship? ![enter image description here](
We know that Lorentz transformations preserve the length of the 4-momentum vector for each particle. In Minkowski space, this length is $E^2-p^2c^2$ up to sign convention, which is irrelevant here. Since this quantity is frame-independent (frame changes are Lorentz transformations) for each particle, the sum must also be frame-independent.
stackexchange-physics
{ "answer_score": 1, "question_score": 0, "tags": "special relativity, energy, momentum, inertial frames, invariants" }
avg columns and order them in sql I need to order this avg values desc, but somehow I can't. Help please !my query is something like this: The solution is probably very simple:)
I assume you want to order the columns having the highest value in left column. I also assume that you are using SQL Server. It certainly looks like that from the pictures. The solution is probably very simple. Don't know about that. You tell me... with C(A, B, C) as ( -- Your query goes here ) select [1],[2],[3] from ( select Val, row_number() over(order by Val desc) as rn from C unpivot (Val for Col in(A, B, C)) U ) T pivot (min(val) for rn in ([1],[2],[3])) P Proof of concept
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, sql order by, average" }