INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Should there be paragraph break between a leading text and itemized list?
What is the right convention for rendering itemized-lists?
Is it like this without any paragraph break between the previous line and the list?
\documentclass{article}
\begin{document}
There are 10 types of people in this world:
\begin{itemize}
\item Those who understand binary.
\item Those who don't.
\end{itemize}
\end{document}
Or is it like this with a paragraph break between them?
\documentclass{article}
\begin{document}
There are 10 types of people in this world:
\begin{itemize}
\item Those who understand binary.
\item Those who don't.
\end{itemize}
\end{document} | LaTeX explicitly tests for this case. If there is a paragraph break before the list the vertical space is adjusted (`\partopsep` rather than `\topsep`) and the text following the list starts a new paragraph.
So both are correct, and like any paragraph break it is up to the author to encode the desired meaning, is the list part of the current paragraph (or sentence) or is it standing as a displayed paragraph separate from the preceding paragraph. | stackexchange-tex | {
"answer_score": 8,
"question_score": 5,
"tags": "lists, paragraphs, best practices"
} |
Python list matching from CSV
I'm a beginner using Python and I'm stuck.
I've imported some data from two separate CSV files and added them to relevant variables:
List_1 = [['01', 'Banana', '2', '10'],['02', 'Apple', '1', '10'],
['03', 'Orange', '3', '10']]
_Explanation of values: [Item number, Item, Item cost, Item Stock]_
List_2 = [['02','3'],['01','1'],['03','5']]
_Explanation of values: [Item number, Amount paid]_
I need to match the 1st value in List_2 i.e 02 with the item number in `List_1` i.e the 1st item. Then retrieve he attributed cost, in this example 2.
I hope this makes sense. I've tried a few times with different syntax etc and failed miserably. | You can build two dictionaries:
items = {entry[0]: {'item': entry[1], 'cost': float(entry[2]), 'stock': int(entry[3])}
for entry in List_1}
paid = {id_: int(count) for id_, count in List_2}
and can now match both datasets:
for id_, count in paid.items():
item = items[id_]
print(item['item'], item['cost'] * count)
Output:
Banana 2.0
Apple 3.0
Orange 15.0 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "python, list, dictionary"
} |
How to create a custom collectionview layout like the image below
I am trying to create something like this in the image . | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "repository, cvs, remote access"
} |
SharePoint 2019 Installation Error - NoComponentID
I am installing a SharePoint 2019 on a single server for development purposes. I am using AutoSPInstaller to do the install. After running that application and the installation completes, I can successfully view central admin and mysites. Howerver going to the default site (ie contoso.com), I get a NoComponentID error. Looking at the ULS log file doesn't provide any details as to what is causing this issue. Googling online, I haven't seen any solutions to this error when it happens after a fresh install. Initially I thought it was because of the site template selected (ie Modern Team Site or Communication Site) but no matter what site template I use, I get the same error. Can someone please help me with this? I have spent days trying to figure this out.
Thanks. | To fix this error, do the following:
1. Go to Central Admin -> Application Management -> Site Collections -> Delete a site collection
2. In the dialog that appears, make sure you select the correct web application and then select the root URL
3. Click OK to confirm the selection
4. This will bring you to the confirmation screen. Click Delete if you are sure you have selected the right site.
5. Next go to Create site collections to create a new site. Make sure the path select displays the forward slash symbol /
Now the new site will operate correctly. | stackexchange-sharepoint | {
"answer_score": 0,
"question_score": 0,
"tags": "sharepoint server, installation, 2019, autospinstaller"
} |
Trigger to create a campaign when an account is created
I am trying to write a trigger that will automatically create a campaign record when a new account is created. Below is my code:
trigger AddCampaign on Account(after insert) {
List<Campaign> myCamp = new List<Campaign>();
for(Account a : Trigger.New) {
myCamp.add(new Campaign(Name=a.Name + ' Campaign',
Type='Webinar',
StartDate=System.today().addMonths(1)
));
}
insert myCamp;
}
For some unknown reason the code is not working and it is not showing any error as well. Please help. | Try the below code, it should work. And also to share a note, Campaigns and Accounts are tied to each other when contacts are added as CampaignMembers. So if just the campaign is created, there will be no change on the related tab.
trigger AutoInsertCampaign on Account (before insert) {
List<Campaign> myCamp = new List<Campaign>();
Date nextMonth = System.today().addMonths(1);
for(Account a : Trigger.New) {
Campaign newCampaign = new Campaign();
newCampaign.put('Name', a.Name + ' Campaign');
newCampaign.put('Type', 'Webinar');
newCampaign.put('StartDate', nextMonth);
newCampaign.put('StartDate', nextMonth);
myCamp.add(newCampaign);
}
Database.insert(myCamp, false);
} | stackexchange-salesforce | {
"answer_score": 1,
"question_score": -3,
"tags": "apex, trigger, automation, after trigger, campaign"
} |
How to rewrite this code from python loops to numpy vectors (for perfomance)?
I have this code:
for j in xrange (j_start, self.max_j):
for i in xrange (0, self.max_i):
new_i = round (i + ((j - j_start) * discriminant))
if new_i >= self.max_i:
continue
self.grid[new_i, j] = standard[i]
and I want to speed it up by throwing away slow native python loops. There is possibility to use numpy vector operations instead, they are really fast. How to do that?
j_start, self.max_j, self.max_i, discriminant
int, int, int, float (constants).
self.grid
two-dimensional numpy array (self.max_i x self.max_j).
standard
one-dimensional numpy array (self.max_i). | Here is a complete solution, perhaps that will help.
jrange = np.arange(self.max_j - j_start)
joffset = np.round(jrange * discriminant).astype(int)
i = np.arange(self.max_i)
for j in jrange:
new_i = i + joffset[j]
in_range = new_i < self.max_i
self.grid[new_i[in_range], j+j_start] = standard[i[in_range]]
It may be possible to vectorize both loops but that will, I think, be tricky.
I haven't tested this but I believe it computes the same result as your code. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "python, performance, algorithm, numpy, vectorization"
} |
Nikon D90 mirror stuck
Suddenly, while taking photos my Nikon D90 turned black and I couldn't see anything through the viewfinder, the result of a locked up mirror as I found out when taking off the lens. The camera display unit does not work either.
What can I do to fix this problem? | It may be the result of a battery going dead without prior warning. This happened to me using a third party battery pack.
In order to fix this replace the battery pack with a charged one (preferably a Nikon battery). Turning the camera on will likely result in the "Err" message being displayed. Simply press down the shutter and the mirror should move into its correct position again. | stackexchange-photo | {
"answer_score": 6,
"question_score": 2,
"tags": "nikon d90, error, mirror"
} |
Add DataCollection properties while Initialize Objects by Using an Object Initializer
Add properties while Initialize Objects by Using an Object Initializer . But how can we add DataCollection property?
Example:
class Student{
public string FirstName{ get; set} ;
public string LastName{ get; set};
public DataCollection<string> Subjects{ get; set} ;
}
Student myStudent = new Student
{
FirstName = "John",
LastName = "Something"
//Subjects.AddRange()
};
So if we want to add property for "Subjects" how can we add in the above condition?
Generally we can do like below.
Student clsStudent = new Student();
clsStudent.FirstName = "Foo";
clsStudent.LastName = "other";
clsStudent.Values.AddRange(new string[] { "c#" }); | Student myStudent = new Student
{
FirstName = "John",
LastName = "Something"
Subjects = {
"Subject1",
"Subject2",
"Subject3",
}
}; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, object, constructor, ctor initializer"
} |
insert multiple authors only if it exists in MySQL
I have a problem . I am doing a PHP -My SQL project . I got to store author/s of a conference paper in a database . But sometimes its just 1 and sometimes it can be 2 or 3 or 10 . So how do i store this without creating rows like author1 ,author 2, ... author n . As for each conference papaer the number of authors will be different .How do i design the table , please help
**conference paper table**
**authors table** | As this is a m:n relationship you'd need an intermediate table that links authors to papers, e.g.:
CREATE TABLE paper_author (
paper_id INT,
author_id INT,
PRIMARY KEY(paper_id, author_id)
);
Then you can check for all authors of a paper with:
SELECT paper.name, author_name
FROM paper
JOIN paper_author ON paper.id = paper_author.author_id
JOIN author ON paper_authors.author_id = author.id
WHERE paper.name = ...;
Same for all papers by a specific author with
WHERE author.name = ...;
Or if you you want a list of authors for each paper on a single row you can use `GROUP BY` and the `GROUP_CONCAT()` aggregate function:
SELECT paper.name, GROUP_CONCAT(author_name)
FROM paper
JOIN paper_author ON paper.id = paper_author.author_id
JOIN author ON paper_authors.author_id = author.id
GROUP BY paper.name; | stackexchange-dba | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, php"
} |
How to grep "&amount"?
I need to look for `&amount` in a file but it throws error -
[1] 25950
amount: Command not found.
Usage: grep [OPTION]... PATTERN [FILE]...
What is the right way to search for it? | Put it in quotes like
grep '&amount' file
so the `&` isn't interpreted by the shell to put the `grep` in the background and then try to run the command `amount`
or alternately, you could escape it so it won't have the special meaning to the shell:
grep \&amount file | stackexchange-unix | {
"answer_score": 3,
"question_score": 0,
"tags": "grep"
} |
Checking if a number's reverse is equal to the number
I have to make a function that tests if a certain value when reversed is equal to it's original form. I get a positive integer `a` and this is the code I came up with
var i = 0;
var numlist1 = [];
numlist1 = a.toString(10).replace(/\D/g, '0').split('').map(Number);
var numlist2 = [];
numlist2 = numlist1.reverse();
var final=1;
while (i<numlist1.length) {
if (numlist1[i] != numlist2[i]) {
final=0;
break;
}
i=i+1;
}
var answer="yes";
if (final == 0) {
answer="no";
}
however when I try using it the answer gets returned as yes, even when I input a number like 211 which is not equal to its reverse. | You don't need to change the number to string if it's just a number.
There a simple logic for checking the number if its palindrome or not
function checkreverse(number) {
var rem, temp, final = 0;
temp = number;
while (number > 0) {
rem = number % 10;
number = parseInt(number / 10);
final = final * 10 + rem;
}
return final === temp;
}
console.log(checkreverse(211));
console.log(checkreverse(212));
console.log(checkreverse(21134));
console.log(checkreverse(211343112)); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript"
} |
List of lists by unique coordinates
I have a data frame like the one below. I want to collapse it, though, so that each unique coordinate is a list of its SubIDs.
subID latlon
1 S20298920 29.2178694, -94.9342990
2 S35629295 26.7063982, -80.7168961
3 S35844314 26.7063982, -80.7168961
4 S35833936 26.6836236, -80.3512144
7 S30634757 42.4585456, -76.5146989
8 S35834082 26.4330582, -80.9416786
9 S35857972 26.4330582, -80.9416786
10 S35833885 26.7063982, -80.7168961
So, here, I want (26.7063982, -80.7168961) to be a list containing (S35629295, S35844314), and (29.2178694, -94.9342990) to be a list containing just (S20298920). I think a list of lists is what makes most sense. | Use `aggregate`:
out <- aggregate(data=df,subID~latlon,FUN = function(t) list(sort(paste(t))))
Since your data set is large and cumbersome, the sample code below uses watered down data which is easier to read.
out <- aggregate(data=df,name~ID,FUN = function(t) list(sort(paste(t))))
out
ID name
1 1 apple, orange
2 2 orange
3 3 apple, orange
**Data:**
df <- data.frame(ID=c(1,1,2,3,3),
name=c('apple', 'orange', 'orange', 'orange', 'apple'))
## Demo
| stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "r, list"
} |
HTMLPanel.wrap() assert fails
I'm using `UiBinder` to create a custom widget. The UI template is something like:
<g:HTMLPanel styleName="setting">
<div ui:field="dynamicDiv">
</div>
{other stuff here}
</g:HTMLPanel>
Then, to add widget in the `dynamicDiv` I wrap it with HTMLPanel:
HTMLPanel.wrap(dynamicDiv);
and just use it as a normal widget.
When I run the application normally everything is fine, but if I run in debug mode, the following
assert Document.get().getBody().isOrHasChild(element);
in `HTMLPanel.wrap()` it fails, hence I am unable to debug the code.
Apart from the annoyance of debugging, I guess there was a good reason to put that assert there, so I would like to understand what is the correct way to wrap that div. | You don't need to _wrap_ the div, just use the appropriate method from the containing `HTMLPanel`; e.g.:
theHtmlPanel.add(theWidget, dynamicDiv); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "gwt, uibinder"
} |
Sending/uploading file to another computer/server
I am working on a Silverlight application to familiarize myself with it.
The application I intend to build has two components: A silverlight web app that I will host (on my home desktop, for now), and a C# app that will run client-side.
The Silverlight app needs to read a file that resides on the client side.
The C# app (which will probably run as a service) needs to send a .txt file (no more than 10kb) to my server every 5-10min or so (will be user configurable).
What is the best way to send the file? (byte stream, or something else?)
How do I configure my server to receive this file? I assume it will involve some IIS configuration, and I could run a C# app that receives the file and saves it in a directory from where the Silverlight app can read it. | You can send a POST request to the server with byte stream and retrieve it on the server.Then process it and show it on your Silverlight app as required.
Also since your silverlight app can directly take file from user and process it in the browser itself if user interaction is required.
Remember Silverlight is a Client Side Technology not Server Side.If you need normal webservice type design where you take file and update some information in database, etc then you need a simple ASP.Net web app not Silverlight. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, silverlight"
} |
Large braces for specifying values of variables by condition
How do I produce a conditional expression with large brackets?
**For example:**
X = 0 if a=1, 1 otherwise, with a large left bracket and specifying each condition in a line? | The `cases` environment from amsmath does the trick.
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation}
X=
\begin{cases}
0, & \text{if}\ a=1 \\
1, & \text{otherwise}
\end{cases}
\end{equation}
\end{document}

