qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
39,400,439 | I have a green navigation bar and a green table view header that together look like this:
[](https://i.stack.imgur.com/BTalO.png)
But when the user scrolls the table view down it appears like this:
[](https://i.stack.imgur.com/BOM5m.png)
I'm attempting to set the color of the grey portion that is revealed when the user drags down to also be green, but can't work out how to do so.
If I set the tableview's background color to green this does not affect it, setting that to green sets the view behind the grey strip but does not affect that strip itself:
[](https://i.stack.imgur.com/KhMku.png)
Here is the grey strip in the view hierarcy:
[](https://i.stack.imgur.com/6OJDE.png)
Is there some way I can set it to green, so when the user drags down they don't see they gray beneath?
The table view in the storyboard is like this:
[](https://i.stack.imgur.com/QM4Gj.png) | 2016/09/08 | [
"https://Stackoverflow.com/questions/39400439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1082219/"
] | I had a same problem, I solved it with this code.
```
CGRect frame = self.ContactTable.bounds;
frame.origin.y = -frame.size.height;
UIView* bgView = [[UIView alloc] initWithFrame:frame];
bgView.backgroundColor = [UIColor systemBackgroundColor];
bgView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// Adding the view
[self.tableView insertSubview:bgView atIndex:0];
``` | Dobiho's answer in **Swift**:
```
var frame = tableView.bounds
frame.origin.y = -frame.size.height
let bgView = UIView(frame: frame)
bgView.backgroundColor = UIColor.green
bgView.autoresizingMask = .flexibleWidth
tableView.addSubview(bgView)
``` |
10,927,550 | I've made a simple calendar where you can select year and month through a dropdown list.
```
<form name=calenderselect method='post' action='calendar.php'>
<select name='month' id='month'>
<option>January</option>
<option>Februari</option>
<option>March</option>
....
</select>
<input type='submit' name='submit' value='Change' />
</form>
```
I find it abit annoying that you have to press the submit button every time you want to change month. I would like it to change the moment I click the month in the list. | 2012/06/07 | [
"https://Stackoverflow.com/questions/10927550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1399283/"
] | here you are: `<select name='month' id='month' onclick="this.form.submit()">`
but i guess you really want to submit the form by `onchange` event. | Add a javascript event on your select :
```
<select name="month" id="month" onChange="yourjsfunction()">
``` |
4,285,214 | I am fitting a model to factor data and predicting. If the `newdata` in `predict.lm()` contains a single factor level that is unknown to the model, *all* of `predict.lm()` fails and returns an error.
Is there a good way to have `predict.lm()` return a prediction for those factor levels the model knows and NA for unknown factor levels, instead of only an error?
Example code:
```
foo <- data.frame(response=rnorm(3),predictor=as.factor(c("A","B","C")))
model <- lm(response~predictor,foo)
foo.new <- data.frame(predictor=as.factor(c("A","B","C","D")))
predict(model,newdata=foo.new)
```
I would like the very last command to return three "real" predictions corresponding to factor levels "A", "B" and "C" and an `NA` corresponding to the unknown level "D". | 2010/11/26 | [
"https://Stackoverflow.com/questions/4285214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452096/"
] | You have to remove the extra levels before any calculation, like:
```
> id <- which(!(foo.new$predictor %in% levels(foo$predictor)))
> foo.new$predictor[id] <- NA
> predict(model,newdata=foo.new)
1 2 3 4
-0.1676941 -0.6454521 0.4524391 NA
```
This is a more general way of doing it, it will set all levels that do not occur in the original data to NA. As Hadley mentioned in the comments, they could have chosen to include this in the `predict()` function, but they didn't
Why you have to do that becomes obvious if you look at the calculation itself. Internally, the predictions are calculated as :
```
model.matrix(~predictor,data=foo) %*% coef(model)
[,1]
1 -0.1676941
2 -0.6454521
3 0.4524391
```
At the bottom you have both model matrices. You see that the one for `foo.new` has an extra column, so you can't use the matrix calculation any more. If you would use the new dataset to model, you would also get a different model, being one with an extra dummy variable for the extra level.
```
> model.matrix(~predictor,data=foo)
(Intercept) predictorB predictorC
1 1 0 0
2 1 1 0
3 1 0 1
attr(,"assign")
[1] 0 1 1
attr(,"contrasts")
attr(,"contrasts")$predictor
[1] "contr.treatment"
> model.matrix(~predictor,data=foo.new)
(Intercept) predictorB predictorC predictorD
1 1 0 0 0
2 1 1 0 0
3 1 0 1 0
4 1 0 0 1
attr(,"assign")
[1] 0 1 1 1
attr(,"contrasts")
attr(,"contrasts")$predictor
[1] "contr.treatment"
```
You can't just delete the last column from the model matrix either, because even if you do that, both other levels are still influenced. The code for level `A` would be (0,0). For `B` this is (1,0), for `C` this (0,1) ... and for `D` it is again (0,0)! So your model would assume that `A` and `D` are the same level if it would naively drop the last dummy variable.
On a more theoretical part: It is possible to build a model without having all the levels. Now, as I tried to explain before, that model is **only** valid for the levels you used when building the model. If you come across new levels, you have to build a new model to include the extra information. If you don't do that, the only thing you can do is delete the extra levels from the dataset. But then you basically lose all information that was contained in it, so it's generally not considered good practice. | A quick-and-dirty solution for split testing, is to recode rare values as "other". Here is an implementation:
```
rare_to_other <- function(x, fault_factor = 1e6) {
# dirty dealing with rare levels:
# recode small cells as "other" before splitting to train/test,
# assuring that lopsided split occurs with prob < 1/fault_factor
# (N.b. not fully kosher, but useful for quick and dirty exploratory).
if (is.factor(x) | is.character(x)) {
min.cell.size = log(fault_factor, 2) + 1
xfreq <- sort(table(x), dec = T)
rare_levels <- names(which(xfreq < min.cell.size))
if (length(rare_levels) == length(unique(x))) {
warning("all levels are rare and recorded as other. make sure this is desirable")
}
if (length(rare_levels) > 0) {
message("recoding rare levels")
if (is.factor(x)) {
altx <- as.character(x)
altx[altx %in% rare_levels] <- "other"
x <- as.factor(altx)
return(x)
} else {
# is.character(x)
x[x %in% rare_levels] <- "other"
return(x)
}
} else {
message("no rare levels encountered")
return(x)
}
} else {
message("x is neither a factor nor a character, doing nothing")
return(x)
}
}
```
For example, with data.table, the call would be something like:
```
dt[, (xcols) := mclapply(.SD, rare_to_other), .SDcol = xcols] # recode rare levels as other
```
where `xcols` is a any subset of `colnames(dt)`. |
51,707,790 | Im learning how to program and I would like to toggle between hiding and showing an element with JavaScript. The script is shown below. It works but instead of showing the solution once the program runs, I would like to have it hidden so that the user can click and see the solution. I would like to have it the other way round. I’ve tried with ‘display:none’ but it stops working. I know its easy but I cant make it work. Can you help me?
```js
function SolutionFunction() {
var x = document.getElementById("solution");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
```
```css
#solution {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
```
```html
<button onclick=" SolutionFunction ()">Try it</button>
<div id=" solution ">
This is the solution.
</div>
``` | 2018/08/06 | [
"https://Stackoverflow.com/questions/51707790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10170226/"
] | You can use the hidden attribute/property on the element to toggle the visibility instead.
You should also remove any spaces you have in `id=""` to be able to properly get the element by id
```js
function SolutionFunction() {
var x = document.getElementById("solution");
x.hidden = !x.hidden
}
```
```css
#solution {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
```
```html
<button onclick=" SolutionFunction ()">Try it</button>
<div id="solution" hidden> <!-- hidden by default -->
This is the solution.
</div>
```
Using the `hidden = true|false` method to toggle the visibility is a better approach since you don't always know how a element display property should be handled after you reset the `display` style. You might want to have the element rendered as `inline-block` or if it's a `<tr>` it should be rendered as row and not a block
---
Another possible solution if you will is the `<details>` element but it don't work in Internet explorer or Edge yet. but it looks simular to what you try to accomplish and don't require any javascript.
See browser support here <https://caniuse.com/#feat=details>
```css
#solution {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
```
```html
<details> <!-- can use the open attribute to show it by default -->
<summary>try it</summary>
<div id="solution">
this is the solution
</div>
</details>
```
it might not look as pretty but it's possible to style it more | Stop the spaces!
```
function SolutionFunction() {
var x = document.getElementById("solution");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#solution {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<button onclick="SolutionFunction()">Try it</button>
<div id="solution" style="display: none;">
This is the solution.
</div>
```
Better yet, reference the element in your function as an argument. Also look into ternary operators:
```
function SolutionFunction(x) {
x.style.display = x.style.display === "none" ? "block" : "none";
}
#solution {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<button onclick="SolutionFunction(document.getElementById('solution'))">Try it</button>
<div id="solution" style="display: none;">
This is the solution.
</div>
``` |
60,588,727 | I am trying to code the implementation of the Cube, Stack example given in this [Coursera course example of Towers of Hanoi](https://www.coursera.org/lecture/cs-fundamentals-1/4-2-tower-of-hanoi-introduction-aLUTd) to learn more C++.
In `stack.h` I have to implement:
```
class Stack {
public:
void push_back(const Cube & cube);
Cube removeTop();
Cube & peekTop();
unsigned size() const;
friend std::ostream & operator<<(std::ostream & os, const Stack & stack);
private:
std::vector<Cube> cubes_;
};
```
The issue I have is with `removeTop()`. I was thinking of returning `nullptr` if the stack (vector) is empty because `pop_back`'s behavior is undefined for an empty vector.
>
> Calling pop\_back on an empty container is undefined. [Cpp Reference](https://en.cppreference.com/w/cpp/container/vector/pop_back)
>
>
>
```
inline Cube Stack::removeTop() {
if (!cubes_.empty()) {
Cube top_cube = cubes_.back();
cubes_.pop_back();
return top_cube;
}
else {
return nullptr;
}
}
```
However, I get an error during compilation.
```
./stack.h:35:12: error: no viable conversion from returned value of type
'std::__1::nullptr_t' to function return type 'uiuc::Cube'
return nullptr;
```
How can I protect the user if I can't return a `nullptr`? Am I limited to just telling the user that the function should not be called on an empty stack and let him/her take care of the checking? | 2020/03/08 | [
"https://Stackoverflow.com/questions/60588727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7093241/"
] | Based on the function signature, you have to implement, you really can't. Typically, you'd guard this sort of thing with an assertion. In some situations you might use the [NullObject pattern](https://en.wikipedia.org/wiki/Null_object_pattern), or you could return a junk object. In newer C++ versions, you can also use `std::optional<T>`.
```
inline Cube Stack::removeTop() {
if (!cubes_.empty()) {
Cube top_cube = cubes_.back();
cubes_.pop_back();
return top_cube;
}
else {
return Cube {};
}
}
``` | As [pyj](https://stackoverflow.com/users/1265214/pyj) noted, since c++17 there is a new mechanism to do so (adopting boost::optional idea). This is the *std::optional* container. When using *std::optional*, you tell the user of this function, that he might get an **empty response**, and therefore, he must check whether it is initialized or not.
From the cpp reference:
>
> The class template std::optional manages an optional contained value, i.e. a value that may or may not be present.
>
>
> A common use case for optional is the return value of a function that may fail. As opposed to other approaches, such as std::pair, optional handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.
>
>
>
Now for the usage:
```
inline std::optional<Cube> Stack::removeTop()
{
if (!cubes_.empty())
{
Cube top_cube = cubes_.back();
cubes_.pop_back();
return top_cube;
}
else
{
return std::nullopt;
}
}
```
And, while you get a std::optional, and not a Cube, there is no **memory allocation** on the heap, which is a great advantage over using pointers for the same output.
>
> If an optional contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though operator\*() and operator->() are defined.
>
>
> |
56,004,908 | Assume there are numerical variables: a, b, c, d, e..., and I want to compare a and b first, pseudo code:
```
if a > b:
if a > b+c:
if a > b+c+d:
...
else:
...
else:
...
else:
...
```
go forward one by one, I don't want such many if-else in code, is there any algorithm method or easy way to achieve that? | 2019/05/06 | [
"https://Stackoverflow.com/questions/56004908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8294738/"
] | If you make a list out of those variables, you can compare `a` to the cumulative sum of that list, and find the first index where it's `False`:
```
import numpy as np
b=1
c=2
d=7
e=10
a=8
x = [b,c,d,e]
np.argmin(np.greater(a,np.cumsum(x)))
```
Try it out! | A pseudo code to do this using a list. Please note that this is just a pseudo-code. You will have to modify it appropriately to suit your needs.
In the below solution, we try to add all parameters into a list. Since list is ordered. We can pick up the parameters in order to compare their sum with `a`.
```
a = 1000
b = 10
c = 20
d = 30
e = 40
cmpr_params = [b,c,d,e]
for i in range(1, (len(cmpr_params)+1)):
if a > sum(cmpr_params[:i]):
print (" a is greater a = %s, sum = %s" %(a, sum(cmpr_params[:i])))
else:
print (" a is lesser a = %s, sum = %s" %(a, sum(cmpr_params[:i])))
```
**Output:**
```
a is greater a = 1000, sum = 10
a is greater a = 1000, sum = 30
a is greater a = 1000, sum = 60
a is greater a = 1000, sum = 100
```
If `a`'s value were to be changed to `85`, the output will be as below:
```
a is greater a = 85, sum = 10
a is greater a = 85, sum = 30
a is greater a = 85, sum = 60
a is lesser a = 85, sum = 100
``` |
69,887,097 | I am using datetime-local input type in HTML, but I don't want to use the "T" on the output. I want to only get the date and time with a space between.
```
<input type="datetime-local" id="date" name="date">
```
The output is:
```
2021-11-08T16:34
```
What i want is:
```
2021-11-08 16:34
```
What do i need to do to get this output?
PS: Try to help me without bootstrap libraries, because on this project i can't use it. | 2021/11/08 | [
"https://Stackoverflow.com/questions/69887097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17338283/"
] | You can define 2 capture groups and check them
```
df = pd.DataFrame(
{'txt': ['firstname lastname (1937-2015)', 'firstname lastname (1780-1820)',
'firstname lastname (1945-?)', 'firstname lastname (1980-2022)']})
df[['birth', 'death']] = df['txt'].str.extract(r'(\d+)-(\d+|\?)').replace({'?': None}).astype(float). \
applymap(lambda x: x if 1800 <= x <= 2021 else None)
print(df)
```
Output:
```none
txt birth death
0 firstname lastname (1937-2015) 1937.0 2015.0
1 firstname lastname (1780-1820) NaN 1820.0
2 firstname lastname (1945-?) 1945.0 NaN
3 firstname lastname (1980-2022) 1980.0 NaN
``` | A generic regex solution to extract the second year (from 1800 to 2099) in Pandas using `Series.str.extract` you can leverage
```py
import pandas as pd
df = pd.DataFrame({'col':['firstname lastname (1937-2015)']})
yr = r'(?:1[89][0-9]{2}|20[01][0-9]|202[01])'
df['second_year'] = df['col'].str.extract(fr'(?s)(?<!\d){yr}(?!\d).*?({yr})(?!\d)')
# => df['second_year']
# 0 2015
# Name: second_year, dtype: object
```
See the [regex demo](https://regex101.com/r/mPyNY4/5). *Details*:
* `(?s)` - `.` now matches across lines
* `(?<!\d)` - a left-hand numeric boundary
* `(?:1[89][0-9]{2}|20[01][0-9]|202[01])` - from 1800 to 2021
* `(?!\d)` - a right hand numeric boundary
* `.*?` - any text, as few chars as possible
* `(1[89][0-9]{2}|20[01][0-9]|202[01])` - Group 1 (the actual return result of `Series.str.extract`): 1800 to 2021
* `(?!\d)` - a right hand numeric boundary
In this concrete case, a simple
```py
df['second_year'] = df['col'].str.extract(r'.*-(\d{4})')
```
will be enough: any text (as many chars other than line break chars as possible) and then a `-` and four digits captured into Group 1.
See [this regex demo](https://regex101.com/r/mPyNY4/5). |
7,823 | In the comment to [this great post](http://www.owenpellegrin.com/blog/testing/how-do-you-solve-multiple-asserts/), Roy Osherove mentioned the [OAPT](http://rauchy.net/oapt/) project that is designed to run each assert in a single test.
The following is written on the project's home page:
>
> **Proper unit tests should fail for
> exactly one reason,** that’s why you
> should be using one assert per unit
> test.
>
>
>
And, also, Roy wrote in comments:
>
> My guideline is usually that you test
> one logical CONCEPT per test. you can
> have multiple asserts on the same
> *object*. they will usually be the same concept being tested.
>
>
>
I think that, there are some cases where multiple assertions are needed (e.g. [Guard Assertion](http://xunitpatterns.com/Guard%20Assertion.html)), but in general I try to avoid this. What is your opinion? Please provide a real world example where multiple asserts are really *needed*. | 2010/09/28 | [
"https://softwareengineering.stackexchange.com/questions/7823",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/1716/"
] | The goal of the unit test is to give you as much information as possible about what is failing but also to help accurately pinpoint the most fundamental problems first. When you know logically that one assertion will fail given that another assertion fails or in other words there is a dependency relationship between the test then it makes sense to roll these as multiple asserts within a single test. This has the benefit of not littering the test results with obvious failures which could have been eliminated if we bailed out on the first assertion within a single test. In the case where this relationship does not exist the preference would naturally be then to separate these assertions into individual tests because otherwise finding these failures would require multiple iterations of test runs to work out all of the issues.
If you then also design the units/classes in such a way that overly complex tests would need to be written it makes less burden during testing and probably promotes a better design. | Yes, it is ok to have multiple assertions *as long as* a failing test gives you enough information to be able to diagnose the failure. This is going to depend on what you're testing and what the failure modes are.
>
> Proper unit tests should fail for exactly one reason, that’s why you should be using one assert per unit test.
>
>
>
I've never found such formulations to be helpful (that a class should have one reason to change is an example of just such an unhelpful adage). Consider an assertion that two strings are equal, this is semantically equivalent to asserting that the length of the two strings are the same and each character at the corresponding index is equal.
We could generalize and say that any system of multiple assertions could be rewritten as a single assertion, and any single assertion could be decomposed into a set of smaller assertions.
So, just focus on the clarity of the code and the clarity of the test results, and let that guide the number of assertions you use rather than vice versa. |
31,127,797 | I have two class like this:
```
class one
{
public $var1 = 'anythig';
}
class two
{
public $var2 = 'anythig';
}
```
I want to know when I create a object instance of these classes what happens? My point is about the values stored in the memory. In reality I have some big class, and my resources are limited. then I want to know, If I put `NULL` into my class when don't need to it anymore is good ? and help to optimizing ?
I have a `switch()` to include the desired class. something like this:
```
switch{
case "one":
require_once('classes/one.php');
break;
case "two":
require_once('classes/two.php');
break;
}
```
Every time I only need one class. When I define a new object *(`$obj = new class`)* what happens to my class previously defined as object instance? that is remain in memory? and if I put `NULL` is helpful ? Please guide me ..
**Edit:**
The last line is useful or not ?
```
$obj = new myvlass;
echo $obj->property; // there is where that my class is done
$obj=NULL;
``` | 2015/06/30 | [
"https://Stackoverflow.com/questions/31127797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The `videoUrl` parameter did not point to the right file.
Use this approach when referencing videos locally:
```
let filename = "yourvideo.mp4"
let allDirs = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDir = allDirs[0] as! NSString
let filePath = documentsDir.stringByAppendingPathComponent(filename)
let fileUrl = NSURL(fileURLWithPath: filePath)
```
The `Documents` directory path (e.g., /var/mobile/Containers/Data/Application/8BA180AB-2DD9-4FD8-9312-2BF006914561/Documents/) apparently changes.
You can't expect the same path every time and therefore can't use a fully formed file URL string like we were, even for testing purposes.
The parent directory to the `Documents` directory -- the alphanumeric string -- is what changes. | The NSURL can mean two different things :
1. The absolute file path that you mentioned i.e. starting with file://
2. The URL that you get from ALAsset. You can get it using :
NSURL \*asseturl = [asset valueForProperty:ALAssetPropertyAssetURL];
where "asset" is of type ALAsset
This URL can then be used to get AVAsset using :
AVAsset.assetWithURL
Please try the second method. |
51,815,123 | I have a model called `ImportTemp` which is used for store imported XLSX file to database. I'm using ActiveStorage for storing the files.
this is the model code:
```
class ImportTemp < ApplicationRecord
belongs_to :user
has_one_attached :file
has_one_attached :log_result
end
```
this is my import controller code:
```
def import
# Check filetype
case File.extname(params[:file].original_filename)
when ".xlsx"
# Add File to ImportFile model
import = ImportTemp.new(import_type: 'UnitsUpload', user: current_user)
import.file.attach(params[:file])
import.save
# Import unit via sidekiq with background jobs
ImportUnitWorker.perform_async(import.id)
# Notice
flash.now[:notice] = "We are processing your xlsx, we will inform you after it's done via notifications."
# Unit.import_file(xlsx)
else flash.now[:error] = t('shared.info.unknown')+": #{params[:file].original_filename}"
end
end
```
after upload the xlsx file, then the import will be processed in sidekiq. This is the worker code (still doesn't do the import actually) :
```rb
class ImportUnitWorker
include Sidekiq::Worker
sidekiq_options retry: false
def perform(file_id)
import_unit = ImportTemp.find(file_id)
# Open the uploaded xlsx to Creek
creek = Creek::Book.new(Rails.application.routes.url_helpers.rails_blob_path(import_unit.file, only_path: true))
sheet = creek.sheets[0]
puts "Opening Sheet #{sheet.name}"
sheet.rows.each do |row|
puts row
end
units = []
# Unit.import(units)
end
```
but after i tried it, it gives me error:
```
Zip::Error (File /rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCZz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--3960b6ba5b55f7004e09967d16dfabe63f09f0a9/2018-08-10_10_39_audit_gt.xlsx not found)
```
but if i tried to open it with my browser, which is the link looks like this:
```
http://localhost:3000/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCZz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--3960b6ba5b55f7004e09967d16dfabe63f09f0a9/2018-08-10_10_39_audit_gt.xlsx
```
it's working and the xlsx is downloaded. My question is what's wrong with it? why the file is not found in the sidekiq? | 2018/08/13 | [
"https://Stackoverflow.com/questions/51815123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8252171/"
] | I ended up using `Tempfile` as suggested by George Claghorn. I don't know if this is the best solution or best practices, but it works for me now. I'm going to use this solution while waiting Rails 6 stable to come out with `ActiveStorage::Blob#open` feature.
```rb
def perform(file_id)
import = ImportTemp.find(file_id)
temp_unit = Tempfile.new([ 'unit_import_temp', '.xlsx' ], :encoding => 'ascii-8bit')
units = []
begin
# Write xlsx from ImportTemp to Tempfile
temp_unit.write(import.file.download)
# Open the temp xlsx to Creek
book = Creek::Book.new(temp_unit.path)
sheet = book.sheets[0]
sheet.rows.each do |row|
# Skip the header
next if row.values[0] == 'Name' || row.values[1] == 'Abbreviation'
cells = row.values
# Add cells to new Unit
unit = Unit.new(name: cells[0], abbrev: cells[1], desc: cells[2])
units << unit
end
# Import the unit
Unit.import(units)
ensure
temp_unit.close
temp_unit.unlink # deletes the temp file
end
end
``` | The answer now seems to be (unless I am missing something):
```
Creek::Book.new file.service_url, check_file_extension: false, remote: true
``` |
64,614,976 | I'm trying to add a delay in one of my loops but I get unexpected results. I've looked at many similar questions but since I'm trying to learn javascript I want to know why this isn't working and how I can get it to work.
If you look at the script below, shouldn't it go like this:
1. cars[1]
2. sleep(); (wait 3 sec then return)
3. add 1
4. Run the script again
5. cars[2]
6. etc ...
With output:
1. Saab
2. Waiting 3 seconds...
3. Volvo
4. Waiting 3 seconds...
5. etc ...
But the output I receive is:
1. Saab
2. Volvo
3. BMW
4. Done
(Waiting 3 seconds here)
5. Waiting 3 seconds...
6. Waiting 3 seconds...
7. Waiting 3 seconds...
Am I stupid or is javascript working entirely different than C++ and assembly?
```js
var nr = 0;
const qty = 3;
function script() {
main();
console.log("Done");
}
function main() {
var cars = ["Saab", "Volvo", "BMW"];
if (nr !== qty) {
console.log(cars[nr]);
sleep();
nr++;
main();
}
else {
return;
}
}
function sleep() {
setTimeout(function () {
console.log('Waiting 3 seconds...');
return;
}, 3000);
}
```
```html
<!DOCTYPE html>
<HTML>
<HEAD>
</HEAD>
<BODY>
<button onclick="script()">Run Script</button>
</BODY>
</HTML>
``` | 2020/10/30 | [
"https://Stackoverflow.com/questions/64614976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9370976/"
] | The `setTimeout()` function doesn't block. It calls the function passed to it after the time out. You can just tell it to call `main`.
```
function main() {
var cars = ["Saab", "Volvo", "BMW"];
if (nr !== qty) {
console.log(cars[nr]);
nr++;
sleep(3, main);
}
}
function sleep(timeout, func)
{
console.log(`Waiting ${timeout} seconds...`);
setTimeout(func, timeout * 1000);
}
``` | [setTimeout](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals) does not interrupt the main thread. Instead, it registers your callback function and continues executing upcoming lines.
To get your desired output, we need to have callbacks here and there. This is something called [asynchronous programming](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous) in JavaScript land. You could also make use of [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to simplify your code.
```
var nr = 0;
const qty = 3;
function script() {
main(function () {
console.log('Done');
});
}
function main(callback) {
var cars = ['Saab', 'Volvo', 'BMW'];
sleep(function loop() {
console.log(cars[nr++]);
if (nr === qty) {
// call the callback function
callback();
} else {
// or do the loop
sleep(loop);
}
});
}
function sleep(callback) {
setTimeout(function () {
console.log('Waiting 3 seconds...');
callback();
}, 3000);
}
``` |
39,409,341 | The following is my controller file:
```
class BiodataController < ApplicationController
def store
@user=params[:username]
@age=params[:age]
@gender=params[:gender]
@mstatus=params[:mstatus]
@language=params[:language]
@email=params[:email]
@mobile=params[:mobile]
if params[:username].present? && params[:age].present? && params[:gender].present? && params[:mstatus].present? && params[:language].present? && params[:email].present? && params[:mobile].present?
Biodatum.create(name: @user, age: @age, gender: @gender, mstatus: @mstatus, language: @language, email: @email, mobile: @mobile)
Infomail.sendmail(@email)
render 'store'
else
render 'Error'
end
end
end
```
My requirement is to send email to the address stored in @email. So I created the mailer as 'Infomail'. The following is my mailer file.
```
class Infomail < ApplicationMailer
default from: 'abc@xyz.co.in'
def sendmail(user)
@user = user
mail(to: @user.email, subject: 'sample mail')
end
end
```
And I also have html file under 'app/views/infomail/sendmail.html.erb'. But it doesn't work. Can any one explain me what is the bug in
my code. | 2016/09/09 | [
"https://Stackoverflow.com/questions/39409341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5063789/"
] | For today's TypeScript and Angular 5, avoiding `WARNING in Circular dependency detected` when importing the global injector, first declare a helper, e.g. `app-injector.ts`:
```js
import {Injector} from '@angular/core';
/**
* Allows for retrieving singletons using `AppInjector.get(MyService)` (whereas
* `ReflectiveInjector.resolveAndCreate(MyService)` would create a new instance
* of the service).
*/
export let AppInjector: Injector;
/**
* Helper to set the exported {@link AppInjector}, needed as ES6 modules export
* immutable bindings (see http://2ality.com/2015/07/es6-module-exports.html) for
* which trying to make changes after using `import {AppInjector}` would throw:
* "TS2539: Cannot assign to 'AppInjector' because it is not a variable".
*/
export function setAppInjector(injector: Injector) {
if (AppInjector) {
// Should not happen
console.error('Programming error: AppInjector was already set');
}
else {
AppInjector = injector;
}
}
```
Next, in your `AppModule`, set it using:
```js
import {Injector} from '@angular/core';
import {setAppInjector} from './app-injector';
export class AppModule {
constructor(injector: Injector) {
setAppInjector(injector);
}
}
```
And wherever needed, use:
```js
import {AppInjector} from './app-injector';
const myService = AppInjector.get(MyService);
``` | I've managed to do it using manual boostrapping. Don't use "`bootstrap: [AppComponent]`" declaration in `@NgModule`, use `ngDoBootstrap` method instead:
```
export class AppModule {
constructor(private injector: Injector) {
}
ngDoBootstrap(applicationRef: ApplicationRef) {
ServiceLocator.injector = this.injector;
applicationRef.bootstrap(AppComponent);
}
}
``` |
7,606,633 | Please see this line of code. This is an invocation of a stored procedure, which returns an `ObjectResult<long?>`. In order to extract the long values I added the Select:
```
dbContext.FindCoursesWithKeywords(keywords).Select(l => l.Value);
```
Based on intellisense this Select returns `IEnumerable<long>`.
I'm not sure whether I read it somewhere or maybe just got used to this assumption - I always thought that when the EF API returns an `IEnumerable` (and not `IQueryable`) then this means that the results have been materialized. Meaning they've been pulled from the database.
I found out today that I was wrong (or maybe that's a bug?). I kept getting the error
>
> "New transaction is not allowed because there are other threads
> running in the session"
>
>
>
Basically, this error tells you that you're trying to save changes while the db reader is still reading records.
Eventually I solved it by (what I considered a long shot) and added `ToArray()` call to materialize the `IEnumerable<long>`...
So - the bottom line - should I expect `IEnumerable` results from EF to contain results that haven't materialized yet? If yes then is there a way to know whether an `IEnumerable` has been materialized or not?
Thanks and apologies if this is one of those 'duhhh' questions... :) | 2011/09/30 | [
"https://Stackoverflow.com/questions/7606633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124132/"
] | Working on an `IEnumerable<T>` means that all further operations will happen in C# code, i.e. linq-to-objects. It does not mean that the query has already executed.
Once you degrade to linq-to-objects all data left at this point needs to be fetched from the database and sent to .net. This can degrade performance drastically(For example database indexes won't be used by linq-to-objects), but on the other hand linq-to-objects is more flexible, since it can execute arbitrary C# code instead of being limited by what your linq provider can translate to SQL.
A `IEnumerable<T>` can be both a deferred query or already materialized data. The standard linq operators typically are deferred, and `ToArray()`/`ToList()` are always materialized. | IEnumerable will not hydrate until materialized. If calling a stored procedure I would think that there is no further filter required, I mean you send parameters to a stored procedure to produce the desired subset of data returned. IEnumerable tied to a stored procedure is fine. However if you are fetching the entire contents of a table, then filtering in the application you should have a strategy. Like, do not ToList() the IEnumerable of the table, you will materialize all rows. Sometimes this will cause an out of memory exception. Besides why consume memory without reason. Use IQueryable against the context, that way you can filter the table at the Data Source, and not in the application. In answer, you have to materialize it. IEnumerable is an interface, only materializing it will "initialize" its type and produce something in my understanding. |
62,134,143 | When its RDBMS, I used Liquibase to deploy the changes in the target database. That has support for multi-tenancy & roll back to different versions.
In Mongo, I tried to find the equivalent library and found the below.
1. <https://github.com/mongobee/mongobee> - Requires java skillset. Last update was 2 Years ago.
2. <https://github.com/coldze/mongol> - Stick to just Json. Low reputation.
3. <https://github.com/mongeez/mongeez> - Kind of promising but very outdated.
4. <https://github.com/tj/node-migrate> - Done in jS, has reputation better than others, but lot of learning required to be familiar with this framework IMO.
For me the criteria are,
1. Upgrade from one version to any new version must be possible.
2. Downgrade from the current version to any old version must be possible ( should have the feasibility to do the complex migration. Ex, refer to the different collections and assign a computed value from the output.
3. Must be able to extract the changes before execution. For verification purposes mostly. Otherwise, during new build deployment, the changes alone to be executed.
4. Easy to adopt, so a lot of learning should be avoided.
You have some other working concept, eager to know. Thanks,
A. | 2020/06/01 | [
"https://Stackoverflow.com/questions/62134143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154991/"
] | If you are using Java, a very good option(I'd say probably the best) is [Mongock](https://www.mongock.io/).
It provides everything you need and there are very good features in the road map.
To get started(if using Spring 5 and spring data 3), you just need :
1. Add Mongock to your pom
```xml
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.github.cloudyrock.mongock</groupId>
<artifactId>mongock-bom</artifactId>
<version>4.1.17</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- ... -->
<dependency>
<groupId>com.github.cloudyrock.mongock</groupId>
<artifactId>mongock-spring-v5</artifactId>
</dependency>
<dependency>
<groupId>com.github.cloudyrock.mongock</groupId>
<artifactId>mongodb-springdata-v3-driver</artifactId>
</dependency>
```
3. Add your Spring and MongoDB dependencies to your pom
4. Add minimum configuration
```yaml
mongock:
change-logs-scan-package:
- your.package.for.changelogs
```
5. Create your changeLog in the package indicated previously indicated: `your.package.for.changelogs`
```java
@ChangeLog(order = "001")
public class DatabaseChangelog {
@ChangeSet(order = "001", id = "changeWithoutArgs", author = "mongock")
public void yourChangeSet() {
// your migration here
}
}
```
5. Add Mongock annotation to your SpringBoot application
```java
@EnableMongock
@SpringBootApplication
public class App {
public static void main(String[] args) {
new SpringApplicationBuilder().sources(App.class).run(args);
}
}
```
This is only a quick introduction on how it works. Please a look to the [documentation](https://www.mongock.io/) for more information.
Disclosure: I am one of the Mongock authors. | I'm not familiar with Liquibase and I'm not sure what you mean by "Must be able to extract the changes before execution", but here is another useful MongoDB-specific option that is similar to node-migrate:
<https://www.npmjs.com/package/migrate-mongo>
Also, an article explaining the how / why to use it:
<https://medium.com/javascript-in-plain-english/developer-story-db-migrations-mongodb-edition-7b36db8f2654> |
58,231,977 | I am having more than 30000 jobs and executions in my rundeck. Is there any API or CLI so that we can schedule to clean periodically. Because of too many jobs and executions rundeck throws `java.lang.OutOfMemoryError: GC Overhead Limit` and the services gets stops.
Also if there are more number. The UI takes long time to render the information.
Any documentations or scripts will be helpful. | 2019/10/04 | [
"https://Stackoverflow.com/questions/58231977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6112907/"
] | Using RD CLI you have [this](https://gist.github.com/shamil/1f6524f06210252c7d13d0deb169bdc2) good option. So, if you're using Rundeck 3.1 or above, you can go to Project Settings > Edit Configuration > Execution History Clean (tab) and click on "Enable" checkbox (then you can define the parameters in the same page).
More info [here](https://docs.rundeck.com/docs/manual/project-settings.html#execution-history-clean). | if your project is only one, you don't have to run the above script.
Go to Projects, Click on `recent` or `failed` or `running` tab and do a `bulk delete` |
6,437 | I feel like something is wrong with the *", notably" part*, but I can't explain why! Is the following sentence grammatically correct?
>
> Employees give relatively low scores across a variety of characteristics, notably the quality of the Marketing department's decisions, compensation, and having sufficient people resources.
>
>
>
(My problem with grammar is that it's completely intuitive, and I often can't explain the rules behind why something is wrong.) | 2010/12/08 | [
"https://english.stackexchange.com/questions/6437",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/2591/"
] | The only thing I would change in the original sentence is the order or wording of the comma-separated list itself; when I first read it, I thought the Marketing Department was at fault for all three issues. If the items are supposed to be in that particular order as the top 3 results, some extra specifiers might be helpful to eliminate the ambiguous structure: `... notably the quality of the Marketing department's decisions, the level of compensation, and the availability of sufficient people resources.` | Punctuation dictates the flow of your sentence, therefore if you feel that the person reading it should take a short breath at that point, then so be it. If it's really bothering you, take the sentence apart and try to reword it differently.
Personally I find it fits perfectly, both reading it in my head and reading aloud.
DISCLAIMER: Born and lived first 22 years in the U.S. |
21,180,931 | So I have this code:
```
import sys ## The 'sys' module lets us read command line arguments
words1 = open(sys.argv[2],'r') ##sys.argv[2] is your dictionary text file
words = str((words1.read()))
def main():
# Get the dictionary to search
if (len(sys.argv) != 3) :
print("Proper format: python filename.py scrambledword filename.txt")
exit(1) ## the non-zero return code indicates an error
scrambled = sys.argv[1]
print(sys.argv[1])
unscrambled = sorted(scrambled)
print(unscrambled)
for line in words:
print(line)
```
When I print words, it prints the words in the dictionary, one word at a time, which is great. But as soon as I try and do anything with those words like in my last two lines, it automatically separates the words into letters, and prints one letter per line of each word. Is there anyway to keep the words together? My end goal is to do ordered=sorted(line), and then an if (ordered==unscrambled) have it print the original word from the dictionary? | 2014/01/17 | [
"https://Stackoverflow.com/questions/21180931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3188565/"
] | Your words is an instance of `str`. You should use `split` to iterate over words:
```
for word in words.split():
print(word)
``` | A `for`-loop takes one element at a time from the "sequence" you pass it. You have read the contents of your file into a single string, so python treats it as a sequence of letters. What you need is to convert it into a list yourself: Split it into a list of strings that are as large as you like:
```
lines = words.splitlines() # Makes a list of lines
for line in lines:
....
```
Or
```
wordlist = words.split() # Makes a list of "words", by splitting at whitespace
for word in wordlist:
....
``` |
15,092,173 | I have a report with a typical date column. I want the user to select a start date from @prompt. Then I want the end date to be 3 months less than the user selected start date.
Example:
```
SELECT Date,Y,Z
FROM TABLE
WHERE Table.Date >= @prompt('Enter value(s) for Acct Open Dt','D',Object',Mono,Free,Persistent,,User:0)
AND
Table.Date <= USER ENTERED DATE - 3 months
```
Is this possible? I have done this very easily in other reporting tools. It seems odd that BOBJ would not have this functionality. | 2013/02/26 | [
"https://Stackoverflow.com/questions/15092173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1123492/"
] | C++ gives you many tools:
* `string` is a class managing the lifetime of character strings.
* `getline` puts a line from a stream (up to the next newline) into a `string`.
* `istringstream` makes an `istream` out of a `string`
* `istream_iterator` iterates over an `istream`, extracting the given type, breaking on whitespace.
* `accumulate` takes iterators delimiting a range and adds together the values:
Altogether:
```
string line;
while (getline(cin, line)) {
istringstream in(line);
istream_iterator<int> begin(in), end;
int sum = accumulate(begin, end, 0);
cout << sum << '\n';
}
``` | Put
`sum=0;` // at the top
ps
```
while(cin.peek()!='\n'){
}
``` |
19,963,209 | Thank you in advance for helping out!!!
I have an mySQL statement that works locally:
```
mysql -u root -ppassword -e 'SELECT "Column 1 text" as "Column 1 Heading", table1.* FROM table1;' dataBase1
```
If I try and run it with SSH, it errors out. I don't know how to get the quote in the SQL statement through SSH.
```
ssh server1 "mysql -u userName -ppassword -e 'SELECT 'Column 1 text' as 'Column 1 Heading', table1.* FROM table1;' dataBase1"
```
Any suggestion would be greatly appreciated..
Thanks,
~Donavon | 2013/11/13 | [
"https://Stackoverflow.com/questions/19963209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1171852/"
] | Try this:
```
> ethn[ethn < 0.3] <- NA
> ethn
caucasian asian latino
1 NA 1.000 1.000
2 0.723 0.622 0.748
3 NA NA 1.000
4 NA 0.316 NA
5 0.799 0.680 0.737
6 1.000 1.000 1.000
7 1.000 1.000 1.000
``` | The`.default` method for the `is.na<-` function succeeds with data.frames:
```
> is.na(ethn) <- ethn <0.3
> ethn
caucasian asian latino
1 NA 1.000 1.000
2 0.723 0.622 0.748
3 NA NA 1.000
4 NA 0.316 NA
5 0.799 0.680 0.737
6 1.000 1.000 1.000
7 1.000 1.000 1.000
```
And looking at the code, before compilation it was exactly what @Jilber offered.
```
`is.na<-.default`
function (x, value)
{
x[value] <- NA
x
}
``` |
3,535,078 | Hi I just installed Tomcat and and am trying to get it up and running however whenever I try to navigate to manager/html it gives me this error "The requested resource (/manager/html) is not available".
The homepage, /docs, /examples all work fine and my logs show nothing. How do I fix this? I'm using Tomcat 6.0.20 and JDK 1.6.0\_21 on Windows 7 64bit. | 2010/08/20 | [
"https://Stackoverflow.com/questions/3535078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426792/"
] | You have to check if you have the folder with name `manager` inside the folder `webapps` in your tomcat.
```
Rubens-MacBook-Pro:tomcat rfanjul$ ls -la webapps/
total 16
drwxr-xr-x 8 rfanjul staff 272 21 May 12:20 .
drwxr-xr-x 14 rfanjul staff 476 21 May 12:22 ..
-rw-r--r--@ 1 rfanjul staff 6148 21 May 12:20 .DS_Store
drwxr-xr-x 19 rfanjul staff 646 17 Feb 15:13 ROOT
drwxr-xr-x 51 rfanjul staff 1734 17 Feb 15:13 docs
drwxr-xr-x 6 rfanjul staff 204 17 Feb 15:13 examples
drwxr-xr-x 7 rfanjul staff 238 17 Feb 15:13 host-manager
drwxr-xr-x 8 rfanjul staff 272 17 Feb 15:13 manager
```
After that you will be sure that you have this permmint for you user in the file `conf/tomcat-users.xml`:
```
<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="test" password="test" roles="admin-gui,manager-gui"/>
```
restart tomcat and stat tomcat again.
```
sh bin/shutdown.sh
sh bin/startup.sh
```
I hope that will works fine for you. | I had the situatuion when tomcat manager did not start. I had this exception in my logs/manager.DDD-MM-YY.log:
```
org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter CSRF
java.lang.ClassNotFoundException: org.apache.catalina.filters.CsrfPreventionFilter
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
...
```
This exception was raised because I used a version of tomcat that hadn't CSRF prevention filter. Tomcat 6.0.24 doesn't have the CSRF prevention filter in it. The first version that has it is the 6.0.30 version (at least. according to the changelog). As a result, Tomcat Manager was uncompatible with version of Tomcat that I used. I've digged description of this issue here: <http://blog.techstacks.com/.m/2009/05/tomcat-management-setting-up-tomcat/comments/>
Steps to fix it:
1. Check version of tomcat installed by running "sh version.sh" from
your tomcat/bin directory
2. Download corresponding version of tomcat
3. Stop tomcat
4. Remove your webapps/manager directory and copy manager application
from distributive that you've downloaded.
5. Start tomcat
Now you should be able to access tomcat manager. |
5,583,469 | I'm making a little "you give me your email, I'll give you an AWESOME song" page for a mate's band. I'm trying to get the simple javascript form (email) validation to work when submitting from with in the jQuery Facebox plugin. I've found out that you need to bind the JS validation function *after* the Facebox has opened or it doesn't work. The basis for doing that is laid out with in the Facebox documentation and should go something like this: `$(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })`. As mentioned below, I didn't think this should be the case as I thought Facebox only showed a hidden element encased in the Facebox CSS parameters but it definitely needs to be bound to the event handler only when the Facebox is opened.
Well it turns out I just cannot get it to work (except in Firefox which meant debugging with Firebug was a bit of a no go!) - you can put any old gumpf into the email form and submit it and it happily sends a confirmation to "asdsdf" or whatever I typed in at the time.
The code is below, I'd really appreciate *any* help on this!
Thanks for your time.
Rich
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Track download</title>
<meta name="image:Background" content="images/background.jpg" />
<link rel="stylesheet" type="text/css" href="reset-min.css" />
<link rel="stylesheet" type="text/css" href="facebox.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/facebox.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a[rel*=facebox]").facebox();
});
</script>
<script type="text/javascript">
function validateForm(){
var x=document.forms["emailForm"]["emailAddress"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
alert("Not a valid e-mail address");
return false;
}
});
</script>
</head>
<body>
<div id="wrapper">
<h1>Gorgeous George</h1><br />
<h2><a href="#user" rel="facebox">Download</a> our new track!</h2><br /><br />
<p>Follow us on <a href="http://gorgeousgeorgetheband.tumblr.com" target="_blank">Tumblr</a></p>
<p>Follow us on <a href="http://soundcloud.com/gorgeous-george-the-band" target="_blank">Soundcloud</a></p>
<div id="user">
<form action="index.php" method="post" name="emailForm" onsubmit="return validateForm();">
<fieldset>
<h3 class="black">Email Address:</h3><br />
<input id="emailAddress" id="emailForm" name="emailAddress" onfocus="(this.value == "Enter Email Address") ? this.value = "" : this.value" size="30" type="text" value="Enter Email Address" width="28" /><br />
<input type="submit" value="Submit" />
</fieldset>
</form>
</div> <img src="images/gorgeousGeorge.jpg" alt="Gorgeous George" class="mainImage" />
</div>
</body>
</html>
``` | 2011/04/07 | [
"https://Stackoverflow.com/questions/5583469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609907/"
] | John Q mentioned that facebox creates a copy of the elements, so to refer to any element in the window, I gave everything a class instead of an id then referred to it thus:
```
$($('.email')[1])
```
Then, unfortunately, I had to roll my own validation because any plugin still didn't work. Here's one example:
```
if($($('.email')[1]).val().length <= 0){
return false;
}
```
Kind of a hack, but hope that helps. | From what I understand of Facebox, the contents of the modal window are always stored in the page but just hidden (by display: none) until required. Therefore you should not need to bind the validation after the facebox has loaded as the elements are in the DOM straight from page load.
With that in mind, try the following HTML. I've added in jQuery validate as it's easy to use and saves reinventing the wheel. And by wheel I mean email address format validation :)
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title><!-- Insert your title here --></title>
<meta name="image:Background" content="images/background.jpg" />
<link rel="stylesheet" type="text/css" href="reset-min.css" />
<link rel="stylesheet" type="text/css" href="facebox.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/facebox.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a[rel*=facebox]").facebox();
$("#user FORM").validate({
rules: {
emailAddress { required: true, email: true }
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<h1>Gorgeous George</h1><br />
<h2><a href="#user" rel="facebox">Download</a> our new track!</h2><br /><br />
<p>Follow us on <a href="http://gorgeousgeorgetheband.tumblr.com" target="_blank">Tumblr</a></p>
<p>Follow us on <a href="http://soundcloud.com/gorgeous-george-the-band" target="_blank">Soundcloud</a></p>
<div id="user">
<form action="index.php" method="post" name="emailForm" onsubmit="return validateForm();">
<fieldset>
<h3 class="black">Email Address:</h3><br />
<input id="emailAddress" id="emailForm" name="emailAddress" onfocus="(this.value == "Enter Email Address") ? this.value = "" : this.value" size="30" type="text" value="Enter Email Address" width="28" /><br />
<input type="submit" value="Submit" />
</fieldset>
</form>
</div> <img src="images/gorgeousGeorge.jpg" alt="Gorgeous George" class="mainImage" />
</div>
</body>
</html>
```
There's obvioulsy more ways to stylise the validation plugin, but this will at least work for you. |
23,696,556 | I've been looking around at other questions but to no avail did I find a solution. I feel like I might not be putting the svg file in the correct location for the css/html to access it
Currently, I have this in a .svg file right next to my HTML file.
```
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<filter id="blur">
<feGaussianBlur stdDeviation="3" />
</filter>
</svg>
```
My css file looks like this
```
.blur {
filter: url(#blur);
}
```
I might be not giving the correct location of the blur possibly? | 2014/05/16 | [
"https://Stackoverflow.com/questions/23696556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2423436/"
] | If your SVG is not in the HTML file, then you cannot just use `url(#blur)`. You would need to use something like `url(my_svg_file.svg#blur)`.
But if I remember correctly, those sort of external file references don't work properly in all browsers anyway. So you should move the contents of the SVG into the HTML file and leave the CSS as `url(#blur)`. | Not sure what you are trying to do but .blur{} refers to the class blur, not the id blur as used in the filter. For adding CSS to the filter try #blur{} instead. |
31,593 | I'm trying to write a function in Workbench which will generate a Fibonacci sequence starting with `F0 = 0` and `F1 = 1`. So far I have this written
```
fibonacciSequence[n_] :=
Module[{fPrev = 0, fNext = 1, i = 0},
While[i++ < n, {fPrev, fNext} = {fNext, fPrev + fNext}];
fNext]
```
How do I modify the function to make it print out a list like the one below when `fibonacciSequence[15]` is called?
```
{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}
```
Sorry, but I am very new to *Mathematica* and my professor didn't give us much instructions or examples of similar functions. | 2013/09/03 | [
"https://mathematica.stackexchange.com/questions/31593",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9350/"
] | This is probably defeating your professor's unspoken desire, but no one explicitly said you required a recursion. It may or may not entertain you to know Binet's formula. Without checking, I would guess that this approach is similar to how the built in function computes Fibonacci numbers. It is clearly computationally cheaper than any sort of recursion or nesting, and that would be noticeable deep into the sequence. This is a bit slower than the built in function, but it will do say the 3 millionth number pretty fast:
```
fibos[n_] := RootReduce@(((1 + Sqrt[5])/2)^n - ((1 - Sqrt[5])/2)^n)/Sqrt[5]
```
This could be made much shorter with some small modicum of effort. To get your table, implement it with something like:
```
Table[fibos[i], {i, 0, 15}]
``` | For giggles, here is a contour integral method (based on Cauchy's formula) for computing the Fibonacci numbers:
```
Table[Round[Re[NIntegrate[1/((1 - z - z^2) z^n),
{z, 1/2, I/2, -1/2, -I/2, 1/2}]/(2 π I)]],
{n, 10}]
{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}
``` |
46,918,397 | With dplyr starting version 0.7 the methods ending with underscore such as summarize\_ group\_by\_ are deprecated since we are supposed to use quosures.
See:
<https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html>
I am trying to implement the following example using quo and !!
Working example:
```
df <- data.frame(x = c("a","a","a","b","b","b"), y=c(1,1,2,2,3,3), z = 1:6)
lFG <- df %>%
group_by( x,y)
lFG %>% summarize( min(z))
```
However, in the case, I need to implement the columns to group by and summarize are specified as strings.
```
cols2group <- c("x","y")
col2summarize <- "z"
```
How can I get the same example as above working? | 2017/10/24 | [
"https://Stackoverflow.com/questions/46918397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2664205/"
] | From `dplyr` 1.0.0 you can use `across` :
```
library(dplyr)
cols2group <- c("x","y")
col2summarize <- "z"
df %>%
group_by(across(all_of(cols2group))) %>%
summarise(across(all_of(col2summarize), min)) %>%
ungroup
# x y z
# <chr> <dbl> <int>
#1 a 1 1
#2 a 2 3
#3 b 2 4
#4 b 3 5
``` | Another option is to use non-standard evaluation (NSE), and have R interpret the string as quoted names of objects:
```
cols2group <- c("x","y")
col2summarize <- "z"
df %>%
group_by(!!rlang::sym(cols2group)) %>%
summarize(min(!!rlang::sym(col2summarize)))
```
The `rlang::sym()` function takes the strings and turns them into quotes, which are in turn unquoted by `!!` and used as names in the context of `df` where they refer to the relevant columns. There's different ways of doing the same thing, as always, and this is the shorthand I tend to use! |
24,782,721 | I'm currently developing an iOS app using swift and Xcode 6 (Beta 3).
Everything went fine so far but now as my project grows, Xcode suddenly began indexing and it does that again and again, making Xcode nearly unusable.
I have searched the web for similar problems and tried the solutions but none of them did help.
Even disabling the indexing process (`defaults write com.apple.dt.Xcode IDEIndexDisable 1`) does not stop Xcode to do that.
While indexing, my CPU usage goes up to 300%+, causing the fans to run at highest speed.
In Activity Monitor there are several tasks named "swift" taking up about 1GB memory each. | 2014/07/16 | [
"https://Stackoverflow.com/questions/24782721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3845091/"
] | Solved it: I deleted the most recently added files from the project and the problem disappeared. Then I started to add back the files, one by one until the problem reappeared. So I found the file causing the problem. Then I deleted the most recently added code from that file and again, the problem disappeared.
That way, I found a piece of code which was responsible for that behavior. | I had that problem when I was at the swift crunch in krakow a couple weeks ago. We had the code on github, experienced that indexing problem on a macbook, we tried pulling the repo on 2 other macbooks, same result.
It's clearly a bug, I don't know what is causing it, we tried whatever we could think of (clean, clean build folder, manually removing files not in the repo, rebooting, killing processes, etc.), and after a couple hours **the only thing left to do was creating a new xcode project from scratch and manually importing the files from the other project**.
Never happened again since then, neither on that nor on other projects. |
38,462,558 | I want to use the strings listed in List\_ and pass them in my function lambda so that each iteration names changes for load or temp....ie. lambda x: x.**load**.reset\_index().T
```
List_ = {'load','Temp','Hum','Hum'}
list__ = []
for names in List_:
test = df.apply(lambda x: x.names.reset_index().T)
list__.append(df)
``` | 2016/07/19 | [
"https://Stackoverflow.com/questions/38462558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6311384/"
] | The List Objects operation appears to be eventually-consistent, even for new objects. According to a support forum post from an AWS employee ChrisP@AWS:
>
> Read-after-write consistency is only valid for GETS of new objects - LISTS might not contain the new objects until the change is fully propagated.
>
>
> — <https://forums.aws.amazon.com/thread.jspa?messageID=687028򧮴>
>
>
> | The preceding answer of @Michael had been accurate before latest announcement from AWS.
**AWS has recently announced that both read after write operation and list operation is now strongly consistent.**
Snippet from AWS:"After a successful write of a new object, or an overwrite or delete of an existing object, any subsequent read request immediately receives the latest version of the object. S3 also provides strong consistency for list operations, so after a write, you can immediately perform a listing of the objects in a bucket with any changes reflected."
Reference - <https://aws.amazon.com/s3/consistency/> |
13,319,660 | Okay I tested the following with the tabbed application template on Xcode 4.5/iOS 6.
1. Created a tabbed application.
2. Created a UIButton subclass called SampleButton and implemented
the following mothods:
```
- (void)touchesBegan:(NSSet *)touches
withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet *)touches
withEvent:(UIEvent *)event
{
[super touchesCancelled:touches withEvent:event];
}
- (void) touchesMoved:(NSSet *)touches
withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches
withEvent:(UIEvent *)event
{
[super touchesEnded:touches withEvent:event];
}
```
3. Added this SampleButton to the first tab.
4. Added breakpoints to all the touch methods.
5. Run on device.
6. Tested that all the touch methods are firing as expected.
7. Now touch the SampleButton and then also press the second tab.
RESULT: View switches to second tab but touchesCancelled and/or touchesEnded are never called in SampleButton. Shouldn't one or the other of those fire if the view changes while I'm touching that button? This is proving to be a huge issue because, in my app I'm playing a sound while that button is down and it never stops playing if the user switches tabs while pressing it. Seems like this used to work fine in iOS3 and iOS4. | 2012/11/10 | [
"https://Stackoverflow.com/questions/13319660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/480641/"
] | I worked around this by setting targets for the actions instead of using the touch methods:
```
[self addTarget:self action:@selector(handleKeyPressed) forControlEvents:UIControlEventTouchDown];
[self addTarget:self action:@selector(handleKeyReleased) forControlEvents:UIControlEventTouchUpInside];
[self addTarget:self action:@selector(handleKeyReleased) forControlEvents:UIControlEventTouchCancel];
```
These seems to get fired correctly even when the view swaps out. | Subclassing the button seems like the hard way to do this. Just tell the audio player to stop playing in the viewDidDisappear:animated: method, as R.A. suggested. |
816,656 | I assume that the iPhone Wi-Fi hardware is able to switch between channels, since my WLAN router shows me channel 1 to 13. So that WLAN spectrum must be devided up into those, I think. I would like to observe the signal strength from a specific channel within my app. Is there a way to get this data? | 2009/05/03 | [
"https://Stackoverflow.com/questions/816656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62553/"
] | There are four [transaction isolation levels](http://www.mssqlcity.com/Articles/General/TIL.htm) in SQL Server:
1. READ UNCOMMITTED
2. READ COMMITTED
3. REPEATABLE READ
4. SERIALIZABLE
For the tables it's applied to, NOLOCK is the equivalent of "read uncommitted". That means you can see rows from transactions that might be rolled back in the future, and many other strange results.
Still, nolock works very well in practice. Especially for read-only queries where displaying slightly wrong data is not the end of the world, like business reports. I'd avoid it near updates or inserts, or generally anywhere near decision making code, especially if it involves invoices.
As an alternative to nolock, consider "read committed snapshot", which is meant for databases with heavy read and less write activity. You can turn it on with:
```
ALTER DATABASE YourDb SET READ_COMMITTED_SNAPSHOT ON;
```
It is available for SQL Server 2005 and higher. This is how Oracle works by default, and it's what stackoverflow itself uses. There's even a [coding horror](http://www.codinghorror.com/blog/archives/001166.html) blog entry about it.
P.S. Long running queries and deadlocks can also indicate SQL Server is working with wrong assumptions. Check if your statistics or indexes are out of date:
```
SELECT
object_name = Object_Name(ind.object_id),
IndexName = ind.name,
StatisticsDate = STATS_DATE(ind.object_id, ind.index_id)
FROM SYS.INDEXES ind
order by STATS_DATE(ind.object_id, ind.index_id) desc
```
Statistics should be updated in a weekly maintenance plan. | You should use nolock when it is ok to read dirty data. A large transaction that may make a number of changes to the database may still be in progress, using nolock will just return the data it has set so far. Should that transaction then rollback the data you are looking at could be wrong. Therefore, you should only use it when it doesn't matter that what you get back could be wrong.
Deadlocks are a common problem, but 9 times out of 10 are entirely caused by a developer problem. I would concentrate on finding the cause of the deadlocks rather than using nolock. It is more than likely just one transaction doing things in a different order to all the others. Fixing just that one may make all your issues vanish. |
43,995,458 | I want to create a shortcode to display the date by increasing 2 days from the current date. For example, if today is 16 may, I want to show 18 may by shortcode.
Please help me with this. | 2017/05/16 | [
"https://Stackoverflow.com/questions/43995458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7392810/"
] | If the value length is fixed this will helps you
```
DECLARE @String VARCHAR(200)
SET @String = '9744123453544'
SELECT STUFF(@String, 5, LEN(@String) - 8, REPLICATE('X', LEN(@String) - 8)) AS HideValue
```
OutPut
```
HideValue
---------
9744XXXXX3544
``` | If you are on SQL Server 2016+ try using dynamic data masking feature. (<https://learn.microsoft.com/en-us/sql/relational-databases/security/dynamic-data-masking>). |
60,469,977 | Made a ror api with auth and JWT to feed a react app. In dev environment (localhost) everything was working fine. Once I deployed to heroku I started to have that error. I deployed following heroku's rails docs: <https://devcenter.heroku.com/articles/getting-started-with-rails5>
When I try to "signup" or "signing" the request fails with status code 500. What is really weird is that in the heroku rails console the user is created, but i'm not getting my token back in json. This is the call from my react app:
```
axios.post('https://hidden-ocean-49877.herokuapp.com/signup', {withCredentials: true,
name: name, email: email, password: password, password_confirmation: passwordConfirmation})
.then(response => {
login(true);
tokenize(response.data.auth_token);
}).catch(error => console.log(error));
```
this is the log in heroku log:
```
2020-02-29T21:43:16.041318+00:00 heroku[router]: at=info method=POST path="/signup" host=hidden-ocean-49877.herokuapp.com request_id=7cd577ad-c7c5-4fa7-aa99-91b4b8e49772 fwd="189.214.5.88" dyno=web.1 connect=1ms service=977ms status=500 bytes=421 protocol=https
2020-02-29T21:43:16.038685+00:00 app[web.1]: I, [2020-02-29T21:43:16.038582 #4] INFO -- : [7cd577ad-c7c5-4fa7-aa99-91b4b8e49772] Completed 500 Internal Server Error in 925ms (ActiveRecord: 29.5ms)
2020-02-29T21:43:16.039125+00:00 app[web.1]: F, [2020-02-29T21:43:16.039063 #4] FATAL -- : [7cd577ad-c7c5-4fa7-aa99-91b4b8e49772]
2020-02-29T21:43:16.039179+00:00 app[web.1]: F, [2020-02-29T21:43:16.039120 #4] FATAL -- : [7cd577ad-c7c5-4fa7-aa99-91b4b8e49772] TypeError (no implicit conversion of nil into String):
2020-02-29T21:43:16.039221+00:00 app[web.1]: F, [2020-02-29T21:43:16.039178 #4] FATAL -- : [7cd577ad-c7c5-4fa7-aa99-91b4b8e49772]
2020-02-29T21:43:16.039264+00:00 app[web.1]: F, [2020-02-29T21:43:16.039226 #4] FATAL -- : [7cd577ad-c7c5-4fa7-aa99-91b4b8e49772] app/lib/json_web_token.rb:9:in `encode'
2020-02-29T21:43:16.039264+00:00 app[web.1]: [7cd577ad-c7c5-4fa7-aa99-91b4b8e49772] app/auth/authenticate_user.rb:9:in `call'
2020-02-29T21:43:16.039264+00:00 app[web.1]: [7cd577ad-c7c5-4fa7-aa99-91b4b8e49772] app/controllers/users_controller.rb:6:in `create'
```
The files that are described above are this ones:
User controller
```
class UsersController < ApplicationController
skip_before_action :authorize_request, only: :create
def create
user = User.create!(user_params)
auth_token = AuthenticateUser.new(user.email, user.password).call
response = { message: Message.account_created, auth_token: auth_token }
json_response(response, :created)
end
private
def user_params
params.permit(
:name,
:email,
:password,
:password_confirmation
)
end
end
```
in app/auth/authenticate\_user.rb:
```
class AuthenticateUser
def initialize(email, password)
@email = email
@password = password
end
# Service entry point
def call
JsonWebToken.encode(user_id: user.id) if user
end
private
attr_reader :email, :password
def user
user = User.find_by(email: email)
return user if user && user.authenticate(password)
raise(ExceptionHandler::AuthenticationError, Message.invalid_credentials)
end
end
```
in app/lib/json\_web\_token.rb:
```
class JsonWebToken
# secret to encode and decode token
HMAC_SECRET = Rails.application.secrets.secret_key_base
def self.encode(payload, exp = 24.hours.from_now)
# set expiry to 24 hours from creation time
payload[:exp] = exp.to_i
# sign token with application secret
JWT.encode(payload, HMAC_SECRET)
end
def self.decode(token)
# get payload; first index in decoded Array
body = JWT.decode(token, HMAC_SECRET)[0]
HashWithIndifferentAccess.new body
# rescue from all decode errors
rescue JWT::DecodeError => e
# raise custom error to be handled by custom handler
raise ExceptionHandler::InvalidToken, e.message
end
end
``` | 2020/02/29 | [
"https://Stackoverflow.com/questions/60469977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11326537/"
] | Judging by the stack trace, the error happens in `app/lib/json_web_token.rb#9`. I suspect that the error happens in:
```
HMAC_SECRET = Rails.application.secrets.secret_key_base
```
then raises a type error in:
```
JWT.encode(payload, HMAC_SECRET)
```
Is it possible that your version of rails uses a new way for fetching `secret_key_base` as described here: [Rails 5.2 application secrets empty at Heroku](https://stackoverflow.com/questions/56889272/rails-5-2-application-secrets-empty-at-heroku)
Try running `Rails.application.secrets.secret_key_base` in prod console and see if it returns anything. | Use instead
```
HMAC_SECRET = Rails.application.secret_key_base
```
<https://github.com/heartcombo/devise/issues/4864> |
7,510,422 | In an application a String is a often used data type. What we know, is that the mutation of a String uses lots of memory. So what we can do is to use a StringBuilder/StringBuffer.
But at what point should we change to StringBuilder?
And what should we do, when we have to split it or to remplace characters in there?
eg:
```
//original:
String[] split = string.split("?");
//better? :
String[] split = stringBuilder.toString().split("?);
```
or
```
//original:
String replacedString = string.replace("l","st");
//better? :
String replacedString = stringBuilder.toString().replace("l","st");
//or
StringBuilder replacedStringBuilder = new StringBuilder(stringBuilder.toString().replace("l","st);
``` | 2011/09/22 | [
"https://Stackoverflow.com/questions/7510422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917672/"
] | >
> What we know, is that the mutation of a String uses lots of memory.
>
>
>
That is incorrect. Strings **cannot** be mutated. They are immutable.
What you are actually talking about is building a String from other strings. That can use a lot more memory than is necessary, but it depends *how* you build the string.
>
> So what we can do is to use a StringBuilder/StringBuffer.
>
>
>
Using a StringBuilder will help in some circumstances:
```
String res = "";
for (String s : ...) {
res = res + s;
}
```
(If the loop iterates many times then optimizing the above to use a StringBuilder *could* be worthwhile.)
But in other circumstances it is a waste of time:
```
String res = s1 + s2 + s3 + s4 + s5;
```
(It is a waste of time to optimize the above to use a StringBuilder because the Java compiler will automatically translate the expression into code that creates and uses a StringBuilder.)
You should only ever use a StringBuffer instead of a StringBuilder when the string needs to be accessed and/or updated by more than one thread; i.e. when it *needs* to be thread-safe.
>
> But at what point should we change to StringBuilder?
>
>
>
The simple answer is to *only* do it when the profiler *tells you* that you have a performance problem in your string handling / processing.
Generally speaking, StringBuilders are used for *building* strings rather as the primary representation of the strings.
>
> And what should we do, when we have to split it or to replace characters in there?
>
>
>
Then you have to review your decision to use a StringBuilder / StringBuffer as your primary representation at that point. And if it is still warranted you have to figure out how to do the operation using the API you have chosen. (This may entail converting to a String, performing the operation and then creating a new StringBuilder from the result.) | Both a `String` and a `StringBuilder` use about the same amount of memory. Why do you think it is “much”?
If you have *measured* (for example with `jmap -histo:live`) that the classes `[C` and `java.lang.String` take up most of the memory in the heap, only then should you think further in this direction.
Maybe there are multiple strings with the same value. Then, since `String`s are immutable, you could *intern* the duplicate strings. Don't use `String.intern` for it, since it has bad performance characteristics, but Google Guava's `Interner`. |
31,238 | What is the reason that a likelihood function is not a pdf (probability density function)? | 2012/06/27 | [
"https://stats.stackexchange.com/questions/31238",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/12223/"
] | We'll start with two definitions:
* A [probability density function (pdf)](http://en.wikipedia.org/wiki/Probability_density_function) is a non-negative function that integrates to $1$.
* The likelihood is defined as the joint density of the observed data as a function of the parameter. But, as pointed out by the reference to Lehmann made by @whuber in a comment below, **the likelihood function is a function of the parameter only, with the data held as a fixed constant.** So the fact that it is a density as a function of the data is irrelevant.
Therefore, the likelihood function is not a pdf because **its integral with respect to the parameter does not necessarily equal 1** (and may not be integrable at all, actually, as pointed out by another comment from @whuber).
To see this, we'll use a simple example. Suppose you have a single observation, $x$, from a ${\rm Bernoulli}(\theta)$ distribution. Then the likelihood function is
$$ L(\theta) = \theta^{x} (1 - \theta)^{1-x} $$
It is a fact that $\int\_{0}^{1} L(\theta) d \theta = 1/2$. Specifically, if $x = 1$, then $L(\theta) = \theta$, so $$\int\_{0}^{1} L(\theta) d \theta = \int\_{0}^{1} \theta \ d \theta = 1/2$$
and a similar calculation applies when $x = 0$. Therefore, $L(\theta)$ cannot be a density function.
Perhaps even more important than this technical example showing why the likelihood isn't a probability density is to point out that **the likelihood is *not* the probability of the parameter value being correct** or anything like that - **it is the probability (density) *of the data given the parameter value***, which is a completely different thing. Therefore one should not expect the likelihood function to behave like a probability density. | I'm not a statistician, but my understanding is that while the likelihood function itself is not a PDF with respect to the parameter(s), it is directly related to that PDF by Bayes Rule. The likelihood function, P(X|theta), and posterior distribution, f(theta|X), are tightly linked; not "a completely different thing" at all. |
16,154,566 | I have an MVC4 site using Castle Windsor that I want to add some WebAPI calls to, so I start digging around a little bit on the interwebs.
Now I don't know the ins and outs of IoC; I followed a tutorial for how to set up Castle Windsor on my project, injecting the `IUnitOfWorkFactory` and the `IApplicationService` as public properties in a base controller, and a few other interfaces as needed in the controller constructors. It works swimmingly, so I've never had to do more with it.
Everywhere that I'm reading up on WebAPI, I'm told DI will not work so well using Castle Windsor, talking about problems with the `IDependencyResolver` and `IDependencyScope`. There are several workarounds and implementations of how to get around this problem, but what is not clear to me is what exactly the problem is. Code snippets are included, but the assumption is you know what class they belong to, and how they are invoked, which unfortunately I do not. Additionally, all the examples I've seen online refer to an exclusive WebAPI project, and not an MVC4 project with a couple `ApiController`s judiciously tossed in. I don't know how, or if, this affects anything.
Why won't what I have working with my standard controllers not work with an API controller? What kind of code acrobatics need to do to get WebAPI calls and standard web calls to work in the same application? | 2013/04/22 | [
"https://Stackoverflow.com/questions/16154566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/610217/"
] | The following sample project gave me the answer I was looking for. It uses Castle Windsor for dependency injection. I was able to use MVC Controllers alongside Web API controllers on the same Application.
[mirajavora / WebAPISample](https://github.com/mirajavora/WebAPISample)
---
Here's the post detailing it:
[Getting Started with ASP.NET Web API](http://blog.mirajavora.com/getting-started-with-asp.net-web-api) | First as Iko stated you need to create a class that implements `IHttpControllerActivator`.
Then in `ContainerBootstrapper` in `Bootstrap()` add the following Replace the default with the one implemented:
```
//This will help in creating Web api with Dependency injection
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator),
new WindsorCompositionRoot(container));
```
Lastly which is not mentioned here and it didn't work for me without it that you should add the following in you implemented `IWindsorInstaller` service inside `install()` :
```
container.Register(
Classes.FromThisAssembly()
.BasedOn<ApiController>()
.LifestyleTransient()
);
``` |
70,699,982 | I have the following array of objects; however this could be any unknown key/value and be infinitely nested, for now this is a testing sample:
```
[
{
"reference_id": "R123",
"customer": "Person 1",
"customer_email": "person1@email.com",
"location": "UK",
"bookings": [
{
"product": "Product 1",
"provider": "Company 1",
"cancellable": true
},
{
"product": "Product 2",
"provider": "Company 2",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
},
{
"reference_id": "R1234",
"customer": "Person 2",
"customer_email": "person2@email.com",
"location": "USA",
"bookings": [
{
"product": "Product 1",
"provider": "Company 1",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
},
{
"reference_id": "R12345",
"customer": "Person 3",
"customer_email": "person3@email.com",
"location": "UK",
"bookings": [
{
"product": "Product 2",
"provider": "Company 2",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
}
]
```
My current implementation is as follows:
```
const selected = [
{
term: 'Company 1',
column: 'provider',
},
{
term: 'Person 1',
column: 'customer',
},
];
const recursivelyFilterByValue = () => (value) => selected.every((item) => {
if (!value) return false;
if (typeof value === 'string') {
// console.log('value', value === item.term);
return value === item.term;
}
if (Array.isArray(value)) {
return value.some(this.recursivelyFilterByValue());
}
if (typeof value === 'object') {
return Object.values(value).some(this.recursivelyFilterByValue());
}
return false;
});
const results = data.filter(recursivelyFilterByValue());
```
Basically I am adding to the "selected" array then using that to filter the data array by. I do want to ensure the key matches the "column" also however I haven't added that yet.
For the input above I would expect to output the below:
```
[
{
"reference_id": "R123",
"customer": "Person 1",
"customer_email": "person1@email.com",
"location": "UK",
"bookings": [
{
"product": "Product 1",
"provider": "Company 1",
"cancellable": true
},
{
"product": "Product 2",
"provider": "Company 2",
"cancellable": true
},
{
"product": "Product 3",
"provider": "Company 1",
"cancellable": true
}
]
},
]
```
However the output array is empty. If I only search for one term (remove all but one term from selected array) the output is correct for that term however any subsequent terms bring back a blank array.
I'm wondering if my use of .some() is the problem however changing this causes too much recursion errors.
Essentially, I want to return the original parent object so long as there is a key:value match for all my conditions in the selected array, at any level of its children.
Any guidance would be much appreciated, thank you. | 2022/01/13 | [
"https://Stackoverflow.com/questions/70699982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6496374/"
] | I'm not quite sure if this is what you're looking for. It makes the assumption that my guess in the comments was correct:
>
> Do I have this right? You have one (presumably dynamic) condition that says that an object either has a `provider` property with value `"Customer 1"` or has a (recursively) descendant object that does. And you have a second condition regarding `customer` and `"Person 1"`, and you're looking for objects that meet both (or all) such conditions. Does that describe what you're trying to do?
>
>
>
Here we have two fairly simple helper functions, `testRecursive` and `makePredicates` as well as the main function, `recursivelyFilterByValue`:
```js
const testRecursive = (pred) => (obj) =>
pred (obj) || Object (obj) === obj && Object .values (obj) .some (testRecursive (pred))
const makePredicates = (criteria) =>
criteria .map (({term, column}) => (v) => v [column] == term)
const recursivelyFilterByValue = (criteria, preds = makePredicates (criteria)) => (xs) =>
xs .filter (obj => preds .every (pred => testRecursive (pred) (obj)))
const selected = [{term: 'Company 1', column: 'provider'}, {term: 'Person 1', column: 'customer'}]
const input = [{reference_id: "R123", customer: "Person 1", customer_email: "person1@email.com", location: "UK", bookings: [{product: "Product 1", provider: "Company 1", cancellable: true}, {product: "Product 2", provider: "Company 2", cancellable: true}, {product: "Product 3", provider: "Company 1", cancellable: true}]}, {reference_id: "R1234", customer: "Person 2", customer_email: "person2@email.com", location: "USA", bookings: [{product: "Product 1", provider: "Company 1", cancellable: true}, {product: "Product 3", provider: "Company 1", cancellable: true}]}, {reference_id: "R12345", customer: "Person 3", customer_email: "person3@email.com", location: "UK", bookings: [{product: "Product 2", provider: "Company 2", cancellable: true}, {product: "Product 3", provider: "Company 1", cancellable: true}]}]
console .log (recursivelyFilterByValue (selected) (input))
```
```css
.as-console-wrapper {max-height: 100% !important; top: 0}
```
* **`testRecursive`** checks whether a predicate is true for an object or for any objects nested inside it.
* **`makePredicates`** turns an array of `{term, column}`-objects into predicate functions that test if an object has the proper term in the property named by the column.
* **`recursivelyFilterByValue`** combines these, calling `makePredicates` to turn the selected items into predicate functions, then filtering the input by testing if each of the predicates is true.
This is not the most efficient code imaginable. It rescans the hierarchy for each predicate. I'm sure we could figure out a version to do the scan only once, but I think it would make for much more complex code. So you might want to test in your production-sized data whether it's fast enough for your needs. | This solution is not as beautifully elegant as an accepted answer, but why not show my efforts. Perhaps someone will find this way more understandable.
```js
const selected = [{term: 'Company 1', column: 'provider'}, {term: 'Person 1', column: 'customer'}]
const input = [{reference_id: "R123", customer: "Person 1", customer_email: "person1@email.com", location: "UK", bookings: [{product: "Product 1", provider: "Company 1", cancellable: true}, {product: "Product 2", provider: "Company 2", cancellable: true}, {product: "Product 3", provider: "Company 1", cancellable: true}]}, {reference_id: "R1234", customer: "Person 2", customer_email: "person2@email.com", location: "USA", bookings: [{product: "Product 1", provider: "Company 1", cancellable: true}, {product: "Product 3", provider: "Company 1", cancellable: true}]}, {reference_id: "R12345", customer: "Person 3", customer_email: "person3@email.com", location: "UK", bookings: [{product: "Product 2", provider: "Company 2", cancellable: true}, {product: "Product 3", provider: "Company 1", cancellable: true}]}]
const iter = (obj, sel) =>
Object.entries(obj).some(([key, value]) => {
if (Array.isArray(value))
return value.some((obj) => iter(obj, sel));
if (typeof value === 'object' && value !== null)
return iter(value, sel);
return (key === sel.column) && (value === sel.term);
});
const deepFilter = (arr, sels) =>
arr.filter((obj) =>
sels.every((sel) => iter(obj, sel)));
console.dir(deepFilter(input, selected), {depth: null});
```
```css
.as-console-wrapper {max-height: 100% !important; top: 0}
``` |
44,432,951 | I have this API that I'm currently using to output a short URL or URL generator. Is there a way to pass the output to an `on-click` function.
The first script shows the API running
```
var base_url = window.location.origin,
hash_bang = "/#/sign-up?referral=",
login = "login",
api_key = "api_key";
function get_short_url(login, api_key, func, value) {
var value = document.getElementById('input-refcode').value;
$.getJSON(
"https://api-ssl.bitly.com//v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": base_url + hash_bang + value
},
function(response)
{
func(response.data.url);
}
);
}
```
---
Second is a script that shares a text via Twitter using `on-click`
```
$('#twitter').on('click', function() {
win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!', '_blank');
win.focus();
});
```
Is there a way to get the output from the first function `get_short_url` then bind it in a `on-click` like this for example
```
$('#twitter').on('click', get_short_url(login, api_key, function(short_url)) {
win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!' + short_url, '_blank');
win.focus();
});
```
I tried this solution but the browser flagged the function as a pop-up
```
$('#twitter').on('click', function() {
var base_url = window.location.origin,
hash_bang_twitter = "/%23/sign-up?referral=",
referral_code = document.getElementById('input-refcode').value;
get_short_url(login, api_key, function(short_url) {
win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up ' + short_url + ' to purchase your first timer package! After your first ride, you get 1 ride on us!' + ' https://www.electricstudio.ph/', '_blank');
win.focus();
});
});
``` | 2017/06/08 | [
"https://Stackoverflow.com/questions/44432951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2500177/"
] | There is no need to, you can simply wrap
```
$('#twitter').on('click', function() {
get_short_url(login, api_key, function(short_url) {
win = ...
win.focus();
});
});
``` | I'm no pro at js, but this seems fairly simple. I have not tested this.
```
var base_url = window.location.origin,
hash_bang = "/#/sign-up?referral=",
login = "login",
api_key = "api_key";
function get_short_url() {
var value = ('#input-refcode').val();
var result = '';
$.getJSON(
"https://api-ssl.bitly.com//v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": base_url + hash_bang + value
},
function(response)
{
result = response.data.url;
}
);
return result;
};
$('#twitter').on('click', function() {
var short_url = get_short_url(function(short_url)
if (short_url !== '') {
win = window.open('https://twitter.com/intent/tweet?text=' + encodeURI("Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us! " + short_url));
win.focus();
}
});
``` |
1,563,313 | I have a windows service and I'd like my application to be able to call some methods on that service.
I've read that this is possible via exposing the required methods with WCF.
Can someone give me a pointer on how to achieve this? I understand web services and calling them, but WCF and windows services are less my forte. | 2009/10/13 | [
"https://Stackoverflow.com/questions/1563313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64519/"
] | Have a look at this: <http://msdn.microsoft.com/en-us/library/ms724429(VS.85).aspx> | If you are looking for the productName+version that marketing uses, it's in the registry:
HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Product Name
Looking at my computer, it says "Windows 8.1 Pro". |
56,199,965 | I'm doing a HTML form, it's meant to create step to pass on a game and I want to be able to enter a number and when for example I enter 5 it instantly show me 5 form to fill and create new step but when I try it doesn't appear how can I do please?
```php
<h3>Insertion des étape :</h3>
<form action="InsertionEtape.php" method="post">
<input type="number" name="quantity" min="1" max="5">
<br>
<?php for ($i=0; $i < $_GET['quantity']; $i++) {
?>
<h5>Nom de l'étape</h5>
<input type="text" name="NomEtape" size="40" maxlength="40">
<br>
<h5> Description de l'étape </h5>
<textarea name="DescriptionEtape" rows="8" cols="80"></textarea>
<br>
<br>
<input type="submit" value="Valider">
<?php
} ?>
</form>
``` | 2019/05/18 | [
"https://Stackoverflow.com/questions/56199965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11359851/"
] | Right so it sounds like you want this form to update on page. For this you'll need to use JavaScript. PHP runs server side only, you want this to update on the client side.
Here is a quick example to get you on the right path. I am using jQuery which is a popular Javascript library.
```js
var $group = $('form .group').clone();
$('[name="quantity"]').on('change input keyup cut paste', function() {
var quantity = parseInt($(this).val());
$('form .group').remove();
for (var i = 0; i < quantity; i++) {
$group.clone().insertBefore('form [type="submit"]');
}
});
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Insertion des étape :</h3>
<form action="InsertionEtape.php" method="post">
<input type="number" name="quantity" value="1" min="1" max="5">
<br>
<div class="group">
<h5>Nom de l'étape</h5>
<input type="text" name="NomEtape[]" size="40" maxlength="40">
<br>
<h5> Description de l'étape </h5>
<textarea name="DescriptionEtape[]" rows="8" cols="80"></textarea>
<br>
</div>
<input type="submit" value="Valider">
</form>
``` | okey I changed to this but an error appeared,
```php
<form action="InsertionEtape.php" method="post">
<input type="number" name="quantity" min="1" max="5">
<br>
<?php for ($i=0; $i < $_GET['quantity']; $i++) {
echo "<h5>Nom de l'étape</h5>";
echo "<input type=\"text\" name=\"NomEtape_".$i."\" size=\"40\" maxlength=\"40\"> <br>";
?>
<h5> Description de l'étape </h5>
<textarea name="DescriptionEtape" rows="8" cols="80"></textarea>
<br>
<br>
<input type="submit" value="Valider">
<?php
} ?>
</form>
```
>
> Notice: Undefined index: quantity in /\*\*\*/\*\*\*\*\*\*\*\*\*\*/\*\*\*\*\*/\*\*\*\*\*\*/WWW/Page\_Administrateur/FormulaireInsertion.php on line 106
>
>
> |
52,537 | I'm trying to get through a proof of Gauss' that certain primes can be written as the sum of two squares. An assumption is that
>
> the order of $\mathbb{Z}[i]/(a+bi)$ is $a^2+b^2$.
>
>
>
I get that $(a+bi)(a-bi)=a^2+b^2$, so this places a bound on the order of integers with no imaginary part. But since $b$ isn't a unit, it doesn't seem like this finishes the proof.
Any hints? | 2011/07/20 | [
"https://math.stackexchange.com/questions/52537",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/2549/"
] | Expanding on Qiaochu's comment, but trying to leave you some room to think:
$\mathbb{Z}[i]$ is a *square [lattice](http://en.wikipedia.org/wiki/Lattice_%28group%29)* in the complex plane, and the ideal $(a+bi)$ is a square sublattice. (Why?) The index of $(a+bi)$ in $\mathbb{Z}[i]$ is the number of elements of $\mathbb{Z}[i]$ inside a fundamental square of $(a+bi)$, including part but not all of its boundary. (Why? And what's with the boundary funny business?) This is the same as the ratio of the area of the fundamental square of $\mathbb{Z}[i]$ to the area of the fundamental square of the sublattice $(a+bi)$. (Why?)
$\mathbb{Z}[i]$'s fundamental square is a unit square, so the question is really about the area of $(a+bi)$'s fundamental square. The line from $0$ to $a+bi$ is a side of this square... | *Hint:* The Gaussian integers are a Euclidean domain with respect to the norm. Hence given $z\in \mathbb Z[i]$ there are $q$ and $r$ in $\mathbb Z[i]$ such that $z=q(a+bi)+r$, with $r=0$ or $N(r)<N(a+bi)$. |
5,117,538 | I have Magento set up to not display VAT on checkout, but it is still adding at the total. It doesn't add it up to the total - which IS correct.
For example if I have an item that costs £5 - with 20% VAT it is £6 and this is set to show in the catalogue prices - which it does. Now on checkout this item would display as £6, then £1 VAT and then shows the total, which is £6..? Has anyone else seen this? | 2011/02/25 | [
"https://Stackoverflow.com/questions/5117538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/616562/"
] | To hide the tax comment out in /app/code/local/Mage/Sales/Model/Quote/Address/Total/Tax.php at the end of the file:
```
public function fetch(Mage_Sales_Model_Quote_Address $address)
{
$applied = $address->getAppliedTaxes();
$store = $address->getQuote()->getStore();
$amount = $address->getTaxAmount();
/* if (($amount!=0) || (Mage::helper('tax')->displayZeroTax($store))) {
$address->addTotal(array(
'code'=>$this->getCode(),
'title'=>Mage::helper('sales')->__('Tax'),
'full_info'=>$applied ? $applied : array(),
'value'=>$amount
));
} */
return $this;
}
```
To include the tax in the shipping costs, change in /app/code/local/Mage/Sales/Model/Quote/Address/Total/Subtotal.php at the end of the file
```
public function fetch(Mage_Sales_Model_Quote_Address $address)
{
$amount = $address->getShippingAmount();
if ($amount!=0 || $address->getShippingDescription()) {
$address->addTotal(array(
'code'=>$this->getCode(),
'title'=>Mage::helper('sales')->__('Shipping & Handling').' ('.$address->getShippingDescription().')',
// OLD 'value'=>$address->getShippingAmount()
'value'=>number_format($address->getShippingAmount() + $address->getShippingTaxAmount(), 2)
));
}
return $this;
}
```
To include the tax in the subtotal, change in /app/code/local/Mage/Sales/Model/Quote/Address/Total/Subtotal.php at the end of the file:
```
public function fetch(Mage_Sales_Model_Quote_Address $address)
{
$address->addTotal(array(
'code'=>$this->getCode(),
'title'=>Mage::helper('sales')->__('Subtotal'),
// OLD 'value'=>$address->getSubtotal()
'value'=>number_format($address->getSubtotal() + $address->getTaxAmount() - $address->getShippingTaxAmount(), 2)
));
return $this;
}
``` | In the end the only way i solved this was by removing the tax out of magento and check the box that says the prices that we submit contain tax. Not ideal. |
60,533,617 | I'm trying to integrate keycloak with a spring boot app and i have a few issues with it.I'm trying to define some endpoints that should be excluded from keycloak validation and let everyone make requests to those endpoints but it's not working.
Here is my config:
```
keycloak.realm=spring-security-quickstart
keycloak.auth-server-url=######
keycloak.ssl-required=external
keycloak.resource=app-authz-spring-security
keycloak.bearer-only=true
keycloak.credentials.secret=secret
keycloak.securityConstraints[0].authRoles[0]=user
keycloak.securityConstraints[0].securityCollections[0].patterns[0]=/testUser
keycloak.securityConstraints[1].authRoles[0]=offline_access
keycloak.securityConstraints[1].securityCollections[0].patterns[0]=/testAdmin
keycloak.securityConstraints[2].authRoles[0]=offline_access
keycloak.securityConstraints[2].securityCollections[0].patterns[0]=/testResource
keycloak.securityConstraints[3].authRoles[0]=*
keycloak.securityConstraints[3].securityCollections[0].patterns[0]=/test
keycloak.policy-enforcer-config.lazy-load-paths=true
logging.level.root=DEBUG
logging.level.org.springframework.boot=DEBUG
spring.main.banner-mode=CONSOLE
```
I've tried to use widlcards but whenever i make a call to /test endpoint it gives me 403 forbidden :(
And in my console i see this:
```
2020-03-04 21:45:57.421 DEBUG 4472 --- [nio-8762-exec-6] o.a.tomcat.util.net.SocketWrapperBase : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@6b4af61c:org.apache.tomcat.util.net.NioChannel@6a67dfe1:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8762 remote=/0:0:0:0:0:0:0:1:51222]], Read from buffer: [0]
2020-03-04 21:45:57.421 DEBUG 4472 --- [nio-8762-exec-6] org.apache.tomcat.util.net.NioEndpoint : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@6b4af61c:org.apache.tomcat.util.net.NioChannel@6a67dfe1:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8762 remote=/0:0:0:0:0:0:0:1:51222]], Read direct from socket: [230]
2020-03-04 21:45:57.421 DEBUG 4472 --- [nio-8762-exec-6] o.a.coyote.http11.Http11InputBuffer : Received [GET /test HTTP/1.1
User-Agent: PostmanRuntime/7.22.0
Accept: */*
Cache-Control: no-cache
Postman-Token: c9cb4fdc-af21-40a3-bff0-8463c81e01d6
Host: localhost:8762
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
]
2020-03-04 21:45:57.422 DEBUG 4472 --- [nio-8762-exec-6] o.k.adapters.PreAuthActionsHandler : adminRequest http://localhost:8762/test
2020-03-04 21:45:57.422 DEBUG 4472 --- [nio-8762-exec-6] o.a.c.authenticator.AuthenticatorBase : Security checking request GET /test
2020-03-04 21:45:57.422 DEBUG 4472 --- [nio-8762-exec-6] org.apache.catalina.realm.RealmBase : Checking constraint 'SecurityConstraint[null]' against GET /test --> false
2020-03-04 21:45:57.422 DEBUG 4472 --- [nio-8762-exec-6] org.apache.catalina.realm.RealmBase : Checking constraint 'SecurityConstraint[null]' against GET /test --> false
2020-03-04 21:45:57.422 DEBUG 4472 --- [nio-8762-exec-6] org.apache.catalina.realm.RealmBase : Checking constraint 'SecurityConstraint[null]' against GET /test --> false
2020-03-04 21:45:57.422 DEBUG 4472 --- [nio-8762-exec-6] org.apache.catalina.realm.RealmBase : Checking constraint 'SecurityConstraint[null]' against GET /test --> true
2020-03-04 21:45:57.422 DEBUG 4472 --- [nio-8762-exec-6] o.a.c.authenticator.AuthenticatorBase : Calling hasUserDataPermission()
2020-03-04 21:45:57.422 DEBUG 4472 --- [nio-8762-exec-6] org.apache.catalina.realm.RealmBase : User data constraint has no restrictions
2020-03-04 21:45:57.422 DEBUG 4472 --- [nio-8762-exec-6] o.a.c.authenticator.AuthenticatorBase : Calling authenticate()
2020-03-04 21:45:57.422 DEBUG 4472 --- [nio-8762-exec-6] o.k.adapters.RequestAuthenticator : NOT_ATTEMPTED: bearer only
2020-03-04 21:45:57.422 DEBUG 4472 --- [nio-8762-exec-6] o.k.a.authorization.PolicyEnforcer : Policy enforcement is enabled. Enforcing policy decisions for path [http://localhost:8762/test].
2020-03-04 21:45:57.423 DEBUG 4472 --- [nio-8762-exec-6] o.k.a.a.KeycloakAdapterPolicyEnforcer : Sending challenge
2020-03-04 21:45:57.423 DEBUG 4472 --- [nio-8762-exec-6] o.k.a.authorization.PolicyEnforcer : Policy enforcement result for path [http://localhost:8762/test] is : DENIED
2020-03-04 21:45:57.423 DEBUG 4472 --- [nio-8762-exec-6] o.k.a.authorization.PolicyEnforcer : Returning authorization context with permissions:
2020-03-04 21:45:57.423 DEBUG 4472 --- [nio-8762-exec-6] o.a.c.authenticator.AuthenticatorBase : Failed authenticate() test
2020-03-04 21:45:57.424 DEBUG 4472 --- [nio-8762-exec-6] o.a.tomcat.util.net.SocketWrapperBase : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@6b4af61c:org.apache.tomcat.util.net.NioChannel@6a67dfe1:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8762 remote=/0:0:0:0:0:0:0:1:51222]], Read from buffer: [0]
2020-03-04 21:45:57.424 DEBUG 4472 --- [nio-8762-exec-6] org.apache.tomcat.util.net.NioEndpoint : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@6b4af61c:org.apache.tomcat.util.net.NioChannel@6a67dfe1:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8762 remote=/0:0:0:0:0:0:0:1:51222]], Read direct from socket: [0]
2020-03-04 21:45:57.424 DEBUG 4472 --- [nio-8762-exec-6] o.apache.coyote.http11.Http11Processor : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@6b4af61c:org.apache.tomcat.util.net.NioChannel@6a67dfe1:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8762 remote=/0:0:0:0:0:0:0:1:51222]], Status in: [OPEN_READ], State out: [OPEN]
2020-03-04 21:45:57.424 DEBUG 4472 --- [nio-8762-exec-6] org.apache.tomcat.util.net.NioEndpoint : Registered read interest for [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper@6b4af61c:org.apache.tomcat.util.net.NioChannel@6a67dfe1:java.nio.channels.SocketChannel[connected local=/0:0:0:0:0:0:0:1:8762 remote=/0:0:0:0:0:0:0:1:51222]]
```
Where's the problem coming from?Is it because i did the request without a token?Or is it because of the policy enforcer?Also, do i need to make any changes into keyloak dashboard? | 2020/03/04 | [
"https://Stackoverflow.com/questions/60533617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8747553/"
] | Found the problem. While the app was running with no other issues than the one stated, when I went to replicate the problem on StackBlitz, the code there gave me an error, telling me that I needed to add the `CrudListComponent` on my @NgModule declaration, so all I had to do was to add the component there, rebuild the app and it worked.
crud.module.ts
```
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { CrudListComponent } from '@modules/crud/crud-list/crud-list.component';
import { CrudFormComponent } from '@modules/crud/crud-form/crud-form.component';
import { CrudComponent } from '@modules/crud/crud.component';
const routes: Routes = [
{
path: '', component: CrudComponent, children: [
{ path: '', component: CrudListComponent },
{ path: 'create', component: CrudFormComponent },
{ path: 'edit/:id', component: CrudFormComponent }
]
},
];
@NgModule({
declarations: [CrudComponent, CrudListComponent, CrudFormComponent],
imports: [CommonModule, RouterModule.forChild(routes)]
})
export class CrudModule { }
``` | This issue is present in the angular 9. I was using **angular(9.0.1)** version so upgraded to **~10.0.9** and now it's working. |
15,330 | You have been chosen to participate in a selection process for a secret underground group. To make sure you're worthy, they test you with a series of devious puzzles. However, one in particular has you stumped...
The challenge you receive is as follows:
>
> People aren't very good at observing things. We hope you are better.
> To solve this challenge, you will need to inspect the contents of the link below:
>
> [http://i.stack.imgur.com/XKGpe.png](https://i.stack.imgur.com/X2plV.png/)
>
> We look forward to your success.
> - The Underground Group
>
>
>
The solution is obvious once found, and requires no special skills to uncover.
But, of course, you need to keep your eyes and mind open... | 2015/05/22 | [
"https://puzzling.stackexchange.com/questions/15330",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/7308/"
] | Not done yet, I think, but:
>
> Using the fill option in paint, this came out:
>
> 
>
> Keep looking!
>
>
>
Also:
>
> The displayed and actual link are different. Following the displayed link shows:
>
> 
>
> Again, filling it in in paint shows:
>
> 
>
> So, is the answer 404? Or is it something to do with either imgur or PSE's 404 page?
>
>
> | The solution is
>
> 404
>
>
>
How it's hidden...
>
> The linked image is described as [http://i.stack.imgur.com/XKGpe.png](https://i.stack.imgur.com/XKGpe.png)
> but actually points to [http://i.stack.imgur.com/X2plV.png/](https://i.stack.imgur.com/X2plV.png/).
> The image actually linked to contains very faint text that reads Keep Looking.
> The file XKGpe.png contains to real solution.
> Using a flood fill or colour replacement tool will reveal the text.
>
>
> |
256,141 | I am lost I just can't seem to get my head around backtracking/recursion approaches. I understand how simple recursion problems like factorials work I can even trace those by hand. But when it comes to backtracking problems I am so lost. I keep trying. its been 5 hours I have been reading various approaches on forums and stack exchange but nothing has clicked.
For instance say I have a array with `[1,2,3,4]` and my destination value is `5`. I am trying to find all possible combinations that equal to my destination value.
I broke this problem down further to make it even more simple for my self to understand. First I can find all possible combinations of the array and then pass them to another function which checks if the sum of that array equals destination value and then only does it print it.
Can someone advice how to approach this? I am not looking for code/answer I want to be able to think and imagine this in my head clearly. | 2014/09/12 | [
"https://softwareengineering.stackexchange.com/questions/256141",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/132623/"
] | You want to enumerate recursively the set of sublists of `1 :: 2 :: 3 :: 4 :: []` which sums to `5`. (The `::` is the OCaml notation for the list construction.) The recursive step in list processing is splitting the list in its head `1` and its tail `2 :: 3 :: 4 :: []` — can we describe our set in these terms?
There is two kinds of sublists of `1 :: 2 :: 3 :: 4 :: []` which sums to `5`:
* The first kind consists of lists starting with `1` and followed by a list which sums to `4 = 5 - 1`.
* The second kind consists of sublists of `2 :: 3 :: 4 :: []` summing to `5`.
Wonderful! If we call `partition` the function `int list -> int -> int list list` finding all the required sublists, the description above just describes how to define `partition lst` for lists `lst`of length `n` given its definition for lists of length `n-1`.
Writing the function in OCaml is then staightforward:
```
let rec partition lst w =
if w = 0 then
[[]]
else
match lst with
| [] -> []
| hd :: tl -> firstkind hd tl (w - hd) @ partition tl w
and firstkind hd tl w =
List.map (fun lst -> hd :: lst) (partition tl w)
``` | I'm assuming for the purpose of this exercise that you don't want any repeats. For example, the combinations for [1..4] are
```
[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,4],[1,3],[1,3,4],
[1,4],[2],[2,3],[2,3,4],[2,4],[3],[3,4],[4]]
```
If not, the process is really the same for all recursive functions: figure out your bases cases, and figure out your larger problem in terms of a smaller problem.
We're going to create a function `subarrays` that takes a list and returns a list of lists—one for every combination, so:
```
subarrays :: [a] -> [[a]]
```
The base case is usually very easy. In this case, the subarrays for an empty list is an empty list, so:
```
subarrays [] = []
```
The recursive step for list functions almost always breaks it into the first element, called the "head" (denoted here by `x`), and the rest of the list, called the "tail" (denoted here by `xs`). We assume we already know the correct answer for the tail, and we use that to build an answer for the head. Here we assign the symbol `combos` to the answer for the tail:
```
subarrays (x:xs) = let combos = subarrays xs
```
So far this is relatively boilerplate code that you find on almost every recursive function in one form or another. The tricky part is now that we've solved it for a smaller list, how do we add another layer?
For an example, assume `combos` contains all the solutions for [2,3,4] and you're building a list that also contains solutions containing `1`. In this case, you can do one of three things to build the larger list.
* Just have `1` by itself. (`[x]`)
* Just have all the other combos by themselves. (`combos`)
* Have all the other combos with a `1` added. (`map (x:) combos`)
Then return a list containing all those possibilities:
```
[x] : map (x:) combos ++ combos
```
That's really all there is to it. Here's the complete program in Haskell with the sum test function as well:
```
subarrays :: [a] -> [[a]]
subarrays [] = []
subarrays (x:xs) = let combos = subarrays xs
in [x] : map (x:) combos ++ combos
combosSumTo :: Int -> [Int] -> [[Int]]
combosSumTo x = filter (\y -> sum y == x) . subarrays
```
As far as how I came up with the three things, you just sort of have to practice, and test and repeat. When I first wrote this just now, I accidentally forgot the `[x]` part, but that showed up in my tests. The trick is don't try to recurse down the stack in your head. Just assume the recursive call gives you the correct answer for the tail of the list. |
26,251 | Numbers 25:9 (NKJV)
>
> 9 And those who died in the plague were twenty-four thousand.
>
>
>
1 Corinthians 10:8 (NKJV)
>
> 8 Nor let us commit sexual immorality, as some of them did, and in one day twenty-three thousand fell;
>
>
>
Assuming Paul was referencing to the incident of Baal of peor where Israel committed sexual immorality,how can we reconcile the difference in terms of numbers that fell in one day | 2016/12/18 | [
"https://hermeneutics.stackexchange.com/questions/26251",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/16527/"
] | The 23,000 refers to the worship of the gods of Moab and the sexual immorality between some Israelite men and the the daughters of Moab. This is known as the rebellion of Baal of Peor at which 24,000 died by the plague ([Numbers 25:9](https://www.biblegateway.com/passage/?search=Numbers%2025%3A9&version=ESV)).
As noted [here](https://hermeneutics.stackexchange.com/questions/1305/per-1-cor-108-when-did-god-kill-23-000-for-sexual-immorality/1308#1308) it is possible to see Paul’s 23,000 as a simple understatement and as such is not literally wrong.
Baal Peor was one of the events during the Exodus which Paul sees as an example:
>
> 6 Now these things took place as **examples** for us, that we might not desire evil as they did. 7 Do not be idolaters as some of them were; as it is written, “The people sat down to eat and drink and rose up to play.” **8 We must not indulge in sexual immorality as some of them did, and twenty-three thousand fell in a single day.** 9 We must not put Christ to the test, as some of them did and were destroyed by serpents, 10 nor grumble, as some of them did and were destroyed by the Destroyer. 11 Now these things happened to them as an **example**, but they were written down for our instruction... (1 Corinthians 10) [ESV]
>
>
>
When approached as an example for the church, it is possible to understand why Paul understated the total and, in doing so was being more precise.
In the event of Baal of Peor, people died in different ways:
>
> 4 And the LORD said to Moses, “Take all the chiefs of the people and hang them in the sun before the LORD, that the fierce anger of the LORD may turn away from Israel.” 5 And Moses said to the judges of Israel, “Each of you kill those of his men who have yoked themselves to Baal of Peor.” ... 7 When Phinehas the son of Eleazar, son of Aaron the priest, saw it, he rose and left the congregation and took a spear in his hand 8 and went after the man of Israel into the chamber and pierced both of them, the man of Israel and the woman through her belly. Thus the plague on the people of Israel was stopped. (Numbers 25)
>
>
>
The “plague” was stopped after the leaders were hung and Phinehas killed the man and the Midianite woman. The total includes those who were hung, the two Phinehas killed, and those who died by some other means.
The "plague" is [מַגֵּפָה](https://www.blueletterbible.org/lang/lexicon/lexicon.cfm?Strongs=H4046&t=KJV) which is elsewhere translated as "slaughter:"
>
> The messenger replied, “Israel has fled before the Philistines, and there has also been a great slaughter (מַגֵּפָה) among the troops; your two sons also, Hophni and Phinehas, are dead, and the ark of God has been captured.” (1 Samuel 4:17 NRSV)
>
>
>
In using this event as an example the total who died was 24,000. That is "the slaughter" which is made up of three groups: those who died by hanging, two who died by the spear, and everyone else. Paul says 23,000 [πίπτω](https://www.blueletterbible.org/lang/lexicon/lexicon.cfm?Strongs=G4098&t=KJV), literally they "fell:"
>
> We must not indulge in sexual immorality as some of them did, and twenty-three thousand fell (πίπτω) in a single day. (1 Corinthians 10:8)
>
>
>
Normally someone who dies, falls. However, Jesus, the head of the church, died and did not fall. He was hanging at the time of His death, just as were the leaders who sinned at Baal of Peor.
The events at Baal of Peor become an example when the Church is the "everyone else" who died, then 23,000 who "fell" becomes a purposeful understatement of the total (which may actually be correct if the number of those who were hung totaled 998). Paul understands the significance of the LORD having the Israelite leaders hung in the sun before the LORD.
The "understated" total draws attention to the reality the head of the Church died while hanging on the cross. Like those leaders at Baal Peor, Jesus was hung in the sun in order to turn away the anger of the LORD from the all who were yoked to sin. | They probably cannot easily be reconciled, but one must ask whether the point of Paul's teaching is to firmly establish exactly how many perished in the plague of old, or is rather that Christians should avoid sexual immorality.
According to the apparatus of the Nestle-Aland Greek English New Testament (11th ed.), certain Latin and Syriac manuscripts do, in fact, indicate 24,000 instead of 23,000, as does one Greek Miniscule dating from the 11th century ([81](https://en.wikipedia.org/wiki/Minuscule_81)), but the majority of manuscripts do indicate 24 and not 23 thousand.
John Chrysostom (4th c.), who normally does not shy away from addressing inconsistencies in Scripture when they occur, does not even mention the discrepancy in his [homily on this passage](https://www.ccel.org/ccel/schaff/npnf112.iv.xxiv.html). One might surmise that the Septuagint (which was favored by the eastern Fathers) perhaps indicates 23 instead of 24 thousand, but this seems not to be the case. Chrysostom is more concerned with the moral of the story rather than the precise details:
>
> “Neither let us commit fornication, as some of them committed.”
> Wherefore doth he here make mention of fornication again, having so
> largely discoursed concerning it before? It is ever Paul’s custom when
> he brings a charge of many sins, both to set them forth in order and
> separately to proceed with his proposed topics, and again in his
> discourses concerning other things to make mention also of the former:
> which thing God also used to do in the Old Testament, in reference to
> each several transgression, reminding the Jews of the calf and
> bringing that sin before them. This then Paul also does here, at the
> same time both reminding them of that sin, and teaching that the
> parent of this evil also was luxury and gluttony. Wherefore also he
> adds, “Neither let us commit fornication, as some of them committed,
> and fell in one day three and twenty thousand.”
>
>
> |
60,275,044 | I have two dates like 2020-12-31 and 2020-12-01 in string format yyyy-mm-dd while check the month it should return true.
Suppose I compare 2020-11-31 and 2020-12-31 it should return false.
If there is a difference in only month and year, it should return true.
For example today Feb 18, 2020, Suppose I choose Feb 11, 2020, it should return true, If I choose Jan 11, 2020, then it should return false.
**Date difference should not be considered** | 2020/02/18 | [
"https://Stackoverflow.com/questions/60275044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4117259/"
] | You can go with the following code:
```
const date1 = new Date('2020-12-01');
const date2 = new Date('2020-12-31');
// if you want to return true or false based on either date or month or year difference then use the following code.
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
// this way if there is difference in either date or month or year then it will return true
if(diffDays) {
return true;
} else {
return false;
}
```
If you want to return either true or false on basis of either month or year only then you can use the following code.
```
const date1 = new Date('2020-12-01');
const date2 = new Date('2020-12-31');
// return basis on difference of either month OR year
return date1.getMonth() === date2.getMonth() || date1.getYear() === date2.getYear()
// return basis on the difference of month AND year
return date1.getMonth() === date2.getMonth() && date1.getYear() === date2.getYear()
``` | Shorted, faster, and simpler solution is:
```js
"2020-11-31".substr(5, 2) === "2020-12-31".substr(5, 2)
``` |
3,165,409 | 
Hello, I am confused as to how they got 5y in this problem when they multiplied dx/dy by dy/dt in the fourth line.
I am also confused as to what dx/dt and dx/dy and dy/dt mean. | 2019/03/28 | [
"https://math.stackexchange.com/questions/3165409",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/649779/"
] | You have:
$|z^2-1|=|z|^2+1$.
Squaring both sides:
$|z^2-1|^2=(|z|^2+1)^2$.
Since:$|a-b|^2=|a|^2+|b|^2-a\bar b-\bar a b$
Now You have:
$|z|^4+1-z^2-\bar z^2=|z|^4+2|z|^2+1$
Rearranging and cancelling terms:
$2|z|^2+z^2+\bar z^2=0$
Now, $|z|^2=z\bar z$
So, you get $(z+\bar z)^2=0$
i.e., $z+\bar z=0$ z is the set of purely imaginary numbers | Note that for $u,v \in \mathbb{C}$ you have
* $|u+v| \leq |u| + |v|$ and equality holds if and only if $\operatorname{Re}(u\bar v)=|u||v|$.
Applying this to the given equation you get
$$|z^2 + (-1)| = |z|^2 +1 \Leftrightarrow \operatorname{Re}(z^2\cdot (-1)) = |z|^2 \Leftrightarrow \boxed{\operatorname{Re}(z^2) = -|z|^2}$$
With $z= x+iy$ you get immediately
$$\boxed{\operatorname{Re}(z^2) = -|z|^2} \Leftrightarrow x^2-y^2 = -(x^2+y^2) \Leftrightarrow x = 0, \; y \in \mathbb{R} \Leftrightarrow \boxed{z = iy}$$ |
38,991,478 | I have two Python lists with the same number of elements. The elements of the first list are unique, the ones in the second list - not necessarily so. For instance
```
list1 = ['e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7']
list2 = ['h1', 'h2', 'h1', 'h3', 'h1', 'h2', 'h4']
```
I want to remove all the "first encountered" elements from the second list and their corresponding elements from the first list. Basically, this means removing all unique elements *and* the first element of the duplicates. With the above example, the correct result should be
```
>>>list1
['e3', 'e5', 'e6']
>>>list2
['h1', 'h1', 'h2']
```
That is, the element 'e1' was removed because its corresponding 'h1' was encountered for the first time, 'e2' was removed because 'h2' was seen for the first time, 'e3' was left because 'h1' was already seen, 'e4' was removed because 'h3' was seen for the first time, 'e5' was left because 'h1' was already seen, 'e6' was left because 'h2' was already seen, and 'e7' was removed because 'h4' was seen for the first time.
What would be an efficient way to solve this problem? The lists could contain thousands of elements, so I'd rather not make duplicates of them or run multiple loops, if possible. | 2016/08/17 | [
"https://Stackoverflow.com/questions/38991478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6597296/"
] | Just use a `set` object to lookup if the current value is already seen, like this
```
>>> list1 = ['e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7']
>>> list2 = ['h1', 'h2', 'h1', 'h3', 'h1', 'h2', 'h4']
>>>
>>> def filterer(l1, l2):
... r1 = []
... r2 = []
... seen = set()
... for e1, e2 in zip(l1, l2):
... if e2 not in seen:
... seen.add(e2)
... else:
... r1.append(e1)
... r2.append(e2)
... return r1, r2
...
>>> list1, list2 = filterer(list1, list2)
>>> list1
['e3', 'e5', 'e6']
>>> list2
['h1', 'h1', 'h2']
```
---
If you are going to consume the elements one-by-one and if the input lists are pretty big, then I would recommend making a generator, like this
```
>>> def filterer(l1, l2):
... seen = set()
... for e1, e2 in zip(l1, l2):
... if e2 not in seen:
... seen.add(e2)
... else:
... yield e1, e2
...
>>> list(filterer(list1, list2))
[('e3', 'h1'), ('e5', 'h1'), ('e6', 'h2')]
>>>
>>> zip(*filterer(list1, list2))
[('e3', 'e5', 'e6'), ('h1', 'h1', 'h2')]
``` | Use a set to keep track of values you've already encountered:
```
seen= set()
index= 0
while index < len(list1):
i1, i2= list1[index], list2[index]
if i2 in seen:
index+= 1
else:
seen.add(i2)
del list1[index]
del list2[index]
``` |
9,027,046 | So I clicked on my storyboard in Xcode today and all of my controllers were squashed. I dragged out an empty ViewController on the left for comparison. Has anyone else encountered this?  | 2012/01/26 | [
"https://Stackoverflow.com/questions/9027046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152845/"
] | This is a bit fragile since it relies on understanding the internals of `argparse.ArgumentParser`, but in lieu of rewriting `argparse.ArgumentParser.parse_known_args`, here's what I use:
```
class OrderedNamespace(argparse.Namespace):
def __init__(self, **kwargs):
self.__dict__["_arg_order"] = []
self.__dict__["_arg_order_first_time_through"] = True
argparse.Namespace.__init__(self, **kwargs)
def __setattr__(self, name, value):
#print("Setting %s -> %s" % (name, value))
self.__dict__[name] = value
if name in self._arg_order and hasattr(self, "_arg_order_first_time_through"):
self.__dict__["_arg_order"] = []
delattr(self, "_arg_order_first_time_through")
self.__dict__["_arg_order"].append(name)
def _finalize(self):
if hasattr(self, "_arg_order_first_time_through"):
self.__dict__["_arg_order"] = []
delattr(self, "_arg_order_first_time_through")
def _latest_of(self, k1, k2):
try:
print self._arg_order
if self._arg_order.index(k1) > self._arg_order.index(k2):
return k1
except ValueError:
if k1 in self._arg_order:
return k1
return k2
```
This works through the knowledge that `argparse.ArgumentParser.parse_known_args` runs through the entire option list once setting default values for each argument. Meaning that user specified arguments begin the first time `__setattr__` hits an argument that it's seen before.
Usage:
```
options, extra_args = parser.parse_known_args(sys.argv, namespace=OrderedNamespace())
```
You can check `options._arg_order` for the order of user specified command line args, or use `options._latest_of("arg1", "arg2")` to see which of `--arg1` or `--arg2` was specified later on the command line (which, for my purposes was what I needed: seeing which of two options would be the overriding one).
UPDATE: had to add `_finalize` method to handle pathological case of `sys.argv()` not containing any arguments in the list) | There is module especially made to handle this :
<https://github.com/claylabs/ordered-keyword-args>
without using orderedkwargs module
----------------------------------
```
def multiple_kwarguments(first , **lotsofothers):
print first
for i,other in lotsofothers:
print other
return True
multiple_kwarguments("first", second="second", third="third" ,fourth="fourth" ,fifth="fifth")
```
output:
```
first
second
fifth
fourth
third
```
On using orderedkwargs module
-----------------------------
```
from orderedkwargs import ordered kwargs
@orderedkwargs
def mutliple_kwarguments(first , *lotsofothers):
print first
for i, other in lotsofothers:
print other
return True
mutliple_kwarguments("first", second="second", third="third" ,fourth="fourth" ,fifth="fifth")
```
Output:
```
first
second
third
fourth
fifth
```
Note: Single asterik is required while using this module with decorator above the function. |
10,139,779 | I have my .htaccess file redirecting all URLs to index.php?url=$1 as shown below:
```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L]
```
But when the url is authenticate?code=blahblahblah the code= part is not pulled in, therefore meaning I cannot access it when handling the page D: Any help? | 2012/04/13 | [
"https://Stackoverflow.com/questions/10139779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/715474/"
] | You need the [`[QSA]`](http://www.google.com/search?q=apache+rewriterule+%5BQSA%5D) flag then. | use `RewriteRule ^(.*)$ index.php?url=$1&%{QUERY_STRING} [L]` instead |
655,641 | Sometimes, an alt-code that I find on the internet does not work on my PC, for example Pi alt code (`Alt`+`227`) throws Ń isntead of π.
So I need to use the character in clipboard (or in a file or wherever) and conver it to Alt-code compatible with my system. Is this possible? | 2013/10/07 | [
"https://superuser.com/questions/655641",
"https://superuser.com",
"https://superuser.com/users/194976/"
] | You can start "Character map", choose your font, search you character and at the bottom (in the status bar) is the Alt code you need.
(In Windows 7 you can press `Start` and begin type `Character map` en choose it at the top.)
The fact that you get a different character with `Alt` + `227` is probably that you're using a different font. So choosing the right font in "Character map" is important.
BTW nowadays the `Alt` combinations consists of a 4 digit number to accommodate a wider range of Unicode characters. The three numbers still work but the `Alt` + `227` is different from `Alt` + `0227`.
 | For Windows, one way to enter codes is by referring to code page
437:
<https://en.wikipedia.org/wiki/Code_page_437>
For anything on that list, you just enter Alt followed by the
decimal code. For example for this character:
```
☺ U+263A
```
According to the chart is decimal `1`. So you will just enter
`Alt + 1`. Another method is Code Page 1252:
<https://en.wikipedia.org/wiki/Windows-1252>
For anything on that this, you just enter Alt followed by `0` and
the decimal code. For example for this character:
```
€ U+20AC
```
According to the chart is decmail `128`. So you will just enter
`Alt + 0128`. |
294,504 | In the beginning of my presentation, I would like to show the following. On the first slide, I would like to show a table of contents with sections only. That is, the subsections should be invisible, but they should be THERE. Then, on the following slides, the subsections shall sucessively be blended in.
Using the option `pausesubsections` for `\tableofcontents` has the disadvantage that only the first section is shown on the first slide. Using the option `hidesubsections` erases the subsections completely, so that it is impossible to blend them in one after another.
I tried setting up a fake table of contents with `enumerate` and `itemize` and using `\pause`, but the spacing is different from a 'real' table of contents. Below provided a MWE.
```
\documentclass{beamer}
\begin{document}
\begin{frame}{Outline}
\tableofcontents[pausesubsections]
\end{frame}
\section{One}
\subsection{OneOne}
\begin{frame}
There is nothing here.
\end{frame}
\subsection{OneTwo}
\begin{frame}
There is nothing here.
\end{frame}
\section{Two}
\subsection{TwoOne}
\begin{frame}
There is nothing here.
\end{frame}
\subsection{TwoTwo}
\begin{frame}
There is nothing here.
\end{frame}
\end{document}
``` | 2016/02/17 | [
"https://tex.stackexchange.com/questions/294504",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/96089/"
] | Since `\big` is the minimum requested size anyway, it's better to use a simpler approach:
```
\documentclass{article}
\usepackage{amsmath,mleftright}
\usepackage{xparse}
\NewDocumentCommand{\evalat}{sO{\big}mm}{%
\IfBooleanTF{#1}
{\mleft. #3 \mright|_{#4}}
{#3#2|_{#4}}%
}
\begin{document}
\begin{align}
& \evalat{f(x)}{x=0} \\
& \evalat[\big]{f(x)}{x=0} \\
& \evalat[\Big]{\frac{\partial f}{\partial x}}{x=0} \\
& \evalat[\bigg]{\frac{\partial f}{\partial x}}{x=0} \\
& \evalat*{\frac{\partial f}{\partial x}}{x=0} \\
& \evalat[\bigg]{\frac{\partial^2 f}{\partial x^2}}{x=0} \\
& \evalat*{\frac{\partial^2 f}{\partial x^2}}{x=0} \\
& \evalat[\bigg]{\left(1+\frac{1}{x}\right)^{\!x^2}}{x=1} \\
& \evalat*{\left(1+\frac{1}{x}\right)^{\!x^2}}{x=1}
\end{align}
\end{document}
```
Note that the last one has a definitely too big bar.
[](https://i.stack.imgur.com/VU4L3.png) | While trying to adapt [Bernard’s answer](https://tex.stackexchange.com/a/294543/69818) to a similar question ([Vertical bar for “evaluated at”](https://tex.stackexchange.com/q/376541/69818)), I noticed that it is defective in that it smashes the height of the “evaluated” subformula, as it can clearly be seen in this modified example,
```
\documentclass{article}
\usepackage{amsmath}
\newcommand\eval[1]{\begin{array}[t]{@{}c@{\,}|@{\,}}%
\raisebox{0pt}[0.33\height][1.33\depth]{$ \displaystyle#1 $}\end{array}}
\begin{document}
\begin{align*}
& 5 + \eval{\dfrac{df}{dt}}_{t = 0} \\[2ex]
& 5 + \eval{\frac{d\Bigl(\dfrac{f}{g}\Bigr)}{dt}}_{t = 0}
\end{align*}
\end{document}
```
which produces the following output:
[](https://i.stack.imgur.com/VBTSU.png)
However, I liked the idea of using a vertical rule instead of a `\vert` delimiter, so I worked out another solution based on this same principle. The height and the depth of the rule are computed keeping in mind the rules detailed in Appendix G of *The TeXbook* for the placement of subscripts (Rules 18a and 18b). Of course, I’ve open to suggestions for what concerns the value of the various parameters.
Here is my current proposal:
```
% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly
% declare the paper format.
\usepackage[T1]{fontenc} % Not always necessary, but recommended.
% End of standard header. What follows pertains to the problem at hand.
\usepackage{amsmath} % I always load it when dealing with math!
\makeatletter
\newcommand*\evaluateat[2]{%
#1% first, typeset the base symbol(s)
\mkern .5\thinmuskip % too little? too much?
\mathpalette{\EA@evaluate@at{#2}}{#1}% then, add the vertical bar
}
\newcommand*\EA@evaluate@at[3]{%
% #1 <- subscripted annotation
% #2 <- style selector, e.g., "\textstyle"
% #3 <- base symbol(s)
\setbox\z@ \hbox{$\m@th\color@begingroup #2#3\color@endgroup$}%
\dimen@ \dimexpr \ht\z@ *\tw@/\thr@@ \relax
\dimen@ii \dp\z@
\ifx #2\scriptscriptstyle
\EA@calc@style@dependent@values \scriptscriptfont \scriptscriptfont
\else \ifx #2\scriptstyle
\EA@calc@style@dependent@values \scriptfont \scriptscriptfont
\else
\EA@calc@style@dependent@values \textfont \scriptfont
\fi \fi
\vrule \@height\dimen@ \@depth\dimen@ii \@width\dimen4
\mathord{% or "\mathclose{}\mathopen{}\mathinner{"?
\vrule \@depth\dp\z@ \@height\z@ \@width\z@
}% } brace match
_{\,#1}%
}
\newcommand*\EA@calc@style@dependent@values[2]{%
% #1 <- main font selector, e.g., "\textfont"
% #2 <- relative script font selector, e.g., "\scriptfont"
\advance \dimen@ii \fontdimen19#2\tw@
\dimen4 \fontdimen16#1\tw@
\ifdim \dimen@ii<\dimen4
\dimen@ii \dimen4
\fi
\advance \dimen@ii \dimen4 % extra depth
% \dimen4 \dimexpr \fontdimen5#1\tw@ *6/5\relax
\dimen4 \fontdimen5#1\tw@ % the ex-height
\ifdim \dimen4 <\z@
\dimen4 -\dimen4
\fi
\ifdim \dimen@<\dimen4
\dimen@ \dimen4
\fi
% Now re-use "\dimen4" to hold the default rule thickness:
\dimen4 \fontdimen8#1\thr@@
}
\makeatother
\begin{document}
In-line: \( \evaluateat{\mathord.}{x=0} + \evaluateat{f}{x=0} +
\evaluateat{f(x)}{x=0} + \evaluateat{\frac{df}{dx}}{x=0} \). And displayed:
\[
\evaluateat{f}{x=0}+\evaluateat{\frac{df}{dx}}{x=0}
- \evaluateat{\,\frac{\frac{df}{dx}\,}{\,\frac{df}{dy}\,}}{x=0,y=0}
\]
Example in \verb|\scriptstyle|:
\( \frac{\evaluateat{f(x)}{x=0}}{g\left(\evaluateat{f(x)}{x=0}\right)} \).
Another example:
\[ \evaluateat{df}{x} \colon T_{x}M\longrightarrow T_{y}N \]
\end{document}
```
This is the output it yields:
[](https://i.stack.imgur.com/o9x0K.png) |
54,116,784 | I have a JTable application. I need to change the cell values and save the data, but only cells with index smaller than or equal to 4 are within the array bounds.
```
package fi.allu.neliojuuri;
import com.sun.glass.events.KeyEvent;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import javax.swing.event.CellEditorListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
public class Neliojuuri extends JPanel
implements ActionListener, ItemListener, TableModelListener {
String newline = "\n";
private JTable table;
private JCheckBox rowCheck;
private JCheckBox columnCheck;
private JCheckBox cellCheck;
private ButtonGroup buttonGroup;
private JTextArea output;
private String[] sarakenimet = new String[70];
private String[] sisakkainen = new String[70];
private Object[][] ulkoinen = new String[71][71];
private DefaultTableModel oletusmalli = null;
private CellEditorListener solumuokkaaja = null;
public Neliojuuri() {
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
for (int i = 0; i < 70; i++) {
sarakenimet[i] = String.valueOf(i + 1);
}
for (int i = 0; i < sisakkainen.length; i++) {
sisakkainen[i] = String.valueOf(i + 1);
}
for (int i = 0; i < ulkoinen.length; i++) {
ulkoinen[i] = sisakkainen;
}
table = new JTable(ulkoinen, sarakenimet);
table.setPreferredScrollableViewportSize(new Dimension(500, 210));
table.setFillsViewportHeight(true);
table.setRowHeight(30);
TableColumnModel sarakeMalli = table.getColumnModel();
for (int i = 0; i < 70; i++) {
sarakeMalli.getColumn(i).setPreferredWidth(75);
}
oletusmalli = new javax.swing.table.DefaultTableModel();
table.setModel(oletusmalli);
String[] sarakenimet = new String[70];
for (int i = 0; i < 70; i++) {
sarakenimet[i] = String.valueOf(i + 1);
}
String[] sisakkainen = new String[70];
for (int i = 0; i < sisakkainen.length; i++) {
sisakkainen[i] = String.valueOf(i + 1);
}
Object[][] ulkoinen = new String[71][71];
for (int i = 0; i < ulkoinen.length; i++) {
ulkoinen[i] = sisakkainen;
}
oletusmalli.setColumnIdentifiers(sarakenimet);
for (int count = 0; count < 70; count++){
oletusmalli.insertRow(count, sisakkainen);
}
table.getSelectionModel().addListSelectionListener(new RowListener());
table.getColumnModel().getSelectionModel().
addListSelectionListener(new ColumnListener());
add(new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getModel().addTableModelListener(this);
add(new JLabel("Selection Mode"));
buttonGroup = new ButtonGroup();
addRadio("Multiple Interval Selection").setSelected(true);
addRadio("Single Selection");
addRadio("Single Interval Selection");
add(new JLabel("Selection Options"));
rowCheck = addCheckBox("Row Selection");
rowCheck.setSelected(true);
columnCheck = addCheckBox("Column Selection");
cellCheck = addCheckBox("Cell Selection");
cellCheck.setEnabled(false);
output = new JTextArea(5, 40);
output.setEditable(false);
output.setFont(new Font("Segoe UI", Font.PLAIN, 20));
add(new JScrollPane(output));
}
private JCheckBox addCheckBox(String text) {
JCheckBox checkBox = new JCheckBox(text);
checkBox.addActionListener(this);
add(checkBox);
return checkBox;
}
private JRadioButton addRadio(String text) {
JRadioButton b = new JRadioButton(text);
b.addActionListener(this);
buttonGroup.add(b);
add(b);
return b;
}
public void actionPerformed(ActionEvent e) {
JFileChooser tiedostovalitsin = new JFileChooser();
JMenuItem source = (JMenuItem)(e.getSource());
if (source.getText() == "Save") {
int palautusArvo = tiedostovalitsin.showSaveDialog(Neliojuuri.this);
if (palautusArvo == JFileChooser.APPROVE_OPTION) {
File tiedosto = tiedostovalitsin.getSelectedFile();
// Tallenna tiedosto oikeasti
for (int i = 0; i < oletusmalli.getRowCount(); i++) {
System.out.println(oletusmalli.getValueAt(1, i).toString());
}
System.out.println(tiedosto.getName());
}
}
String command = e.getActionCommand();
//Cell selection is disabled in Multiple Interval Selection
//mode. The enabled state of cellCheck is a convenient flag
//for this status.
if ("Row Selection" == command) {
table.setRowSelectionAllowed(rowCheck.isSelected());
//In MIS mode, column selection allowed must be the
//opposite of row selection allowed.
if (!cellCheck.isEnabled()) {
table.setColumnSelectionAllowed(!rowCheck.isSelected());
}
} else if ("Column Selection" == command) {
table.setColumnSelectionAllowed(columnCheck.isSelected());
//In MIS mode, row selection allowed must be the
//opposite of column selection allowed.
if (!cellCheck.isEnabled()) {
table.setRowSelectionAllowed(!columnCheck.isSelected());
}
} else if ("Cell Selection" == command) {
table.setCellSelectionEnabled(cellCheck.isSelected());
} else if ("Multiple Interval Selection" == command) {
table.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//If cell selection is on, turn it off.
if (cellCheck.isSelected()) {
cellCheck.setSelected(false);
table.setCellSelectionEnabled(false);
}
//And don't let it be turned back on.
cellCheck.setEnabled(false);
} else if ("Single Interval Selection" == command) {
table.setSelectionMode(
ListSelectionModel.SINGLE_INTERVAL_SELECTION);
//Cell selection is ok in this mode.
cellCheck.setEnabled(true);
} else if ("Single Selection" == command) {
table.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
//Cell selection is ok in this mode.
cellCheck.setEnabled(true);
}
//Update checkboxes to reflect selection mode side effects.
rowCheck.setSelected(table.getRowSelectionAllowed());
columnCheck.setSelected(table.getColumnSelectionAllowed());
if (cellCheck.isEnabled()) {
cellCheck.setSelected(table.getCellSelectionEnabled());
}
}
private void outputSelection() {
output.append(String.format("Lead: %d, %d. ",
table.getSelectionModel().getLeadSelectionIndex(),
table.getColumnModel().getSelectionModel().
getLeadSelectionIndex()));
output.append("Rows:");
for (int c : table.getSelectedRows()) {
output.append(String.format(" %d", c));
}
output.append(". Columns:");
for (int c : table.getSelectedColumns()) {
output.append(String.format(" %d", c));
}
output.append(".\n");
}
@Override
public void itemStateChanged(ItemEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void tableChanged(TableModelEvent e) {
int rivi = e.getFirstRow();
int sarake = e.getColumn();
TableModel malli = (TableModel)e.getSource();
String sarakeNimi = malli.getColumnName(sarake);
Object data = malli.getValueAt(rivi, sarake);
MyTableModel taulumalli = new MyTableModel();
taulumalli.setValueAt(data, rivi, sarake);
System.out.println("rivi: " + rivi + " sarake: " + sarake + " data: " + data);
}
private void setValueAt(Object data, int rivi, int sarake) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private class RowListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
return;
}
output.append("ROW SELECTION EVENT. ");
outputSelection();
}
}
private class ColumnListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
return;
}
output.append("COLUMN SELECTION EVENT. ");
outputSelection();
}
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
private Object[][] data = {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
public JMenuBar luoValikkoPalkki() {
JMenuBar valikkopalkki = new JMenuBar();
JMenu valikko = new JMenu("File");
valikko.setMnemonic(KeyEvent.VK_F);
valikko.getAccessibleContext().setAccessibleDescription(
"File saving menu");
valikkopalkki.add(valikko);
JMenuItem valikkoitem = new JMenuItem("Save", KeyEvent.VK_S);
valikkoitem.setAccelerator(KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_S, ActionEvent.CTRL_MASK));
valikkoitem.addActionListener(this);
valikko.add(valikkoitem);
return valikkopalkki;
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Disable boldface controls.
UIManager.put("swing.boldMetal", Boolean.FALSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
//Create and set up the window.
JFrame frame = new JFrame("Neliöjuuri");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Neliojuuri neliojuuri = new Neliojuuri();
frame.setJMenuBar(neliojuuri.luoValikkoPalkki());
//Create and set up the content pane.
Neliojuuri newContentPane = new Neliojuuri();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
```
Stacktrace:
```
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 5
at fi.allu.neliojuuri.Neliojuuri$MyTableModel.setValueAt(Neliojuuri.java:356)
at fi.allu.neliojuuri.Neliojuuri.tableChanged(Neliojuuri.java:261)
at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:296)
at javax.swing.table.AbstractTableModel.fireTableCellUpdated(AbstractTableModel.java:275)
at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:666)
at javax.swing.JTable.setValueAt(JTable.java:2744)
at javax.swing.JTable.editingStopped(JTable.java:4729)
at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:141)
at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:368)
at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:233)
at javax.swing.JTable$GenericEditor.stopCellEditing(JTable.java:5473)
at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:385)
at javax.swing.JTextField.fireActionPerformed(JTextField.java:508)
at javax.swing.JTextField.postActionEvent(JTextField.java:721)
at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:836)
at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1668)
at javax.swing.JComponent.processKeyBinding(JComponent.java:2882)
at javax.swing.JComponent.processKeyBindings(JComponent.java:2929)
at javax.swing.JComponent.processKeyEvent(JComponent.java:2845)
at java.awt.Component.processEvent(Component.java:6316)
at java.awt.Container.processEvent(Container.java:2239)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1954)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:835)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1103)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:974)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:800)
at java.awt.Component.dispatchEventImpl(Component.java:4760)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
at java.awt.EventQueue$4.run(EventQueue.java:733)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
```
I expect to be able to change all the cell values in the table, but I can only do so to a few of them. Cells with index greater than or equal to 5 return ArrayIndexOutOfBounds error. | 2019/01/09 | [
"https://Stackoverflow.com/questions/54116784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5964318/"
] | You could slice the array and omit the last element.
```js
var array = [1, 2, 3],
item;
for (item of array.slice(0, -1)) {
console.log(item)
}
``` | If you want to change your loop behavior based the specific index, then it's probably a good idea to use an explicit index in your for-loop.
If you simply want to skip out on the last element, you can do something like
```
for (item of array.slice(0, -1)) {
//do something for every element except last
}
``` |
8,863,103 | A few days ago I've asked a question concerning how to detect an end of input file of N(N is unknown) lines.
```
StringBuilder input = new StringBuilder();
int endOfFile = 0
while ((endOfFile = Console.Read()) != -1) {
input.Append(((char)endOfFile).ToString());
input.Append(Console.ReadLine());
}
```
I've edited my question, but I guess this is the same as some of the hints below. | 2012/01/14 | [
"https://Stackoverflow.com/questions/8863103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/824431/"
] | This could help in looping through the file and check for end of file.
```
using (StreamReader sr = new StreamReader(@"test.txt"))
{
string line;
while ( (line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
```
**UPDATE**
Here is a link from msdn [ReadLine method](http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx) | Are you planning on using the shell to redirect standard input to your input file?
Why not use something like TextReader.Read() or TextReader.ReadLine()? <http://msdn.microsoft.com/en-us/library/system.io.textreader.aspx> |
34,487,991 | I want to know why this error comes when try to upload file with real device using Marshmallow. Can you please explain the solution for this.
>
> 12-28 10:39:32.606: E/3(17552): Excption : java.io.FileNotFoundException: /storage/emulated/0/WoodenstreetD.doc: open failed: ENOENT (No such file or directory)
>
>
>
I was stuck with this for last week and still getting same issue.
Thanks In Advance. | 2015/12/28 | [
"https://Stackoverflow.com/questions/34487991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This error comes due to wrong path. The path your getting from onActivityResult is not correct. Use this to get path of selected file.
```
public static String getRealPathFromUri(Context ctx, Uri uri) {
String[] filePathColumn = { MediaStore.Files.FileColumns.DATA };
Cursor cursor = ctx.getContentResolver().query(uri, filePathColumn,
null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
Log.e("", "picturePath : " + picturePath);
cursor.close();
}
return picturePath;
}
```
picturePath gives you full path of image/file.
It'll work for me. | i worte this and it'll work for me.
```
public static java.io.File convertUriTFile(Activity activity, Uri uri) {
InputStream inputStream = null;
java.io.File file = null;
try {
inputStream = activity.getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
file = new java.io.File(activity.getCacheDir(), "temp");
try (OutputStream output = new FileOutputStream(file)) {
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
``` |
29,678,424 | I would like to show one progress bar the resets when its finished. Here is the code. When you run it you can see it makes a new line every time .
```
import time
import sys
toolbar_width = 40
numbers = [1,2,4,5,6,7,8,9,10]
for number in numbers:
for i in xrange(toolbar_width):
time.sleep(0.1) # do real work here
# update the bar
sys.stdout.write("-")
sys.stdout.flush()
sys.stdout.write("\n")
``` | 2015/04/16 | [
"https://Stackoverflow.com/questions/29678424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4624573/"
] | Print a carriage return when you are done:
```
import time
import sys
toolbar_width = 40
numbers = [1,2,4,5,6,7,8,9,10]
for number in numbers:
#print number
for i in xrange(toolbar_width):
time.sleep(0.1) # do real work here
# update the bar
sys.stdout.write("-")
sys.stdout.flush()
sys.stdout.write("\r")
# ^^^^^^^^^^^^^^^^^^^^ <--- here!
```
This way, the cursor will go back to the beginning of the line.
However, this will go to the beginning of the line and keep what was there before, as @Kevin comments below. To blank the line you can print a long line with spaces surrounded by `\r`: the first to start printing at the beginning of the given line and the second to put the cursor back in the beginning.
```
sys.stdout.write("\r \r")
``` | ```
sys.stdout.write("\r" + " " * toolbar_width + "\r")
```
instead of
```
sys.stdout.write("\n")
```
Explain:
* `\r` -- return at the beginning of line
* `" " * toolbar_width` -- fill the line with space of the size toolbar\_width
* `\r` -- return again at the beginning of line |
41,708,152 | I am trying to use `removeEventListener` but in line with `event.target.removeEventListener('click', myName, false);` is mistake. I tried different ways but none works.
```
document.querySelector('#imagesContainer').addEventListener('click', function myName (event) {
var images = this.formData.getAll('images[]');
var picName = event.target.parentNode.dataset.name;
var id = event.target.parentNode.getAttribute('id');
var xxx = document.getElementById(id);
xxx.outerHTML = "";
delete xxx;
for (var n = 0; n < images.length; n++) {
if (images[n].name == picName) {
var removedObject = images.splice(n, 1);
removedObject = null;
break;
}
}
this.formData.delete('images[]');
[].forEach.call(images, function(image){
this.formData.append('images[]', image);
}.bind(this));
event.target.removeEventListener('click', myName, false);
}.bind(this), false);
``` | 2017/01/17 | [
"https://Stackoverflow.com/questions/41708152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4418289/"
] | You would need to first shift by the required number of bits then perform a bitwise OR of the new data.
```
int a = 0;
a = a << 3;
a = a | 0x5;
a = a << 3;
a = a | 0x3;
printf("a=%x\n", a);
```
( Used separate assignments and operators instead of compound operators to make it clearer to beginners. )
Result:
```
a=2b
``` | >
> Is there a way for me to say left shift 101 into the variable
>
>
>
No. You need to left shift first, then add (or OR) the new value.
```
int eax = 0;
eax <<= 3;
eax |= 5;
``` |
59,942,915 | I want to display an Image or Text in Center like `No Record Found` all details are fetched from API. In Native Android `setEmptyView()` for this condition but no idea how can I do this in flutter. Non-stop progress Dialog is running but the text is not displayed. I added code with my JSON response
```
List<NewAddressModel> newAddress = List();
bool isLoading = false;
Scaffold(
body :isLoading
? Center(
child: CircularProgressIndicator(),
)
: Container(
color: Color.fromRGBO(234, 236, 238, 1),
child: getListView()
),
)
```
```
Widget getListView(){
return newAddress.isNotEmpty ?
ListView.builder(itemCount: newAddress.length,
itemBuilder: (BuildContext context, int index) {
return addressViewCard(index);
}
)
: Center(child: Text("No Found"));
}
```
```
Future<List>hitGetAddressApi() async {
setState(() {
isLoading = true;
});
final response = await http.post(api);
var userDetails = json.decode(response.body);
if (response.statusCode == 200) {
newAddress = (json.decode(response.body) as List)
.map((data) => new NewAddressModel.fromJson(data))
.toList();
setState(() {
isLoading = false;
newAddressModel = new NewAddressModel.fromJson(userDetails[0]);
});
}
return userDetails;
}
```
```
This is JSON Response which I am getting from my API.
[
{
"id": "35",
"name": "Toyed",
"mobile": "8855226611",
"address": "House No 100",
"state": "Delhi",
"city": "New Delhi",
"pin": "000000",
"userid": "2",
}
]
``` | 2020/01/28 | [
"https://Stackoverflow.com/questions/59942915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12094392/"
] | You have to use different `widget` for this. You can use something like this to display empty image when there is no data.
```
@override
Widget build(BuildContext context) {
if (array.isEmpty()) {
return Widget(child: Thing(this.name));
} else {
return Widget(child: WithoutThing(this.name));
}
}
```
Hope this will be helpful. | In your case, the best solution will be the use of [**FutureBuilder**](https://api.flutter.dev/flutter/widgets/FutureBuilder/FutureBuilder.html) .
The [FutureBuilder class](https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html)
[An article that can help you](https://medium.com/nonstopio/flutter-future-builder-with-list-view-builder-d7212314e8c9) |
62,010,915 | When nav component switches to a fragment, I get this "Views added to a FragmentContainerView must be associated with a Fragment" crash. What causes this? | 2020/05/25 | [
"https://Stackoverflow.com/questions/62010915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/251120/"
] | I didn't see this mentioned anywhere and it took a while to figure out but in this case, I was trying to set up a old legacy fragment while migrating to the nav arch component.
The reason was in the frag's `onCreateView`, the inflate looked like:
```kotlin
layoutView = inflater.inflate( R.layout.home, container, false );
```
The last argument automatically attaches the view to the container. This works fine in old style fragments and activities. It does not work with the nav arch component because the root container is a `FragmentContainerView` which only allows fragments to be attached to it.
Setting the last argument to false makes it work properly. | Just replace your **onViewCreated** method.
```
class MyFragment : Fragment() {
override fun onCreateView( inflater: LayoutInflater,container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_post,container,false)
}
}
``` |
3,580,839 | >
> Why does $\left(1+{\frac{1}{\sqrt{n}}}\right)^\sqrt{n}$ also converge to $e$?
>
>
>
I mean, if we use, instead of $\sqrt{n}$, something like $2n$ or $n^2$, we could argue that these sequences are SUBsequences of $(1+1/n)^n$. I need a proper definition or explanation why these sequences are related to the "original" sequence of $e$. Is there something which tells are that these sequences (with $\sqrt{n}$, $2n$, $n^2$) are related to it?
I would appreciate an answer. If my question sounds trivial, I'm sorry. The explanation that all sequences $\sqrt{n}$, $2n$, etc are converging to infinity does not seem legitimate, as, for instance, $(1+1/(2n))^n$ converges to $\sqrt{e}$, yet both $2n$ and $n$ converge to infinity.
Thanks in advance. | 2020/03/14 | [
"https://math.stackexchange.com/questions/3580839",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/740715/"
] | You can always make a substitution. For your first example, set $y=\sqrt n.$ Then as $n\to+\infty,$ we have that $\sqrt n\to+\infty,$ so that $y\to+\infty$ too. Then we have that $$\left(1+\frac{1}{\sqrt n}\right)^{\sqrt n}=\left(1+\frac1y\right)^y\to e.$$
You can then see that this also works for any function $f(n)$ such that $f(n)\to+\infty$ as $n\to+\infty.$ | Note that
$$ \lim\_{n\to\infty}\left(1+\frac1{n}\right)^{n+1}=\lim\_{n\to\infty}\left(1+\frac1{n}\right)^{n}\cdot \lim\_{n\to\infty}\left(1+\frac1{n}\right)=e.$$
Likewise,
$$ \lim\_{n\to\infty}\left(1+\frac1{n+1}\right)^{n}=e.$$
Let $a\_n$ be a sequence of reals with $a\_n\to\infty$. Then wlog. $a\_n\ge 1$ for all $n$.
If $m\_n\in\Bbb N$ with $m\_n\le a\_n<m\_n+1$, then
$$\left(1+\frac1{m\_n+1}\right)^{m\_n}<\left(1+\frac1{a\_n}\right)^{a\_n}< \left(1+\frac1{m\_n}\right)^{m\_n+1}.$$
Now given $\epsilon>0$, there exists $N$ with $\left|\left(1+\frac1{n+1}\right)^{n}-e\right|<\epsilon$ and
$\left|\left(1+\frac1{n}\right)^{n+1}-e\right|<\epsilon$ for all $n>N$. From $a\_n\to\infty$, there also exists $M$ such that $a\_n>N+1$ for all $n>M$. Then $m\_n>N$ for all $n>M$ and hence $$\left|\left(1+\frac1{a\_n}\right)^{a\_n} -e\right|<\epsilon$$
for all $n>M$. In other words,
$$\lim\_{n\to\infty}\left(1+\frac1{a\_n}\right)^{a\_n}=e. $$
However, there is no reason to believe that $$\left(1+\frac1{a\_n}\right)^{b\_n} $$
converegs to $e$ or at all when $a\_n\to \infty$ and $b\_n\to \infty$ are *different* sequences. |
1,595,785 | Is there a way that I can pass in a reference to an object, manipulate it inside my method which directly changes the referenced object?
For instance I want to pass a dropdownlist into my method, manipulate it and be done. This method is going to take in any dropdownlist:
```
public static void MyMethod(Dropdownlist list1, ref DropdownList list2)
{
// just manipulate the dropdown here... no need to returnit. Just Add or remove some values from the list2
}
```
obviously I can't just pass a dropdownlist object to list2. So how can I do this? I am going to remove some values in the list. And this will be a nice utility method so I don't have to repeat this code all over the place for this functionality that I'm going to be performing in the method. | 2009/10/20 | [
"https://Stackoverflow.com/questions/1595785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93468/"
] | Yes (but more like Javadoc) - [look at JSDoc](http://jsdoc.sourceforge.net/)
Basically you use Javadoc-like special syntax in your comments e.g. `@param` like in the following example and then parser will generate good looking HTML output for you
```
/**
* Shape is an abstract base class. It is defined simply
* to have something to inherit from for geometric
* subclasses
* @constructor
*/
function Shape(color){
this.color = color;
}
``` | I haven't personally used it, but [jsdoc-toolkit](http://code.google.com/p/jsdoc-toolkit/) seems to be what you're after. |
5,261,748 | I've tried some dropdown menus, but they drop behind other frames. | 2011/03/10 | [
"https://Stackoverflow.com/questions/5261748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/521180/"
] | Can you give each cell a unique id? Then you can just do:
```
var cell_ids = ['id-cell-1', 'id-cell-2',...];
var cellcontents = [];
while (i < 10) {
cellcontents.push($("#" + cell_ids[i]).html());
i--;
}
``` | an array?
this is just semi psuedo code but:
```
var i;
var innerString[];
while (i < 10) {
innerString[i] = (innerHTML of elementID);
i++;
}
``` |
35,945,855 | I am trying to get a value from the table.
```
cursor=db.rawQuery("select value from '" + tableName + "' where key= '" + name + "' ",null);
if (cursor.getCount()>0){
if (cursor.moveToFirst()){
String value= cursor.getString(cursor.getColumnIndex("value"));
return value;
}
cursor.close();
}
```
I get the exception:
```
Couldn't read row 0, col -1 from Cursor Window.Make sure cursor is initialised correctly before accessing data from it.
```
When I use:
```
cursor.getString(0);
```
I am able to get the value I need.
If I use,
```
cursor.getString(cursor.getColumnIndex("value"));
```
I get the exception.
HEre is the snapshot of my table:
[](https://i.stack.imgur.com/Q23He.png) | 2016/03/11 | [
"https://Stackoverflow.com/questions/35945855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3695849/"
] | Table and column names in SQL are case sensitive. Since your column is named "VALUE", you need to getColumnIndex("VALUE") | The Table you created must have a column with name \_id. it won't work until you add column with column index "\_id".
if you do not have any column with column index "\_id". Explicitly uninstall your app from settings->app manager. and re-run you app after adding required column. |
25,387,114 | I am new to Android application development and Java programming, currently, I'm working on a project to retrieve from my database the status of a service. However, the application will stop working whenever I tried to submit my tracking ID.
MainActivity.java
```
package com.example.trackstatus;
import com.example.testapp.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button btnViewStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Buttons
btnViewStatus = (Button) findViewById(R.id.btnViewStatus);
// view products click event
btnViewStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching View status activity
Intent i = new Intent(getApplicationContext(), ViewTrackingStatusActivity.class);
startActivity(i);
}
});
}}
```
TrackStatus Manifest
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package = "com.example.trackstatus"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="20" />
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- View Tracking Status Activity -->
<activity
android:name=".ViewTrackingStatusActivity"
android:label="View Tracking Status" >
</activity>
</application>
</manifest>
```
ViewTrackingStatusActivity.java
```
package com.example.trackstatus;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.testapp.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ViewTrackingStatusActivity extends Activity{
TextView textView1;
EditText trackingNumberText;
Button btnViewStatus;
String tid;
String tracking;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// url to get service status
private static String url = "http://10.0.2.2/1201716f/android%20connect/get_svc.php?tid=0";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_TRACKING = "tracking";
private static final String TAG_TID = "tid";
public String trackingno;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
trackingNumberText = (EditText) findViewById(R.id.trackingNumberText);
trackingno = trackingNumberText.getText().toString();
btnViewStatus = (Button) findViewById(R.id.btnViewStatus);
Intent intent = getIntent();
tid = intent.getStringExtra(TAG_TID);
// Getting tracking status details in background thread
new GetStatusDetails().execute();
//Toast.makeText(getApplicationContext(),"Hello",
// Toast.LENGTH_LONG).show();
}
class GetStatusDetails extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewTrackingStatusActivity.this);
pDialog.setMessage("Loading details");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tid", trackingno));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
// check your log for json response
Log.d("Tracking Status Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray trackingObj = json.getJSONArray(TAG_TRACKING); // JSON Array
// get first product object from JSON Array
JSONObject tracking = trackingObj.getJSONObject(0);
// display tracking status in ToastBox
Toast.makeText(ViewTrackingStatusActivity.this,json.getString(TAG_TRACKING),Toast.LENGTH_LONG).show();
}
else
{
//service with tid not found
Toast.makeText(getApplicationContext(),"Service not found!",Toast.LENGTH_LONG).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
return null;
}
}
}
```
JSONParser.java
```
package com.example.trackstatus;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
```
Logcat
```
08-19 23:52:46.644: D/AndroidRuntime(3809): Shutting down VM
08-19 23:52:46.644: W/dalvikvm(3809): threadid=1: thread exiting with uncaught exception (group=0x41b37700)
08-19 23:52:46.654: E/AndroidRuntime(3809): FATAL EXCEPTION: main
08-19 23:52:46.654: E/AndroidRuntime(3809): android.os.NetworkOnMainThreadException
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
08-19 23:52:46.654: E/AndroidRuntime(3809): at libcore.io.IoBridge.connect(IoBridge.java:112)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.net.Socket.connect(Socket.java:842)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-19 23:52:46.654: E/AndroidRuntime(3809): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.example.trackstatus.JSONParser.makeHttpRequest(JSONParser.java:63)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.example.trackstatus.ViewTrackingStatusActivity$GetStatusDetails$1.run(ViewTrackingStatusActivity.java:92)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Handler.handleCallback(Handler.java:730)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Handler.dispatchMessage(Handler.java:92)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.os.Looper.loop(Looper.java:137)
08-19 23:52:46.654: E/AndroidRuntime(3809): at android.app.ActivityThread.main(ActivityThread.java:5293)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 23:52:46.654: E/AndroidRuntime(3809): at java.lang.reflect.Method.invoke(Method.java:525)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
08-19 23:52:46.654: E/AndroidRuntime(3809): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
08-19 23:52:46.654: E/AndroidRuntime(3809): at dalvik.system.NativeStart.main(Native Method)
08-19 23:52:49.086: I/Process(3809): Sending signal. PID: 3809 SIG: 9
``` | 2014/08/19 | [
"https://Stackoverflow.com/questions/25387114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3956889/"
] | According to your LogCat message:
```
Caused by: java.lang.NullPointerException at com.example.trackstatus.ViewTrackingStatusActivity.onCreate(ViewTrackingStatusActivity.java:55)
```
You are missing :
```
setContentView(R.layout.your_layout);
```
where your EditText `trackingNumberText` must be declared.
thats the reason for what `trackingNumberText` is null
```
trackingNumberText = (EditText) findViewById(R.id.trackingNumberText);
```
More info:
**[setContentView() method](http://developer.android.com/reference/android/app/Activity.html#setContentView(android.view.View))**
### Update:
Since you have this new exception: **[NetworkOnMainThreadException](http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html)**
```
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
```
you have to implement the use of **[AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html)**
And hey! you don´t need to use `runOnUiThread` inside the `doInBackground()` method of the Asynctask :P:
```
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
```
Move the lines that implies operations on UI thread like
```
Toast.makeText(getApplicationContext(),"Service not found!",Toast.LENGTH_LONG).show();
```
to the `onPostExecute()` method of the `Asynctask` | The error is in `Line55`
`String trackingno = trackingNumberText.getText().toString();`
`trackingNumberText` is **NULL**
instead try to do NULL check
```
String trackingno = "";
if(trackingNumberText.getText().length() > 0)
{
trackingno = trackingNumberText.getText().toString();
} else {
Toast.makeText(getApplicationContext(), "Enter values", Toast.LENGTH_LONG).show();
return;
}
```
**EDIT:**
You have to send all requests to server in Background Thread, use [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html)
Here is the detailed example for [performing Network Operation.](http://developer.android.com/training/basics/network-ops/connecting.html) |
25,594,535 | I have accidentally deleted App.xaml and App.xaml.cs from project solution. Now when I try to compile my program I get this error:
Error 1 Program 'xxx\WpfApplication1\obj\Release\Pacman Reloaded.exe' does not contain a static 'Main' method suitable for an entry point xxx\WpfApplication1\WpfApplication1\CSC WpfApplication1
I have tryed to copy & paste this files from another WPF project (I chave changed namespace and so on) but it haven't appeared in my solution explorer.
Adding new class and changing it's name to App.xaml does work neither.
What should I do to get my app working? | 2014/08/31 | [
"https://Stackoverflow.com/questions/25594535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2267956/"
] | It is not enough to create a new class. You need a pair of xaml and xaml.cs files properly setup to work together. Create a new window called App. That will give you the files. Then modify them both to turn the window into an application:
App.xaml needs to look like this:
```
<Application x:Class="WpfApplication3.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
```
Of course WpfApplication3 must be replaced with your own application name.
Then make App.xaml.cs look like this, also changing WpfApplication3:
```
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
namespace WpfApplication3
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
```
Lastly change the properties for App.xaml to make Build Action read ApplicationDefinition.
That should do it. | you can find the deleted App.xaml in your recycle bin. Search it there then put it in your desktop then right click on your project/Solution in visual studio hover on add choose existing item, locate the App.xaml then click add. |
12,199 | As a kid I watched a movie that was my dads. All I remember from it was there was some kind of (potentially reluctant) hero / anti hero. He's trying to shoot an (Asian?) guy who could dodge the bullets. This guy ends up training him up (perhaps) and then this hero / anti hero has the same ability. Ability in the ninja sense I think. One of these powers was the ability to run across liquid surfaces I think.
What I'm pretty sure on:
1. Western cop / hero / anti hero tries to shoot an Asian fella who can dodge bullets
2. At some point after the training he is being chased and he runs across wet concrete (or similar) whereas the bad guy falls straight in.
I have a feeling it was Charles Bronson or someone like that, and could have been quite b movie like. | 2013/06/26 | [
"https://movies.stackexchange.com/questions/12199",
"https://movies.stackexchange.com",
"https://movies.stackexchange.com/users/3441/"
] | Is it [Remo Williams: The Adventure Begins](http://www.imdb.com/title/tt0089901/),
>
> where An officially "dead" cop is trained to become an extraordinarily
> unique assassin in service of the US president.
>
>
>
Given answer by reading [this](http://answers.yahoo.com/question/index?qid=20090325075903AATi5nT) Yahoo question and its selected answer. | This sounds like "[Remo Williams: The Adventure Begins](http://www.youtube.com/watch?v=C_lKShbp3nw)." The cheesy dodging of bullets is a component of the fictional martial art Shinanju. |
41,029,712 | I am trying to find a file ("Vodoo.txt") on my D:\ drive using static recursion in JAVA. I was wondering if you might be able to help me find out what I am doing wrong.
My goal is to search through all of my folders until I find "Vodoo.txt" and print out the path to that file.
>
> My Code:
>
>
>
```
import java.io.*;
import java.util.*;
public class FindFile
{
public static String searchForFile(File currentFolder, String filename)
{
File root = currentFolder;
File[] list = root.listFiles();
if(list != null)
{
for(File f : list)
{
if(f.isDirectory())
{
File path = f.getAbsoluteFile();
if(f.getName().equals(filename))
{
System.out.println(f.getAbsoluteFile());
}
//System.out.println(f.getAbsoluteFile());
return searchForFile(path, filename);
}
}
}
return "WRONG DIRECTORY";
}
public static void main(String[] args)
{
FindFile ff = new FindFile();
File currentFolder = new File("D:\\2016-2017\\Fall2016");
String fileName = "Vodoo.txt";
System.out.println("Search for Vodoo.txt under " + currentFolder);
System.out.println("------------------------------------");
ff.searchForFile(currentFolder, fileName);
}
}
```
>
> Output:
>
>
>
Search for Vodoo.txt under D:\2016-2017\Fall2016
>
> My actual file location:
>
>
>
D:\2016-2017\Fall2016\201\_CSCE\_Programming\Assignment 5\RecursivelyFindFile\Vodoo.txt | 2016/12/08 | [
"https://Stackoverflow.com/questions/41029712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6906088/"
] | Using the lag function is the best approach to this.
```
SELECT [Year], [Item], [Qty], [Amount],
[Qty] - LAG([Qty]) OVER (PARTITION BY [Item] ORDER BY [Year]) [QtyDiff],
[Amount] - LAG([Amount]) OVER (PARTITION BY [Item] ORDER BY [Year]) [AmountDiff]
FROM [ItemTable] it
order BY [Year] DESC, [Item];
```
Hope this helps. | Here is the required query:
```
SET @YEAR1 = '2014';
SET @YEAR2 = '2015';
SELECT
Item,
if(count(*)>1,sum(if(Year=@YEAR2,Qty,-Qty)),NULL) as 'Qty Diff',
if(count(*)>1,sum(if(Year=@YEAR2,Amount,-Amount)),NULL) as 'Amount Diff'
FROM
table
WHERE
Year IN (@YEAR1,@YEAR2)
group by Item;
``` |
188,855 | I have a `2D platformer` and if my player dies, he goes back to the start, but I want there to be checkpoints.
My current Respawn script:
```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Respawn : MonoBehaviour
{
public GameObject PlayerPrefab;
public Transform SpawnPoint;
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Trap")
{
PlayerPrefab.transform.position = SpawnPoint.transform.position;
}
}
}
```
I don't know how to implement checkpoints into this. | 2021/02/04 | [
"https://gamedev.stackexchange.com/questions/188855",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/146741/"
] | I would recommend you to structure your project a bit differently. Instead of having the `Respawn` script on the player (I assume it's on the player) detect and handle all the interactions with different objects in the world, you should make those objects themselves responsible for detecting the player and triggering a response from it.
So first of all, don't make the player a trigger. Give it a Rigidbody2D, so it can be detected by trigger areas (if you don't want to use the Unity physics and handle movement yourself, make it kinematic). Turn the `private void OnTriggerEnter2D` into a `public void DieAndRespawn()` method which can be called by other scripts if they want the player to die and respawn. Note that when this script is on the player, it doesn't need an explicit reference to the player because it can just access the properties of the gameObject it's on directly.
```
public class Respawn : MonoBehaviour
{
public Transform spawnPoint;
public void DieAndRespawn()
{
Debug.Log("Nooooooooo!");
transform.position = spawnPoint.transform.position;
}
}
```
Then create separate scripts for `Trap` and `Checkpoint`. Give the objects they are on Colliders with "Is Trigger?" enabled, so they can detect the player and cause something to happen to it. Their collision methods then would look like this for the Trap component:
```
void OnTriggerEnter2D(Collider2D other)
{
Respawn respawn = other.GetComponent<Respawn>();
if (respawn != null) {
Debug.Log(other.name + " ran into " + name);
respawn.DieAndRespawn();
}
}
```
And like this for the Checkpoint component:
```
void OnTriggerEnter2D(Collider2D other)
{
Respawn respawn = other.GetComponent<Respawn>();
if (respawn != null) {
Debug.Log("Setting spawn point of " + other.name + " to location of " + name);
respawn.spawnPoint = gameObject.transform;
}
}
```
Note that these traps and checkpoints don't recognize the player by a tag, but instead by having a specific component. That means that they can now not just interact with the player but also with anything else which has the `Respawn` component. Like for example a second player or an AI actor which you want to die and respawn just like a human player. | You clearly know how to move the player to a spawn point when hitting a trap.
You can use the same logic to move the spawn point to a checkpoint when hitting the checkpoint. |
26,276,700 | I have the following 4 tables: MainTable, Warehouse,Customer and Company.
The schema of these tables:
```
create table MainTable(ID int, Warehouse_id int, Customer_ID int)
create table Warehouse (Warehouse_id int, company_id int)
create table Customer (Customer_ID int, Company_ID int)
create table company (Company_id int, Country_ID int, Zone_ID int)
```
The objectif is to get the Country\_ID and Zone\_ID for the corresponding ID (of MainTable).
We have 2 different cases: `if MainTable.Warehouse_ID` is not null we should do the inner join on Warehouse table (on field warehouse\_id) and then a join on Company table (on field Company\_ID),
`else` (if MainTable.Warehouse\_ID is null) we should do the inner join on Customer Table (on Customer\_ID field) and then on Company Table (on Company\_ID field).
the following query generates an error near the word 'case':
```
select CO.Country_ID, CO.Zone_ID
from MainTable MT
inner join (case
when MT.Warehouse_ID is not null
then
Warehouse W on MT.Warehouse_ID=W.Warehouse_ID
inner join Company CO on W.Company_ID=CO.Company_ID
else
Customer Cu on MT.Customer_ID=Cu.Customer_ID
inner join Company C on Cu.Company_ID=CO.Company_ID
end)
```
Am I doing this right with a small syntax error that i missed? If not..is there any other way to do it?
Thanks | 2014/10/09 | [
"https://Stackoverflow.com/questions/26276700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3569267/"
] | You can use [UNION](http://msdn.microsoft.com/en-us/library/ms180026.aspx):
```
SELECT CO.Country_ID, CO.Zone_ID
FROM MainTable MT
INNER JOIN Warehouse W ON MT.Warehouse_ID=W.Warehouse_ID
INNER JOIN Company CO on W.Company_ID=CO.Company_ID
WHERE MT.Warehouse_ID IS NOT NULL
UNION
SELECT CO.Country_ID, CO.Zone_ID
FROM MainTable MT
INNER JOIN Customer Cu ON MT.Customer_ID=Cu.Customer_ID
INNER JOIN Company CO on Cu.Company_ID=CO.Company_ID
WHERE MT.Warehouse_ID IS NULL
``` | You can't do that. **What would you expect the output to be** with this kind of conditional joins ?
Have you tried using outer joins ?
```
select ISNULL(C1.Country_ID,C2.Country_ID) as Country_ID,ISNULL(C1.Zone_ID,C2.Zone_ID) as Zone_ID
from MainTable MT
left outer join Warehouse W on MT.Warehouse_ID=W.Warehouse_ID
left outer join Company1 C1 on W.Company_ID=C1.Company_ID
left outer join Customer Cu on MT.Customer_ID=Cu.Customer_ID
left outer join Company2 C2 on Cu.Company_ID=C2.Company_ID
``` |
50,278,840 | In the Main function of this script I have two if statements, each having two conditions that should be met before running. In the first if statement both conditions are met but the code is not running. Below is the code and the output. Any insight would be valuable!
```
$port= new-object system.io.ports.serialport com4
$port.open()
$gpi= 0
$toggle1 = 0
$toggle2 = 0
function read-com{
$port.write("gpio read 0`r")
$dump = $port.readline()
$script:gpi = $port.readline()
}
function low-com{
C:\Users\ccrcmh1djg\Videos\Reel\default.m4v
}
function high-com{
C:\Users\ccrcmh1djg\Videos\Reel\on-air.m4v
}
function main{
do{
read-com
sleep -m 500
'read-com'
$toggle1
$gpi
if(($gpi -eq 0) -and ($toggle1 -eq 0)){
$toggle1 = 1
$toggle2 = 0
low-com
'low-com conditions met'
}else{write-host 'low-com condition not met'}
$toggle1
$gpi
if(($gpi -eq 1) -and ($toggle2 -eq 0)){
$toggle1 = 0
$toggle2 = 1
high-com
'high-com conditions met'
}Else{Write-Host 'high-com condition not met'}
'loop'
}while ($port.IsOpen)
}
main
```
Output:
```
read-com
0
0
low-com condition not met
0
0
high-com condition not met
loop
```
Thanks! | 2018/05/10 | [
"https://Stackoverflow.com/questions/50278840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9772404/"
] | Here's the stored procedure method. In SSMS, run this one time
```
CREATE PROCEDURE dbo.UpdateAndGetLegal
AS
UPDATE Legal
SET Category = CASE WHEN DATEDIFF(MONTH, GETDATE(), [End date]) > 9 THEN 'Blue'
WHEN DATEDIFF(MONTH, GETDATE(), [End date]) < 9
AND DATEDIFF(MONTH, GETDATE(), [end date]) > 1 THEN 'Orange'
WHEN DATEDIFF(MONTH, GETDATE(), [End date]) < 2 THEN 'Red'
END
WHERE classification = 'A'
SELECT classification
, DATEDIFF(MONTH, GETDATE(), [End date])
, Category
FROM Legal
```
That will create a stored procedure that runs the update and returns the SELECT results.
In Excel, I almost never have to `.Add` a ListObject. Sometimes I have to change the SQL statement of an existing ListObject, but once a table is created, you don't really need to create it again. So I'm not entirely sure what you're doing, but here's how it would look in one of my projects.
I create an Excel file (or template if it's something I'm generating on the fly). In that file, I create an external data ListObject with a commandtext of
```
EXEC UpdateAndGetLegal
```
Then if the user simply refreshes the table, I'm done. If I need my code to refresh the table, it's
```
Sheet3.ListObjects(1).QueryTable.Refresh
```
If you're passing Windows credentials through to SQL Server, all of the users will need EXECUTE rights for the stored procedures. | I'm taking a bit of a guess here, but it's based on something that feels off.
Every time you run your SELECT to get some data
```
Select
classification,
datediff(month, GETDATE(), [End date]),
Category
from
Legal
```
You first run an UPDATE...
```
Update Legal
Set Category = Case
when datediff(month, GETDATE(), [End date]) > 9
then 'Blue'
when datediff(month, GETDATE(), [End date]) < 9
and datediff(month, GETDATE(), [end date]) > 1
then 'Orange'
when datediff(month, GETDATE(), [End date]) < 2
then 'Red'
End
where classification = 'A'
```
That's strange and I can't think of a usecase where this would be appropriate in any database. Instead you could just have a SELECT all by itself:
```
Select
classification,
datediff(month, GETDATE(), [End date]),
Case WHEN classification = 'A'
THEN
CASE
when datediff(month, GETDATE(), [End date]) > 9
then 'Blue'
when datediff(month, GETDATE(), [End date]) < 9
and datediff(month, GETDATE(), [end date]) > 1
then 'Orange'
when datediff(month, GETDATE(), [End date]) < 2
then 'Red'
End
ELSE Category
END
from
Legal
```
That does the same thing, but without touching the underlying data in `Legal`. This SELECT is the one that you want to shoehorn in to your VBA/QueryTable. |
10,842,571 | I have to implement [Battleship game](http://en.wikipedia.org/wiki/Battleship_%28game%29) in C++. It would be *Human* vs *Computer* game.
Everything is quite straight forward except positioning computer's ships on start of the game. Computer's ships' positions should be random. But how should I (optimally) choose cells of the array for ships?
Writing code which would set random position for a ship and then check if cells in the neighborhood are empty could be very time consuming.
Any ideas? | 2012/05/31 | [
"https://Stackoverflow.com/questions/10842571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1321680/"
] | Use a linked list, where each node is a link to a square on the board. You can then a) generate a random node and b) as you place ships remove nodes from the list. You can remove extra nodes from around the placed ship to make give that ship some room (don't want your ships to touch ;) | If it's computer vs. computers, you just have to make sure you place the ships randomly across the board such that none of the ships are adjacent to each other.
However, since you're playing a human you can get a little more creative. It's like the game rock-paper-scissors where you can gain an edge by exploiting human tendencies. |
34,420,590 | I have some trouble with validation in Laravel 5.2
When i try validate request in controller like this
```
$this->validate($request, [
'title' => 'required',
'content.*.rate' => 'required',
]);
```
Validator catch error, but don't store them to session, so when i'm try to call in template this code
```
@if (isset($errors) && count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
```
Laravel throw the error
```
Undefined variable: errors (View: /home/vagrant/Code/os.dev/resources/views/semantic/index.blade.php)
```
When i'm try validate with this code
```
$validator = Validator::make($request->all(), [
'title' => 'required',
'content.*.rate' => 'required'
]);
if ($validator->fails()) {
return redirect()
->back()
->withInput($request->all())
->withErrors($validator, 'error');
}
```
Variable $error also not available in template but if i try to display errors in controller
```
if ($validator->fails()) {
dd($validator->errors()->all());
}
```
Errors displays but i can't access to them from template.
What's wrong? | 2015/12/22 | [
"https://Stackoverflow.com/questions/34420590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/467310/"
] | ```
// Replace
Route::group(['middleware' => ['web']], function () {
// Add your routes here
});
// with
Route::group(['middlewareGroups' => ['web']], function () {
// Add your routes here
});
``` | ```
// Controller
$this->validateWith([
'title' => 'required',
'content.*.rate' => 'required',
]);
// Blade Template
@if ($errors->has('title'))
<span class="error">
<strong>{{ $errors->first('title') }}</strong>
</span>
@endif
@if ($errors->has('anotherfied'))
<span class="error">
<strong>{{ $errors->first('anotherfied') }}</strong>
</span>
@endif
```
Find the [documentation](https://laravel.com/api/5.2/Illuminate/Foundation/Validation/ValidatesRequests.html). |
60,899,696 | I have a scenario where I want to cache a JSON response and use it further.
I have total two requests out of which one I want to cache and use the response in another request, however the other request should not be cached. As of now what I have tried cache's all the requests.
Here is what I have tried :
```
import requests
import requests_cache
requests_cache.install_cache('test_cache', expire_after=120)
r = requests.get('http://localhost:5000/')
print(r.content)
r1 = requests.get('http://localhost:5000/nocach')
print(r1.content)
```
Here I want only the requests should be cached for `r` and not for `r1` .
Is there any other way that supports my scenario as of now I am using `requests-cache` which caches all requests , however my desired scenario woudl be not to cache all request but the ones that I want to be cached for specific time.
How can I achieve this any help ? | 2020/03/28 | [
"https://Stackoverflow.com/questions/60899696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12967623/"
] | There is a feature in `requests_cache` to temporarily disable the cache feature. This is the method `.disabled()`. In the following snippet I use the `with` keyword to create the temporary scope in which the requests are not cached.
```
import requests
import requests_cache
requests_cache.install_cache('test_cache', expire_after=120)
r = requests.get('http://localhost:5000/')
print(r.content)
with requests_cache.disabled():
r1 = requests.get('http://localhost:5000/nocach')
print(r1.content)
```
Additionally, you can add a check if it was fetched from cache with the attribute `from_cache`
```
r1 = requests.get('http://localhost:5000/nocach')
print( hasattr(r1, 'from_cache') )
```
wich should return `False` if it was placed in the `disabled` cache code context | Option 1: CachedSession
=======================
Alternatively, you can use [requests\_cache.CachedSession](https://requests-cache.readthedocs.io/en/stable/user_guide/general.html) to cache requests instead of `install_cache()`, and a regular [requests.Session](https://docs.python-requests.org/en/latest/user/advanced/#session-objects) (or just `requests.get()`) for non-cached requests:
```py
import requests
from requests_cache import CachedSession
session = CachedSession('test_cache', expire_after=120)
# Cached request
r = session.get('http://localhost:5000/')
print(r)
# Non-cached request
r1 = requests.get('http://localhost:5000/nocache')
print(r1)
```
Option 2: URL patterns
======================
Another option, as of **requests-cache 0.7+**, is to use [URL glob patterns](https://requests-cache.readthedocs.io/en/stable/user_guide/expiration.html#expiration-with-url-patterns) to define which requests to cache. This works with both `CachedSession` and `install_cache()`, and is especially useful if you want to set a different expiration for different hosts.
```py
from requests_cache import CachedSession
urls_expire_after = {
'https://httpbin.org/get': 120, # Cache for 2 minutes
'https://httpbin.org/delay': -1, # Cache indefinitely
'https://httpbin.org/ip': 0, # Don't cache
}
session = CachedSession('test_cache', urls_expire_after=urls_expire_after)
# Cached request with expiration
r = session.get('https://httpbin.org/get')
print(r)
# Cached request with no expiration
r1 = session.get('https://httpbin.org/delay/1')
print(r1)
# Non-cached request
r2 = session.get('https://httpbin.org/ip')
print(r2)
``` |
21,091,188 | How to remove the `type` from the JSON output that I have. I have a class/bean that contains output of a REST service.I'm using `jersey-media-moxy` to do the conversion.
The service
```
@Resource
public interface MyBeanResource
{
@GET
@Path("/example")
@Produces( MediaType.APPLICATION_JSON )
public Bean getBean();
}
```
The Bean
```
@XmlRootElement
class Bean
{
String a;
}
```
I want to add some functionality (for initializing the bean using the constructor)
```
class BeanImpl extends Bean
{
BeanImpl(OtherClass c)
{
a = c.toString()
}
}
```
The outputted JSON is:
`{type:"beanImpl", a:"somevalue"}`
I do not want the `type` in my JSON. How can I configure this? | 2014/01/13 | [
"https://Stackoverflow.com/questions/21091188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461499/"
] | MOXy will add a type indicator to differentiate between the different subtypes. This however will only happen if MOXy is aware of the subtypes (it isn't by default).
Demo Code
---------
**Demo**
Below is the equivalent code that Jersey will call on MOXy.
```
import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
public class Demo {
public static void main(String[] args) throws Exception {
MOXyJsonProvider mjp = new MOXyJsonProvider();
BeanImpl beanImpl = new BeanImpl(new OtherClass());
mjp.writeTo(beanImpl, Bean.class, Bean.class, null, null, null, System.out);
}
}
```
**Output**
```
{}
```
Possible Problem?
-----------------
Do you potentially have an `@XmlSeeAlso` annotation on your real `Bean` class?
```
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlSeeAlso(BeanImpl.class)
class Bean
{
String a;
}
```
Then the output will be (assuming `BeanImpl` also has a no-arg constructor):
```
{"type":"beanImpl"}
``` | I used a Jersey specific Jackson package in a slightly different case, it worked. Detailed configuration is described in [Jersy document](https://jersey.java.net/documentation/latest/media.html#json.jackson). In my case, I used a generic type field in an @XmlRootElement class. MOXy added a type in the JSON output. I can see why MOXy does it. If the JSON output needs to be unmarshalled back to a Java object, MOXy needs to know the type to create the correct object. However, in my case, the type is unsightly in the JSON output. |
6,300,332 | I have a current Android app that uses i18n via resources. res/values-es/strings.xml and so on. When I test it on a device with the language set to Espanol it pulls the correct resources, from the values-es file, but the accent characters are way out of whack.
For example, I want to use the lowercase o with an accent (ó). I have tried with the actual character in the strings.xml file (using the character map on Ubuntu to create the string) and with the entity, in either case it comes out like some other character set accent I don't recognize:

The same character looks perfect WITHIN strings.xml when using many different text editors. And the file is UTF-8 (tried recreating it with the Android "wizard" tool in Eclipse to make sure).
strings.xml
```
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="label_app_version">Versión</string>
</resources>
```
Now I've used French, and German before in other Android apps, with all sorts of accents, and haven't seen this problem, so I'm entirely confused at the moment. What am I doing wrong this time? | 2011/06/09 | [
"https://Stackoverflow.com/questions/6300332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/252676/"
] | I finally solved this one. I was using a font and calling setTypeface earlier in the code. The font I'm using must not have the special characters needed for the other languages. I need to check to make sure my user's are using a locale that my font supports before setting the font.
I should have realized this and checked it earlier.
So the bottom line is this, if you get strange results with certain characters in different locales, make sure you're not using fonts that don't support those characters. Fall back to not using a font (don't call setTypeface) and test that way. | This is strange as it should not cause a problem. Maybe you should try to embed string into CDATA section, like this:
```
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="label_app_version"><![CDATA[Versión]]></string>
</resources>
``` |
3,302 | What is a good way of learning how to season food correctly? Are there some foods which are particularly bland until seasoned correctly that can be used to 'educate' your palate as to what is correctly seasoned? | 2010/07/26 | [
"https://cooking.stackexchange.com/questions/3302",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/210/"
] | My best recommendation is to taste as you go. Taste the initial product...raw vegetable, ingredient from the can, bottle, etc. and then continue to taste and sample a dish throughout the cooking process to see how flavors develop/diminish and enhance one another through the cooking process.
Learning to season food is a process of educating your palate and developing a "flavor memory"
One of the most important factors is to use enough salt. Food that is properly seasoned with salt shouldn't taste salty but will have a brighter more vibrant flavor of the ingredients that are in the dish. Food must be cooked with salt for this to occur. Food that is seasoned at the table will merely taste salty as the salt doesn't have a chance to dissolve and pull the juices out and help them mingle with one another as happens during cooking.
The more of the basic flavor profiles that you can incorporate the more lively and flavorful anything will be. Even before cooking you can take a look at a recipe and "disect" its flavor profile by determining which ingredients will add sweetness, sourness, etc. If you notice that it's heavy in one direction or another, the flavor profile of the item(s) missing will likely improve the dish. Then it's a matter of deciding what ingredient with that flavor profile would be best to add to that particular dish.
**Shameless *(but applicable to the question)* plug:**
If you're ever in Savannah, GA I offer a class called "Flavor Dynamics". It is focused entirely around understanding how flavor develops, what affects our perception of flavor, and how to create well rounded flavor in your food. | Definitely taste as you go and season gradually and regularly. Good chefs might taste their dish thirty times before it gets to the plate. Proper seasoning is not a formula, it's heat-seeking missile that constantly adjusts to hit its target. Or an impressionist painter who builds a base of color and then dabs on highlights and shadow to bring out the bigger picture.
Details: Salt is not a flavor, just a flavor enhancer. Add dried spices early, fresh herbs late. The more seasoning cooks, the *deeper* it's flavor, the less seasoning cooks the *sharper* its flavor. If you season early and late, you get both effects.
Anatomy is the base of flavor. We taste sweet, salty, acid, bitter, and *umami*. Also heat. If your food tastes bland, one of these is missing. If your food tastes *off*, one of these is out of balance with another.
Sweetness is sugar, honey, carmelized onions. Acid is lemons, lime, vinegar. Bitter is dark greens, brussel sprouts, rind. Umami is sauteed mushrooms, soy sauce, melted cheese. Other foods float between categories depending on the variety and how they are prepared.
Generally, the more you cook something, the more sweet, less acidic, and more umami it becomes. Up to a point. Overcook and food becomes bitter, bland, compost.
The rest is smell. Your nose carries subtleties of taste your mouth can't detect. Warm food often tastes better because the aroma is unleashed (also the sugars). To master flavor, smell your food. Smell your spices. Smell your ingredients. Flavor is the interface between food and human. The only tool you have is your senses. |
9,529,504 | I try to connect to Facebook throught Facebook API, I follow this example: <https://github.com/facebook/facebook-android-sdk/tree/master/examples/simple>
Everything is ok, but when I try to edit some code, I mean I want to display the dialog post message after the login is successful like this:
```
public void onAuthSucceed() {
mText.setText("You have logged in! ");
//This is the code to call the post message dialog.
mFacebook.dialog(Example.this, "feed",new SampleDialogListener());
}
```
I receive this error in the logcat:
```
03-02 13:32:08.629: E/AndroidRuntime(14991): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@405180f8 is not valid; is your activity running?
03-02 13:32:08.629: E/AndroidRuntime(14991): at android.view.ViewRoot.setView(ViewRoot.java:532)
03-02 13:32:08.629: E/AndroidRuntime(14991): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
03-02 13:32:08.629: E/AndroidRuntime(14991): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
03-02 13:32:08.629: E/AndroidRuntime(14991): at android.view.Window$LocalWindowManager.addView(Window.java:424)
03-02 13:32:08.629: E/AndroidRuntime(14991): at android.app.Dialog.show(Dialog.java:241)
03-02 13:32:08.629: E/AndroidRuntime(14991): at com.facebook.android.Facebook.dialog(Facebook.java:780)
03-02 13:32:08.629: E/AndroidRuntime(14991): at com.facebook.android.Facebook.dialog(Facebook.java:737)
03-02 13:32:08.629: E/AndroidRuntime(14991): at com.facebook.android.Example$SampleAuthListener.onAuthSucceed(Example.java:113)
03-02 13:32:08.629: E/AndroidRuntime(14991): at com.facebook.android.SessionEvents.onLoginSuccess(SessionEvents.java:78)
03-02 13:32:08.629: E/AndroidRuntime(14991): at com.facebook.android.Example$LoginDialogListener.onComplete(Example.java:88)
03-02 13:32:08.629: E/AndroidRuntime(14991): at com.facebook.android.Facebook$1.onComplete(Facebook.java:320)
03-02 13:32:08.629: E/AndroidRuntime(14991): at com.facebook.android.FbDialog$FbWebViewClient.shouldOverrideUrlLoading(FbDialog.java:144)
03-02 13:32:08.629: E/AndroidRuntime(14991): at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:218)
03-02 13:32:08.629: E/AndroidRuntime(14991): at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:337)
03-02 13:32:08.629: E/AndroidRuntime(14991): at android.os.Handler.dispatchMessage(Handler.java:99)
03-02 13:32:08.629: E/AndroidRuntime(14991): at android.os.Looper.loop(Looper.java:130)
03-02 13:32:08.629: E/AndroidRuntime(14991): at android.app.ActivityThread.main(ActivityThread.java:3687)
03-02 13:32:08.629: E/AndroidRuntime(14991): at java.lang.reflect.Method.invokeNative(Native Method)
03-02 13:32:08.629: E/AndroidRuntime(14991): at java.lang.reflect.Method.invoke(Method.java:507)
03-02 13:32:08.629: E/AndroidRuntime(14991): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
03-02 13:32:08.629: E/AndroidRuntime(14991): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
03-02 13:32:08.629: E/AndroidRuntime(14991): at dalvik.system.NativeStart.main(Native Method)
```
Any idea? | 2012/03/02 | [
"https://Stackoverflow.com/questions/9529504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917206/"
] | After execute the thread, add these two line of code, and that will solve the issue.
```
Looper.loop();
Looper.myLooper().quit();
``` | Another developer use case: If the `WindowManager` or `getWindow()` is being called on `onCreate()` or `onStart()` or `onResume()`, a `BadTokenException` is thrown. You will need to wait until the view is prepared and attached.
Moving the code to `onAttachedToWindow()` solves it. It may not be a permanent solution, but as much as I could test, it always worked.
In my case, there was a need to increase the screen brightness when the activity became visible. The line `getWindow().getAttributes().screenBrightness` in the `onResume()` resulted in an exception. Moving the code to `onAttachedToWindow()` worked. |
30,836,183 | I'm working on an application that requires the use of getting dates for national holidays.
Below, I was able to get Memorial Day:
```swift
// Set the components for Memorial Day (last Monday of May)
let memorialDayComps = NSDateComponents()
memorialDayComps.weekday = 2
memorialDayComps.month = 5
memorialDayComps.year = currentYear
var mondaysOfMay = [NSDate]()
for var i = 1; i <= 5; i++ {
memorialDayComps.weekdayOrdinal = i
let monday = calendar.dateFromComponents(memorialDayComps)
let components = calendar.components(.CalendarUnitMonth, fromDate: monday!)
if components.month == 5 {
mondaysOfMay.append(monday!)
}
}
let memorialDayDate = mondaysOfMay.last
```
Because the dates are pretty well set, I am able to successfully create `NSDate` instances for the following holidays:
* New Year's Day
* Martin Luther King, Jr. Day
* Presidents' Day
* Memorial Day
* Independence Day
* Labor Day
* Thanksgiving Day
* Christmas Day
However, the only one that I am having difficulty figuring out how to get is Easter. It varies every year, so I'm curious as to whether anyone else has been able so successfully get the date for Easter via an API or other means. | 2015/06/15 | [
"https://Stackoverflow.com/questions/30836183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3720634/"
] | I was able to find a [gist](https://gist.github.com/duedal/2eabcede718c69670102) on GitHub that has a solution that was accurate for calculating and returning an `NSDate` for Easter.
The code below is what the gist contains:
```swift
// Easter calculation in swift after Anonymous Gregorian algorithm
// Also known as Meeus/Jones/Butcher algorithm
func easter(Y : Int) -> NSDate {
let a = Y % 19
let b = Int(floor(Double(Y) / 100))
let c = Y % 100
let d = Int(floor(Double(b) / 4))
let e = b % 4
let f = Int(floor(Double(b+8) / 25))
let g = Int(floor(Double(b-f+1) / 3))
let h = (19*a + b - d - g + 15) % 30
let i = Int(floor(Double(c) / 4))
let k = c % 4
let L = (32 + 2*e + 2*i - h - k) % 7
let m = Int(floor(Double(a + 11*h + 22*L) / 451))
let components = NSDateComponents()
components.year = Y
components.month = Int(floor(Double(h + L - 7*m + 114) / 31))
components.day = ((h + L - 7*m + 114) % 31) + 1
components.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let cal = NSCalendar(calendarIdentifier: NSGregorianCalendar)
return cal.dateFromComponents(components)
}
println(easter(2014)) // "2014-04-20 00:00:00 +0000"
``` | Here is a Swift 5 implementation of [*O'Beirne*'s algorithm](https://books.google.be/books?id=zfzhCoOHurwC&num=15&pg=PA828) with inline documentation.
The code is more compact than the implementations in the other provided answers because it makes use of Integer arithmetic and thus removes the need to explicitly round numbers and convert between `Float`s and `Int`s.
```
/// **How ten divisions lead to Easter** *by T. H. O'Beirne, New Scientist, march 30 1961 - Vol. 9,Nr. 228*
func easter(in year: Int) -> (day: Int, month: Int) {
/// Identify the position of the `year` in a 19-year cycle, to use this later to determine the principal constituent of the changes of full-moon dates from year to year
let a = year % 19
/// Take note of the corrections which the Gregorian calendar introduces in century years
let (b, c) = year.quotientAndRemainder(dividingBy: 100)
/// Take account of the leap-year exceptions in century years
let (d, e) = b.quotientAndRemainder(dividingBy: 4)
/// Provide similarly for the century years auxiliary corrections to the new-moon and full-moon dates
let g = (8*b + 13) / 25
/// Determine the number of days between 21 March and the coincident or next full moon, if no special exceptions arise
let h = (19*a + b - d - g + 15) % 30
/// Determine the position of the year in the ordinary leap-year cycle of four years
let (i, k) = c.quotientAndRemainder(dividingBy: 4)
/// Determine number of days (between 0 and 6) until the Sunday *after* full moon
let l = (2*e + 2*i - h - k + 32) % 7
/// The exceptions which make a 29-day month interrupt the regularity of a simpler pattern need here be considered *only* when they transfer the full moon *from a Sunday to a Saturday*: the *Easter date* is unaffected in other cases. When appropriate — 1954 and 1981 are quite rare examples — we have m=1; otherwise m=0 : this permits the necessary correction (failing which the Easter date *would* be 26 April in 1981.
let m = (a + 11*h + 19*l) / 433
/// Determine days between March 22 and Easter
let relativeDayCount = h + l - 7*m
/// Convert relative day count into absolute month and day index
let month = (relativeDayCount + 90) / 25
return (day: (relativeDayCount + 33*month + 19) % 32, month)
}
func easterDate(in year: Int) -> Date {
let (day, month) = easter(in: year)
let components = DateComponents(
timeZone: TimeZone(secondsFromGMT: 0),
year: year, month: month, day: day
)
return Calendar(identifier: .gregorian).date(from: components)!
}
``` |
39,606,379 | I have two yii2 projects based on kartik practical A and B. Both using johnitvn/ajaxcrudmodal. It looks like single page crud with ajax modal for create and update.
I use kartik select2 in \_form.php.
However, in the project that based on practical A it can work carefully. But in the project that use practical B, it shows correctly but the searchbox is not working. It cannot be clicked and I cannot type anything on it.
I already set tabindex to false.
```
<?php
Modal::begin([
"id" => "ajaxCrudModal",
"footer" => "", // always need it for jquery plugin
'size' => Modal::SIZE_DEFAULT,
'options' => [
'class' => 'slide',
'tabindex' => false // important for Select2 to work properly
],
])
?>
<?php Modal::end(); ?>
```
Can someone help? I confused why in one project it works but not working in other project??
Thanks,
Daniel | 2016/09/21 | [
"https://Stackoverflow.com/questions/39606379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2264589/"
] | This isn't something you're going to fix yourself.
The problem that you're facing is that you need compiler assistance. In the "real" Visual Studio, that's provided by Intellisense. This includes a C++ compiler (surprisingly enough, not Microsoft's own but EDG's). Since it's a compiler, it's smart enough to figure out what `std::fstream` really is: `std::basic_fstream<char>`, a template. Instantiating that gives Intellisense a list of members.
But without the Intellisense compiler, VS Code cannot figure out the members of that template. | It works in my VS2008, while you must include the corresponding header file firstly. |
4,056,614 | I've read about how a hard job in programming is writing code "at the right level of abstraction". Although abstraction is generally hiding details behind a layer, is writing something at the right level of abstraction basically getting the methodss to implement decision correct? For example, if I am going to write a class to represent a car, I will provide properties for the wheels etc, but if I am asked to write a class for a car with no wheels, I will not provide the wheels and thus no method to "drive" the car. Is this what is meant by getting the abstraction right?
Thanks | 2010/10/29 | [
"https://Stackoverflow.com/questions/4056614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32484/"
] | I don't think that's it.
To me, abstraction is synonymous with generalization. The more abstract something is, the more the author is trying to think about a problem in such a way that it's easier to extend and apply to new problems.
In general, greater abstraction requires more effort to develop and to understand. If you're a developer, and you're given a highly abstract framework to work with, you'll be forced to think in terms of the framework rather than using concepts that your common sense might suggest.
So, as in your example, a Car would be a very low level of abstraction. A RollingVehicle might be a higher one, and Transport might be the most abstract of all.
The right choice depends on how broadly you wish to apply your classes and how easily understood you'd like them to be. | I think one dangerous aspect of abstraction is its ability to erase or hide the reality or the design it represents. You should always maintain a reasonable distance between what you represent and the representation. By "reasonable" I mean easily understandable by an external developer how hasn't been coding on this specific project.
Joel Spolsky stated it quite right talking about the dangers of ["architecture astronauts"](http://www.joelonsoftware.com/articles/fog0000000018.html):
>
> When great thinkers think about problems, they start to see patterns. They look at the problem of people sending each other word-processor files, and then they look at the problem of people sending each other spreadsheets, and they realize that there's a general pattern: sending files. That's one level of abstraction already. Then they go up one more level: people send files, but web browsers also "send" requests for web pages. And when you think about it, calling a method on an object is like sending a message to an object! It's the same thing again! Those are all sending operations, **so our clever thinker invents a new, higher, broader abstraction called messaging, but now it's getting really vague and nobody really knows what they're talking about any more. Blah**.
>
>
> |
21,457,906 | 
We have tabbar and a more view controller (bacuse too many icons for the tabbar) with icon and text. The icon (png) image color is black but on the device or simulator it's always gray. I would like to know how to change the icon color or transparency of the icon. Idea why? | 2014/01/30 | [
"https://Stackoverflow.com/questions/21457906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/777612/"
] | `default=randomword()` is wrong. Since the function has called so become a constant, it is not a function any more. Pass a callable function if you want to get different values every execution:
```
import random, string
from sqlalchemy import create_engine, Column, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
engine = create_engine('sqlite:///foo.db')
Session = sessionmaker(bind=engine)
sess = Session()
def randomword():
return ''.join(random.choice(string.lowercase) for i in xrange(10))
class Foo(Base):
__tablename__ = 'foo'
key = Column(String, primary_key=True, default=randomword)
Base.metadata.create_all(engine)
```
Demo:
```
>>> sess.add(Foo())
>>> sess.add(Foo())
>>> sess.add(Foo())
>>> sess.flush()
>>> [foo.key for foo in sess.query(Foo)]
[u'aerpkwsaqx', u'cxnjlgrshh', u'dszcgrbfxn']
``` | default=randomword will solve the issue.
Not useful for you case, but there is another default called 'server\_default' which sits at the DB. So, even if you are manually inserting rows, 'server\_default' gets applied. |
35,914,161 | I am attempting to set a certificate in my CloudFrontDistribution using Cloud Formation.
My certificate has been issued via Certificate Manager. It has been approved, and I have validated that the certificate works by manual configuration directly through the CloudFront console.
Within my CloudFormation template, I have attempted to use both the *Identifier* and *ARN* values associated with the certificate in the IamCertificateId property:
```
"ViewerCertificate" : {
"IamCertificateId" : "********",
"SslSupportMethod": "sni-only"
}
```
But in both cases I receive the following error:
```
The specified SSL certificate doesn't exist, isn't valid, or doesn't include a valid certificate chain.
```
Reading the docs for the [DistributionConfig Complex Type](http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/DistributionConfigDatatype.html#DistributionConfigDatatype_Elements) it looks like there is a 'ACMCertificateArn' property, but this does not seem to work via CloudFormation.
Any help would be appreciated. | 2016/03/10 | [
"https://Stackoverflow.com/questions/35914161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14971/"
] | Cloudformation added this property but it is not documented. You can use like this easily:
```
"ViewerCertificate": {
"SslSupportMethod": "sni-only",
"AcmCertificateArn": "CERTIFICATE_ARN"
}
```
Be aware that the certificate must be created in us-east-1 region, if not it won't be accepted. | Took a few days but found the answer with some help from AWS support.
The information for:
```
"ViewerCertificate" : {
"IamCertificateId" : "********",
"SslSupportMethod": "sni-only"
}
```
is found using the CLI "aws iam list-server-certificates":
```
{
"ServerCertificateId": "ASCAXXXXXXXXXXXXXX",
"ServerCertificateName": "devops.XXXXXXX.com",
"Expiration": "2017-03-10T15:00:33Z",
"Path": "/cloudfront/",
"Arn": "arn:aws:iam::XXXXXXXXXXX:server-certificate/cloudfront/devops.XXXXXXXXXXX.com",
"UploadDate": "2016-03-14T16:13:59Z"
},
```
Once I found that I added a variable cloudfront.CloudFrontCertificateId with the ServerCertificateId and fed it into the ViewerCertificate:
```
"ViewerCertificate" : {
"IamCertificateId" : {{ cloudfront.CloudFrontCertificateId }},
"SslSupportMethod": "sni-only"
}
``` |
3,622,180 | As an example, in $\mathbb{R^3}$, the canonical basis is:\begin{align}
B &= \left(\begin{bmatrix}
1 \\
0 \\
0
\end{bmatrix},\begin{bmatrix}
0 \\
1 \\
0
\end{bmatrix}, \begin{bmatrix}
0 \\
0 \\
1
\end{bmatrix}\right)
\end{align}
So it is a set of 3 vectors.
There are also different bases in $\mathbb{R^3}$ but they always are sets of 3 vectors. I am wondering why couldn't just \begin{align}
A &= \begin{bmatrix}
1 \\
1 \\
1
\end{bmatrix}
\end{align}
be considered a basis? Couldn't vector A, multiplied with any scalar reproduce the whole vector space $\mathbb{R^3}$? | 2020/04/12 | [
"https://math.stackexchange.com/questions/3622180",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/248360/"
] | The vector $(1,1,1)$ clearly doesn’t span all of $\mathbb R^3$ since you can only generate vectors of the form $(a,a,a)$ from it: remember that when you multiply a vector by a scalar, you multiply all of the components by the same value.
You do ask an important question earlier, though: does every basis of $\mathbb R^3$ have exactly three vectors? For that, we have to look into the definition of the *dimension* of a (finite-dimensional) vector space more closely. You’ve probably learned it as the number of vectors in a basis for the space, but how do we know that this number is well-defined? There are two key theorems that bear on this which are presented in more rigorous expositions of the material before defining dimension. I won’t prove them here, but they basically say that there’s a maximum number of vectors that can form a linearly-independent set, and that if you have a linearly-independent set of vectors that spans a space, then no smaller set of vectors can span it. Applying the second theorem to your question in particular, since the standard basis consists of three vectors, this means that we can never find a set of fewer than three vectors that will span all of $\mathbb R^3$.
Taken together, these two theorems say that the number of linearly-independent vectors that it takes to span a space is unique, and we call that number the dimension of the space. | No, it cannot reproduce.
The dimension of a vector space is an invariant in the sense that each basis of an $n$-dimensional vector space consists of $n$ elements.
Your vector $A$ is a linear combination of the canonical basis $B=\{e\_1,e\_2,e\_3\}$:
$A = e\_1 + e\_2 + e\_3$, but not every vector in ${\Bbb R}^3$ is a scalar multiple of $A$. |
64,200,443 | Cant Really bend my mind around this problem I'm having:
say I have 2 arrays
```py
A = [2, 7, 4, 3, 9, 4, 2, 6]
B = [1, 1, 1, 4, 4, 7, 7, 7]
```
what I'm trying to do is that if a value is repeated in array B (like how 1 is repeated 3 times), those corresponding values in array A are added up to be appended to another array (say C)
so C would look like (from above two arrays):
```py
C = [13, 12, 12]
```
Also sidenote.. the application I'd be using this code for uses timestamps from a database acting as array B (so that once a day is passed, that value in the array obviously won't be repeated)
Any help is appreciated!! | 2020/10/04 | [
"https://Stackoverflow.com/questions/64200443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14055214/"
] | Here is a solution without pandas, using only `itertools` `groupby`:
```
from itertools import groupby
C = [sum( a for a,_ in g) for _,g in groupby(zip(A,B),key = lambda x: x[1])]
```
yields:
```
[13, 12, 12]
``` | I would use pandas for this
Say you put those arrays in a DataFrame. This does the job:
```
df = pd.DataFrame(
{
'A': [2, 7, 4, 3, 9, 4, 2, 6],
'B': [1, 1, 1, 4, 4, 7, 7, 7]
}
)
df.groupby('B').sum()
``` |
26,899,973 | I'm in the process of experimenting with transitioning an existing web app from knockout to react js.
As it stands the application establishes a websocket connection to the server and receives update asynchronously (there can be many clients which can affect each others state, think chat room for example).
My Question is, if I were do the rendering server side, how could changes be pushed down to each client?
I've only just started reading up on rendering on the server so I may be misunderstanding how it works but the way I believe:
Client performs an action which is sent to the server, server responds with an html fragment which the client then replaces into it's DOM
In the case of an app where the state can be changed by either the server or another client, would I still be forced to use websockets/http polling to show these updates?
Is it possible for the server to push down new fragments otherwise? | 2014/11/13 | [
"https://Stackoverflow.com/questions/26899973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2778940/"
] | With React, unidirectional flows are often the best way to do it. To achieve this, we should use an event emitter.
Your get JSON from the server using websockets, SSE, or polling (it doesn't matter). They should be in an envelope format. This would be an example for a chat application.
```js
{
"type": "new-message",
"payload": {
"from": "someone",
"to": "#some-channel",
"time": 1415844019196
}
}
```
When you get this message from the server, you emit it as an event.
```js
var handleMessage = function(envelope){
myEventEmitter.emit(envelope.type, envelope.payload);
};
```
This is a form of dispatcher. It simply gets the event, and broadcasts it to anyone who's interested. Usually the interested party will be a component or a store (in flux).
```js
var MessageList = React.createClass({
componentDidMount: function(){
myEventEmitter.on('new-message', this.handleNewMessage);
},
handleNewMessage: function(message){
if (message.to === this.props.channel) {
this.setState({messages: this.state.messages.concat(message)});
}
},
componentWillUnmount: function(){
myEventEmitter.removeListener(this.handleNewMessage);
},
...
});
```
When the user submits a message, you'd emit a 'user-new-message' event. The same part of code that implements `handleMessage` would be listening to this event, send the message to the server, and emit a new-message event so that the UI could be updated.
You can also keep a list of received messages elsewhere in your code (not in a component), or make a request to get recent messages from the server.
Sending html from the server is usually a very bad, inflexible, and unperformant idea. AJAX is for getting data to the client, and the client chooses how to present this data to the user. | >
> if I were do the rendering server side, how could changes be pushed down to each client?
>
>
>
Well, you just said it, via Sockets.
However, this is not really "optimal". You wouldn't want to push markup down the line every time. I suggest you push a template down to the client if they don't have it, or just pre-load it in the page. When they do, just push down data down the line instead and have the client-side render it.
>
> In the case of an app where the state can be changed by either the server or another client, would I still be forced to use websockets/http polling to show these updates?
>
>
>
There's an alternative to WebSockets called Server-Side Events. It's kinda like WebSockets but it's one-way, server -> browser only. Browser listens for server-side stuff the same way you would via WebSockets. However, communicatiing *to the server*, you can use plain old AJAX or forms or whatever. [Support is limited](http://caniuse.com/#feat=eventsource) but there are polyfills.
In fact, you can do the same thing with WebSockets, just utilize the downline, but that would defeat its purpose. |
6,972,650 | I have a problem with the gloss effect in app icon at iOS 5 beta 5, in iOS 4 it's show the effect not gloss, but iOS5 shows the gloss effect. I put the option `Icon already includes gloss effects = YES`, but simply does not work, and it appears that the application Google+ also has the same problem | 2011/08/07 | [
"https://Stackoverflow.com/questions/6972650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/881095/"
] | First Settings in a your project info-list set key **Icon already inculdes gloss effects** to YES Boolean value like below screen shot:

after try project Target settings tick the **checkbox** in the **summary** tap in the **App Icons** section
like below screen shot:

it's worked for me!
Welcome in Advance! | There are 2 keys in the Info.plist governing this.
xCode generated the following code for you, but it doesn't offer a GUI for changing this:
Open your Info.plist file (Right Click > Open As > Source Code).
```
<key>CFBundleIcons</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>myIcon.png</string>
</array>
<key>UIPrerenderedIcon</key>
<false/>
</dict>
</dict>
```
set the `UIPrerenderedIcon = true` and you are good to go (this is NOT the other `UIPrerenderedIcon` that also exists in this file as a boolean key!). |
31,698,756 | I just added the new TabLayout component to my app. As you may know there are two different modes for tabs `app:tabMode="scrollable"` and `app:tabMode="fixed"`.
When I use `app:tabMode="fixed"` I get following result:
[](https://i.stack.imgur.com/1yEbJ.png)
There's no margin/padding on the left and right side but the text is wrapped.
But when I use `app:tabMode="scrollable"` I get following result:
[](https://i.stack.imgur.com/YpoAy.png)
The text is not wrapped but here is a weird margin on the right side and I can't get rid of it.
I also tried setting the tabGravity to either `app:tabGravity="center"` or `app:tabGravity="fill"` but did not achieve any changes.
Would be nice if any of you smart guys and girls got a solution for me.
Cheers, Lukas | 2015/07/29 | [
"https://Stackoverflow.com/questions/31698756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2642024/"
] | Here's a quick hack, a lot shorter than using `setCustomView()`: use the `android:theme` attribute on your `TabLayout`:
```
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/TabLayout_Theme"
app:tabMode="fixed"/>
```
Then in your themes XML:
```
<style name="TabLayout_Theme" parent="@style/AppTheme">
<item name="android:singleLine">true</item>
</style>
```
We have to do it this way, because unfortunately the `android:singleLine` attribute is ignored on the `app:tabTextAppearance` set on the TabLayout. `app:tabTextAppearance` is really only useful for changing text size. | With this code you are able to remove the default padding. For me it worked to make slightly longer texts within one line
```
<android.support.design.widget.TabLayout
app:tabPaddingStart="-1dp"
app:tabPaddingEnd="-1dp"
```
From here:
<http://panavtec.me/playing-with-the-new-support-tablayout> |
15,564,902 | I am trying to simulate a live data stream, to test a program that is constantly filtering and computing data points. Mainly I need to make sure that it will meet timing.
Every 50 milliseconds there will be a new data point that will need to be computed on.
So I would like to create a java clock that is independent of what is currently running in the jvm or anything like that happening on the system.
So my question is two fold:
first of all, System.currentTimeMillis() will not be what I want here because it is based on when the jvm was opened, and it would happen when ever the system call gets executed.
second, how do i make a thread that will be constantly running and always trigger exactly on the 50ms mark? | 2013/03/22 | [
"https://Stackoverflow.com/questions/15564902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742197/"
] | Not transparent, but still [lazy fetching](http://springinpractice.com/2011/12/28/initializing-lazy-loaded-collections-with-spring-data-neo4j/).
```
template.fetch(person.getDirectReports());
``` | Some updates based on the current neo4j reference - <http://docs.spring.io/spring-data/neo4j/docs/current/reference/html/>
@Fetch is a Obsolete annotation
neo4jTemplate.fetch() is not available, you should specify the depth - <http://docs.spring.io/spring-data/neo4j/docs/current/reference/html/#_api_changes> |
4,885,337 | How would I extract Active Directory info (Username, first name, surname) and populate an SQL table with the results?
Many thanks
Scott | 2011/02/03 | [
"https://Stackoverflow.com/questions/4885337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/601388/"
] | If you just need it in SQL, I'm using the code below
```
INSERT...
SELECT A.SAMAccountName, A.Mail, A.displayName FROM
(SELECT * FROM OpenQuery(ADSI, 'SELECT title, displayName, sAMAccountName, givenName, telephoneNumber, facsimileTelephoneNumber, sn, userAccountControl,mail
FROM ''LDAP://domain.ro/DC=domain,DC=ro'' where objectClass = ''User''')
WHERE (sn is not null) and (givenName is not null) and (mail is not null) )A
```
where ADSI is a linked server created based on this:
<http://msdn2.microsoft.com/en-us/library/aa772380(VS.85).aspx> | There are different ways to do that. I use PHP to get data out of our Active Directory.Take a look at the chapter "[Lightweight Directory Access Protocol](http://www.php.net/manual/en/book.ldap.php)" in the PHP Documentation. It's also easy to populate a database using PHP, e.g. [MySQL](http://www.php.net/manual/en/book.mysql.php) or [Microsoft SQL Server](http://www.php.net/manual/en/book.mssql.php). |
62,473,510 | Here is my SQL request for a PostgreSQL datatable
```
select main_bundle_statuses.status from (
select main_bundle.status,
row_number() over
(partition by main_bundle.client_id order by main_bundle.created desc)
as rnum
from bundle main_bundle
join config_dependence cd on cd.main_config_id = main_bundle.config_bundle_id
where cd.dependent_config_id = b.config_bundle_id
and main_bundle.client_id = b.client_id) main_bundle_statuses
where main_bundle_statuses.rnum = 1) as main_bundle_status,
```
I need to check null value of main\_bundle\_status, as a second column. I tried to write this:
```
(case
when main_bundle_status is null then true
else false
end) as dependent
```
But I got an error. How can I check the value - is it null or not, and return it as dependent? | 2020/06/19 | [
"https://Stackoverflow.com/questions/62473510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12898912/"
] | The problem is the lack of precision in pi. The result of the expression in your code is just 12.56. To get to 12.57, increase the precision.
```
from math import pi
R=2
Z=2*pi*R
print(round(Z, 2))
``` | You could use [`math.pi`](https://www.w3schools.com/python/ref_math_pi.asp) instead of `3.14` to be more precise, and then round it to two decimals, since with `math.pi` `Z=12.566370614359172`:
```
import math
R=2
Z= 2*math.pi*R
print(round(Z, 2))
>>>12.57
``` |
49,724,516 | I have an NSCollectionView and I would like to hide the horizontal scroll indicators.
I've tried
```
collectionView.enclosingScrollView?.verticalScroller?.isHidden = true
```
But it is not working.
Thank you in advance. | 2018/04/09 | [
"https://Stackoverflow.com/questions/49724516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3019776/"
] | **hidden** didn't work for me too.
The only way I found to hack this, is by changing inset:
(**scrollViewCollectionView** is of type **NSScrollView**, this example is while creating **NSCollectionView** programmatically)
```
scrollViewCollectionView.documentView?.enclosingScrollView?.scrollerInsets = NSEdgeInsets.init(top: 0, left: 0, bottom: 100, right: 0)
```
Please note: My NSCollectionView is horizontal, and less then 100 height, this is why this hack resolved in a hidden indicator. | I got same problem and just solve it. You can write your own custom `NSScrollView` and override 2 stored property: `hasHorizontalScroller`, `horizontalScroller`, and 1 function `scrollWheel(with:)`. Here's my code:
```
class MyScrollView: NSScrollView {
override var hasHorizontalScroller: Bool {
get {
return false
}
set {
super.hasHorizontalScroller = newValue
}
}
override var horizontalScroller: NSScroller? {
get {
return nil
}
set {
super.horizontalScroller = newValue
}
}
//comment it or use super for scrroling
override func scrollWheel(with event: NSEvent) {}
}
```
And don't forget to set `Border Scroll View` class to `MyScrollView` in .xib or storyboard.
Enjoy it! |
36,650,319 | I'm trying to make the user be able to remove his upvote by re-clicking on the upvote button
Here's my controller
```
def upvote
if current_user.voted_up_on? @post
@post = Post.find(params[:id])
@currentUserLikes = PublicActivity::Activity.where(trackable_id: @post.id, owner_id: current_user.id, key: "post.like")
@currentUserLikes.destroy_all
else
@post = Post.find(params[:id])
@post.upvote_by current_user
@post.create_activity :like,
owner: current_user,
recipient: @post.user
end
end
def downvote
@post = Post.find(params[:id])
@post.downvote_by current_user
@post.create_activity :dislike,
owner: current_user,
recipient: @post.user
end
```
I tried placing the if else in the index but it became too complicated,
why isn't it working?
Note that currentUserLike is to destroy user's upvote action.
**and**
The upvote button is no more working, I didn't post the index because I didn't change it back when I didn't change the controller | 2016/04/15 | [
"https://Stackoverflow.com/questions/36650319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5738789/"
] | Consider of using dictionary mapping:
```
dmap = {
'As': parse_as,
'Between': parse_between,
'During': parse_during
}
```
Then you only need to use it like this:
```
dmap = {
'As': parse_as,
'Between': parse_between,
'During': parse_during
}
for l in f.readline():
s = l.split(' ')
p = dmap.get(s, None)
if p is None:
print('error')
else:
ts1, ts2 = p(l)
#continue to process
```
A lot easier to maintain. If you have new function, you just need to add it into the `dmap` together with its keyword:
```
dmap = {
'As': parse_as,
'Between': parse_between,
'During': parse_during,
'After': parse_after,
'Before': parse_before
#and so on
}
``` | Why not use a regular expression?
```
import re
# open file
with open('datafile.txt') as f:
for line in f:
ts_vals = re.findall(r'(\d+:\d\d:\d\d)', line)
# process ts1 and ts2
```
Thus `ts_vals` will be a list with either one or two elements for the examples provided. |
43,534,240 | I have an AJAX request call (with JQuery) to my django view. It sends to view this kind of data:
```
{"cityId": 1, "products_with_priority": [{"id": 1, "priority": 1}, {"id": 2, "priority": 2}, {"id": 3, "priority": 3}, {"id": 4, "priority": 4}, {"id": 5, "priority": 5}]}
```
In my django view, I'm trying to get this list like this:
```
def my_view(request):
city_id = request.POST.get('city_id')
products_priorities = request.POST.getlist("products_with_priority")
```
Where `city_id` returns `1` and `products_with_priority` returns empty array.
How it is possible to receive array of dictionaries from request? | 2017/04/21 | [
"https://Stackoverflow.com/questions/43534240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3003432/"
] | Ensure your dataType is `json`, and stringify your array:
```
dataType: 'json',
data: {'cityId': 1, 'products_with_priority': JSON.stringify([{"id": 1, "priority": 1}, {"id": 2, "priority": 2}, {"id": 3, "priority": 3}, {"id": 4, "priority": 4}, {"id": 5, "priority": 5}])}
```
Then use the (standard Python library) `json`'s `loads()` method in your Django view:
```
products_priorities = json.loads(request.POST.get('products_with_priority'))
``` | In AJAX request, make sure you include the header:
```
content-type: application/json
```
Then if you are using Python 3 as I do, in Django View:
```
def my_view(request):
received_json = json.loads(request.read().decode('utf-8'))
products_priority = received_json['products_with_priority']
``` |
16,874,983 | API Console data seems to be corrupted for my account. I cannot recreate the Client ID for package **com.clc.mmm.free** and my production key.
The error I am getting is "This client ID is globally unique and is already in use", **although no Client ID exist for this package in any of my active or deleted API Console projects**.
Please note that I could delete and recreate Client IDs for other packages and keys with no problem. The issue is related with package com.clc.mmm.free.
This issue prevent me to publish my new version of the app which includes singn-in with Google+.
I'll really appreciate if an engineer from API Console team can look into this. Thank you.
(Sorry to re-post this issue, but I believe this better describes the problem as it cannot be easily reproduced probably...) | 2013/06/01 | [
"https://Stackoverflow.com/questions/16874983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004296/"
] | Since the key names you'll get from your CCTV system are not in quotes, the string is not a valid JSON string. You won't be able to parse it with `json_decode` without performing some ugly string modification.
When searching for an alternative, I found this answer: <https://stackoverflow.com/a/6250894/1560865>
The answer recommends to use the fact that JSON is a subset of YAML. Since YAML is a bit less strict about the quotes, you'll therefore should be able to parse your string with a YAML parser. | Use [`json_decode()`](http://www.php.net/manual/function.json-decode.php) with something like this:
```
<?php
$encdata = getTheData(); // your method to get the string
$data = json_decode($encdata);
foreach($data => $row)
{
// access the row members like this:
// $row->alarmimage
// $row->timestamp
// $row->date
// ...
}
?>
``` |
66,147,707 | I'm a student learning C and I was puttering around with arrays of strings and malloc().
I have the following code that is supposed to load an array of strings (statically created) with dynamically created strings (please forgive / correct me if my terminology does not align with the code I have).
The problem is, once I go to free that memory, I get the following error: `free(): invalid pointer`
Here is the code:
```
#include <stdio.h>
#include <stdlib.h>
#define RAM_SIZE 5
char* ram [RAM_SIZE];
int next_free_cell = 0;
void freeAndNullRam(){
for (int i = 0 ; i < RAM_SIZE ; i++){
printf("%d\n", i);
free(ram[i]);
ram[i] = NULL;
}
}
int main(int argc, const char *argv[])
{
for (int i= 0; i < RAM_SIZE; i++){
ram[i] = (char*)malloc(sizeof(char*)*5);
ram[i] = "aaaa";
}
for (int i= 0; i < RAM_SIZE; i++){
int empty = (ram[i] ==NULL);
if(!empty){
printf("%s\n", ram[i]);
}
}
freeAndNullRam();
for (int i= 0; i < RAM_SIZE; i++){
int empty = (ram[i] ==NULL);
printf("%d\n", empty);
}
return 0;
}
```
I know the issue is definitely in the `freeAndNullRam()` function (obviously), but I don't understand why. My understanding is that at compile time, an array of 5 pointers to char arrays is created, but to actually fill the cells of the array, I need to `malloc` them some memory. Why does the program complain when I free the pointers in the array, but not when I give them memory?
Thanks! | 2021/02/11 | [
"https://Stackoverflow.com/questions/66147707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8163401/"
] | `ram[i] = "aaaa";` reassigns the pointers at `a[i]` to point to static memory, discarding the result of `malloc`. Later on you pass those pointers to `free`, which fails because they were not the result of an `*alloc` function.
Use [`strcpy`](https://linux.die.net/man/3/strcpy) to instead copy the string from static memory into your allocated destination.
```
strcpy(a[i], "aaaa")
``` | C's syntax strongly suggests that `"aaaa"` is a "string". People even talk of this syntax that way: they call it "strings". But `"aaaa"` is nothing such. It's the unfortunately named string literal, which is *not* a string - neither in C nor in C++. A `char *` is not a string either - it's a pointer-typed value. It's used to represent strings, but itself is *not* a string - not even close.
You have *quite reasonably* expected that `"aaaa"` might behave like any other rvalue of the "obvious" type. Alas, while `1` is an integer literal of type `int`, `"aaaa"` is a string literal of a pointer type `const char *` - its value is not a string, but a pointer!
It's as if when you wrote `42`, C gave you a `const int *` pointing to `42`. That's what "string" literals do. That's the awfully deplorable side of C :(
In C++, there actually is a string type (`std::string`), and you can even write literals of that type with a new syntax introduced in C++11: `"aaaa"s` is an rvalue\* of type `std::string`, and you can assign them exactly as you would expect of any other value type like `int`.
Since you're already thinking a bit like in C++, perhaps you can investigate that language next. It takes much less effort to do plenty of basic things in C++ compared to C.
\*technically rvalue reference |
47,345,474 | Using C++11 or C++14:
I have a:
```
constexpr double [2][3][4] = some value;
```
I want `constexpr int [2][3][4]` from this.
(Actually I will want `constexpr my_type [2][3][4]`, but that should be trivially solvable once int works.)
The only solution I came up with was a container class with `operator[]` overloaded so it behaves like an array. Is there a way to keep standard array syntax? Or possibly `std::array<std::array...>>` without creating a new class?
I do not want the input to be `std::array` - that is a constraint of the system. The input must be C compatible. The converted array can be C++. | 2017/11/17 | [
"https://Stackoverflow.com/questions/47345474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832745/"
] | If you accept a `constexpr std::array<std::array<int, 4U>, 3U>, 2U>`, well... using ~~SFINAE~~ tag-dispatching, `std::rank`, `decltype()`, `auto` as return type and `std::index_sequence` (so a C++14 solution) you can ping-pong play with a `getArray()` and his helper `getArrayH()` functions as follows
**NOTE**: answer modified (improved, IMHO) taking inspiration from a Julius's example (thanks!)
```
#include <array>
#include <iostream>
#include <type_traits>
template <typename T>
std::integral_constant<bool, std::rank<T>::value != 0U> isArray ();
template <typename targetT, typename origT, std::size_t Dim>
constexpr auto getArray (origT(&)[Dim]);
template <typename targetT, typename arrT, std::size_t ... Is>
constexpr auto getArrayH (arrT const & arr,
std::false_type const &,
std::index_sequence<Is...> const &)
{ return std::array<targetT, sizeof...(Is)>{ { targetT(arr[Is])... } }; }
template <typename targetT, typename arrT, std::size_t ... Is>
constexpr auto getArrayH (arrT const & arr,
std::true_type const &,
std::index_sequence<Is...> const &)
{ return std::array<decltype(getArray<targetT>(arr[0])), sizeof...(Is)>
{ { getArray<targetT>(arr[Is])... } }; }
template <typename targetT, typename origT, std::size_t Dim>
constexpr auto getArray (origT(&arr)[Dim])
{ return getArrayH<targetT>(arr, decltype(isArray<origT>()){},
std::make_index_sequence<Dim>{}); }
int main ()
{
constexpr double ad3[2][3][4]
{ { { 1.0, 2.0, 3.0, 4.0 },
{ 2.1, 3.1, 4.1, 5.1 },
{ 3.2, 4.2, 5.2, 6.2 } },
{ { 6.3, 5.3, 4.3, 3.3 },
{ 5.4, 4.4, 3.4, 2.4 },
{ 4.5, 3.5, 2.5, 1.5 } } };
for ( auto const & ad2 : ad3 )
for ( auto const & ad1 : ad2 )
for ( auto const & ad0 : ad1 )
std::cout << ad0 << ' ';
std::cout << std::endl;
constexpr auto ai3 = getArray<int>(ad3);
static_assert(std::is_same<decltype(ai3),
std::array<std::array<std::array<int, 4U>, 3U>, 2U> const>{}, "!");
for ( auto const & ai2 : ai3 )
for ( auto const & ai1 : ai2 )
for ( auto const & ai0 : ai1 )
std::cout << ai0 << ' ';
std::cout << std::endl;
}
``` | Unfortunately, [`std::array::operator[]` is not constexpr before C++17](http://en.cppreference.com/w/cpp/container/array/operator_at). Hence you probably need to come up with your own boilerplate.
Here is an example in C++17. If you export the "indices trick" into a separate function (instead of lambda) and implement your own version of `std::array`, then this approach should also work with C++14.
<https://godbolt.org/g/FayqEn>
```
#include <array>
#include <iostream>
#include <utility>
////////////////////////////////////////////////////////////////////////////////
template<size_t... is, class F>
constexpr decltype(auto) indexer(std::index_sequence<is...>, F f) {
return f(std::integral_constant<std::size_t, is>{}...);
}
template<size_t N_, class F>
constexpr decltype(auto) indexer(F f) {
constexpr size_t max_index_length = 4096;
constexpr size_t N = std::min(N_, max_index_length);
static_assert(N == N_, "");
return indexer(std::make_index_sequence<N>{}, f);
}
////////////////////////////////////////////////////////////////////////////////
template<class T>
constexpr auto make_array(T val) {
return val;
}
template<class NestedArrays, std::size_t N>
constexpr auto make_array(NestedArrays(&arr)[N]) {
using NestedStdArrays = decltype(make_array(arr[0]));
return indexer<N>([=] (auto... ns) {
return std::array<NestedStdArrays, N>{
make_array(arr[ns])...
};
});
}
////////////////////////////////////////////////////////////////////////////////
int main() {
constexpr int input_from_c[1][3][2]{
{ {0, 10}, {20, 30}, {40, 50} }
};
constexpr auto nested_std_arrays = make_array(input_from_c);
using NestedStdArrays = std::decay_t<decltype(nested_std_arrays)>;
static_assert(
std::is_same<
NestedStdArrays,
std::array<std::array<std::array<int, 2>, 3>, 1>
>{}, ""
);
static_assert(0 == nested_std_arrays[0][0][0], "");
static_assert(10 == nested_std_arrays[0][0][1], "");
static_assert(20 == nested_std_arrays[0][1][0], "");
static_assert(30 == nested_std_arrays[0][1][1], "");
static_assert(40 == nested_std_arrays[0][2][0], "");
static_assert(50 == nested_std_arrays[0][2][1], "");
return 0;
}
``` |
3,650,995 | I'm starting to design an application, that will, in part, run through a directory of files and compare their extensions to their file headers.
Does anyone have any advice as to the best way to approach this? I know I could simply have a lookup table that will contain the file's header signature. e.g., `JPEG: \xFF\xD8\xFF\xE0`
I was hoping there might be a simper way.
Thanks in advance for your help. | 2010/09/06 | [
"https://Stackoverflow.com/questions/3650995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180449/"
] | I'm afraid it'll have to be more complicated than that. Not every file type has a header at all, and some (such as RAR) have their characteristic data structures at the end rather than at the beginning.
You may want to take a look at the Unix `file` command, which does the same job:
* <http://linux.die.net/man/1/file>
* <http://linux.die.net/man/5/magic> | You can know the file type of file reading the header using apache tika.
Following code need apache tika jar.
```
InputStream is = MainApp.class.getResourceAsStream("/NetFx20SP1_x64.txt");
BufferedInputStream bis = new BufferedInputStream(is);
AutoDetectParser parser = new AutoDetectParser();
Detector detector = parser.getDetector();
Metadata md = new Metadata();
md.add(Metadata.RESOURCE_NAME_KEY,MainApp.class.getResource("/NetFx20SP1_x64.txt").getPath());
MediaType mediaType = detector.detect(bis, md);
System.out.println("MIMe Type of File : " + mediaType.toString());
``` |
8,603,944 | I'm getting a text from server side and I want to show one word for each button click. Here is my approach:
```
$(document).ready(function()
{
$.ajax(
{
type: "GET",
dataType: 'json',
url: "request.php",
success: function (response){
var words = text.match(/\b([a-z]{1,})\b/gi); //text is an element of json array
for (i = 0; i < 10; ++i)
$("#container").append("<span>"+words[i]+"</span>").hide();
}
});
});
```
My function to display words. It doesn't work, just for explaining what I'm trying to do.
```
$(function()
{
$("#button").click(function(){
$("#container span").fadeIn(450); // shows nothing
});
});
```
Jquery selector can't select the spans because they are not at html. Could you advise me a solution?
(When I wrote $("#container").fadeIn(450); it shows all the words.) | 2011/12/22 | [
"https://Stackoverflow.com/questions/8603944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/784266/"
] | There two problems with your code;
You're using `.append()` to append `span` elements to `#container` but it returns `#container` jQuery object. So everytime you append a `span` element you call `.hide()` for `#container`. As you can see I changed it a little. You have to create `span` element, hide it and then append it to `#container`, like this;
```
$("<span>"+words[i]+" </span>").hide().appendTo("#container");
```
Second problem is with your `.click()` function. Your selector selects all span elements, there is pseudo selectors for selecting hidden elements or first element etc. Using them together you can select first hidden element like this;
```
$('#container span:hidden:first');
```
And finally implementing these to your code will give us this result;
```
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: 'json',
url: "request.php",
success: function(response) {
var words = text.match(/\b([a-z]{1,})\b/gi); //text is an element of json array
for (i = 0; i < 10; ++i) {
$("<span>"+words[i]+" </span>").hide().appendTo("#container");
}
}
});
});
$(function() {
$("#button").click(function() {
$('#container span:hidden:first').fadeIn(450);
});
});
```
But of course, if you want to `fadeIn` all of your `span` elements at once you can use your piece of code;
```
$("#container span").fadeIn(450);
```
[Here](http://jsfiddle.net/karalamalar/ELHsE/) is an example of your code. | Declare two vars:
```
var arr = [];
var inc = 0;
```
After the ajax call, store the words to an array:
```
for (i = 0; i < 10; ++i)
arr.push(words[i]);
}
```
then:
```
$("#button").click(function(){
while (inc < arr.length) {
$("#container").html("<span>"+words[i]+"</span>");
inc++;
});
```
I havent tested this. Hope this helps. |
531,685 | I have a MacPorts installed ProFTPD daemon installed. It worked like a charm for a year. Now it does not work at all anymore. All I get is
### Connection refused
```
ftp localhost
Trying ::1...
ftp: Can't connect to `::1': Connection refused
Trying 127.0.0.1...
ftp: Can't connect to `127.0.0.1': Connection refused
Trying fe80::1%lo0...
ftp: Can't connect to `fe80::1%lo0': Connection refused
ftp: Can't connect to `localhost'
```
I wrote to MacPorts and ProFTP, but no answers there as of yet so I hope someone here can help me out.
### Troubleshooting
Found some troubleshooting tips [here](https://serverfault.com/questions/227309/proftpd-not-working).
When I check for ProTPD processes I get
```
ps -ef | grep proftpd
0 58 1 0 4Aug13 ?? 0:00.77 /opt/local/bin/daemondo --label=proftpd --start-cmd /opt/local/etc/LaunchDaemons/org.macports.proftpd/proftpd.wrapper start ; --stop-cmd /opt/local/etc/LaunchDaemons/org.macports.proftpd/proftpd.wrapper stop ; --restart-cmd /opt/local/etc/LaunchDaemons/org.macports.proftpd/proftpd.wrapper restart ; --pid=none
501 27233 26992 0 1:42PM ttys000 0:00.00 grep proftpd
```
So it seems some processes are running. But not the needed ProFTPD process.
When I used the following command to see if port 21 is active:
```
sudo lsof -i :21
```
I get zero results. So ProFTPD is clearly not running and port 21 is not active which is the regular FTP port.
### Question
Does anyone here know what I am missing here? I need it back to to the sweet any easy updating of local website copies.
### Update
ProFTPD Configuration file is here <http://pastebin.com/4VvSHz5p> . Even though it is a basic setup there does not seem to be anything wrong with it. @Janne Pikkarainen mentioned it was missing directories, but in the end this was not the issue.
### Update 2 Debug Commands
Asked by GioMac I tried `sudo proftpd -n -d 10`. Command was not found. The command `sudo /opt/local/sbin/proftpd -n -d 10` did work and gave us some clues
### Update 3 Re-installation Port
I reinstalled all as suggested by GioMac and that did not work either. Still had the same errors.
### Update 4 The Solution: Proper (re)starting ProFTDP
Then I ran `sudo /opt/local/etc/LaunchDaemons/org.macports.proftpd/proftpd.wrapper start` as suggested by @GioMac. Running similar command from sbin and bin did not work. And then I tested the FTP connection again.
```
sudo /opt/local/etc/LaunchDaemons/org.macports.proftpd/proftpd.wrapper start
Password:
```
Command worked and I had no errors. ProFTPD was (re)started like this again. Then I did the ultimate test to see if I could FTP locally again:
```
jaspersmbp:etc jasper$ cd
jaspersmbp:~ jasper$ ftp jasper@localhost
Trying ::1...
ftp: Can't connect to `::1': Connection refused
Trying 127.0.0.1...
Connected to localhost.
220 ProFTPD 1.3.3e Server (ProFTPD Default Installation) [127.0.0.1]
331 Password required for jasper
Password:
230 User jasper logged in
Remote system type is UNIX.
```
Eureka! Connection could be made again and I could also update my local WordPress installations again. | 2013/08/17 | [
"https://serverfault.com/questions/531685",
"https://serverfault.com",
"https://serverfault.com/users/101547/"
] | If you're talking about backing up the vhd of the virtual machine, you can:
* Create periodic blob **snapshots** (since the vhd is stored in a Windows Azure Storage blob). Initially snapshots don't really take up any space since they're effectively an index of storage pages. Over time, if these pages change, *then* the snapshot(s) grow in size. You can create as many snapshots as you want, but you'll need to purge them over time to avoid storage growth as your vhd changes.
* Create blob **copies**. This is a complete copy of the vhd, unlike the snapshot. And you can make copies across storage accounts (or even across data centers).
Regarding the snapshots: You can create a brand new blob from a snapshot, which you may find convenient at times.
Regarding the blob-copies: The one challenge you might run into, when making a blob copy: If the source changes during the copy, the copy will fail. So for an OS vhd, this operation should only be done if the Virtual Machine is in a stopped state. You may find snapshots to be the better mechanism in this case.
There's really no Azure-specific mechanism for things like system restore points, as that's within the OS itself. | This is a nice tutorial complementing David's answer: [Create Backups of Virtual Machines in Windows Azure by using PowerShell](http://blogs.technet.com/b/heyscriptingguy/archive/2014/01/24/create-backups-of-virtual-machines-in-windows-azure-by-using-powershell.aspx)
You can backup *AzureOSDisk* and *AzureDataDisk* in four steps:
* Select virtual machine to back up
* Identify virtual hard disks
* Create cloud storage container for storing backups
* Back up virtual machines in Windows Azure to cloud storage |
37,276,732 | `calling button.selected = true` does not fills the entire button frame with tint color.
>
> Expected result
>
>
>
The button should be filled entirely with the tint color in selected state.
>
> Actual result
>
>
>
The tint color only filled the the area around the text in button.
[](https://i.stack.imgur.com/Fepgw.png)
How to **fill the entire button frame(area)** with the color when the button is in **selected(or any other) state**? | 2016/05/17 | [
"https://Stackoverflow.com/questions/37276732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3600738/"
] | I agree with **Mike**, the question is a bit ambiguous. I think what you're asking for is:
```
<span>{{::ma.cities[ma.selected].Name}}</span>
```
But then again, as **Mike** said, you could've achieved that with another scope variable, and it would be probably a much clearer solution. | As YOU adviced I modified html template:
```
<span ng-repeat="city in ::ma.cities" class="view" ng-if="::city.Id == ma.selectedId">
{{city.Name}}
</span>
```
Here is [plunker](http://plnkr.co/edit/IqkZEIvQFSn9oIRS9Sfc?p=info). |
8,807 | On earth, we use a simple but effective coordinate system which determines position unambiguously on the surface (GPS achieving accuracy within 1 meter, which speaking as an engineer, is a remarkable feat in of itself).
For example, Greenwich, England is located at coordinates 51.4800° N, 0.0000°. This disregards tilt of the earth, position around the sun, minor gravitational directional changes due to the pull of the moon, etc. because they are not relevant.
My point is that should we one day inhabit one or more planets outside our solar system, we'll need a new unambiguous system to identify coordinates of the planet in 3d space.
A 3d coordinate system with an x, y, and z coordinate would be relatively impractical since the position of the planet in question would be constantly changing position. There are several factors that come to mind to take into consideration:
* Position of the star it is orbiting
* Any local moons that may alter it's position slightly.
* The tilt of the planet at any given moment (unlike our current system which needs not consider the current tilt of the planet, you would need to know the current tilt in order to find the proper 2d planetary coordinates)
Like most good systems, it must have the following qualities:
* Be precise, in this case lets say within a kilometer of the destination.
* Be concise. Minimize the amount of information you need to provide, in this case in order to unambiguously find the position of the planet
* Be accurate also in the near future. Coordinates which are established on earth must still unambiguously be valid by the time a ship arrives (lets say remain within a kilometer of the destination within 100+ years time)
Assume there are no adverse space-time effects to consider (which would likely make an accurate and practical interplanetary coordinate system nearly impossible).
Assume that we will have computers and thus you do not have to provide information that could otherwise be calculated or remains relatively static (within 100 years time stays the same). For example, given a star's 3d coordinates and angle, a computer would load the planet's distance from the sun and be able to determine roughly where that planet would be, without having to include it in the coordinate system. | 2015/01/16 | [
"https://worldbuilding.stackexchange.com/questions/8807",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/557/"
] | >
> Suppose you were given orders to explore an unknown planet's volcano, how would they deliver the coordinates?
>
>
>
"They" would need to give you two things: the coordinates of the planet itself, needed for the interplanetary travel, and the coordinates of the volcano on the planet.
These are two different coordinate systems, with different origins and uses. It is like when you say "42nd Main Street, third floor, office 31". You use a three dimensional system for locating the bunch of offices of the company (42nd Main Street, third floor) and then a different system to locate office 31.
So, to locate the planet, the system does actually exist. Actually, several of them. The simplest method is to give planet's xyz coordinates, but the more stable is to give its orbital parameters. These are enough to know where the planet is just knowing the time.
e.g. Earth has a semi-major axis of 149513000 km, eccentricity of 0.0161700, inclination of 7.155 deg to Sun's equator, and an argument of perihelion of 326.0590 deg. These, together with current time, tell you exactly "Where Earth is".
Once on the planet, the current longitude/latitude system is well defined once you know the origin of longitudes, to say, the Greenwich point.
If you were also in need to locate the star itself, for interstellar trips, you have two options: either the galactic coordinates (galactic latitude, galactic longitude and distance to the galactic center) or those relative to Sun's position. | The co-ordinate system you choose would depend on the location you want to specify.
If you want to specify the position of a star within the Milky Way, one option might be to use a polar co-ordinate system centered on the galactic center of mass. Inspired by the terrestrial longitude/latitude co-ordinate system, we would align the North/South axis with the galactic axis of rotation (mean orbital axis of all the stars in the galaxy). This would require a choice of "North", a "galactic prime meridian" (0 degree "galactic longitude" plane), and a choice of right or left handed co-ordinates (in which direction do longitude values increase). We might base the galactic prime meridian on the location of the Sun. Of course the Sun is in orbit around the galactic center, so our co-ordinate system would be slowly rotating. It would also mean that virtually every star in the galaxy will have some motion with respect to this co-ordinate system, so won't have a fixed location. However, that motion might be slow enough that we can assign galactic co-ordinates to stars and they will remain useful for practical time spans.
To specify the location of a remote world, you'd have to identify its host star and its orbital parameters, as described in other answers.
To specify a location on the surface of a remote world (we'll assume worlds with solid surfaces), you'd need to establish a co-ordinate system for each world. Again, drawing inspiration from terrestrial longitude/latitude co-ordinates, it would be a polar system, with the axis aligned to the planet's axis of rotation (assuming it has a stable rotation). Again, there needs to be a choice of "North", a choice of prime meridian, and choice of handedness. On Earth, Grenwich was something of an arbitrary choice, chosen perhaps only because it was the site of an observatory. On a remote world, one might identify the site of a specific colony or a geographic feature and set the planet's prime meridian from that. As with plate tectonics on Earth, the exoplanet surface might be in motion, so whatever feature was used to set the prime meridian may gradually move away, so it would only serve as inspiration. |
6,686,290 | I'm looking for a way to serve a "Maintenance Mode" website from Amazon S3 or Azure Blob storage while I'm updating my website to a new version. I'd like to just flip DNS over to point to maint.mydomain.com (which would be a static site & return 503 http status). Is this possible to do with either of these, or would I need to create a traditional website to host this?
I can get S3 to serve a website, but it always shows HTTP status 200. Any ideas? | 2011/07/13 | [
"https://Stackoverflow.com/questions/6686290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/226060/"
] | It seems like you can also make amazon s3 to return 404s for your website during maintenance by specifying incorrect path to the index file and providing correct path for the error page which will be always returned when you hit any url at the endpoint (including root). | You're approaching this wrong.
You should run multiple instances, a staging and a production. Both staging and production are "production" code, but staging is used to actually deploy your changes. Once your staging is up and running you flip the staging and production instances (in Azure this is called a VIP swap). This allows the user to experience an "instant" upgrade (in quotes as there is still some fractional downtime and you can get errors in cases where the user comes in at the exact moment of the switch). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.