INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
C# MVC Change the Startup Page I just created my first C# Razor MVC3 project. I've dabbled in it before but this is the first time I created one. Anyhow, I have a simple question. I am using the `MembershipProvider` `AspNetSqlProfileProvider` that was build with the default project. My question is simple, where and how do I check if the user is logged on before it loads the `Home/Index.cshtml` so that I can direct them to another page? If they are logged on, I want to take them to the customer portal. If they are not logged on, I want to take them to the logon screen.
A more generic way to set this up would involve 2 steps: First, add an [Authorize] attribute to your action that you are securing: [Authorize] public ActionResult Index() { } This will make sure that the user has authenticated (using FormsAuthentication). Second, in your Web.config file, set the URL that you want the user to be redirected to when they need to login. <authentication mode="Forms"> <forms name="cookieName" loginUrl="~/Account/LogOn" timeout="30" domain=".example.com" slidingExpiration="true" /> </authentication>
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, asp.net mvc, razor, membership provider" }
COM ListItem not updating ClientContext cl = new Microsoft.SharePoint.Client.ClientContext(" + "mysharepoint" + "/" + SubWeb); System.Net.NetworkCredential cred = new System.Net.NetworkCredential("myuser", "mypass", "ntuni"); cl.Credentials = cred; ListItemCollection result; List qrtList = cl.Web.Lists.GetByTitle(QRT_LIST_NAME); result = qrtList.GetItems(CamlQuery.CreateAllItemsQuery()); cl.Load(result); cl.ExecuteQuery(); foreach (ListItem item in result) { if (item.FieldValues["UniqueId"].ToString() == QrtId) { item.FieldValues["R_x00e9_ponse"] = r.ResponseTxt; item.Update(); qrtList.Update(); } } cl.ExecuteQuery(); My object doesnt update once i visite the sharepoint for some reason. This is wraped around a try catch and nothing gets caught.
Reference your fields without FieldValues: item["R_x00e9_ponse"] = r.ResponseTxt;
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 0, "tags": "development, list, client object model, list item" }
Try to delete a file in android. file deleted but the file path is exist in content resolver. i did the wrong way? I tried this code File file = new File("/storage/emulated/0/Movies/Instagram/VID_42790208_180323_463.mp4"); file.delete(); actually its deleted the file. but the content resolver still querying the deleted file path. also i am getting the path from content resolver. help me. thanks a lot.
You have to let the media scanner know that you have deleted the file. Try the following code after delete. MediaScannerConnection.scanFile(mContext, new String[]{file.getPath()}, new String[]{file.getName()}, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String s, Uri uri) { getContentResolver().delete(uri, null, null); } }); Refer the documentation) for more info
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, android contentprovider, android contentresolver" }
Recording indicator sound getting recorded When I initiate a recording, I have a sound effect play to indicate the recording started. I'm current implementing a 1 second delay to avoid recording the recording indicator sound. //Play the sound [self.defaultPlayer play]; //Create the delay double delayInSeconds = 1.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ //Record [self.recorder record]; }); Is there a better way of doing this?
You can use an AVAudioPlayer object for playing the sound, set it's delegate to self, and implement the AVAudioPlayerDelegate method: - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag Where you can call: [self.recorder record]; I think this is a nice way to make the system nicely syncronize everything.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios, objective c" }
Typescript - array items from a list of various interfaces interface NamedAnimal { name: string; } interface Fish extends NamedAnimal { type: 'fish'; water: 'fresh' | 'salt'; } interface Dog extends NamedAnimal { type: 'dog'; breed: 'terrier' | 'mutt'; } type Animal = Fish | Dog; const animals: Animal[] = [ { type: 'dog', name: 'rover', breed:'terrier' } ]; function doSomething(animal: Animal) { if (animal.breed) { // do something doglike..... } } doSomething(animals[0]); In the above example why does referencing 'animal.breed' give me an error saying 'Property "breed" does not exist on type Fish' How can I change this so that it can be any of the types listed? (this is not my actual code but an example of an issue I have).
You can use the `in` operator to narrow the type down to `Dog`, see the TypeScript documentation. function doSomething(animal: Animal) { if ('breed' in animal) { // do something doglike..... } } Since both `Fish` and `Dog` have a `type` field you can also use this field to discriminate the type: function doSomething(animal: Animal) { if (animal.type === 'dog') { // TypeScript now know this is the 'Dog' type console.log(animal.breed) } }
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "typescript, typescript typings" }
reading from console without pausing the program i have made a small opengl program using the d programming language. what i am trying to do is to allow the program to read input from the console. i have tried to use readf(), getc() and some other functions. but my problem is i don't want the program to pause while looking for input. i have tried to search around for a solution but could not find any. so if anyone know how to check if something actually have been written in the console and if so read that. or if there exists any function that reads from console, but will be ignored if nothing gets written. i mainly would like to know how to do this in d but a solution for c++ could be useful too.
You need to use a separate thread. Something like this is one way to do it in D: import std.stdio, std.concurrency; void main() { // Spawn a reader thread to do non-blocking reading. auto reader = spawn(() { // Read console input (blocking). auto str = readln(); // Receive the main thread's TID and reply with the string we read. receive((Tid main) { send(main, str); }); }); // ... This is where you can do work while the other thread waits for console input ... // Let the reader thread know the main thread's TID so it can respond. send(reader, thisTid); // Receive back the input string. receive((string str) { writeln("Got string: ", str); }); } This spawns a separate thread which does the console input waiting while your main thread can do other work.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "console, d" }
Unique 4 digit random number in C# I want to generate an unique 4 digit random number. This is the below code what I have tried: **Code for generating random number** //Generate RandomNo public int GenerateRandomNo() { int _min = 0000; int _max = 9999; Random _rdm = new Random(); return _rdm.Next(_min, _max); } The problem is I have received a random no with value `241` which is not a 4 digit number. Is there any problems with the code?
//Generate RandomNo public int GenerateRandomNo() { int _min = 1000; int _max = 9999; Random _rdm = new Random(); return _rdm.Next(_min, _max); } you need a 4 digit code, start with 1000
stackexchange-stackoverflow
{ "answer_score": 62, "question_score": 26, "tags": "c#, random" }
How to install a "pdf printer"? Is there a way to install a printer that prints to pdf? There's a lot of discussions about this in the web foruns, but none seens to work.
Ubuntu ships with this functionality. Try opening gedit or another GUI text editor and clicking the print button: ![enter image description here]( When the Print dialog appears, select the "Print to File" printer and select a location for the PDF. After clicking Print, you should end up with a PDF file in that location containing an identical copy of what would have printed on a sheet of paper. !enter image description here
stackexchange-askubuntu
{ "answer_score": 25, "question_score": 73, "tags": "printing, pdf" }
Create Columns in a datatable with a single expression I want to define a datatable with columns, where the column definition is _part_ of the datatable definition statement. Eg //valid syntax DataTable dt = new DataTable(); dt.Columns.add("num",typeof(int)); dt.Columns.add("num2",typeof(int)); But I would rather want to do something along the lines of //invalid syntax DataTable dt = new DataTable(Data.Columns[] { {"num",typeof(int)}, {"num2",typeof(int)} }; Is this possible? If it is, what is the correct syntax.
You can't initialize DataTable with collection initializer. All you can use is `AddRange` method of `DataColumnCollection`, but I don't think its much better than your original approach DataTable dt = new DataTable(); dt.Columns.AddRange(new[] { new DataColumn("num", typeof(int)), new DataColumn("num2", typeof(int)) }); You can create extension method which will add columns in fluent way: public static DataTable AddColumn<T>(this DataTable dt, string name) { dt.Columns.Add(name, typeof(T)); return dt; } Usage: var dt = new DataTable() .AddColumn<int>("num") .AddColumn<int>("num2");
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c#, datatable" }
Comparing two Big O notations Please, could you help me with the question below. Demonstrate that O(log n^k) = O(log n):
Using properties of logs, log(n^k) can easily be transformed into _k_ log(n). Then, because constant factors 'small out' as it were when using big O notation, O( _k_ log(n))= O(log(n)). Thus, O(log(n^k)) = O( _k_ log(n)) = O(log(n)).
stackexchange-math
{ "answer_score": 0, "question_score": -3, "tags": "asymptotics, computer science" }
.htaccess condition for admin area i need to write condition for non admin area. Please, help me with syntax. <FilesMatch ".(gif|jpg|png)$"> RewriteEngine On RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^(.*)$ /watermark/_watermark.php [T=application/x-httpd-php,L,QSA] </FilesMatch> for example - if url has no **/admin/** substring - it should be true for script executing. Thanks,
Simply use that as your pattern for `RewriteRule`: RewriteCond %{REQUEST_FILENAME} -f RewriteRule !(^|/)admin/ /watermark/_watermark.php [T=application/x-httpd-php,L,QSA]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, regex, .htaccess, mod rewrite" }
Geochart - mark one country with a special color There is a standard example of Google Geochart, countries have a scale color depends on value. My question is how to mark one country, for example Canada, with an red one, but leave another countries like before. It is ok if Canada will be without value, just how to mark it in another color? < google.setOnLoadCallback(drawRegionsMap); function drawRegionsMap() { var data = google.visualization.arrayToDataTable([ ['Country', 'Popularity'], ['Germany', 200], ['United States', 300], ['Brazil', 400], ['Canada', 500], ['France', 600], ['RU', 700] ]); var options = {}; var chart = new google.visualization.GeoChart(document.getElementById('regions_div')); chart.draw(data, options); } The desire result: !The desire result
If you specify the `defaultColor` and give `Canada` no value, this will do exactly what you want. So something like: google.setOnLoadCallback(drawRegionsMap); function drawRegionsMap() { var data = google.visualization.arrayToDataTable([ ['Country', 'Popularity'], ['Germany', 200], ['United States', 300], ['Brazil', 400], ['Canada', null], ['France', 600], ['RU', 700] ]); var options = {defaultColor: 'red'}; var chart = new google.visualization.GeoChart(document.getElementById('regions_div')); chart.draw(data, options); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, google maps, charts" }
Where is payment(py_) API doc in Stripe? I found that there is a type of id start with `py_`, It is unique id for payments, but I have never seen it in Stripe API doc.
`py_` objects have the same API shape as the Charge object. They are fundamentally the same thing, but in most cases represent a transaction/transfer between 2 Stripe accounts (i.e. with Connect).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "api, stripe payments" }
Add desktop notifications for Chrome or Firefox I noticed that chat supports desktop notifications to notify you when someone pings you, which made me think that maybe the main site has this functionality as well, and I'd really like to use it in that case. But I couldn't find an option to turn them on anywhere. Chrome notifications look like this: > !example for chrome desktop notification
I started writing an implementation using the Stack Exchange API, but noticed that the API is too slow because of cached results. So, I took another path: I've created a Chrome extension which uses Web Sockets to get real-time notifications. These notifications are then displayed in a desktop notification. 10 dec 2012: I have **ported the Chrome extension to a Firefox add-on**! Example: !1 unread messages in your inbox * **Source code** : Github Source Code * **Chrome Web store** : Chrome Extension * **Firefox add-on** : Firefox addon * **Stack Apps** : Real-time desktop notifications for Stack Exchange inbox ( Chrome / Firefox )
stackexchange-meta
{ "answer_score": 43, "question_score": 60, "tags": "feature request, notifications, global inbox, desktop notifications" }
Integer to Binary Conversion in Simulink This might look a repetition to my earlier question. But I think its not. I am looking for a technique to convert the signal in the Decimal format to binary format. I intend to use the Simulink blocks in the Xilinx Library to convert decimal to binary format. So if the input is 3, the expected output should in 11( 2 Clock Cycles). I am looking for the output to be obtained serially. Please suggest me how to do it or any pointers in the internet would be helpful. Thanks
You are correct, what you need is the parallel to serial block from system generator. It is described in this document: < This block is a rate changing block. Check the mentions of the parallel to serial block in these documents for further descriptions: < <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "fpga, simulink, xilinx, system generator" }
How to get the .apk file of an application programmatically I want to create an application which has the following functionality. It should save its **.apk** file to the **sdcard**. Imagine I have a `Button`. On clicking it I have to save the **.apk** file of the application.
It is easy to do that.. 1. First you get all installed applications, 2. For each one, get public source directory. 3. copy the file to the SDCard. Note: No need to be rooted. Here is the snippt code: final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> apps = getPackageManager().queryIntentActivities(mainIntent, 0); for (ResolveInfo info : apps) { File file = new File(info.activityInfo.applicationInfo.publicSourceDir); // Copy the .apk file to wherever }
stackexchange-stackoverflow
{ "answer_score": 61, "question_score": 48, "tags": "android" }
Class property attribute for intellisense? Let's say I have this class... Public Class Person Public Property Gender As String = "male" End Class And I do this... Dim p As New Person p.Gender ... and hover the mouse over "Gender", then intellisence shows me .... > Property.Person.Gender As String Can I somehow add an attribute to the Gender property to show more intellisence help - like... > Property.Person.Gender As String = "male" Or maybe... > Property.Person.Gender As String > > It is default set to 'Male' I was hoping to do smething like... Public Class Person <Intellisence="It is default set to 'male'"> Public Property Gender As String = "male" End Class Thanks
You can use the XML comment to achieve that. All tags are listed in Microsoft website: C# and VB.NET More example can be found here: < Back to your question, you can set the summary tag in your property, e.g.: Public Class Person /// <summary> /// It is default set to 'Male'</summary> Public Property Gender As String = "male" End Class
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "visual studio, visual studio 2015" }
Is there a name for synonyms that appear to have opposite meanings? The words flammable and inflammable mean the same thing, but (to someone unfamiliar with their meaning) appear to be opposites (because of the "in" prefix). Is there a name for such word pairs that appear to be opposites but actually mean the same thing? A few other examples are _ravel/unravel_ , _regardless/irregardless_ , _radiation/irradiation_ , _incite/excite_ , _culpatory/inculpatory_ , _press/depress_ , _to/unto_ , _part/depart_ , _fat chance/slim chance_ , _thaw/dethaw/unthaw_ , _candescent/ incandescent_ , _canny/uncanny_ , _dead/undead_ , _write up/write down_ , _valuable/invaluable_ , _habitable/inhabitable_
How about **false enemies**? I originally voted to close because I thought _synonym_ was an adequate generic term here, but Stephen's comment re false friends prompted me to Google language "false enemies". It seems clear that this coinage has occurred to others (here it is in a Wikipedia talk page, for example). The first other "clear-cut" example I came up with was ravel / unravel, but I've found a couple more since, as have others here - maybe OP's right, we need a word to Know thine enemy! EDIT: If an out-and-out neologism is acceptable, there's always the crypto- prefix _(secret, hidden, or concealed)_ , so they could be **cryptosynonyms** (though I must admit that one doesn't yet seem to have occurred to anyone else within the scope of Google's indexing routines).
stackexchange-english
{ "answer_score": 12, "question_score": 26, "tags": "single word requests, synonyms, antonyms" }
how to display a message if a product is direct delivery (attribute = yes) I have an attribute called direct delivery. Is there a way to display a message on the shipping method page tell the customer they have a direct delivery item in their cart. The attribute "direct delivery" is a yes/ no attribute. thank you
on method.phtml file.you need get list of product and check it attribute value yes $quote = Mage::getSingleton('checkout/session')->getQuote(); $cartItems = $quote->getAllVisibleItems(); foreach ($cartItems as $item) { $productId = $item->getProductId(); $product = Mage::getModel('catalog/product')->load($productId); if($product->getData('attributecode')==1){ //direct delivery possaible } }
stackexchange-magento
{ "answer_score": 2, "question_score": 2, "tags": "attributes, shipping, if" }
Find minimum values among the 5 integers? I need to find the minimum of 5 integer values. i have used if else statement to compare. So its not looking good. i.e. code is very lengthy. I dont know how to reduce the code complexity. can anyone help me out? Regards, Karthi
Check out the Min method of LINQ.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 7, "tags": "c# 4.0" }
How to inject a config setting into a custom RavenDB bundle I have hardcoded an SQL Server connection string into a RequestResponder. What is the recommended way of getting the config into the RequestResponder in a way that could work in both Debug and Release? Is it recommended to use MEF or Database.Configuration such as: var connectionString = database.Configuration.GetConfigurationValue<string>("MySettings/ConnectionString")
We use either an appSettings value or putting the config inside a RavenDB doc.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ravendb" }
Размещение названий выбранных ListBoxItem-ов в string[] Как поместить названия выбранных элементов `ListBox`-а в строковой массив?
Выбранные элементы ListBox В общем случае: 'ListBox_name'.SelectedItems.Cast<'Model_name'>().Select(x => x.'propertyName'); Например: SomeListBox.SelectedItems.Cast<MyModel>().Select(x => x.Name); Если Вы используете MVVM с соответствующим биндингом ListBox.ItemsSource, то нужно в классе модели описать свойство IsSelected , сделать Биндинг далее во ViewModel выполнить: ListOfItems.Where(x => x.IsSelected).Select(x => x.Name);
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c#, массивы, wpf, строки" }
Duplicate a row in SQL? OK I have a table that has two columns, userID and courseID. It is used to assign training courses to a user. It looks like this: userid courseid 0 1 0 3 0 6 1 1 1 4 1 5 so user 0 is assigned to courses 1,3,6 and user 1 is assigned to 1, 4 5 anyways I need to take every user that is assigned to 6 and create a new row that has that userid and courseid 11, basically assigning every user who is currently assigned to 6 to also be assigned to 11 for some reason (I did not create this database) both rows are marked as primary keys, and some statements I have tried have thrown an error because of this, what the heck is the deal? oh maybe it is because there are a few users that are already assigned to 11 so it is choking on those maybe? please help
Insert Into TableName (userID, courseID) Select userID, 11 From TableName Where courseID=6; Also, I'm a bit confused by your comment that both are primary keys. Both rows can be _part_ of the primary key or both can be Unique keys but they cannot both be a primary key. As far as errors go, it is probably because the query tried to insert rows that were duplicates of already existing rows. To eliminate this possibility you could do this: Insert Into TableName (userID, courseID) Select userID, 11 From TableName Where courseID=6 AND (userID not in (Select userID From TableName Where courseID=11)) Depending on your database this could work too: INSERT OR IGNORE INTO TableName (userID, courseID) SELECT userID, 11 FROM TableName WHERE courseID=6; Anyway, there you go.
stackexchange-stackoverflow
{ "answer_score": 67, "question_score": 42, "tags": "sql" }
What is Interoperability Index R98? In the uploaded pictures from my mobile phone, I get a line with the following information: Interoperability Index = R98? What is this Index?
Quote from www.exif.org/dcf.PDF (Design rule for Camera File system): > With the rapidly growing popularity of digital still cameras, there are increasing demands for file interchangeability, which will allow images captured on one camera to be viewed on another, or output directly to a printer. ExifR98 is a set of compatibility recommendations designed to meet such needs, by strictly defining the range of Exif application, and by setting out detailed rules for recording and playing image files not specified in the Exif format. Basically it's a set of rules for the file names, directory structure and mandatory meta-data for digital camera so that all compatible viewers and printer will be able to read the memory cards of all compatible cameras. All cameras that are compatible with ExifR98 are required to add the interoperability index tag to the EXIF data with the value "R98" (among other things).
stackexchange-photo
{ "answer_score": 6, "question_score": 6, "tags": "metadata, cameraphones" }
How to dynamically reference razor components like Vue? Normally with Vue.js you would reference a component in markup similar to Blazor as so: <UserImageComponent> ... </UserImageComponent> However, Vue.js has the ability to load a component dynmically: <component v-bind:is="UserImageComponent"> ... </component> Does Blazor have something like this?
The easy way around is to build a basically empty component, give it a ChildContent parameter and set that to anything you like. [Parameter] public RenderFragment ChildContent { get; set; } The RenderFragment will render anything you throw in there, even if it's another component or if you set it dynamically.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "blazor" }
Обновление сайта на WordPress есть сайт на котором нужно обновить тему, провести оптимизацию и чистку большого количества медиа файлов, удалить ненужные файлы и тд. Это всё удобнее всего делать на локальном сервере, экспортировав весь сайт, а после всех изменений перенести обратно на хастинг, удалив старый. Собственно вопрос заключается в том, ухудшится ли сео сайта и его позиция в выдаче (над сео когда то работала студия), при том что все ссылки, названия файлов и тд останутся такими же?
> Это всё удобнее всего делать на локальном сервере Насчёт удобнее - вопрос спорный. Но правильнее - однозначно на том же сервере. На др. домене, с закрытым извне доступом. См так же Как правильно перенести сайт на WordPress? > ухудшится ли сео сайта и его позиция в выдаче (над сео когда то работала студия), при том что все ссылки, названия файлов и тд останутся такими же? Если не накосячить, то с чего бы?
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "wordpress, seo, оптимизация сайтов, поисковые системы" }
Switch Requests to Content Specific to Requesting Domain Lets say I have several web sites on my web server, all as applications under one domain. How could I register other domains to point to the same web server, and redirect requests to, e.g. a web site linked to the requesting domain? I know I'll have to have a root site, and I'm guessing I may have have to do some voodoo in the request pipline on this root site, and dispatch a changed request to the relevant sub-site. Example, I would like _acme.net_ and _ajax.net_ to both point to the same address as _root.net_. When a browser requests _acme.net_ , the content at _acme.root.net_ or _root.net/acme_ , should be served, but the user must still see _acme.net_ in their address bar
On Apache you could do something like this: NameVirtualHost *:80 <VirtualHost *:80> ServerName acme.net DocumentRoot C:/www/ </VirtualHost> <VirtualHost *:80> ServerName acme.root.net DocumentRoot C:/www/ </VirtualHost> I hope it could be useful for you.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, apache, iis" }
Print Nothing Using Crystal Reports I'm trying to prevent anything from printing when a certain condition is met. For example, let's say I've suppressed every section for when `var="abc";`. However, when I try to print this report, a blank page gets printed. I'm using a Seagull printer and tearoff labels, if that makes a difference.
Make sure section properties of 'New Page Before' and 'New Page After' are turned off for the suppress scenarios.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "crystal reports" }
Как считать массив чисел с бинарного файла с помощью метода read()? void read(int* arr) { ifstream file_if; file_if.open("arr.txt", ios::binary); if (!file_if.is_open()) cout << "error opening file for reading" << endl; else file_if.read((char*)&arr, size); file_if.close(); } > size - замер массива; > file_if.read((char*)&arr, size); - чтение из файла сразу в целый массив, до этого была запись в файл "file_of.write((char*)&arr, size);"
`file_if.read((char*)arr, size * sizeof(int));` \- чтение целого массива; `file_if.read((char*)&arr, sizeof(int));` \- чтение одной переменной, той на которой стоит указатель `seekg()`(по умолчанию в начале файла); `for (int index = 0; index < size; ++index) {file_if.read((char*)arr[index], sizeof(int));}`\- чтение одного элемента в ваш массив под номером `index`; Работает это так: считываем элемент с файла и сохраняем его в массив под номером `index`, после чего указатель перемещается на sizeof(int);
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++" }
AWS Access Key for S3 user - Key works but don't see it anywhere in the AWS account's IAM users We're using a AWS Access Key/Secret pair for S3 uploads on an old client website. During an audit, we discovered that the Access Key used for uploads, while still working, doesn't appear to exist in any IAM user for the client's AWS account. I ran `aws sts get-access-key-info --access-key-id=[old key]` and it provided the correct AWS account id for our client. But searching for this key in our IAM users (< shows no results. How can this be? Can the Access Key live somewhere else outside IAM?
Accepted answer from @kdgregory > It could belong to the root user. If yes, then you very much want to disable it. – kdgregory 2 hours ago
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "amazon web services, amazon s3, amazon iam" }
Having CMD commands run in background I'm working on a python program. I want to run commands on cmd and have my result back in the program without notifying the user and also not opening the cmd window. So the whole progress should be in the background,and the output must be printed in my own program interface. I found OS module, does it satisfy my two demands? If yes, how? Thanks.
You can use threads to do stuff in the background. In python, one way of doing that is via the threading module. from threading import Thread import time def do_stuff(): time.sleep(5) print("tasks being done in the backgroud") print("Outputting Result to user") print("Program Begin") t1 = Thread(target=do_stuff) t1.start() while(True): print("Program doing other stuff") time.sleep(1) if t1.is_alive() == False: break Here we have a function do_stuff() that does something. Now, with help of threads, we can run it in the background and do other things meanwhile.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, python 3.x, cmd, background" }
What are the unit's of r in the equation r=mv/Be? I apologise for the incredibly basic question, but could anyone let me know the units of r (e.g. are they metres, millimetres, centimetres?) As my A-level physics teacher was incredibly inconsistent when describing this and there is nothing in the book on this point
All you need to know is that it has units for a length-scale. If you put all numbers in in SI-units (meter, seconds, kilograms, Kelvin, Amps etc) you _will_ get an SI-unit out. So only SI-units for the variables, and $r$ will come out in the SI-unit of length: _meters_. As the comment to the question describes, your question therefore can't be answered unless you tell the units of each value you plug into the formula. And honestly, if you know each unit that is put in, then you should be able to easily divide and multiply to see what the final unit of that calculation turns out to be.
stackexchange-physics
{ "answer_score": 1, "question_score": -1, "tags": "magnetic fields" }
Increase number of content database for one site collection I am using SharePoint 2013. * Is there any way to create more than one content database for one site collection? * Is there a way to increase the size limit of a content database using RBS or any suggested tool?
Whilst a content database can contain more than one site collection. A site collection however, can contain only one content database. RBS can be used to prevent database growth as it stores data in physical location. See more about RBS here:
stackexchange-sharepoint
{ "answer_score": 4, "question_score": 2, "tags": "2013, database, remote blob storage, rbs, size" }
Why on Heroku, if I click on "About your application’s environment", it will say page not found? Example: < If I click on "About your application’s environment" it will say: > The page you were looking for doesn't exist. > > You may have mistyped the address or the page may have moved. but if I run the server in development mode on my computer, it will pop down the info. (and all files are added and committed with git, as `git status` shows everything committed. This app is using Ruby 1.9.2, Rails 3.0.5)
The welcome page is not ment for production. so the url where the data is loaded from doesn't exist (`
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 2, "tags": "ruby on rails, ruby on rails 3, heroku" }
How to get the Row Number for a row after sorting using SQLite? My database table (Employee) consists of two columns (Name, Salary). I tried to sort the table based on Salary in descending order and get the corresponding row number based on Name. (To assign the rank based on highest Salary). I tried this query SELECT ROW_NUMBER () OVER ( ORDER BY Salary ) RowNum FROM Employee WHERE Name='Ram'; On my table, Ram gets the second highest salary. So I expect the output to be 2. But I got only errors. Please, someone help me with this problem.
Your query returns only 1 row because of the condition: WHERE Name='Ram' So you will always get 1 as result. Select the row number from the subquery with `RANK()` to handle ties for salaries and use `DESC` to sort descending the salaries: SELECT t.RowNum FROM ( SELECT Name, RANK() OVER (ORDER BY Salary DESC) RowNum FROM Employee ) t WHERE t.Name='Ram'; Another simpler and maybe more efficient solution without window functions: SELECT COUNT(*) + 1 RowNum FROM Employee WHERE Salary > (SELECT Salary FROM Employee WHERE Name='Ram');
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sqlite" }
Return HTTP Status Code 301 for all pages ending on .php How would I redirect all pages on my website that have /de/ _.php or /en/_.php in the URL? I dont want to redirect domain.com/index.php though, only domain.com/de/.php or /en/*.php.
You can use this rule RewriteRule ^(en|de)/(.*?)\.php$ / [R=301,L]
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": ".htaccess, http, redirect" }
How do I get water from a well into my waterskin? I figured out that I can `u`se the well, then `Lower the bucket`, then `u`se the well again, and then `Raise the bucket`. I'm guessing the bucket is full of water, but how do I fill my waterskin with the water in the bucket?
1. `u`se the well. 2. `Lower the bucket` 3. `u`se the well again. 4. `Raise the bucket` 5. `Shift`+`i`nteract with your `waterskin`. 6. `Fill _ waterskin from _ bucket (direction)`
stackexchange-gaming
{ "answer_score": 4, "question_score": 3, "tags": "dwarf fortress, dwarf fortress adventure" }
Nutch 1.6 find original url of redirected ones I wonder how could I find the original url after it hits a redirection. They're actually found on seedlist but I can not guarantee which url is redirected to which url. In Fetcher phase I expect to read it from Nutch.WRITABLE_REPR_URL_KEY, but it is overriden by redirected url. Any suggestion how to read them from crawldb, segments or linkdb? PS: I only crawl first-level pages (depth:1) on seedlist. Best, Tugcem.
You can dump the outlinks by doing the following bin/nutch readseg -dump crawl/segments/segmentname/ outputdir -nocontent -nofetch - nogenerate -noparse -noparsetext Also to properly follow the redirects, you might want to change this property in nutch-default.xml <property> <name>http.redirect.max</name> <value>5</value> <description>The maximum number of redirects the fetcher will follow when trying to fetch a page. If set to negative or 0, fetcher won't immediately follow redirected URLs, instead it will record them for later fetching. </description> </property>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, nutch, redirect" }
Materialize css- input range value popup I was wondering how to have the value of the range to show up when scrolling the range input <form action="#"> <h5>The Temperature</h5> <!--the temperature--> <p class="range-field"> <input type="range" id="temp" min="0" max="100" /> </p> </form>
Please try using `input.value` This should get the current input element value. <input type="range" min="5" max="10" step="1" oninput="showVal(this.value)" onchange="showVal(this.value)">
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "css, web, materialize" }
tensoring with flat module factors the kernel I want to show that if $F$ is a flat $R$-module, then for any $R$-homomorphism $\varphi: M \rightarrow N$, we have $$\ker (1_F \otimes \varphi) \cong F \otimes \ker \varphi $$ The $\supset$ direction is trivial. For the $\subset$ direction, I use the fact that $F\otimes(-)$ preserves the injectivity of the map $$ M /\ker \varphi \overset{\tilde{\varphi}}{\rightarrow} N $$ Thus if $f\otimes m \in \ker (1_F \otimes \varphi)$, i.e. $f\otimes [m]$ mapped to $0$ under $1_F \otimes \tilde{\varphi}$, we have $f\otimes [m] =0$. This suggests me to complete the proof by showing $$ F\otimes \frac{M}{\ker\varphi} \cong \frac{F\otimes M}{F\otimes \ker\varphi} $$ Is this relation true? It seems very plausible for me that $f\otimes[m] \mapsto [f\otimes m]$ gives the isomorphism. But I struggle at the injectivity part of the proof.
Since $F$ is flat, tensoring with it preserves exactness of _all_ exact sequences; from $$ 0\to\ker f\to M\xrightarrow{f} N \to \operatorname{coker}f\to 0 $$ you get the exact sequence $$ 0\to F\otimes\ker f\to F\otimes M\xrightarrow{1_F\otimes f} F\otimes N \to F\otimes\operatorname{coker}f\to 0 $$ which is (isomorphic to) the standard kernel-cokernel sequence for $1_F\otimes f$. Hence $$ \ker(1_F\otimes f)\cong F\otimes\ker f $$
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "abstract algebra, modules, homological algebra, flatness" }
change label on asp fileupload control I am using a asp fileUpload control, and was wondering if it is possible to change the lable on the button from the default "Browse". <span class="spanText"> <asp:FileUpload ID="fileUpload" runat="server" Width="280px" /> </span> From what i can read, there donesn't seem to be an easyway, unless I dig into its controls colection. Thanks
This is not possible out-of-the-box. "Browse" is really a convention and what people expect when browsing to a file on their own machine. You'd have to have a compelling reason to go to the trouble of changing it - and that would be a hack at best.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "asp.net, file upload" }
c++ syntax for initializing arrays I came across this code fragment, it compiles fine with g++. I can understand what is happening, but is this valid c++ or an extension? const char* msgs[] = { [0] = "message0", [1] = "message1" };
It is valid C syntax. In C you may use so-called _designators._ designator: [ constant-expression ] . identifier One more example struct A { int x; int y; } a = { .x = 10, .y = 20 }; However it is not valid in C++. In C++ you should write const char* msgs[] = { "message0", "message1" }; If a C++ compiler compiles the declaration you showed then it is its own language extension that is not C++ compliant.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "c++, arrays, initialization" }
Clone an Object3D model from a Collada load call I'm trying to clone an ThreeJS Object3D model. I've found various code here and on GitHub and nothing is working for me. The code below comes in part from How to clone an object3d in Three.js? var loader = new THREE.ColladaLoader(); loader.load('../Model.dae', function (result) { var loadedMesh = // No sure where this comes from // Create X of these for ( var i = 0; i < 10; i ++ ) { var mesh = new THREE.Mesh( loadedMesh.geometry, loadedMesh.material ); mesh.position.set( i * 100, 0, 0 ); scene.add( mesh ); } } Can you help be fill in the blanks?
This ended up working: var loader = new THREE.ColladaLoader(); loader.load('../Turn.dae', function colladaReady(result) { var piece = result.scene.children[0]; for (var i = 0; i < 10; i++) { var newPiece = new THREE.Object3D(); for (var j = 0; j < piece.children.length; j++) { newPiece.add(new THREE.Mesh(piece.children[j].geometry, piece.children[j].material)); } newPiece.position.set(i * 100, 0, 0); newPiece.scale.set(30, 30, 30); scene.add(newPiece); } renderer.render(scene, camera); }); So instead of getting a single mesh, I got a group of meshes. I'm new to this, so I don't know why this is different from what every other answer I've seen. The dae file was exported directly from Sketchup. I'd be interested in knowing if there is a easier/better was to do this.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "three.js" }
NSMutableArray:How to allow duplicate values I'm reading a JSON code such as: [{"question_id":"1", "trigger_value":"Yes", "question_text":"What is your first name?", "question_type":"YN"}, {"question_id":"2", "trigger_value":"Yes", "question_text":"What is your second name?", "question_type":"YN"} ] But once it's set into NSMutableArray, the duplicate values are deleted. I would like to allow them to check the question_type for each question. NSString *question_id; NSString *question_text; NSString *question_type; while (dicjson = (NSDictionary*)[enumerator nextObject]) { question_id = [dicjson objectForKey:@"question_id"]; question_type = [dicjson objectForKey:@"question_type"]; [mutjson setObject:question_id forKey:question_type]; } Would you give me any idea of allowing duplicate values...? Thanks in advance.
mutjson looks like a mutable dictionary and not a mutable Array. So yes, in a dictionary object if you are setting the same key, it will overwrite the previous value. If you need to store dictionary object, create a mutable array and add each object inside that array as a dintionary object... NSMutableArray *results = [[NSMutableArray alloc] init]; while (dicjson = (NSDictionary*)[enumerator nextObject]) { question_id = [dicjson objectForKey:@"question_id"]; question_type = [dicjson objectForKey:@"question_type"]; [result addObject:[NSDictionary dictionaryWithObject:question_id forKey:question_type]]; }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "iphone, objective c" }
MySQL query who return 0 or 1 according date I have this query: SELECT DATE_FORMAT(DATE_SUB(`expiry_date`, INTERVAL 7 DAY), '%d %m %Y') FROM `my_subscriptions` WHERE `user_id` = '[user_id]'; which returns `expiry_date` minus 7 days; let's call that the "returned date". Now I would like compare this "returned date" against the current date (the time right now), returning `0` if the current date is less than or equal to the "returned date", and `1` if it's bigger. How can I do that?
You can use CASE and also use `NOW()` for the current date time. Try this SELECT CASE WHEN NOW() <= DATE_FORMAT(DATE_SUB(`expiry_date`, INTERVAL 7 DAY), '%Y-%m-%d') THEN 0 ELSE 1 END AS is_expired FROM `my_subscriptions` WHERE `user_id` = '[user_id]';
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql" }
finding manager id from employee table I have a table data like in the below. Emp_id Emp_name Dept_id 111 aaa 1 222 bbb 2 333 ccc 3 444 ddd 4 555 eee 5 Then i want to populate new column manager id as next emp_id from the employee table like in the below. Emp_id Emp_name Dept_id Manager_id 111 aaa 1 222 222 bbb 2 333 333 ccc 3 444 444 ddd 4 555 555 eee 5 111 Thanks for your help in advance!
You can return the value as: select t.*, coalesce(lead(empid) over (order by empid), min(empid) over () ) as manager_id from t; Perhaps a `select` query is sufficient. Actually modifying the table is a bit tricky and the best syntax depends on the database.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "sql" }
A collection of arithmetic series in $\mathbb Z$ is a basis for a topology > Show that the collection of arithmetic series $S(a,b)=\\{an+b\mid n\in \mathbb Z\\}$ in $\mathbb Z$ is a basis for a topology. I know the definition of basis of topology, but I don't know how to approach this question. This is not a homework question, I'm preparing myself for a quiz.
In order for the collection of all sets $S(a,b)$ to form a basis, they must satisfy two conditions: a) Every integer in $\mathbb{Z}$ must belong to some basis element; b) If an integer lies in two basis elements, then there exists a third basis element containing that integer and contained in the intersection of the two basis elements. The first condition holds because $\mathbb{Z} = S(1,0)$. The second condition holds because if $x$ lies in the intersection of the two arithmetic sequences $S(a,b)$, $S(a',b')$, then we have $S(a,b) \cap S(a',b') = S(\operatorname{lcm}(a,a'),x)$. Interesting fact: this result is the basis (hehe) for Furstenberg's topological proof of the infinitude of primes. A few years back I made some slides for a short presentation concerning this cute result; you can find them here if you are interested.
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "general topology" }
What type of Rasengan did Boruto used? When Boruto fires his Rasengan it varnishes. What type of Rasengan did Boruto use?
When Boruto is trying to convince Sasuke to train him, he creates a small rasengan infused with wind chakra. > Though Boruto's Rasengan is initially much smaller, he subconsciously applies wind-natured chakra to it, enabling him to hurl the Rasengan across distances. While it loses its physical form shortly after bring thrown, the wind and force continue on-course unseen, tricking the opponent to let their guard down as sufficient damage is inflicted when it makes contact. Boruto eventually becomes able to create a normal-sized Rasengan after more training. - naruto.wikia.com/
stackexchange-anime
{ "answer_score": 3, "question_score": 1, "tags": "naruto" }
How do I get a list of suppressed code analysis warnings from a visual studio project? I have enabled code analysis for all the projects in a solution. To overcome various code analysis warnings the code contains numerous code suppression attributes (System.Diagnostics.CodeAnalysis.SuppressMessage). I want to get a list of these suppression attributes. I want this list so that I can see if the suppression is still needed and check that we have suitable justifications specified. Does anyone have or know of a good method/plugin/tool to get a list/report of suppressed code analysis warnings from a visual studio project/solution?
`Edit -> Find and Replace -> Find in Files`, or default shortcut `Ctrl`+`Shift`+`F`. Just tell it to search for `SuppressMessage` in the entire solution. It will drop all of the results with their file locations into a dialog, which you can copy/paste into your viewer/editor of choice.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "visual studio 2012, code analysis, fxcop" }
Can I use the javascript interpreter inside Firefox as a js shell? I would like to start coding with JS by writing more evolved versions of my bash scripts, therefore I would like to take actions like download a package, unpack it, move between folders, execute shell/system commands, etc etc ... . Now I would like to use the integrated shell interpreter inside Firefox but without any DOM related features and basically it should be as "dry" as possible so I can get a fairly standard JS shell and also a more simple set of APIs. Someone knows if I can do that ?
There's Rhino and SpiderMonkey which are both related to the Mozilla JS engine. A list of other JS shells is here which include things like Node (based on the Chrome V8 engine). I'm personally using Node just because the level of 3rd party support for Node modules seems to have really taken off in the last couple years and you can also use it for web server development if you so choose and it all runs on many platforms.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, shell, firefox" }
Are content scripts in Chrome extensions run in the extension process or the tab process? Are content scripts in Chrome extensions run in the extension process or the tab process? I.e. if my extension process in the Chrome task manager is taking up a lot of CPU, is the offending code most likely in the content scripts, or the background page of my extension.
They are run in the tab's process.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "google chrome extension" }
Oracle, Pl/SQL: substitution/replace function I am facing a unique challenge, the problem I'm facing is something like this: I need to ignore the zero from the input: For example Example 1 Input --> 1580 output --> 158 Example 2 Input --> 3008 output --> 38 Is there any built function or through normal query I can solve the above problem or do I need to write custom pl/sql code. Please suggest.
SQL: select 3008 original, REPLACE(TO_CHAR(3008), '0', '') replaced from dual; Result: original | replaced ---------|---------- 3008 | 38 ---------|----------
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, oracle" }
Concept for read more (button) in post and showing post until read more tag Can someone explain the PHP concept in blog posts for showing text until read more is inserted and some function which can recognize the read more tag like in wordpress `<!--more-->` and show text until tag read more is inserted. Thanks
You can just use a string split around the read more tags, anything before it is essentially your abstract, the concatenation of the before and after is your full text. You can use javascript on the frontend to switch between the abstract and full text when pressing the more/less buttons.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "php" }
(Null) Values in SSAS cube when selecting a role I have the following problem: When I process a cube in SSAS and view the data as a normal user without restrictions all is well and the aggregated results show their normal values. When I choose inside Data Tools (MsSQL 2012) to view the data as a specific role then all the security constraints work normally (For example I view only the Specific country data and no other) but all the corresponding values are (null). I have tried Visual Totals = true and I have imposed those restrictions on both the dimension and the cube. The CALCULATE in calculation script is still there (everything works ok when I choose to use a normal user). This is happening on both the measures and the calculated values!!! Any ideas what could be happening?
**Solved.** This problem had to do with **cell data**!!! The Data Tools studio **automatically checks** the **enable Cell Data permissions** checkboxes in the respective tab. If no MDX query is defined in these, then it is automatically assumed that you have no permissions to view any aggregated measure data!!!! _**Uncheck them_** or **_define_** the proper **_MDX query_** and the problem will be fixed!!!!
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "sql server, ssas, security roles" }
Weird output from URL html source Swift Basically I'm trying to download the HTML source code of a `URL` object into a String... I've followed step-by-step examples of how-to-do so on StackOverflow. import Foundation try! print(String(contentsOf: URL(string: " encoding: .utf16)) This is a small sample of the output I'm getting: ⁡ When I was really just expecting some plain HTML output. The only thing I could think that's causing this issue has to be related to Networking(such as the `DNS` servers being queried). But, just in case I'm asking it on here to get a review of the code.
It's unclear why you want to encode the output to `UTF-16`, although removing it should work: try! print(String(contentsOf: URL(string: " That should return the `html` of the `URL`. You can use an encoding, however, `UTF-16` is likely not correct in this circumstance. try! print(String(contentsOf: URL(string: " encoding: .ascii)) `ASCII` would likely work.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "swift" }
Mint 16 Cinnamon, maximize window fully I am using Linux Mint 16 Petra cinnamon. The problem I have is that when I drag a window to the top edge of the screen the window only maximizes to the top half of the screen instead of the the entire screen, just like when I hit the maximize button (plus button on the top right side of the screen). This is what I get. !enter image description here This is what I want to happen. !enter image description here
Go into System Settings, then into "Window Tiling and Edge Flip" and check the box marked "Maximize, instead of tile, when dragging window to top edge".
stackexchange-unix
{ "answer_score": 31, "question_score": 22, "tags": "linux mint, window" }
nuxtjs is blocking the loading of youtube videos by default or is it the browser? I have set: render: { csp: false }, in my nuxt.config.js but youtube videos are still being blocked by CSP? is that a default browser thing?
The issue was not with nuxtjs but rather csp settings in my nginx config which overrode nuxtjs settings via http header injection.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "vue.js, vuejs2, nuxt.js, content security policy, nuxtjs" }
What Emacs Lisp function is to `require` as `autoload` is to `load`? I am trying to program GNU Emacs 23 to issue `require` commands lazily, on demand, instead of up front in my `.emacs` file. If I wanted to delay the execution of a `load` command, I could use `autoload`. But `require` and `load` take different sorts of arguments. Is there a predefined function that does for `require` the same job that `autoload` does for `load`? And if not, what tools would people recommend that I use to roll my own?
There is not difference between `require` and `load` with regards to `autoload`. `require` is just a frontend to `load`, which more or less comes down to: (defun require (feature &optional filename noerror) (unless (featurep feature) (let ((filename (or filename (symbol-name feature)))) (load filename noerror)))) As you can see, the symbol name given to `require` is equal to the filename given to `load`. As a matter of fact, the first `(require 'foo)` evaluated in an Emacs session is equivalent to `(load "foo")`. Thus, you can just use `(auto-load 'foo-function "foo")` for `foo-function` from the library `foo`, that you can load with `(require 'foo)`.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 8, "tags": "emacs, elisp" }
Ubuntu 16.10 to 16.04 Hi guys I have a laptop dual-booted with Ubuntu 16.10 and Windows 7. So I was wondering if I could downgrade back to 16.04 LTS and btw I installed 16.04 then upgraded to 16.10. I really want to go back to 16.04 because a lot of software I want hasn't been released for 16.10 "Yakkety"
There is currently no way of doing a "rollback" to Ubuntu 16.04 LTS. However you could always just backup, get the 16.04 LTS installation files and clean install.
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "16.04, 16.10, downgrade" }
Word for a religious leader who has been forsaken by their followers I'm looking for a single adjective to describe a religious leader, e.g. a priest or the Lord, who has been forsaken by their followers. Not necessarily betrayed, but had the followers' faith lost. The word would be used as a name of a "unit type" in a game: "____ Imam", "_____ kohen". I'd prefer the word to be an adjective bringing connotations of having fallen from grace, and for a word that most would understand. I've tried looking for antonyms of "forsaken", "betrayed", "praised", "sacred" and similar. The closest word I've found would be "fallen kohen", which doesn't fit as it seems to put the kohen at fault.
A thesaurus look up would suggest words like _deserted_ , _jilted_ , or _disowned_ , but I suspect **disgraced** may fit your use case. > having fallen from favor or a position of power or honor; discredited. Google > the loss of respect, honor, or esteem; ignominy; shame: Dictionary.com
stackexchange-english
{ "answer_score": 1, "question_score": 2, "tags": "single word requests" }
Is it possible to select multiple tables with different quantity attributes? Note: I looked in this forum and could not find the solution I'm looking for. These are the tables I created: library: name, registry book: date, author, code Question 1: Is it possible to select the attributes of the two tables even though they have different attribute amounts? Question 2: Can I access (select) the attributes of the `book` table through the `library` table?
Q1: Yes, as long as they have a common relation (primary key, foreign key). If they have a relation you can always query to get items even if they have different number. Q2: Yup! You can select books through the use of the library table. You can use something similar to: SELECT book.author FROM library INNER JOIN book ON library.registry=book.code;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "mysql, sql" }
Where are the entries located for icons listed in Show Applications? When I open up the Show Applications menu to see all my installed software, I see a lot of dead links, mostly for programs I have previously installed through Wine, which I no longer use. However, I can't delete them. Is there some place I can manually edit or delete these from? Running Ubuntu 19.04.
Application launchers (files with `.desktop` suffix) for apps installed using Wine should be found in your `~/.local/share/applications/` directory. However snap applications may also exhibit the same issue, viz. ghost icons in application overview after uninstalling the application. In that case the launchers would be found in `/var/lib/snapd/desktop/applications/` directory.
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 1, "tags": "gnome shell" }
KeyError handling for variable depth dictionaries I have a list of dictionaries that have variable depth and different keys. for example: a = [{attr1: 1, attr2: {secondary_attr1: 'sometext', secondary_attr2: 'sometext', complex_attr: {more_attr: 999}}}, {attr1: 2}] I am using a class to collect all the information I need from each element of the list, but of course when I try to get an item from a key that is not in that particular dictionary, I get KeyError. Here is how I am creating the instances for each element of the list a: InsertLine(i['attr1'],i['attr2']['secondary_attr1']) I tried to define a simple function but it doesn't work: def handle_keyerror(try_key): try: try_key return try_key except KeyError: return 'NULL' I hope I made the probem clear.
Your function doesn't work because it will always return try_key. Try this. def handle_keyerror(try_key): try: your_dictionary[try_key] except KeyError: return None return try_key Anyway it is a bad idea to check it like that. You should rather use `dict.get(key, default=None)`. If in dict there is no key `key` then it will return default value.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, error handling" }
What's the recommended way to create a native-looking UI on Firefox OS? I understand that in Firefox OS every app is a web app, but I'd like to create a "native" look & feel in my own application, meaning that I want it to "fit in" with the built-in application styles. Mozilla even has a style guide for this: < **Is there a stylesheet and/or a JavaScript which I can include in my app in order to create controls and UI elements that look like the ones in the style guide?** (The only download I could find on that site was a PSD containing all the designs, but I'm looking for something ready-to-use.)
You have the good link for some UI guidelines, but you can check what we call the Building Blocks or even get those on GitHub. Another way is to see what we did in GAIA, but in any situations, it's not just about importing a CSS file.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "javascript, html, css, user interface, firefox os" }
Convert SQL to LINQ/EF I want to convert this SQL query to LINQ. But I'm new in EF. Please help SQL Query select * from VersionHistory where id in( select OptionsId from StylesHistory where ConId=540 and OptionsId = 28286 and ModifiedAtVersion>1) TIA I tried Something like this var stylesHistory = _context.VersionHistory .Where(x => x.ModifiedAtVersion > 1 && x.Id==28286 && x.Contract.Id==540) .ToList() Not Sure How I can add Sub Query
You can easily write that as: var result = ctx.VersionHistory .Where(vh => ctx.StylesHistory .Any( sh => sh.OptionsId == vh.Id && sh.OptionsId == 28286 && sh.ConId = 540 && sh.ModifiedAtVersion > 1));
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "sql, sql server, entity framework, linq" }
R:Extracting words from one column into different columns I've been figuring this out for a couple of hours now. Let's say I have a column with 1-4 words, separated by space: aba bkak absbs a2aj akls bios sad fasa lgk . . . I would like those words to be in separate columns, for easier further processing. SO instead those words are in one column, how do I get them to separate columns? Thanks for any help.
Try library(splitstackshape) cSplit(df1, 'V1', ' ') Or library(tidyr) separate(df1, 'V1', paste0('V', 1:4), sep= ' ', extra='drop') Or using `base R` read.table(text=df1$V1, sep=' ', fill=TRUE) NOTE: Used the column name as 'V1' and dataset as 'df1'
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "r, multiple columns" }
DIY Leather engraving Is there a way to engrave or carve words into leather without the use of professional engraving or stamping tools? I want to make one similar to the one in the picture, but can not find the kit to do so anywhere in my local stores. I read somewhere that it could be done by heated knife but I'm not sure. Any help, please? (Any link to a tutorial would be appreciated, too) ![enter image description here](
[![Image from \[Wikimedia Commons\]\( Traditionally engraving like this would be done with a swivel knife \- these will generally cost a few pounds or dollars, so are much more affordable than a laser engraver. They do take a bit of skill to use, so I would suggest practising on some offcuts first. You can find tutorials on swivel knife usage all over the internet.
stackexchange-crafts
{ "answer_score": 1, "question_score": 2, "tags": "leather, carving" }
Como usar o "echo" em uma view do Laravel? Estou querendo que no meu `layout` `blade` **`echo`** somente se a variável `$errors` estiver definida: @section('mensagens') <div class="container"> <div class="row"> <div class="col-md-2"></div> {{ isset($errors) ? '<div class="col-md-8 alert alert-danger">' $errors->first('prontuario') $errors->first('senha') '</div>' : '' }} <div class="col-md-2"></div> </div> </div> @show Como eu faço para ele só mostrar essa `div` da classe `alert-danger` se a variável `$errors` do meu formulário estiver definida?
Você também pode fazer assim: @section('mensagens') <div class="container"> <div class="row"> <div class="col-md-2"></div> @if (count($errors)) <div class="col-md-8 alert alert-danger"> @foreach ($errors->all() as $error) {{ $error }} @endforeach </div> @endif <div class="col-md-2"></div> </div> </div> @show Em vez de você setar cada erro individual, você percorre todos os erros e exibe cada um.
stackexchange-pt_stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "php, html, laravel, mvc, laravel blade" }
Embedding a PDF as a resource in WPF application I want to embed a PDF file (which is basically have Product details, Release notes) and wants to open that file from menu bar. What would be the best approach. I need to use this file in installer also. So i'm looking for an approach in which file will be moved to BIN on compilation and from there installer can access that file. IDEAS ...
Finally i did it in following way: a. We've a folder which contains notes.pdf (used by installshield). b. Created a pre build command to copy the pdf file from installshield folder to output directory. c. use process.start("notes.pdf"); to open the file. As it would look in bin directory first for pdf file and we've already copied it there. It worked for both Installer version and running application from code.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, .net, wpf" }
View getVisibility() isShown() return incorrect visibility I've a view that gets conditionally added to parent. I check if its already added to parent or not, unfortunately, it always return its visible. if (findViewById(R.id.bottom_bar).getVisibility == View.Visible) if (findViewById(R.id.bottom_bar).isShown()) both return `true` even when view was never added ans is not visible.
`getVisibility()` simply returns the visibility you want the view to have when added to the window. It doesn't change unless you call `setVisibility()`. It also doesn't indicate whether the view is actually visible on screen. `isShown()` is similar. Here is the doc: > Returns the visibility of this view and all of its ancestors > > **Returns** > True if this view and all of its ancestors are `VISIBLE`
stackexchange-stackoverflow
{ "answer_score": 38, "question_score": 15, "tags": "android" }
subversion ignore nestered externals I'm working on a big project using subversion, and we use externals everywhere. This makes an "svn up" take forever since it has a delay on each external. To fix this, I want to remove some nested externals. Is there a way to add an external but specify that you don't want IT'S externals? Example layout, where "A -> B" means "dir A is an external of B": /modules/testfiles /modules/mymodule /modules/mymodule/testfiles -> /modules/testfiles /proj/mymodule -> /modules/mymodule That last external adds the nested "testfiles" external: /proj/mymodule/testfiles -> /modules/mymodule/testfiles -> /modules/testfiles Is there a way to prevent nested externals like this?
I am not aware that this is possible with `svn`. You could look into `svn up --ignore-externals` and see whether this helps. Alternatively, you can try to `svn up --set-depth empty <dir>` on those (external) directories you do not wish to update.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "svn, svn externals" }
Get only filename from url in php without any variable values which exist in the url I want to get filename without any `$_GET` variable values from a URL in php? My URL is ` I only want to retrieve the `learningphp.php` from the URL? **How to do this?** I used `basename()` function but it gives all the variable values also: `learntolearn.php?lid=1348` which are in the URL.
This should work: echo basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']); But beware of any malicious parts in your URL.
stackexchange-stackoverflow
{ "answer_score": 81, "question_score": 62, "tags": "php, url, get, filenames" }
How can I get the JWT access_token after loging in with ADAL.js? I see that adal.idtoken is stored in the cache. However, it doesn't look like a JWT which is what I think I need to pass to my azure mobile service to get a AUMO auth token.
If you want to retrieve cached tokens programmatically, see AuthenticationContext.prototype.getCachedToken from < All the tokens issued by Azure AD are JWT tokens.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, adal" }
SpyOn SideNav does not find given method I have a side navigation menu in my test project and i want to write a simple test to check that the sidenav opens ( **toggles** ) when i click the button. The AppComponent itself references to sidebar via its dependency sidenavbar. it('when button is clicked, sidenav appears', async(() => { const fixture = TestBed.createComponent(AppComponent); const component = fixture.componentInstance; let sidenav_button = fixture.debugElement.nativeElement.querySelector('button'); fixture.detectChanges(); expect(component.sidenavbar.opened).toBeFalsy(); spyOn(component.sidenavbar, 'toggle'); sidenav_button.click(); fixture.whenStable().then(() => { fixture.detectChanges(); expect(component.sidenavbar.toggle).toHaveBeenCalled(); }); right now it says, the method toggle() does not exist to spy on it. I am pretty sure it actually does.
It could be that `toggle` is private and you can't spy on it. `sidenavbar` is an `object` within `AppComponent`, correct? It's not a child component? If I were you, I would just see the `opened` property changed. it('when button is clicked, sidenav appears', async(() => { const fixture = TestBed.createComponent(AppComponent); const component = fixture.componentInstance; let sidenav_button = fixture.debugElement.nativeElement.querySelector('button'); fixture.detectChanges(); expect(component.sidenavbar.opened).toBeFalsy(); // spyOn(component.sidenavbar, 'toggle'); sidenav_button.click(); fixture.whenStable().then(() => { fixture.detectChanges(); expect(component.sidenavbar.opened).toBeTruthy(); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "angular, typescript, unit testing, testing" }
Datepicker minDate today and maxDate 31 Dec Next year Try to limit the date selection between today and 31st Dec of next year. $(function() { $('.public-holiday-date-pick').datepicker({ minDate: '0', yearRange: '-0:+1', maxDate: ??? hideIfNoPrevNext: true }); }); How should I define maxDate ? tried few things like '31 12 +1', or just 'last day of next year', did not work.
1) First get today's using var today = new Date(); 2) Similarly set the **`lastDate`** as below var lastDate = new Date(today.getFullYear() +1, 11, 31); The value in `lastDate` will be like > **`lastDate = 31 December, today's year +1`** Finally set the **`lastDate`** as **`maxDate`** var today = new Date(); //Get today's date var lastDate = new Date(today.getFullYear() +1, 11, 31); //To get the 31st Dec of next year $(function() { $('.public-holiday-date-pick').datepicker({ minDate: '0', yearRange: '-0:+1', maxDate: lastDate, //set the lastDate as maxDate hideIfNoPrevNext: true }); }); ## JSFiddle
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "datepicker, jquery ui datepicker" }
df --total command for mac? I want to use command line to retrieve the total disk space on a machine as one value. On most Linux machines, the "df --total" returns such a value at the end of the regular df output. On osx9, 10, 11, and 12, there seems to be no option like this. [u'df: illegal option -- -\n', u'usage: df [-b | -H | -h | -k | -m | -g | -P] [-ailn] [-T type] [-t] [filesystem ...]\n'] Same issue with older linux os, redhat5, centos5, etc. Another way to approach this? Is there another command to isolate certain values? I am mainly looking for the "total% used" value.
You'll have to calculate the value yourself, e.g. using awk: df | awk ' BEGIN { SIZE=0; USED=0; AVAILABLE=0 } // { print } $3~/[0-9]/ { SIZE += $2; USED += $3; AVAILABLE += $4 } END { printf "total\t%lu\t%lu\t%lu\t%d%%\n", SIZE, USED, AVAILABLE, (USED * 100 / SIZE); }' to break it down * line 1 of awk sets up the variables at the start, * line 2 prints every line (I'm making it explicit), * line 3 says if I find a number in the third column add it to the totals * line 4 says at the end print a 'total' line (somewhat similar to `--total`'s line)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "linux, macos, command, diskspace" }
How to add a rewrite condition to only pass URL's with one folder depth? I have a rewrite rule that needs to only be applied to urls that go no further in depth than 1 folder example.com/a >> rewrite me AND NOT example.com/a/b >> don't rewrite me So I only need to rewrite urls with a depth of 1. Greater depth is allowed but needs to go through unaltered. How would i do that doing a Mod_Rewrite condition statement? And where can I have my personal rewrite rule written. Thank you!
RewriteEngine on # Matches URLs which are equal to: "", "<text>", or "<text>/" # if it matches, the rewrite engine does not attempt to match any more patterns RewriteRule ^[^/]*/?$ - [L] # If the above doesn't match, meaning it's depth is more than one, # it forbids the content from being delivered RewriteRule .* - [F]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "regex, apache, mod rewrite" }
How would I access a list in a dictionary? I am currently working with the ROBLOX API service and giving me the audit log from a group. The only problem which has occurred now is: I don't know how I would use it normally. Anyone of you got maybe an idea how I would access the date: dictionary -> data . The dictionary is looking like this when I use: `for x in finalresponse:` ![enter image description here]( . When I then just print the dictionary by itself it comes this: ![enter image description here]( So, as I already asked: How would I access then in the dictionary the list data with all the other important data?
print(finalresponse["data"]) Basic :)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "python" }
What is the simplest way to do settings files in Java? Obviously enough, I want to avoid hardcoding paths and such into my application, and as a result, I'd like to make a settings file that will store simple things like strings and such. What is the simplest way to do so? I was thinking something along the lines of how Cocoa uses object persistence, but I can't seem to find anything equivalent.
You could use properties files which are manipulated with the java.util.Properties class.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 5, "tags": "java" }
How can I use error_log() with WordPress? I'm trying to use `error_log()` in a custom WordPress plugin I am building but for some reason, I can't. When I use `error_log()` my site just breaks, but I'm not seeing any errors in `debug.log`. I have setup debugging in my `wp_config.php` file like this: define('WP_DEBUG', true); define('WP_DEBUG_LOG', true); Stranegly, if I use `error_log()` in my theme, the site doesn't break, but nothing is output to `debug.log` either. What do I need to do to be able to use `error_log()` in my WordPress plugin and theme? I'm using WordPress 3.9.1.
According to the Codex, `WP_DEBUG_DISPLAY` should be set to true by default, but it would seem that was not the case. Adding `define('WP_DEBUG_DISPLAY', true);` to `wp_config.php` fixed the error logging. Setting `WP_DEBUG_DISPLAY` to `false` removed the errors from the browser but allowed them to be output in the log. It would seem that Wordpress requires `define('WP_DEBUG_DISPLAY');` to output errors to the log whether you set it to be `true` or `false`.
stackexchange-stackoverflow
{ "answer_score": 19, "question_score": 30, "tags": "php, wordpress, debugging, error logging" }
Reading Powerpoint SmartArt in Java I found Apache POI doesn't support reading SmartArt component. (Am I right?) So I tried Aspose.Slides and it worked. But the trial version has critical restriction. (can't get text has length over 5 characters) Can anybody help?
You can read SmartArt with docx4j/pptx4j. To see how it is represented, upload your sample pptx to webapp.docx4java.org/OnlineDemo/PartsList.html then click through into the /ppt/diagrams parts. There is also a document Creating SmartArt with docx4j, though please note this is an advanced topic (and you are largely on your own).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "apache poi, powerpoint, openxml" }
AWStats and Time Taken to serve the Request I have several IIS 6 web servers I manage and I turn on the time-taken field in the logs. I use AWStats to generate various reports from the log data. One of my developer counterparts has recently asked me to provide a report based on the Time-Taken data. She is specifically looking for top 20 pages sorted by average time-taken, plus min and max time-takens. I am thinking that I can achieve this by creating an ExtraSection in my AWStats config file. Is this feasible? Does anyone have any config samples they are willing to share? Any pointers are greatly appreciated.
It'll be very difficult to know how long the entire page takes to load. Not impossible, but difficult. You will need 'group' by referrals. For each PHP/ASP/Whatever/HTML page that is output, then find all the requests immediately after it that have the referrer of the just-requested page, for that IP address. Keep going until that IP requests another HTML page. Repeat and rinse. As for how to actually do this in AWStats, I honestly don't know. You might need to do up a script or something to parse the logs manually.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 5, "tags": "iis 6, log files, awstats" }
Emacs Display Effects with Yasnippet Yasnippet has a nice "run ... after exiting a snippet". What I would like to do is include some visual effect after each ending snippet (changing background color for, say a second, or more sophisticated stuff). I did this by switching background colors back and forth in that hook, but it's really short and not efficient, and also ugly. However, how can this, or something similar be done with a timer? Optional: Suggestions for fancy effects (including a timer) are welcome.
You can change the background once and then change it again 1 second later by using `run-with-timer`: (run-with-timer 1 nil 'my-fun) where `my-fun` does the action you want.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "emacs, colors, background, yasnippet" }
What is the working principle of electric arc lighters? How do electric arc lighters work? The wikipedia article about this is very short. So I understand that there is a current at low voltage that leaps over air and turns it into plasma, but what then is the purpose of four points that create a cross of plasma like in this company's products? Is this a new invention or just perfected enough in recent years (batteries with enough capacity?) to be suitable for hand held battery driven lighters? ![enter image description here]( The image of the lighter is taken from here. Ps. Sorry for asking multiple questions at once but they all seem interrelated to me.
the crossed-arc trick is a way of stabilizing the formation of the arc. this was learned over 100 years ago when arcs were used in a primitive radio transmitter called a spark gap transmitter. these fell out of use after vacuum tubes were invented but in the years before that, lots of clever experimental work went into making arcs stable and repeatable, and the multi-electrode arc was one of them.
stackexchange-physics
{ "answer_score": 3, "question_score": 0, "tags": "everyday life, plasma physics" }
Django Querysets & dynamic string filtering It seems that `__in` is only suitable for integers. I am trying to filter by strings. I've tried this but it does not work. groups = ['foo', 'bar'] args = [] for group in groups: args.append(Q(name=group)) group_ids = Group.objects.filter(*args) What is the preferred way to dynamically filter a Django queryset using strings?
`__in` can be used for strings as it translates to a SQL `IN` operation. Whether or not it is case-sensitive my depend on your table/column collation.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "django" }
Can Hazelcast jet stream directly trigger events? After a stream is being processed (applying filter and etc), can each of the remaining items in the processed stream trigger events directly instead of being written to a sink? I have a bunch of devices keep reporting status to the hazelcast jet stream server. The server performs some filtering on the stream and only keeps devices that are really in bad shape. I want these devices directly trigger some maintenance events instead of being written to a sink (e.g. IMAP). Currently, what I am doing is to sink the stream to a IMAP and register listeners on the map. However, I am not sure if this is the best practice for my use case. I mainly have two concerns: 1. I don't necessarily need to store those devices. All I need is to tell some other service the device needs to be maintained. 2. Doc says heavy logic shouldn't be put in the listener. What should I do if the task triggered by the event is comprehensive?
Looks like what you need is a custom sink, see our Reference Manual section on the topic. In the `receiveFn` you can notify the other service about the device.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "hazelcast, hazelcast imap, hazelcast jet" }
Is it possible to add an attachment to an existing Task or Event? Using the standard Salesforce interface for Tasks (Page Layout), there is a related list for Attachments. However, there's no button to add a new Attachment to an existing Task, and when I edit the Tasks Page layout the Attachments related list is "not customizable". **Is there another way to add an attachment to a Task (or Event)?** I'd like to make sure I'm not missing anything using standard customization before using Apex/Visualforce.
You just need to Edit the task itself to see the Add Attachment button. It's only available in the task edit view.
stackexchange-salesforce
{ "answer_score": 10, "question_score": 7, "tags": "attachment, tasks" }
Fetch particular tags from HTML docs obtained after crawling and parsing using Apache Nutch 1.4 I used nutch 1.4 and crawled a website. I got the website crawled successfully and all the pages were dumped into segments. I merged all the segments to one segment and then i used readseg command to obtain a text version of all the crawled pages. Now I need to find out, URL of page and the meta data stored in that page. I don't know which command to use or shall i need to do something different. Have made a lot of efforts on google Some people said that you have to write a separate plugin for it. Can someone tell me please. Thanks a lot :) :)
Finally, I am able to do it. Sharing in case someone else needs it. You can use index-metatags plugin provided here: < It will solve this problem Cheers :)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, apache, meta tags, nutch" }
Black screen after changing systemctl I wanted to start my MacBook running Linux Mint laptop in terminal mode, so I searched the internet and found this command: `systemctl set-default multi-user.target` After running that command and rebooting, it started normally but ended in a black screen. It looks like it turned off my screen and I can enter my rEFInd boot menu and I can change boot options from there, but I don't now how this works. What can I do?
You may be able to return to the original state by running `systemctl set-default graphical.target` If you are not even able to boot, you could try adding this boot option/argument `systemd.unit=graphical.target`
stackexchange-unix
{ "answer_score": 0, "question_score": 0, "tags": "boot, refind" }
Calculate average using average value I hope the title makes a bit of sense, as I don't know how to phrase it. Basically, I'm writing a script which checks the response time of a server in milliseconds. But instead of having thousands of values, I'd like to just stick to a single average value. What math would I need to use for using an average value to calculate a new average value? Ie: ` 9 + 4 + 7 = 20 / 3 = 6.666667 <-- correct average 9 + 4 = 13 / 2 = 6.5 + 7 = 13.5 / 2 = 6.75 <-- incorrect average ` What would I need to change in that 2nd calculation in order to keep getting the correct average?
You can't do this without a few more variables. You'll need to know $N$, the number of data points. Then you do what you did: $$Avg_{new} = \frac{(Avg_{old}*N + Data_{new})}{N+1}$$ And be sure to update $N = N+1$ afterwards.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "average" }
Is it possible to fire a browser's about window with Javascript? Well the title explains my whole question. What i want to archive, is a revolutionary 'upgrade' button, that when you press it, the browser's native 'update' window pops up. If it is not present, then it create's an fake update window, so that users can update the browser. I do not longer want to support the old IE6 browser. I want to force my users to upgrade their browser as it is insane to support a 10 year old browser.
If you are looking to get remove support for IE 6, I suggest visiting Microsof't website dedicated to the cause < The site contains instructions on how to place a banner on your site advising IE 6 users that they are using a very out of date browser. < It informs them how to upgrade.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "javascript, browser, internet explorer 6" }
How do I make sudo!! add a space after sudo? When I type sudo!! it never puts a space between sudo and anything. How do I make sudo!! add a space? Example: nano text.txt sudo!! sudonano text.txt Maybe I am using it wrong but it never works unless I add a space after sudo.
You need to use sudo !! instead of `sudo!!`. This is intended behaviour. The `!!` history expansion, as stated in the documentation: > designates the preceding command. When you type this, the preceding command is repeated in toto. It is simply as if `!!` were replaced with a find/replace with the contents of the last line. Naturally, since your line didn't start with a space, a space isn't included in the expansion.
stackexchange-raspberrypi
{ "answer_score": 7, "question_score": 1, "tags": "raspbian, bash, sudo" }
Testnet fallback nodes Is there a list of nodes on Testnet that work like the fallback nodes on the Mainnet? I am trying to test my Bitcoin communication code and I'd like to start with just one IP I can rely to be on and responsive.
Blockexplorer.com runs a testnet node all the time.
stackexchange-bitcoin
{ "answer_score": 4, "question_score": 4, "tags": "fallback nodes, testnet" }
How do I execute a line conditionally in Visual Studio 2010? I'd like the line to execute when running within Visual Studio but not when the exe is running stand alone. Thanks.
Do you mean when a debugger is attached? If so, you could do something like this: #if DEBUG if (Debugger.IsAttached) { //Your code here } #endif This will only run when the debugger is attached, such as running with F5. Double clicking it or using Ctrl+F5 won't cause the `if` statement to be hit. It's also wrapped in a conditional so then when you compile to release the code is not even there.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 2, "tags": "c#, visual studio 2010" }
Sort nvarchar in SQL Server 2008 I have a table with this data in SQL Server : Id ===== 1 12e 5 and I want to order this data like this: id ==== 1 5 12e My `id` column is of type `nvarchar(50)` and I can't convert it to `int`. Is this possible that I sort the data in this way?
I'd actually use something along the lines of this function, though be warned that it's not going to be super-speedy. I've modified that function to return only the numbers: CREATE FUNCTION dbo.UDF_ParseNumericChars ( @string VARCHAR(8000) ) RETURNS VARCHAR(8000) WITH SCHEMABINDING AS BEGIN DECLARE @IncorrectCharLoc SMALLINT SET @IncorrectCharLoc = PATINDEX('%[^0-9]%', @string) WHILE @IncorrectCharLoc > 0 BEGIN SET @string = STUFF(@string, @IncorrectCharLoc, 1, '') SET @IncorrectCharLoc = PATINDEX('%[^0-9]%', @string) END SET @string = @string RETURN @string END GO Once you create that function, then you can do your sort like this: SELECT YourMixedColumn FROM YourTable ORDER BY CONVERT(INT, dbo.UDF_ParseNumericChars(YourMixedColumn))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, sql server, tsql" }
Countability of Gaussian Integers I am attempting to show that Gaussian Integers are countable. Is it valid to map $a + bi$ to an ordered pair $(a, b)$ and then map this to the set of rationals $a/b$ ? I am unsure if this works since $a/b$ is not defined at $b = 0$ and am unsure of a different way to go about this. Any hints welcome, thanks!
We have $\mathbb{Z}[i]=\\{a+bi\mid a,b\in \mathbb{Z}\\}$ and thus a bijection to pairs $(a,b)\in \mathbb{Z}\times \mathbb{Z}$. Since the product of two countable sets is countable, this is countable.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "elementary set theory, gaussian integers" }
Content type of S3 key is being set as 'application/octet-stream' even after explicitly setting it to "text/plain", in python boto I have to save a certain textfile to S3 using boto. I have fetched the textfile using "requests" library. I have written the following code to save the file to S3: filename = "some/textfile/fi_le.txt" k = bucket.new_key(filename) k.set_contents_from_string(r.raw.read()) k.content_type = 'text/plain' print k.content_type k = bucket.get_key(filename) print k.content_type The output is: text/plain application/octet-stream What should I do to set the file's content_type to 'text/plain'? Note: I am dealing with a lot of such files, so setting it manually in AWS console is not an option.
Try setting the content type before you call `set_contents_from_string`: k = bucket.new_key(filename) k.content_type = 'text/plain' k.set_contents_from_string(r.raw.read()) The reason you have to set it before, not after, is because the `set_contents_from_string` method is what actually results in the file being written to S3 - and once it's written, changes to the local object attributes won't be reflected. So instead, you set the local attributes first, before the object is written, so they'll be written properly when you set the contents.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, amazon web services, amazon s3, boto" }
jQuery Dynamically Sized margins 2 I'm working on dynamically resizing vertical margins with jQuery and I'm wonder if if how I can resolve a problem that causes the margins to resize only once when the page loads. /* PAGE SIZE */ $(document).ready(function(){ var WIDTH = $(window).width(); if(WIDTH > 1420){ $("ul#menu-content-1.menu").css("margin-top","59px"); $("div.menu-content-container").css("margin-top","59px") } else if(WIDTH < 1420) { $("ul#menu-content-1.menu").css("margin-top","-59px"); $("div.menu-content-container").css("margin-top","-59px"); } }); This is my existing code. How can I fix this recurring problem so that each time the page loads and the window is resized, the margins will adjust?
`.ready()`, `.resize()` are short-cuts for using the `.bind()` function (or `.on()` in jQuery 1.7+). `.resize(function () {})` maps to `.bind('resize', function () {})`. Here is how your code would look using `.on()` wherever possible: $(document).on('ready', function() { $(window).on('resize', function() { // Stuff in here happens on ready and resize. var WIDTH = $(window).width(); if(WIDTH > 1420){ $("ul#menu-content-1.menu").css("margin-top","59px"); $("div.menu-content-container").css("margin-top","59px") } else if(WIDTH < 1420) { $("ul#menu-content-1.menu").css("margin-top","-59px"); $("div.menu-content-container").css("margin-top","-59px"); } }).trigger('resize'); // Trigger resize handlers. });//ready
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "javascript, jquery, html, css, margin" }
SSIS Flat File Source Not Splitting Column by Comma I have a flat file connector in SSIS but for some reason it is not splitting the commas into columns. I have the column delimiter set to comma and you can see in "Column 0" there is commas "," however it just doesn't want to split them. Has anyone come across this before? Any help would be amazing! The file has a LF line terminators (UNIX way). Is this an issue for SSIS? There is an option I have selected. ![enter image description here](
I've found the solution, needed to remove a few rows to get the headers to split, using the "Header row to skip" entry. Thanks for all your help! ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "sql server, ssis, flat file, dataflowtask" }
git ls-tree output of working directory? I am looking for a way to have output in the same manner as `ls-tree`, but of my working directory. Whenever I run `git ls-tree .` it says `fatal: Not a valid object name .`
`git ls-tree` only works with git refs, e.g. `ls-tree HEAD` or `ls-tree 1.9.1` Try `git ls-files`. You probably want the `-s` and/or `-m` flags. * * * As you point out, `git ls-files -s` will list the files in the index (i.e. files that have been staged). In theory, you could mess with the index, run `git ls-files -s`, then try restore it, e.g. git commit git add . git ls-files -s git reset . git reset --soft HEAD^ Seems right, and worked in a simple test, but could eat all your files.
stackexchange-stackoverflow
{ "answer_score": 27, "question_score": 18, "tags": "git, git ls tree" }