val rowRDD = Row.fromSeq(textLines.map(_.split(",")))
However, I'm getting the error `type mismatch; found : org.apache.spark.rdd.RDD[Array[String]] required: Seq[Any]`
How can i fix the map? | If what you're trying to do is to load a **CSV** into a **DataFrame** , there's a simpler way:
val dataframe: DataFrame = spark.read.csv("file.text")
Alternatively, if you're truly interested in converting an `RDD[String]` into an `RDD[Row]` \- here's how you'd do that:
val rows: RDD[Row] = textLines.map(_.split(",")).map {
a: Array[_] => Row(a: _*)
}
But note that this might create "uneven" rows (if your data isn't a proper CSV, different rows might have different number of columns, which would make this RDD pretty unusable). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "scala, apache spark"
} |
Retrieve windows placement from saved workspace in Windows Registry
I have a MFC application that automatically saves and restores its workspace (window position, open panes, sizes, etc) to Windows Registry (e.g. `HKCU\Software\foo\bar\Workspace`). It's working correctly.
Now I'm interested in showing a splash screen _before_ loading any other window (user requirements). This splash screen must be shown in the same screen where the application's main window will be shown.
I've noticed that in the Registry there is a value `HKCU\Software\foo\bar\Workspace\WindowPlacement\MainWindowRect` that I guess contains the information about the top-left point and size of the window. With that information I'm able to get the correct screen number (see this other post if interested in how).
How can I get and interpret that `MainWindowRect` value? | As far as I've been able to see, the `MainWindowRect` happens to be the direct memory dump of a `RECT` structure. A simple cast is enough to get the window's rect.
Here the full code snippet for getting the value as well as the associated monitor:
// Assumes SetRegistryKey has been already called
if (const auto hKey = AfxGetApp()->GetSectionKey("Workspace\\WindowPlacement")) {
DWORD dwReturn[32];
DWORD dwBufSize = sizeof(dwReturn);
if (RegQueryValueEx(hKey, "MainWindowRect", 0, 0, (LPBYTE)dwReturn, &dwBufSize) == ERROR_SUCCESS) {
const auto rectWindow = *(RECT*)dwReturn;
// Get monitor index from window's rect
const auto hMonitor = MonitorFromRect(&rectWindow, MONITOR_DEFAULTTONEAREST);
const auto iMonitorIndex = GetMonitorIndex(hMonitor); // see linked post for GetMonitorIndex implementation
}
RegCloseKey(hKey);
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, windows, mfc, registry"
} |
how to prevent a event in tinymce
i have a problem working with the tinyMCE (thanks for this superb documentation!! _irony_ )
all i'm searching for is a similar method to jQuerys event.preventDefault() but i want to stop the events fired by the editor.
i tried to use the `execcommand_callback: function(editorID,elem,event)` attribute at the initialization but all i get is a string (editorID), a html node (elem) and another string which contains the name of the current executed event, no event object. I could manipulate the node where the command will be executed but this wont help me preventing the event.
To disable all Buttons or the whole editor is not an option, any ideas? is this even possible?
i googled the whole weekend and everyone wants to disable the buttons :-/ | Those callbacks are not "real" browser events.
Try `return true` to stop calling next callback in chain. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 4,
"tags": "javascript, jquery, events, event handling, tinymce"
} |
finding mode from histogram
i have this function to print the histogram, I suppose to use this function calculate mode as well, I understand that to find mode you need to compare number of occurrences of each score, but I can't figured out how to implement this into the code. Is there anyway to implement this function to find mode?
this is my function
int calMode(RECORD list[], int count){
int tempMode = 0;
int i, k;
int current = 0;
while (current < count)
{
printf("%d:", list[current].score);
for(k=0; (i=current + k) < count ; ++k)
{
if(list[current].score == list[i].score)
printf("*");
else
break;
}
if(k > tempMode)
tempMode = k;
printf("\n");
current = current + k;
}
printf("%d\n", tempMode);
return tempMode;
} | int calMode(RECORD list[], int count){
int tempMode;
int i, k;
int current = 0;
int max = -1;
int update = 0;
while (current < count){
printf("%d:", list[current].score);
for(k=0; (i=current + k) < count ; ++k){
if(list[current].score == list[i].score)
printf("*");
else
break;
}
printf("\n");
if(k>max){
max = k;
tempMode = list[current].score;
update = 1;
} else if(k == max){
update = 0;
}
current = current + k;
}
if(update == 0)
tempMode = -1;//indeterminable
return tempMode;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c, structure, histogram, mode"
} |
How to remove plastic pad for cooler around a CPU
!enter image description here
I'm trying to remove the CPU.
What is the black plastic round thing around CPU and how to remove it? | That ring is the mount for what is probably an aftermarket cooling fan.
If there are not screws visible at the top, try checking the other side of the mainboard (it will have to be removed from the case likely). | stackexchange-superuser | {
"answer_score": 2,
"question_score": 2,
"tags": "cpu, cpu cooler"
} |
How to redefine cov to calculate population covariance matrix
The standard `cov` function calculates the sample covariance matrix, I want to have the population covariance matrix.
I tried the following:
cov.pop <- function(x,y=NULL) {
cov(x,y)*(length(x)-1)/length(x)
}
> sapply(list(Apple,HP,Microsoft),cov.pop,y=Apple) #correct
[1] 0.7861672 0.1363396 0.2223303
> sapply(list(Apple,HP,Microsoft),cov.pop,y=HP) #correct
[1] 0.13633964 0.09560376 0.05226032
> sapply(list(Apple,HP,Microsoft),cov.pop,y=Microsoft) #correct
[1] 0.22233028 0.05226032 0.13519964
> cov.pop(cbind(Apple,HP,Microsoft)) #not correct
Apple HP Microsoft
Apple 0.8444018 0.14643887 0.23879919
HP 0.1464389 0.10268552 0.05613145
Microsoft 0.2387992 0.05613145 0.14521443
**My question**
Is there a simple way to modify the `cov.pop` function to get the correct population covariance matrix? | I guess the results are different because the `length` in the `matrix` (i.e. `cbind(Apple, HP, Microsoft)` and the `length` in each `list` element is not the same
cov.pop <- function(x,y=NULL) {
cov(x,y)*(NROW(x)-1)/NROW(x)
}
Using an example dataset
set.seed(24)
Apple <- rnorm(140)
HP <- rnorm(140)
Microsoft <- rnorm(140)
cov.pop(cbind(Apple,HP,Microsoft))
# Apple HP Microsoft
#Apple 0.946489639 0.006511604 0.02518080
#HP 0.006511604 1.015532869 0.04940075
#Microsoft 0.025180805 0.049400745 1.08388185
sapply(list(Apple,HP,Microsoft),cov.pop,y=Apple)
#[1] 0.946489639 0.006511604 0.025180805
sapply(list(Apple,HP,Microsoft),cov.pop,y=HP)
#[1] 0.006511604 1.015532869 0.049400745
sapply(list(Apple,HP,Microsoft),cov.pop,y=Microsoft)
#[1] 0.02518080 0.04940075 1.08388185 | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 8,
"tags": "r, covariance"
} |
Не работает else(((
Есть скрипт, который выборочно выводит свойство объекта через **prompt**. По задумке, если пользователь ведет другое значение, которого нет в объекте, то должно выводиться сообщение **"Введите age или name"** , но вместо него выходит значение **undefined**
В каком месте я ошибся?
let border = prompt('Что хотите узнать?' , '');
let user ={
name: 'Domik',
age: 99,
};
if (border == border){
alert(user[border]);
}
else{
alert('Введите age или name');
} | Ошибка здесь:
if (border == border)
Эта конструкция бессмысленная. Вы проверяете значение переменной с самой собой.
* * *
Как вариант: брать имена ключей и проверять наличие имени этого ключа в массиве. Если есть - то выводить значение по ключу, в ином случае - ошибку.
let border = prompt('Что хотите узнать?', '');
let user = {
name: 'Domik',
age: 99,
};
let objectPropertyKeys = Object.keys(user);
let alertText = objectPropertyKeys.includes(border) ? user[border] : `Введите одно из значений: ${objectPropertyKeys.join(', ')}`;
alert(alertText); | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript"
} |
Find the point in this line such that the distance from $A$ is $\sqrt{3}$
My line:
$$r: (0,2,-2) + \lambda (1,-1,2)$$
The point:
$$A = (0,2,1)$$
I know that the line has equations:
$$x = \lambda \\\ y = 2-\lambda\\\z = -2+2\lambda$$
But when I use the distance formula from the line to the point I get:
$$\sqrt{l^2 + (2-l -2)^2 (-2+2l-1)^2} = \sqrt{3}$$
Where $l$ is not an interger, as expected in the answer. What's wrong? | Well, you need to take an arbitrary point on the line, which is $$(x,y,z) = (l, 2-l, -2+2l)$$ and find it's distance $d$ from $A = (0,2,1)$, which is given by $$ d^2 = (l-0)^2 + (2-l-2)^2 + (-2+2l+1)^2. $$ Now note that you want $d^2=3$ and the RHS simplifies to yield $$ 3 = 2l^2 + (2l-1)^2 $$ and now can you solve it? | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "linear algebra, geometry"
} |
Intellij - disable vertical line/right margin
 was renamed to **Hard wrap at** option. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 4,
"tags": "intellij idea, margin"
} |
When I change array to vector, the program is abnormal
When I use an `array`, the following code works well. I tried to replace `array` with `std::vector`, but found that procedures often appear abnormalities, need to run more times. Anything I missed? I am using g++ 10.3.
#include <iostream>
#include <vector>
int main() {
int n = 3;
for (int k = 1; k <= 4; ++k) {
// int *A = new int[k]();
std::vector<int> A(k, 0);
int i = 0;
for (; i >= 0; A[i]++) {
for (int j = 0; j < k; ++j) {
std::cout << A[j] << " ";
}
std::cout << "\n";
for (i = k - 1; i >= 0 && A[i] == n - 1; i--)
A[i] = 0;
}
}
return 0;
} | In this for loop in its third part
for (; i >= 0; A[i]++) {
^^^^^^
the variable `i` can be equal to `-1` after the inner loop
for (i = k - 1; i >= 0 && A[i] == n - 1; i--)
where the same variable `i` is used (for example when `k` is equal to `1`).
So it is unimportant whether you are using a vector or an array. The program has undefined behavior. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, for loop, g++, nested loops, stdvector"
} |
Eject Virtual Devices permanently
I installed some programs (e.g. `Sequel Pro`), when I eject the virtual device from the Finder it seems ok but after some time it is re-added.
* Is there a way to remove them permanently?
* What is the reason of this behaviour?
**Edit:**
My machine is a MBP 15" 2016 with macOS Sierra 10.12.6.
The problem does't give any error. Simply if I remove the devices they reappear after a while. The devices now are `Sequel Pro 1.1.2` and `fastnosql-1.5.1`. I don't know if this is OS related or single programs related.
!enter image description here | There is a simple general explanation for why this happens: macOS will make shortcuts (aliases / sym links) to files that exist on a mounted disk Image or remote volume.
When you open that shortcut, the images get re-mounted assuming there are no password is needed or the credentials are cached in an unlocked keychain.
Now - you might need to do some work sleuthing why you are running files from those specific images, but the general idea is you can look around and worst case copy the DMG files to an external drive and delete them locally to see what things complain about a missing link / missing file when they run or open.
The most common case is you didn’t copy apps from the DMG to /Applications or a local folder and apps in the dock or elsewhere point at the DMG and not a local copy. | stackexchange-apple | {
"answer_score": 0,
"question_score": 2,
"tags": "finder, install, external disk, disk volume"
} |
Highest diff between max and min values in a pandas df
I have this df:
values = {'a':[1,2,3,4], 'b':[1,2,5,9], 'c':[10,1000,20,30]}
d=pd.DataFrame(values)
What's the best way to get the column with the highest spread between max and min values?
The output shoub be: `c` because `1000 - 10` > `9 - 1` > `4 - 1` | Short and simple way:
d.apply(lambda x: max(x)-min(x)).idxmax()
Output:
c | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python 3.x, pandas"
} |
Where i can find Magento advance cms admin html file
I have downloaded the advance cms extension all working fine . I need to edit the admin panel listing page. Does any one has idea where i can find the advance cms admin panel html file ? | all backend html files (actually phtml files) can be found in app/design/adminhtml/...
You could also mean admin grid? then look in your module folder in Block folder. Then search for Grid.php files. One of them should be the one you look for. I'm not sure if you would like to add/remove columns, but If you do, check this tutorial here on how to edit your grid: inchoo.net/ecommerce/magento/how-to-extend-magento-order-grid | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "php, magento, zend framework"
} |
Colored text block to be populated programmatically
I want to have the functional equivalent of a text block that supports multiple colors.
I've tried creating a UserControl and adding multiple text blocks and setting their foreground to the colors I need, however this is really slow as I will be changing and clearing the text every few seconds.
I've also tried using a RichTextBox, but it seems like it was not designed to be populated programmatically.
Suggestions? | `TextBlock` can display multiple "runs" - blocks of text with same formatting. Use `Inlines` property to access them:
using System.Windows.Documents;
using System.Windows.Media;
var inlines = textBlock.Inlines;
inlines.Add(new Run("This is red") { Foreground = Brushes.Red });
inlines.Add(new LineBreak()); // in case if you want new line
inlines.Add(new Run("And this is blue") { Foreground = Brushes.Blue }); | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "wpf, textarea"
} |
How is WinForms programming in Visual C++/C# different from Windows programming in Visual C++(MFC)
How is winforms programming in visual c++/c# different from windows programming in visual c++(MFC).
Also I want to know whether C# is strong enough to do Windows programming as in other than forms. | There are a few notable differences:
* You'll eventually be more productive as it is much easier to do (.net)
* The language helps you from making a lot of common mistakes (null pointers, overflows, leaks)
* The framework is a lot (and really I mean a lot) more clean than MFC
* In essence you can do almost anything. The least common 0.01% of things you need to do through direct win32 DLL invokes (or use a wrapper or library someone else made) | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "c#, visual c++, mfc"
} |
What is a typical scenario for and end-user reports design?
I'm wondering what would be the typical scenario for using an end-user report designer. What I'm thinking of is to have a base report with all the columns that I can have, also with a basic view of the report (formatting, order of columns, etc.) and then let the user to change that format and order, take out or add (from the available columns) data to it, etc.
Is that a common way to address what is called end-user designer for reports or I'm off track?
I know it depends on the user (if it's someone that can handle SQL or not for example), but is it common to have a scenario where the user can build everthing from the sql query to the formatting?
Thanks!
Sebastian | The first thing I would think about is to put them in a very tightly controlled sandbox, both for security and also to prevent monstrous, server-eating queries. Beyond that, I think giving them a "menu" of limited options is a good path. I would not give them direct access to SQL. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "asp.net, report, designer, end user"
} |
error in mysql insert query in MYSQL 5.6.12
I tried to use the following code to insert,
$op=$_POST["ans"];
$username=$_GET["username"];
mysql_query("insert into $username values('Q3','$op')")
or die(mysql_error());
But I got the following error:
> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near **'values('Q1','Wrong')'** at line 1
Why am I getting this error? How can I fix it? | Your query structure is not making any sense. You're inserting into `$username`? That's not the name of the table, is it?
mysql_query("INSERT INTO `tablename` values('Q3','" . mysql_real_escape_string($op) . "')") or die(mysql_error());
Always be very careful to escape any and all user data being put into your queries, and please, please stop using `mysql_query` in new code. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql"
} |
In c#, how to assign a sql query result within a variable?
SqlConnection connection = new SqlConnection(connString.ToString());
string select = "SELECT (CASE WHEN MAX(page_no) IS NULL THEN 1 ELSE MAX(page_no)+1 END) FROM dbo.BOOK";
string insert = "INSERT INTO dbo.BOOK (book_id,select) VALUES (121,4)";
SqlCommand sqlCommand = new SqlCommand(insert,connection);
insert.ExecuteNonQuery();
Here I got exception where the insert contains invalid string select. Please tell me how assign sub query within the insert? | you cannot use a select statement like this if you want to use a sub query it has to be in single statement
but in above statement you write in different different statement for selection and insert query .
so `cmd.ExecuteNonquery()` execute only `insert` text statement so SQL engine unable to find `SELECT`(and SELECT is a Reserved keyword) so it gives you a error
if you go with subquery try this
SqlConnection connection = new SqlConnection(connString.ToString());
string select = "SELECT 121, (CASE WHEN MAX(page_no) IS NULL THEN 1 ELSE MAX(page_no)+1 END) FROM dbo.BOOK";
string insert = "INSERT INTO dbo.BOOK (book_id,[select]) "+select;
SqlCommand sqlCommand = new SqlCommand(insert,connection);
sqlCommand.ExecuteNonQuery(); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c#, sql, insert, subquery"
} |
What is the meaning of Neighbor Mr. Robutusen words?
In **The Princess Diaries** (2001), what is the meaning of Mr. Robutusen words (say to himself):
> Mr. Robutusen: The elegant European woman didn't stay for tea.
>
> Mia: Thanks (to Joe who opens the car's door for her)
>
> Mr. Robutusen: **But the promise of tomorrow hung in the air.** | Essentially it means that Mr Robutusen liked/was impressed by/was attracted to Clarisse when he met her.
Although she's left today there is the possibility he might see her again **tomorrow (or at least in the future)** and that's something he looks forward to.
It may also be a quote from an **unsourced poem** but only the first couple of lines are apt.
> **The promise of tomorrow**
>
> **and the hope of dreams come true...** | stackexchange-movies | {
"answer_score": 2,
"question_score": 3,
"tags": "plot explanation, the princess diaries"
} |
Comparison between Html with and without Html helpers
I have an asp.net mvc4 application in which some `Html.Helpers` are used in place of Html code
<form></form>
==>
@Html.BeginForm(){}
I used the concept of Model Binding: the code becomes more readable and more maintainable and it's good. But I wonder :
1. if the model contains big data, did the binding of the model takes more time than a basic Html code?
2. Apart maintainability and readability, did the HTML Helpers have others benefits? | 1. This has nothing to do with html (helpers), binding is done by the framework when POST
2. 'Only' those benefits. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c#, html, asp.net, asp.net mvc 4, razor"
} |
How do I divide a list of LI's with JavaScript?
Let's say my `Rails 3` app returns a list of `li` tags. Think of an image gallery where each `li` tag contains a small image.
What I want to do is determine the width of the screen, then only show 5-7 images before I move down to the next line.
For example, say I have a wide-screen monitor I might have:
IMG1 IMG2 IMG3 IMG4 IMG5 IMG6 IMG7
IMG8 IMG9 ...
But on a smaller monitor, I would want:
IMG1 IMG2 IMG3 IMG4 IMG5
IMG6 IMG7 IMG8 IMG9 ...
Maybe JavaScript isn't the best way to do this. Would it be better to write some method in Rails?
Thanks for any suggestions. | You should probably just use CSS for this issue. Make the LIs float: left and they adapt to the space available. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "javascript, css, sorting, html lists"
} |
Direction of magnetic field
How did we know that the direction of magnetic field is from north to south and not the opposite? For example, we may use iron filings, and they will take the shape of the magnetic field, but how we knew it is from north to south and not the opposite | The direction of a magnetic field is arbitrary.
Some time ago it was noticed that magnetic materials aligned themselves in an geographic North to South line.
The part of the magnetic material which point roughly towards the geographic North pole was called the north-seeking pole of the magnet which then became the the north pole of the magnet.
Faraday used the term lines of force for what we now call lines of magnetic field and at some stage it was decided that magnetic field lines go from a north pole to a south pole or have a direction which is the same as that of the force on a isolated north pole if such an entity exited.
So I "know" that the lines of magnetic field go from north to south only because everybody uses that convention. | stackexchange-physics | {
"answer_score": 3,
"question_score": 0,
"tags": "electromagnetism, magnetic fields"
} |
errorInvalid / used nonce - Twitter oauth - Ruby on Rails
I have a server which is polling for mentions from Twitter. It works great in my test environment, but in production it started to fail after a while.
I use the twitter_oauth gem 0.4.0. I cant see whats different in production.
client = TwitterOAuth::Client.new(
:consumer_key => 'k7P---------gTQ',
:consumer_secret => 'PDWa-------------ThaOBM',
:token => '1608769-------------------------igwp0YzHslh',
:secret => '00L-------------------------CZfZTt0'
)
last_index = self.fetch_message_index
s = client.mentions
It worked for a while, but now it just works in the test-environment. | It turned out that the time was out of sync on my server. When I adjusted the clock, everything started to work again. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, twitter"
} |
Is $\sum_{n=2}^{\infty}\frac{e^{in}}{n [\ln (n)]^{\alpha}}$ absolutely convergent?
For which values of $\alpha$ the serie $$\sum_{n=2}^{\infty}\frac{e^{in}}{n [\ln (n)]^{\alpha}}$$ converges absolutely? and for which values is conditional convergent?
I know that $\sum e^{in}$ diverges (I proved it before), and now I think I need to consider cases for $\alpha$: if $\alpha=0$ or $\alpha\neq0$.
If $\alpha=0$, $\sum_{n=2}^{\infty}\frac{e^{in}}{n [\ln (n)]^{\alpha}}$ converges by Dirichlet test.
Now I just need to analyze the convergence of $\sum_{n=2}^{\infty}|\frac{e^{in}}{n [\ln (n)]^{\alpha}}|$, but I think it would be the same result because all the terms involved in the series would be positive, in conclusion the whole serie is Absolutely convergent.
But if $\alpha\neq0$, should I consider the cases where $\alpha<0$ and $\alpha>0$ or would be more simple considering the general case?
Also can someone give a hint/help to proof the rest ? | It is conditionally convergent (by the Dirichlet test) for any $\alpha$ since $\frac{1}{n \ln(n)^\alpha}$ decreases to zero as $n \to \infty$ for any $\alpha$ (I'm cheating a bit here because $\frac{1}{n\ln(n)^\alpha}$ is not a monotone decreasing sequence; however, it is decreasing for large enough $n$ and the limit is zero which is sufficient). To test absolute convergence, you need $$\sum_{n=2}^\infty \frac{1}{n \ln(n)^\alpha}$$ to converge (since $\lvert e^{in} \rvert = 1$ for all $n$). For this we use the integral test. Using $u = \ln (x)$, we see $$\int_2^\infty \frac{dx}{x \ln(x)^\alpha} = \int^{\infty}_{\ln(2)} \frac{du}{u^\alpha}.$$ This converges iff $\alpha > 1$; thus the sum also converges absolutely for $\alpha > 1$. | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "sequences and series, complex analysis, convergence divergence, divergent series"
} |
Can I use infernal machine in all difficulties?
I'm new to the game. I got all the requirements to craft an infernal machine playing the Master difficulty. I want to know if it is possible to use it while at hard difficulty. In fact, I am afraid of not being able to defeat the bosses.
So, can I use the infernal machine in all difficulties, or it depends where I get the parts?
Also, is the drop rate any better in a difficulty rather than in another? | **You got all the requirements to craft an infernal machine, I suppose you are talking about the lvl 60 one**
In fact, we are still able to craft the "old" infernal machine. As long as you are lvl 60 and under, the key wardens will drop the keys for the old, pre-patch-2.0 machine. for lvl 61 to 69, there is no way you can have any drops for hellfire rings events. When you reach lvl 70 you will have the key wardens drop the new parts for the new event released in patch 2.0.
I was needed to clarify this before answering your original question. So now..
**So, can I use the infernal machine in all difficulties, or it depends where I get the parts?**
In no way you are restricted to craft or use your machine in any difficulty. However, both Keys and Organs now only drop in Torment I or above at the following rates:
1. Torment I: 25%
2. Torment II: 28%
3. Torment III: 33%
4. Torment IV: 38%
5. Torment V: 43%
6. Torment VI: 50%
Here is my source (blue post). | stackexchange-gaming | {
"answer_score": 5,
"question_score": 5,
"tags": "diablo 3"
} |
How to compare string to enum type in Java?
I have an enum list of all the states in the US as following:
public enum State
{ AL, AK, AZ, AR, ..., WY }
and in my test file, I will read input from a text file that contain the state. Since they are string, how can I compare it to the value of enum list in order to assign value to the variable that I have set up as:
private State state;
I understand that I need to go through the enum list. However, since the values are not string type, how can you compare it? This is what I just type out blindly. I don't know if it's correct or not.
public void setState(String s)
{
for (State st : State.values())
{
if (s == State.values().toString())
{
s = State.valueOf();
break;
}
}
} | try this
public void setState(String s){
state = State.valueOf(s);
}
You might want to handle the IllegalArgumentException that may be thrown if "s" value doesn't match any "State" | stackexchange-stackoverflow | {
"answer_score": 26,
"question_score": 10,
"tags": "java, string, enums, compare"
} |
Embed private/closed facebook group
Does anyone know if it´s possible to embed a private/closed facebook group?
Are there perhaps any features in the graph api that can help me solve this? | The only way to access a private group is to use the `user_managed_groups` permission and get the feed with the `/group-id/feed` endpoint: <
Of course this only works with an admin account. You should not put the feed of a private group online anyway, that would make the whole point of a group being private useless. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "facebook, facebook graph api"
} |
Why did Rails change "drive" to "drife"?
I just ran this..
rails g scaffold shared_drive drive_name:string drive_path:string security_group_read:string security_group_modify:string
When I open the route `localhost:3000/shared_drives/new` the header reads **New Shared Drife**
When I try to create a new object on this page, I get this error
ActionController::ParameterMissing in SharedDrivesController#create
param is missing or the value is empty: shared_drife
What is going on?!?! Why did Rails change the name of my model? | It's about "Inflections". You can find more information here. It discussed earlier in issues of rails/rails and here is the solution. | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 12,
"tags": "ruby on rails, ruby"
} |
scope for zip code with space
Here in Holland our zip code has this format: "1234 AA". Zip codes are stored in the database as "1234AA" and with the use of a decorator it shows with the space in a view. I have a search field and I want the user to be able to search for "1234 AA" to find zip codes of "1234AA". How can I create a search scope in the model to do this? | In your controller, where you handle the search-related logic, can't you just strip the whitespace ? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails 3"
} |
Detect when scrolled to last li
I need to check if the user has scrolled to the end of a list item `<li>` on my page. I want to perform an _AJAX_ call, when this happens.
How to know if the user has scrolled to the last list item.
This is what I've tried till now.
if ($('li:last').is(':visible')) {
alert('Scrolled to last li');
}
But, unfortunately it is not working. | You can use a function like this:
function isElementVisible(elem)
{
var $elem = $(elem);
var $window = $(window);
var docViewTop = $window.scrollTop();
var docViewBottom = docViewTop + $window.height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
And handle the scroll event:
$(document).ready(function(){
$(window).scroll(function(){
var e = $('#yourContiner ul li:last');
if (isElementVisible(e)) {
alert('visible');
}
})
}) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "jquery, html, viewport"
} |
Ansible Determine Operating System
As part of my deploy script I wanna check which operating system I am deploying to. I used `ansible localhost -m setup` and as they say in the documentation this outputs a lot. Is there a way I can just access the ubuntu distro I am using? Ideally I want to find if the box is running Trusty or Precise | ## `ansible_distribution_release`
The fact is called `ansible_distribution_release`. If you are running Ubuntu 14.04, the fact would read " **trusty** ".
Two other example values: `ansible_distribution_release` would be " **xenial** " for Ubuntu 16.04 and " **precise** " for Ubuntu 12.04.
## `ansible_distribution_version`
You can also look at the fact `ansible_distribution_version`. For Ubuntu 14.04, you would see " **14.04** ".
Two other example values: `ansible_distribution_version` would be " **16.04** " for Ubuntu 16.04 and " **12.04** " for Ubuntu 12.04.
Here is an example task that you could put into a playbook to install the `build-essential` package only on Ubuntu 14.04:
- name: Install build-essential for Ubuntu 14.04 only
apt: name=build-essential state=present
when: ansible_distribution_version == "14.04" | stackexchange-superuser | {
"answer_score": 34,
"question_score": 21,
"tags": "ubuntu, ansible"
} |
Problems With Tables And PHP
I'm using this code to populate a Table:
<style type="text/css">
table, td
{
border-color: #600;
border-style: solid;
}
table
{
border-width: 0 0 1px 1px;
border-spacing: 0;
border-collapse: collapse;
}
td
{
margin: 0;
padding: 4px;
border-width: 1px 1px 0 0;
background-color: #FFC;
}
</style>
<table>
<tr>
<th>Files</th>
</tr>
<?php
foreach(new DirectoryIterator('/home/nathanpc/public_html') as $directoryItem) {
if($directoryItem->isFile()) {
printf('<td><tr><a href="/%1$s">%1$s</a></tr></td>', $directoryItem->getBasename());
}
} ?>
</table>
But when I try it, what I got was values outside the table, and all disorganized. Here it is on the server: < | Should be instead:
printf('<tr><td><a href="/%1$s">%1$s</a></td></tr>', $directoryItem->getBasename());
`tr` means "table row", these should encapsulate the `td`s, not the other way around. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "php, html, html table"
} |
Why don't charges leak through conductors?
Imagine a negatively charged conducting sphere placed in vacuum. Now all the negative charge must be at the surface.
Any electron present at the surface of conductor will experience a net repulsive force due to other charges.
So why doesn't that electron fly off the conductor (but instead remains on the surface)? | It will in the if you have accumulate enough charge such that the repulsive force overcomes the attraction to the protons in the nucleus. | stackexchange-physics | {
"answer_score": 0,
"question_score": 0,
"tags": "electrostatics, conductors"
} |
Which decompression algorithms are safe to use on attacker-supplied buffers?
I want to save network bandwidth by using compression, such as bzip2 or gzip.
Attackers, as well as normal users, may send compressed messages.
Are there sequences of bytes which will cause some decompression functions to become stuck in an infinite loop, or to use vast amounts of memory?
Is so, is this a fundamental property of those algorithms, or just an implementation bug? | I can only speak for zlib's inflate. There is no input that would result in an infinite loop or uncontrolled memory consumption.
Since the maximum compression of deflate is less than 1032:1, then inflate when working normally can expand up to almost 1032:1. You just need to be able to handle that possibility. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "compression, gzip, bzip2, libz"
} |
window.location.search query as JSON
Is there a better way to convert a URL's location.search as an object? Maybe just more efficient or trimmed down? I'm using jQuery, but pure JS can work too.
var query = window.location.search.substring(1), queryPairs = query.split('&'), queryJSON = {};
$.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; }); | Here's a pure JS function. Parses the search part of the current URL and returns an object. (It's a bit verbose for readability, mind.)
function searchToObject() {
var pairs = window.location.search.substring(1).split("&"),
obj = {},
pair,
i;
for ( i in pairs ) {
if ( pairs[i] === "" ) continue;
pair = pairs[i].split("=");
obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
}
return obj;
}
On a related note, you're not trying to store the single parameters in "a JSON" but in "an object". ;) | stackexchange-stackoverflow | {
"answer_score": 35,
"question_score": 22,
"tags": "jquery, json, search, window.location"
} |
Markdown not aligning tables
I run markdown-mode on emacs on OSX as well and it handles tables very well. Every time I hit enter or tab, emacs fills in all the blank spaces to line up the columns.
On my ubuntu box, it doesn't seem to recognize the table at all, but the same tables work great in org-mode
I'm running markdown-mode v2.3 from MELPA-stable and I tried removing it and adding it again with no luck.
I would appreciate any suggestions as this really makes my life easier. | I upgraded my version of markdown-mode from melpa-stable to melpa.
I also commented out this line on my emacs dot file.
;; '(package-selected-packages
;; (quote
;; (pkg-info haskell-mode epl edit-indirect dash markdown-mode+ ess flycheck markdown-mode ## org)))
I think this was some how overwriting my newer version. I don't fully understand my solution, but it works now. Hope this helps someone else. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "emacs, markdown"
} |
Need help getting a shift to return a time frame in Excel
I am trying to get a formula into excel that will return a time frame based on the Shift entered in a cell. I see a lot of questions doing the opposite, taking a time frame and returning Shift 1, Shift 2 or Shift 3, but I can't seem to work the formulas backwards to fit what I'm working towards.
For reference the Shift Column, if 1 should return 6:45 am to 2:45 pm 2 should return 2:45 pm to 10:45 pm 3 should return 10:45 pm to 6:45 am
Excel Shift Snippet
!1 | Two solutions:
* Use the `INDEX` function: store the 3 shift timeframes in range `Q3:Q5` and find the correct time from it. Here is what it gives: screenshot_solution_formula (I've added two more columns for start and end in case it helps, but no problem if we remove them). Below is the formula to put in L2 and to pull.
L2 = INDEX(Q$3:Q$5,NUMBERVALUE(LEFT($K2,1)),0)
* Use the `CHOOSE function` to choose from different timeframes specified in formula, by putting this in L2:
L2 = CHOOSE(NUMBERVALUE(LEFT($K2,1)),"6:45 am to 2:45 pm"," 2:45 pm to 10:45 pm", "10:45 pm to 6:45 am") | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "excel, excel formula, formula"
} |
Double associative array or indexed + associative array
I have an array
apple
color: red
price: 2
orange
color: orange
price: 3
banana
color: yellow
price: 2
When I get `input`, let's say `green apple` how do I check if it exists in the array and display its data (if it exists). | $fruits = array(
'apple' => array(
'color' => 'green',
'price' => 3
),
'banana' => array(
'color' => 'yelo',
'price' => 2
),
);
That?
You can look up by name using `$fruits[$fruit_name];` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, arrays"
} |
Google Cloud Storage management with Android
I'm using pliablematter simple-cloud-storage to manage uploads/downloads of files using Google Cloud Storage. But I'm not able to make it work, there's a property file with this content:
project.id=0000000000
application.name=Application Name
[email protected]
private.key.path=/var/key
I know my project.id, aplication name and account id but what should I put in private key path?? I generated and downloaded the service account private key but no matter which path location I always get `java.io.FileNotFoundException`
Moreover, where should I save private keys in Android applications?
Github project <
Please help! Thanks | I was able to solve this by copying the private key to an internal storage folder, then I put the path location in private.key.path
Don't know if this is the right way but it worked for me. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "android, google cloud storage"
} |
Xcode - Delete application before running on device
Is there a way in Xcode (4.6) to delete the application on the device before installing it ?
I need it for testing purposes and it will be easier if the application will be deleted from the device before being installed again. | The only way is to delete it manually. There's no way to have xcode delete the app from a device before running each time if that's what you were asking. Sorry, it would be a great feature, but for now, there's no way to do that. Not even on the simulator.
I think you should file a bug/feature request with apple though! That functionality would come in handy for me! | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 17,
"tags": "ios, iphone, xcode"
} |
R: using ifelse function for non-numerical values
I have some trouble using the `ifelse` option. I want to use this function in order to do a multiple linear regression. I have a large dataset and most of the data are "NA" and some others are words. The idea is to have `NA = 0` and if not `NA` then it should be equal to 1. So I've done :
dsp = ifelse (sp == "NA", 0, 1)
But when I print dsp : I can see that the non `NA` values are changed to `1` but the `NA` values are not changed to `0` and are still the same.
I've tried the `is.na()` function, then I get `FALSE` for `NA` values and `TRUE` for non-NA values. I've tried `ifelse( dsp == "False", 0, 1)` but I have the same result as `dsp = ifelse (sp == "NA", 0, 1)`
Any idea about what should I do?
Thanks for your help :) | If I understood you correctly, you want to replace all the `NA`s in the vector with `0` and if there is a value to `1`.
as @Maurits Evers said, you can do it like this:
require(tidyverse)
df %>%
mutate(x = ifelse(is.na(x), 0, 1))
In addition, you can get the same result using `case_when`:
df %>%
mutate(x = case_when(
is.na(x) ~ 0,
TRUE ~ 1))
Also, you can do it with base R:
df[which(abs(df$x) >= 0), ] <- 1
df$x[is.na(df$x), ] <- 0
As suggested by @Tino, another base R option can be using `transform()` and `ifelse()`.
transform(df, x = ifelse(is.na(x), 0, 1))
sample dataset:
df <- data.frame(x = c(NA, 1, 2, NA, 3)) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "r, if statement"
} |
思います grammar including て-Form
I have question regarding the following sentence in English:
I also think that holidays are good and people need it.
At first I came up with this:
>
But I am not sure whether this would be the better solution?
>
Is there a specific order or rule I can apply to this? | The outer (or main) clause is just fine; means "I also think that ". But the inner clause (the opinion itself) has several errors.
1. First, you must use instead of the first , because "holidays are good" is a generic statement that is supposed to be always true. only means "this one is the better one (than the other one)".
>
2. / is a tricky adjective which may mean the opposite of what you think. To avoid this, you should use ("thing") and say (literally "Holidays are good things").
>
3. is not 100% wrong in casual settings, but normally you need before this . This use of is a bit odd because usually refers to a specified singular object. You can repeat , or omit it altogether because it can be inferred. fits better in a formal sentence.
>
All in all, you can say:
> *
> *
> *
> | stackexchange-japanese | {
"answer_score": 3,
"question_score": 1,
"tags": "syntax, phrases, sentence, grammar"
} |
How to parse a config. ini file in another directory in python
I have to parse config.ini file in another directory and read few values using python. | import os
import datetime
import time
import numpy as np
import pandas as pd
yesterday_date = (datetime.datetime.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
for name in os.listdir('D:\Test'):
full_name = os.path.join('D:\Test', name)
if time.strftime('%Y-%m-%d', time.localtime(os.path.getmtime(full_name))) == yesterday_date:
folder_name_path = 'D:\Test\\' + name
filename_path = folder_name_path + '\\' + 'mentionfilename'
from openpyxl.workbook import Workbook
df = pd.read_excel(r'C:\Users\Desktop\testing_today.xlsx')
df_old = pd.read_excel(filenamepath)
df_new=df.merge(df_old[['mtm','wes','fre']],on='mtm')
writer =pd.ExcelWriter(r'C:\Users\Desktop\output.xlsx')
df_new.to_excel(writer,'Sheet1')
writer.save() | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": -3,
"tags": "python, parsing, config"
} |
.NET: How to query the NT/Users database or record?
how can we query the NT/Users database for all users on the machine? | I assume you're using C#. You can get them using WMI:
using System.Management;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SelectQuery query = new SelectQuery("Win32_UserAccount");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject envVar in searcher.Get())
{
Console.WriteLine("Username : {0}", envVar["Name"]);
}
Console.ReadLine();
}
}
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": ".net, windows"
} |
Performance check between shared cluster and laptop with Intel(R)Core™ i7
I am not really familiar with shared clusters, but I am assuming performance should not differ much in terms of completing a single task when compared with a laptop processor. I have a C++ code which I ran on my laptop with Intel(R)Core™ i7-4558U 2.80 GHz CPU and 16.0 GB RAM, with the operating system of 64 bit Windows 10. On the other hand, I have results of the same code from a publication which belong to the tests conducted on a shared cluster with Intel Xeon 2.3 GHz CPU and 4 GB memory limit with Linux operating system. The program uses CPLEX as the solver: my laptop has IBM Cplex 12.7 whereas previous runs used IBM CPLEX 12.4 (Cplex, 2012). My results seem to take **300 times more** than the reported results of the previous run. **_Does this much difference make sense? If so what could be the driver behind it?_** | This could be attributed to _performance variability_ (see, for example, section 5 of the MIPLIB 2010 paper here). In a nutshell, minor differences in problem formulation (e.g., order of constraints, input format, etc.), or running on different platforms, can have a great effect on the time to solve. With CPLEX 12.7, you can use the interactive to help you evaluate variability. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "linux, windows, performance, cluster computing, cplex"
} |
$X_i$ follows Bernoulli distribution find UMVUE of $\theta(1-\theta)$
> Let $X_1,X_2,X_3 ...X_n$ be a random sample from Bernoulli distribution with parameter $\theta$.Find UMVUE of $\theta(1-\theta)$.
I know that $T=\sum_{i=1}^{n}X_i$ is complete sufficient statistic for our paramenter $\theta$. I am trying to find out function of T which is a unique unbiased estimator of $\theta(1-\theta)$. Now $T\sim Bin(n,\theta)$
$E(T^2)-E(T)^2=V(T)$
$n\theta(1-\theta)+n^2\theta^2-n^2\theta^2=n\theta(1-\theta)$
$\implies\dfrac{1}{n}(T^2-\bar{T}^2)$ is umvue of $\theta(1-\theta)$
> If I have sample size $n=10$ with observations $1,1,1,1,1,0,0,0,0,0$ obtain the value of this estimator.
Now I am stuck at this point that is $T^2$ is $T^2=\sum_{i=1}^{n}X_i^2$ or $T^2=(\sum_{i=1}^{n}X_i)^2$. Can someone help me and tell at what point I am doing things wrongly? | An unbiased estimator of $\theta$ is $\frac{T}{n} $ where $T=\sum\limits_{k=1}^n X_k$.
From your approach that $\operatorname{Var}_{\theta}(T)=\mathrm E_{\theta}(T^2)-(\mathrm E_{\theta}(T))^2=n\theta(1-\theta)$, it follows that an unbiased estimator of $\theta^2$ is $\frac{T(T-1)}{n(n-1)}$. You do not get unbiased estimator of $\theta(1-\theta)$ directly from this step.
An unbiased estimator of $\theta(1-\theta)$ is therefore $\frac{T}{n}-\frac{T(T-1)}{n(n-1)}$, which is also the UMVUE. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "statistics, statistical inference, binomial distribution, parameter estimation"
} |
How to customize Material UI Chip component to be editable and copy paste content (comma separated)
I have the requirement for create the input field which takes the numbers array(comma ','separated ) like [123,34,23,13].
I want when user copy this 123,34,23,13 into input field it should change in this below format based on comma.
. | This is I found till now : <
There is missing part when the API return the wrong/Invalid array of input then it should convert into red flag | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "reactjs, material ui, components, chips"
} |
How do I search within someone's tweets?
I remember Jeff Atwood (@codinghorror) had posted a tweet about a new website, but I can't seem to find the link.
Is there any way I can search within someone's tweets to find that link? | Remy Sharp wrote a website application that will search your, or someone else's tweets without the limitations Twitter imposes so you can search far further back in time. It's at < | stackexchange-webapps | {
"answer_score": 29,
"question_score": 53,
"tags": "twitter, search"
} |
Prove the |F| on a disk is bounded by the maximal value on the boundary
Let $F$ be continuous on $\overline{D}(0,1)$ and holomorphic on $D(0,1)$. Suppose that $|F(z)|\leq 1$ when $|z|=1$. Prove that $|F(z)|\leq 1$ for all $z\in D(0,1)$.
Here $D(p,r)$/$\overline{D}(p,r)$ are the open/closed disk with radius $r$ centered at $p$.
I thought if I use the Cauchy integral formula $$|F(z)| = |\frac{1}{2\pi i} \oint_{D(0,1-\epsilon)} \frac{F(\zeta)}{\zeta - z} d\zeta |$$
and find a way to bound the integral on the right side with some known bounds related to the $|\int F|$ and $\int |F|$. Although I can't find any bound for that to work. | For $z=0$ the bound works. For $z \ne 0$, note that the fractional linear transformation $\phi(\zeta) = \frac{\zeta + z}{1 + \overline{z} \zeta}$ maps $D(0,1)$ onto itself and maps $0$ to $z$, so you can apply the previous case to $G(\zeta) = F(\phi(\zeta))$. | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "complex analysis"
} |
Find all nearby points in a set, for each element of the set
Given a finite set $S$ of points in $\mathbb R^p$ and a number $\rho$, my collaborators and I want to find, for each $s\in S$, the other points in $S$ that are within $\rho$ of $s$. Of course there's the obvious $O(|S|^2)$ algorithm, and we also came up with something (roughly, sort in each dimensions, then for each dimension and for each element of $S$ mark nearby points in some sparse matrices, and then combine the sparse matrices) that has better running time under certain assumptions, but not in the worst case.
I feel that this must be a standard problem, but I haven't been able to find references. I was wondering if someone here knows what I should search for or can suggest a good reference to start from?
Thanks in advance! | I think what you are looking for is the Fixed-radius near neighbors problem. | stackexchange-cstheory | {
"answer_score": 8,
"question_score": 7,
"tags": "reference request, cg.comp geom"
} |
Rails source location of method without an object
How do I find the source location of a method without an object? E.g. I want to find the source location of the Active Record's find method, or the Machinist gem's make method. These methods are usually called without any object. | require 'active_record'
m=ActiveRecord::Base.method :find
# => #<Method: Class(ActiveRecord::Querying)#find>
m.source_location
# => ["/<snip>/gems/activerecord-3.2.11/lib/active_record/querying.rb", 4] | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "ruby on rails"
} |
Making a field readonly in Django Admin, based on another field's value
How to make a field in Django Admin readonly or non-editable based on the value from another field? I have used `readonly_fields=('amount',)` but this wont fix my problem , as I need to manage it based on another field . | You can override the admin's `get_readonly_fields` method:
class MyAdmin(admin.ModelAdmin):
def get_readonly_fields(self, request, obj=None):
if obj and obj.another_field == 'cant_change_amount':
return self.readonly_fields + ('amount',)
return self.readonly_fields | stackexchange-stackoverflow | {
"answer_score": 28,
"question_score": 12,
"tags": "django, django models, django forms"
} |
Scheme - using apply
I received the following exercise as homework. I sat on it for hours without any success, so I have no choice but to use your help.
**Examples:**
(define m1 (cons "fixNumber" (lambda () 42)))
(define m3 (cons "add" (lambda (x y) (+ x y))))
(define myobj (create-obj (list m1 m2 m3)))
(myobj "fixNumber" '()) ;; => 42
(myobj "add" '(1 2)) ;; => 3
(myobj "myMethod" '()) ;; => "Error: no such method" | This should do:
(define (create-obj mlist)
(lambda (method parms)
(let ((func (assoc method mlist)))
(if func
(apply (cdr func) parms)
"Error: no such method")))) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "function, object, scheme, apply"
} |
How to prove $x^2+y^2\geq y^2$
Intuitive it's easy to see that $x^2+y^2\geq y^2$ is true, but I want to prove this.
**My attempt:**
> I know $a^2\geq 0$ for all $a\in \mathbb R$.
>
> I let $a=x-y$ so
>
> \begin{align} &(x-y)^2=x^2-2xy+y^2\geq 0 \\\ &\iff x^2+y^2\geq 2xy \end{align} But I'm stuck here, what is the next step?
_A second question_. If I instead have a strict inequality $x^2+y^2> y^2$, this is only valid if $x\neq 0$, right? | Note that $x^2\geq 0$, where equality holds if and only if $x=0$. Therefore $$ x^2+y^2 \geq 0 + y^2 = y^2 $$ and equality holds if and only if $x=0$. | stackexchange-math | {
"answer_score": 6,
"question_score": -1,
"tags": "algebra precalculus, inequality, proof writing"
} |
Translating {{ model.name }} data dynamically in django template
Can anyone suggest shortest way to translate {{ model.name }} type of data in django template? | `Templates aren't supposed to do buisiness logic` in django, in a good way you need to pass already translated data in your template.
Although if you actually in need to do it, you can use `django filters`:
Link to django documentation
Code may look like this:
`new_filter.py`
from django.template.defaulttags import register
@register.filter
def translator_filter(string_to_translate):
translated_string = #do logic with translation here
return translated_string
`any_page.html`
<p>{{ model.name|translator_filter }}</p> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "django, django models, internationalization"
} |
stop unknown instance for mysql
I have to reset a mySQL root password but when I try to run this command:
sudo stop mysql
and it outputs: stop unknown instance | It seems your shell thinks `stop` is a program. Instead you should run :
sudo service mysql stop
or
sudo /etc/init.d/mysql stop | stackexchange-unix | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql"
} |
The key step to prove log-convexity is preserved under sums
In S. Boyd textbook p.105 (button): (cvx = convex)
Let F = log f & G = log g are convex (i.e. Let f & g are log-cvx)
(This guarantees f & g are cvx, since log-cvx is included in cvx)
Now, the book says:
From the **composition rules for cvx functions: log(exp(F) + exp(G)) = log(f + g) is cvx.**
I do not understand the last step?
What I think is:
exp(F) & exp(G) are cvx .... (OK)
exp(F) + exp(G) are cvx .... (OK)
However, logarithm is a concave function in R++
Composition rules:
!enter image description here
Thanks!! | I was puzzled by the statement too. Here is my proof:
$F$ and $G$ are convex. With $e(*) = \exp(*)$, $$Z=\log[e(F) + e(G)]$$ $$Z' = \frac{[e(F)F' + e(G)G']}{[e(F) + e(G)]}$$ $$Z" = -\frac{[e(F)F' + e(G)G']^2}{[e(F) + e(G)]^2}+\frac{[e(F)(F')^2+ e(F)F''+ e(G)(G')^2+e(G)G'']}{[e(F) + e(G)]}$$ Check: $$T = [e(F)(F')^2+ e(F)F''+ e(G)(G')²+e(G)G'']\cdot [e(F) + e(G)] - [e(F)F' + e(G)G']^2$$ $$T = e(F)(F')^2(G) + e(G)(G')^2e(F) - 2e(G)e(F)F'G' + [e(F)F''+e(G)G'']\cdot [e(F)+e(G)]$$ $$= e(F)e(G)[F'-G']^2+[e(F)F''+e(G)G'']\cdot [e(F)+e(G)]$$ $$e(f)>0, \ e(G)>0, \ F''\ge 0, \ G''\ge 0.$$
So: $$T\ge0 \implies Z''\ge0 \implies Z \ \text{is convex}$$ Also: $$Z=\log(f+g)$$ $$\implies f+g \ \text{is log-convex.}$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "convex analysis"
} |
Factor $t^3-6t^2+9t-4$
> Factor $t^3-6t^2+9t-4.$
I have studied how to factor only quadratic polynomials. Can you give me a hint? | Whenever you see a polynomial of more than degree $2$ that you have to factor, first use the Rational Root Theorem. It states that, for an integer-coefficient polynomial $a_{n}x^{n} + a_{n-1}x^{n-1} +...+a_{1}x + a_{0}$, all rational rational roots are of the form $\frac{d_{0}}{d_{n}}$, where $d_{0}$ is a factor of $a_{0}$ and $d_{n}$ is a factor of $a_{n}$. (Note: factors can be positive or negative). Then, all possible rational roots of your polynomial are $-4, -2, -1, 1, 2, 4$. We find that $1$ and $4$ are roots, and thus:
$$t^{3}-6t^{2} + 9t - 4 = (t - 1)(t - 4)(t - r)$$
Where $r$ is the third root. Note that $(-1)(-4)(-r)$ must equal $-4$, so $-r = -1$ and thus $r = 1$. Then, the only roots are $\boxed{1\text{ and }4.}$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "algebra precalculus, factoring"
} |
initializing a 48bpp bitmap from a file in c#
I write a 48bppRgb to a file but when I create a bitmap from this file it is 32bppArgb(object img2 has a property PixelFormat.32bppArgb).
Minimized example:
Bitmap img1 = new Bitmap(100, 100, PixelFormat.Format48bppRgb);
img1.Save("/img1.bmp");
Bitmap img2 = new Bitmap("/img1.bmp");
Why? | More than one problem. You didn't save the image in the BMP format. The default format for Image.Save(string) is PNG. The PNG encoder built into GDI+ doesn't support 48bpp images. Saving as a BMP requires specifying the image format:
Bitmap img1 = new Bitmap(100, 100, PixelFormat.Format48bppRgb);
img1.Save("c:/temp/img1.bmp", ImageFormat.Bmp);
You'll however find that the BMP encoder doesn't support 48bpp images either, you'll get a 24bpp image when you load it back. None of the codecs supports 48bpp.
There's lots of missing functionality in GDI+. ImageFormat.Icon doesn't work for example, it actually saves a PNG. And support for any of the Indexed pixels formats is quite poor. If you need this kind of support then you'll need a professional imaging library. LeadTools or ImageMagick are the usual choices. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c#, image processing, bitmap"
} |
IsolatedStorageSettings ApplicationSettings for Windows Phone app 8 updates
Are the settings stored by a Windows Phone 8 app saved when the app gets updated through AppStore? | IsolatedStorageSettings provide a convenient way to store user specific data as key-value pairs in a local IsolatedStorageFile with an lifespan of the application. You can find more about IsolatedStorageSettings Class.
So the answer is that Windows Phone app will save any data saved after app update. If you uninstall app you lose all your data from IsolatedStorageSettings. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "c#, windows phone"
} |
What are all these Harry Potter objects?
The first three or four were especially confusing to me, I'm not sure what they are. What are all these Harry Potter objects?
. | From left to right:
1. The Philosopher's (Sorcerer's) Stone

