qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
72,523,117 | Say I have a dataframe that ***looks*** like this (wasn't sure how to actually rep. this data, given its size):
```
minutes <- seq(0,585, by = 15)
salinity <- as.numeric(sample(x = 29:55, size = 40, replace = TRUE))
site <- c(1, 2, 3, ...etc.)
year <- c(2020, 2019, ...etc.)
season <- c("Dry", "Wet")
df <- cbind.data.frame(year, season, site, minutes, salinity)
> head(df)
year season site minutes salinity
1 2020 DRY 1 0 54
2 2020 DRY 1 15 39
3 2020 DRY 1 30 44
4 2020 DRY 1 45 54
5 2020 DRY 1 60 43
6 2020 DRY 1 75 40
```
and in reality it has +800k rows of continuously measured data in 15 min. increments for the past couple of years at "n" sites.
I'm attempting to make a matrix/table like this in R (that was originally created in Excel). Color is not important, I only hope to re-create the table itself. The values in this plot are the maximum/highest number of minutes where a range of values were consistently measured (ex. For each site, season, and year, create a table that shows the longest lasting run of continuous minutes where the values stayed between 40-50).
[](https://i.stack.imgur.com/nXHga.png) | 2022/06/06 | [
"https://Stackoverflow.com/questions/72523117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16401542/"
] | Just change the volar version **0.37.2 to 0.36.0** and everyting will be fine.
Note: I spent coulple of hours and didn't find the exact solution and then simply tried this; then everything worked fine.
This link helped to get some idea regarading this issue:
<https://github.com/microsoft/TypeScript/issues/28631#issuecomment-472606019> | Fixed on `0.37.3`, so you don't have to alter your config or anything - <https://github.com/johnsoncodehk/volar/issues/1405#issuecomment-1149618450> |
8,595,332 | So my code was working before. I don't know what I did for this to happen and I can't seem to fix it. I've seen people say to reset the ModelState. ( ModelState.Clear(); ) But that didn't help. Also, it doesn't help that I'm still fairly new to MVC. Any help would be appreciated. Thanks.
Controller:
```
public ActionResult Create()
{
ActiveDirectoryModel adm = new ActiveDirectoryModel();
ViewBag.notifyto = adm.FetchContacts();
var model = Populate();
return View(model);
}
[HttpPost]
public ActionResult Create(CreateViewModel model)
{
if (ModelState.IsValid)
{
model.leaf.Date = DateTime.Now.Date;
model.leaf.Category = model.CategoryId;
model.leaf.SubCategory = model.SubCategoryId;
model.leaf.AssignedTo = model.AssignedToId;
model.leaf.CoAssignedTo = model.CoAssignedToId;
model.leaf.Status = model.StatusId;
model.leaf.Priority = model.PriorityId;
//model.lead.Parent = model.ParentID;
db.LeafItems.AddObject(model.leaf);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
public CreateViewModel Populate()
{
ActiveDirectoryModel adm = new ActiveDirectoryModel();
var model = new CreateViewModel
{
AssignedToItems = adm.FetchContacts(),
CoAssignedToItems = adm.FetchContacts(),
NotifyToItems = adm.FetchContacts(),
CategoryItems =
from c in new IntraEntities().CategoryItems.ToList()
select new SelectListItem
{
Text = c.Name,
Value = c.ID.ToString()
},
SubCategoryItems =
from sc in new IntraEntities().SubCategoryItems.ToList()
select new SelectListItem
{
Text = sc.Name,
Value = sc.ID.ToString()
},
StatusItems =
from s in new IntraEntities().StatusItems.ToList()
where s.IsPriority == false
select new SelectListItem
{
Text = s.Name,
Value = s.ID.ToString()
},
PriorityItems =
from p in new IntraEntities().StatusItems.ToList()
where p.IsPriority == true
select new SelectListItem
{
Text = p.Name,
Value = p.ID.ToString()
}
};
return model;
}
```
View:
```
<div class="createTopInner">
<div class="editor-label">
@Html.LabelFor(model => model.leaf.Category)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.CategoryId, Model.CategoryItems, "")
@Html.ValidationMessageFor(model => model.leaf.Category)
</div>
</div>
```
Model:
```
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> CategoryItems { get; set; }
``` | 2011/12/21 | [
"https://Stackoverflow.com/questions/8595332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1026288/"
] | If your ModelState is not valid on your POST action, you need to repopulate your SelectList properties:
```
if( ModelState.IsValid )
{
// save and redirect
// ...
}
// repopulate your SelectList properties:
model.CategoryItems = GetCategories();
return View(model);
```
Do not repopulate the entire model because otherwise you could potentially lose any changes that the user made. | another way i have find the solution is take hidden field. so in your case you could do as below:
```
@Html.HiddenFor(model => model.CategoryId)
```
Now with another field form also post and set CategoryId in respective model. |
2,067,436 | Right now, I'm working on a project which requires sequential text key generation. I need to seed the key generator with an integer corresponding to a certain key, which the constructor converts to a key.
My key generator overloads the increment operators so that the string is incremented directly, rather than what I had previously been doing, which is incrementing an index value, then converting the index to a key for every key that I wanted to generate.
My problem is that I have a limited character set I want to use when generating keys. I have to find the character in the key that I want to increment, find out where it is in my character set, find the next character in the set, then replace the character in the key with the next character in the set.
Here is my code:
```
// Not the full charset
std::string charset = "abcdefghijklmnopqrstuvwxyz0123456789";
std::string key;
key.push_back(charset[0]);
for(unsigned int place = 0; place < key.length(); place++)
{
if(key[place] == charset[charset.length() - 1])
{
// Overflow, reset char at place
key[place] = charset[0];
if((key.length() - 1) < (place + 1))
{
// Carry, no space, insert char
key.insert(key.begin(), charset[0]);
break;
}
else
{
// Space available, increment next char
continue;
}
}
else
{
// Increment char at place
key[place] = charset[charset.find(key[place]) + 1];
break;
}
}
```
In profiling, I found that the search operation is really slowing things down. Is there any faster way of doing this? I thought of creating a linked list out of the character set, but before I do that, I'd like some input on this. | 2010/01/14 | [
"https://Stackoverflow.com/questions/2067436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136846/"
] | Rather than doing a find, why don't you have a reverse translation array? The array index would be the character, and the value in the array would be its numeric value (or index into the other array).
```
key[place] = charset[reverse_charset[key[place]] + 1];
``` | Perhaps you would be better off working with indexes into the charset, and then converting them to actual characters when needed?
That would save you the overhead of searching for characters in the charset. And converting a charset index into a character would be a constant-time operation, unlike the inverse.
Store your key as a vector of integers 0 ~ N-1 where N is the length of your charset. Convert those integers to actual characters only when needed, i.e. after the increment. |
2,067,436 | Right now, I'm working on a project which requires sequential text key generation. I need to seed the key generator with an integer corresponding to a certain key, which the constructor converts to a key.
My key generator overloads the increment operators so that the string is incremented directly, rather than what I had previously been doing, which is incrementing an index value, then converting the index to a key for every key that I wanted to generate.
My problem is that I have a limited character set I want to use when generating keys. I have to find the character in the key that I want to increment, find out where it is in my character set, find the next character in the set, then replace the character in the key with the next character in the set.
Here is my code:
```
// Not the full charset
std::string charset = "abcdefghijklmnopqrstuvwxyz0123456789";
std::string key;
key.push_back(charset[0]);
for(unsigned int place = 0; place < key.length(); place++)
{
if(key[place] == charset[charset.length() - 1])
{
// Overflow, reset char at place
key[place] = charset[0];
if((key.length() - 1) < (place + 1))
{
// Carry, no space, insert char
key.insert(key.begin(), charset[0]);
break;
}
else
{
// Space available, increment next char
continue;
}
}
else
{
// Increment char at place
key[place] = charset[charset.find(key[place]) + 1];
break;
}
}
```
In profiling, I found that the search operation is really slowing things down. Is there any faster way of doing this? I thought of creating a linked list out of the character set, but before I do that, I'd like some input on this. | 2010/01/14 | [
"https://Stackoverflow.com/questions/2067436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136846/"
] | Rather than doing a find, why don't you have a reverse translation array? The array index would be the character, and the value in the array would be its numeric value (or index into the other array).
```
key[place] = charset[reverse_charset[key[place]] + 1];
``` | I am not sure I understood what you wanted to do exactly but here is a little console program that prints out a sequence of 36\*36\*36 3-digit keys in base 36 using your charset as the digits. So it starts at aaa and ends at 999.
```
#include <stdio.h>
typedef int Number;
const size_t N = 3;
size_t B = 36;
Number key[N] = {0};
bool carry = false;
char A[] = "abcdefghifjlmnopqrstuvwxyz0123456789";
void incr(size_t i)
{
if(!carry)
{
return;
}
++key[i];
if(key[i] == B)
{
key[i] = 0;
}
else
{
carry = false;
}
}
void Incr()
{
carry = true;
size_t i = 0;
while(carry)
{
incr(i++);
}
}
void Print()
{
for(int i = N - 1; i >= 0; --i)
{
printf("%c", A[key[i]]);
}
printf("\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
for(int i = 0; i < B * B * B; ++i)
{
Print();
Incr();
}
return 0;
}
``` |
2,067,436 | Right now, I'm working on a project which requires sequential text key generation. I need to seed the key generator with an integer corresponding to a certain key, which the constructor converts to a key.
My key generator overloads the increment operators so that the string is incremented directly, rather than what I had previously been doing, which is incrementing an index value, then converting the index to a key for every key that I wanted to generate.
My problem is that I have a limited character set I want to use when generating keys. I have to find the character in the key that I want to increment, find out where it is in my character set, find the next character in the set, then replace the character in the key with the next character in the set.
Here is my code:
```
// Not the full charset
std::string charset = "abcdefghijklmnopqrstuvwxyz0123456789";
std::string key;
key.push_back(charset[0]);
for(unsigned int place = 0; place < key.length(); place++)
{
if(key[place] == charset[charset.length() - 1])
{
// Overflow, reset char at place
key[place] = charset[0];
if((key.length() - 1) < (place + 1))
{
// Carry, no space, insert char
key.insert(key.begin(), charset[0]);
break;
}
else
{
// Space available, increment next char
continue;
}
}
else
{
// Increment char at place
key[place] = charset[charset.find(key[place]) + 1];
break;
}
}
```
In profiling, I found that the search operation is really slowing things down. Is there any faster way of doing this? I thought of creating a linked list out of the character set, but before I do that, I'd like some input on this. | 2010/01/14 | [
"https://Stackoverflow.com/questions/2067436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136846/"
] | You could store a vector of the same length as your key, where each element in the vector was the index in the charset of the corresponding character in the key.
For example, if `key[0]` was 'c', then `thisVector[0]` would be 2, since 'c' is the 3rd character in the character set.
Then all operations would be performed on that integer vector, removing the necessity for a `find` operation on the string. | Perhaps you would be better off working with indexes into the charset, and then converting them to actual characters when needed?
That would save you the overhead of searching for characters in the charset. And converting a charset index into a character would be a constant-time operation, unlike the inverse.
Store your key as a vector of integers 0 ~ N-1 where N is the length of your charset. Convert those integers to actual characters only when needed, i.e. after the increment. |
2,067,436 | Right now, I'm working on a project which requires sequential text key generation. I need to seed the key generator with an integer corresponding to a certain key, which the constructor converts to a key.
My key generator overloads the increment operators so that the string is incremented directly, rather than what I had previously been doing, which is incrementing an index value, then converting the index to a key for every key that I wanted to generate.
My problem is that I have a limited character set I want to use when generating keys. I have to find the character in the key that I want to increment, find out where it is in my character set, find the next character in the set, then replace the character in the key with the next character in the set.
Here is my code:
```
// Not the full charset
std::string charset = "abcdefghijklmnopqrstuvwxyz0123456789";
std::string key;
key.push_back(charset[0]);
for(unsigned int place = 0; place < key.length(); place++)
{
if(key[place] == charset[charset.length() - 1])
{
// Overflow, reset char at place
key[place] = charset[0];
if((key.length() - 1) < (place + 1))
{
// Carry, no space, insert char
key.insert(key.begin(), charset[0]);
break;
}
else
{
// Space available, increment next char
continue;
}
}
else
{
// Increment char at place
key[place] = charset[charset.find(key[place]) + 1];
break;
}
}
```
In profiling, I found that the search operation is really slowing things down. Is there any faster way of doing this? I thought of creating a linked list out of the character set, but before I do that, I'd like some input on this. | 2010/01/14 | [
"https://Stackoverflow.com/questions/2067436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136846/"
] | You could store a vector of the same length as your key, where each element in the vector was the index in the charset of the corresponding character in the key.
For example, if `key[0]` was 'c', then `thisVector[0]` would be 2, since 'c' is the 3rd character in the character set.
Then all operations would be performed on that integer vector, removing the necessity for a `find` operation on the string. | I am not sure I understood what you wanted to do exactly but here is a little console program that prints out a sequence of 36\*36\*36 3-digit keys in base 36 using your charset as the digits. So it starts at aaa and ends at 999.
```
#include <stdio.h>
typedef int Number;
const size_t N = 3;
size_t B = 36;
Number key[N] = {0};
bool carry = false;
char A[] = "abcdefghifjlmnopqrstuvwxyz0123456789";
void incr(size_t i)
{
if(!carry)
{
return;
}
++key[i];
if(key[i] == B)
{
key[i] = 0;
}
else
{
carry = false;
}
}
void Incr()
{
carry = true;
size_t i = 0;
while(carry)
{
incr(i++);
}
}
void Print()
{
for(int i = N - 1; i >= 0; --i)
{
printf("%c", A[key[i]]);
}
printf("\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
for(int i = 0; i < B * B * B; ++i)
{
Print();
Incr();
}
return 0;
}
``` |
2,067,436 | Right now, I'm working on a project which requires sequential text key generation. I need to seed the key generator with an integer corresponding to a certain key, which the constructor converts to a key.
My key generator overloads the increment operators so that the string is incremented directly, rather than what I had previously been doing, which is incrementing an index value, then converting the index to a key for every key that I wanted to generate.
My problem is that I have a limited character set I want to use when generating keys. I have to find the character in the key that I want to increment, find out where it is in my character set, find the next character in the set, then replace the character in the key with the next character in the set.
Here is my code:
```
// Not the full charset
std::string charset = "abcdefghijklmnopqrstuvwxyz0123456789";
std::string key;
key.push_back(charset[0]);
for(unsigned int place = 0; place < key.length(); place++)
{
if(key[place] == charset[charset.length() - 1])
{
// Overflow, reset char at place
key[place] = charset[0];
if((key.length() - 1) < (place + 1))
{
// Carry, no space, insert char
key.insert(key.begin(), charset[0]);
break;
}
else
{
// Space available, increment next char
continue;
}
}
else
{
// Increment char at place
key[place] = charset[charset.find(key[place]) + 1];
break;
}
}
```
In profiling, I found that the search operation is really slowing things down. Is there any faster way of doing this? I thought of creating a linked list out of the character set, but before I do that, I'd like some input on this. | 2010/01/14 | [
"https://Stackoverflow.com/questions/2067436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136846/"
] | This is another version of the generalized base conversion problem, with n=36.
What you want to do is view your key as an unsigned integer, and view the "string" that you're handing out as a base 36 (a-z + 0-9) representation of that key.
Handing out a key then becomes converting the "next key" value to the base36 string, then increment the next key value.
To convert, do the same thing you'd do to convert any integer to a hex representation, but swap in 36 instead of 16 on the modulo math. I'll leave this as an exercise for the reader. :) | Perhaps you would be better off working with indexes into the charset, and then converting them to actual characters when needed?
That would save you the overhead of searching for characters in the charset. And converting a charset index into a character would be a constant-time operation, unlike the inverse.
Store your key as a vector of integers 0 ~ N-1 where N is the length of your charset. Convert those integers to actual characters only when needed, i.e. after the increment. |
2,067,436 | Right now, I'm working on a project which requires sequential text key generation. I need to seed the key generator with an integer corresponding to a certain key, which the constructor converts to a key.
My key generator overloads the increment operators so that the string is incremented directly, rather than what I had previously been doing, which is incrementing an index value, then converting the index to a key for every key that I wanted to generate.
My problem is that I have a limited character set I want to use when generating keys. I have to find the character in the key that I want to increment, find out where it is in my character set, find the next character in the set, then replace the character in the key with the next character in the set.
Here is my code:
```
// Not the full charset
std::string charset = "abcdefghijklmnopqrstuvwxyz0123456789";
std::string key;
key.push_back(charset[0]);
for(unsigned int place = 0; place < key.length(); place++)
{
if(key[place] == charset[charset.length() - 1])
{
// Overflow, reset char at place
key[place] = charset[0];
if((key.length() - 1) < (place + 1))
{
// Carry, no space, insert char
key.insert(key.begin(), charset[0]);
break;
}
else
{
// Space available, increment next char
continue;
}
}
else
{
// Increment char at place
key[place] = charset[charset.find(key[place]) + 1];
break;
}
}
```
In profiling, I found that the search operation is really slowing things down. Is there any faster way of doing this? I thought of creating a linked list out of the character set, but before I do that, I'd like some input on this. | 2010/01/14 | [
"https://Stackoverflow.com/questions/2067436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136846/"
] | I am not sure I understood what you wanted to do exactly but here is a little console program that prints out a sequence of 36\*36\*36 3-digit keys in base 36 using your charset as the digits. So it starts at aaa and ends at 999.
```
#include <stdio.h>
typedef int Number;
const size_t N = 3;
size_t B = 36;
Number key[N] = {0};
bool carry = false;
char A[] = "abcdefghifjlmnopqrstuvwxyz0123456789";
void incr(size_t i)
{
if(!carry)
{
return;
}
++key[i];
if(key[i] == B)
{
key[i] = 0;
}
else
{
carry = false;
}
}
void Incr()
{
carry = true;
size_t i = 0;
while(carry)
{
incr(i++);
}
}
void Print()
{
for(int i = N - 1; i >= 0; --i)
{
printf("%c", A[key[i]]);
}
printf("\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
for(int i = 0; i < B * B * B; ++i)
{
Print();
Incr();
}
return 0;
}
``` | Perhaps you would be better off working with indexes into the charset, and then converting them to actual characters when needed?
That would save you the overhead of searching for characters in the charset. And converting a charset index into a character would be a constant-time operation, unlike the inverse.
Store your key as a vector of integers 0 ~ N-1 where N is the length of your charset. Convert those integers to actual characters only when needed, i.e. after the increment. |
2,067,436 | Right now, I'm working on a project which requires sequential text key generation. I need to seed the key generator with an integer corresponding to a certain key, which the constructor converts to a key.
My key generator overloads the increment operators so that the string is incremented directly, rather than what I had previously been doing, which is incrementing an index value, then converting the index to a key for every key that I wanted to generate.
My problem is that I have a limited character set I want to use when generating keys. I have to find the character in the key that I want to increment, find out where it is in my character set, find the next character in the set, then replace the character in the key with the next character in the set.
Here is my code:
```
// Not the full charset
std::string charset = "abcdefghijklmnopqrstuvwxyz0123456789";
std::string key;
key.push_back(charset[0]);
for(unsigned int place = 0; place < key.length(); place++)
{
if(key[place] == charset[charset.length() - 1])
{
// Overflow, reset char at place
key[place] = charset[0];
if((key.length() - 1) < (place + 1))
{
// Carry, no space, insert char
key.insert(key.begin(), charset[0]);
break;
}
else
{
// Space available, increment next char
continue;
}
}
else
{
// Increment char at place
key[place] = charset[charset.find(key[place]) + 1];
break;
}
}
```
In profiling, I found that the search operation is really slowing things down. Is there any faster way of doing this? I thought of creating a linked list out of the character set, but before I do that, I'd like some input on this. | 2010/01/14 | [
"https://Stackoverflow.com/questions/2067436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136846/"
] | This is another version of the generalized base conversion problem, with n=36.
What you want to do is view your key as an unsigned integer, and view the "string" that you're handing out as a base 36 (a-z + 0-9) representation of that key.
Handing out a key then becomes converting the "next key" value to the base36 string, then increment the next key value.
To convert, do the same thing you'd do to convert any integer to a hex representation, but swap in 36 instead of 16 on the modulo math. I'll leave this as an exercise for the reader. :) | I am not sure I understood what you wanted to do exactly but here is a little console program that prints out a sequence of 36\*36\*36 3-digit keys in base 36 using your charset as the digits. So it starts at aaa and ends at 999.
```
#include <stdio.h>
typedef int Number;
const size_t N = 3;
size_t B = 36;
Number key[N] = {0};
bool carry = false;
char A[] = "abcdefghifjlmnopqrstuvwxyz0123456789";
void incr(size_t i)
{
if(!carry)
{
return;
}
++key[i];
if(key[i] == B)
{
key[i] = 0;
}
else
{
carry = false;
}
}
void Incr()
{
carry = true;
size_t i = 0;
while(carry)
{
incr(i++);
}
}
void Print()
{
for(int i = N - 1; i >= 0; --i)
{
printf("%c", A[key[i]]);
}
printf("\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
for(int i = 0; i < B * B * B; ++i)
{
Print();
Incr();
}
return 0;
}
``` |
11,172,620 | I am struggling with linking ALAssetsLibrary in my code.
I have googled a lot on this and followed more than one tutorial to the last dot yet I am still where I began.
```
Ld /Users/vedprakash/Library/Developer/Xcode/DerivedData/PickThumb-gmvprlkgmgexedeojbaoeidbadnw/Build/Products/Debug-iphonesimulator/PickThumb.app/PickThumb normal i386
cd "/Users/vedprakash/Documents/XCode Projects/PickThumb"
setenv MACOSX_DEPLOYMENT_TARGET 10.6
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/clang -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk -L/Users/vedprakash/Library/Developer/Xcode/DerivedData/PickThumb-gmvprlkgmgexedeojbaoeidbadnw/Build/Products/Debug-iphonesimulator -F/Users/vedprakash/Library/Developer/Xcode/DerivedData/PickThumb-gmvprlkgmgexedeojbaoeidbadnw/Build/Products/Debug-iphonesimulator -filelist /Users/vedprakash/Library/Developer/Xcode/DerivedData/PickThumb-gmvprlkgmgexedeojbaoeidbadnw/Build/Intermediates/PickThumb.build/Debug-iphonesimulator/PickThumb.build/Objects-normal/i386/PickThumb.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -Xlinker -no_implicit_dylibs -D__IPHONE_OS_VERSION_MIN_REQUIRED=50000 -framework UIKit -framework Foundation -framework CoreGraphics -o /Users/vedprakash/Library/Developer/Xcode/DerivedData/PickThumb-gmvprlkgmgexedeojbaoeidbadnw/Build/Products/Debug-iphonesimulator/PickThumb.app/PickThumb
Undefined symbols for architecture i386:
"_OBJC_CLASS_$_ALAssetsLibrary", referenced from:
objc-class-ref in PickThumbViewController.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
``` | 2012/06/23 | [
"https://Stackoverflow.com/questions/11172620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1477296/"
] | You need to add the `AssetsLibrary` framework to the “Link Binary With Libraries” build phase of your `PickThumb` target.
[How to "add existing frameworks" in Xcode 4?](https://stackoverflow.com/questions/3352664/how-to-add-existing-frameworks-in-xcode-4) | In Xcode 10.2 I just added
```
AssetsLibrary.framework
```
in the Target>Build Phases> Link Binary With Libraries section |
14,763,212 | Compare const and non-const pointers. Is the comparison legal? Any special care for such comparison. Thanks. | 2013/02/07 | [
"https://Stackoverflow.com/questions/14763212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2052376/"
] | A pointer to `T` can be implicitly converted into a const pointer to `T`; similarly, a pointer to `T` can be implicitly converted into a pointer to `const T`. The compiler will do either of those conversions, or both, as needed when you try to compare a pointer to a const pointer. There's nothing there that's any more risky than comparing two non-const pointers or two const pointers. | The purpose of const as in
>
> const char\* p
>
>
>
is to promise that you will not change it. In theory, a non-const pointer should never be pointing at the same location in the same code, as a matter of good coding practice that is. In practice, you may end up making something const because it makes your life easier, but it is not really a true const conceptually. In that case you might need to compare. As was mentioned, depending on what compiler you are using and what settings it has, it may or may not like such a comparison. Just in case it might not, force a cast to a non-const before comparing if this is bothering you, like this, for example:
>
> if ((char\*)const\_p == non\_const\_p)
>
>
> |
3,804,875 | How would you suggest using `AsEnumerable` on a non-generic `IQueryable`?
I cannot use the `Cast<T>` or `OfType<T>` methods to get an `IQueryable<object>` before calling `AsEnumerable`, since these methods have their own explicit translation by the underlying `IQueryProvider` and will break the query translation if I use them with a non-mapped entity (obviously object is not mapped).
Right now, I have my own extension method for this (below), but I'm wondering if there's a way built into the framework.
```
public static IEnumerable AsEnumerable(this IQueryable queryable)
{
foreach (var item in queryable)
{
yield return item;
}
}
```
So, with the above extension method, I can now do:
```
IQueryable myQuery = // some query...
// this uses the built in AsEnumerable, but breaks the IQueryable's provider because object is not mapped to the underlying datasource (and cannot be)
var result = myQuery.Cast<object>().AsEnumerable().Select(x => ....);
// this works (and uses the extension method defined above), but I'm wondering if there's a way in the framework to accomplish this
var result = myQuery.AsEnumerable().Cast<object>().Select(x => ...);
``` | 2010/09/27 | [
"https://Stackoverflow.com/questions/3804875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326518/"
] | Since the interface `IQueryable` inherits from `IEnumerable` why not:
```
IQueryable queryable;
IEnumerable<T> = (queryable as IEnumerable).Cast<T>();
```
**Edit**
There are two `Cast<>` extension methods:
```
public static IQueryable<TResult> Cast<TResult>(this IQueryable source)
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source)
```
Which one is called is statically decided by the compiler. So casting an `IQueryable` as an `IEnumerable` will cause the second extension method to be called, where it will be treated as an `IEnumerable`. | The type `IQueryable` inherits from the non-generic `IEnumerable` so this extension method doesn't seem to serve any purpose. Why not just use it as `IEnumerable` directly? |
3,804,875 | How would you suggest using `AsEnumerable` on a non-generic `IQueryable`?
I cannot use the `Cast<T>` or `OfType<T>` methods to get an `IQueryable<object>` before calling `AsEnumerable`, since these methods have their own explicit translation by the underlying `IQueryProvider` and will break the query translation if I use them with a non-mapped entity (obviously object is not mapped).
Right now, I have my own extension method for this (below), but I'm wondering if there's a way built into the framework.
```
public static IEnumerable AsEnumerable(this IQueryable queryable)
{
foreach (var item in queryable)
{
yield return item;
}
}
```
So, with the above extension method, I can now do:
```
IQueryable myQuery = // some query...
// this uses the built in AsEnumerable, but breaks the IQueryable's provider because object is not mapped to the underlying datasource (and cannot be)
var result = myQuery.Cast<object>().AsEnumerable().Select(x => ....);
// this works (and uses the extension method defined above), but I'm wondering if there's a way in the framework to accomplish this
var result = myQuery.AsEnumerable().Cast<object>().Select(x => ...);
``` | 2010/09/27 | [
"https://Stackoverflow.com/questions/3804875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326518/"
] | Since the interface `IQueryable` inherits from `IEnumerable` why not:
```
IQueryable queryable;
IEnumerable<T> = (queryable as IEnumerable).Cast<T>();
```
**Edit**
There are two `Cast<>` extension methods:
```
public static IQueryable<TResult> Cast<TResult>(this IQueryable source)
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source)
```
Which one is called is statically decided by the compiler. So casting an `IQueryable` as an `IEnumerable` will cause the second extension method to be called, where it will be treated as an `IEnumerable`. | JaredPar's answer in other words:
```
public static IEnumerable AsEnumerable(this IEnumerable source)
{
return source;
}
```
Usage:
```
IQueryable queryable = // ...
IEnumerable enumerable = queryable.AsEnumerable();
IEnumerable<Foo> result = enumerable.Cast<Foo>();
// ↑
// Enumerable.Cast<TResult>(this IEnumerable source)
``` |
3,804,875 | How would you suggest using `AsEnumerable` on a non-generic `IQueryable`?
I cannot use the `Cast<T>` or `OfType<T>` methods to get an `IQueryable<object>` before calling `AsEnumerable`, since these methods have their own explicit translation by the underlying `IQueryProvider` and will break the query translation if I use them with a non-mapped entity (obviously object is not mapped).
Right now, I have my own extension method for this (below), but I'm wondering if there's a way built into the framework.
```
public static IEnumerable AsEnumerable(this IQueryable queryable)
{
foreach (var item in queryable)
{
yield return item;
}
}
```
So, with the above extension method, I can now do:
```
IQueryable myQuery = // some query...
// this uses the built in AsEnumerable, but breaks the IQueryable's provider because object is not mapped to the underlying datasource (and cannot be)
var result = myQuery.Cast<object>().AsEnumerable().Select(x => ....);
// this works (and uses the extension method defined above), but I'm wondering if there's a way in the framework to accomplish this
var result = myQuery.AsEnumerable().Cast<object>().Select(x => ...);
``` | 2010/09/27 | [
"https://Stackoverflow.com/questions/3804875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326518/"
] | Since the interface `IQueryable` inherits from `IEnumerable` why not:
```
IQueryable queryable;
IEnumerable<T> = (queryable as IEnumerable).Cast<T>();
```
**Edit**
There are two `Cast<>` extension methods:
```
public static IQueryable<TResult> Cast<TResult>(this IQueryable source)
public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source)
```
Which one is called is statically decided by the compiler. So casting an `IQueryable` as an `IEnumerable` will cause the second extension method to be called, where it will be treated as an `IEnumerable`. | To clarify, you are trying to add a "force expression evaluation" to your linq expression tree so that part of the expression tree is evaluated against the underlying provider (linq to SQL for example) and the rest is evaluated in memory (linq to objects). But you want to be able to specify the entire express tree without actually executing the query or reading any results into memory.
This is a good thing and it shows some insight into the way that Linq works. Good job.
The confusion I see here is your use of "AsEnumerable" as the method name. To me (and I think many people who thinq linq ) "AsEnumerable" is too similar to the "AsQueryable" method which is essentially a cast, not an actual evaluator. I propose you rename your method to "Evaluate". This is my Evaluate() method from my personal Linq extensions library.
```
/// <summary>
/// This call forces immediate evaluation of the expression tree.
/// Any earlier expressions are evaluated immediately against the underlying IQueryable (perhaps
/// a Linq to SQL provider) while any later expressions are evaluated against the resulting object
/// graph in memory.
/// This is one way to determine whether expressions get evaluated by the underlying provider or
/// by Linq to Objects in memory.
/// </summary>
public static IEnumerable<T> Evaluate<T>(this IEnumerable<T> expression)
{
foreach (var item in expression)
{
yield return item;
}
}
/// <summary>
/// This call forces immediate evaluation of the expression tree.
/// Any earlier expressions are evaluated immediately against the underlying IQueryable (perhaps
/// a Linq to SQL provider) while any later expressions are evaluated against the resulting object
/// graph in memory.
/// This is one way to determine whether expressions get evaluated by the underlying provider or
/// by Linq to Objects in memory.
/// </summary>
public static IEnumerable Evaluate(this IEnumerable expression)
{
foreach (var item in expression)
{
yield return item;
}
}
```
This allows you to write a query where some of the query is evaluated by SQL (for example) and the rest is evaluated in memory. A good thing. |
8,733,999 | I have an rss parser as part of my app code, and it is working fine and loading the rss xml file and populating the tableview fine.
The problem is with a refresh/reload button, which does reload the rss data, but it APPENDS the new data to the table and the table just grows and grows in size.
What the behaviour should do is to clear the old table data and rebuild the table with the new data - so that the table always shows just ONE set of data and doesn't keep growing every time the reload/refresh is pressed.
The table build code is as follows:
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
cell.textLabel.text = [[stories objectAtIndex: storyIndex] objectForKey: @"date"];
cell.detailTextLabel.text = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
[cell.textLabel setLineBreakMode:UILineBreakModeWordWrap];
[cell.textLabel setNumberOfLines:0];
[cell.textLabel sizeToFit];
[cell.detailTextLabel setLineBreakMode:UILineBreakModeWordWrap];
[cell.detailTextLabel setNumberOfLines:0];
[cell.detailTextLabel sizeToFit];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
```
And the reload/refresh button code is:
```
- (void)reloadRss {
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
[[self navigationItem] setLeftBarButtonItem:barButton];
[barButton release];
[activityIndicator release];
[activityIndicator startAnimating];
[self performSelector:@selector(parseXMLFileAtURL) withObject:nil afterDelay:0];
[newsTable reloadData];
}
```
I have tried to solve this by adding the line:
```
if (stories) { [stories removeAllObjects]; }
```
to the reload section, which I think should work and does clear the table, but the app then crashes the app with an EXC\_BAD\_ACCESS.
Any ideas or suggestions greatly appreciated! | 2012/01/04 | [
"https://Stackoverflow.com/questions/8733999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1076261/"
] | Actually, have now solved this!
Was due to "autoreleasing" elements of the array, so after clearing this out, they were invalid.
Removing `autorelease` and just releasing these objects in the final dealloc worked. | The Code **EXC\_BAD\_ACCESS** does mean, that you want connect at a variable that does not exists anymore.
In your code example, I can see, the problem to see at the following two lines of code:
```
[activityIndicator release];
[activityIndicator startAnimating];
```
You release the activityIdicator befor starting the Animating.
Try to release at the end of the function.
```
[activityIndicator startAnimating];
[self performSelector:@selector(parseXMLFileAtURL) withObject:nil afterDelay:0];
[newsTable reloadData];
[activityIndicator release];
``` |
21,279,393 | I have some questions about XMLHttpRequest using $.Post $.Ajax:
1- How the server side verifies if the request was sent from same browser?
2- How the server side verifies if session user who sent the request has been changed on same browser? (ex: user logout and another user login on same browser)
3- Do I need any special settings or PHP code at server side for #1 and #2?
Also please give me a link to good documentation about any security issues related to XMLHttpRequest.
Thanks | 2014/01/22 | [
"https://Stackoverflow.com/questions/21279393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2007059/"
] | 1. Browsers and servers use cookies to check whether request was sent from same browser. Every request will have cookies attached.
2. The basic idea about the sessions is simple. Whenever you send a request to the server, the session variable (if present) will be sent along with the request to your server.
Again, if you modify anything in session or clear the session, the response will contain the modified session. Since both request and response contain sessions, they can operate independently.
3. By using $\_SESSION in PHP, you will be able to retrieve sessions in server. Just use $\_SESSION['userid'] == to check whether it's the same user.
I understand you are a PHP person but take a look at node.js request and response objects for a better clarity about sessions.
Also you can encrypt session variables in server for security. Code Igniter session library is an excellent example for this. | 1. It doesn't
2. By whatever mechanism it uses to track who is logged in for any other kind of request (presumably the data your server side application stores in the session will change)
3. No |
222,298 | The effect I'm looking for in the end is to have the first line in some paragraphs bolded. These would be the first paragraph of each section in my post. This kind of effect is used on [this](http://www.bloomberg.com/features/2016-how-to-hack-an-election/) Bloomberg.com post. Notice the first paragraph in the post and then also the first paragraph of later sections of the post are bolded. The way they accomplished this was to have a particular class ("section-break" in their post) applied to the paragraphs they wanted this effect on, and then using the ::first-line css pseudo class, applying it to the paragraphs with the "section-break" class.
I can set up the css to do that what they did; the only thing I'm struggling with his how I can delineate, while writing my post, which paragraphs would be the beginning of a new section and so would need to have their own "section-break" class. Is there a built in way to do this? And if not how might I be able to hack it in?
Thanks! | 2016/04/01 | [
"https://wordpress.stackexchange.com/questions/222298",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91575/"
] | I figured this out. Even though Wordpress automatically adds the `<p>` tag and doesn't show it to you in the editor (in either the 'visual' or 'text' editor views), you can type it in anyway in the 'text' editor view, along with a class.
So to do this, go to the 'text' editor view, and just type, e.g., `<p class="section-break>Here is the first paragraph of a new section of my document</p>`.
And although when you type a regular `<p>` tag yourself (without a class) it will disappear when you switch to the 'visual' editor and back to the 'text' editor view, if instead you type it in with a class, it will stay there available to edit if it has a class attribute (e.g., `<p class="something">stuff</p>`). | If you want to add specific styles to a specific section within the paragraph you can create a element with a class name, and then add styles within your stylesheet.
Or, in this case, you can just use to make a line bold. |
47,012,120 | I have a dataframe of IDs and addresses. Normally, I would expect each recurring ID to have the same address in all observations, but some of my IDs have different addresses. I want to locate those observations that are duplicated on ID, but have at least 2 different addresses. Then, I want to randomize a new ID for one of them (an ID that didn't exist in the DF before).
For example:
```
ID Address
1 X
1 X
1 Y
2 Z
2 Z
3 A
3 B
4 C
4 D
4 E
5 F
5 F
5 F
```
Will return:
```
ID Address
1 X
1 X
6 Y
2 Z
2 Z
3 A
7 B
4 C
8 D
9 E
5 F
5 F
5 F
```
So what happened is the 3rd,7th, 9th and 10th observations got new IDs. I will mention that it is possible for an ID to have even more than 2 different addresses, so the granting of new IDs should happen for each unique address.
Edit:
I added a code for a longer example of a data frame, with rand column that should be ignored but kept in final output.
```
df <- data.frame(ID = c(1,1,1,2,2,3,3,4,4,4,5,5,5),
Address = c("x","x","y","z","z","a","b","c","d","e",
"f","f","f"),
rand = sample(1:100, 13))
``` | 2017/10/30 | [
"https://Stackoverflow.com/questions/47012120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4732998/"
] | Here's a solution with `tidyr` and functions `nest` / `unnest`
```
library(tidyr)
library(dplyr)
df %>% group_by(ID,Address) %>% nest %>%
`[<-`(duplicated(.$ID),"ID",max(.$ID, na.rm = TRUE) + 1:sum(duplicated(.$ID))) %>%
unnest
# # A tibble: 13 x 3
# ID Address rand
# <dbl> <fctr> <int>
# 1 1 x 58
# 2 1 x 4
# 3 6 y 75
# 4 2 z 5
# 5 2 z 19
# 6 3 a 55
# 7 7 b 34
# 8 4 c 53
# 9 8 d 98
# 10 9 e 97
# 11 5 f 13
# 12 5 f 64
# 13 5 f 80
```
If you use `magrittr`, replace `[<-` with `inset` if you want prettier code (same output). | An option would be `data.table`. After grouping by 'ID', `if` the number of `unique` 'Address' is greater than 1 and the 'Address' is not equal to the first `unique` 'Address', then get the row index (`.I`) and assign those 'ID' with the 'ID's that are not already in the original dataset
```
library(data.table)
i1 <- setDT(df)[, .I[if(uniqueN(Address)>1) Address != unique(Address)[1]], ID]$V1
df[i1, ID := head(setdiff(as.numeric(1:10), unique(df$ID)), length(i1))]
df
# ID Address rand
# 1: 1 x 58
# 2: 1 x 4
# 3: 6 y 75
# 4: 2 z 5
# 5: 2 z 19
# 6: 3 a 55
# 7: 7 b 34
# 8: 4 c 53
# 9: 8 d 98
# 10: 9 e 97
# 11: 5 f 13
# 12: 5 f 64
# 13: 5 f 80
```
---
Or we can use `base R`
```
ids <- names(which(rowSums(table(unique(df)))>1))
i2 <- with(df, ID %in% ids & Address != ave(as.character(Address),
ID, FUN = function(x) x[1]))
df$ID[i2] <- head(setdiff(1:10, unique(df$ID)), sum(i2))
``` |
42,362,024 | I am getting the following crash for a lot of users :
```
Fatal Exception: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Set java.util.Map.keySet()' on a null object reference
at com.google.android.gms.internal.zzbtn.zza(Unknown Source)
at com.google.android.gms.internal.zzbtn.run(Unknown Source)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
```
I searched through external libraries and found that the source of crash is firebase-config library in the following class zzbtn(see method - zza()).
```
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.google.android.gms.internal;
import android.content.Context;
import android.util.Log;
import com.google.android.gms.internal.zzbtl;
import com.google.android.gms.internal.zzbto;
import com.google.android.gms.internal.zzbtr;
import com.google.android.gms.internal.zzbxt;
import com.google.android.gms.internal.zzbts.zza;
import com.google.android.gms.internal.zzbts.zzb;
import com.google.android.gms.internal.zzbts.zzc;
import com.google.android.gms.internal.zzbts.zzd;
import com.google.android.gms.internal.zzbts.zze;
import com.google.android.gms.internal.zzbts.zzf;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class zzbtn implements Runnable {
public final Context mContext;
public final zzbto zzclY;
public final zzbto zzclZ;
public final zzbto zzcma;
public final zzbtr zzclQ;
public zzbtn(Context var1, zzbto var2, zzbto var3, zzbto var4, zzbtr var5) {
this.mContext = var1;
this.zzclY = var2;
this.zzclZ = var3;
this.zzcma = var4;
this.zzclQ = var5;
}
private zza zza(zzbto var1) {
zza var2 = new zza();
if(var1.zzace() != null) {
Map var3 = var1.zzace();
ArrayList var4 = new ArrayList();
Iterator var5 = var3.keySet().iterator();
while(var5.hasNext()) {
String var6 = (String)var5.next();
ArrayList var7 = new ArrayList();
Map var8 = (Map)var3.get(var6);
/* Crash is here when reading keySet() on null map */
Iterator var9 = var8.keySet().iterator();
while(var9.hasNext()) {
String var10 = (String)var9.next();
zzb var11 = new zzb();
var11.zzaB = var10;
var11.zzcml = (byte[])var8.get(var10);
var7.add(var11);
}
zzd var16 = new zzd();
var16.zzaGP = var6;
zzb[] var12 = new zzb[var7.size()];
var16.zzcmq = (zzb[])var7.toArray(var12);
var4.add(var16);
}
zzd[] var15 = new zzd[var4.size()];
var2.zzcmi = (zzd[])var4.toArray(var15);
}
if(var1.zzzD() != null) {
List var13 = var1.zzzD();
byte[][] var14 = new byte[var13.size()][];
var2.zzcmj = (byte[][])var13.toArray(var14);
}
var2.timestamp = var1.getTimestamp();
return var2;
}
public void run() {
zze var1 = new zze();
if(this.zzclY != null) {
var1.zzcmr = this.zza(this.zzclY);
}
if(this.zzclZ != null) {
var1.zzcms = this.zza(this.zzclZ);
}
if(this.zzcma != null) {
var1.zzcmt = this.zza(this.zzcma);
}
if(this.zzclQ != null) {
zzc var2 = new zzc();
var2.zzcmm = this.zzclQ.getLastFetchStatus();
var2.zzcmn = this.zzclQ.isDeveloperModeEnabled();
var2.zzcmo = this.zzclQ.zzacj();
var1.zzcmu = var2;
}
if(this.zzclQ != null && this.zzclQ.zzach() != null) {
ArrayList var8 = new ArrayList();
Map var3 = this.zzclQ.zzach();
Iterator var4 = var3.keySet().iterator();
while(var4.hasNext()) {
String var5 = (String)var4.next();
if(var3.get(var5) != null) {
zzf var6 = new zzf();
var6.zzaGP = var5;
var6.zzcmx = ((zzbtl)var3.get(var5)).zzacd();
var6.resourceId = ((zzbtl)var3.get(var5)).zzacc();
var8.add(var6);
}
}
zzf[] var11 = new zzf[var8.size()];
var1.zzcmv = (zzf[])var8.toArray(var11);
}
byte[] var9 = zzbxt.zzf(var1);
try {
FileOutputStream var10 = this.mContext.openFileOutput("persisted_config", 0);
var10.write(var9);
var10.close();
} catch (IOException var7) {
Log.e("AsyncPersisterTask", "Could not persist config.", var7);
}
}
}
```
This class is used in FirebaseRemoteConfig class (see method zzt()) as given below :
<https://gist.github.com/anonymous/e6f23c1dc37bf905a9224d8b72ab6cd9>
And I am using FirebaseRemoteConfig in my application class as below :
```
public class MyApp extends MultiDexApplication {
public static boolean sound = true;
private static Context context;
private Typeface regularTypeFace;
private Typeface boldTypeFace;
private final String LOG_TAG = "MyApp";
private FirebaseRemoteConfig remoteConfig = null;
@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
context = getApplicationContext();
/* Try catch to handle any runtime exception thrown by firebase API */
try {
/* Initialize firebase app : Done to avoid crashes due to IllegalStateException - Default FirebaseApp is not initialized */
FirebaseApp.initializeApp(this);
/* Start to fetch Remote config parameters */
startConfigFetch();
} catch (Exception e){
e.printStackTrace();
}
}
/**
* Description : Fetches remote config params from firebase & uses the fetched values
*/
public void startConfigFetch() {
/* try to get the default instance of Firebase Remote config */
/* try-catch : To Resolve Crash #1399 */
try {
remoteConfig = FirebaseRemoteConfig.getInstance();
} catch (IllegalStateException e){
e.printStackTrace();
}
/* If we don't get an instance of Firebase remote config, then do nothing */
if (remoteConfig == null){
return;
}
FirebaseRemoteConfigSettings remoteConfigSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
remoteConfig.setConfigSettings(remoteConfigSettings);
remoteConfig.setDefaults(R.xml.remote_config_defaults);
/* Time for which cache lives, for now its 0 ms */
long cacheExpiration = 0;
OnCompleteListener<Void> onCompleteListener = new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
if (getContext() != null) {
onFetchConfigSuccess();
}
} else {
Log.d(LOG_TAG, "Stories Fetch Fail");
}
}
};
OnFailureListener onFailListener = new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d(LOG_TAG, "Stories Fetch Fail in remote config");
}
};
remoteConfig.fetch(cacheExpiration).addOnCompleteListener(onCompleteListener).addOnFailureListener(onFailListener);
}
/**
* Called when fetch config is success
* */
private void onFetchConfigSuccess() {
/* Once the config is successfully fetched it must be activated before newly fetched */
/* values are returned (or can be used) */
remoteConfig.activateFetched();
/* Get dynamic stories string */
String dynamicStories = remoteConfig.getString(Common.KEY_DYNAMIC_STORIES_FIREBASE_CONFIG);
/* Get bundled stories (these are app-bundled stories & dynamic stories but part of bundled stories) */
String bundledStories = remoteConfig.getString(Common.KEY_BUNDLED_STORIES_FIREBASE_CONFIG);
/* Do something with dynamicStories & bundledStories values */
}
}
```
And class zzbto is here :
<https://gist.github.com/anonymous/e2f3a67e6fd3be51ba4456fe2e847890>
Please help to resolve this crash. | 2017/02/21 | [
"https://Stackoverflow.com/questions/42362024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3904327/"
] | Hint:
1. Produce `[f x1,...,f xn]` first, applying `f` to every member.
2. Then, write a function that takes `[y1,...,yn]` and `w` and produces an interleaving `[y1,w,y2,w,...,yn]`. This can be done by recursion. (There's also a library function for that, but it's not important.)
3. Compose both, to obtain `[f x1, ",", ...]` and then concatenate the result.
4. Add brackets to the resulting string. | How about this:
```
import Data.List
flist f list = "[" ++ (intercalate "," $ map f list) ++ "]"
```
`intercalate` puts Strings in between of other Strings, it is (in this case) [a slightly configurable version of `unwords`](https://stackoverflow.com/questions/5521560/haskell-words-unwords-delimiter). |
48,247,393 | I am trying to preload server form in the constructor of client form, in a separate thread. My reason is that server load is time consuming.
Here's the client form, you can see in the constructor that I am calling `Preload()`. There's also a button, clicking on it should show the server, which should be fast since the server form is already preloaded:
```
public partial class Form1 : Form
{
ServerUser server = null;
public Form1()
{
InitializeComponent();
Preload();
}
public async void Preload()
{
await Task.Run(() =>
{
server = new ServerUser();
server.LoadDocument();
server.ShowDialog();
}
);
}
private void button1_Click(object sender, EventArgs e)
{
server.Show();
}
}
```
Here I try to preload form `ServerUser` in constructor of `Form1` and if I click on button1 Server form show faster
And here's the server form:
```
public partial class ServerUser : Form
{
public ServerUser()
{
InitializeComponent();
}
public void LoadDocument()
{
ConfigureSource();
}
public void ConfigureSource()
{
InvokeUpdateControls();
}
public void InvokeUpdateControls()
{
UpdateControls();
}
private void UpdateControls()
{
richTextBox1.Rtf = Resource1.ReferatPPC_Bun___Copy;
}
}
``` | 2018/01/14 | [
"https://Stackoverflow.com/questions/48247393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9018083/"
] | You need to rethink your design. You should create all forms from the main UI thread, and offload the heavy lifting(non UI stuff) to the background threads. Calling UI methods from background threads results in undefined behavior or exceptions.
Also, I think you misunderstand what `await` does. You call `Preload()` synchronously even though it is an asynchronous method. This means that by the time `server.Show();` is called, Server might still be running one of these methods:
```
server = new ServerUser(); //you should move this outside of Task.Run()
server.LoadDocument(); //implement this method using background threads
server.ShowDialog(); //this will actually throw an exception if called via Task.Run();
```
From your sample I suppose LoadDocument is the expensive operation. You should rewrite that method to run on a background thread and make `ServerUser` show a loading screen untill `LoadDocument()` completes. Make sure that all UI methods from LoadDocument are called via [BeginInvoke](https://msdn.microsoft.com/en-us/library/0b1bf3y3(v=vs.110).aspx)
or **proper** async/await. | Send in constructor;
```
public partial class ServerUser : Form
{
public ServerUser(Form1 form1)
{
InitializeComponent();
form1.Preload();
}
public void LoadDocument()
{
ConfigureSource();
}
public void ConfigureSource()
{
InvokeUpdateControls();
}
public void InvokeUpdateControls()
{
UpdateControls();
}
private void UpdateControls()
{
richTextBox1.Rtf = Resource1.ReferatPPC_Bun___Copy;
}
}
public partial class Form1 : Form
{
ServerUser server = null;
public Form1()
{
InitializeComponent();
Preload();
}
public async void Preload()
{
await Task.Run(() =>
{
server = new ServerUser();
server.LoadDocument();
server.ShowDialog();
}
);
}
private void button1_Click(object sender, EventArgs e)
{
server=new ServerUser(this);// or whatever you want
server.Show();
}
}
``` |
128,840 | We need to do some user documentation for a product we have been working on for the past few sprints. We are now starting a new project in the next sprint and the PO is making the documentation for the product produced previously a User story for this sprint.
I am just wondering your opinion on this approach. Personally, I don't agree that documentation is a User Story within Scrum because it doesn't produce any code.
EDIT: Thanks for your opinions guys. I had it in the back of my head that a sprint was to implement an increment of working software, but your views have changed my outlook. Thank you for all your answers. | 2012/01/06 | [
"https://softwareengineering.stackexchange.com/questions/128840",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/40251/"
] | "As a user of X, I need to know how X works" seems like a legitimate user story to me. This could result in written documentation or online help.
The point isn't just code--it's meeting the users' requirements. | Ideally, documentation is part of every user story and never builds up. But, in the real world, that often doesn't happen. In that case, you should create a user story for catching up on a specific missing piece of documentation.
You're right, it doesn't produce any code. But it does satisfy a user requirement and should be prioritised against other user requirements.
If this means that it never gets done, because this and that functionality is being worked on then you probably didn't need the documentation that badly. |
128,840 | We need to do some user documentation for a product we have been working on for the past few sprints. We are now starting a new project in the next sprint and the PO is making the documentation for the product produced previously a User story for this sprint.
I am just wondering your opinion on this approach. Personally, I don't agree that documentation is a User Story within Scrum because it doesn't produce any code.
EDIT: Thanks for your opinions guys. I had it in the back of my head that a sprint was to implement an increment of working software, but your views have changed my outlook. Thank you for all your answers. | 2012/01/06 | [
"https://softwareengineering.stackexchange.com/questions/128840",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/40251/"
] | Ideally, documentation is part of every user story and never builds up. But, in the real world, that often doesn't happen. In that case, you should create a user story for catching up on a specific missing piece of documentation.
You're right, it doesn't produce any code. But it does satisfy a user requirement and should be prioritised against other user requirements.
If this means that it never gets done, because this and that functionality is being worked on then you probably didn't need the documentation that badly. | I agree with pdr's documentation assessment if its about requirement, technical or project documentation. Ideally it should be incorporated into sprint work.
Product documentation I feel is very different as it is an actual user requested deliverable and directly provides value to the user. This should be understood of course that Product Documentation is essentially **not** a Technical Task but a Functional Task, and may or may not be a suitable activity for a technical resource on the project.
I think it should be a user story, however I feel that a project resource that has a firm understanding of the business requirements, user perspective and good technical writing skills should be assigned these tasks. Ideally this would be a business analyst if one is available, or perhaps a higher order QA tester with a firm understanding of the requirements, user stories and good technical writing skills. This could also be a developer, however product documentation written by developers tends not to be as high quality or as useful because developers usually are too close to the technical details. |
128,840 | We need to do some user documentation for a product we have been working on for the past few sprints. We are now starting a new project in the next sprint and the PO is making the documentation for the product produced previously a User story for this sprint.
I am just wondering your opinion on this approach. Personally, I don't agree that documentation is a User Story within Scrum because it doesn't produce any code.
EDIT: Thanks for your opinions guys. I had it in the back of my head that a sprint was to implement an increment of working software, but your views have changed my outlook. Thank you for all your answers. | 2012/01/06 | [
"https://softwareengineering.stackexchange.com/questions/128840",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/40251/"
] | Ideally, documentation is part of every user story and never builds up. But, in the real world, that often doesn't happen. In that case, you should create a user story for catching up on a specific missing piece of documentation.
You're right, it doesn't produce any code. But it does satisfy a user requirement and should be prioritised against other user requirements.
If this means that it never gets done, because this and that functionality is being worked on then you probably didn't need the documentation that badly. | In our organization, the tooling team, in charge of our maintaining and enhancing our continuous integration system is using Scrum to help them manage their work. They are not writing code but they are practicing Scrum nonetheless.
To answer your question specifically, I would ask if the team considers that the documentation is part of the "Definition of Done" or not.
If the team considers that the documentation is part of the "definition of done" then, there is no need for an additional story and the story cannot be accepted unless the documentation is written and validated.
If the team considers that the documentation is not part of the "definition of done", I would create a separate story so that the Product Owner can manage their work. |
128,840 | We need to do some user documentation for a product we have been working on for the past few sprints. We are now starting a new project in the next sprint and the PO is making the documentation for the product produced previously a User story for this sprint.
I am just wondering your opinion on this approach. Personally, I don't agree that documentation is a User Story within Scrum because it doesn't produce any code.
EDIT: Thanks for your opinions guys. I had it in the back of my head that a sprint was to implement an increment of working software, but your views have changed my outlook. Thank you for all your answers. | 2012/01/06 | [
"https://softwareengineering.stackexchange.com/questions/128840",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/40251/"
] | "As a user of X, I need to know how X works" seems like a legitimate user story to me. This could result in written documentation or online help.
The point isn't just code--it's meeting the users' requirements. | I agree with pdr's documentation assessment if its about requirement, technical or project documentation. Ideally it should be incorporated into sprint work.
Product documentation I feel is very different as it is an actual user requested deliverable and directly provides value to the user. This should be understood of course that Product Documentation is essentially **not** a Technical Task but a Functional Task, and may or may not be a suitable activity for a technical resource on the project.
I think it should be a user story, however I feel that a project resource that has a firm understanding of the business requirements, user perspective and good technical writing skills should be assigned these tasks. Ideally this would be a business analyst if one is available, or perhaps a higher order QA tester with a firm understanding of the requirements, user stories and good technical writing skills. This could also be a developer, however product documentation written by developers tends not to be as high quality or as useful because developers usually are too close to the technical details. |
128,840 | We need to do some user documentation for a product we have been working on for the past few sprints. We are now starting a new project in the next sprint and the PO is making the documentation for the product produced previously a User story for this sprint.
I am just wondering your opinion on this approach. Personally, I don't agree that documentation is a User Story within Scrum because it doesn't produce any code.
EDIT: Thanks for your opinions guys. I had it in the back of my head that a sprint was to implement an increment of working software, but your views have changed my outlook. Thank you for all your answers. | 2012/01/06 | [
"https://softwareengineering.stackexchange.com/questions/128840",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/40251/"
] | "As a user of X, I need to know how X works" seems like a legitimate user story to me. This could result in written documentation or online help.
The point isn't just code--it's meeting the users' requirements. | In our organization, the tooling team, in charge of our maintaining and enhancing our continuous integration system is using Scrum to help them manage their work. They are not writing code but they are practicing Scrum nonetheless.
To answer your question specifically, I would ask if the team considers that the documentation is part of the "Definition of Done" or not.
If the team considers that the documentation is part of the "definition of done" then, there is no need for an additional story and the story cannot be accepted unless the documentation is written and validated.
If the team considers that the documentation is not part of the "definition of done", I would create a separate story so that the Product Owner can manage their work. |
128,840 | We need to do some user documentation for a product we have been working on for the past few sprints. We are now starting a new project in the next sprint and the PO is making the documentation for the product produced previously a User story for this sprint.
I am just wondering your opinion on this approach. Personally, I don't agree that documentation is a User Story within Scrum because it doesn't produce any code.
EDIT: Thanks for your opinions guys. I had it in the back of my head that a sprint was to implement an increment of working software, but your views have changed my outlook. Thank you for all your answers. | 2012/01/06 | [
"https://softwareengineering.stackexchange.com/questions/128840",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/40251/"
] | I agree with pdr's documentation assessment if its about requirement, technical or project documentation. Ideally it should be incorporated into sprint work.
Product documentation I feel is very different as it is an actual user requested deliverable and directly provides value to the user. This should be understood of course that Product Documentation is essentially **not** a Technical Task but a Functional Task, and may or may not be a suitable activity for a technical resource on the project.
I think it should be a user story, however I feel that a project resource that has a firm understanding of the business requirements, user perspective and good technical writing skills should be assigned these tasks. Ideally this would be a business analyst if one is available, or perhaps a higher order QA tester with a firm understanding of the requirements, user stories and good technical writing skills. This could also be a developer, however product documentation written by developers tends not to be as high quality or as useful because developers usually are too close to the technical details. | In our organization, the tooling team, in charge of our maintaining and enhancing our continuous integration system is using Scrum to help them manage their work. They are not writing code but they are practicing Scrum nonetheless.
To answer your question specifically, I would ask if the team considers that the documentation is part of the "Definition of Done" or not.
If the team considers that the documentation is part of the "definition of done" then, there is no need for an additional story and the story cannot be accepted unless the documentation is written and validated.
If the team considers that the documentation is not part of the "definition of done", I would create a separate story so that the Product Owner can manage their work. |
65,896,559 | I have some items inside of my `LinearLayout` and what I want to do is, arrange the items vertically in a way that it would spread evenly with default margin across the items.
This is what I have now :
[](https://i.stack.imgur.com/SFnCR.png)
So All the FAB's inside of the linear layout doesn't spread evenly, and even if I set a `layout_marginStart` it could cause some problems due to different resolutions across the android models.
```
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:layout_marginTop="25dp"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:elevation="0dp"
app:backgroundTint="@color/gray"
app:elevation="0dp"
android:src="@android:color/transparent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="10sp"
android:text="S"
android:elevation="16dp"
android:textColor="@android:color/white"/>
</FrameLayout>
``` | 2021/01/26 | [
"https://Stackoverflow.com/questions/65896559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10881932/"
] | Try this instead of FrameLayout:
```
<RelativeLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_marginTop="25dp">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:elevation="0dp"
android:src="@android:color/transparent"
app:backgroundTint="@color/gray"
android:layout_centerInParent="true"
app:elevation="0dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:elevation="16dp"
android:text="S"
android:textColor="@android:color/white"
android:textSize="10sp" />
</RelativeLayout>
```
The children of a LinearLayout spread evenly when they have android:layout\_width="0dp" and android:layout\_weight="1" | You can use the `layout_weight="value"` property. So you can set the weight for each FAB so that they can evenly get separated in the layout.
For example if you want three FABs evenly seperate, you can set `layout_weight="1"` for each FAB, then it will seperate evenly. You can also use Decimal Values instead of 1. |
32,501,002 | I'm removing the hash value with `parent.location.hash = ''` but that instantly makes the browser jump to the top of the page - can I just remove the `#!ajax-url-part` from the browser without making it jump to the top of the page?
Thank you. | 2015/09/10 | [
"https://Stackoverflow.com/questions/32501002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2065540/"
] | As OP wants, I put my comment in an answer because is a valid answer:
You can read this blog:
<http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/>
The trick is as easy as this:
```
window.history.pushState(“object or string”, “Title”, “/new-url”);
```
Good luck! | window.location.href.substr(0, window.location.href.indexOf('#'))
or
window.location.href.split('#')[0] |
58,178,874 | I am trying to make a **checkbox** smaller and change the size of border
I have tried playing around with layout in XML and `.width()`or `.height` in Kotlin. Neither does anything to change the size of it. I went to the tutorial that was recommended to others that asked these questions, but I did not understand what he did.
Any suggestions?
**mycheckbox.xml**
```
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
```
```
android:id="@+id/stSafeCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/my_checkbox" />
```
**my\_checkbox.xml**
```
<item
android:state_checked="false"
android:drawable="@drawable/checkbox_off_background"/>
<item
android:state_checked="true"
android:drawable="@drawable/checkbox_on_background"/>
```
**checkbox\_off\_background**
```
<item>
<shape android:shape="rectangle">
<size
android:width="25dp"
android:height="25dp" />
</shape>
</item>
<item android:drawable="@android:drawable/checkbox_off_background" />
```
**checkbox\_on\_background.xml**
```
<item>
<shape android:shape="rectangle">
<size
android:width="25dp"
android:height="25dp" />
</shape>
</item>
<item android:drawable="@android:drawable/checkbox_on_background" />
``` | 2019/10/01 | [
"https://Stackoverflow.com/questions/58178874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12146689/"
] | The `break` only breaks the for-loop but then continues with the code below. You probably just say `return` instead or `System.exit(0);` | You need a boolean flag.
Set the flag to false, when there is any negative number.
Check the flag before checking max number.
```
Scanner sc = new Scanner(System.in);
int a[] = new int[6];
boolean flag = true;
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt(); // To exit loop
if (a[i] < 0) {
System.out.println("Invalid Mark");
flag = false;
break;//return; //System.exit(0); any of these 3 will work fine.
}
}
if (flag) {
int max = a[0];
for (int i = 1; i < a.length; i++) // To find highest
{
if (max < a[i])
max = a[i];
}
System.out.println("Highest Mark is" + max);
}
``` |
58,178,874 | I am trying to make a **checkbox** smaller and change the size of border
I have tried playing around with layout in XML and `.width()`or `.height` in Kotlin. Neither does anything to change the size of it. I went to the tutorial that was recommended to others that asked these questions, but I did not understand what he did.
Any suggestions?
**mycheckbox.xml**
```
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
```
```
android:id="@+id/stSafeCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/my_checkbox" />
```
**my\_checkbox.xml**
```
<item
android:state_checked="false"
android:drawable="@drawable/checkbox_off_background"/>
<item
android:state_checked="true"
android:drawable="@drawable/checkbox_on_background"/>
```
**checkbox\_off\_background**
```
<item>
<shape android:shape="rectangle">
<size
android:width="25dp"
android:height="25dp" />
</shape>
</item>
<item android:drawable="@android:drawable/checkbox_off_background" />
```
**checkbox\_on\_background.xml**
```
<item>
<shape android:shape="rectangle">
<size
android:width="25dp"
android:height="25dp" />
</shape>
</item>
<item android:drawable="@android:drawable/checkbox_on_background" />
``` | 2019/10/01 | [
"https://Stackoverflow.com/questions/58178874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12146689/"
] | This can be simplified a bit, no need to keep an array:
```
public class HighestMark {
private static final int MAX_INPUT = 6; // could just hard-code this in loop, but good practice to set constants
private static final Scanner SCAN = new Scanner(System.in);
public static void main(String[] args) {
int highest = 0;
for (int i = 0; i < MAX_INPUT; i++) {
int next = SCAN.nextInt();
if (next < 0) { // validate the input (require non-negative int)
System.out.println("appropriate error message...");
break;
}
if (next > highest) {
highest = next;
}
}
System.out.println("Highest mark is " + highest);
}
}
``` | You need a boolean flag.
Set the flag to false, when there is any negative number.
Check the flag before checking max number.
```
Scanner sc = new Scanner(System.in);
int a[] = new int[6];
boolean flag = true;
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt(); // To exit loop
if (a[i] < 0) {
System.out.println("Invalid Mark");
flag = false;
break;//return; //System.exit(0); any of these 3 will work fine.
}
}
if (flag) {
int max = a[0];
for (int i = 1; i < a.length; i++) // To find highest
{
if (max < a[i])
max = a[i];
}
System.out.println("Highest Mark is" + max);
}
``` |
68,773,352 | I have an array of 5 divs
```
`<div id="cap-left2"</div>`
`<div id="cap-left1"</div>`
`<div id="cap-base"</div>`
`<div id="cap-right1"></div>`
`<div id="cap-right2"</div>`
```
all these divs have a background .
In my javascript I have :
```
let items = [capBase,capLeft1,capLeft2,capRight1,capRight2];
```
this works :
```
`var tom = items[Math.floor(Math.random()*items.length)]
console.log(tom)`
```
and this works
```
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style)`
```
but I want the backgroundColor and neither of these work:
```
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style.background)`
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style.backgroundColor)`
```
what I am trying to do is lets say i have 5 swatches represented by 5 elements in an array . i want to be able to have a button that allows me to randomize what colors fill each element
any help would be appreciated | 2021/08/13 | [
"https://Stackoverflow.com/questions/68773352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16028691/"
] | Java has random number generator support via the `java.util.Random` class. This class 'works' by having a seed value, then giving you some random data based on this seed value, which then updates the seed value to something new.
This pragmatically means:
* 2 instances of j.u.Random with the same seed value will produce the same sequence of values if you invoke the same sequence of calls on it to give you random data.
* But, seed values are of type `long` - 64 bits worth of data.
* Thus, to do what you want, you need to write an algorithm that turns any String into a `long`.
* Given that long, you simply make an instance of `j.u.Random` with that long as seed, using the [`new Random(seedValue)`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#Random-long-) constructor.
So that just leaves: How do I turn a string into a long?
Easy way
--------
The simplest answer is to invoke `hashCode()` on them. But, note, hashcodes only have 32 bits of info (they are `int`, not `long`), so this doesn't cover all possible seed values. This is unlikely to matter unless you're doing this for crypto purposes. If you ARE, then you need to stop what you are doing and do a lot more research, because it is extremely easy to mess up and have working code that seems to test fine, but which is easy to hack. You don't want that. For starters, you'd want `SecureRandom` instead, but that's just the tip of the iceberg.
Harder way
----------
Hashing algorithms exist that turn arbitrary data into fixed size hash representations. The hashCode algorithm of string [A] only makes 32-bits worth of hash, and [B] is not cryptographically secure: If you task me to make a string that hashes to a provided value I can trivially do so; a cryptographically secure hash has the property that I can't just cook you up a string that hashes to a desired value.
You can search the web for hashing strings or byte arrays (you can turn a string into one with `str.getBytes(StandardCharsets.UTF_8)`).
You can 'collapse' a byte array containing a hash into a long also quite easily - just take any 8 bytes in that hash and use them to construct a long. "Turn 8 bytes into a long" also has tons of tutorials if you search the web for it.
I assume the easy way is good enough for this exercise, however.
Thus:
-----
```
String key = ...;
Random rnd = new Random(key.hashCode());
int number1 = rnd.nextInt(10) + 1;
int number2 = rnd.nextInt(10) + 1;
System.out.println("First number: " + number1);
System.out.println("Second number: " + number2);
``` | You could get the hashcode of the string, then use that to seed a random number generator. Use the RNG to get numbers in the range 1 - 10. |
14,686,001 | I have some text files in a directory. I would like to read all the files in this directory and if the file has the following line
`SAMPLE 350 AN INTEGER OF TYPE :DECIMAL : CAN BE ASSEMBLED BY` move that file with its all contents to another directory.
How can I do this? | 2013/02/04 | [
"https://Stackoverflow.com/questions/14686001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2039457/"
] | Using `find` and `grep`:
```
$ find . -type f -exec \
fgrep -l "SAMPLE 350 AN INTEGER OF TYPE :DECIMAL : CAN BE ASSEMBLED BY" {} \; \
| xargs -i% mv % /path/to/new/dir
``` | This is easy in bash:
```
grep -l "PATTERN" *
```
gives you a list of files that contains PATTERN in current directory. So unless you have too many files you could do:
```
mv `grep -l "SAMPLE 350 AN INTEGER OF TYPE :DECIMAL : CAN BE ASSEMBLED BY"` /another/directory
```
The back ticks (they are no normal quotes) executes the command and replaces it with the output (in this case with the list of files). Instead of the back ticks you can use $(command). So you can just as well write:
```
mv $(grep -l "SAMPLE 350 AN INTEGER OF TYPE :DECIMAL : CAN BE ASSEMBLED BY") /another/directory
```
If you have alot of files, bash might not be able to expand that many files (you will reach the limit of how big your command will be...it is alot). You must then resort to xargs:
```
grep -l "SAMPLE 350 AN INTEGER OF TYPE :DECIMAL : CAN BE ASSEMBLED BY" | xargs -i mv {} /another/directory
```
The -i to xargs means that it will take one line at a time from the output from grep (a matching filename) and where the {} are will be expanded to that text and the command will run. |
14,686,001 | I have some text files in a directory. I would like to read all the files in this directory and if the file has the following line
`SAMPLE 350 AN INTEGER OF TYPE :DECIMAL : CAN BE ASSEMBLED BY` move that file with its all contents to another directory.
How can I do this? | 2013/02/04 | [
"https://Stackoverflow.com/questions/14686001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2039457/"
] | Using `find` and `grep`:
```
$ find . -type f -exec \
fgrep -l "SAMPLE 350 AN INTEGER OF TYPE :DECIMAL : CAN BE ASSEMBLED BY" {} \; \
| xargs -i% mv % /path/to/new/dir
``` | Here is a solution in python. The os.path.isdir() was necessary to bypass subdirectories. The "and file[-3:] != '.py'" is needed if running this .py script from the source directory. Alternately you could just check for the name of the script if you need to move .py files.
```
import os
import shutil
src = '/source'
dst = '/destination'
pattern = 'SAMPLE 350 AN INTEGER OF TYPE :DECIMAL : CAN BE ASSEMBLED BY'
for file in os.listdir(src):
if not os.path.isdir(file):
f = open(file)
for line in f:
if pattern in line and file[-3:] != '.py':
f.close()
shutil.move(file,dst)
break
f.close()
``` |
21,910,653 | So i made test code:
```
$fopen = fopen('./mydata.csv',"r");
$data = fgetcsv($fopen, 1000, ",");
fclose($fopen);
$fp = fopen('mynewdata.csv','a');
fputcsv($fp,$data,',');
fclose($fp);
```
Content of mydata.csv file:
>
> string "some thing", sec string,next string
>
>
>
New content of mynewdata.csv file:
>
> "string ""some thing"""," sec string","next string"
>
>
>
My question is: Where this ' " ' comes from. What i do wrong that my output is different than input.
Few more obserwations:
When i do test like, with enclosure: '' -> empty string:
```
$data = fgetcsv($fopen, 1000,',','');
print_r($data);
```
It print's nothing insted of array with 2 rows, and that's the error i got from logs:
" FastCGI sent in stderr: "PHP message: PHP Warning: fgetcsv(): enclosure must be a **character**" So what would be the other option to give as the enclosure an empty string. | 2014/02/20 | [
"https://Stackoverflow.com/questions/21910653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1847939/"
] | As you can see by the [`fputcsv` documentation](http://dk1.php.net/fputcsv):
>
> int fputcsv ( resource $handle , array $fields [, string $delimiter = ',' [, string $enclosure = '"' ]] )
>
>
>
The last parameter is the enclosure. Since you haven't defined yours, it defaults to `"`, and then it has to escape your quote by placing a double quote.
To get rid of this, simply specify an empty string:
```
$fopen = fopen('./mydata.csv',"r");
$data = fgetcsv($fopen, 1000, ",");
fclose($fopen);
$fp = fopen('mynewdata.csv','a');
fputcsv($fp,$data,',','');
// ^^
fclose($fp);
```
But *why* does it do this by default?!
--------------------------------------
To avoid errors if you have commas in your strings. Imagine the following:
```
$data = array('my string', 'is a great string', 'and it is, very nice');
```
With an enclosure it would result in the following:
```
"my string","is a great string","and it is, very nice"
```
*Without* an enclosure, it would result in the following:
```
my string,is a great string,and it is, very nice
```
Which would be misinterpreted as 4 values instead of 3. | Thank you guys for your replay. But the answer is different. I step on php bug:
<https://bugs.php.net/bug.php?id=51496>
If some of you guy's out there know the solution, please write it.
My php version 5.4.6.
Edit.
So to get rid of that problem insted of function fgetcsv and fputcsv i did way around:
```
$handle = fopen('./mydata.csv','r');
$data = fgets($handle);
$data = str_replace(', ','@!#$',$data);
$data = explode(',',$data);
$data = str_replace('@!#$',', ',$data);
$fp = fopen('mynewdata.csv','a');
$data = implode($data,',');
fwrite($fp, $data."\n");
fclose($fp);
fclose($handle);
```
The other solution. Insted of str\_replace, explode, str\_replace you can do:
```
$handle = fopen('./mydata.csv','r');
$data = fgets($handle);
$data = explode('","', preg_replace('/([^ ]),([^ ])/', '$1","$2', $data));
fclose($handle);
...
``` |
4,912,154 | I have two models:
User
```
has_one :email
```
Email
```
belongs_to :user
```
I put the email\_id foreign key (NOT NULL) inside users table.
Now I'm trying to save it in the following way:
```
@email = Email.new(params[:email])
@email.user = User.new(params[:user])
@email.save
```
This raises a db exception, because the foreign key constraint is not met (NULL is inserted into email\_id). How can I elegantly solve this or is my data modeling wrong? | 2011/02/06 | [
"https://Stackoverflow.com/questions/4912154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130111/"
] | Yes, but only by invoking it:
```
Func<object> func = delegate { return a; };
// or Func<object> func = () => a;
object b = func();
```
And of course, the following is a lot simpler...
```
object b = a;
```
---
In the comments, cross-thread exceptions are mentioned; this can be fixed as follows:
If the delegate is the thing we want to run back on the UI thread *from* a BG thread:
```
object o = null;
MethodInvoker mi = delegate {
o = someControl.Value; // runs on UI
};
someControl.Invoke(mi);
// now read o
```
Or the other way around (to run the delegate on a BG):
```
object value = someControl.Value;
ThreadPool.QueueUserWorkItem(delegate {
// can talk safely to "value", but not to someControl
});
``` | Just declare somewhere these static functions:
```
public delegate object AnonymousDelegate();
public static object GetDelegateResult(AnonymousDelegate function)
{
return function.Invoke();
}
```
And anywhere use it as you want like this:
```
object item = GetDelegateResult(delegate { return "TEST"; });
```
or even like this
```
object item = ((AnonymousDelegate)delegate { return "TEST"; }).Invoke();
``` |
4,912,154 | I have two models:
User
```
has_one :email
```
Email
```
belongs_to :user
```
I put the email\_id foreign key (NOT NULL) inside users table.
Now I'm trying to save it in the following way:
```
@email = Email.new(params[:email])
@email.user = User.new(params[:user])
@email.save
```
This raises a db exception, because the foreign key constraint is not met (NULL is inserted into email\_id). How can I elegantly solve this or is my data modeling wrong? | 2011/02/06 | [
"https://Stackoverflow.com/questions/4912154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130111/"
] | Yes, but only by invoking it:
```
Func<object> func = delegate { return a; };
// or Func<object> func = () => a;
object b = func();
```
And of course, the following is a lot simpler...
```
object b = a;
```
---
In the comments, cross-thread exceptions are mentioned; this can be fixed as follows:
If the delegate is the thing we want to run back on the UI thread *from* a BG thread:
```
object o = null;
MethodInvoker mi = delegate {
o = someControl.Value; // runs on UI
};
someControl.Invoke(mi);
// now read o
```
Or the other way around (to run the delegate on a BG):
```
object value = someControl.Value;
ThreadPool.QueueUserWorkItem(delegate {
// can talk safely to "value", but not to someControl
});
``` | ```
using System;
public delegate int ReturnedDelegate(string s);
class AnonymousDelegate
{
static void Main()
{
ReturnedDelegate len = delegate(string s)
{
return s.Length;
};
Console.WriteLine(len("hello world"));
}
}
``` |
4,912,154 | I have two models:
User
```
has_one :email
```
Email
```
belongs_to :user
```
I put the email\_id foreign key (NOT NULL) inside users table.
Now I'm trying to save it in the following way:
```
@email = Email.new(params[:email])
@email.user = User.new(params[:user])
@email.save
```
This raises a db exception, because the foreign key constraint is not met (NULL is inserted into email\_id). How can I elegantly solve this or is my data modeling wrong? | 2011/02/06 | [
"https://Stackoverflow.com/questions/4912154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130111/"
] | Just declare somewhere these static functions:
```
public delegate object AnonymousDelegate();
public static object GetDelegateResult(AnonymousDelegate function)
{
return function.Invoke();
}
```
And anywhere use it as you want like this:
```
object item = GetDelegateResult(delegate { return "TEST"; });
```
or even like this
```
object item = ((AnonymousDelegate)delegate { return "TEST"; }).Invoke();
``` | ```
using System;
public delegate int ReturnedDelegate(string s);
class AnonymousDelegate
{
static void Main()
{
ReturnedDelegate len = delegate(string s)
{
return s.Length;
};
Console.WriteLine(len("hello world"));
}
}
``` |
29,308,901 | So i have `.cont` that's centered in using position absolute and is height 80% of body.
Inside it there are two divs. One is fixed height. And other one needs to expand to rest of parent, `.cont`.
So How do i make it expand to parent.
One other requirement is that content in both of these needs to be vertically and horizontally centered.
```
body
.cont
.top
.fillRest
```
Here is jsfiddle: <http://jsfiddle.net/24jocwu5/>
1. make .fillRest Expand to rest of .cont.
2. vertically and Horizontally center h1 headings in both divs.
Don't Use calc()
can use display table, flow, position, and other tricks.
 | 2015/03/27 | [
"https://Stackoverflow.com/questions/29308901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319799/"
] | Here you go. Absolutely position the white container with a top-padding that equals the height of your fixed-height top div. Then give the top div a z-index so it goes over your white box:
Fiddle - <http://jsfiddle.net/24jocwu5/2/>
```
* {margin: 0; padding: 0;}
html, body {
height: 100%;
background-color: #3dd;
color: #aaa;
font-family: helvetica;
}
.cont {
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
background-color: #1af;
width: 400px;
margin: auto;
height: 80%;
}
.top {
height: 100px;
background-color: pink;
position: relative;
z-index: 1;
}
.fillRest {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding-top: 100px;
height: 100%;
background-color: #fff;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
h1 {
text-align: center;
width: 200px;
margin: auto;
background-color: #eee;
}
``` | This is what you want?
Only position fixed and right and left 0
<http://jsfiddle.net/pabliiitoo/24jocwu5/1/>
```
.fillRest {
position: fixed;
left: 0;
right: 0;
background-color: red;
min-height: 80px;
}
``` |
29,308,901 | So i have `.cont` that's centered in using position absolute and is height 80% of body.
Inside it there are two divs. One is fixed height. And other one needs to expand to rest of parent, `.cont`.
So How do i make it expand to parent.
One other requirement is that content in both of these needs to be vertically and horizontally centered.
```
body
.cont
.top
.fillRest
```
Here is jsfiddle: <http://jsfiddle.net/24jocwu5/>
1. make .fillRest Expand to rest of .cont.
2. vertically and Horizontally center h1 headings in both divs.
Don't Use calc()
can use display table, flow, position, and other tricks.
 | 2015/03/27 | [
"https://Stackoverflow.com/questions/29308901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319799/"
] | You can use flexbox for this
```
.cont {
display: flex;
flex-direction: column;
}
.cont > div {
display: flex;
}
.fillRest {
flex: 1;
}
```
[**Working Fiddle**](http://jsfiddle.net/z24x0rvo/) | This is what you want?
Only position fixed and right and left 0
<http://jsfiddle.net/pabliiitoo/24jocwu5/1/>
```
.fillRest {
position: fixed;
left: 0;
right: 0;
background-color: red;
min-height: 80px;
}
``` |
29,308,901 | So i have `.cont` that's centered in using position absolute and is height 80% of body.
Inside it there are two divs. One is fixed height. And other one needs to expand to rest of parent, `.cont`.
So How do i make it expand to parent.
One other requirement is that content in both of these needs to be vertically and horizontally centered.
```
body
.cont
.top
.fillRest
```
Here is jsfiddle: <http://jsfiddle.net/24jocwu5/>
1. make .fillRest Expand to rest of .cont.
2. vertically and Horizontally center h1 headings in both divs.
Don't Use calc()
can use display table, flow, position, and other tricks.
 | 2015/03/27 | [
"https://Stackoverflow.com/questions/29308901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319799/"
] | Here you go. Absolutely position the white container with a top-padding that equals the height of your fixed-height top div. Then give the top div a z-index so it goes over your white box:
Fiddle - <http://jsfiddle.net/24jocwu5/2/>
```
* {margin: 0; padding: 0;}
html, body {
height: 100%;
background-color: #3dd;
color: #aaa;
font-family: helvetica;
}
.cont {
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
background-color: #1af;
width: 400px;
margin: auto;
height: 80%;
}
.top {
height: 100px;
background-color: pink;
position: relative;
z-index: 1;
}
.fillRest {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding-top: 100px;
height: 100%;
background-color: #fff;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
h1 {
text-align: center;
width: 200px;
margin: auto;
background-color: #eee;
}
``` | In order to expand the .fillRest to the rest of its parent .cont, you need to set it's height to a percentage. I estimate about 20~30% is what you want in order to maintain a similar look to the image you've provided here.
To test it, grab a very large paragraph full of letters and anything you want and put it where the 'Content' text is, that way you will be able to see it expanding in a responsive way. Another suggestion I will give you is to make your width percentages as well, so that they expand according to the width of the screen responsively.
Let me know if this helped you, otherwise I can take another look :)
CSS
```
.cont {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
background-color: #1af;
width: 400px;
margin: auto;
height: 80%;
}
``` |
29,308,901 | So i have `.cont` that's centered in using position absolute and is height 80% of body.
Inside it there are two divs. One is fixed height. And other one needs to expand to rest of parent, `.cont`.
So How do i make it expand to parent.
One other requirement is that content in both of these needs to be vertically and horizontally centered.
```
body
.cont
.top
.fillRest
```
Here is jsfiddle: <http://jsfiddle.net/24jocwu5/>
1. make .fillRest Expand to rest of .cont.
2. vertically and Horizontally center h1 headings in both divs.
Don't Use calc()
can use display table, flow, position, and other tricks.
 | 2015/03/27 | [
"https://Stackoverflow.com/questions/29308901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319799/"
] | You can use flexbox for this
```
.cont {
display: flex;
flex-direction: column;
}
.cont > div {
display: flex;
}
.fillRest {
flex: 1;
}
```
[**Working Fiddle**](http://jsfiddle.net/z24x0rvo/) | In order to expand the .fillRest to the rest of its parent .cont, you need to set it's height to a percentage. I estimate about 20~30% is what you want in order to maintain a similar look to the image you've provided here.
To test it, grab a very large paragraph full of letters and anything you want and put it where the 'Content' text is, that way you will be able to see it expanding in a responsive way. Another suggestion I will give you is to make your width percentages as well, so that they expand according to the width of the screen responsively.
Let me know if this helped you, otherwise I can take another look :)
CSS
```
.cont {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
background-color: #1af;
width: 400px;
margin: auto;
height: 80%;
}
``` |
29,308,901 | So i have `.cont` that's centered in using position absolute and is height 80% of body.
Inside it there are two divs. One is fixed height. And other one needs to expand to rest of parent, `.cont`.
So How do i make it expand to parent.
One other requirement is that content in both of these needs to be vertically and horizontally centered.
```
body
.cont
.top
.fillRest
```
Here is jsfiddle: <http://jsfiddle.net/24jocwu5/>
1. make .fillRest Expand to rest of .cont.
2. vertically and Horizontally center h1 headings in both divs.
Don't Use calc()
can use display table, flow, position, and other tricks.
 | 2015/03/27 | [
"https://Stackoverflow.com/questions/29308901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319799/"
] | Here you go. Absolutely position the white container with a top-padding that equals the height of your fixed-height top div. Then give the top div a z-index so it goes over your white box:
Fiddle - <http://jsfiddle.net/24jocwu5/2/>
```
* {margin: 0; padding: 0;}
html, body {
height: 100%;
background-color: #3dd;
color: #aaa;
font-family: helvetica;
}
.cont {
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
background-color: #1af;
width: 400px;
margin: auto;
height: 80%;
}
.top {
height: 100px;
background-color: pink;
position: relative;
z-index: 1;
}
.fillRest {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding-top: 100px;
height: 100%;
background-color: #fff;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
h1 {
text-align: center;
width: 200px;
margin: auto;
background-color: #eee;
}
``` | Personally, I think the way you're going about this is all wrong. But maybe something like this would work.
<http://jsfiddle.net/24jocwu5/5/>
CSS selectors I changed:
```
.cont {
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
background-color: #1af;
width: 400px;
margin: 10% auto;
overflow: hidden;
}
.top {
height: 20%;
background-color: rgba(255,255,255,.8);
}
.fillRest {
background-color: white;
position: relative;
width: 100%;
height: 80%;
}
h1 {
text-align: center;
width: 100%;
margin: auto;
background-color: #eee;
}
``` |
29,308,901 | So i have `.cont` that's centered in using position absolute and is height 80% of body.
Inside it there are two divs. One is fixed height. And other one needs to expand to rest of parent, `.cont`.
So How do i make it expand to parent.
One other requirement is that content in both of these needs to be vertically and horizontally centered.
```
body
.cont
.top
.fillRest
```
Here is jsfiddle: <http://jsfiddle.net/24jocwu5/>
1. make .fillRest Expand to rest of .cont.
2. vertically and Horizontally center h1 headings in both divs.
Don't Use calc()
can use display table, flow, position, and other tricks.
 | 2015/03/27 | [
"https://Stackoverflow.com/questions/29308901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319799/"
] | Here you go. Absolutely position the white container with a top-padding that equals the height of your fixed-height top div. Then give the top div a z-index so it goes over your white box:
Fiddle - <http://jsfiddle.net/24jocwu5/2/>
```
* {margin: 0; padding: 0;}
html, body {
height: 100%;
background-color: #3dd;
color: #aaa;
font-family: helvetica;
}
.cont {
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
background-color: #1af;
width: 400px;
margin: auto;
height: 80%;
}
.top {
height: 100px;
background-color: pink;
position: relative;
z-index: 1;
}
.fillRest {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding-top: 100px;
height: 100%;
background-color: #fff;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
h1 {
text-align: center;
width: 200px;
margin: auto;
background-color: #eee;
}
``` | This is Summary Of Ways.. First two ways posted here--
1. [FlexBox Method](https://stackoverflow.com/questions/29308901/how-do-i-get-last-div-to-expand-parents-height/29309253#29309253) 100% WORKS
2. [Padding Method](https://stackoverflow.com/questions/29308901/how-do-i-get-last-div-to-expand-parents-height/29309196#29309196) 80% WORKS. Useful But not exactly.
3. Css Table Cell and Table Rows 100% WORKS. From Me.
4. Using Calcs Simplest One. 100% WORKS. From me.
**Css Table Cell**: <http://jsfiddle.net/24jocwu5/7/>
***.cont*** is The Table. **top & fillRest** are table rows, and there is **cell** which can have vertical align middle.
**Calc Method**: <http://jsfiddle.net/24jocwu5/9/>
*Works but doesn't scale well if content increases, so need to use another div which can contain the content. Like so <http://jsfiddle.net/24jocwu5/10/>*
**Default code:**
```
* {margin: 0; padding: 0; }
html, body {
height: 100%;
background-color: #3dd;
color: #aaa;
font-family: helvetica;
}
.cont {
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
background-color: #1af;
width: 400px;
margin: auto;
height: 80%;
}
``` |
29,308,901 | So i have `.cont` that's centered in using position absolute and is height 80% of body.
Inside it there are two divs. One is fixed height. And other one needs to expand to rest of parent, `.cont`.
So How do i make it expand to parent.
One other requirement is that content in both of these needs to be vertically and horizontally centered.
```
body
.cont
.top
.fillRest
```
Here is jsfiddle: <http://jsfiddle.net/24jocwu5/>
1. make .fillRest Expand to rest of .cont.
2. vertically and Horizontally center h1 headings in both divs.
Don't Use calc()
can use display table, flow, position, and other tricks.
 | 2015/03/27 | [
"https://Stackoverflow.com/questions/29308901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319799/"
] | You can use flexbox for this
```
.cont {
display: flex;
flex-direction: column;
}
.cont > div {
display: flex;
}
.fillRest {
flex: 1;
}
```
[**Working Fiddle**](http://jsfiddle.net/z24x0rvo/) | Personally, I think the way you're going about this is all wrong. But maybe something like this would work.
<http://jsfiddle.net/24jocwu5/5/>
CSS selectors I changed:
```
.cont {
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
background-color: #1af;
width: 400px;
margin: 10% auto;
overflow: hidden;
}
.top {
height: 20%;
background-color: rgba(255,255,255,.8);
}
.fillRest {
background-color: white;
position: relative;
width: 100%;
height: 80%;
}
h1 {
text-align: center;
width: 100%;
margin: auto;
background-color: #eee;
}
``` |
29,308,901 | So i have `.cont` that's centered in using position absolute and is height 80% of body.
Inside it there are two divs. One is fixed height. And other one needs to expand to rest of parent, `.cont`.
So How do i make it expand to parent.
One other requirement is that content in both of these needs to be vertically and horizontally centered.
```
body
.cont
.top
.fillRest
```
Here is jsfiddle: <http://jsfiddle.net/24jocwu5/>
1. make .fillRest Expand to rest of .cont.
2. vertically and Horizontally center h1 headings in both divs.
Don't Use calc()
can use display table, flow, position, and other tricks.
 | 2015/03/27 | [
"https://Stackoverflow.com/questions/29308901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319799/"
] | You can use flexbox for this
```
.cont {
display: flex;
flex-direction: column;
}
.cont > div {
display: flex;
}
.fillRest {
flex: 1;
}
```
[**Working Fiddle**](http://jsfiddle.net/z24x0rvo/) | This is Summary Of Ways.. First two ways posted here--
1. [FlexBox Method](https://stackoverflow.com/questions/29308901/how-do-i-get-last-div-to-expand-parents-height/29309253#29309253) 100% WORKS
2. [Padding Method](https://stackoverflow.com/questions/29308901/how-do-i-get-last-div-to-expand-parents-height/29309196#29309196) 80% WORKS. Useful But not exactly.
3. Css Table Cell and Table Rows 100% WORKS. From Me.
4. Using Calcs Simplest One. 100% WORKS. From me.
**Css Table Cell**: <http://jsfiddle.net/24jocwu5/7/>
***.cont*** is The Table. **top & fillRest** are table rows, and there is **cell** which can have vertical align middle.
**Calc Method**: <http://jsfiddle.net/24jocwu5/9/>
*Works but doesn't scale well if content increases, so need to use another div which can contain the content. Like so <http://jsfiddle.net/24jocwu5/10/>*
**Default code:**
```
* {margin: 0; padding: 0; }
html, body {
height: 100%;
background-color: #3dd;
color: #aaa;
font-family: helvetica;
}
.cont {
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
background-color: #1af;
width: 400px;
margin: auto;
height: 80%;
}
``` |
46,316 | Pleasures for us is pain & suffering for the animals which are slaughtered. When we are causing suffering & pain to others, we lose moral rights to expect not the same ever happened to us. In case of animal slaughtering, do we also lose the moral rights to mourn if our beloved ones are killed the same way which we, being non Vegetarian, kill other creatures? In other words, Don't we have moral rights to take it as injustice to ourselves if our beloved ones are killed, being Non Vegetarian?
**EDIT**: Seems I am unable to express myself clearly, I would like to ask the same question in other words: Do non-vegetarians lose rights to ask GOD if their beloved ones are killed, presuming GOD doesn't want us to kill any creature intentionally for sensual pleasures. (Seems obvious if god is Benevolent & Equal to all the creatures.)? | 2017/10/01 | [
"https://philosophy.stackexchange.com/questions/46316",
"https://philosophy.stackexchange.com",
"https://philosophy.stackexchange.com/users/23084/"
] | >
> *moral rights*
>
>
>
"Rights" aren't a moral or ethical category. They are a juridical category.
>
> *to mourn*
>
>
>
To "mourn", on the other hand, is psychological, not moral or juridical, phenomenon.
So, the "moral right to mourn" is a conflation of disparate concepts, which becomes meaningless at all three - juridical, moral, psychological - levels.
Juridically, there is nothing that can be done to prevent people from mourning. If they think that the defeat of their preferred soccer team is something to mourn, more than the death of thousands of people in a war on the other side of the planet, there is nothing to be done about. What would we do? Jail them? Tell them they are going to hell? Dose them some chemical that will make them unable to mourn?
Morally, you can condemn whatever you want. It doesn't affect the rights of others. You may think that those who see too much television lose their moral grounds to complain about the moral decadence of society, for television is hugely responsible for such decadence. They will still watch TV and complain about the decaying mores of the commonwealth. Both things are, and should be, legal rights; a society in which either or both were forbidden would be horrible to live in.
Psychologically, there is nothing that can be done about mourning or not mourning. One may think that I should mourn the extinction of the pox virus; but the fact is that if I am not, for any reason, psychologically attached to such virus, I won't mourn its extinction, and may be indifferent or happy about it. It's possible, I guess, to shame people into pretending that they are unhappy about a given event, but it is not possible to make them unhappy if they are not.
And this - shaming people - is what this idea is probably about. It is not that we should not mourn the passing of our grandmother just because we just ate a barbecue; it is that we should not have eaten the barbecue, for we should think of the poor cow as we think of our grandmother. But as some of the comments above pointed out, the vast majority of human beings do not think a cow is equivalent to a human being, and consequently won't be able to act as if it was.
---
Evidently, the idea of an all-encompassing equivalence among all living beings is pragmatically unsustainable. All human beings, vegetarians and animal-rights activists included, are "especiesist" - they do not think killing a vegetal is the same as killing an animal, they do not think killing an insect - or any invertebrate - is the same as killing a mammal, they rarely think that amphibians, fish, or lizards, are on the same standing as birds and mammals, and more often than not discriminate among mammals - who does empathise with a bat or a hyaena as much as with a panda, for instance?
---
Talking about empathy, it is often repeated that a psychopath is someone who is devoid of empathy. But empathy is a complicated thing; as someone else put it, if you break your leg, do you want a physician who painfully pulls it into the right position, or a physician who hugs you and cries together? "Empathy" can be paralising in this sence. If no empathy makes one a psychopath, unqualified empathy may turn one *hysteric*.
Most of us are by far more empathetic towards our own relatives, friends, neighbours, etc, than towards people we do not know and live far away. And the idea that you should not mourn your grandmother because you didn't properly mourn the victims of a hurricane in Texas or an earthquake in Mexico is somewhat disturbing - at some point, all-encompassing empathy veers dangerously in the direction of no empathy at all. | Sea urchins can kill off kelp forest if left unchecked. It was meat-eating sea otters who restored the forests, where other critters can have a place to live.
Goats are capable of turning grasslands into deserts. It was meat-eating wolfs who checked the goats' number and kept alive the grassland, where other critters can live.
When the Mongols were strong, farmers could not ravage the earth.
There is nothing inherently morally superior in a vegetarian, and experience does not support this connection either. India, for example, probably has [the worst environmental record](https://www.google.com/search?q=cry%20of%20a%20river&hs=8Uk&channel=fs&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiOs9PEntLWAhVRziYKHUGjD_oQ_AUICygC&biw=1547&bih=855) of the whole world despite being mostly vegetarian. |
3,565 | This comes from one of my favorite interview questions, though apparently it is now a fairly well-known puzzle. I have no way of knowing, but if you have already heard the answer it would be polite to let others try instead.
### Task:
Write a function that takes as input a singly-linked list and returns true if it loops back on itself, and false if it terminates somewhere.
Here's some example code in C as a starting point so you can see what I mean, but feel free to write your answer in whatever language you like:
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *first)
{
/* write your own loop detection here */
}
```
### Hints:
There is a way to make this function run in O(n) time with a constant amount of extra memory. Good on you if you figure it out, but any working answer deserves some upvotes in my book. | 2011/08/26 | [
"https://codegolf.stackexchange.com/questions/3565",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/2360/"
] | C, non-golfed
-------------
The idea is to have to pointers p1 and p2 that traverse the list. p2 moves twice as fast as p1. If p2 reaches p1 at some point then there is a loop. Here is the C code (not tested, though).
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *p)
{
struct node *p1 = p, *p2 = p->next;
if (!p2) return 0;
while (p1 != p2) {
// p1 goes one step
p1 = p1->next;
if (!p1) return 0;
// p2 goes two steps
p2 = p2->next;
if (!p2) return 0;
p2 = p2->next;
if (!p2) return 0;
}
return 1;
}
``` | Ada
---
The "Floyd's Cycle-Finding Algorithm" is the best solution. It's also called "The Tortoise and the Hare Algorithm".
linked\_lists.ads:
```
generic
type Element_Type is private;
package Linked_Lists is
type Node is private;
type List is private;
function Has_Loops (L : List) return Boolean;
private
type List is access Node;
type Node is record
Value : Element_Type;
Next : List;
end record;
end Linked_Lists;
```
linked\_lists.adb:
```
package body Linked_Lists is
function Has_Loops (L : List) return Boolean is
Slow_Iterator : List := L;
Fast_Iterator : List := null;
begin
-- if list has a second element, set fast iterator start point
if L.Next /= null then
Fast_Iterator := L.Next;
end if;
while Fast_Iterator /= null loop
-- move slow iterator one step
-- guaranteed to be /= null, since it is behind fast iterator
Slow_Iterator := Slow_Iterator.Next;
-- move fast iterator one step
-- guaranteed to be valid, since while catches null
Fast_Iterator := Fast_Iterator.Next;
-- move fast iterator another step
-- null check necessary
if Fast_Iterator /= null then
Fast_Iterator := Fast_Iterator.Next;
end if;
-- if fast iterator arrived at slow iterator -> loop detected
if Fast_Iterator = Slow_Iterator then
return True;
end if;
end loop;
-- fast iterator arrived end, no loop present.
return False;
end Has_Loops;
end Linked_Lists;
```
here is the implementation of the Brent algorithm:
```
package body Linked_Lists is
function Has_Loops (L : List) return Boolean is
Turtle : List := L;
Rabbit : List := L;
Steps : Natural := 0;
Limit : Positive := 2;
begin
-- is rabbit at end?
while Rabbit /= null loop
-- increment rabbit
Rabbit := Rabbit.Next;
-- increment step counter
Steps := Steps + 1;
-- did rabbit meet turtle?
if Turtle = Rabbit then
-- LOOP!
return True;
end if;
-- is it time to move turtle?
if Steps = Limit then
Steps := 0;
Limit := Limit * 2;
-- teleport the turtle
Turtle := Rabbit;
end if;
end loop;
-- rabbit has reached the end
return False;
end Has_Loops;
end Linked_Lists;
``` |
3,565 | This comes from one of my favorite interview questions, though apparently it is now a fairly well-known puzzle. I have no way of knowing, but if you have already heard the answer it would be polite to let others try instead.
### Task:
Write a function that takes as input a singly-linked list and returns true if it loops back on itself, and false if it terminates somewhere.
Here's some example code in C as a starting point so you can see what I mean, but feel free to write your answer in whatever language you like:
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *first)
{
/* write your own loop detection here */
}
```
### Hints:
There is a way to make this function run in O(n) time with a constant amount of extra memory. Good on you if you figure it out, but any working answer deserves some upvotes in my book. | 2011/08/26 | [
"https://codegolf.stackexchange.com/questions/3565",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/2360/"
] | C, non-golfed
-------------
The idea is to have to pointers p1 and p2 that traverse the list. p2 moves twice as fast as p1. If p2 reaches p1 at some point then there is a loop. Here is the C code (not tested, though).
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *p)
{
struct node *p1 = p, *p2 = p->next;
if (!p2) return 0;
while (p1 != p2) {
// p1 goes one step
p1 = p1->next;
if (!p1) return 0;
// p2 goes two steps
p2 = p2->next;
if (!p2) return 0;
p2 = p2->next;
if (!p2) return 0;
}
return 1;
}
``` | Since the solution is already in the open, I think it's fair to step in now with Brent's algorithm, which is the one I'm familiar with from integer factorisation.
```
#define bool int
#define false 0
#define true 1
bool has_loops(struct node *first) {
if (!first) return false;
struct node *a = first, *b = first;
int step = 1;
while (true) {
for (int i = 0; i < step; i++) {
b = b->next;
if (!b) return false;
if (a == b) return true;
}
a = a->next;
if ((step << 1) > 0) step <<= 1;
}
}
``` |
3,565 | This comes from one of my favorite interview questions, though apparently it is now a fairly well-known puzzle. I have no way of knowing, but if you have already heard the answer it would be polite to let others try instead.
### Task:
Write a function that takes as input a singly-linked list and returns true if it loops back on itself, and false if it terminates somewhere.
Here's some example code in C as a starting point so you can see what I mean, but feel free to write your answer in whatever language you like:
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *first)
{
/* write your own loop detection here */
}
```
### Hints:
There is a way to make this function run in O(n) time with a constant amount of extra memory. Good on you if you figure it out, but any working answer deserves some upvotes in my book. | 2011/08/26 | [
"https://codegolf.stackexchange.com/questions/3565",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/2360/"
] | C, non-golfed
-------------
The idea is to have to pointers p1 and p2 that traverse the list. p2 moves twice as fast as p1. If p2 reaches p1 at some point then there is a loop. Here is the C code (not tested, though).
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *p)
{
struct node *p1 = p, *p2 = p->next;
if (!p2) return 0;
while (p1 != p2) {
// p1 goes one step
p1 = p1->next;
if (!p1) return 0;
// p2 goes two steps
p2 = p2->next;
if (!p2) return 0;
p2 = p2->next;
if (!p2) return 0;
}
return 1;
}
``` | Haskell
-------
Naive algorithm:
```
import Data.Set (Set)
import qualified Data.Set as Set
type Id = Integer
data Node a = Node { getValue :: a, getId :: Id }
hasLoop :: [Node a] -> Bool
hasLoop = hasLoop' Set.empty
hasLoop' :: Set Id => [Node a] -> Bool
hasLoop' set xs = case ns of
[] -> False
x:xs' -> let
ident = getId x
set' = Set.insert ident set
in if Set.member ident set
then True
else hasLoop' set' xs'
```
Floyd's Cycle-Finding Algorithm:
```
import Control.Monad (join)
import Control.Monad.Instances ()
import Data.Function (on)
import Data.Maybe (listToMaybe)
type Id = Integer
data Node a = Node { getValue :: a, getId :: Id }
next :: [a] -> Maybe [a]
next [] = Nothing
next (_:xs) = Just xs
nexts :: [a] -> [a] -> (Maybe [a], Maybe [a])
nexts xs ys = (next xs, next $ next ys)
hasLoop :: [Node a] -> Bool
hasLoop = uncurry hasLoops' . join nexts
hasLoop' :: Maybe [Node a] -> Maybe [Node a] -> Bool
hasLoop' (Just xs) (Just ys)
| on (==) (getId . listToMaybe) xs ys = True
| otherwise = uncurry hasLoop' $ nexts xs ys
hasLoop' _ Nothing = False
hasLoop' Nothing _ = False -- not needed, but there for case completeness
``` |
3,565 | This comes from one of my favorite interview questions, though apparently it is now a fairly well-known puzzle. I have no way of knowing, but if you have already heard the answer it would be polite to let others try instead.
### Task:
Write a function that takes as input a singly-linked list and returns true if it loops back on itself, and false if it terminates somewhere.
Here's some example code in C as a starting point so you can see what I mean, but feel free to write your answer in whatever language you like:
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *first)
{
/* write your own loop detection here */
}
```
### Hints:
There is a way to make this function run in O(n) time with a constant amount of extra memory. Good on you if you figure it out, but any working answer deserves some upvotes in my book. | 2011/08/26 | [
"https://codegolf.stackexchange.com/questions/3565",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/2360/"
] | C, non-golfed
-------------
The idea is to have to pointers p1 and p2 that traverse the list. p2 moves twice as fast as p1. If p2 reaches p1 at some point then there is a loop. Here is the C code (not tested, though).
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *p)
{
struct node *p1 = p, *p2 = p->next;
if (!p2) return 0;
while (p1 != p2) {
// p1 goes one step
p1 = p1->next;
if (!p1) return 0;
// p2 goes two steps
p2 = p2->next;
if (!p2) return 0;
p2 = p2->next;
if (!p2) return 0;
}
return 1;
}
``` | D
=
This is a solution I thought of myself. It runs in O(n) and uses O(1) memory.
What I'm doing is simply iterating through the list and reversing all the pointers. If the list contains a cycle, you'll eventually end up at the beginning of the list and otherwise you end up at the end, which is somewhere else if your list is longer than 1. Now you've determined the result you can restore the list by simply reversing the pointers again.
Here is my code and a test:
```
import std.stdio;
// The list structure.
struct node(T)
{
T data;
node!T * next;
this(T data) {this.data = data; next = null;}
}
bool hasLoop(T)(node!T * first)
{
// List shorter than two nodes has no loops.
if(!first || !first.next)
{
return false;
}
// Keep iterating through the list, while reversing the pointers.
node!T * previous = null,
current = first;
while(current)
{
auto next = current.next;
current.next = previous;
previous = current;
current = next;
}
// If the last node was the beginning of the list, there was a cycle.
// Otherwise, there are none.
bool result = previous == first;
// Do the reversal again to restore the list to its original state.
current = previous;
previous = null;
while(current)
{
auto next = current.next;
current.next = previous;
previous = current;
current = next;
}
// Done!
return result;
}
// Test
unittest
{
// Build a list.
int[] elems = [1,2,3,4,5,6,7,8,42];
auto list = new node!int(elems[0]);
auto curr = list;
foreach(x; elems[1..$])
{
curr.next = new node!int(x);
curr = curr.next;
}
// Outcomment the line below to test for a non-cycle list.
curr.next = list.next.next.next;
// Do cycle check.
writeln(hasLoop(list) ? "yes" : "no");
// Confirm the list is still correct.
curr = list;
for(int i = 0; i < elems.length; ++i, curr = curr.next)
{
assert(curr.data == elems[i]);
}
}
``` |
3,565 | This comes from one of my favorite interview questions, though apparently it is now a fairly well-known puzzle. I have no way of knowing, but if you have already heard the answer it would be polite to let others try instead.
### Task:
Write a function that takes as input a singly-linked list and returns true if it loops back on itself, and false if it terminates somewhere.
Here's some example code in C as a starting point so you can see what I mean, but feel free to write your answer in whatever language you like:
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *first)
{
/* write your own loop detection here */
}
```
### Hints:
There is a way to make this function run in O(n) time with a constant amount of extra memory. Good on you if you figure it out, but any working answer deserves some upvotes in my book. | 2011/08/26 | [
"https://codegolf.stackexchange.com/questions/3565",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/2360/"
] | Ada
---
The "Floyd's Cycle-Finding Algorithm" is the best solution. It's also called "The Tortoise and the Hare Algorithm".
linked\_lists.ads:
```
generic
type Element_Type is private;
package Linked_Lists is
type Node is private;
type List is private;
function Has_Loops (L : List) return Boolean;
private
type List is access Node;
type Node is record
Value : Element_Type;
Next : List;
end record;
end Linked_Lists;
```
linked\_lists.adb:
```
package body Linked_Lists is
function Has_Loops (L : List) return Boolean is
Slow_Iterator : List := L;
Fast_Iterator : List := null;
begin
-- if list has a second element, set fast iterator start point
if L.Next /= null then
Fast_Iterator := L.Next;
end if;
while Fast_Iterator /= null loop
-- move slow iterator one step
-- guaranteed to be /= null, since it is behind fast iterator
Slow_Iterator := Slow_Iterator.Next;
-- move fast iterator one step
-- guaranteed to be valid, since while catches null
Fast_Iterator := Fast_Iterator.Next;
-- move fast iterator another step
-- null check necessary
if Fast_Iterator /= null then
Fast_Iterator := Fast_Iterator.Next;
end if;
-- if fast iterator arrived at slow iterator -> loop detected
if Fast_Iterator = Slow_Iterator then
return True;
end if;
end loop;
-- fast iterator arrived end, no loop present.
return False;
end Has_Loops;
end Linked_Lists;
```
here is the implementation of the Brent algorithm:
```
package body Linked_Lists is
function Has_Loops (L : List) return Boolean is
Turtle : List := L;
Rabbit : List := L;
Steps : Natural := 0;
Limit : Positive := 2;
begin
-- is rabbit at end?
while Rabbit /= null loop
-- increment rabbit
Rabbit := Rabbit.Next;
-- increment step counter
Steps := Steps + 1;
-- did rabbit meet turtle?
if Turtle = Rabbit then
-- LOOP!
return True;
end if;
-- is it time to move turtle?
if Steps = Limit then
Steps := 0;
Limit := Limit * 2;
-- teleport the turtle
Turtle := Rabbit;
end if;
end loop;
-- rabbit has reached the end
return False;
end Has_Loops;
end Linked_Lists;
``` | Haskell
-------
Naive algorithm:
```
import Data.Set (Set)
import qualified Data.Set as Set
type Id = Integer
data Node a = Node { getValue :: a, getId :: Id }
hasLoop :: [Node a] -> Bool
hasLoop = hasLoop' Set.empty
hasLoop' :: Set Id => [Node a] -> Bool
hasLoop' set xs = case ns of
[] -> False
x:xs' -> let
ident = getId x
set' = Set.insert ident set
in if Set.member ident set
then True
else hasLoop' set' xs'
```
Floyd's Cycle-Finding Algorithm:
```
import Control.Monad (join)
import Control.Monad.Instances ()
import Data.Function (on)
import Data.Maybe (listToMaybe)
type Id = Integer
data Node a = Node { getValue :: a, getId :: Id }
next :: [a] -> Maybe [a]
next [] = Nothing
next (_:xs) = Just xs
nexts :: [a] -> [a] -> (Maybe [a], Maybe [a])
nexts xs ys = (next xs, next $ next ys)
hasLoop :: [Node a] -> Bool
hasLoop = uncurry hasLoops' . join nexts
hasLoop' :: Maybe [Node a] -> Maybe [Node a] -> Bool
hasLoop' (Just xs) (Just ys)
| on (==) (getId . listToMaybe) xs ys = True
| otherwise = uncurry hasLoop' $ nexts xs ys
hasLoop' _ Nothing = False
hasLoop' Nothing _ = False -- not needed, but there for case completeness
``` |
3,565 | This comes from one of my favorite interview questions, though apparently it is now a fairly well-known puzzle. I have no way of knowing, but if you have already heard the answer it would be polite to let others try instead.
### Task:
Write a function that takes as input a singly-linked list and returns true if it loops back on itself, and false if it terminates somewhere.
Here's some example code in C as a starting point so you can see what I mean, but feel free to write your answer in whatever language you like:
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *first)
{
/* write your own loop detection here */
}
```
### Hints:
There is a way to make this function run in O(n) time with a constant amount of extra memory. Good on you if you figure it out, but any working answer deserves some upvotes in my book. | 2011/08/26 | [
"https://codegolf.stackexchange.com/questions/3565",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/2360/"
] | Ada
---
The "Floyd's Cycle-Finding Algorithm" is the best solution. It's also called "The Tortoise and the Hare Algorithm".
linked\_lists.ads:
```
generic
type Element_Type is private;
package Linked_Lists is
type Node is private;
type List is private;
function Has_Loops (L : List) return Boolean;
private
type List is access Node;
type Node is record
Value : Element_Type;
Next : List;
end record;
end Linked_Lists;
```
linked\_lists.adb:
```
package body Linked_Lists is
function Has_Loops (L : List) return Boolean is
Slow_Iterator : List := L;
Fast_Iterator : List := null;
begin
-- if list has a second element, set fast iterator start point
if L.Next /= null then
Fast_Iterator := L.Next;
end if;
while Fast_Iterator /= null loop
-- move slow iterator one step
-- guaranteed to be /= null, since it is behind fast iterator
Slow_Iterator := Slow_Iterator.Next;
-- move fast iterator one step
-- guaranteed to be valid, since while catches null
Fast_Iterator := Fast_Iterator.Next;
-- move fast iterator another step
-- null check necessary
if Fast_Iterator /= null then
Fast_Iterator := Fast_Iterator.Next;
end if;
-- if fast iterator arrived at slow iterator -> loop detected
if Fast_Iterator = Slow_Iterator then
return True;
end if;
end loop;
-- fast iterator arrived end, no loop present.
return False;
end Has_Loops;
end Linked_Lists;
```
here is the implementation of the Brent algorithm:
```
package body Linked_Lists is
function Has_Loops (L : List) return Boolean is
Turtle : List := L;
Rabbit : List := L;
Steps : Natural := 0;
Limit : Positive := 2;
begin
-- is rabbit at end?
while Rabbit /= null loop
-- increment rabbit
Rabbit := Rabbit.Next;
-- increment step counter
Steps := Steps + 1;
-- did rabbit meet turtle?
if Turtle = Rabbit then
-- LOOP!
return True;
end if;
-- is it time to move turtle?
if Steps = Limit then
Steps := 0;
Limit := Limit * 2;
-- teleport the turtle
Turtle := Rabbit;
end if;
end loop;
-- rabbit has reached the end
return False;
end Has_Loops;
end Linked_Lists;
``` | D
=
This is a solution I thought of myself. It runs in O(n) and uses O(1) memory.
What I'm doing is simply iterating through the list and reversing all the pointers. If the list contains a cycle, you'll eventually end up at the beginning of the list and otherwise you end up at the end, which is somewhere else if your list is longer than 1. Now you've determined the result you can restore the list by simply reversing the pointers again.
Here is my code and a test:
```
import std.stdio;
// The list structure.
struct node(T)
{
T data;
node!T * next;
this(T data) {this.data = data; next = null;}
}
bool hasLoop(T)(node!T * first)
{
// List shorter than two nodes has no loops.
if(!first || !first.next)
{
return false;
}
// Keep iterating through the list, while reversing the pointers.
node!T * previous = null,
current = first;
while(current)
{
auto next = current.next;
current.next = previous;
previous = current;
current = next;
}
// If the last node was the beginning of the list, there was a cycle.
// Otherwise, there are none.
bool result = previous == first;
// Do the reversal again to restore the list to its original state.
current = previous;
previous = null;
while(current)
{
auto next = current.next;
current.next = previous;
previous = current;
current = next;
}
// Done!
return result;
}
// Test
unittest
{
// Build a list.
int[] elems = [1,2,3,4,5,6,7,8,42];
auto list = new node!int(elems[0]);
auto curr = list;
foreach(x; elems[1..$])
{
curr.next = new node!int(x);
curr = curr.next;
}
// Outcomment the line below to test for a non-cycle list.
curr.next = list.next.next.next;
// Do cycle check.
writeln(hasLoop(list) ? "yes" : "no");
// Confirm the list is still correct.
curr = list;
for(int i = 0; i < elems.length; ++i, curr = curr.next)
{
assert(curr.data == elems[i]);
}
}
``` |
3,565 | This comes from one of my favorite interview questions, though apparently it is now a fairly well-known puzzle. I have no way of knowing, but if you have already heard the answer it would be polite to let others try instead.
### Task:
Write a function that takes as input a singly-linked list and returns true if it loops back on itself, and false if it terminates somewhere.
Here's some example code in C as a starting point so you can see what I mean, but feel free to write your answer in whatever language you like:
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *first)
{
/* write your own loop detection here */
}
```
### Hints:
There is a way to make this function run in O(n) time with a constant amount of extra memory. Good on you if you figure it out, but any working answer deserves some upvotes in my book. | 2011/08/26 | [
"https://codegolf.stackexchange.com/questions/3565",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/2360/"
] | Since the solution is already in the open, I think it's fair to step in now with Brent's algorithm, which is the one I'm familiar with from integer factorisation.
```
#define bool int
#define false 0
#define true 1
bool has_loops(struct node *first) {
if (!first) return false;
struct node *a = first, *b = first;
int step = 1;
while (true) {
for (int i = 0; i < step; i++) {
b = b->next;
if (!b) return false;
if (a == b) return true;
}
a = a->next;
if ((step << 1) > 0) step <<= 1;
}
}
``` | Haskell
-------
Naive algorithm:
```
import Data.Set (Set)
import qualified Data.Set as Set
type Id = Integer
data Node a = Node { getValue :: a, getId :: Id }
hasLoop :: [Node a] -> Bool
hasLoop = hasLoop' Set.empty
hasLoop' :: Set Id => [Node a] -> Bool
hasLoop' set xs = case ns of
[] -> False
x:xs' -> let
ident = getId x
set' = Set.insert ident set
in if Set.member ident set
then True
else hasLoop' set' xs'
```
Floyd's Cycle-Finding Algorithm:
```
import Control.Monad (join)
import Control.Monad.Instances ()
import Data.Function (on)
import Data.Maybe (listToMaybe)
type Id = Integer
data Node a = Node { getValue :: a, getId :: Id }
next :: [a] -> Maybe [a]
next [] = Nothing
next (_:xs) = Just xs
nexts :: [a] -> [a] -> (Maybe [a], Maybe [a])
nexts xs ys = (next xs, next $ next ys)
hasLoop :: [Node a] -> Bool
hasLoop = uncurry hasLoops' . join nexts
hasLoop' :: Maybe [Node a] -> Maybe [Node a] -> Bool
hasLoop' (Just xs) (Just ys)
| on (==) (getId . listToMaybe) xs ys = True
| otherwise = uncurry hasLoop' $ nexts xs ys
hasLoop' _ Nothing = False
hasLoop' Nothing _ = False -- not needed, but there for case completeness
``` |
3,565 | This comes from one of my favorite interview questions, though apparently it is now a fairly well-known puzzle. I have no way of knowing, but if you have already heard the answer it would be polite to let others try instead.
### Task:
Write a function that takes as input a singly-linked list and returns true if it loops back on itself, and false if it terminates somewhere.
Here's some example code in C as a starting point so you can see what I mean, but feel free to write your answer in whatever language you like:
```
struct node
{
void *value;
struct node *next;
};
int has_loops(struct node *first)
{
/* write your own loop detection here */
}
```
### Hints:
There is a way to make this function run in O(n) time with a constant amount of extra memory. Good on you if you figure it out, but any working answer deserves some upvotes in my book. | 2011/08/26 | [
"https://codegolf.stackexchange.com/questions/3565",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/2360/"
] | Since the solution is already in the open, I think it's fair to step in now with Brent's algorithm, which is the one I'm familiar with from integer factorisation.
```
#define bool int
#define false 0
#define true 1
bool has_loops(struct node *first) {
if (!first) return false;
struct node *a = first, *b = first;
int step = 1;
while (true) {
for (int i = 0; i < step; i++) {
b = b->next;
if (!b) return false;
if (a == b) return true;
}
a = a->next;
if ((step << 1) > 0) step <<= 1;
}
}
``` | D
=
This is a solution I thought of myself. It runs in O(n) and uses O(1) memory.
What I'm doing is simply iterating through the list and reversing all the pointers. If the list contains a cycle, you'll eventually end up at the beginning of the list and otherwise you end up at the end, which is somewhere else if your list is longer than 1. Now you've determined the result you can restore the list by simply reversing the pointers again.
Here is my code and a test:
```
import std.stdio;
// The list structure.
struct node(T)
{
T data;
node!T * next;
this(T data) {this.data = data; next = null;}
}
bool hasLoop(T)(node!T * first)
{
// List shorter than two nodes has no loops.
if(!first || !first.next)
{
return false;
}
// Keep iterating through the list, while reversing the pointers.
node!T * previous = null,
current = first;
while(current)
{
auto next = current.next;
current.next = previous;
previous = current;
current = next;
}
// If the last node was the beginning of the list, there was a cycle.
// Otherwise, there are none.
bool result = previous == first;
// Do the reversal again to restore the list to its original state.
current = previous;
previous = null;
while(current)
{
auto next = current.next;
current.next = previous;
previous = current;
current = next;
}
// Done!
return result;
}
// Test
unittest
{
// Build a list.
int[] elems = [1,2,3,4,5,6,7,8,42];
auto list = new node!int(elems[0]);
auto curr = list;
foreach(x; elems[1..$])
{
curr.next = new node!int(x);
curr = curr.next;
}
// Outcomment the line below to test for a non-cycle list.
curr.next = list.next.next.next;
// Do cycle check.
writeln(hasLoop(list) ? "yes" : "no");
// Confirm the list is still correct.
curr = list;
for(int i = 0; i < elems.length; ++i, curr = curr.next)
{
assert(curr.data == elems[i]);
}
}
``` |
1,556,716 | I distributed an iPhone application to some testers who are using Windows. On their machines, the application that I built (in the form of an .app bundle) appeared as a directory. That makes sense because a .app bundle **is** actually a directory.
What mechanism does Mac OS X use to display these bundles as files within Finder? Is there anyway to get the same kind of abstraction on Windows? | 2009/10/12 | [
"https://Stackoverflow.com/questions/1556716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105382/"
] | No, but why would you want to? An .app on Mac is not equivalent to an .exe on Windows - if you explore the .app bundle on a Mac (using "Show Package Contents"), you'll see an actual executable program inside. *This* program is more the equivalent of a Windows .exe, and you can liken the entire .app bundle to the Program Files directory for an application on Windows. All the .app serves to do is to concentrate program resources in one directory, much like an install directory does on Windows. | It's kind of the same magic that lets zip files appear as "compressed folders". It's what the shell does but I am afraid you have no way of hooking into such things. |
1,556,716 | I distributed an iPhone application to some testers who are using Windows. On their machines, the application that I built (in the form of an .app bundle) appeared as a directory. That makes sense because a .app bundle **is** actually a directory.
What mechanism does Mac OS X use to display these bundles as files within Finder? Is there anyway to get the same kind of abstraction on Windows? | 2009/10/12 | [
"https://Stackoverflow.com/questions/1556716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105382/"
] | It's kind of the same magic that lets zip files appear as "compressed folders". It's what the shell does but I am afraid you have no way of hooking into such things. | If you are distributing to Windows users all will go much better if you give them IPA files instead of app bundles.
The easiest way to create an IPA file is to drag the .app bundle into iTunes, and then look for the IPA file that it generates for you. |
1,556,716 | I distributed an iPhone application to some testers who are using Windows. On their machines, the application that I built (in the form of an .app bundle) appeared as a directory. That makes sense because a .app bundle **is** actually a directory.
What mechanism does Mac OS X use to display these bundles as files within Finder? Is there anyway to get the same kind of abstraction on Windows? | 2009/10/12 | [
"https://Stackoverflow.com/questions/1556716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105382/"
] | No, but why would you want to? An .app on Mac is not equivalent to an .exe on Windows - if you explore the .app bundle on a Mac (using "Show Package Contents"), you'll see an actual executable program inside. *This* program is more the equivalent of a Windows .exe, and you can liken the entire .app bundle to the Program Files directory for an application on Windows. All the .app serves to do is to concentrate program resources in one directory, much like an install directory does on Windows. | If you are distributing to Windows users all will go much better if you give them IPA files instead of app bundles.
The easiest way to create an IPA file is to drag the .app bundle into iTunes, and then look for the IPA file that it generates for you. |
23,783,427 | i am a beginner in haskell programming and very often i get the error
```
xxx.hs:30:1: parse error on input `xxx'
```
And often there is a little bit playing with the format the solution. Its the same code and it looks the same, but after playing around, the error is gone.
At the moment I've got the error
```
LookupAll.hs:30:1: parse error on input `lookupAll'
```
After that code:
```
lookupOne :: Int -> [(Int,a)] -> [a]
lookupOne _ [] = []
lookupOne x list =
if fst(head list) == x then snd(head list) : []
lookupOne x (tail list)
-- | Given a list of keys and a list of pairs of key and value
-- 'lookupAll' looks up the list of associated values for each key
-- and concatenates the results.
lookupAll :: [Int] -> [(Int,a)] -> [a]
lookupAll [] _ = []
lookupAll _ [] = []
lookupAll xs list = lookupOne h list ++ lookupAll t list
where
h = head xs
t = tail xs
```
But I have done everything right in my opinion. There are no tabs or something like that. Always 4 spaces. Is there a general solutoin for this problems? I am using notepad++ at the moment.
Thanks! | 2014/05/21 | [
"https://Stackoverflow.com/questions/23783427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420062/"
] | The problem is not with `lookupAll`, it's actually with the previous two lines of code
```
if fst (head list) == x then snd (head list) : []
lookupOne x (tail list)
```
You haven't included an `else` on this if statement. My guess is that you meant
```
if fst (head list) == x then snd (head list) : []
else lookupOne x (tail list)
```
Which I personally would prefer to format as
```
if fst (head list) == x
then snd (head list) : []
else lookupOne x (tail list)
```
but that's a matter of taste.
---
If you are wanting to accumulate a list of values that match a condition, there are a few ways. By far the easiest is to use `filter`, but you can also use explicit recursion. To use `filter`, you could write your function as
```
lookupOne x list
= map snd -- Return only the values from the assoc list
$ filter (\y -> fst y == x) list -- Find each pair whose first element equals x
```
If you wanted to use recursion, you could instead write it as
```
lookupOne _ [] = [] -- The base case pattern
lookupOne x (y:ys) = -- Pattern match with (:), don't have to use head and tail
if fst y == x -- Check if the key and lookup value match
then snd y : lookupOne x ys -- If so, prepend it onto the result of looking up the rest of the list
else lookupOne x ys -- Otherwise, just return the result of looking up the rest of the list
```
Both of these are equivalent. In fact, you can implement `filter` as
```
filter cond [] = []
filter cond (x:xs) =
if cond x
then x : filter cond xs
else filter cond xs
```
And `map` as
```
map f [] = []
map f (x:xs) = f x : map f xs
```
Hopefully you can spot the similarities between `filter` and `lookupOne`, and with `map` consider `f == snd`, so you have a merger of the two patterns of `map` and `filter` in the explicit recursive version of `lookupOne`. You could generalize this combined pattern into a higher order function
```
mapFilter :: (a -> b) -> (a -> Bool) -> [a] -> [b]
mapFilter f cond [] = []
mapFilter f cond (x:xs) =
if cond x
then f x : mapFilter f cond xs
else : mapFilter f cond xs
```
Which you can use to implement `lookupOne` as
```
lookupOne x list = mapFilter snd (\y -> fst y == x) list
```
Or more simply
```
lookupOne x = mapFilter snd ((== x) . fst)
``` | I think @bheklilr is right - you're missing an `else`.
You could fix this particular formatting problem, however, by forming `lookupOne` as a function composition, rather than writing your own new recursive function.
For example, you can get the right kind of behaviour by defining `lookupOne` like this:
```
lookupOne a = map snd . filter ((==) a . fst)
```
This way it's clearer that you're first filtering out the elements of the input list for which the first element of the tuple matches the key, and then extracting just the second element of each tuple. |
30,633,378 | I cannot find a way to change the color of an Excel data bar based on value. Current formatting options only permit different colors based on positive/negative values. I'm currently using Excel 2010.
I would like to have the color of a data bar show up as 'red' if the value if between 0-0.3, 'yellow' if the value is between 0.3-0.6, and 'green' if the value if between >0.6.
Would really appreciate any info people could share.
Thanks,
TB | 2015/06/04 | [
"https://Stackoverflow.com/questions/30633378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4971822/"
] | Data bars only support one color per set. The idea is that the length of the data bar gives you an indication of high, medium or low.
Conditional colors can be achieved with color scales.
What you describe sounds like a combination of the two, but that does not exist in Excel and I don't see an easy way to hack it.
You could use a kind of in-cell "chart" that was popular before sparklines came along. Use a formula to repeat a character (in the screenshot it's the character `g` formatted with Marlett font), and then use conditional formatting to change the font color.

For a nicer "bar" feel, use unicode character 2588 with a regular font.

Edit: Not every Unicode character is represented in every font. In this case the the unicode 2588 shows fine with Arial font but not with Excel's default Calibri. Select your fonts accordingly. The Insert > Symbol dialog will help find suitable characters.
 | In your case, highlight the cell will be more suitable as we can not form data bar with multiple colors
Conditional Formationg >Manage Rules...>New Rule
Under Select a Rule Type, choose "Use a formula to determince which cells to format" and set your rules there
 |
30,633,378 | I cannot find a way to change the color of an Excel data bar based on value. Current formatting options only permit different colors based on positive/negative values. I'm currently using Excel 2010.
I would like to have the color of a data bar show up as 'red' if the value if between 0-0.3, 'yellow' if the value is between 0.3-0.6, and 'green' if the value if between >0.6.
Would really appreciate any info people could share.
Thanks,
TB | 2015/06/04 | [
"https://Stackoverflow.com/questions/30633378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4971822/"
] | Data bars only support one color per set. The idea is that the length of the data bar gives you an indication of high, medium or low.
Conditional colors can be achieved with color scales.
What you describe sounds like a combination of the two, but that does not exist in Excel and I don't see an easy way to hack it.
You could use a kind of in-cell "chart" that was popular before sparklines came along. Use a formula to repeat a character (in the screenshot it's the character `g` formatted with Marlett font), and then use conditional formatting to change the font color.

For a nicer "bar" feel, use unicode character 2588 with a regular font.

Edit: Not every Unicode character is represented in every font. In this case the the unicode 2588 shows fine with Arial font but not with Excel's default Calibri. Select your fonts accordingly. The Insert > Symbol dialog will help find suitable characters.
 | I setup conditional formatting in the cell adjacent to the data bar that changes color based on the value in the target cell (green, yellow, red, orange). I then loop through the VBA below to update the data bar color based on the conditional formatting in the adjacent cell.
```
Dim intCount As Integer
Dim db As DataBar
On Error Resume Next
For intCount = 9 To 43 'rows with data bars to be updated
Worksheets("Worksheet Name").Cells(intCount, 10).FormatConditions(1).BarColor.Color = Worksheets("Worksheet Name").Cells(intCount, 11).DisplayFormat.Interior.Color
Next intCount
``` |
30,633,378 | I cannot find a way to change the color of an Excel data bar based on value. Current formatting options only permit different colors based on positive/negative values. I'm currently using Excel 2010.
I would like to have the color of a data bar show up as 'red' if the value if between 0-0.3, 'yellow' if the value is between 0.3-0.6, and 'green' if the value if between >0.6.
Would really appreciate any info people could share.
Thanks,
TB | 2015/06/04 | [
"https://Stackoverflow.com/questions/30633378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4971822/"
] | Data bars only support one color per set. The idea is that the length of the data bar gives you an indication of high, medium or low.
Conditional colors can be achieved with color scales.
What you describe sounds like a combination of the two, but that does not exist in Excel and I don't see an easy way to hack it.
You could use a kind of in-cell "chart" that was popular before sparklines came along. Use a formula to repeat a character (in the screenshot it's the character `g` formatted with Marlett font), and then use conditional formatting to change the font color.

For a nicer "bar" feel, use unicode character 2588 with a regular font.

Edit: Not every Unicode character is represented in every font. In this case the the unicode 2588 shows fine with Arial font but not with Excel's default Calibri. Select your fonts accordingly. The Insert > Symbol dialog will help find suitable characters.
 | Instead of creating conditional formatting for a range of cells, I conditionally formatted each cell individually using VBA based on the two subs below. The result is shown in the link below the code. Hope this helps.
```
' The purpose of this sub is to add a data bar to an individual cell
' The value in the cell is expected to be decimal numbers between -1 and 1
' If the value is greater than or equal to -0.1 and less than or equal to 0.1, then display green bars
' If the value is less than -0.1 and greater than -.2, OR greater than 0.1 and less than 0.2 then yellow bars
' All other scenarios display red bars
Sub Add_Data_Bar(rngCell As Range, dblValue As Double)
' Clears existing conditional formatting from the cell
' Adds a new data bar to the cell
With rngCell.FormatConditions
.Delete
.AddDatabar
End With
' Creates a databar object for the databar that has been added to the cell
Dim dbar As Databar
Set dbar = rngCell.FormatConditions(rngCell.FormatConditions.Count)
' Sets the databar fill type to display as gradient
dbar.BarFillType = xlDataBarFillGradient
' Sets the databar border style
dbar.BarBorder.Type = xlDataBarBorderSolid
' Sets the databar axis position
dbar.AxisPosition = xlDataBarAxisMidpoint
' Sets the minimum limit of the data bar to -1
With dbar.MinPoint
.Modify newtype:=xlConditionValueNumber, newvalue:=-1
End With
' Sets the maximum limit of the data bar to +1
With dbar.MaxPoint
.Modify newtype:=xlConditionValueNumber, newvalue:=1
End With
' Sets the color based on what value has been passed to the sub
' Green
If dblValue <= 0.1 And dblValue >= -0.1 Then
With dbar
.BarColor.Color = RGB(99, 195, 132) ' Green
.BarBorder.Color.Color = RGB(99, 195, 132)
End With
' Yellow
ElseIf (dblValue > 0.1 And dblValue <= 0.2) Or (dblValue < -0.1 And dblValue >= -0.2) Then
With dbar
.BarColor.Color = RGB(255, 182, 40) ' Yellow
.BarBorder.Color.Color = RGB(255, 182, 40)
End With
' Red
Else
With dbar
.BarColor.Color = RGB(255, 0, 0) ' Red
.BarBorder.Color.Color = RGB(255, 0, 0)
End With
End If
End Sub
' Applies the databar formatting to each cell in a range
‘ Call this on the Worksheet_Change event so that the formatting updates when data is refreshed
Sub Loop_Through_Range()
' Range to be looped through
Dim rng As Range
Set rng = Sheet1.Range("A2:A22")
' Range for For Loop
Dim cell As Range
' Loops through each cell in your range
For Each cell In rng.Cells
Call Add_Data_Bar(cell, cell.Value)
Next
End Sub
```
[Worksheet View](https://i.stack.imgur.com/EVeX9.png) |
30,633,378 | I cannot find a way to change the color of an Excel data bar based on value. Current formatting options only permit different colors based on positive/negative values. I'm currently using Excel 2010.
I would like to have the color of a data bar show up as 'red' if the value if between 0-0.3, 'yellow' if the value is between 0.3-0.6, and 'green' if the value if between >0.6.
Would really appreciate any info people could share.
Thanks,
TB | 2015/06/04 | [
"https://Stackoverflow.com/questions/30633378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4971822/"
] | I setup conditional formatting in the cell adjacent to the data bar that changes color based on the value in the target cell (green, yellow, red, orange). I then loop through the VBA below to update the data bar color based on the conditional formatting in the adjacent cell.
```
Dim intCount As Integer
Dim db As DataBar
On Error Resume Next
For intCount = 9 To 43 'rows with data bars to be updated
Worksheets("Worksheet Name").Cells(intCount, 10).FormatConditions(1).BarColor.Color = Worksheets("Worksheet Name").Cells(intCount, 11).DisplayFormat.Interior.Color
Next intCount
``` | In your case, highlight the cell will be more suitable as we can not form data bar with multiple colors
Conditional Formationg >Manage Rules...>New Rule
Under Select a Rule Type, choose "Use a formula to determince which cells to format" and set your rules there
 |
30,633,378 | I cannot find a way to change the color of an Excel data bar based on value. Current formatting options only permit different colors based on positive/negative values. I'm currently using Excel 2010.
I would like to have the color of a data bar show up as 'red' if the value if between 0-0.3, 'yellow' if the value is between 0.3-0.6, and 'green' if the value if between >0.6.
Would really appreciate any info people could share.
Thanks,
TB | 2015/06/04 | [
"https://Stackoverflow.com/questions/30633378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4971822/"
] | I setup conditional formatting in the cell adjacent to the data bar that changes color based on the value in the target cell (green, yellow, red, orange). I then loop through the VBA below to update the data bar color based on the conditional formatting in the adjacent cell.
```
Dim intCount As Integer
Dim db As DataBar
On Error Resume Next
For intCount = 9 To 43 'rows with data bars to be updated
Worksheets("Worksheet Name").Cells(intCount, 10).FormatConditions(1).BarColor.Color = Worksheets("Worksheet Name").Cells(intCount, 11).DisplayFormat.Interior.Color
Next intCount
``` | Instead of creating conditional formatting for a range of cells, I conditionally formatted each cell individually using VBA based on the two subs below. The result is shown in the link below the code. Hope this helps.
```
' The purpose of this sub is to add a data bar to an individual cell
' The value in the cell is expected to be decimal numbers between -1 and 1
' If the value is greater than or equal to -0.1 and less than or equal to 0.1, then display green bars
' If the value is less than -0.1 and greater than -.2, OR greater than 0.1 and less than 0.2 then yellow bars
' All other scenarios display red bars
Sub Add_Data_Bar(rngCell As Range, dblValue As Double)
' Clears existing conditional formatting from the cell
' Adds a new data bar to the cell
With rngCell.FormatConditions
.Delete
.AddDatabar
End With
' Creates a databar object for the databar that has been added to the cell
Dim dbar As Databar
Set dbar = rngCell.FormatConditions(rngCell.FormatConditions.Count)
' Sets the databar fill type to display as gradient
dbar.BarFillType = xlDataBarFillGradient
' Sets the databar border style
dbar.BarBorder.Type = xlDataBarBorderSolid
' Sets the databar axis position
dbar.AxisPosition = xlDataBarAxisMidpoint
' Sets the minimum limit of the data bar to -1
With dbar.MinPoint
.Modify newtype:=xlConditionValueNumber, newvalue:=-1
End With
' Sets the maximum limit of the data bar to +1
With dbar.MaxPoint
.Modify newtype:=xlConditionValueNumber, newvalue:=1
End With
' Sets the color based on what value has been passed to the sub
' Green
If dblValue <= 0.1 And dblValue >= -0.1 Then
With dbar
.BarColor.Color = RGB(99, 195, 132) ' Green
.BarBorder.Color.Color = RGB(99, 195, 132)
End With
' Yellow
ElseIf (dblValue > 0.1 And dblValue <= 0.2) Or (dblValue < -0.1 And dblValue >= -0.2) Then
With dbar
.BarColor.Color = RGB(255, 182, 40) ' Yellow
.BarBorder.Color.Color = RGB(255, 182, 40)
End With
' Red
Else
With dbar
.BarColor.Color = RGB(255, 0, 0) ' Red
.BarBorder.Color.Color = RGB(255, 0, 0)
End With
End If
End Sub
' Applies the databar formatting to each cell in a range
‘ Call this on the Worksheet_Change event so that the formatting updates when data is refreshed
Sub Loop_Through_Range()
' Range to be looped through
Dim rng As Range
Set rng = Sheet1.Range("A2:A22")
' Range for For Loop
Dim cell As Range
' Loops through each cell in your range
For Each cell In rng.Cells
Call Add_Data_Bar(cell, cell.Value)
Next
End Sub
```
[Worksheet View](https://i.stack.imgur.com/EVeX9.png) |
497,407 | We started a TCP/IP introductory course at work today, and learned about the different classes of network addresses:
```
Class A addresses are from 0.0.0.0 thru 127.x.x.x
Class B addresses are from 128.0.0.0 thru 191.x.x.x
Class C addresses are from 192.0.0.0 thru 223.x.x.x
Class D addresses are from 224.0.0.0 thru 239.x.x.x
Class E addresses are from 240.0.0.0 thru 255.x.x.x
```
I'm not clear on the possible subnet sizes for the different classes of networks. For example, what is the largest subnet mask possible for a Class C network? Is it 255.255.255.0, or could you also have 255.255.0.0 and 255.0.0.0? | 2012/11/01 | [
"https://superuser.com/questions/497407",
"https://superuser.com",
"https://superuser.com/users/115033/"
] | There are no classes, they were deprecated in 1994 (seriously, that was 18 years ago as of writing this). Your teacher should be **fired** for even mentioning them (outside a *history* class) as it will only confuse you when you learn how networks actually work.
Networks are subnetted using CIDR (and expressed in CIDR notation). While the old class system maps to particular CIDR subnets, it's a terrible concept. In short, try to forget what you've already learned and dive into [How does IPv4 Subnetting Work?](https://serverfault.com/questions/49765/how-does-ipv4-subnetting-work) | For a bit of perspective, classful network types are still used as a common terminology for internal and private (RFC1918) networks.
It's true that since BPG4, CIDR has made classful Internet boundaries meaningless, but when talking about interior networks and classful routing protocols, it's still useful to know the differences in the classes.
To answer your question, classful boundaries are fixed in size. The subnet masks for each are as follows:
```
CLASS A: 255.0.0.0 (/8)
CLASS B: 255.255.0.0 (/16)
CLASS C: 255.255.255.0 (/24)
CLASS D: N/A (These are used for multicast traffic and are routed internally using PIM or DVMRP and do not correspond to traditional subnet masks)
CLASS E: N/A (There are experimental and/or reserved addresses)
```
A larger collection of classful networks is called a *supernet* and a sub-divided classful network is called a *subnet*. When you talk about the largest possible subnet mask, you are generally referring to the largest possible network portion and smallest usable host portion. For routing subnet purposes, the largest subnet mask is 255.255.255.252 (/30). This is typically used for point-to-point links and transit networks that only need two hosts/gateways on a subnet.
There is no limit to the maximum size a supernet can be, up to a subnet mask of 0.0.0.0 (/0), which would indicate that every address is local and not routed. Note that this is different than a default route of 0.0.0.0, which is the least specific route and routes all traffic not defined by a more specific route.
If you are looking for the largest possible subnet mask to define all Class A networks and so on, here is the list based upon the first octet:
```
CLASS A: 0 - 127 = 128.0.0.0 (/1) = 128 /8 networks
CLASS B: 128 - 191 = 192.0.0.0 (/2) = 64 /8 networks or 16,384 /16 networks
CLASS C: 192 - 223 = 224.0.0.0 (/3) = 32 /8 networks or 2,097,152 /24 networks
CLASS D: 224 - 239 = 240.0.0.0 (/4) = 16 /8 networks or 268,435,456 multicast addresses
CLASS E: 240 - 255 = 248.0.0.0 (/5) = 8 /8 networks or ??? (I haven't a clue lol)
```
Hope that helps!! |
6,127,157 | I have a solution with 15+ projects in there
While jumping to a class is easy enough in VS2008/2010 with RightClick-Goto definition which jumps to the file containing the definition, but how to locate the project which contains this new class/file ??
I seem to recall it's possible using some "magic" keystrokes/menu but can's seem to locate it | 2011/05/25 | [
"https://Stackoverflow.com/questions/6127157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135852/"
] | That is one well defined question!
There is a question over what is a model. I believe there is a definition floating around as to what constitutes a model in the backbone world, and I'm not sure your strategy is in keeping with that definition. Also you are storing the state in both the url, and the model. You can just store the state in the url, as I will explain.
If I was doing this, there would be 2 views. One for your app controls, and nested inside that one for your graph: GraphView, and AppView. The model will be the data your going to plot, not the state of the interface.
Use a controller to kick start the app view and also to process any interface state defined in the url.
There is a question about levers of state in Backbone. Traditional web applications used a link/url as the primary lever of state but all that is now changing. Here is one possible strategy:
```
Checkbox Change Event -> Update location fragment -> trigger route in controller -> update the view
Slider Change Event -> Update location fragment -> trigger route in controller -> update the view
```
The great thing about such a strategy is that it takes care of the case where urls are passed around or bookmarked
```
Url specified in address bar -> trigger route in controller -> update the view
```
I'll take a stab at a pseudo code example. For this, I will make some assumptions on the data:
The data is the dog population over time (with a granularity of year), where the slider should have a lower and upper bound, and there volume data is too large to load it all to the client at once.
First let's look at the Model to represent the statistical data. For each point on the graph we need something like { population: 27000, year: 2003 }
Lets represent this as
```
DogStatModel extends Backbone.Model ->
```
and a collection of this data will be
```
DogStatCollection extends Backbone.Collection ->
model: DogStatModel
query: null // query sent to server to limit results
url: function() {
return "/dogStats?"+this.query
}
```
Now lets look at the controller. In this strategy I propose, the controller lives up to its name.
```
AppController extends Backbone.Controller ->
dogStatCollection: null,
appView: null,
routes: {
"/:query" : "showChart"
},
chart: function(query){
// 2dani, you described a nice way in your question
// but will be more complicated if selections are not mutually exclusive
// countries you could have as countries=sweden;france&fullscreen=true
queryMap = parse(query) //
if (!this.dogStatCollection) dogStatCollection = new DogStatCollection
dogStatCollection.query = queryMap.serverQuery
if (!this.appView) {
appView = new AppView()
appView.collection = dogStatCollection
}
appView.fullScreen = queryMap.fullScreen
dogStatCollection.fetch(success:function(){
appView.render()
})
}
``` | >
> 2) How can I avoid my views setting an attribute on the model which they themselves listen for?
>
>
>
You don't. Your model should be doing validation on any attributes you try to update so your view *needs* to listen in case your setting of the attribute failed or the validation changed the value.
What your view does is, it's *tries* to set a value on the model, the model then either sets it, changes the data and sets it, or rejects it. Your view needs to be updated accordingly.
>
> 3) How can I push a new state based on a part of the model?
>
>
>
```
// for each attribute
_.each(["attribute1", "attribute2", "attribute3", ...], _.bind(function(val) {
// bind the change
// bind the setState with `this` and the `value` as the first parameter
this.bind("change:" + value, _.bind(this.setState, this, value));
}, this));
``` |
17,057,338 | why i ask this question because i always worried about code like this style
```
def callsomething(x):
if x in (3,4,5,6):
#do something
```
if the function callsomething was called frequently ,did the (3,4,5,6) waste too much space and time?in some language like C, it might be putted into data segment like constant,but in python,i don't know how it works,so i tended to write code like this
```
checktypes = (3,4,5,6)#cache it
def callsomething(x):
global checktypes
if x in checktypes:
#do something
```
but after test i found this way make program slower, in more complicated case, the code would be like this:
```
types = (3,4,5,6)
def callsomething(x):
global types
for t in types:
t += x
#do something
```
still slower than this
```
def callsomething(x):
for t in (3+x,4+x,5+x,6+x):
#do something
```
in this case, the program must create (3+x,4+x,5+x,6+x),right?but it still faster than the first version,not head too much though.
i know the global var access in python would slow down program but how dose it compare to creating an struct? | 2013/06/12 | [
"https://Stackoverflow.com/questions/17057338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2003548/"
] | Don't worry, it's stored as a constant (which explains why it's faster than you expected)
```
>>> def callsomething(x):
... if x in (3,4,5,6): pass
...
>>> import dis
>>> dis.dis(callsomething)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 5 ((3, 4, 5, 6))
6 COMPARE_OP 6 (in)
9 POP_JUMP_IF_FALSE 15
12 JUMP_FORWARD 0 (to 15)
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
```
Looking up `x` in a `set` should be faster, right? But Uh Oh...
```
>>> def callsomething(x):
... if x in {3,4,5,6}: pass
...
>>> dis.dis(callsomething)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (3)
6 LOAD_CONST 2 (4)
9 LOAD_CONST 3 (5)
12 LOAD_CONST 4 (6)
15 BUILD_SET 4
18 COMPARE_OP 6 (in)
21 POP_JUMP_IF_FALSE 27
24 JUMP_FORWARD 0 (to 27)
>> 27 LOAD_CONST 0 (None)
30 RETURN_VALUE
```
set is mutable, so Python hasn't made this optimization until recently. Python3.3 sees that it's safe to make this into a frozenset
```
Python 3.3.0 (default, Sep 29 2012, 17:17:45)
[GCC 4.7.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def callsomething(x):
... if x in {3,4,5,6}: pass
...
>>> import dis
>>> dis.dis(callsomething)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 5 (frozenset({3, 4, 5, 6}))
6 COMPARE_OP 6 (in)
9 POP_JUMP_IF_FALSE 15
12 JUMP_FORWARD 0 (to 15)
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
>>>
``` | If you really want to do a hack so that you can get constants for things beyond tuples, you could do something gross like
```
def foo(x, dont_use_this=frozenset([1,2,3])):
if x in dont_use_this:
# do something
return x
```
But don't do that. |
401,043 | What are some ways of documenting pitfalls and gotchas when working with a codebase with a team of developers? I'm working with a team of developers on a big codebase and there's lots of small little things that cause headaches and frustrations in code, configuration, and testing. It doesn't seem appropriate to put them into the github pages because they could be scattered across repositories and projects - so my question is what are some examples of documenting pitfalls and common gotchas? | 2019/11/13 | [
"https://softwareengineering.stackexchange.com/questions/401043",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/128090/"
] | Quirks and hacks which are easy to explain could be explained in a form of a **comment**. After all, the purpose of the comments is exactly that—come to a rescue when one cannot or doesn't have enough resources to make unclear code clearer. The goal here is to help a programmer who's reading a given line of code (or series of lines) and asks himself what went so wrong in the past that it resulted in this specific piece of code.
Weird architecture decisions (which seemed right when they were taken, then appeared to be wrong, but nobody made the effort to refactor the codebase) should be documented in an **architecture document**. Put it in a location where anybody working on the project would find it easily, and make sure new programmers joining the project would necessarily read it.
In both cases, make sure you (and your coworkers) understand that **there is nothing normal in having a source code full of pitfalls and gotchas that need to be documented**.
Talk with your product owner to reserve a few hours or days per week for large refactoring tasks (i.e. changes at design or architecture level). If you don't, the project is doomed, as every other project where technical debt was left increasing.
Moreover, code-level refactoring should be your constant activity: whenever you work on a piece of code, ensure you follow the boy scout rule: “Leave your code better than you found it.” If a method is unclear because someone used one-letter names for the variables, don't keep it this way: rename them. It doesn't take long, and it will pay out the next time someone won't lose ten minutes trying to figure out how this method works. Most refactoring techniques are pretty simple and quick to implement, and many are very effective. | No quirks would be better
-------------------------
First and foremost, the [principle of least astonishment](https://en.wikipedia.org/wiki/Principle_of_least_astonishment) applies:
>
> A typical formulation of the principle, from 1984, is: "If a necessary feature has a high astonishment factor, it may be necessary to **redesign the feature**."
>
>
>
In other words: **remove the quirks**. The time your developers lose on dealing with the quirks is likely to be bigger than the time needed for removing the quirk altogether.
[XKCD](https://xkcd.com/1205/) has a really handy guide to show you the rough numbers on how long you can justify spending time on fixing something based on how often you encounter it:
[](https://i.stack.imgur.com/1Vp6q.png)
Taking a simple example, if your team runs into a particular quirk once a week (on average) and you spend 30 minutes on it (on average), and this product is expected to be used for the next 5 years, that gives you a whopping 21 hours or **just under 3 days** to work on fixing the quirk before you've spent more time than you've saved. Even if you encounter the same issue only on a monthly basis, that still gives you **about a day** to fix it.
Note that the time spent on a quirk very quickly adds up. Bugfixing, rerunning a comprehensive test playlist, communication during a daily standup, merge conflicts, training, reading the documentation on the quirk, ... Also note that training counts for double time because it's a time investment on both the trainer and the trainee's part.
Documentation is not a [panacea](https://en.wikipedia.org/wiki/Panacea_(medicine))
----------------------------------------------------------------------------------
Don't get me wrong, documentation is essential, especially when you account for the
[bus factor](https://en.wikipedia.org/wiki/Bus_factor), but documentation should not be your only line of defense.
Whenever they encounter an issue, no one is going to read through the entire documentation before consulting anyone else (nor should they). If they think the problem is new, they will spend time digging into it and it will take time (quirks tend to inherently be counterintuitive). If they don't think the problem is new, they're going to ask someone more experienced if there's a known resolution.
Documentation is great for referring to, but it doesn't inherently prevent developers distracting each other by asking about the problem. [Developer productivity tanks when they get distracted](https://www.gamasutra.com/view/feature/190891/programmer_interrupted.php), and the duration of the distraction is a surprisingly negligible factor here (whether the distraction takes seconds, minutes or hours).
>
> **No Distractions**
>
> Another approach for getting into the zone is to avoid all distractions. Some people are more sensitive to distraction than others, but we should always aim to minimise the kinds of distraction that pulls our mind out of what we're currently doing. **Avoiding the context switching cost is a big win**.
>
>
>
The rest of [the article](https://lifehacker.com/what-is-the-zone-anyway-5920484) is less relevant here but it touches on the importance of not switching context if you want to keep productivity up.
When you need to document
-------------------------
But sometimes, quirks are too ingrained, or you're unable to convince management to refactor the code. These things happen. And when they do, documentation is the least you can do (cynical pun intended).
For one-off quirks (i.e. located on a single line or file), inline comments are the most easily noticed warnings. This ensures that developers who look at the quirky code are immediately alerted of the quirk.
If the quirks are endemic to the architecture and thus spread across an entire layer (or worse; multiple layers), inline comments don't cut it. You don't want to pepper them across your codebase.
Here, it becomes more appropriate to have a **developer guideline** for the project which outlines common pitfalls (among other things). Arseni's answer calls this an "architecture document" but the gist is the same.
As a consultant, I tend to write these guidelines for projects where I'm unable to assist development or review the code on an ongoing basis (whether it be a limited contract duration or other responsibilities). The document contains more than just pitfalls, but the overall purpose of the content is to steer developers in the right direction in regards to implementation, separation of responsibilities over multiple layers, dependencies and the aforementioned quirks, pitfalls and FAQ.
This may seem like overkill, but in my job context I'm often writing these for teams where bad practice is the norm or teams that struggle with consistency and/or good practice guidelines. Given your situation of having *"lots of small little things that cause headaches and frustrations in code, configuration, and testing"*, that is not too dissimilar and similar documentation may be warranted if you cannot continuously rely on the guiding hand of a more experienced developer/reviewer to avoid the quirks. |
71,398,009 | I have a Python script using Brownie that occasionally triggers a swap on Uniswap by sending a transaction to Optimism Network.
It worked well for a few days (did multiple transactions successfully), but now each time it triggers a transaction, I get an error message:
>
> TransactionError: Tx dropped without known replacement
>
>
>

However, the transaction goes through and get validated, but the script stops.
```js
swap_router = interface.ISwapRouter(router_address)
params = (
weth_address,
dai_address,
3000,
account.address,
time.time() + 86400,
amount * 10 ** 18,
0,
0,
)
amountOut = swap_router.exactInputSingle(params, {"from": account})
``` | 2022/03/08 | [
"https://Stackoverflow.com/questions/71398009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18410235/"
] | There is a possibility that one of your methods seeks data off-chain and is being called prematurely before the confirmation is received.
I had the same problem, and I managed to sort it out by adding
time.sleep(60)
at the end of the function that seeks for data off-chain | "Dropped and replaced" means the transaction is being replaced by a new one, Eth is being overloaded with a new gas fee. My guess is that you need to increase your gas costs in order to average the price. |
70,900,373 | Like in this example, <https://www.duden.de/rechtschreibung/Regen_Niederschlag> , the words are sorted in the following way:
"regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbö, Regenbogen..."
that is, it is a "more non-case-sensitive" sorting than Collections.Sort() automatically does. Lowercase words come before uppercase ones like "regen, Regen".
```
ArrayList<String> regen = new ArrayList<String>( );
for(String x : new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit",
"regen", "Regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen"}) {
regen.add(x);
}
```
Collections.sort(regen) response:
`[Regelwidrigkeit, Regelzeit, Regen, Regenabflussrohr, Regenanlage, Regenbogen, Regenbö,`
`regelwidrig, regen, regenarm]// lowercase at the end`
I can implement a comparator for this, but I'd rather take one-liner of code to get this way of sorting. Such as:
Collections.SomeMethod(regen); or Collections.Sort(regen, some\_extra\_parameter);
But I haven't found after deep google search, unfortunately. | 2022/01/28 | [
"https://Stackoverflow.com/questions/70900373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17677104/"
] | * You can use `String.CASE_INSENSITIVE_ORDER` to order strings in case-insensitive way.
* If you also at the same time want to farther specify order of elements which current comparator considers as equal (like `String.CASE_INSENSITIVE_ORDER` would do for `"Regen"` and `"regen"`) then you can use [`Comparator#thenComparing`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Comparator.html#thenComparing(java.util.Comparator)) method and pass to it Comparator which would sort those equal elements like you want.
+ Assuming you would also want to order `"Regen", "regen"` as `"regen", "Regen"` (lower-case before upper-case) you can simply reverse their natural order with `Comparator.reverseOrder()`.
So your code can look like:
```
regen.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.reverseOrder()));
```
Demo:
```
ArrayList<String> regen = new ArrayList<String>(
Arrays.asList("regelwidrig", "Regelwidrigkeit", "Regelzeit",
"Regen", "regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen")
);
regen.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.reverseOrder()));
System.out.println(regen);
```
Result: `[regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbogen, Regenbö]`
(notice `"Regen"`, `"regen"` ware swapped) | Just use a oneliner "Comparator.comparing"
```
List<String> regen = new ArrayList<String>( );
for(String x : new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit",
"regen", "Regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen"}) {
regen.add(x);
}
Collections.sort(regen, Comparator.comparing(s -> s.toLowerCase()));
System.out.println(regen);
```
Result will be:
regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbogen, Regenbö |
70,900,373 | Like in this example, <https://www.duden.de/rechtschreibung/Regen_Niederschlag> , the words are sorted in the following way:
"regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbö, Regenbogen..."
that is, it is a "more non-case-sensitive" sorting than Collections.Sort() automatically does. Lowercase words come before uppercase ones like "regen, Regen".
```
ArrayList<String> regen = new ArrayList<String>( );
for(String x : new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit",
"regen", "Regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen"}) {
regen.add(x);
}
```
Collections.sort(regen) response:
`[Regelwidrigkeit, Regelzeit, Regen, Regenabflussrohr, Regenanlage, Regenbogen, Regenbö,`
`regelwidrig, regen, regenarm]// lowercase at the end`
I can implement a comparator for this, but I'd rather take one-liner of code to get this way of sorting. Such as:
Collections.SomeMethod(regen); or Collections.Sort(regen, some\_extra\_parameter);
But I haven't found after deep google search, unfortunately. | 2022/01/28 | [
"https://Stackoverflow.com/questions/70900373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17677104/"
] | Just use a oneliner "Comparator.comparing"
```
List<String> regen = new ArrayList<String>( );
for(String x : new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit",
"regen", "Regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen"}) {
regen.add(x);
}
Collections.sort(regen, Comparator.comparing(s -> s.toLowerCase()));
System.out.println(regen);
```
Result will be:
regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbogen, Regenbö | The reason why strings are sorted the way they are naturally sorted is because the ASCII values for these characters have a lower value for *UPPERCASE* than for *lowercase*. In this case, all words starts with "R" and the ASCII value of uppercase "R" is 82 (52 hex), whereas lowercase "R" is 114 (72 hex). For that reason, `Regen` will precede `regen` when sorting in natural order (in Java).
So, using plain Java
```
public static void main(String[] args) {
List<String> words = Arrays.asList(new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit", "regen", "Regen", "Regenabflussrohr", "Regenanlage", "regenarm", "Regenbö", "Regenbogen"});
Collections.sort(words);
System.out.println(words);
}
```
Will output
```
[Regelwidrigkeit, Regelzeit, Regen, Regenabflussrohr, Regenanlage, Regenbogen, Regenbö, regelwidrig, regen, regenarm]
```
As you can see, all words starts with "R", but sorting puts all capitalized words ahead of ones that start with lowercase.
As @Pshemo indicated in his answer, you can (should) code your comparator account for case sensitivity and to reverse the order of lowercase vs uppercase as needed. |
70,900,373 | Like in this example, <https://www.duden.de/rechtschreibung/Regen_Niederschlag> , the words are sorted in the following way:
"regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbö, Regenbogen..."
that is, it is a "more non-case-sensitive" sorting than Collections.Sort() automatically does. Lowercase words come before uppercase ones like "regen, Regen".
```
ArrayList<String> regen = new ArrayList<String>( );
for(String x : new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit",
"regen", "Regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen"}) {
regen.add(x);
}
```
Collections.sort(regen) response:
`[Regelwidrigkeit, Regelzeit, Regen, Regenabflussrohr, Regenanlage, Regenbogen, Regenbö,`
`regelwidrig, regen, regenarm]// lowercase at the end`
I can implement a comparator for this, but I'd rather take one-liner of code to get this way of sorting. Such as:
Collections.SomeMethod(regen); or Collections.Sort(regen, some\_extra\_parameter);
But I haven't found after deep google search, unfortunately. | 2022/01/28 | [
"https://Stackoverflow.com/questions/70900373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17677104/"
] | Collators
=========
Use the `Collator` class for locale-sensitive `String` comparison.
Specifically, Java has support for German [collators](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/Collator.html):
```
Collator collator = Collator.getInstance(Locale.GERMAN);
regen.sort(collator);
```
Example:
```
List<String> inputs = new ArrayList <>(
List.of( "regelwidrig", "Java", "Regelwidrigkeit", "Regelzeit", "regen", "Regen", "Regenabflussrohr", "Regenanlage", "regenarm", "Regenbö", "Regenbogen" )
);
inputs.sort( java.text.Collator.getInstance( Locale.GERMAN ) ) ;
```
>
> [Java, regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbö, Regenbogen]
>
>
> | Just use a oneliner "Comparator.comparing"
```
List<String> regen = new ArrayList<String>( );
for(String x : new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit",
"regen", "Regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen"}) {
regen.add(x);
}
Collections.sort(regen, Comparator.comparing(s -> s.toLowerCase()));
System.out.println(regen);
```
Result will be:
regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbogen, Regenbö |
70,900,373 | Like in this example, <https://www.duden.de/rechtschreibung/Regen_Niederschlag> , the words are sorted in the following way:
"regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbö, Regenbogen..."
that is, it is a "more non-case-sensitive" sorting than Collections.Sort() automatically does. Lowercase words come before uppercase ones like "regen, Regen".
```
ArrayList<String> regen = new ArrayList<String>( );
for(String x : new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit",
"regen", "Regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen"}) {
regen.add(x);
}
```
Collections.sort(regen) response:
`[Regelwidrigkeit, Regelzeit, Regen, Regenabflussrohr, Regenanlage, Regenbogen, Regenbö,`
`regelwidrig, regen, regenarm]// lowercase at the end`
I can implement a comparator for this, but I'd rather take one-liner of code to get this way of sorting. Such as:
Collections.SomeMethod(regen); or Collections.Sort(regen, some\_extra\_parameter);
But I haven't found after deep google search, unfortunately. | 2022/01/28 | [
"https://Stackoverflow.com/questions/70900373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17677104/"
] | * You can use `String.CASE_INSENSITIVE_ORDER` to order strings in case-insensitive way.
* If you also at the same time want to farther specify order of elements which current comparator considers as equal (like `String.CASE_INSENSITIVE_ORDER` would do for `"Regen"` and `"regen"`) then you can use [`Comparator#thenComparing`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Comparator.html#thenComparing(java.util.Comparator)) method and pass to it Comparator which would sort those equal elements like you want.
+ Assuming you would also want to order `"Regen", "regen"` as `"regen", "Regen"` (lower-case before upper-case) you can simply reverse their natural order with `Comparator.reverseOrder()`.
So your code can look like:
```
regen.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.reverseOrder()));
```
Demo:
```
ArrayList<String> regen = new ArrayList<String>(
Arrays.asList("regelwidrig", "Regelwidrigkeit", "Regelzeit",
"Regen", "regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen")
);
regen.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.reverseOrder()));
System.out.println(regen);
```
Result: `[regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbogen, Regenbö]`
(notice `"Regen"`, `"regen"` ware swapped) | The reason why strings are sorted the way they are naturally sorted is because the ASCII values for these characters have a lower value for *UPPERCASE* than for *lowercase*. In this case, all words starts with "R" and the ASCII value of uppercase "R" is 82 (52 hex), whereas lowercase "R" is 114 (72 hex). For that reason, `Regen` will precede `regen` when sorting in natural order (in Java).
So, using plain Java
```
public static void main(String[] args) {
List<String> words = Arrays.asList(new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit", "regen", "Regen", "Regenabflussrohr", "Regenanlage", "regenarm", "Regenbö", "Regenbogen"});
Collections.sort(words);
System.out.println(words);
}
```
Will output
```
[Regelwidrigkeit, Regelzeit, Regen, Regenabflussrohr, Regenanlage, Regenbogen, Regenbö, regelwidrig, regen, regenarm]
```
As you can see, all words starts with "R", but sorting puts all capitalized words ahead of ones that start with lowercase.
As @Pshemo indicated in his answer, you can (should) code your comparator account for case sensitivity and to reverse the order of lowercase vs uppercase as needed. |
70,900,373 | Like in this example, <https://www.duden.de/rechtschreibung/Regen_Niederschlag> , the words are sorted in the following way:
"regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbö, Regenbogen..."
that is, it is a "more non-case-sensitive" sorting than Collections.Sort() automatically does. Lowercase words come before uppercase ones like "regen, Regen".
```
ArrayList<String> regen = new ArrayList<String>( );
for(String x : new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit",
"regen", "Regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen"}) {
regen.add(x);
}
```
Collections.sort(regen) response:
`[Regelwidrigkeit, Regelzeit, Regen, Regenabflussrohr, Regenanlage, Regenbogen, Regenbö,`
`regelwidrig, regen, regenarm]// lowercase at the end`
I can implement a comparator for this, but I'd rather take one-liner of code to get this way of sorting. Such as:
Collections.SomeMethod(regen); or Collections.Sort(regen, some\_extra\_parameter);
But I haven't found after deep google search, unfortunately. | 2022/01/28 | [
"https://Stackoverflow.com/questions/70900373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17677104/"
] | * You can use `String.CASE_INSENSITIVE_ORDER` to order strings in case-insensitive way.
* If you also at the same time want to farther specify order of elements which current comparator considers as equal (like `String.CASE_INSENSITIVE_ORDER` would do for `"Regen"` and `"regen"`) then you can use [`Comparator#thenComparing`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Comparator.html#thenComparing(java.util.Comparator)) method and pass to it Comparator which would sort those equal elements like you want.
+ Assuming you would also want to order `"Regen", "regen"` as `"regen", "Regen"` (lower-case before upper-case) you can simply reverse their natural order with `Comparator.reverseOrder()`.
So your code can look like:
```
regen.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.reverseOrder()));
```
Demo:
```
ArrayList<String> regen = new ArrayList<String>(
Arrays.asList("regelwidrig", "Regelwidrigkeit", "Regelzeit",
"Regen", "regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen")
);
regen.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.reverseOrder()));
System.out.println(regen);
```
Result: `[regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbogen, Regenbö]`
(notice `"Regen"`, `"regen"` ware swapped) | Collators
=========
Use the `Collator` class for locale-sensitive `String` comparison.
Specifically, Java has support for German [collators](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/Collator.html):
```
Collator collator = Collator.getInstance(Locale.GERMAN);
regen.sort(collator);
```
Example:
```
List<String> inputs = new ArrayList <>(
List.of( "regelwidrig", "Java", "Regelwidrigkeit", "Regelzeit", "regen", "Regen", "Regenabflussrohr", "Regenanlage", "regenarm", "Regenbö", "Regenbogen" )
);
inputs.sort( java.text.Collator.getInstance( Locale.GERMAN ) ) ;
```
>
> [Java, regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbö, Regenbogen]
>
>
> |
70,900,373 | Like in this example, <https://www.duden.de/rechtschreibung/Regen_Niederschlag> , the words are sorted in the following way:
"regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbö, Regenbogen..."
that is, it is a "more non-case-sensitive" sorting than Collections.Sort() automatically does. Lowercase words come before uppercase ones like "regen, Regen".
```
ArrayList<String> regen = new ArrayList<String>( );
for(String x : new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit",
"regen", "Regen", "Regenabflussrohr",
"Regenanlage", "regenarm", "Regenbö", "Regenbogen"}) {
regen.add(x);
}
```
Collections.sort(regen) response:
`[Regelwidrigkeit, Regelzeit, Regen, Regenabflussrohr, Regenanlage, Regenbogen, Regenbö,`
`regelwidrig, regen, regenarm]// lowercase at the end`
I can implement a comparator for this, but I'd rather take one-liner of code to get this way of sorting. Such as:
Collections.SomeMethod(regen); or Collections.Sort(regen, some\_extra\_parameter);
But I haven't found after deep google search, unfortunately. | 2022/01/28 | [
"https://Stackoverflow.com/questions/70900373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17677104/"
] | Collators
=========
Use the `Collator` class for locale-sensitive `String` comparison.
Specifically, Java has support for German [collators](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/Collator.html):
```
Collator collator = Collator.getInstance(Locale.GERMAN);
regen.sort(collator);
```
Example:
```
List<String> inputs = new ArrayList <>(
List.of( "regelwidrig", "Java", "Regelwidrigkeit", "Regelzeit", "regen", "Regen", "Regenabflussrohr", "Regenanlage", "regenarm", "Regenbö", "Regenbogen" )
);
inputs.sort( java.text.Collator.getInstance( Locale.GERMAN ) ) ;
```
>
> [Java, regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbö, Regenbogen]
>
>
> | The reason why strings are sorted the way they are naturally sorted is because the ASCII values for these characters have a lower value for *UPPERCASE* than for *lowercase*. In this case, all words starts with "R" and the ASCII value of uppercase "R" is 82 (52 hex), whereas lowercase "R" is 114 (72 hex). For that reason, `Regen` will precede `regen` when sorting in natural order (in Java).
So, using plain Java
```
public static void main(String[] args) {
List<String> words = Arrays.asList(new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit", "regen", "Regen", "Regenabflussrohr", "Regenanlage", "regenarm", "Regenbö", "Regenbogen"});
Collections.sort(words);
System.out.println(words);
}
```
Will output
```
[Regelwidrigkeit, Regelzeit, Regen, Regenabflussrohr, Regenanlage, Regenbogen, Regenbö, regelwidrig, regen, regenarm]
```
As you can see, all words starts with "R", but sorting puts all capitalized words ahead of ones that start with lowercase.
As @Pshemo indicated in his answer, you can (should) code your comparator account for case sensitivity and to reverse the order of lowercase vs uppercase as needed. |
548,798 | The exercise is to find the accumulation points of the set $S=\{(\frac {1} {n}, \frac {1} {m}) \space m, n \in \mathbb N\}$
I'm trying to prove that if $A$={accumulation points of the set $S$}, then $A=\{(0,0), (\frac {1} {n},0),(0,\frac {1} {m}) \space n,m \in \mathbb N\}$. I could prove that the set of the right side of the equality is included in $A$. I don't know how to prove the other inclusion, which means that if $x$ is an accumulation point of $S$, then $x$ has to be $(0,0)$, or of the form $(\frac {1} {n},0)$ or $(0,\frac {1} {m})$. | 2013/11/02 | [
"https://math.stackexchange.com/questions/548798",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/100106/"
] | I think you might mean $N\cap Z(G) \neq \{e\}$. In which case,
1. Use the Class equation
2. If $x\in N$, then the conjugacy class $C(x) \subset N$ | If $H$,$K$ are any subgroups of a group $G$, with identity $e$, then $H \setminus K \neq \langle e \rangle $, since $e \in H,K$ and hence $e \not\in H \setminus K $. Your question is a special case of that. |
10,131,208 | In my assets, I have a file called `maps.js.erb`, basically with only the following (debugging) content:
```
alert("<%= @map.width %>");
```
This JS file is loaded through the `show.html.erb` view belonging to maps.
```
<%= javascript_include_tag params[:controller] %>
<h1><%= @map.title %></h1>
…
```
The HTML file itself shows the map's title, e.g. when browsing to `/maps/1/`, since `@map` is defined in the controller. However, as soon as I include the JS file, I get the following error:
>
> ### NoMethodError in Maps#show
>
>
> Showing `…/app/views/maps/show.html.erb` where line #1 raised:
>
>
> undefined method 'title' for nil:NilClass
> (in `…/app/assets/javascripts/maps.js.erb`)
>
>
>
* Why is `@map` not available in the `js.erb` file?
* How else can I access this instance variable defined in my controller? | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/435093/"
] | Ryan Bates did a screencast right on that topic - you might wanna check it out:
<http://railscasts.com/episodes/324-passing-data-to-javascript>
---
In the `html.erb` file, you can define the variables:
```
<%= javascript_tag do %>
window.productsURL = "<%=j products_url %>";
window.products = <%=raw Product.limit(10).to_json %>;
<% end %>
``` | You cannot have @map.title evaluated in a common js file, because that file is generated and served once, before later invokations of the controller, and then cached.
However, you can have javascript in your HTML page. That javascript can be generated with a constant value supplied by <%= @map.title %>.
Put the javascript in a partial, and render it in a tag in your page.
I have seen Bank of America do this in their web site. They generate all the account transactions in a javascript array on the page. |
10,131,208 | In my assets, I have a file called `maps.js.erb`, basically with only the following (debugging) content:
```
alert("<%= @map.width %>");
```
This JS file is loaded through the `show.html.erb` view belonging to maps.
```
<%= javascript_include_tag params[:controller] %>
<h1><%= @map.title %></h1>
…
```
The HTML file itself shows the map's title, e.g. when browsing to `/maps/1/`, since `@map` is defined in the controller. However, as soon as I include the JS file, I get the following error:
>
> ### NoMethodError in Maps#show
>
>
> Showing `…/app/views/maps/show.html.erb` where line #1 raised:
>
>
> undefined method 'title' for nil:NilClass
> (in `…/app/assets/javascripts/maps.js.erb`)
>
>
>
* Why is `@map` not available in the `js.erb` file?
* How else can I access this instance variable defined in my controller? | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/435093/"
] | Ryan Bates did a screencast right on that topic - you might wanna check it out:
<http://railscasts.com/episodes/324-passing-data-to-javascript>
---
In the `html.erb` file, you can define the variables:
```
<%= javascript_tag do %>
window.productsURL = "<%=j products_url %>";
window.products = <%=raw Product.limit(10).to_json %>;
<% end %>
``` | Don't forget to use `escape_javascript()`. |
10,131,208 | In my assets, I have a file called `maps.js.erb`, basically with only the following (debugging) content:
```
alert("<%= @map.width %>");
```
This JS file is loaded through the `show.html.erb` view belonging to maps.
```
<%= javascript_include_tag params[:controller] %>
<h1><%= @map.title %></h1>
…
```
The HTML file itself shows the map's title, e.g. when browsing to `/maps/1/`, since `@map` is defined in the controller. However, as soon as I include the JS file, I get the following error:
>
> ### NoMethodError in Maps#show
>
>
> Showing `…/app/views/maps/show.html.erb` where line #1 raised:
>
>
> undefined method 'title' for nil:NilClass
> (in `…/app/assets/javascripts/maps.js.erb`)
>
>
>
* Why is `@map` not available in the `js.erb` file?
* How else can I access this instance variable defined in my controller? | 2012/04/12 | [
"https://Stackoverflow.com/questions/10131208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/435093/"
] | You cannot have @map.title evaluated in a common js file, because that file is generated and served once, before later invokations of the controller, and then cached.
However, you can have javascript in your HTML page. That javascript can be generated with a constant value supplied by <%= @map.title %>.
Put the javascript in a partial, and render it in a tag in your page.
I have seen Bank of America do this in their web site. They generate all the account transactions in a javascript array on the page. | Don't forget to use `escape_javascript()`. |
57,708 | I can imagine that finding $p,q,n$ are easy, but my text book also says the $e$ can be found rapidly, so how does modern RSA find this $e$?
 | 2018/03/22 | [
"https://crypto.stackexchange.com/questions/57708",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/-1/"
] | A simple way to achieve this with common algorithms would be to do the following:
1. Choose a random key (key)
2. Encrypt the data using the random key (encrData)
3. Hash the encrypted data (encrHash)
4. Xor the key and the hash (xorKey)
5. The result data would be the encrypted data + the Xor key (encrData+xorKey)
To reverse:
1. Split the data into encrData+xorKey
2. Hash the encrypted data (encrHash)
3. Xor the xorKey with the encrHash Because the way xor works this reverses the process above (key)
4. Decrypt the data with the key
If needed base64 the encrypted data to produce string form
With this scheme you will need the entire string to decrypt the data and can use any secure algorithm (ex AES and SHA256) | Let's take the simplest cipher I can think of which the key is not obvious: [ROT13](https://en.wikipedia.org/wiki/ROT13). You replace a letter with the 13th letter after it, in the alphabet. Because there are 26 letters in the alphabet, you don't need to inverse the algorithm for decryption. Is ROT13 an example of keyless encryption, a very weak one of course? No, because 13 is your key. I don't think any algorithm that can be expressed with a computer can be keyless.
Another bizarre example of which the key is not obvious is a language. Obscure languages have been used as a form of encryption. The most famous example are the [code talkers](https://en.wikipedia.org/wiki/Code_talker) of World War II. Navajo was an unwritten language at that time and the only way to encrypt a message was using your language skills and your mouth. You decrypted a message using your ears, your language skills, and pen and paper. So is this form of encryption keyless? To answer that question, we have to know if this algorithm can be expressed by a computer. There is no way for a computer to translate English to Navajo right now, but there are services that can translate English to Chinese and vice versa. If we trained a language model that could automatically translate English to Navajo using a computer, that model would be your key.
So this answer doesn't ultimatively exclude any form of keyless encryption might exist. I just had a look at some encryption topics not covered by RFC or NIST and I don't think it's possible for keyless encryption to exist. |
57,708 | I can imagine that finding $p,q,n$ are easy, but my text book also says the $e$ can be found rapidly, so how does modern RSA find this $e$?
 | 2018/03/22 | [
"https://crypto.stackexchange.com/questions/57708",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/-1/"
] | A simple way to achieve this with common algorithms would be to do the following:
1. Choose a random key (key)
2. Encrypt the data using the random key (encrData)
3. Hash the encrypted data (encrHash)
4. Xor the key and the hash (xorKey)
5. The result data would be the encrypted data + the Xor key (encrData+xorKey)
To reverse:
1. Split the data into encrData+xorKey
2. Hash the encrypted data (encrHash)
3. Xor the xorKey with the encrHash Because the way xor works this reverses the process above (key)
4. Decrypt the data with the key
If needed base64 the encrypted data to produce string form
With this scheme you will need the entire string to decrypt the data and can use any secure algorithm (ex AES and SHA256) | I believe this can be achieved, but of course you need to secure both of your encryption and decryption algorithms. Hide it on a very secure server with a rest endpoint where authentication is needed to be able to use the rest service. so to use the algorithm you need to send authenticated requests to your secure endpoint. Also dont forget to obfusicate your production codes.
If you are new to writing encryption algorithm you can start by learning som simple trans table encoding just to get a start.
Your key will be mathematics and with the use of strong psuedo random number generators. So if you store all results in a database, be sure to use encryption and not pure encodings cause it will be easy to crack.
Why not try to create a random number generator too while your at it. If you can calculate the n^x decimal of sqrt(2) or Pi, or some othe irrational number you can create your own deviation to produce a strong non standard prn.
If you belive your encryption is strong enough try to give a sample of x number of pure values and the values of the encryption to see if anyone can crack them.
And lastly don’t take my word on any of this Im just a noob, with an imagination that I know something I dont, I do other stuff for a living. |
57,708 | I can imagine that finding $p,q,n$ are easy, but my text book also says the $e$ can be found rapidly, so how does modern RSA find this $e$?
 | 2018/03/22 | [
"https://crypto.stackexchange.com/questions/57708",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/-1/"
] | [OAEP](https://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding) - Optimal Asymmetric Encryption Padding may be what you want.
In RSA public-key encryption system, in order to prevent partial decryption, OAEP padding is used. In essence, it's a Feistel network with randomizing element.
When used alone, it can ensure no partial information can be derived from any partial information, but when the whole message is available, it's trivial.
In your case, this is no longer encryption - it's secret sharing.
[Related link](https://en.wikipedia.org/wiki/All-or-nothing_transform) | One-time pad it
===============
Given the following conditions...
* [Alice](https://en.wikipedia.org/wiki/Alice_and_Bob) has a plain-text. She wants to encrypt that.
* After encrypting it, Alice obtains several cipher-texts.
* Alice wants to give the cipher-texts to people that are not authorised to read the plain-text. None of them shall be able to decipher the cipher-text on their own.
* If all the people that have the cipher-texts give them back to Alice, Alice must be able to reconstruct the plain-text.
This is easy: **use a [One-time pad](https://en.wikipedia.org/wiki/One-time_pad)**.
1. Alice creates a key (K1) of the same length as the plain-text.
2. Alice XORs the plain-text with the key, she gets C1.
3. Alice gives K1 to Bob and C1 to Carol.
Unless Bob and Carol are in cahoots, neither can reconstruct the message. When both of them give the key and cipher-text back to Alice, Alice only needs to XOR them together to get the plain-text back.
Expanding
=========
Alice wants better security and involves Dave and Erin. The algorithm becomes:
1. Alice creates a key (K1) of the same length as the plain-text.
2. Alice XORs the plain-text with K1, she gets C1.
3. Alice gives K1 to Bob.
4. Alice repeats 1, 2 and 3, applies K2 on C1, and gets C2. She gives K2 to Carol.
5. Alice repeats 5, to get K3 and C3. She gives K3 to Dave.
6. Alice gives C3 to Erin.
This can be repeated as many times as Alice likes.
There is some fragility in this as Alice needs to get the key/cipher back from **everyone** before she can get her plain-text back. But this is a problem for another post. |
57,708 | I can imagine that finding $p,q,n$ are easy, but my text book also says the $e$ can be found rapidly, so how does modern RSA find this $e$?
 | 2018/03/22 | [
"https://crypto.stackexchange.com/questions/57708",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/-1/"
] | [OAEP](https://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding) - Optimal Asymmetric Encryption Padding may be what you want.
In RSA public-key encryption system, in order to prevent partial decryption, OAEP padding is used. In essence, it's a Feistel network with randomizing element.
When used alone, it can ensure no partial information can be derived from any partial information, but when the whole message is available, it's trivial.
In your case, this is no longer encryption - it's secret sharing.
[Related link](https://en.wikipedia.org/wiki/All-or-nothing_transform) | I believe this can be achieved, but of course you need to secure both of your encryption and decryption algorithms. Hide it on a very secure server with a rest endpoint where authentication is needed to be able to use the rest service. so to use the algorithm you need to send authenticated requests to your secure endpoint. Also dont forget to obfusicate your production codes.
If you are new to writing encryption algorithm you can start by learning som simple trans table encoding just to get a start.
Your key will be mathematics and with the use of strong psuedo random number generators. So if you store all results in a database, be sure to use encryption and not pure encodings cause it will be easy to crack.
Why not try to create a random number generator too while your at it. If you can calculate the n^x decimal of sqrt(2) or Pi, or some othe irrational number you can create your own deviation to produce a strong non standard prn.
If you belive your encryption is strong enough try to give a sample of x number of pure values and the values of the encryption to see if anyone can crack them.
And lastly don’t take my word on any of this Im just a noob, with an imagination that I know something I dont, I do other stuff for a living. |
57,708 | I can imagine that finding $p,q,n$ are easy, but my text book also says the $e$ can be found rapidly, so how does modern RSA find this $e$?
 | 2018/03/22 | [
"https://crypto.stackexchange.com/questions/57708",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/-1/"
] | Secret Sharing may be another option to consider. It allows you to take a value, break it up into arbitrarily many pieces, and possession of a subset of these pieces, not the entire set, makes reconstruction of the original value impossible. This is done by multiple means, the simplest of which is with respect to additive secret sharing. Given a secret value $x$, $m$ shares of $x$ in a group $Z\_N$ may be generated by selecting $m-1$ random values and assigning them to shares $$\forall i \in \{1,\dots,m-1\},[x]\_N^{P\_i}\in\_RZ\_N $$ The final share satisfies the equation
$$[x]\_N^{P\_m}=(x-\sum\_{i=1}^{m-1}[x]\_N^{P\_i})\mod N$$
This way every share is uniform random and is secure in an information theoretic sense. Additionally, this holds up to an individual possessing any $m-1$ magnitude subset of shares. Only possession of all $m$ shares will allow the original secret to be reconstructed, and this holds without respect to assumptions or limitations on computational power. If an individual does posess all $m$ shares, reconstruction of the secret is very easy since:
$$x=(\sum\_{i=1}^{m}[x]\_N^{P\_i})\mod N$$ | One-time pad it
===============
Given the following conditions...
* [Alice](https://en.wikipedia.org/wiki/Alice_and_Bob) has a plain-text. She wants to encrypt that.
* After encrypting it, Alice obtains several cipher-texts.
* Alice wants to give the cipher-texts to people that are not authorised to read the plain-text. None of them shall be able to decipher the cipher-text on their own.
* If all the people that have the cipher-texts give them back to Alice, Alice must be able to reconstruct the plain-text.
This is easy: **use a [One-time pad](https://en.wikipedia.org/wiki/One-time_pad)**.
1. Alice creates a key (K1) of the same length as the plain-text.
2. Alice XORs the plain-text with the key, she gets C1.
3. Alice gives K1 to Bob and C1 to Carol.
Unless Bob and Carol are in cahoots, neither can reconstruct the message. When both of them give the key and cipher-text back to Alice, Alice only needs to XOR them together to get the plain-text back.
Expanding
=========
Alice wants better security and involves Dave and Erin. The algorithm becomes:
1. Alice creates a key (K1) of the same length as the plain-text.
2. Alice XORs the plain-text with K1, she gets C1.
3. Alice gives K1 to Bob.
4. Alice repeats 1, 2 and 3, applies K2 on C1, and gets C2. She gives K2 to Carol.
5. Alice repeats 5, to get K3 and C3. She gives K3 to Dave.
6. Alice gives C3 to Erin.
This can be repeated as many times as Alice likes.
There is some fragility in this as Alice needs to get the key/cipher back from **everyone** before she can get her plain-text back. But this is a problem for another post. |
57,708 | I can imagine that finding $p,q,n$ are easy, but my text book also says the $e$ can be found rapidly, so how does modern RSA find this $e$?
 | 2018/03/22 | [
"https://crypto.stackexchange.com/questions/57708",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/-1/"
] | Secret Sharing may be another option to consider. It allows you to take a value, break it up into arbitrarily many pieces, and possession of a subset of these pieces, not the entire set, makes reconstruction of the original value impossible. This is done by multiple means, the simplest of which is with respect to additive secret sharing. Given a secret value $x$, $m$ shares of $x$ in a group $Z\_N$ may be generated by selecting $m-1$ random values and assigning them to shares $$\forall i \in \{1,\dots,m-1\},[x]\_N^{P\_i}\in\_RZ\_N $$ The final share satisfies the equation
$$[x]\_N^{P\_m}=(x-\sum\_{i=1}^{m-1}[x]\_N^{P\_i})\mod N$$
This way every share is uniform random and is secure in an information theoretic sense. Additionally, this holds up to an individual possessing any $m-1$ magnitude subset of shares. Only possession of all $m$ shares will allow the original secret to be reconstructed, and this holds without respect to assumptions or limitations on computational power. If an individual does posess all $m$ shares, reconstruction of the secret is very easy since:
$$x=(\sum\_{i=1}^{m}[x]\_N^{P\_i})\mod N$$ | The "key" is secret data that are used in encryption with known "algorithm". Of course you can make keyless algorithm - get permutation, shifting stuff around, bit inversion, whatever. Employ any known strong encryption with built-in values. Mix and match all you want! However, this effectively makes algorithm itself the key. Once someone has access to your encryptor/decryptor and/or any built-in values, they don't need to know any additional data - which is ENTIRE REASON for separate key - and can decrypt whatever they want.
Incidentally that's primary and inevitable point of failure of futile attempts for DRM. |
57,708 | I can imagine that finding $p,q,n$ are easy, but my text book also says the $e$ can be found rapidly, so how does modern RSA find this $e$?
 | 2018/03/22 | [
"https://crypto.stackexchange.com/questions/57708",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/-1/"
] | Clarification
-------------
>
> I'm wondering whether there exists an encoding/hashing/encryption scheme whereby the original string can always be derived in its entirety given the entire encoded/hashed/encrypted string, and nothing else (no key/password). But also, no portion of the original string can be derived given any portion of the encoded/hashed/encrypted string.
>
>
>
I am assuming that "no portion of the original string can be derived given any portion of the encoded/hashed/encrypted string" means "no portion of the original string can be derived given anything less than the entire encoded/hashed/encrypted string", otherwise the question would be self-contradictory.
Answer
------
It sounds like you are looking for a permutation. A permutation is an invertible transformation on a fixed-size set of blocks. If your input is larger, the/an [All-Or-Nothing Transform](https://en.wikipedia.org/wiki/All-or-nothing_transform) may be useful. The OAEP mentioned by @DannyNiu is an example of an AONT.
For example, many block ciphers are built by interleaving applications of a permutation with the addition of secret key material. The permutation provides diffusion, which ensures that if you modify any part of the output then attempt to invert it, you end up back at a completely different input.
If you simply strip the key addition portion from a block cipher, it should also do what you're asking. For example, [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) consists of subBytes, mixColumns, shiftRows, and addRoundKey. If you were to omit the addRoundkey operation, you would be left with a fixed permutation that provides the required avalanche effect and some degree of unpredictability. Another example of a permutation is [keccak-f](https://en.wikipedia.org/wiki/Keccak#The_block_permutation), which does the mixing for the [SHA3 algorithm](http://en.wikipedia.org/wiki/Keccak).
A key-less permutation does not provide encryption
--------------------------------------------------
Note that such a construction with no key is no longer providing *encryption*, as it is not possible to provide confidentiality of the message without some kind of secrecy, which is what the key provides. If anyone who has an input message can compute an output "ciphertext", or anyone who has an output "ciphertext" can invert it to the input message, then clearly confidentiality of the input cannot be achieved.
You tagged this question with "encoding", so perhaps confidentiality is not required in your use case. You would need to establish what you need this construction for and whether or not this is an issue. | Let's take the simplest cipher I can think of which the key is not obvious: [ROT13](https://en.wikipedia.org/wiki/ROT13). You replace a letter with the 13th letter after it, in the alphabet. Because there are 26 letters in the alphabet, you don't need to inverse the algorithm for decryption. Is ROT13 an example of keyless encryption, a very weak one of course? No, because 13 is your key. I don't think any algorithm that can be expressed with a computer can be keyless.
Another bizarre example of which the key is not obvious is a language. Obscure languages have been used as a form of encryption. The most famous example are the [code talkers](https://en.wikipedia.org/wiki/Code_talker) of World War II. Navajo was an unwritten language at that time and the only way to encrypt a message was using your language skills and your mouth. You decrypted a message using your ears, your language skills, and pen and paper. So is this form of encryption keyless? To answer that question, we have to know if this algorithm can be expressed by a computer. There is no way for a computer to translate English to Navajo right now, but there are services that can translate English to Chinese and vice versa. If we trained a language model that could automatically translate English to Navajo using a computer, that model would be your key.
So this answer doesn't ultimatively exclude any form of keyless encryption might exist. I just had a look at some encryption topics not covered by RFC or NIST and I don't think it's possible for keyless encryption to exist. |
57,708 | I can imagine that finding $p,q,n$ are easy, but my text book also says the $e$ can be found rapidly, so how does modern RSA find this $e$?
 | 2018/03/22 | [
"https://crypto.stackexchange.com/questions/57708",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/-1/"
] | The "key" is secret data that are used in encryption with known "algorithm". Of course you can make keyless algorithm - get permutation, shifting stuff around, bit inversion, whatever. Employ any known strong encryption with built-in values. Mix and match all you want! However, this effectively makes algorithm itself the key. Once someone has access to your encryptor/decryptor and/or any built-in values, they don't need to know any additional data - which is ENTIRE REASON for separate key - and can decrypt whatever they want.
Incidentally that's primary and inevitable point of failure of futile attempts for DRM. | One-time pad it
===============
Given the following conditions...
* [Alice](https://en.wikipedia.org/wiki/Alice_and_Bob) has a plain-text. She wants to encrypt that.
* After encrypting it, Alice obtains several cipher-texts.
* Alice wants to give the cipher-texts to people that are not authorised to read the plain-text. None of them shall be able to decipher the cipher-text on their own.
* If all the people that have the cipher-texts give them back to Alice, Alice must be able to reconstruct the plain-text.
This is easy: **use a [One-time pad](https://en.wikipedia.org/wiki/One-time_pad)**.
1. Alice creates a key (K1) of the same length as the plain-text.
2. Alice XORs the plain-text with the key, she gets C1.
3. Alice gives K1 to Bob and C1 to Carol.
Unless Bob and Carol are in cahoots, neither can reconstruct the message. When both of them give the key and cipher-text back to Alice, Alice only needs to XOR them together to get the plain-text back.
Expanding
=========
Alice wants better security and involves Dave and Erin. The algorithm becomes:
1. Alice creates a key (K1) of the same length as the plain-text.
2. Alice XORs the plain-text with K1, she gets C1.
3. Alice gives K1 to Bob.
4. Alice repeats 1, 2 and 3, applies K2 on C1, and gets C2. She gives K2 to Carol.
5. Alice repeats 5, to get K3 and C3. She gives K3 to Dave.
6. Alice gives C3 to Erin.
This can be repeated as many times as Alice likes.
There is some fragility in this as Alice needs to get the key/cipher back from **everyone** before she can get her plain-text back. But this is a problem for another post. |
57,708 | I can imagine that finding $p,q,n$ are easy, but my text book also says the $e$ can be found rapidly, so how does modern RSA find this $e$?
 | 2018/03/22 | [
"https://crypto.stackexchange.com/questions/57708",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/-1/"
] | Clarification
-------------
>
> I'm wondering whether there exists an encoding/hashing/encryption scheme whereby the original string can always be derived in its entirety given the entire encoded/hashed/encrypted string, and nothing else (no key/password). But also, no portion of the original string can be derived given any portion of the encoded/hashed/encrypted string.
>
>
>
I am assuming that "no portion of the original string can be derived given any portion of the encoded/hashed/encrypted string" means "no portion of the original string can be derived given anything less than the entire encoded/hashed/encrypted string", otherwise the question would be self-contradictory.
Answer
------
It sounds like you are looking for a permutation. A permutation is an invertible transformation on a fixed-size set of blocks. If your input is larger, the/an [All-Or-Nothing Transform](https://en.wikipedia.org/wiki/All-or-nothing_transform) may be useful. The OAEP mentioned by @DannyNiu is an example of an AONT.
For example, many block ciphers are built by interleaving applications of a permutation with the addition of secret key material. The permutation provides diffusion, which ensures that if you modify any part of the output then attempt to invert it, you end up back at a completely different input.
If you simply strip the key addition portion from a block cipher, it should also do what you're asking. For example, [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) consists of subBytes, mixColumns, shiftRows, and addRoundKey. If you were to omit the addRoundkey operation, you would be left with a fixed permutation that provides the required avalanche effect and some degree of unpredictability. Another example of a permutation is [keccak-f](https://en.wikipedia.org/wiki/Keccak#The_block_permutation), which does the mixing for the [SHA3 algorithm](http://en.wikipedia.org/wiki/Keccak).
A key-less permutation does not provide encryption
--------------------------------------------------
Note that such a construction with no key is no longer providing *encryption*, as it is not possible to provide confidentiality of the message without some kind of secrecy, which is what the key provides. If anyone who has an input message can compute an output "ciphertext", or anyone who has an output "ciphertext" can invert it to the input message, then clearly confidentiality of the input cannot be achieved.
You tagged this question with "encoding", so perhaps confidentiality is not required in your use case. You would need to establish what you need this construction for and whether or not this is an issue. | A simple way to achieve this with common algorithms would be to do the following:
1. Choose a random key (key)
2. Encrypt the data using the random key (encrData)
3. Hash the encrypted data (encrHash)
4. Xor the key and the hash (xorKey)
5. The result data would be the encrypted data + the Xor key (encrData+xorKey)
To reverse:
1. Split the data into encrData+xorKey
2. Hash the encrypted data (encrHash)
3. Xor the xorKey with the encrHash Because the way xor works this reverses the process above (key)
4. Decrypt the data with the key
If needed base64 the encrypted data to produce string form
With this scheme you will need the entire string to decrypt the data and can use any secure algorithm (ex AES and SHA256) |
57,708 | I can imagine that finding $p,q,n$ are easy, but my text book also says the $e$ can be found rapidly, so how does modern RSA find this $e$?
 | 2018/03/22 | [
"https://crypto.stackexchange.com/questions/57708",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/-1/"
] | Clarification
-------------
>
> I'm wondering whether there exists an encoding/hashing/encryption scheme whereby the original string can always be derived in its entirety given the entire encoded/hashed/encrypted string, and nothing else (no key/password). But also, no portion of the original string can be derived given any portion of the encoded/hashed/encrypted string.
>
>
>
I am assuming that "no portion of the original string can be derived given any portion of the encoded/hashed/encrypted string" means "no portion of the original string can be derived given anything less than the entire encoded/hashed/encrypted string", otherwise the question would be self-contradictory.
Answer
------
It sounds like you are looking for a permutation. A permutation is an invertible transformation on a fixed-size set of blocks. If your input is larger, the/an [All-Or-Nothing Transform](https://en.wikipedia.org/wiki/All-or-nothing_transform) may be useful. The OAEP mentioned by @DannyNiu is an example of an AONT.
For example, many block ciphers are built by interleaving applications of a permutation with the addition of secret key material. The permutation provides diffusion, which ensures that if you modify any part of the output then attempt to invert it, you end up back at a completely different input.
If you simply strip the key addition portion from a block cipher, it should also do what you're asking. For example, [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) consists of subBytes, mixColumns, shiftRows, and addRoundKey. If you were to omit the addRoundkey operation, you would be left with a fixed permutation that provides the required avalanche effect and some degree of unpredictability. Another example of a permutation is [keccak-f](https://en.wikipedia.org/wiki/Keccak#The_block_permutation), which does the mixing for the [SHA3 algorithm](http://en.wikipedia.org/wiki/Keccak).
A key-less permutation does not provide encryption
--------------------------------------------------
Note that such a construction with no key is no longer providing *encryption*, as it is not possible to provide confidentiality of the message without some kind of secrecy, which is what the key provides. If anyone who has an input message can compute an output "ciphertext", or anyone who has an output "ciphertext" can invert it to the input message, then clearly confidentiality of the input cannot be achieved.
You tagged this question with "encoding", so perhaps confidentiality is not required in your use case. You would need to establish what you need this construction for and whether or not this is an issue. | One-time pad it
===============
Given the following conditions...
* [Alice](https://en.wikipedia.org/wiki/Alice_and_Bob) has a plain-text. She wants to encrypt that.
* After encrypting it, Alice obtains several cipher-texts.
* Alice wants to give the cipher-texts to people that are not authorised to read the plain-text. None of them shall be able to decipher the cipher-text on their own.
* If all the people that have the cipher-texts give them back to Alice, Alice must be able to reconstruct the plain-text.
This is easy: **use a [One-time pad](https://en.wikipedia.org/wiki/One-time_pad)**.
1. Alice creates a key (K1) of the same length as the plain-text.
2. Alice XORs the plain-text with the key, she gets C1.
3. Alice gives K1 to Bob and C1 to Carol.
Unless Bob and Carol are in cahoots, neither can reconstruct the message. When both of them give the key and cipher-text back to Alice, Alice only needs to XOR them together to get the plain-text back.
Expanding
=========
Alice wants better security and involves Dave and Erin. The algorithm becomes:
1. Alice creates a key (K1) of the same length as the plain-text.
2. Alice XORs the plain-text with K1, she gets C1.
3. Alice gives K1 to Bob.
4. Alice repeats 1, 2 and 3, applies K2 on C1, and gets C2. She gives K2 to Carol.
5. Alice repeats 5, to get K3 and C3. She gives K3 to Dave.
6. Alice gives C3 to Erin.
This can be repeated as many times as Alice likes.
There is some fragility in this as Alice needs to get the key/cipher back from **everyone** before she can get her plain-text back. But this is a problem for another post. |
19,334,041 | I moved a database from SQL Server 2012 to Azure. I don't want to use the user `master`, so I created a user `test`. This is what I did for database XXX on Azure:
```
create user test from login test with default_schema=[dbo]
exec sp_addrolemember 'db_owner','test'
```
I checked, and the database objects I am interested in are all in the schema `dbo`. The table `Users` is in the schema `dbo`.
The connection string in my web project has `test` as the login. It produces the error message:
```
The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'
```
What does the error message mean and what can I do to let user `test` access the database XXX? | 2013/10/12 | [
"https://Stackoverflow.com/questions/19334041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936293/"
] | I had just, for the first time, used the Plesk panel on my website hosting service to download an "Export Dump" file of my hosted SQL Server database.
After needing to use a different StackOverflow Question/Answer to understand how to use what I had downloaded, then in SQL Server Management studio I went into Security | Logins and pointed one of the Logins to the new local database I now had and tried to run my app. I got the error message in this Question (except my error message mentioned 'Keys' rather than 'Users').
So then, I followed the Answer provided here by Kellen Stuart, and it was a help for sure. The difference in my situation was, instead of the login having all the Database roles checked, my login had none of the roles checked.
So for my purposes (developing an app on my local workstation) I just needed to check db\_owner, and I was good to go. | Grant permissions for that user is needed |
19,334,041 | I moved a database from SQL Server 2012 to Azure. I don't want to use the user `master`, so I created a user `test`. This is what I did for database XXX on Azure:
```
create user test from login test with default_schema=[dbo]
exec sp_addrolemember 'db_owner','test'
```
I checked, and the database objects I am interested in are all in the schema `dbo`. The table `Users` is in the schema `dbo`.
The connection string in my web project has `test` as the login. It produces the error message:
```
The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'
```
What does the error message mean and what can I do to let user `test` access the database XXX? | 2013/10/12 | [
"https://Stackoverflow.com/questions/19334041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936293/"
] | Using SSMS, I made sure the user had connect permissions on both the database and ReportServer.
On the specific database being queried, under properties, I mapped their credentials and enabled datareader and public permissions. Also, as others have stated-I made sure there were no denyread/denywrite boxes selected.
I did not want to enable db ownership when for their reports since they only needed to have select permissions. | I resolve my problem doing this. [IMPORTANT NOTE: It allows escalated (expanded) privileges to the particular account, possibly more than are needed for individual scenario].
1. Go to '**Object Explorer**' of SQL Management Studio.
2. Expand **Security**, then **Login**.
3. Select the user you are working with, then right click and select **Properties Windows**.
4. In *Select a Page*, Go to **Server Roles**
5. Click on **sysadmin** and save. |
19,334,041 | I moved a database from SQL Server 2012 to Azure. I don't want to use the user `master`, so I created a user `test`. This is what I did for database XXX on Azure:
```
create user test from login test with default_schema=[dbo]
exec sp_addrolemember 'db_owner','test'
```
I checked, and the database objects I am interested in are all in the schema `dbo`. The table `Users` is in the schema `dbo`.
The connection string in my web project has `test` as the login. It produces the error message:
```
The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'
```
What does the error message mean and what can I do to let user `test` access the database XXX? | 2013/10/12 | [
"https://Stackoverflow.com/questions/19334041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936293/"
] | Using SSMS, I made sure the user had connect permissions on both the database and ReportServer.
On the specific database being queried, under properties, I mapped their credentials and enabled datareader and public permissions. Also, as others have stated-I made sure there were no denyread/denywrite boxes selected.
I did not want to enable db ownership when for their reports since they only needed to have select permissions. | Check space of your database.this error comes when space increased compare to space given to database. |
19,334,041 | I moved a database from SQL Server 2012 to Azure. I don't want to use the user `master`, so I created a user `test`. This is what I did for database XXX on Azure:
```
create user test from login test with default_schema=[dbo]
exec sp_addrolemember 'db_owner','test'
```
I checked, and the database objects I am interested in are all in the schema `dbo`. The table `Users` is in the schema `dbo`.
The connection string in my web project has `test` as the login. It produces the error message:
```
The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'
```
What does the error message mean and what can I do to let user `test` access the database XXX? | 2013/10/12 | [
"https://Stackoverflow.com/questions/19334041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936293/"
] | 1. Open SQL Management Studio
2. Expand your database
3. Expand the "Security" Folder
4. Expand "Users"
5. Right click the user (the one that's trying to perform the query) and select `Properties`.
6. Select page `Membership`.
7. Make sure you uncheck
`db_denydatareader`
`db_denydatawriter`
[](https://i.stack.imgur.com/zvmJl.png)
This should go without saying, but only grant the permissions to what the user needs. An easy lazy fix is to check `db_owner` like I have, but this is not the best security practice. | This is how I was able to solve the problem when I faced it
1. Start SQL Management Studio.
2. Expand the Server Node (in the 'Object Explorer').
3. Expand the Databases Node and then expand the specific Database which you are trying to access using the specific user.
4. Expand the Users node under the Security node for the database.
5. Right click the specific user and click 'properties'. You will get a dialog box.
6. Make sure the user is a member of the db\_owner group (please read the comments below before you use go this path) and other required changes using the view. (I used this for 2016. Not sure how the specific dialog look like in other version and hence not being specific) |
19,334,041 | I moved a database from SQL Server 2012 to Azure. I don't want to use the user `master`, so I created a user `test`. This is what I did for database XXX on Azure:
```
create user test from login test with default_schema=[dbo]
exec sp_addrolemember 'db_owner','test'
```
I checked, and the database objects I am interested in are all in the schema `dbo`. The table `Users` is in the schema `dbo`.
The connection string in my web project has `test` as the login. It produces the error message:
```
The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'
```
What does the error message mean and what can I do to let user `test` access the database XXX? | 2013/10/12 | [
"https://Stackoverflow.com/questions/19334041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936293/"
] | The syntax to grant select permission on a specific table :
```
USE YourDB;
GRANT SELECT ON dbo.functionName TO UserName;
```
To grant the select permission on all tables in the database:
```
USE YourDB;
GRANT SELECT TO UserName;
``` | I resolve my problem doing this. [IMPORTANT NOTE: It allows escalated (expanded) privileges to the particular account, possibly more than are needed for individual scenario].
1. Go to '**Object Explorer**' of SQL Management Studio.
2. Expand **Security**, then **Login**.
3. Select the user you are working with, then right click and select **Properties Windows**.
4. In *Select a Page*, Go to **Server Roles**
5. Click on **sysadmin** and save. |
19,334,041 | I moved a database from SQL Server 2012 to Azure. I don't want to use the user `master`, so I created a user `test`. This is what I did for database XXX on Azure:
```
create user test from login test with default_schema=[dbo]
exec sp_addrolemember 'db_owner','test'
```
I checked, and the database objects I am interested in are all in the schema `dbo`. The table `Users` is in the schema `dbo`.
The connection string in my web project has `test` as the login. It produces the error message:
```
The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'
```
What does the error message mean and what can I do to let user `test` access the database XXX? | 2013/10/12 | [
"https://Stackoverflow.com/questions/19334041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936293/"
] | Using SSMS, I made sure the user had connect permissions on both the database and ReportServer.
On the specific database being queried, under properties, I mapped their credentials and enabled datareader and public permissions. Also, as others have stated-I made sure there were no denyread/denywrite boxes selected.
I did not want to enable db ownership when for their reports since they only needed to have select permissions. | May be your Plesk panel or other panel subscription has been expired....please check subscription End. |
19,334,041 | I moved a database from SQL Server 2012 to Azure. I don't want to use the user `master`, so I created a user `test`. This is what I did for database XXX on Azure:
```
create user test from login test with default_schema=[dbo]
exec sp_addrolemember 'db_owner','test'
```
I checked, and the database objects I am interested in are all in the schema `dbo`. The table `Users` is in the schema `dbo`.
The connection string in my web project has `test` as the login. It produces the error message:
```
The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'
```
What does the error message mean and what can I do to let user `test` access the database XXX? | 2013/10/12 | [
"https://Stackoverflow.com/questions/19334041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936293/"
] | I think the problem is with the user having **deny privileges**. This error comes when the user which you have created does not have the sufficient privileges to access your tables in the database. Do grant the privilege to the user in order to get what you want.
**[GRANT](https://learn.microsoft.com/en-us/sql/t-sql/statements/grant-object-permissions-transact-sql)** the user specific permissions such as SELECT, INSERT, UPDATE and DELETE on tables in that database. | Grant permissions for that user is needed |
19,334,041 | I moved a database from SQL Server 2012 to Azure. I don't want to use the user `master`, so I created a user `test`. This is what I did for database XXX on Azure:
```
create user test from login test with default_schema=[dbo]
exec sp_addrolemember 'db_owner','test'
```
I checked, and the database objects I am interested in are all in the schema `dbo`. The table `Users` is in the schema `dbo`.
The connection string in my web project has `test` as the login. It produces the error message:
```
The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'
```
What does the error message mean and what can I do to let user `test` access the database XXX? | 2013/10/12 | [
"https://Stackoverflow.com/questions/19334041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936293/"
] | The syntax to grant select permission on a specific table :
```
USE YourDB;
GRANT SELECT ON dbo.functionName TO UserName;
```
To grant the select permission on all tables in the database:
```
USE YourDB;
GRANT SELECT TO UserName;
``` | I had just, for the first time, used the Plesk panel on my website hosting service to download an "Export Dump" file of my hosted SQL Server database.
After needing to use a different StackOverflow Question/Answer to understand how to use what I had downloaded, then in SQL Server Management studio I went into Security | Logins and pointed one of the Logins to the new local database I now had and tried to run my app. I got the error message in this Question (except my error message mentioned 'Keys' rather than 'Users').
So then, I followed the Answer provided here by Kellen Stuart, and it was a help for sure. The difference in my situation was, instead of the login having all the Database roles checked, my login had none of the roles checked.
So for my purposes (developing an app on my local workstation) I just needed to check db\_owner, and I was good to go. |
19,334,041 | I moved a database from SQL Server 2012 to Azure. I don't want to use the user `master`, so I created a user `test`. This is what I did for database XXX on Azure:
```
create user test from login test with default_schema=[dbo]
exec sp_addrolemember 'db_owner','test'
```
I checked, and the database objects I am interested in are all in the schema `dbo`. The table `Users` is in the schema `dbo`.
The connection string in my web project has `test` as the login. It produces the error message:
```
The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'
```
What does the error message mean and what can I do to let user `test` access the database XXX? | 2013/10/12 | [
"https://Stackoverflow.com/questions/19334041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936293/"
] | 1. Open SQL Management Studio
2. Expand your database
3. Expand the "Security" Folder
4. Expand "Users"
5. Right click the user (the one that's trying to perform the query) and select `Properties`.
6. Select page `Membership`.
7. Make sure you uncheck
`db_denydatareader`
`db_denydatawriter`
[](https://i.stack.imgur.com/zvmJl.png)
This should go without saying, but only grant the permissions to what the user needs. An easy lazy fix is to check `db_owner` like I have, but this is not the best security practice. | I resolve my problem doing this. [IMPORTANT NOTE: It allows escalated (expanded) privileges to the particular account, possibly more than are needed for individual scenario].
1. Go to '**Object Explorer**' of SQL Management Studio.
2. Expand **Security**, then **Login**.
3. Select the user you are working with, then right click and select **Properties Windows**.
4. In *Select a Page*, Go to **Server Roles**
5. Click on **sysadmin** and save. |
19,334,041 | I moved a database from SQL Server 2012 to Azure. I don't want to use the user `master`, so I created a user `test`. This is what I did for database XXX on Azure:
```
create user test from login test with default_schema=[dbo]
exec sp_addrolemember 'db_owner','test'
```
I checked, and the database objects I am interested in are all in the schema `dbo`. The table `Users` is in the schema `dbo`.
The connection string in my web project has `test` as the login. It produces the error message:
```
The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'
```
What does the error message mean and what can I do to let user `test` access the database XXX? | 2013/10/12 | [
"https://Stackoverflow.com/questions/19334041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/936293/"
] | I think the problem is with the user having **deny privileges**. This error comes when the user which you have created does not have the sufficient privileges to access your tables in the database. Do grant the privilege to the user in order to get what you want.
**[GRANT](https://learn.microsoft.com/en-us/sql/t-sql/statements/grant-object-permissions-transact-sql)** the user specific permissions such as SELECT, INSERT, UPDATE and DELETE on tables in that database. | Check space of your database.this error comes when space increased compare to space given to database. |
6,372,248 | I have a problem and need some help. My application uses outlook to send email with attachments. Right now i need to find out when the email with attachment has been send out completely by outlook. I tried to follow this [link](http://social.msdn.microsoft.com/forums/en-US/vsto/thread/d891c669-21af-4ce4-b24b-8f6eb2308227) but the ItemEvents\_10\_SendEventHandler does not fulfil my task as outlook will still be attaching the document when this event is fired. I found out that the email takes time to send out due to the attachment and the duration depends on the attachment size. I want my program to be notified if possible or wait until the email has been send out completely. Can someone guide me or tell me the approach on how to get this to work. Any help provided will be greatly appericiated. | 2011/06/16 | [
"https://Stackoverflow.com/questions/6372248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/293240/"
] | Mostly not, modern CPU's are very fast... The most notable improvement is the speed in the download speeds. Strip out any unnecessary comments sent down the wire to the browser, minify CSS, JavaScript files, use CDN's etc. | It depends how many comments there are.
In general though, most developers have a live version of all their code that is compressed- no whitespace outside of text formatting, no comments, etc. And an offline version that is developer-friendly with all the extra formatting and so on.
Another thing to note is with '//' style comments, they won't really hinder performance since the parser skips straight to the next line. With /\*\*/ comments, the parsers has to keep reading all your comments until it encounters the closing \*/ so its *ever-so-slightly* more cpu intensive.
Paragraph 2 though, imo. :) |
1,002,429 | I used to have a Server 2003 R2 Hyper-V VM instance running on an Server 2012 R2. The performance was very good. THen, I was told that 2003 wasn't being supported anymore by a software package I use, so I upgraded to 2008 R2, and that's when all my SMB shares took a nosedive.
When I attempt to navigate to my network drive using SMB2 (verified using wireshark), When I open a folder, it takes almost a minute to list the content of the folder. Using 2003, it was instantaneous. Then, when I move my mouse cursor over a file in the folder, windows explorer locks up for another minute. Wireshark doesn't produce anything other than Keep-Alive messages while I wait for a response from the server. Any ideas as to why this is happening after my upgrade? | 2020/02/09 | [
"https://serverfault.com/questions/1002429",
"https://serverfault.com",
"https://serverfault.com/users/559370/"
] | I should have read [the manual](https://www.freedesktop.org/software/systemd/man/systemd.link.html) more carefully.
>
> The first (in lexical order) of the link files that matches a given device is applied. Note that a default file 99-default.link is shipped by the system. Any user-supplied .link should hence have a lexically earlier name to be considered at all.
>
>
>
Renaming `/etc/systemd/network/ens19.link` to `/etc/systemd/network/00-ens19.link` helped.
`[MATCH]` should be `[Match]` and `[LINK]` should be `[Link]`.
To apply a changed .link file to the link I can reboot or run
```
udevadm test-builtin net_setup_link /sys/class/net/ens19
```
(Because .link files are processed by udev and not systemd-networkd, restarting systemd-networkd is insufficient.) | As per [systemd.network](https://www.freedesktop.org/software/systemd/man/systemd.network.html) link aliases are not (yet?) supported. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.