:
bpy.context.scene.frame_current = iframe
print( bpy.context.scene.sun_pos_properties.time )
sun.keyframe_insert( data_path="location", frame=iframe )
However the sun_pos_properties.time is always printing the time (for frame #1), even though it is animated, and the inserted keys are also not changing. Can some kind brilliant person give me a hint on how to complete this script? | Simpler than I thought:
sun = bpy.data.objects["Sun"]
sun.select_set(True)
bpy.ops.nla.bake( frame_start=1, frame_end=10, bake_types={'OBJECT'} ) | stackexchange-blender | {
"answer_score": 1,
"question_score": 2,
"tags": "python, animation, keyframes"
} |
SQL Current and Future Dates
I have an Events table and have found a solution for selecting all Current events and Upcoming events (within the next 14 days).
I'm just wondering if there is a better solution than using the OR in the WHERE statement. This solution makes me feel like a crappy programmer.
SELECT
eventID
,eventTitle
,eventStartDate
,eventFinishDate
FROM Events
WHERE eventStartDate <= GETDATE() AND eventFinishDate >= GETDATE()
OR eventStartDate >= GETDATE() AND DATEDIFF(DAY,GETDATE(),eventStartDate) <= 14
ORDER BY eventStartDate
Your wisdom is greatly appreciated! Thanks much | You probably need something like:
SELECT
eventID
,eventTitle
,eventStartDate
,eventFinishDate
FROM Events
WHERE GETDATE() BETWEEN eventStartDate AND eventFinishDate
OR eventStartDate BETWEEN GETDATE() AND DATEADD(DAY, 14, GETDATE())
ORDER BY eventStartDate
By the way, always take care when using OR operators to specify exactly what you need using parenthesis. Your code example might fail because of this. If you were getting wrong results, you should try:
SELECT
eventID
,eventTitle
,eventStartDate
,eventFinishDate
FROM Events
WHERE (eventStartDate <= GETDATE() AND eventFinishDate >= GETDATE())
OR (eventStartDate >= GETDATE() AND DATEDIFF(DAY,GETDATE(),eventStartDate) <= 14)
ORDER BY eventStartDate
In my code this it not needed because it's not a complex expression, there's just one OR. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "sql, date"
} |
Create specific array from text Swift
I have a text that is **String** , with a lot of words, but I need to create from it a specific array that will consist of all words that start with **capital** "A" and should not have "\n". Words with capital "A" do not repeat.
I am struggling with deleting " \ " and how to work with capital letters. | Something like this?
let captialAs = string
.split(whereSeparator: { $0 == "\n" || $0 == " " })
.filter { $0.starts(with: "A") } | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "arrays, swift, string"
} |
Search a column in pandas dataframe
The following takes in the `user_time` as input. And returns the actual time if it existed in the `df['time']` or returns the closest time whether it is +1 or -1 ahead or behind of the seconds specified. The range in not more than +120 seconds. So if it is not in the 120 seconds, then it does not exist.
#Following Format always 'yyyy-mm-dd hh:mm:ss'
user_time = '2018-04-10 13:00:03'
if user_time not in df['time']:
closest_time =
#df.loc[df['time'].str.contains(closest_time )]
I am not sure how to find the closest time to pass it to the function and print out that row if the actual time does not exist | this should work fine:
In [38]: sd = pd.DataFrame({'date':pd.date_range('2018-01-01 00:00:00','2018-01-5 00:00:00',freq='min')})
In [39]: sd['date'] = pd.to_datetime(sd['date'])
In [41]: sd.iloc[(sd['date'] - pd.to_datetime('2018-01-03 01:12:23')).abs().argsort()][:1]
Out[41]:
date
2952 2018-01-03 01:12:00
or
In [50]: sd.iloc[(sd['date'] - pd.to_datetime('2018-01-03 01:12:23')).abs().argmin()]
Out[50]:
date 2018-01-03 01:12:00
Name: 2952, dtype: datetime64[ns] | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, pandas"
} |
How to isolate multiple Teamcity agents from getting picked up by a specific job
I would like my build job to not build on specific teamcity agents and there is no common pattern for the build agent names. Is there a way I can isolate multiple agents from getting picked up by a single job.
For example I can make sure that the build job does not pick up 1 agent using the following parameter.
teamcity.agent.name
does not match
agent-001
How can I similarly tell the teamcity job to not run on the following agents as well.
"123-agent"
"my_agent"
"test_agent"
"agent_do_not_use"
I cannot use the same parameter, teamcity.agent.name with does not match for multiple agents. Can you all teamcity experts help me out here please on what is the best way to achieve this. | You can add agent requirement with "does not match" condition which accepts regular expression and set it to: 123-agent|my_agent|test_agent|agent_do_not_use
Using an agent requirement based on presence (or absence) of a specific property coming from agent's buildAgent.properties file would probably be a better solution to using agent names in the requirement.
Alternative means to manage agent's compatibility are: use agent pools and use agent's Compatible Configurations set to a limited set. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "teamcity, agent, teamcity 9.0, agents"
} |
What does "扎し魔神" mean in this epiphet?
What does "" mean in this epiphet?
 {
HelperClass helperClass = new HelperClass();
EditText extiText = (EditText) findViewById(R.id.editText1);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
example 2
class TestActivity extends Activity() {
HelperClass helperClass;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
helperClass = new HelperClass();
editText = (EditText) findViewById(R.id.editText1);
}
} | You can do
HelperClass helperClass = new HelperClass();
But you can't do
EditText extiText = (EditText) findViewById(R.id.editText1);
like example 1.
Because the layout file in loaded when `onCreate` in called for `setContentView(R.layout.layout);` and because `R.id.editText1` is a part of this layout, you have not access to it until layout gets loaded.
Read about onCreate() | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "android, instantiation, android lifecycle"
} |
Why doesn't Gauss Divergence Theorem work for me?
I need to evaluate the volume $$V=\\{(x,y,z) \mid 0≤x≤2,\; 0≤y≤2,\; \frac x2\leq z\leq-x+3\\}$$
The sum of the double integrals gives me a value of $12$ And the triple integral gives me a value of $24$ What am I doing wrong? Can someone please point out my mistake? | $$\iiint_V1dzdydx=2\int_0^2\int_{x/2}^{3-x}1dzdx$$$$=6\int_0^21-\frac x2dx$$$$=6\bigg(x-\frac{x^2}4\bigg)\bigg|_0^2$$$$=12$$ | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "multivariable calculus"
} |
Confusion with arguments of complex numbers.
I need help to decide which pair(s) among these three complex numbers are equal:
$z_1 = ae^{i\alpha}+be^{i\beta}$,
$z_2=ae^{i(\alpha+2\pi x)}+be^{i(\beta+2\pi x)}$,
$z_3=ae^{i(\alpha+2\pi x)}+be^{i(\beta-2\pi x)}$.
Where $x$ is an integer.
I only know all three have the same modulus and same principal argument. But I don't think they are all equal. I suspect that $z_1\neq z_2$ and $z_1=z_3$. But these are just wild guesses.
Background: I want to know this because I'm studying the $k^{th}$ root of such complex numbers. | We have $e^{2\pi i n} = 1$ for $n \in \mathbb{Z}$, since arguments of $0,\pm 2\pi,\pm 4\pi, \dotsc$ all correspond to the positive real axis. (Note, in that regard, that adding or subtracting $2\pi$ from an argument leaves the complex number exactly the same, as it corresponds to a full rotation).
Therefore, since $x$ is an integer, $z_1 = z_2 = z_3$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "complex numbers"
} |
cleaning up centos install
I am relatively new to using linux but have a vps with centos installed with uTorrent installed via wine.
The VPS has 50GB of space which I have noticed all of that is being taken up by the home/admin/ directory.
Inside this directory are two other directories - Desktop and Downloads which downloads only takes up 34gb and Desktop which says nothing due to all that is on there is 1 icon to utorrent.
What could be taking up the extra 16GB of space?
EDIT:
the files were in /home/admin/.local/share/Trash/files | I'll bet it's temp files used by uTorrent. Try checking under `/home/admin/.wine/dosdevices/c:/`. The `/home/admin/.wine` directory is hidden since its name starts with a period, that's why you probably didn't check it.
You can also use `find` to check for files bigger than, say, 50 MB, a la:
find /home/admin -size +50M
Adjust the 50M accordingly (+100M for finding files bigger than 100MB, +1G for files bigger than 1 GB, etc.) | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 1,
"tags": "centos, filesystems"
} |
Use mod_proxy to change port to url apache2
I'm running NodeBB a forum which runs on port 4567 and I need it to be redirected to https and have the port removed on the end. I've looked around but nothing has worked. This is what I've tried:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
<Directory />
AllowOverride none
Require all denied
</Directory>
ProxyPass /
ProxyPassReverse /
I want the end URL to look like this: < Thanks in advance. | I just had a slight error.
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
<Directory />
AllowOverride none
Require all denied
</Directory>
ProxyPass /
ProxyPassReverse / | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "apache2, mod proxy"
} |
running java programs in Eclipse
I am having a problem running java programs in Eclipse,
When i Click on Run button to Run the Project i get error until i manually Add that project in Run Configurations , Why do i have to add Evey project in Run configurations before running it ? If i have a single .java file i couldn't be able to run this file as i cannot add this File in Run Configurations because it is just a single file not a complete project having a package.
Last time when i was using eclipse and whenever i click on Run the project i selected automatically runs without adding it inside the Run configurations but since i Deleted and Eclipse and Re-Install it i am facing these kind of troubles , could somebody help me out ? | If its a single java file then you can right click on the file and select the "run as java application" option to allow you to run the program.
The Run Configurations option is used to make sure that you save some project specific run setings and use that shortcut each time to run the project.
For single programs i think the first option is better. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, eclipse, compilation"
} |
C++ Outputting text on a window
Simple question, is drawing text using functions like TextOut or DrawText better then creating a static control, performance wise?
And which has better performance TextOut or DrawText? | Second question first: `DrawText` calls `TextOut`, so if you don't need the formatting capabilities of `DrawText`, you can go straight to `TextOut`.
If raw performance is all you care about, then drawing directly will be faster. However, raw performance should not be your sole concern. It is also more work and does not support accessibility (which means you have to write additional code to support `IAccessible`). | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "c++, windows, text, gdi"
} |
basic HTTP authentication preventing user adding bookmark
I have a resource for `coffeeshops` where I allow the user to both `favorite` and `bookmark` individual coffee shops.
I also have `http_basic_authenticate_with`on the coffeeshop controller to prevent anyone but me from writing to my db.
It seems my current setup then doesn't allow users to actually `favorite` or `bookmark` unless they sign in.
How can I get around this? I am also using Devise for user management, can I take advantage of that to restrict write access to the database allowing me to remove `http_basic_authenticate_with`?
_coffeeshop_controller.rb_
class CoffeeshopsController < ApplicationController
http_basic_authenticate_with name: "*******, password: "*******", except: [:index, :show]
I tried updating this to `[:index, :show, :put]` but that has not made a difference. | in the `except` you should list the controller actions and not http methods, so something like the following:
class CoffeeshopsController < ApplicationController
http_basic_authenticate_with name: "*******", password: "*******", except: [:index, :favorite, :bookmark]
def index
# list of coffeeshops without authentication
end
def new
# requires authentication
end
def create
# requires authentication
end
def favorite
# endpoint to mark coffeeshop as favourite without authentication
end
def bookmark
# endpoint to bookmark a coffeeshop without authentication
end
...
end | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, devise, basic authentication"
} |
Do Java compiler warnings affect compile time?
I've got a legacy project with several thousand compiler warnings (raw types, unnecessary @SuppressWarnings, unused imports etc) - the project has about 5000 Java source files. Are these warnings likely to have any significant impact on the compile time?
Please note: **I am well aware that getting rid of compiler warnings _just_ to improve performance is not a good reason for doing so. I'd love to get rid of the warnings to make it easier to add new code, reduce potential bugs etc. But in this case, all I'm asking is if the compilation process takes longer if there are large numbers of warnings.** | No; not significantly. The value of addressing compiler warnings comes from reducing project maintenance time, i.e., the programmer's time, not from the time it takes to compile. By addressing these warnings you will have a clearer picture of what's going awry instead of getting lost in a sea of warnings... | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "java, performance, compilation, compiler warnings"
} |
Fine/Coarse moduli spaces and extensions of fields.
Let $K/k$ be an arbitrary field extension and $X$, $Y$ varieties over $k$ (lets assume projective and perhaps smooth to avoid technicalities). There is a fine moduli space of morphisms between $X$ and $Y$ parametrized by a scheme $Hom(X,Y)$ over $k$. My question is whether $Hom(X,Y)_K$ is isomorphic to $Hom(X_K, Y_K)$ where ${}_K$ denotes tensoring with $Spec K$. From the universal property of $Hom(X,Y)$ we have a bijection between maps $Spec K\to Hom(X,Y)$ (i.e. $K$-rational points, as a set contained in $Hom(X,Y)_K$) and maps $Y_K\to X_K$. I seem to be a bit confused as to whether this is enough to conclude.
Finally, could we get a similar thing to work for the coarse Kontsevich moduli space $\mathcal{M}_{g,n}(X,\beta)$ even though there is no universal family? Thanks. | If $X,Y$ are $S$-schemes, then $\underline{\hom}_S(X,Y)$ denotes the sheaf on $S$-schemes defined by $T \mapsto \hom_T(X_T,Y_T)$. Now, if $S'/S$ is any base change, we have for every $S'$-scheme $T$:
$$\hom_{S'}(T,\underline{\hom}_S(X,Y)_{S'}) = \hom_S(T,\underline{\hom}_S(X,Y)) = \hom_T(X_T,Y_T)$$
$$ = \hom_T((X_{S'})_T,(Y_{S'})_T)) = \hom_{S'}(T,\underline{\hom}_{S'}(X_{S'},Y_{S'}))$$
Hence, $\underline{\hom}_S(X,Y)_{S'} = \underline{\hom}_{S'}(X_{S'},Y_{S'})$. | stackexchange-mathoverflow_net_7z | {
"answer_score": 2,
"question_score": 1,
"tags": "ag.algebraic geometry, moduli spaces"
} |
Get Date from day of year in Excel
I have a spreadsheet with the following information;
Stock Code Day of Year
5102560 170
5102600 167
5102617 163
5102154 164
I want to be able to return the date from the day of year number. Is there an excel function that will allow me to do this? | This should work
`=DATE(2004,1,your_value)` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "excel"
} |
Unable to establish JDBC connection to Oracle DBMS in Eclipse
I'm using Oracle 18c Express edition and trying to connect to the same using the below code.
DriverManager.getConnection("jdbc:oracle:thin://@localhost:1521/XE", "system", "Root123");
And upon execution, there's an exception:
java.sql.SQLException: Invalid Oracle URL specified
I am unable to figure out what's wrong with the URL. Kindly help resolve this issue. TIA. | According to Oracle's documentation the URL should be:
jdbc:oracle:<drivertype>:<user>/<password>@<database>
Where user and password can be provided as connection properties:
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@myhost:1521:orcl", "scott", "tiger");
You probably need to remove the `//` from the URL as well:
jdbc:oracle:thin:@localhost:1521:XE | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, oracle, eclipse, jdbc, connection"
} |
How to change IPB static pages? (like contact form)
I want to edit contact us page but I cannot find the HTML code anywhere.
I tried:
* Searching all files for text match of contact us page code
* Editing theme code and searching for contact template
Without luck. If anyone has idea how to change index.php?/contact please tell me.
Also not only contact other pages. | The best way I found is to either make a theme hook in on of your applications or a code hook to display your own form and template. Be sure to call the parent function though and return the correct values, if any. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "html, ipb, invision power board"
} |
map(arcpy.AddError, traceback.format_exc().split("\n"))
What does this expression mean? I see this in many python scripts.
try:
...
except Exception as e:
import traceback
map(arcpy.AddError, traceback.format_exc().split("\n"))
arcpy.AddError(str(e))
traceback.format_exc().split("\n") returns ['None',''] | This is calling on the built in map function, which takes a function as the first argument (arcpy.AddError) and telling it to call AddError for every piece of the message split by a new line character. So for example, if the traceback message was this:
Error Reading File:
File is of the wrong type
Needs to be CSV file
the raw string would be:
`"ErrorError Reading File:\n File is of the wrong type\n Needs to be CSV file"`
So this:
`map(arcpy.AddError, traceback.format_exc().split("\n"))`
is the exact same as:
arcpy.AddError('Error Reading File:')
arcpy.AddError(' File is of the wrong type')
arcpy.AddError(' Needs to be CSV file') | stackexchange-gis | {
"answer_score": 2,
"question_score": 0,
"tags": "python, arcpy"
} |
Why are all snippets loading several times on page load?
I have a simple about page being rendered with the content of only one entry and some Low Variables bits. It's rather slow (3.8806 seconds according to the Output Profiler), and the Template Debugging shows that all possible snippets are being loaded 6 times in each page load. The only number I could correlate with that is the number of templates being rendered in the page (aside from the main page, there's embedded template partials for the header and footer, scripts, etc). Am I correct in assuming that all snippet content is being loaded for every time a template is loaded? Is there any way to make it not do that? | The snippets are not actually "loading" - they are simply bits of text being stored in memory (much like global variables). They aren't actually processed until they're called. So they're not an overhead problem.
You'll see these being "loaded" each time you run the template engine - which means the primary template, and then each embed. | stackexchange-expressionengine | {
"answer_score": 2,
"question_score": 1,
"tags": "templates, performance, snippets"
} |
I have a problem using a variable when modifying a css property
I want to change a css property of a HTML element using Javascript. I can't find a solution to my problem. I would like to use the element with the id of CreateMenu, and apply the variable called value to the property specified by the type variable, but it doesn't seem to support variables.
edit: Type is the variable i want to use to get which property i want to edit.
function style(name, type, value) {
document.getElementById("CreateMenu").style.type = value;
} | I did not test the following but you can access an object property by its key name this way:
function style(name, type, value) {
document.getElementById("CreateMenu").style[type] = value;
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, html, css"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.