qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
27,332,170 |
Everything seemed to be running okay (for several days), but I ran into an issue only once and having a really hard time to reproduce the problem.
"Comparison method violates its general contract!" was thrown and completely caught me off guard. I have the following:
```
public class CustomComparator implements Comparator<Chromosome> {
public int compare(Chromosome c1, Chromosome c2){
return c1.compareTo(c2);
}
}
```
My Chromosome class:
```
public class Chromosome implements Comparable<Chromosome>{
private double rank;
//bunch of methods...
@Override public int compareTo(Chromosome c){
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this.getRank() == c.getRank()) //getRank() simply returns a double value 'rank'
return EQUAL;
else if (this.getRank() < c.getRank())
return BEFORE;
else //i.e. (this.getRank() > c.getRank())
return AFTER;
}
```
I have an ArrayList and I used both Collections.sort(MyList) and Collections.sort(MyList, Collections.reverseOrder()). They're still working fine up till now. I just ran into that error only once out of 100's of run. Is there something wrong with this implementation?
|
2014/12/06
|
[
"https://Stackoverflow.com/questions/27332170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4222618/"
] |
Java 7 has changed the behavior of their sorting algorithms a bit. They now throw an Exception if a violation of the general contract for the `compareTo` method is detected. You can read about that contract's properties for example [here](https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html).
In general it could be violated for example in case that it would resolve to a < b and b < a. If this was detected before Java 7, it was just silently ignored. Now an Exception will be thrown.
If you want to use the old behaviour, you may use the following:
`System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");`
But I don't encourage you to do this. You should just change your implementation to the standard implementation of double comparison via [`Double.compare(a, b)`](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#compare%28double,%20double%29). This implementation correctly deals with infinity and NaN values for doubles.
Furthermore if your `Comparator` just delegates to the `compareTo` method, it can be discarded in general.
|
4,161,943 |
I am a beginner in js, and am puzzled by the following code:
```
Foo = function(arg) {
this.arg = arg;
};
Foo.prototype = {
init: function () {
var f = function () {
alert("current arg: " + this.arg); // am expecting "bar", got undefined
}
f();
}
};
var yo = Foo("bar");
yo.init();
```
I was expected to get "current arg: bar", but got "current arg: undefined". I noticed that by copying this.arg into a "normal" variable first, and refering this variable in the closure works:
```
Foo.prototype = {
init: function () {
var yo = this.arg;
var f = function () {
alert("current arg: " + yo); }
f();
}
};
```
Am I doing something wrong, got wrong expectations, or does it fall into one of the js WTF ?
|
2010/11/12
|
[
"https://Stackoverflow.com/questions/4161943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11465/"
] |
It depends on how the function was invoked.
If invoked with keyword `new` then `this` refers to the object being constructed (which will be implicitly returned at the end of the function).
If invoked as a normal function, `this` refers to the global `window` object.
Example:
```
// Constructor for Foo,
// (invoke with keyword new!)
function Foo()
{
this.name = "Foo" ;
}
myFoo = new Foo() ;
alert( 'myFoo ' + myFoo.name + '\n' + 'window: ' + window.name ) ; // window.name will be empty
// now if we invoke Foo() WITHOUT keyword NEW
// then all references to `this` inside the
// function Foo will be to the
// __global window object__, i.e. the global window
// object will get clobbered with new properties it shouldn't
// have! (.name!)
Foo() ; // incorrect invokation style!
alert( 'myFoo ' + myFoo.name + '\n' + 'window: ' + window.name ) ;
```
JavaScript doesn't have "constructors" per se, the only way JavaScript knows that your `function` is actually a "constructor" is invokation style (namely you using keyword `new` whenever you invoke it)
|
615,875 |
Good afternoon,
I would like to know how to colour the nodes A and Y in another colour (grey for example) without changing the colour of the other two nodes.
Best regards.
```
\begin{figure}[h]
\centering
\begin{tikzpicture}[
node distance=1cm and 1cm,
mynode/.style={draw,circle,text width=0.5cm,align=center}
]
\node[mynode] (z) {A};
\node[mynode,right=of z] (x) {Y};
\node[mynode,left=of z] (y) {$U_A$};
\node[mynode,right=of x] (w) {$U_Y$};
\path (x) edge[latex-] (z);
\path (y) edge[latex-] (z);
\path (x) edge[latex-] (w);
\end{tikzpicture}
\caption{Graph.}
\end{figure}
```
|
2021/09/18
|
[
"https://tex.stackexchange.com/questions/615875",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/252116/"
] |
Replace `\pgfcalendarweekdayshortname` by `\myweekday` and define the latter in the preamble as
```
\newcommand\myweekday[1]{\ifcase#1M\or T\or W\or T\or F\or S\or S\fi}
```
[](https://i.stack.imgur.com/Uh52X.png)
```
\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{calendar}
\newcommand\myweekday[1]{\ifcase#1M\or T\or W\or T\or F\or S\or S\fi}
\begin{document}
\begin{tikzpicture}
\calendar[dates=2021-01-01 to 2021-01-last,
day list downward,
day code={
\node[anchor = east]{\tikzdaytext};
\draw node[anchor = west, gray]{\myweekday{\pgfcalendarcurrentweekday}};
},
execute after day scope={
\ifdate{Sunday}{\pgftransformyshift{1em}}{}},
]
if(weekend) [shape=coordinate]; % (1)
\end{tikzpicture}
\end{document}
```
|
40,886,904 |
I've tried to build <https://github.com/DEVSENSE/Phalanger>, but after the build process it shows build errors. I tried VS 2015, maybe there it just a question of a wrong version?
[](https://i.stack.imgur.com/Q6qXv.png)
|
2016/11/30
|
[
"https://Stackoverflow.com/questions/40886904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3941733/"
] |
No. They are completely different.
`test in [1,2,3]` checks if there is a property **named** `2` in the object. There is, it has the value `3`.
`[1,2,3].indexOf(test)` gets the first property with the **value** `2` (which is in the property named `1`)
>
> suggest that you can't do in on an array, only on an object
>
>
>
Arrays are objects. (A subclass if we want to use classical OO terminally, which doesn't really fit for a prototypal language like JS, but it gets the point across).
The array `[1, 2, 3]` is *like* an object `{ "0": 1, "1": 2, "2": 3 }` (but inherits a bunch of other properties from the Array constructor).
|
35,254,997 |
How to implement a button above the keyboard? (For example: "Notes" app, or
[like this](http://i.stack.imgur.com/hrLlq.gif)
|
2016/02/07
|
[
"https://Stackoverflow.com/questions/35254997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4478196/"
] |
MKaro's solution works! I'll attach the Swift 3 version for faster copy-paste.
**Swift 3:**
```
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
keyboardToolbar.isTranslucent = false
keyboardToolbar.barTintColor = UIColor.white
let addButton = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(someFunction)
)
addButton.tintColor = UIColor.black
keyboardToolbar.items = [addButton]
textView.inputAccessoryView = keyboardToolbar
```
|
72,144,828 |
```
class Dashboard extends Component {
constructor(props) {
super(props)
this.state = {
assetList: [],
assetList1: [];
}
}
componentDidMount = async () => {
const web3 = window.web3
const LandData=Land.networks[networkId]
if (LandData) {
const landList = new web3.eth.Contract(Land.abi, LandData.address)
this.setState({ landList })
}
}
...
}
```
In this code the state for `landlist` is not defines in `constructor` but `setState` is used. If I have to convert the code to a function component, what will be the equivalent code?
|
2022/05/06
|
[
"https://Stackoverflow.com/questions/72144828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19055006/"
] |
In React class components, there existed a single `state` object and you could update it with any properties you needed. State in React function components functions a little differently.
React function components use the `useState` hook to explicitly declare a state variable and updater function.
You can use a single state, and in this case the functionality would be pretty similar, keeping in mind though that unlike the `this.setState` of class components, the `useState`
Example:
```
const Dashboard = () => {
const [state, setState] = React.useState({
assetList: [],
assetList1: []
});
useEffect(() => {
const web3 = window.web3;
const LandData = Land.networks[networkId];
if (LandData) {
const landList = new web3.eth.Contract(Land.abi, LandData.address);
setState(prevState => ({
...prevState,
landList,
}));
}
}, []);
return (
...
);
};
```
With the `useState` hook, however, you aren't limited to a single state object, you can declare as many state variables necessary for your code to function properly. In fact it is recommended to split your state out into the discrete chunks of related state.
Example:
```
const Dashboard = () => {
const [assetLists, setAssetLists] = React.useState({
assetList: [],
assetList1: []
});
const [landList, setLandList] = React.useState([]);
useEffect(() => {
const web3 = window.web3;
const LandData = Land.networks[networkId];
if (LandData) {
const landList = new web3.eth.Contract(Land.abi, LandData.address);
setLandList(landList);
}
}, []);
return (
...
);
};
```
|
66,386,300 |
I am doing below steps , and in the process I am losing the transformed data though I am using cache() on the data .
**STEP -1 : READ DATA FROM CASSANDRA:**
```
data = spark_session.read \
.format('org.apache.spark.sql.cassandra') \
.options(table=table, keyspace=keyspace) \
.load()
data_cached = data.cache()
```
**STEP-2: READ DATA FROM AWS S3 BUCKET LET'S SAY S3\_data\_path**
```
s3_full_df = spark.read.format("parquet").load(S3_data_path)
full_data = s3_full_df .cache()
full_data.show(n=1, truncate=False)
```
**STEP-3: Finding difference between cassandra data from step-1 and s3 parquet file data from step -2**
```
diff_data = data_cached.subtract(full_data)
diff_data_cached = diff_data .cache()
diff_data_cached.count()
```
**STEP-4: writing step-3 data diff\_data\_cached into aws s3 bucket , let's say s3\_diff\_path**
```
diff_data_cached.write.parquet(inc_path)
```
**STEP-5: IMP STEP : overwriting cassandra data from step -1 to aws s3 path S3\_data\_path ( in STEP-2)**
```
data_cached.write.parquet(full_path, mode="overwrite")
```
**STEP -6 : writing diff\_data\_cached in database . This step has issue .**
diff\_data\_cached is available in STEP-3 is written to data base but after STEP-5 diff\_data\_cached is empty , My assumption is as in STEP-5 , data is overwritten with STEP-1 data and hence there is no difference between two data-frames, but since I have run cache() operation on diff\_data\_cached and then have run count() to load data in memory so my expectation is diff\_data\_cached should be available in memory for STEP-6 , rather than spark lazily evaluates.
|
2021/02/26
|
[
"https://Stackoverflow.com/questions/66386300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8236029/"
] |
**1. General approach: You can create a matrix in base R:**
```
## vectors with same length
obs_date <- c(1,2,3,1,2)
yields <- c(0.05,0.06,0.01,0.02,0.04)
maturities <- c(3,3,4,5,3)
# creating matrix
m <- matrix(c(obs_date, yields, maturities), ncol = 3)
# print matrix
print(m)
# print class of m
class(m)
```
**2. How to create a matrix with vectors of different length:**
```
## vectors of different length
obs_date_1 <- c(1,2,3,1)
yields_1 <- c(0.05,0.06,0.01,0.02,0.04)
maturities_1 <- c(3,3,4)
# create a list of vectors
listofvectors <- list(obs_date_1, yields_1, maturities_1)
# create the matrix
matrixofdiffvec_length <- sapply(listofvectors, '[', seq(max(sapply(listofvectors, length))))
matrixofdiffvec_length
class(matrixofdiffvec_length)
```
|
5,988,457 |
I'm compiling a trivial C++ file `Temp.cpp`:
```
#include <string>
int main() { std::wstring s; }
```
With the command line:
```
cl.exe /MD /Iinc\api\crt\stl60 /Iinc\crt /Iinc\api C:\Temp.cpp
/LibPath:lib\wxp\i386 /LibPath:lib\crt\i386
/link /LibPath:lib\wxp\i386 /LibPath:lib\crt\i386
```
in the WDK 7.1 Windows XP Free Build Environment.
I get link errors like (LNK2019):
```
unresolved external symbol "__declspec(dllimport) public: __thiscall
std::basic_string<wchar_t,struct std::char_traits<wchar_t>,
class std::allocator<wchar_t> >::~basic_string<wchar_t,
struct std::char_traits<wchar_t>,class std::allocator<wchar_t> >(void)"
(__imp_??1?$basic_string@_WU?$char_traits@_W@std@@V?$allocator
@_W@2@@std@@QAE@XZ) referenced in function _main
```
If I use `string` instead of `wstring`, it works.
What's the cause of the problem? How can I use `wchar_t`-based types in my source file?
|
2011/05/13
|
[
"https://Stackoverflow.com/questions/5988457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/541686/"
] |
The likely fix would be to set /Zc:wchar\_t- to turn off wchar\_t as an intrinsic type. STL6 doesn't have great support for /Zc:wchar\_t which is the default since at least VC7.1, perhaps earlier.
Meta: Please don't use the STL60 version of STL. This version from 1998 lacks a large number of bug fixes, performance improvements and standards-conformance work that you can find in a modern STL. If you are using the VC compiler toolchain the free VC++ express includes STL.
Martyn
|
1,061,449 |
I have a directory containing thousands of files with names
```
t_00xx_000xxx.png
```
I want to change their names to `00xx_000xxx_t.png`
so take the prefix and put it as a postfix, can this be done in only one command
|
2018/08/01
|
[
"https://askubuntu.com/questions/1061449",
"https://askubuntu.com",
"https://askubuntu.com/users/837988/"
] |
This is possible with the [`rename`](http://manpages.ubuntu.com/manpages/bionic/en/man1/prename.1p.html) command:
First check what *would* be done (by suppliying `-n`). If it looks good, drop the `-n` and run again:
```
rename -n 's/t_(.+)\.png$/$1_t.png/' *.png # check only
rename 's/t_(.+)\.png$/$1_t.png/' *.png # actually rename the files
```
|
17,618,051 |
My setup is as follows: Windows 7, XAMPP with Apache and PHP enabled I have a PHP script in which I call an external program to do run a conversion. This external program is an EXE file, which requires 3 attributes:
* The source file
* The destination file
* Additional flags (conversion type etc)
When I use the command line tool built into XAMPP to execute my script, everything works fine. But when I use the exec() function in my PHP script, no output file is created. I'm pretty sure the conversion is actually happening (it takes about 5 seconds, about the same time it takes to run the PHP script).
I think it's a permissions thing, so I already moved the EXE file to the same folder as my PHP file and adjusted the permissions of the entire folder (I granted all permissions to all users). I also disabled the Windows UAC and tried to put the command in a BAT file. The file just is not created.
Any help or tips would be greatly appreciated!
My PHP code is as follows:
```
exec('c:\converter.exe c:\src.txt c:\dst.txt -f', $output);
print_r($output);
```
When I print out $output, the array turns out to be empty. When I put the exact same command in Command Prompt, the code works like a charm (no syntax errors). I use absolute paths as well.
|
2013/07/12
|
[
"https://Stackoverflow.com/questions/17618051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2029689/"
] |
The default driver for Capybara is Rack::Test. Your page probably requires javacript which means that Capybara's default driver is not rendering everything correctly. Just set `Capybara.default_driver = :selenium`. This way the javascript is run correctly.
See also [link](http://www.opinionatedprogrammer.com/2011/02/capybara-and-selenium-with-rspec-and-rails-3/), which explains how to change the driver for only one testcase and not the whole test suite. Note that if you use selenium as the driver the method `save_and_open_page` probably won't work.
|
6,604,814 |
Well, I've finally decided that I'm not crazy. So, that leaves DataMapper.
Here's what I'm doing. I have a model Msrun which `has 1` Metric.
```
tmp = Msrun.first_or_create # I'll skip the boring details
tmp.metric = Metric.first_or_create( {msrun_id: tmp.id}, {metric_input_file: @metricsfile} )
p tmp.metric # => #<Metric @metric_input_file=nil @msrun_id=1>
tmp.metric.metric_input_file = @metricsfile
p tmp.metric # => #<Metric @metric_input_file=#<Pathname:/home/ryanmt/Dropbox/coding/rails/metrics_site/spec/tfiles/single_metric.txt> @msrun_id=1>
```
So, why doesn't this work? I'm reading <http://datamapper.org/docs/create_and_destroy> and doing what it shows working. This has been terribly arduous. Thanks for any help.
Update:
I still can't figure out what is going on, but to prove I'm not insane...
```
puts Metric.all # => []
tmp.metric = Metric.first_or_create( {msrun_id: tmp.id}, {metric_input_file: @metricsfile} )
puts Metric.all # => [] #??????????????
tmp.metric.metric_input_file = @metricsfile
p tmp.metric # => #<Metric @metric_input_file=#<Pathname:/home/ryanmt/Dropbox/coding/rails/metrics_site/spec/tfiles/single_metric.txt> @msrun_id=1>
tmp.metric.save
puts Metric.all # => [#<Metric @metric_input_file=#<Pathname:/home/ryanmt/Dropbox/coding/rails/metrics_site/spec/tfiles/single_metric.txt> @msrun_id=1>]
```
So, not only is `first_or_create` not delivering on the behavior I expect by reading the source
```
def first_or_create(conditions = {}, attributes = {})
first(conditions) || create(conditions.merge(attributes))
end
```
but it is also not even creating.
|
2011/07/07
|
[
"https://Stackoverflow.com/questions/6604814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/654245/"
] |
I'm probably missing something here (more of those boring details might help) but if the metric exists, it's metric\_input\_file shouldn't be updated, i.e., it's only set when new. If you're after updating then you can do
```
.first_or_create(msrun_id: tmp.id).update(metric_input_file: @metricsfile)
```
Or if not hitting the database twice is relevant, then
```
m = Metric.first_or_new(msrun_id: tmp.id)
[set..save..assign]
```
But if it's not being set on *new models*, I don't see what would cause that from the code posted so far, more..?
[UPDATED]
Based on your new code, I'd say this is "a classic case" of a false DM save. I usually add the following line to an initialization section, e.g., application.rb in Rails.
```
DataMapper::Model.raise_on_save_failure = true
```
Unfortunately, the exception raised never tells you why (there's a special place in hell for that choice, right next to people who talk in theaters.) But it's typically one of:
* a slightly incorrect association definition
* a has/belongs\_to that isn't "required: false" and isn't set
* putting the wrong datatype into a field, e.g., a string into a decimal
* a validation failing
If you want to post your model definitions, the problem may be spottable there.
|
38,620,944 |
I have a function onload which is just a simple console.log
```
<script>
onload = function(){
console.log('Hello');
}
</script>
```
I call it in my body like so
```
<body window.onload="onload();">
```
which after the page loads correctly prints
```
Hello
```
But I am trying to make it so when I click on my it also calls this function so I tried
```
<th onclick()="onload();">
```
Doing so results in
```
Uncaught TypeError: onload is not a function
```
I thought I might add that I generate my html file using a jade template so the table is dynamically loaded in (not sure if that matters)
Thank you
|
2016/07/27
|
[
"https://Stackoverflow.com/questions/38620944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770808/"
] |
solve it like this
```
import { Http, Response } from '@angular/http';
export class LoginService {
constructor(private http: Http) {
}
}
```
or use it like this
```
public constructor(@Inject(Http) private http: Http) {}
```
|
423 |
Somebody answered this question instead of the question [here](https://mathoverflow.net/questions/410/what-is-an-example-of-a-smooth-variety-over-a-finite-field-fp-which-does-not-emb), so I am asking this with the hope that they will cut and paste their solution.
|
2009/10/13
|
[
"https://mathoverflow.net/questions/423",
"https://mathoverflow.net",
"https://mathoverflow.net/users/2/"
] |
Examples are also in my paper "Murphy's Law in Algebraic Geometry", which you can get from my [preprints page](http://math.stanford.edu/~vakil/preprints.html)
Here is a short (not quite complete) description of a construction, with two explanations of why it works. I hope I am remembering this correctly!
In characteristic $>2$, consider the blow up of $\mathbf{P}^2$ at the $\mathbf{F}\_p$-valued points of the plane. Take a Galois cover of this surface, with Galois group $(\mathbf{Z}/2)^3$, branched only over the proper transform of the lines, and the transform of another high degree curve with no $\mathbf{F}\_p$-points.
Then you can check that this surface violates the numerical constraints of the Bogomolov-Miyaoka-Yau inequality, which holds in characteristic zero; hence it doesn't lift. (This is in a paper by Rob Easton.) Alternatively, show that deformations of this surface must always preserve that Galois cover structure, which in turn must preserve the data of the branch locus back in $\mathbf{P}^2$, meaning that any deformation must preserve the data of those $p^2+p+1$ lines meeting $p+1$ to a point, which forces you to live over $\mathbf{Z}/p$.
The two papers mentioned above give more exotic behavior too (of different sorts in the two papers), e.g. you an find a surface that lifts to $\mathbf{Z}/p^{10}$ but still not to $\mathbf{Z}\_p$.
|
14,261,656 |
I'm using `@Html.Action()` to render a child action within my view.
The `_ViewStart.cshtml` file specifies that all views should use a particular layout like this:
```
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
```
Problem is, that layout is getting applied to my child action too, so the final page ends up with two headers and two footers. How do I prevent this?
|
2013/01/10
|
[
"https://Stackoverflow.com/questions/14261656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164923/"
] |
2 possibilities:
1. `return PartialView()` from the corresponding controller action instead of a `return View()`
2. Blank out the layout in the view itself
```
@{
Layout = null;
}
```
|
18,248,384 |
Anyone point out the issue?
Keep getting "The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."
```
public IEnumerable<Appointment> FindAllAppointmentsWithReminders()
{
DateTime reminderDate = DateTime.Today.Date;
IEnumerable<Appointment> apps = RepositorySet
.OfType<Appointment>()
.Include("Client")
.Where(c => EntityFunctions.TruncateTime(c.Client.Reminder.Date) == reminderDate.Date
&& reminderDate.Date > EntityFunctions.TruncateTime(c.StartTime.Date));
return apps;
}
```
|
2013/08/15
|
[
"https://Stackoverflow.com/questions/18248384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1401620/"
] |
Remove all the `.Date` from your method but this:
```
DateTime reminderDate = DateTime.Today.Date;
```
EntityFramework doesn't support the `.Date` property of `Datetime`. For this reason there is the pseudo-function `EntityFunctions.TruncateTime`, and for the `reminderDate` you already remove the time in the `DateTime reminderDate = DateTime.Today.Date`.
```
public IEnumerable<Appointment> FindAllAppointmentsWithReminders()
{
DateTime reminderDate = DateTime.Today.Date;
IEnumerable<Appointment> apps = RepositorySet
.OfType<Appointment>()
.Include("Client")
.Where(c => EntityFunctions.TruncateTime(c.Client.Reminder) == reminderDate
&& reminderDate > EntityFunctions.TruncateTime(c.StartTime));
return apps;
}
```
|
33,182 |
I'm currently getting to grips with the new (3.1) ArcGIS JavaScript API and how it bundles Dojo and relies on Dojo's Asynchronous Module Definition (AMD) approach.
I'm familiar with AMD and recently completed a project using Require, Backbone, and OpenLayers in combination - overall a very pleasant experience.
However I'm worried by
* how tightly-coupled Dojo is with the ArcGIS JavaScript API,
* that trying to use Require instead of Dojo AMD throws an exception, and
* that Dojo AMD doesn't seem to have the same user-base and momentum as Require, making it difficult to research / resolve problems without hitting the forums
My main concern is that I will write an ArcGIS JavaScript API application and not be able to build / package it into a single / small number of scripts. This will leave me with an application making 100+ HTTP requests at startup for all of the modules it depends on.
I've seen [this article](http://odoe.net/blog/?p=307) covering 3.0 but it doesn't mention the build process and I believe 3.0 is quite different. I've also seen [this piece](http://geospatialscott.blogspot.ca/2011/06/using-dojo-build-system-to-speed-up.html) on building / packaging an application that uses the ArcGIS JavaScript API but the comments suggest this is pre-Dojo 1.7 AMD.
Have ESRI really only half implemented the AMD approach, and in a way that will actually make my application slower? Why can I not find ESRI documentation on building / packaging a JavaScript API-based application?
Any thoughts or experience here would be much appreciated.
**EDIT** Based on the answers so far it seems that no, ESRI hasn't provided any information on building your Dojo application after inflating the number of scripts involved. It seems the only useful information available is from non-official sources and slightly outdated (enough to cause problems). This leads to me wonder why more people aren't vocal about the API's new improvements / deficiencies
* am I being too critical / demanding in expecting some more information here?
* is no one using the latest version of the API?
* should I use an older version of the API that doesn't depend on AMD?
|
2012/09/11
|
[
"https://gis.stackexchange.com/questions/33182",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/2788/"
] |
Since esri does not ship source code you cannot build one layer package with all your classes. You will have to push out the esri api locally or using the CDN and then pull down your layer file. So you will have 2 and then the extra's that esri forgot to bundle or chose not to.
We've put together a discard layer so that you don't duplicate packages within your own built layer file and the esri layer file. This is pre AMD but as you've noticed, AMD is only partially implemented in the current version of the API.
[This blog post](http://geospatialscott.blogspot.com/2011/06/using-dojo-build-system-to-speed-up.html) will outline everything you need to know and the concept will apply for newer versions.
the freenode irc chatroom #dojo has great realtime information if you dont' want to wait around for the forum.
|
14,787,571 |
I found this post on [Bootstrap Tutorial for Blog Design](http://www.9lessons.info/2012/03/bootstrap-tutorial-for-blog-design.html).
I am planning to use it for one of my project for the responsive layout that it provides.
I have found an issue in the page hosted for [demo](http://demos.9lessons.info/bootstrap/index.html).
have attached a screenshot 
The first post in the page "Facebook Timeline Design using JQuery and CSS" is falling outside the border of the background [Have marked it in blue].[not the expected result]
The rest of the posts in the page falls inside the border which is the expected behaviour[have marked it in green].
Is there any way I can fix the issue of the first post falling outside the background border. I have tested this in IE,firefox and chrome with the same results.
have created a jsbin page [here](http://jsbin.com/anuvej/2/edit)
|
2013/02/09
|
[
"https://Stackoverflow.com/questions/14787571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/328911/"
] |
You can get it resolved by using jquery selector
```
$('.row > [class*="span"]:first-child').css({"padding-left":"20px"});
```
|
29,424,655 |
I have a directive and now I want to send same data to other controller's methods and this controller is totally independent of this directive. this other controller is actually resides out the current directory.
How can I do this in angularjs?
|
2015/04/03
|
[
"https://Stackoverflow.com/questions/29424655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2561567/"
] |
Create an angular service and inject in both the controllers. Update a variable in that service from controller 1 and retrieve in controller 2. Something like this -
```
myApp.factory('myFactory', function () {
// declare and store the value in a local variable here
var prop = '';
return {
getProperty: function () {
return prop;
},
setProperty: function(value) {
prop = value;
}
};
});
function Ctrl1($scope, myFactory) {
myFactory.setProperty('myValue');
}
function Ctrl2($scope, myFactory) {
val = myFactory.getProperty();
}
```
An angular service is a Singleton, so it maintains the state throughout the code.
|
67,510,810 |
I have the query below. How come with the invoice\_dt set between 1/1/2021 - 5/31/2021... the output display ALL date ranges. How would I set it to look for dups based on pay\_cte within the date range?
```
with pay_cte( vendor_id,invoice_id, pay_amt,pay_cnt ) as (
select vendor_id,invoice_id, pay_amt,count(*)
from ps_voucher
where invoice_dt between '01-Jan-2021' and '31-May-2021'
group by vendor_id,invoice_id, pay_amt
having count(*)>1)
select t.vendor_id, t.voucher_id,t.INVOICE_ID,t.gross_amt, t.INVOICE_DT
from ps_voucher t
join pay_cte p on t.vendor_id=p.vendor_id and t.invoice_id = p.invoice_id
and t.gross_amt=p.pay_amt
```
|
2021/05/12
|
[
"https://Stackoverflow.com/questions/67510810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12081754/"
] |
The reason your query is returning all dates is due to the fact that your actual select statement that uses the `WITH` clause does not have any filtering for dates. It is likely that your `ps_voucher` table has records in it that have `INVOICE_DT` values that are out of the range of dates about which you are curious.
There are two ways you can filter results; the first is in the (inner) `JOIN` clause, and the second is by adding a `WHERE` clause in the query.
Option 1:
```
with pay_cte( vendor_id,invoice_id, pay_amt,pay_cnt ) as (
select
vendor_id,
invoice_id,
pay_amt,
count(*)
from ps_voucher
where
invoice_dt between '01-Jan-2021' and '31-May-2021'
group by
vendor_id,
invoice_id,
pay_amt
having
count(*)>1
)
select
t.vendor_id,
t.voucher_id,
t.INVOICE_ID,
t.gross_amt,
t.INVOICE_DT
from ps_voucher t
join pay_cte p
on t.vendor_id = p.vendor_id
and t.invoice_id = p.invoice_id
and t.gross_amt=p.pay_amt
and t.INVOICE_DT between '01-Jan-2021' and '31-May-2021'
```
Option 2:
```
with pay_cte( vendor_id,invoice_id, pay_amt,pay_cnt ) as (
select
vendor_id,
invoice_id,
pay_amt,
count(*)
from ps_voucher
where
invoice_dt between '01-Jan-2021' and '31-May-2021'
group by
vendor_id,
invoice_id,
pay_amt
having
count(*)>1
)
select
t.vendor_id,
t.voucher_id,
t.INVOICE_ID,
t.gross_amt,
t.INVOICE_DT
from ps_voucher t
join pay_cte p
on t.vendor_id = p.vendor_id
and t.invoice_id = p.invoice_id
and t.gross_amt=p.pay_amt
where
t.INVOICE_DT between '01-Jan-2021' and '31-May-2021'
```
|
19,235,348 |
I have the following line of code, which conditionally redirects that I would like to include in my Rails controller and execute only in the case that the request is an HTML request.
I would like to skip this logic in the case that the request is JSON. How does one do this in conjunction with the `respond_to :html, :json` method, declared before all controller actions?
```
redirect_to some_controller and return if @pages.empty?
```
|
2013/10/07
|
[
"https://Stackoverflow.com/questions/19235348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165448/"
] |
You want something like this:
```
class SomeController < ApplicationController
def index
@pages = Pages.find(:all)
respond_to do |format|
format.html do
redirect_to other_controller and return if @pages.empty
# ... other logic ...
end
format.json { render json: @pages }
end
end
end
```
|
61,716,602 |
I have a button that triggers my view state. As I have now added a network call, I would like my view model to replace the @State with its @Publihed variable to perform the same changes.
How to use my @Published in the place of my @State variable?
So this is my SwiftUI view:
```
struct ContentView: View {
@ObservedObject var viewModel = OnboardingViewModel()
// This is the value I want to use as @Publisher
@State var isLoggedIn = false
var body: some View {
ZStack {
Button(action: {
// Before my @State was here
// self.isLoggedIn = true
self.viewModel.login()
}) {
Text("Log in")
}
if isLoggedIn {
TutorialView()
}
}
}
}
```
And this is my model:
```
final class OnboardingViewModel: ObservableObject {
@Published var isLoggedIn = false
private var subscriptions = Set<AnyCancellable>()
func demoLogin() {
AuthRequest.shared.login()
.sink(
receiveCompletion: { print($0) },
receiveValue: {
// My credentials
print("Login: \($0.login)\nToken: \($0.token)")
DispatchQueue.main.async {
// Once I am logged in, I want this
// value to change my view.
self.isLoggedIn = true } })
.store(in: &subscriptions)
}
}
```
|
2020/05/10
|
[
"https://Stackoverflow.com/questions/61716602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10408494/"
] |
Remove state and use view model member directly, as below
```
struct ContentView: View {
@ObservedObject var viewModel = OnboardingViewModel()
var body: some View {
ZStack {
Button(action: {
self.viewModel.demoLogin()
}) {
Text("Log in")
}
if viewModel.isLoggedIn { // << here !!
TutorialView()
}
}
}
}
```
|
6,248,351 |
If i have the following structure in an MVC site.
```
Areas
+ Documents
+ Controllers
+ Models
+ Views
+ Shared
+ icons
icon.png
```
I am trying to use `img src='@url.Content("~/Areas/Documents/Views/Shared/icons/icon.png")'`/>
Why is this image unavailable?
Is there another path to use? Weird that I can browse to the file path in firefox, but as soon as I click on the image it errors with resource unavailable.
Do images have to go into the content directory?
Regards
Craig.
|
2011/06/06
|
[
"https://Stackoverflow.com/questions/6248351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231821/"
] |
This works for me
img src='@Url.Content("../../Content/Images/6.jpg")' alt="" style="width: 100px; height: 100px" />
Yet my problem is getting the corresponding image to the product I am trying to show, no luck so far, I have tried hard coding too.
|
18,414,075 |
This question is chiefly about LINQ and possibly covariance.
Two of my Entities implement the **IDatedItem** interface. I'd like to union, then sort these, for enumerating as a single list. I must retain entity-specific properties at enumeration-time.
To clarify by example, one approach I tried was:
```
Context.Table1.Cast<IDatedItem>().
Union(Context.Table2.Cast<IDatedItem>()).
SortBy(i => i.Date).
ForEach(u => CustomRenderSelector(u, u is Table1));
```
In trying to do this various ways, I've run into various errors.
* LINQ to Entities only supports casting EDM primitive or enumeration types.
* Unable to process the type '.IDatedItem[]', no known mapping to the value layer
* Unable to create a constant value of type 'IDatedItem'. Only primitive types
* etc.
The bigger picture:
* The IDatedItem interface shown here is a simplification of the actual shared properties.
* In practice, the tables are filtered before the union.
* The entity-specific properties will be rendered, in order, in a web page.
* In a parallel feature, they will be serialized to a JSON result hierarchy.
* I'd like to be able to perform LINQ aggregate operations on the results as well.
|
2013/08/24
|
[
"https://Stackoverflow.com/questions/18414075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608220/"
] |
This requires more space than a comment offers. On the other hand, this is not really an answer, because there is no satisfying answer, really.
For a `Union` to succeed, both collections must have the same type (or have intrinsic conversions to common types, that's what covariance is about).
So a first go at getting a correct Union could be:
```
Context.Table1.Select(t1 => new {
A = t1.PropA,
B = t1.PropB,
Date = t1.Date
})
.Union(
Context.Table1.Select(t2 => new {
A = t2.PropC,
B = t2.PropD,
Date = t2.Date
}))
.OrderBy(x => x.Date)
.ToList();
```
which projects both tables to the same anonymous type. Unfortunately, because of the anonymous type, you can't do `.Cast<IDatedItem>()`.
Therefore, the only way to get a `List<IDatedItem>` is to define a type that implements `IDatedItem` and project both tables to that type:
```
Context.Table1.Select(t1 => new DateItem {
A = t1.PropA,
B = t1.PropB,
Date = t1.Date
})
.Union(
Context.Table1.Select(t2 => new DateItem {
A = t2.PropC,
B = t2.PropD,
Date = t2.Date
}))
.OrderBy(item => item.Date)
.AsEnumerable()
.Cast<IDatedItem>()
```
Which (I think) is quite elaborate. But as long as EF doesn't support casting to interfaces in linq queries it's the way to go.
By the way, contrary to what I said in my comment, the sorting will be done in SQL. And you can use subsequent aggregate functions on the result.
|
4,553,304 |
`Qt` has a flexible and powerful layout mechanism to handle view of desktop application's windows.
But it is so flexible, that it nearly cannot be understood, when something goes wrong and needs fine tuning. And so powerful, that it can beat anyone in their tries to overwhelm Qt's opinion of how form should look.
So, can anyone explain, or provide articles, or source of Qt's positioning mechanisms?
I'm trying to force the `QLabel`, `QPushButton` and `QTableView`, marked by trailing underscores in their names, be two times higher than `QTextBrowser` having `verticalStretch = 1` below. How can I handle widget's height properly?
[.ui file of my form on google docs. Search '\_\_\_\_' in names, preview in QtDesigner](https://docs.google.com/leaf?id=0B60otNVdbWrrZjk2MGZmZjUtOTRkNy00Yjc3LTliZjMtOTJiMThmNzk1YTZh&hl=en)
|
2010/12/29
|
[
"https://Stackoverflow.com/questions/4553304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/286291/"
] |
Layouts are actually easy to understand "I think". :)
A simple explanation of layouts can be found in the QT book "**[C++ Gui programming with QT 2nd edition](https://web.archive.org/web/20090822161435/qt.nokia.com/developer/books/cpp-gui-programming-with-qt-4-2nd-edition/)**"
**What you should be aware of regarding layouts and their size policies**
* Most Qt widgets have a size policy. This size policy tells the system how the widget should stretch or shrink. It's got from the class QSizePolicy. A size policy has both vertical and horizontal components.
* Most widgets also have a size Hint. This size hint tells the system a widgets preferred size
* QSizePolicy has a stretch factor to allow widgets to grow at different rates
\*\*I am only familiar with 4 size policies\*\*
* fixed size policy - The size of the widget is fixed and it can't be stretched. It remains at its size hint.
* minimum size policy - The size hint is the smallest possible size of the widget, but it \_can still\_ grow bigger if necessary.
* Preferred size policy - the widget can shrink or grow bigger than its size hint.
* expanding size policy - the widget can shrink or grow bigger than its size hint :)
You may want to ask,
What is the difference between preferred and expanding?
\*\*Answer:\*\* Imagine a form with 2 widgets, one with preferred and another with expanding. Then any extra space will be given to the widget with the expanding policy. The widget with the preferred policy will remain at its size hint.
I recommend (WARNING: am not an expert :)) **you buy and read through** "**[C++ Gui programming with QT 2nd edition](https://web.archive.org/web/20090822161435/qt.nokia.com/developer/books/cpp-gui-programming-with-qt-4-2nd-edition/)**". I am currently reading it and it is making a lot of sense. Look at the images and see if they make some sense.
**Explaining size policies**

**A simple example**
This is a simple dialog with 2 buttons whose horizontal and vertical size policies are shown as are the horizontal and vertical stretch.

**Here is the preview at its smallest size.**

**Here is another preview at a larger size**

[EDITED: //added size hint example]
**WHY YOU SHOULD CARE ABOUT SIZEHINT**
You can see that every widget has a sizeHint which is vital because QT's layout system always respects the sizeHint. This is only a problem if the default size of the widget is not exactly what you want. The only way around this problem is to extend (subclass) the widget and reimplement its `sizeHint()` member function. An example is worth 1000 words. To save space, see my blog where there is an example project.
|
405,123 |
I know that Hamel bases have a couple of defects for the purposes of doing analysis in infinite dimensions:
(1) Every Hamel basis of a complete normed space must be uncountable.
(2) For every Hamel basis of a complete normed space, all but finitely many of the coordinate functionals are discontinuous.
I also know both (1) and (2) are false if completeness is dropped.
Here are my questions, which I have labeled A,B,C,D:
A. I don't see why (1) is a serious problem. An uncountable Hamel basis seems just as hard (or just as easy) to work with as a countable Hamel basis. After all, Hamel bases are about unique representation as *finite* linear combinations. What am I missing?
B. (2) seems like it could be inconvenient. But I don't have a concrete understanding of why. What does (2) stop you from doing? I see that it means the standard dual basis for the algebraic dual is not basis a for the continuous dual.
C. Is there something else that goes wrong with Hamel basis in infinite dimensional spaces? Something, perhaps, that is more obviously inconvenient?
D. Is there something that goes wrong with Hamel basis in *incomplete* infinite dimensional spaces?
**Edit:** Some commentators have pointed out that Hamel bases cannot be produced explicitly for the most important spaces. I was aware of that, and should have said so. Is there anything else for C, other than (1),(2), and the lack of explicitness?
|
2021/09/29
|
[
"https://mathoverflow.net/questions/405123",
"https://mathoverflow.net",
"https://mathoverflow.net/users/150527/"
] |
The following perhaps could be a comment, but I thought that maybe I should state it as an answer so it can get positive or negative feedback.
To my mind, whenever I have taught linear algebra in the past, I emphasises that the great power of having a basis B for a vector space V, to study a linear map T from V to some other vector space W it is enough to know what T does on the elements of B. More precisely: T is uniquely determined by its restriction to B; and any function $B \to W$ extends (uniquely) to a linear map $V \to W$.
To make use of this, we therefore want to have examples or results where we can actually specify the values of T on some given basis.
Now suppose you want to study continuous linear maps $V\to W$ between Banach spaces. Since you can never get your hands on a Hamel basis, there is no possibility of creating interesting/useful linear maps by starting with a function defined on that basis. More seriously: if one just works abstractly and says that any function on a Hamel basis extends uniquely to a linear map on the containing space, how would one be able to tell if the resulting linear map is continuous?
Another practical problems is that most of the time, Banach spaces come with extra structure or context: e.g. $L^p(\mu)$ spaces or $C(K)$-spaces. Discontinuous linear maps are just not going to see this structure.
I think that ultimately, the point is that in functional analysis we want to do more than prove results of the form "if such-and-such a map exists, then another kind of map exists". One actually wants to relate Banach spaces to each other: to understand which ones embed as closed subspaces of other ones; to study settings where every bounded linear map from one space to another is automatically (weakly) compact; and so on. Hamel bases will rarely tell us anything here, because they don't reflect or detect various continuity or compactness properties.
|
29,591,304 |
I am developing an android application where I need to detect the blinking of eyes. So far I have been able to detect the face and eyes using OpenCV. But now I need to check if the eyes are open or close. I read somewhere that one of the ways I can do that is by measuring the pixel intensities (grey levels). But it was not properly explained as in how to do that step by step. I am actually new to OpenCV. So can anyone please help me how can I do that. It is really very important.
Here is my onCameraFrame method:
```
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba = inputFrame.rgba();
mGray = inputFrame.gray();
if (mAbsoluteFaceSize == 0) {
int height = mGray.rows();
if (Math.round(height * mRelativeFaceSize) > 0) {
mAbsoluteFaceSize = Math.round(height * mRelativeFaceSize);
}
}
if (mZoomWindow == null || mZoomWindow2 == null)
CreateAuxiliaryMats();
MatOfRect faces = new MatOfRect();
if (mJavaDetector != null)
mJavaDetector.detectMultiScale(mGray, faces, 1.1, 2,
2, // TODO: objdetect.CV_HAAR_SCALE_IMAGE
new Size(mAbsoluteFaceSize, mAbsoluteFaceSize),
new Size());
Rect[] facesArray = faces.toArray();
for (int i = 0; i < facesArray.length; i++) {
Core.rectangle(mRgba, facesArray[i].tl(), facesArray[i].br(),
FACE_RECT_COLOR, 2);
xCenter = (facesArray[i].x + facesArray[i].width + facesArray[i].x) / 2;
yCenter = (facesArray[i].y + facesArray[i].y + facesArray[i].height) / 2;
Point center = new Point(xCenter, yCenter);
Rect r = facesArray[i];
// compute the eye area
Rect eyearea = new Rect(r.x + r.width / 20,
(int) (r.y + (r.height / 20)), r.width - 2 * r.width / 20,
(int) (r.height / 9.0));
// split it
Rect eyearea_right = new Rect(r.x + r.width / 6,
(int) (r.y + (r.height / 4)),
(r.width - 2 * r.width / 16) / 3, (int) (r.height / 4.0));
Rect eyearea_left = new Rect(r.x + r.width / 11
+ (r.width - 2 * r.width / 16) / 2,
(int) (r.y + (r.height / 4)),
(r.width - 2 * r.width / 16) / 3, (int) (r.height / 4.0));
// draw the area - mGray is working grayscale mat, if you want to
// see area in rgb preview, change mGray to mRgba
Core.rectangle(mRgba, eyearea_left.tl(), eyearea_left.br(),
new Scalar(255, 0, 0, 255), 2);
Core.rectangle(mRgba, eyearea_right.tl(), eyearea_right.br(),
new Scalar(255, 0, 0, 255), 2);
if (learn_frames < 5) {
teplateR = get_template(mJavaDetectorEye, eyearea_right, 24);
teplateL = get_template(mJavaDetectorEye, eyearea_left, 24);
learn_frames++;
} else {
// Learning finished, use the new templates for template
// matching
match_eye(eyearea_right, teplateR, method);
match_eye(eyearea_left, teplateL, method);
}
}
return mRgba;
}
```
Thanks in advance.
|
2015/04/12
|
[
"https://Stackoverflow.com/questions/29591304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4216014/"
] |
I already worked on this problem and this algorithm. It's implemented (C++) here: <https://github.com/maz/blinking-angel> with algorithm here: <http://www.cs.bu.edu/techreports/pdf/2005-012-blink-detection.pdf> .
As far as I can remember:
* You get B&W current and 100ms ago frames
* You do new - old (see 154 in github code)
* You apply a threshold then a dilatation filter
* You compute contours
* If you have a `blob with area > to a threshold` at the eye location, it means that user blinked eyes
Give a look at the `is_blink` function at line 316. In his case, he do `w * h of blob surrounding box > to a threshold`.
In fact it use difference between eye/skin color. In Github implementation, threshold > 5 is used.
|
9,609,672 |
Is it possible to edit the text within a cell in datatables. So that when the user double clicks on the cell it becomes editable ?
Thanks
|
2012/03/07
|
[
"https://Stackoverflow.com/questions/9609672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470184/"
] |
No. I've seen all three. Personally, I use
```
if (!str[0])
```
Using strlen is a waste of processor time and not safe unless you can guarantee the string is terminated.
|
12,088 |
Which book is more a beginner to learn to program in c++ (or GML) and more fun: "Game Maker 8 Cookbook" (available for pre-order), or "The Game Maker's Companion" ?
|
2011/05/09
|
[
"https://gamedev.stackexchange.com/questions/12088",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/7193/"
] |
I created a game in Game Maker long ago, and was frustrated with the lack of control over many of the game elements. They try to take the programming out of game making. So I'm afraid you won't find Game Maker to be much help if you're trying to learn C++, or really programming in general.
I would recommend going with [Beginning C++ Through Game Programming, Third Edition](http://rads.stackoverflow.com/amzn/click/1435457420) if you want to achieve your intended goal.
|
9,434,956 |
So my CoreData model has one entity for the time being. It has several attributes, for testing purpose I set these attributes in the applicationdidfinishlaunching method. As soon as I set an NSNumber (Integer 16 or float) attribute it gets a EXC\_BAD\_ACCESS exception.
The string attributes work and gets stored, I tested this with a fetch.
If I set the Integer 16 number to 0 it does not crash but I guess it's because it gets assigned nil then.
**Core data NSManagedObject created by xcode:**
```
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface ReminderSchedule : NSManagedObject
@property (nonatomic, retain) NSNumber * intervalSize;
@property (nonatomic, retain) NSNumber * intervalType;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * quantity;
@property (nonatomic, retain) NSDate * startDate;
@property (nonatomic, retain) NSNumber * unit;
@end
```
**Inside the applicationdidfinishlaunching method in the appdelegate**
```
ReminderSchedule *reminderSchedule;
reminderSchedule = [NSEntityDescription insertNewObjectForEntityForName:@"ReminderSchedule" inManagedObjectContext:self.managedObjectContext];
reminderSchedule.unit = 1; <==== EXC_BAD_ACCESS
reminderSchedule.quantity = 4.0f; <==== EXC_BAD_ACCESS
reminderSchedule.name = @"this works";
reminderSchedule.intervalType = 2; <==== EXC_BAD_ACCESS
reminderSchedule.intervalSize = 2; <==== EXC_BAD_ACCESS
[self.managedObjectContext save:nil]; //just for testing, never gets here
```
|
2012/02/24
|
[
"https://Stackoverflow.com/questions/9434956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/871561/"
] |
You are passing in an 'int' and not an NSNumber.
Try this:
```
reminderSchedule.unit = [NSNumber numberWithInt:1]; // this won't crash
```
You can also reformat your @property to NSInteger. This will allow you to pass in a straight integer.
|
567,409 |
Just finished developing a website for a client and I've uploaded it to their VPS, but we're having problems with php/wordpress writing to files and folders. I haven't had a problem like this in many years because I'm used to having suhosin installed. I can chmod to 777, but I believe that is a security risk? As far as I know the other option is to change the owner of the files/folders to the same user as apache (nobody). I tried to do that but I don't have permission.
So my questions are:
Is chmod 777 a security risk?
is getting the server admin to change the owner to match the apache user a good solution?
Or what is the best solution?
|
2014/01/15
|
[
"https://serverfault.com/questions/567409",
"https://serverfault.com",
"https://serverfault.com/users/134716/"
] |
I don't usually use ufw. I use iptables directly.
Ubuntu usually gets updates using http protocol. So, you need to have outbound HTTP port open. If you want to restrict your rules on specific hosts, you need to figure out the Ubuntu repositories IPs `/etc/apt/sources.list`.
A better solution is to redirect HTTP traffic to web proxy and allow only specific domains/URLs. This is more accurate than resolving names to IPs to block them using firewall.
|
1,565,826 |
High School student here. I have been trying to derive a formula for an egg shaped curve. There are plenty of examples of egg shaped curves in the internet. Apparently it is a common topic.
I noticed Mr. Itou's approach for said curve as a section made by cutting a Pseudo-sphere by means of inclined plane. ([link](http://www.geocities.jp/nyjp07/index_egg_by_Itou_E.html), bottom of the page). I did not see the advantage in using a pseudo-sphere instead of a simpler surface.
I decided to do something similar, but starting with an hyperbolic funnel (Surface of revolution made by rotating a hyperbola in the ZY plane arround the Z-axis).
I wrote the equation, and after the rotation I obtained this parametric equation:
$$
\begin{cases} & x = t\sin s\\ & y = t\cos s \\ & z = 1/t \end{cases}
$$
After eliminating the parameters (using the pitagorean identity) I arrive at the following equation:
$x^{2}y^{2}+z^{2}y^{2}-1=0$
After solving for z, and plot for ${z \in \mathbb{R}:z>0}$ I got:
[Function plot](https://i.stack.imgur.com/MHWDJ.gif)
Now I would like to intersect the surface with an inclined plane to obtain my egg shaped curve. Then I would rotate the $P(x,y,z)$ to the XY plane to get a function $f(x)$.
I have no idea how to do this (obtaining the curve equation)
I tried equating both expressions (the surface and the plane) but when I plot it I get a strange curve. I tried to intersect it with the plane $z=3$ but instead of a circle I get something resembling a Gaussian curve reflected on the x-axis.
$x^{2}y^{2}+z^{2}y^{2}-z-1=0$
I have some knowledge in linear algebra and working with planes, lines in $R^{3}$.
I made the intersection by hand (technical drawing is pretty useful :) so I know that my original equations are right.
Any hints on how to get the function of the intersection?
|
2015/12/08
|
[
"https://math.stackexchange.com/questions/1565826",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/296974/"
] |
I don't see anything circular in comparing areas to get the inequality $\sin x < x < \tan x$ for $0 < x < \pi/2$. However we need to be very cautious in defining the symbols $\sin x, \tan x$ properly given $x$ a real number.
The approach based on areas goes like this. Using the concept of definite integrals it can be proven that a sector of a circle has an area. This does not require anything beyond the continuity of the function $\sqrt{1 - x^{2}}$ in interval $[0, 1]$. In particular justification of the area of a circle is not dependent on the definition of trigonometric functions and $\pi$.
Next consider a unit circle with origin $O$ as center and let $A$ be the point $(1, 0)$. Let $P$ be any point on the circle. For our purposes it is sufficient to consider $P$ to be in first quadrant. Let the area of sector $AOP$ be $y$ so that $y > 0$. Also let $x = 2y$ and then **by definition the point $P$ is $(\cos x, \sin x)$.** This is the usual definition of trigonometric functions as studied at the age of 15 years or so.
Note that some textbooks base the definition of $\sin x, \cos x$ on the basis of length of arc $AP$ which is $x$. The definition is equivalent to the one based on areas of sectors, but comparing areas of figures is simpler than comparing the length of arcs (at least in this context). Consider the tangent $AT$ to unit circle at point $A$ such that $OPT$ is a line segment. Also let $PB$ be a perpendicular to $OA$ and $B$ is the foot of this perpendicular. Now it is easy to show that $$\text {area of }\Delta AOP < \text{ area of sector }AOP < \text{ area of }\Delta AOT$$ (because each region is contained in the next). However it is very difficult to compare the length of arc $AP$ with the length of line segments $PB$ and $AT$ (because there is no containment here).
The above inequality leads to $$\sin x < x < \tan x$$ from which we get $\sin x \to 0$ as $x \to 0$ and then $\cos x = \sqrt{1 - \sin^{2}x} \to 1$. Further the inequality is equivalent to $$\cos x < \frac{\sin x}{x} < 1$$ and hence $(\sin x)/x \to 1$ as $x \to 0$.
---
**Update**: It appears from OP's comments that the relation between length of an arc of a circle and area of corresponding sector is something which can't be proven without using any analytic properties of circular functions. However this is not the case.
Let $P = (a, b)$ be a point on unit circle $x^{2} + y^{2} = 1$ and let $A = (1, 0)$. For simplicity let's consider $P$ in first quadrant so that $a, b$ are positive. Then the length of arc $AP$ is given by $$L = \int\_{a}^{1}\sqrt{1 + y'^{2}}\,dx = \int\_{a}^{1}\frac{dx}{\sqrt{1 - x^{2}}}$$ The area of the sector $AOP$ is given by $$A = \frac{ab}{2} + \int\_{a}^{1}\sqrt{1 - x^{2}}\,dx$$ We need to prove that $L = 2A$. We will do this using the fact that $b = \sqrt{1 - a^{2}}$ and using integration by parts.
We have
\begin{align}
\int\sqrt{1 - x^{2}}\,dx &= x\sqrt{1 - x^{2}} - \int x\cdot\frac{-x}{\sqrt{1 - x^{2}}}\,dx\notag\\
&= x\sqrt{1 - x^{2}} - \int \frac{1 - x^{2} - 1}{\sqrt{1 - x^{2}}}\,dx\notag\\
&= x\sqrt{1 - x^{2}} - \int \sqrt{1 - x^{2}}\,dx + \int \frac{1}{\sqrt{1 - x^{2}}}\,dx\notag\\
\Rightarrow \int\sqrt{1 - x^{2}}\,dx &= \frac{x\sqrt{1 - x^{2}}}{2} + \frac{1}{2}\int \frac{dx}{\sqrt{1 - x^{2}}}\notag\\
\end{align}
Hence $$\int\_{a}^{1}\sqrt{1 - x^{2}}\,dx = - \frac{a\sqrt{1 - a^{2}}}{2} + \frac{1}{2}\int\_{a}^{1}\frac{dx}{\sqrt{1 - x^{2}}}$$ or $$\int\_{a}^{1}\frac{dx}{\sqrt{1 - x^{2}}} = 2\left(\frac{ab}{2} + \int\_{a}^{1}\sqrt{1 - x^{2}}\,dx\right)$$ or $L = 2A$ which was to be proved.
Contrast the above proof of relation between length and area with the following totally non-rigorous proof. Let the length of arc $AP$ be $L$. Then the angle subtended by it at the center is also $L$ (definition of radian measure). Divide this angle into $n$ parts of measure $L/n$ each and then the area of sector $AOP$ is sum of areas of these $n$ sectors. If $n$ is large then area of each of these $n$ sectors can be approximated by area of the corresponding triangles and this area is $$\frac{1}{2}\sin (L/n)$$ so that the area of the whole sector $AOP$ is $(n/2)\sin(L/n)$. As $n \to \infty$ this becomes $L/2$ and here we need the analytic property of $\sin x$ namely $(\sin x)/x \to 1$ as $x \to 0$. Therefore area can't be the basis of a proof of this limit. This is perhaps the reason that proofs for limit formula $(\sin x)/x \to 1$ looks circular.
A proper proof can't be done without integrals as I have shown above. Hence the proof that $(\sin x)/x \to 1$ depends upon Riemann integration and definition of $\sin x, \cos x$ as inverses to the integrals. This is same as $e^{x}$ is defined as inverse to integral of $1/x$.
Also see [my another answer to a similar question](https://math.stackexchange.com/a/1001053/72031).
|
44,562,560 |
Where I can disable **"Unclosed comment"** inspection in PhpStorm?
[](https://i.stack.imgur.com/sFLY3.png)
I can't find this inspection settings
```
<script type="text/javascript">
$(function () {
/*// Typeahead
var a = $.parseJSON('<?php //echo json_encode( $groups); ?>');
$('#query').typeahead({
local: a
});*/
});
</script>
```
|
2017/06/15
|
[
"https://Stackoverflow.com/questions/44562560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6625548/"
] |
It's a known issue.
<https://youtrack.jetbrains.com/issue/WEB-22461> -- watch this ticket (star/vote/comment) to get notified on any progress.
Possible workaround -- use single line comments instead of block comments.
|
38,433,834 |
Below are the xml file
```
<maindata>
<publication-reference>
<document-id document-id-type="docdb">
<country>US</country>
<doc-number>9820394ASD</doc-number>
<date>20111101</date>
</document-id>
<document-id document-id-type="docmain">
<doc-number>9820394</doc-number>
<date>20111101</date>
</document-id>
</publication-reference>
</maindata>
```
i want to extract the `<doc-number>`tag value under the type = "`docmain`"
below is my java code, while executed its extract `9829394ASD` instead of `9820394`
```
public static void main(String[] args) {
String filePath ="D:/bs.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nodeList = doc.getElementsByTagName("publication-reference");
List<Biblio> docList = new ArrayList<Biblio>();
for (int i = 0; i < nodeList.getLength(); i++) {
docList.add(getdoc(nodeList.item(i)));
}
} catch (SAXException | ParserConfigurationException | IOException e1) {
e1.printStackTrace();
}
}
private static Biblio getdoc(Node node) {
Biblio bib = new Biblio();
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
bib.setCountry(getTagValue("country",element));
bib.setDocnumber(getTagValue("doc-number",element));
bib.setDate(getTagValue("date",element));
}
return bib;
}
```
let me know how can we check the Type its docmain or doctype, should extract only if the type is docmain else should leave the element
added the getTagValue method
```
private static String getTagValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}
```
|
2016/07/18
|
[
"https://Stackoverflow.com/questions/38433834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2257288/"
] |
Change your method `getdoc()` so that it create only a `Biblio` object for 'docmain` types.
```
private static Biblio getdoc(Node node) {
Biblio bib = null;
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String type = element.getAttribute("document-id-type");
if(type != null && type.equals("docmain")) {
bib = new Biblio();
bib.setCountry(getTagValue("country",element));
bib.setDocnumber(getTagValue("doc-number",element));
bib.setDate(getTagValue("date",element));
}
}
return bib;
}
```
Then in your main method you should only add to the list, if `getdoc()` result is not null:
```
for (int i = 0; i < nodeList.getLength(); i++) {
Biblio biblio = getdoc(nodeList.item(i));
if(biblio != null) {
docList.add(biblio);
}
}
```
**Update:**
Ok, this is horrible, sorry. You should really learn a little bit about XPath.
I try to rewrite this using XPath expressions.
First we need four XPath expressions. One to extract a node list with all `document-id` elements with type `docmain`.
The XPath expression for this is: `/maindata/publication-reference/document-id[@document-id-type='docmain']` (whole XML document in context).
Here the predicate in [] ensures, that only `document-id` elements with type `docmain` are extracted.
Then for each field in a `document-id` element (with `document-id` element as context):
* country: `country`
* docnumber: `doc-number`
* date: `date`
We use a static initializer for that:
```
private static XPathExpression xpathDocId;
private static XPathExpression xpathCountry;
private static XPathExpression xpathDocnumber;
private static XPathExpression xpathDate;
static {
try {
XPath xpath = XPathFactory.newInstance().newXPath();
// Context is the whole document. Find all document-id elements with type docmain
xpathDocId = xpath.compile("/maindata/publication-reference/document-id[@document-id-type='docmain']");
// Context is a document-id element.
xpathCountry = xpath.compile("country");
xpathDocnumber = xpath.compile("doc-number");
xpathDate = xpath.compile("date");
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
```
Then we rewrite the method `getdoc`. This method now gets a `document-id` element as input and creates a `Biblio` instance out of it using XPath expressions:
```
private static Biblio getdoc(Node element) throws XPathExpressionException {
Biblio biblio = new Biblio();
biblio.setCountry((String) xpathCountry.evaluate(element, XPathConstants.STRING));
biblio.setDocnumber((String) xpathDocnumber.evaluate(element, XPathConstants.STRING));
biblio.setDate((String) xpathDate.evaluate(element, XPathConstants.STRING));
return biblio;
}
```
Then in the `main()` method you use the XPath expression to extract only the needed elements:
```
NodeList nodeList = (NodeList) xpathDocId.evaluate(doc, XPathConstants.NODESET);
List<Biblio> docList = new ArrayList<Biblio>();
for (int i = 0; i < nodeList.getLength(); i++) {
docList.add(getdoc(nodeList.item(i)));
}
```
|
29,117,951 |
I have this [Website](http://avocat.dac-proiect.ro/wp/?page_id=10)
**HTML:**
```css
.lista_sus li {
display: inline-block;
position: relative;
margin: 0 9px 5px 0;
background-color: #041067;
}
.lista_sus li p {
position: absolute;
top: 0;
left: 0;
color: white;
}
.hide {
display: none;
}
```
```html
<ul class="lista_sus">
<li>
<img src="./wp-content/themes/twentyfourteen/images/1.png" alt="Smiley face" height="250" width="250">
<p class="hide">
<div class="title">Zorica L. Codoban
<br>avocat
<br>
</div>
- Avocat din anul 1997
<br>- domenii de specialitate: drept civil, drept comercial, drept succesoral, drept imobiliar, dreptul muncii, drept administrativ, dreptul familiei;
<br>- limbi vorbite: franceza.
</p>
</li>
```
I want to position text over the image ... I did some testing we have found here in the forum but not working.
How can i solve this problem?
Can you help me please?
Thanks in advance!
|
2015/03/18
|
[
"https://Stackoverflow.com/questions/29117951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4684429/"
] |
Create HTML `background Image`
Or change structure for HTML code and use `float` for this.
|
10,546,302 |
How can I find all indexes of a pattern in a string using c#?
For example I want to find all `##` pattern indexes in a string like this `45##78$$#56$$JK01UU`
|
2012/05/11
|
[
"https://Stackoverflow.com/questions/10546302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269997/"
] |
```
string pattern = "##";
string sentence = "45##78$$#56$$J##K01UU";
IList<int> indeces = new List<int>();
foreach (Match match in Regex.Matches(sentence, pattern))
{
indeces.Add(match.Index);
}
```
indeces will have 2, 14
|
13,768,049 |
Is there a way to use instanceof based on the passed argument of a method? Example
```
doSomething(myClass.class); /* I would like to call this also with other classes */
public void doSomething(/*generic parameter that accepts all classes, not just myClass */) {
if (myObject instanceOf /* the generic parameter */ == true) {...}
}
```
sometimes I'll call the method using myClass.class but other times I would like to call it using someOtherClass.class - I don't want to change the if condition though. Is that possible? If so, how? :)
Thanks
|
2012/12/07
|
[
"https://Stackoverflow.com/questions/13768049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/511477/"
] |
You're looking for the [`Class.isInstance()` method](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isInstance(java.lang.Object)).
```
public void doSomething(Class<?> c, Object myObject) {
if (c.isInstance(myObject)) {...}
}
```
|
11,047,344 |
I'm trying to check network available or not.
But in my emulator it always shows `connected` (after disconnecting internet also)
Is there any mistake in my code.I am connecting with **wifi**.
*Code:*
```
public class AndroidConnectivityActivity extends Activity
{
Button checkBtn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkBtn = (Button) findViewById(R.id.button1);
checkBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(isInternetOn())
{
Toast.makeText(getBaseContext(), "Connected",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Not connected",
Toast.LENGTH_SHORT).show();
}
}});
}
public final boolean isInternetOn()
{
ConnectivityManager connec = (ConnectivityManager) getSystemService
(Context.CONNECTIVITY_SERVICE);
if ((connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)
||(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING)
||(connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING)
||(connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED))
{
return true;
}
else if ((connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED)
|| (connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED))
{
return false;
}
return false;
}
}
```
|
2012/06/15
|
[
"https://Stackoverflow.com/questions/11047344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1453422/"
] |
use below code
```
public static boolean isInternetAvailable(Context context)
{
boolean isInternetAvailable = false;
try
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null && (networkInfo.isConnected()))
{
isInternetAvailable = true;
}
}
catch(Exception exception)
{
// Do Nothing
}
return isInternetAvailable;
}
```
and also try on real device
use code in Activity onCreate Method like
```
if(isInternetAvailable(this))
{
Toast toast = Toast.makeText(this, "internet available", Toast.LENGTH_SHORT);
toast.show();
}
else
{
Toast toast = Toast.makeText(this, "internet not available", Toast.LENGTH_SHORT);
toast.show();
}
```
Required manifest permission
```
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
```
|
145,015 |
How to evaluate the following definite integral:
$$\int\_{-1}^1 \exp\left(\frac1{x^2-1}\right) \, dx$$
It seems that indefinite integral also cannot be expressed in standard functions. I would like any solution in popular elementary or non-elementary functions.
|
2012/05/14
|
[
"https://math.stackexchange.com/questions/145015",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/2513/"
] |
I have the best approach:
$\int\_{-1}^1e^{\frac{1}{x^2-1}}~dx$
$=\int\_{-1}^0e^{\frac{1}{x^2-1}}~dx+\int\_0^1e^{\frac{1}{x^2-1}}~dx$
$=\int\_1^0e^{\frac{1}{(-x)^2-1}}~d(-x)+\int\_0^1e^{\frac{1}{x^2-1}}~dx$
$=\int\_0^1e^{\frac{1}{x^2-1}}~dx+\int\_0^1e^{\frac{1}{x^2-1}}~dx$
$=2\int\_0^1e^{\frac{1}{x^2-1}}~dx$
$=2\int\_0^\infty e^{\frac{1}{\tanh^2x-1}}~d(\tanh x)$
$=2\int\_0^\infty e^{-\frac{1}{\text{sech}^2x}}~d(\tanh x)$
$=2\int\_0^\infty e^{-\cosh^2x}~d(\tanh x)$
$=2\left[e^{-\cosh^2x}\tanh x\right]\_0^\infty-2\int\_0^\infty\tanh x~d\left(e^{-\cosh^2x}\right)$
$=4\int\_0^\infty e^{-\cosh^2x}\sinh x\cosh x\tanh x~dx$
$=4\int\_0^\infty e^{-\cosh^2x}\sinh^2x~dx$
$=4\int\_0^\infty e^{-\frac{\cosh2x+1}{2}}\dfrac{\cosh2x-1}{2}dx$
$=2e^{-\frac{1}{2}}\int\_0^\infty e^{-\frac{\cosh2x}{2}}(\cosh2x-1)~dx$
$=e^{-\frac{1}{2}}\int\_0^\infty e^{-\frac{\cosh2x}{2}}(\cosh2x-1)~d(2x)$
$=e^{-\frac{1}{2}}\int\_0^\infty e^{-\frac{\cosh x}{2}}(\cosh x-1)~dx$
$=e^{-\frac{1}{2}}\left(K\_1\left(\dfrac{1}{2}\right)-K\_0\left(\dfrac{1}{2}\right)\right)$
|
8,794,937 |
I know how to create bundle using console. Now I want to add second controller to generated bundle, how can I do it from console. (php app/console generate:controller doesn't work)
|
2012/01/09
|
[
"https://Stackoverflow.com/questions/8794937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/783353/"
] |
Since version `2.2` you can use
```
php app/console generate:controller
```
Documentation [here](http://symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_controller.html).
|
184,047 |
I have made a site in SharePoint 2013 and different users in my sites like who can view, visit, edit or has full control of the site.
Now for some users I want to hide the browse and page tab from the navigation bar. There are many links available but not working from me.
Can somebody give me brief technical details as to how this could be done?
Moreover how can I hide settings link in my ribbon for some users?
|
2016/06/16
|
[
"https://sharepoint.stackexchange.com/questions/184047",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/54193/"
] |
1. Create JavaScript or CSS code that hides the items from the ribbon
2. Place that code inside Script Editor Web Part
3. Use Audience targeting in web part properties to only "display" that web part to specific users (=to those from which you wish to hide the ribbon items)
|
389,953 |
You often *plunge* into the sea or *plunge* you hands into your pockets.
Can the word be used to describe a "horizontal immersion"?
Example sentence:
>
> She opened the door and **plunged** into the blinding sun.
>
>
>
If not, what's a more appropriate word?
|
2017/05/19
|
[
"https://english.stackexchange.com/questions/389953",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/202294/"
] |
It's perfectly acceptable, but you might want to consider the "literal baggage," for lack of a better word, that the figurative term carries with it.
Take the OED literal definition that this derives from:
>
> To thrust, throw, or drop into or in a liquid, penetrable substance, deep pit, container, etc.; to immerse, to submerge.
>
>
>
In any case that you use the word "plunge," readers will associate it with the literal meaning to derive its figurative meaning. If you want to invoke feelings of falling deep into something, then it's appropriate. Just be aware that the use **ordinarily** refers to falling or pushing *in a downward direction*.
|
59,893,690 |
```
$scope.vergleich = function () {
if ($scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei || dataService.dic.neu.rechtsformKanlei ) !== -1) {
return true
} else {
return false; }
}
}
```
I am currently student and intelliJ tells me I have to simplify this if-statement but I have no idea how. Maybe somebody can help me.
|
2020/01/24
|
[
"https://Stackoverflow.com/questions/59893690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
The simplification is probably that, if `condition` is a boolean, :
```
if (condition) {
return true;
}
else {
return false;
}
```
is equivalent to
```
return condition;
```
**However** there also seems to be a logical error in your test.
```
$scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei ||
dataService.dic.neu.rechtsformKanlei ) !== -1
```
Does **not** mean the same thing as :
```
$scope.relrechtsform.indexOf(dataService.dic.alt.rechtsformKanlei) !== -1 ||
$scope.relrechtsform.indexOf(dataService.dic.neu.rechtsformKanlei) !== -1
```
|
58,843,192 |
I have two different JSON object. One object is empList and other one is holidayList.
I want to add hours from each JSON object.Andthe sum of hours should be pushed to sumHoursList JSON object.I am doing this using Angular6.
I am not getting exactly how to iterate this to get the required result.
**Basically I want to add hours from both the datalist of empList , to that want to add hours from holiday list, and the sum value should
append in sumhourlist**
Below is my code.
```
this.empList = [
{
'id': 1,
'name': 'Name1',
datalist: [
{
"date": 1,
"hours": 6
},
{
"date": 2,
"hours": 0
},
{
"date": 3,
"hours": 12
}
]
},
{
'id': 2,
'name': 'Name2',
datalist:[
{
"date": 1,
"hours": 0
},
{
"date": 2,
"hours": 8
},
{
"date": 3,
"hours": 0
}
]
},
];
this.holidayList=[
{
"date": 1,
"hours": 0
},
{
"date": 2,
"hours": 8
},
{
"date": 3,
"hours": 12
}
]
sumHoursList = [
{
"date": 1,
"hours": 6
},
{
"date": 2,
"hours": 16
},
{
"date": 3,
"hours": 24
}
]
```
Can anyone please help me how to do this.
|
2019/11/13
|
[
"https://Stackoverflow.com/questions/58843192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4675072/"
] |
Try modifying your ingress objects rewrite-target & path as below:
```
nginx.ingress.kubernetes.io/rewrite-target: /$1
path: /(.*)
```
and make sure you checked this [documentation](https://kubernetes.github.io/ingress-nginx/examples/rewrite/#rewrite-target)
Once you tried this let me know.
|
299,535 |
Chrome always quit when I click on the `X` button on a tab, without asking me anything!
Even when I close Chrome he do not alert me if I am willing to relay close it?
Many times it happened that accidentally I clicked on `X` button.
|
2011/06/20
|
[
"https://superuser.com/questions/299535",
"https://superuser.com",
"https://superuser.com/users/71640/"
] |
If you accidently close all your tabs you can reload Chrome and press `CTRL` + `SHIFT` + `T`.
This will restore your previous session for all your tabs.
You could also look for a Chrome extension such as [Windows Close Protector](https://chrome.google.com/webstore/detail/lnpifgapnmpninomacbhdlconlpikdai).
|
20,699,509 |
This html form and the related php code works pretty well together. I need to add a word counter. Any suggestions.
```
<form action="form.php" method="POST">
<fieldset>
<input type="hidden" name='counter' value='2'/>
<p><label for="heading1"></label>
<input type="text" name="heading1" size="60" /></p>
<p><label for="input1"></label>
<textarea cols="width" rows="height" name="input1">...</textarea></p>
<p><label for="heading2"></label>
<input type="text" name="heading2" size="60" value="first para title..."></p>
<p><label for="input2"></label>
<textarea cols="width" rows="height" name="input2">...</textarea></p>
<br />
<fieldset>
<input type="submit" value="" />
<input type="reset" value="" />
</fieldset>
</form>
```
The related php code is found below.
```
<?php
$count=$_REQUEST['counter'];
for($i=1;$i<=$count;$i++)
{
echo "<p>" . $_REQUEST['heading'.$i] . "</p>";
echo "<p>" . $_REQUEST['input'.$i]. "</p>";
}
?>
```
|
2013/12/20
|
[
"https://Stackoverflow.com/questions/20699509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2714362/"
] |
Like this:
```
var output = document.getElementById("counter"),
textarea = document.getElementById("textarea");
textarea.onkeyup = function (event) {
var words = textarea.value.split(" ");
output.value = words.length;
};
```
To make it easier, add IDs to your HTML elements like this:
```
<input type="hidden" name="counter" id="counter" value="0"/>
<textarea cols="width" rows="height" name="input2" id="textarea">...</textarea>
```
What this does: Every time the user releases types a letter into the textarea it will take the contents, split it on spaces and counts the number of words which is inserted into your hidden `counter` field. When the form is submitted the number of words will also be sent to the server.
However, if you don't need the number of words in the client (for instance showing the user how many words she has typed) then I suggest you do this in PHP. Look at the `str_split` function.
|
11,240,723 |
I have an issue of alphabetically sorting the contacts picked from the address book into section headers . I can arrange them alphabetically without the section headers but how to put them according to the names of the contacts ? I do not want to use the NSDictionary as I am able to do the sorting without it. Please view the code below :-
```
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [arrayForLastName count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[alphabets sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z", nil];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [arrayForLastName count];
}
```
Any help would be appreciated thanx :)
|
2012/06/28
|
[
"https://Stackoverflow.com/questions/11240723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1479368/"
] |
You can achieve this in following way -
1.Create an index array that contains all the required index -
```
NSArray *indexArray = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z", nil];
```
2.For Each index you need to have an array that will display row for those sections. SO you can have a dictionary that contain an array corresponding to each index.
Check this tutorial, it will help you in implementing this- <http://www.icodeblog.com/2010/12/10/implementing-uitableview-sections-from-an-nsarray-of-nsdictionary-objects/>
|
17,649,574 |
I am migrating some plugin from `Linux` to `Windows`.
Plugin is written using `Perl` and it has the function called `system()` that will execute the shell commands.
But I am migrating to Windows now. Any way I can run the linux command in windows using system() Per function?
Some `Perl Module` avail for this ?
|
2013/07/15
|
[
"https://Stackoverflow.com/questions/17649574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/799046/"
] |
You can run the `system()` command but there are caveats. A nice description is contained in [*Using system or exec safely on Windows*](http://blogs.perl.org/users/graham_knop/2011/12/using-system-or-exec-safely-on-windows.html). This article resulted in the [Win32::ShellQuote](http://p3rl.org/Win32%3a%3aShellQuote) module.
|
45,988 |
On Windows I can use Utilu Firefox collection (there also ie collection on his site).
How can I use multiple browser versions to see how my website works in different versions of different browsers in OS X?
For example I want to install [browsers with biggest market share](https://en.wikipedia.org/wiki/Browser_market_share#Summary_table):
* Internet Explorer
* Firefox 3.6, latest and previous
* Google Chrome latest and previous
* Safari (any older versions possible)
* Opera
|
2012/03/26
|
[
"https://apple.stackexchange.com/questions/45988",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/14692/"
] |
Firefox
-------
[Firefoxes](https://github.com/omgmog/install-all-firefox) is a shell scripts that will install all major versions of Firefox on OS X, and set up separate profiles so you can use them simultaneously. Currently it installs:
* Firefox 2.0.0.20
* Firefox 3.0.19
* Firefox 3.5.9
* Firefox 3.6.28
* Firefox 4.0.1
* Firefox 5.0.1
* Firefox 6.0.1
* Firefox 7.0.1
* Firefox 8.0.1
* Firefox 9.0.1
* Firefox 10.0.2
* Firefox 11.0
* Firefox Beta
* Firefox Aurora
* Firefox Nightly
* Firefox UX Nightly
You can set it up so it only installs the specific versions you want.
Optionally, the script can install Firebug for each version of Firefox too.
It will also set icons that contain the version number:

Safari
------
For Safari, check out [Multi-Safari](http://michelf.com/projects/multi-safari/).
Chrome/Chromium
---------------
For Chrome/Chromium, install any version you want, change the app name from `Chromium.app` to e.g. `Chromium 19.app` for clarity, then [disable auto-updates](http://dev.chromium.org/administrators/turning-off-auto-updates) for that version.
Opera
-----
Download old Opera versions here: <ftp://ftp.opera.com/pub/opera/mac/>
IE
--
Get VirtualBox and then run [this `ievms` script](https://github.com/xdissent/ievms). It will automatically download legal Windows images for testing purposes and set up virtual machines for every IE version you need.
|
38,210,037 |
I have a console script in a Yii2 advanced installation from which I can successfully use several models under 'common\models\modelName', but when I try to use a model from under 'backend\models\db\AuthAssignment' I get the following error:
>
> Exception 'yii\base\UnknownClassException' with message 'Unable to find 'backend\models\db\AuthAssignment' in file: /var/www/html/mvu/backend/models/db/AuthAssignment.php. Namespace missing?'
>
>
>
This model file starts as follows:
```
<?php
namespace app\models\db;
use Yii;
class AuthAssignment extends \yii\db\ActiveRecord {
```
And the call from the console\controller file is as follows:
```
<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
use backend\models\db\AuthAssignment;
use common\models\CourseLessons;
use common\models\Courses;
use common\models\Customer;
use common\models\Users;
class MijnvuController extends Controller {
```
What namespace could the error mean here and where to include it?
|
2016/07/05
|
[
"https://Stackoverflow.com/questions/38210037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3197616/"
] |
Turns out that I needed to produce a duplicate of the specific model under 'frontend\models\db\AuthAssignment' because frontend and backend have similar functionality while running different databases.
Called it accordingly and it works:
```
<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
use backend\models\db\AuthAssignment;
use common\models\CourseLessons;
use common\models\Courses;
use common\models\Customer;
use common\models\Users;
class MijnvuController extends Controller {
```
|
47,820,182 |
I have a query (below) that uses ldap connection to retrieve AD related info. However, the issue is this query provide all of the employees. I am only looking for current employees. I was told to use following information to pull "Active only" employees:
>
> OU=CompanyName Users,DC=CompanyName,DC=local
>
>
>
I tried to modify below select statement to add OU related information, but query keeps failing. Anyone know how to convert above string into a proper ldap location?
```
SELECT
*
FROM OPENQUERY( ADLink,
'
SELECT
employeeNumber,
name
FROM ''LDAP://ldap.CompanyName.local/DC=CompanyName;DC=local''
WHERE objectClass = ''user''
AND objectCategory = ''Person''
ORDER BY title asc
') A
```
|
2017/12/14
|
[
"https://Stackoverflow.com/questions/47820182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2055916/"
] |
To prevent error you have now - just make `sort` parameter non optional (move it to the beginning of parameter list and remove = `null`). If it fails to bind (for example, no sort is specified in query string) - it will have `null` value anyway, so there is no reason to have `= null` default in this case.
Now, your sort specification is split over multiple query string parameters:
```
sort[0][field]=tradeName&sort[0][dir]=asc
```
so to bind it to your model, you will need a custom model binder. First create class to represent sort specification:
```
public class KendoSortSpecifier {
public string Field { get; set; }
public string Direction { get; set; }
}
```
Then custom model binder (this is just an example, adjust to your own needs if necessary):
```
public class KendoSortSpecifierBinder : System.Web.Http.ModelBinding.IModelBinder {
private static readonly Regex _sortFieldMatcher;
private static readonly Regex _sortDirMatcher;
const int MaxSortSpecifiers = 5;
static KendoSortSpecifierBinder() {
_sortFieldMatcher = new Regex(@"^sort\[(?<index>\d+)\](\[field\]|\.field)$", RegexOptions.Singleline | RegexOptions.Compiled);
_sortDirMatcher = new Regex(@"^sort\[(?<index>\d+)\](\[dir\]|\.dir)$", RegexOptions.Singleline | RegexOptions.Compiled);
}
public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext) {
if (bindingContext.ModelType != typeof(KendoSortSpecifier[]))
return false;
var request = actionContext.Request;
var queryString = request.GetQueryNameValuePairs();
var result = new List<KendoSortSpecifier>();
foreach (var kv in queryString) {
var match = _sortFieldMatcher.Match(kv.Key);
if (match.Success) {
var index = int.Parse(match.Groups["index"].Value);
if (index >= MaxSortSpecifiers)
continue;
while (result.Count <= index) {
result.Add(new KendoSortSpecifier());
}
result[index].Field = kv.Value;
}
else {
match = _sortDirMatcher.Match(kv.Key);
if (match.Success) {
var index = int.Parse(match.Groups["index"].Value);
if (index >= MaxSortSpecifiers)
continue;
while (result.Count <= index) {
result.Add(new KendoSortSpecifier());
}
result[index].Direction = kv.Value;
}
}
}
bindingContext.Model = result.Where(c => !String.IsNullOrEmpty(c.Field)).ToArray();
return true;
}
}
```
And finally your controller method signature:
```
public IHttpActionResult GetTrades(
[System.Web.Http.ModelBinding.ModelBinder(typeof(KendoSortSpecifierBinder))]
KendoSortSpecifier[] sort,
int page = -1,
int pageSize = -1,
int skip = -1,
int take = -1)
```
Now you have strongly typed model of your sort (except `Direction` can be represented by enum instead of string) and can use it as necessary to sort your data.
|
11,121,193 |
I found a way to write the `if` statement in another way (I think) while searching in the source code of a website.
Instead of:
```
if(a)b;
```
or:
```
a?b:'';
```
I read:
```
!a||b;
```
Is the third way the same as the first two? And if yes, why we would use the third way?
|
2012/06/20
|
[
"https://Stackoverflow.com/questions/11121193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365010/"
] |
The third way is the same as the previous ones. One argument to use it is saving bytes. A strong argument against using it is readability. You'd better focus on readability in writing code, and use a minimizer (such as [Google Closure Compiler](http://closure-compiler.appspot.com)) to save bytes.
It can be even shorter:
```
a && b;
/* !a||b means:
(not a) OR b
which is equivalent to
a AND b
which turns out to be
a && b
*/
```
|
59,584,189 |
My problem: Want to display every letter after 1 second, but instead of this I display all the letters immediately. I have tried many ways to do this but still can't.
My code:
```
const [parrot, setParrot] = useState({ content: ' ' });
const displayText = () => {
let text = 'Parrot';
let freeLetters = [...text];
let sumOfLetters = [];
for (let k = 0; k < freeLetters.length; k++) {
(function() {
let j = k;
setTimeout(() => {
sumOfLetters.push(freeLetters[j]);
console.log(sumOfLetters);
setParrot({
content: sumOfLetters.join(' ')
});
console.log(parrot.content);
}, 1000);
})();
}
};
return (
<div className={classes.contentwrapper}>
<h1 onClick={() => displayText()}>Click me, {parrot.content}</h1>
</div>
);
```
|
2020/01/03
|
[
"https://Stackoverflow.com/questions/59584189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11449471/"
] |
Your timeouts are all set to 1000 milliseconds, you should multiply the timeout by the current index of the loop.
What you need to do is increase the setTimeout wait value on each iteration of your loop. See a working example below.
```
const [parrot, setParrot] = useState({ content: ' ' });
const displayText = () => {
let text = 'Parrot';
let freeLetters = [...text];
let sumOfLetters = [];
for (let k = 0; k < freeLetters.length; k++) {
(function() {
let j = k;
setTimeout(() => {
sumOfLetters.push(freeLetters[j]);
console.log(sumOfLetters);
setParrot({
content: sumOfLetters.join(' ')
});
console.log(parrot.content);
}, 1000 * (j + 1));
// j + 1 because the loop starts at 0.
// For the second iteration this will be 2000 ms
// For the third, 3000 ms
// Etc.
})();
}
};
return (
<div className={classes.contentwrapper}>
<h1 onClick={() => displayText()}>Click me, {parrot.content}</h1>
</div>
);
```
|
55,454 |
It's 2016, but for some reason, the Cold War never ended. You've been inspired by your (for some inexplicable reason) favorite movie, Indiana Jones 4, to start a new business: building refrigerators. However, the market is so saturated that in order to distinguish yourself with a nice marketing campaign, you decide to make them **NUKEPROOF!**
The refrigerator should be:
1. Usable as a real refrigerator would be.
2. No bigger than standard double door refrigerator, so no room-sized walk-in refrigerator. Though, you *can* add some additional size for additional armor, for example, in **reasonable** margins, so nothing like 10 meters of iron from one side.
3. Protect one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion.
How are you going to design it and what materials are you going to use?
|
2016/09/15
|
[
"https://worldbuilding.stackexchange.com/questions/55454",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/26768/"
] |
**It's Not Possible**
You have asked for a **Science-Based** answer, and it's just not going to happen. Despite what Indiana Jones says, it's impossible to build a nuke-proof fridge. Even if the fridge itself is basically OK, the concussive force it went under would jar it severely (and rattle anyone inside of it to death) - or the heat of the blast would cook you inside of it.
So to answer your question about what I would make it out of, since I'm selling snake oil anyway I would build it with the CHEAPEST things I could, put a basic lead plating around it all so people thought it was built in a sturdy fashion, then make profit. And shortly after selling a few I'd close up shop and drop the alias I was using.
If I were to try to answer this more to the spirit of your question than how it was asked, to survive the nuke you would want to build the fridge out of lead (obviously). Your trouble would come where you would want your fridge to have enough air to breathe for awhile (you know the nuke is coming, but not exactly when, so you would hide in there for a bit). At that point you can either make holes in your fridge - drastically reducing its efficacy as a food chiller and as a life saving device - or install some kind of oxygen tank and air scrubber. Those however are going to take up a lot of space.
Some other downsides:
The air tank may explode due to the concussive force of the blast. And when your house is on fire, opening a door and releasing a lot of oxygen into the room will result in you being lit on fire. Of course, not opening the door will ALSO result in your death because that fridge will heat up as the house burns. If your house collapses though, it's a bit of a moot point as you'll be trapped in your fridge and won't have to worry about picking one or there other.
.
**Update\***
Because the comments pointed out the OP updated the question with a specific distance a nuclear yield, let's make sure it's still impossible.
According to [NUKEMAP](http://nuclearsecrecy.com/nukemap/) a 1.2 Megaton nuke has the following effects at 2km:
**Outside of Fireball Radius (1.04km)**
Well, that's good!
**Inside or Radiation Radius (2.56km)**
Less good. 500rem (5 Sv) of radiation - [that's lethal](https://www.standeyo.com/News_Files/NBC/Roentgen.chart.html)! We need to get that down to about 200rem (2 Sv; the "largest dose that does not cause illness severe enough to require medical care in over 90% of people" per previous link).
The best possible shielding wouldn't be Lead, it would actually be Tungsten. To be safe, we'll use two halving-factors, which would actually reduce radiation to ~125rem (1.25 Sv; a hair over the "Smallest dose causing loss of hair after 2 weeks in at least 10% of people").
Link: [Half-Value Layers](https://www.nde-ed.org/EducationResources/CommunityCollege/Radiography/Physics/HalfValueLayer.htm)
If we used Lead, we would need to line the fridge with: 0.98" (24.9 mm; let's call it 1" or 25.4 mm to be safe).
If we used Tungsten, we would need to line the fridge with: 0.62" (15.8 mm; let's call it 0.7" or 17.8 mm to be safe).
Well, that's possible to accommodate - you're still alive!
**Inside 20PSI (138 kPa) Air Blast Radius (3km)**
Per NUKEMAP, at 20PSI (138 kPa) heavy concrete buildings are severely damaged or demolished. Unless you are living underground or in a very fortunate large concrete building, **per [FEMA](http://www.fema.gov/pdf/plan/prevent/rms/155/e155_unit_vi.pdf), you are dead**. You cannot expect the fridge to withstand this blast.
**Inside 5PSI (34.5 kPa) Air Blast Radius (7.4km)**
Per NUKEMAP, at 5PSI (34.5 kPa) residential buildings can be expected to collapse. If you are in your fridge and cannot escape due to the roof having collapsed in front of the door, **you will be trapped and die**.
**Inside the Thermal Radiation Radius (13.6km)**
Per NUKEMAP, within this radius 3rd degree burns can be expected. At this point your house has collapsed on you and spontaneously combusted. If you were lucky enough to survive the pressure (doubtful), **you are now roasting alive in your Tungsten-lined tomb**.
***There is no such thing as being "safe" 2km from any instrument of mass thermonuclear war, least of all in a REFRIGERATOR.***
|
206,671 |
**EDIT**
After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references.
For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question:
* a 4 hours pre-interview, offsite programming test is not usual but
* many people pointed it out that for some companies you would interview for much-much longer than that all together
* it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company
* all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances
I wanted my original question to be about how *reasonable* to expect 4 hours from me, and how *ethical* to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange.
However, I found all your answers valuable and thanks for sharing.
**ORIGINAL POST**
I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own.
Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in.
Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than **4 hours**.
Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test)
Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated.
What I came up as a conclusion with this company is that either:
1) My motivation is not good and probably they are looking for someone else
2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them
3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...)
How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?
|
2013/07/31
|
[
"https://softwareengineering.stackexchange.com/questions/206671",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/30439/"
] |
Let me take the company's side for a moment, since the other answers haven't so far. It would be nearly impossible to build a usable code base out of a conglomeration of 4-hour coding test submissions from people whose qualifications are completely unknown. Creating a detailed enough specification, vetting the responses, and integrating it with the rest of your code would take longer than 4 hours. Not to mention most useful enterprise-level software projects require thousands of man hours. The thought of building a business on splitting that out into 4-hour increments with weeks of turnaround time each is frankly ridiculous.
Giving a real life problem of the business is one of the best ways to determine if someone will be good at, shockingly, solving real life problems of the business. I do this frequently in interviews (although I ask for general design principles and not 4 hours worth of code), and every single time it has been a problem I have already solved. If I hadn't already solved it, the test would lose almost all probative value.
Whether a 4-hour test is worth it to you is a personal decision. I was always taught to treat looking for full-time work as a full time job. When you're unemployed or underemployed and spending 8 hours a day looking for work, a 4-hour coding test is nothing. I've spent far longer than that on tasks like brushing up on rusty languages, writing portfolio programs, and customizing resumes for specific positions.
On the other hand, some of the best workers are already gainfully employed, and only casually looking for better opportunities. People in that situation are unlikely to go through the rigamarole of a 4-hour test, unless the opportunity is stellar. However, that's the company's problem, not yours.
As far as discerning what it means about the company's attitude toward their employees, I don't think you can really say anything either way, other than they are probably tired of dealing with unqualified applicants, to a degree that they're willing to throw out some of the good with the bad.
|
10,739 |
I'm currently working on a novel, in which one of the POV characters is a slave. He was born to a slave (so he was born a slave) of a rich merchant family and was treated well most of his life. One day he travels with his master to a foreign country where slavery had been abolished. The interaction with the foreign "free" people makes him doubt his position.
Might be relevant that he is of a different race than his masters, and the population of the foreign country he travels to belongs to his race.
Initially I want him to not see the injustice in his state and to love his master (they have a close relationship since they grew up together), yet I (born into a *mostly* slave-free world) have no idea how to portray him. Almost anything I try to write about him feels contrived.
How could I better identify with him?
or
Any reference to a novel (historical fiction preferred, could be any period in history) with a slave POV character (third-person preferred) will do.
|
2014/04/16
|
[
"https://writers.stackexchange.com/questions/10739",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/8048/"
] |
If you're looking for first-hand accounts, I'd recommend [Ten Years a Slave](http://www.amazon.co.uk/gp/product/1499102534/ref=as_li_ss_il?ie=UTF8&camp=1634&creative=19450&creativeASIN=1499102534&linkCode=as2&tag=nonshewro0a-21). It's an autobiographical account of a free black man who was forced into slavery, and it's pretty shocking. It was also made into a (wonderful/horrific) film last year, which I'd recommend looking out for.
For a short-read, there's [A Letter to my Old Master](http://www.lettersofnote.com/2012/01/to-my-old-master.html), a letter - believed to be real - from a freed slave to his old master, who asked him to return to work.
It's not quite a first-hand account, but I'd also recommend looking up the YouTube series Ask a Slave; it's based on the real-life, modern experiences of an actress working in a historical house, where she portrayed a slave and had to answer questions from visitors about her 'daily life'. What's quite interesting is seeing the inherent beliefs and misunderstandings people still have today about slavery and race.
Also, I don't have any books to recommend but it might be worth looking into Stockholme Syndrome and domestic abuse as well as slavery, to help with the angle of your character loving the slave owner. It might help your character feel less contrived if, instead of being naive, he's been manipulated. I think you can believe anything is 'your fault' if someone tells you so long enough.
For some more generic thoughts about your story, a person who has been raised in slavery from birth would most likely be indoctrined in the religion and custom of their slavers, which could potentially help mould the thoughts of your character. I'm not certain if your story takes place in this world? It might help your story to create some specific, rather racist religion if it doesn't, but even if it does some people have interpreted the Curse of Ham in the Bible as a condemnation of dark skin - as if it's something you're cursed with - and the Book of Mormon has mentions of God 'setting a mark upon' sinners, which has been interpreted as meaning giving them dark skin.
Now obviously that's hogswash, but if you lived in a culture of slavery, you would want to find reasons to justify your actions and ways of seeing your slaves as something lesser than you, and you could easily find meanings in religious passages to support your needs.
In Ten Years a Slave, the slave owners regularly gather the slaves to listen to Christian sermons and speeches, and if you were brought up having people read from important-sounding books every day, and explaining that the passages mean you're indebted to them, you might well believe it yourself.
However, I think the older you got, the more difficult it would be to believe. As What said, you would most likely be aware of the injustice. I think it would be entirely human to ask, 'Why me? What's the difference between me and my master?' You would compare yourself to them, especially if you were brought up together, and I'm sure more than once you'd see injustice directly, even if it was small - say he hit you with a stick or stole sweets from the pantry. When *his* skin didn't 'darken' and he wasn't beaten, you would have to question why.
It gets harder if there are more slaves, as there are likely to be, as you would be exposed to more points of view which would likely be different, and it would be very easy to be jaded and bitter from very early on. Even 'kind' masters didn't treat their slaves *well*; a slave is a slave.
I don't know how grim a story yours is, but in American slavery, we have accounts of children being taken away from parents and sold, and young women being raped; it would be pretty easy to see the injustice there.
Still, as Craig pointed out, some slaves in America stayed with their masters because it was the only life they'd known - a home and daily meals (and not being killed for running away) would seem the sensible option to many people. That doesn't mean they were *happy*. It's not really comparable but just as an example of human psychology, in 2011 Gallup reported 71% of American workers hate their jobs - I think it's fair to say a lot of people, no matter the situation, will take the devil they know.
I think there's a very interesting and complex psychology there to explore. Good luck!
|
1,331,178 |
I'm new to DDD and NHibernate.
In my current project, I have an entity Person, that contains a value object, let's say Address. Today, this is fine. But maybe one day I will have a requirement that my value object (in this case Address), will have to become an entity.
Before trying to model this on a DDD-way, in a more data-centric approach, I had a table Person, with an Id, and another table Address, whose PK was actually an FK, it was the Id of a Person (ie, a one-to-one relationship).
I've been reading that when I map a Value Object as a Component, its value will get mapped as columns on my Entity table (so, I would not have the one-to-one relationship).
My idea was that, when needed, I would simply add a surrogate key to my Address table, and then it becomes an Entity.
How should I design this using NHibernate? Should I already make my Address object an Entity?
Sorry, I don't even know if my questions are clear, I'm really lost here.
|
2009/08/25
|
[
"https://Stackoverflow.com/questions/1331178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150339/"
] |
In the system we are building, we put Value-Objects in separate tables. As far as I know, NHibernate requires that an `id` must added to the object, but we ignore this and treat the object as a Value-Object in the system. As you probably know, a Value-Object is an object that you don't need to track, so we simply overlook the `id` in the object. This makes us freer to model the database the way we want and model the domain model the way we want.
|
51,710,761 |
I'm new to mongodb , and i try to insert data in database through my html page using post method. and i use mongoose in server side.
here is my code look like.
```
var LoginInfoSchema = new mongoose.Schema
({
_id : String,
user: String,
password: String
});
var user = mongoose.model('user',LoginInfoSchema);
app.post('/login', function(req, res) {
new user({
_id : req.body.email,
user : req.body.user,
password : req.body.password
}).save(function(err,doc){
if(err) res.json(err);
else res.redirect('/');
});
mongoose.connect('mongodb://localhost:27017/UserInfo',function(err,db){
if(err) console.log(err);
db.collection("users").insertOne(user, function(error, result) {
if(error) console.log(error);
console.log("1 document inserted");
db.close();
});
});
});
```
whenever i insert data from localhost html page it will inserted successfully , i see that from mongo.exe terminal but i got error that is
name: 'MongoError',
message: 'Write batch sizes must be between 1 and 100000. Got 0 operations.',
ok: 0,
errmsg: 'Write batch sizes must be between 1 and 100000. Got 0 operations.',
code: 16,
codeName: 'InvalidLength',
[Symbol(mongoErrorContextSymbol)]: {} }
i search everywhere i cannot solve it . what its exactly mean please answer.
|
2018/08/06
|
[
"https://Stackoverflow.com/questions/51710761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7611778/"
] |
First I would use mongoose.connect() on top of your file and outside from the route handler.
Then when you use user.save(), you have already saved data into your DB and thanks to the callback function you can handle potential errors or display some success message. So db.collection.("users").insertOne() is kind of redundant.
Try this code maybe ? :
```
mongoose.connect('mongodb://localhost:27017/UserInfo');
var LoginInfoSchema = new mongoose.Schema({
_id : String,
user: String,
password: String
});
var user = mongoose.model('user',LoginInfoSchema);
app.post('/login', function(req, res) {
new user({
_id : req.body.email,
user : req.body.user,
password : req.body.password
}).save(function(err,doc) {
if(err) res.json(err);
res.redirect('/');
});
});
```
Hope that helps, Cheers
|
61,925 |
I am having troubles understanding utilitarianism a little bit, and have posed this question to a number of people and been met mostly with bafflement about how I cannot see the error in my proposed claim. But, when they explain against it, I cannot see the soundness of their argument. So, I am willing to accept that there is an essential error I am making in my reasoning, and am making this post in the hopes that someone will be able to point it out.
People like to say against utilitarianism the idea of inalienable rights. We believe people should have them, not because they will increase pleasure/decrease pain in the aggregate, but for some other given reason. Despite the fact that 30 people being run over by a bus is a much more unpleasurable result than one person being run over, we still (some of us) do not think it right to push that person in front of the bus to save the 30. Not advocating for this, just as a proposed counter-argument.
My question is: if we say that inalienable rights are valuable, are we not just simply choosing a different kind of pleasure that we place value on? People should have inalienable rights, and the value of a society which upholds these rights (with that value being determined by the consummate pleasure that comes with having inalienable rights, as compared to not having them) we consider to be a greater point value (+100 points of pleasure) versus the 30 people surviving the bus crash (+50 points of pleasure).
Or, if I refuse to torture one person to save two people from being tortured. Some might call me a Kantian, or some other thing, but not a utilitarian. But am I not just saying that the point value of the displeasure that comes from taking it upon myself to torture the one person (perhaps I believe that humans do not have that right, only God does) is -1 trillion versus the (granted) still very large point value of saving the other 2 (-1 billion)?
I had someone say, ok, well that is no longer about the aggregate. That is about the one person saving their self the -1 trillion points value. But for the person making this decision, isn't the idea that a society in which these decisions are made by people (and not God, say) substantially worse than even half of that society getting killed off? Like, if I think there are personal moral laws that absolutely cannot be transgressed, I only think that because I believe acting in a contrary way will be extremely unpleasurable (be it spiritually, emotionally, or for the greater society). And perhaps I believe that a society of people that have license to kill off the one for the many is damaged in a way that is way worse for the aggregate than half of its population dying.
I almost wonder if this can't be distilled to: for any value claim, is there not a normative claim attached necessarily? I believe this is the is/ought debate, right? If I refrain from doing something that I think is bad, is it not always because I also believe that everyone doing that thing would also be bad, which means utilitarianism can't be escaped? Any normative belief I have is also a belief that the aggregate is better off (i.e. experiences more pleasure or less displeasure) for having this.
|
2019/04/17
|
[
"https://philosophy.stackexchange.com/questions/61925",
"https://philosophy.stackexchange.com",
"https://philosophy.stackexchange.com/users/30741/"
] |
The difference is that a utilitarian who endorses inalienable rights can conceive of a world in which that endorsement ends up morally wrong, even if our actual world endorses inalienable rights. By contrast, deontologists about rights say such a world is quite literally inconceivable. Indeed, on a basic utilitarian analysis, we can imagine a case in which inalienable rights are *unjustified*, even if such a case never obtains. In a world in which the enforcement of a right led to negative utility in the aggregate, it would have to be admitted that the prescription of utilitarianism in this case would be not only that violation of the right was permissible but *obligatory*. The deontologist about rights says such a situation is quite literally inconceivable: there is no possible world in which it is morally permissible to violate the right of another. Hence, talk of inalienable rights in utilitarianism reduces to shorthand for talk about utility. The deontologist would argue that this is unacceptable: rights are valuable not for their utility but because they, say, preserve human dignity.
Now you might want to then pose the question: why do we want to preserve human dignity in the first place? And you might want to argue: we want to preserve human dignity because societies that preserve human dignity tend to lead to greater aggregate utility. This would be a particular theory, but you can't simply assert that this is what's going on, you'd have to argue for that claim.
My sense is that you are confusing *ethical* and *psychological* hedonism. A psychologist, for example, might be able to collect data to support the claim that---as a matter of empirical fact---most people reason in a hedonist-utilitarian fashion about moral matters, even if they don't explicitly hold utilitarianism as a moral theory or even if they explicitly hold some competing moral theory (such as deontology or virtue ethics). In other words, it may be that what in fact motivates us psychologically is pleasure and pain. Hence, it may be that, statistically speaking, the reason most people end up behaving in such a way that endorses inalienable rights is based on utilitarian considerations. But that is a separate matter from whether utilitarianism can actually give us a theory that *grounds* the value of inalienable rights.
Hence, this quote:
>
> Like, if I think there are personal moral laws that absolutely cannot be transgressed, I only think that because I believe acting in a contrary way will be extremely unpleasurable (be it spiritually, emotionally, or for the greater society).
>
>
>
...is the kind of hanging chad in your case. You claim that the only reason you believe in a moral law is because you in turn believe that acting in a way contrary to that law will lead to negative utility. But have you really separated out psychological from ethical hedonism here? Do you just take it that your behaviors *are* motivated by pleasure and pain? if so, that means you're a psychological hedonist. But *ought* your actions be motivated by pleasure and pain? Well that's a different question, and to jump from psychological to ethical hedonism is simply begging the question in favor of utilitarianism. First you need to clearly separate in your mind the question of how people psychologically deliberate about things, from the question of moral value. You would need to make the case that moral laws are *grounded* in utility, rather than just argue that people in fact reason in utilitarian ways. Indeed, Mill tries to do this himself when he claims that all Kant's derivations of moral duties from the categorical imperative implicitly rely on reasoning about the aggregate consequences of an action on the resulting world in which such moral laws were implemented globally and without exception.
|
21,824,701 |
I want to traverse through .gz file and read the contents of file.
My folder structure:
1) ABC.gz
1.1) ABC
1.1.1) Sample1.txt
1.1.2) Sample2.txt
1.1.3) Test1.txt
I wanted to traverse through .gz , then read and print the contents of Sample\*.txt file.
Test\*.txt should be ignored. Importantly i do not want to copy / extract the gz to a different location.
Perl script i have to read the file:
```
use strict;
use warnings;
my $filename = 'Sample1.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";
while (my $row = <$fh>) {
chomp $row;
print "$row\n";
}
```
|
2014/02/17
|
[
"https://Stackoverflow.com/questions/21824701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3318108/"
] |
First of all a gzip file is a compressed version of a single file. From your description you most likely have a tar archive which was then compressed.
The second point is that you will have to decompress it, either in memory or a temporary file.
You will definitely not be able to read it row by row.
Take a look at [Tie::Gzip](http://search.cpan.org/~softdia/Tie-Gzip-0.06/lib/Tie/Gzip.pm) for the handling of compressed files and at [Archive::Tar](http://search.cpan.org/~bingos/Archive-Tar-1.96/lib/Archive/Tar.pm) for tar archives.
|
8,754,159 |
I am using VS2005 C#
I have a GridView and I have enabled row editing.
However, I have some columns which will have a larger input, such as *Comments* column, which will contain more words.
Is there a way to adjust the textbox sizes?
|
2012/01/06
|
[
"https://Stackoverflow.com/questions/8754159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/872370/"
] |
If you want control over width *and* height, as well as other properties, you can reference the TextBox in your GridView's RowDataBound event and set its height and width as well as setting the TextMode to MultiLine:
```
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit)
{
// Comments
TextBox comments = (TextBox)e.Row.Cells[column_index].Controls[control_index];
comments.TextMode = TextBoxMode.MultiLine;
comments.Height = 100;
comments.Width = 400;
}
}
```
Ensure you're referencing the edit row by checking the RowState or EditIndex, and set your column\_index and control\_index appropriately. For BoundFields, the control index will typically be 0.
|
20,652,297 |
I have 100 machines to be automatically controlled using passwordless ssh.
However, since passwordless ssh requires id\_rsa handshaking, it takes some time for controlling a machine as we can see in the following.
```
$ time ssh remote hostname
remote
real 0m0.294s
user 0m0.020s
sys 0m0.000s
```
It takes approximately 0.3 seconds, and doing this all over 100 machines takes around 30 seconds.
What I'm looking for is to make the account on the remote machine no password at all.
Is there a way to do it?
|
2013/12/18
|
[
"https://Stackoverflow.com/questions/20652297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023045/"
] |
There is a way: use [telnet](http://en.wikipedia.org/wiki/Telnet). It provides the same as ssh without authentication and encryption.
|
9,497 |
So, a teacher explained to me that 究竟 is a more formal way of saying 到底. However, I'm still curious if there are there any other usage differences between the two? Is 究竟 only used in examples that are relatively “夸张”
>
> E.g. 你究竟为什么要离开我。
>
>
>
|
2014/09/10
|
[
"https://chinese.stackexchange.com/questions/9497",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/6003/"
] |
1) "究竟" is more formal than "到底". In everyday spoken Chinese, "究竟" is rarely used. It is used almost only in drama and written Chinese.
2) Well, I would say that the magnitude of "究竟" is equal to that of "到底". They are all equivalent to "on the earth".
|
95,010 |
I'm trying to understand different methods of calculating interest on installment loans. I keep coming across the terms "simple interest" and "actuarial method". They seem to be related but I haven't found a clear explanation. Here's an example of something I read on another website that has me confused:
>
> **Simple interest** is computed on the actual balance outstanding on the payment due date. **Precomputed interest** is calculated on the original principal balance. The interest is added to the original principal balance and divided by the number of payments to determine the payment amount. ... the Rule of 78s is no longer an acceptable method of accounting for loan income. The acceptable method for accounting for loan income is the **actuarial method**.
>
>
>
|
2018/05/01
|
[
"https://money.stackexchange.com/questions/95010",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/42805/"
] |
Definitions of simple interest differ, e.g. the naïve version here: [What is 'Simple Interest'](https://www.investopedia.com/terms/s/simple_interest.asp).
```
Simple Interest = P x I x N
where
P is the principal
I is the periodic interest rate
N is the number of periods
```
(*an example is included below*)
However, by contrast, insofar as "*Simple interest is computed on the actual balance outstanding on the payment due date.*", this is what is used by standard (actuarial) methods.
The simple interest (actuarial) method also differs from the Rule of 78s.
As described here: [Rule of 78s - Precomputed Loan](https://en.wikipedia.org/wiki/Rule_of_78s#Precomputed_Loan)
>
> Finance charge, carrying charges, interest costs, or whatever the cost
> of the loan may be called, can be calculated with simple interest
> equations, add-on interest, an agreed upon fee, or any disclosed
> method. Once the finance charge has been identified, the Rule of 78s
> is used to calculate the amount of the finance charge to be rebated
> (forgiven) in the event that the loan is repaid early, prior to the
> agreed upon number of payments.
>
>
>
So taking a simple example: a 12 month loan repaid early, after 9 months.
```
principal s = 995.40
no. months n = 12
int. rate r = 0.03 per month
```
By simple interest (actuarial) methods, using formula 1 (derived below).
```
repayments d = r (1 + 1/((1 + r)^n - 1)) s = 100
total int. t = d n - s = 204.60
```
However if the loan is repaid early, after 9 months, using formula 2.
```
x = 9
total int. t = ((1 + r)^x - 1) s + (d (1 - (1 + r)^x + r x))/r = 187.46
```
So the interest saved by repaying early is
```
204.60 - 187.46 = 17.14
```
If this was calculated by the Rule of 78s, with the finance charge taken as the total interest due for the 12 month loan.
```
precomputed interest f = 204.60
precomuputed loan = s + f = 955.40 + 204.60 = 1160
interest forgiven = f (3/78 + 2/78 + 1/78) = 15.74
```
So in this case it disadvantages the borrower to use the Rule of 78s.
Note the finance charge calculated by the naïve simple interest method in the aforementioned link: [What is 'Simple Interest'](https://www.investopedia.com/terms/s/simple_interest.asp)
```
Simple Interest = P x I x N = 955.40 x 0.03 x 12 = 343.94
```
This is a long way from 204.60, but then the demo interest rate is quite high, accentuating the disparity. The naïve simple interest method is otherwise disregarded in this answer.
Demonstrating the interest calculations graphically, it can be observed that the interest payments calculated for months 10, 11 & 12 by the Rule of 78s are less than the simple interest/actuarial calculations.
[](https://i.stack.imgur.com/BIIdM.png)
Formulae derivations
[](https://i.stack.imgur.com/hlcAX.png)
|
39,515,915 |
I want to make sure if there are better way of my below code , a way to send data to server the below is working , but can be better?
```
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String json = "";
String s_calc=String.valueOf(calc);;
try {
RequestBody formBody = new FormEncodingBuilder()
// .add("tag","login")
.add("likes", "9")
.add("id", id)
.build();
Request request = new Request.Builder()
.url("http://justedhak.com/old-files/singleactivity.php")
.post(formBody)
.build();
Response responses = null;
try {
responses = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
String jsonData = responses.body().string();
JSONObject Jobject = new JSONObject(jsonData);
int success = Jobject.getInt("success");
if (success == 1) {
// this means that the credentials are correct, so create a login session.
JSONArray JAStuff = Jobject.getJSONArray("stuff");
int intStuff = JAStuff.length();
if (intStuff != 0) {
for (int i = 0; i < JAStuff.length(); i++) {
JSONObject JOStuff = JAStuff.getJSONObject(i);
//create a login session.
// session.createLoginSession(name, pass);
}
}
} else {
// return an empty string, onPostExecute will validate the returned value.
return "";
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
}
//this return will be reached if the user logs in successfully. So, onPostExecute will validate this value.
return "RegisterActivity success";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// if not empty, this means that the provided credentials were correct. .
if (!result.equals("")) {
finish();
return;
}
//otherwise, show a popup.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SingleObjectActivity.this);
alertDialogBuilder.setMessage("Wrong username or password, Try again please.");
// alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface arg0, int arg1) {
// alertDialog.dismiss();
// }
// });
// alertDialog = alertDialogBuilder.create();
// alertDialog.show();
}
}
```
|
2016/09/15
|
[
"https://Stackoverflow.com/questions/39515915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2291869/"
] |
You can use [AutoMapper](http://automapper.org/):
```
public Dog UsingAMR(Person prs)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Person, Dog>();
});
IMapper mapper = config.CreateMapper();
return mapper.Map<Person, Dog>(prs);
}
```
Then you can easily:
```
Person ps = new Person {Name = "John", Number = 25};
Dog dog = UsingAMR(ps);
```
Just don't forget to **install `AutoMapper` first** from the package manager console as mentioned in the reference:
1. From *Tools* menu click on *NuGet Package Manager* ==> *Package Manager Console*
2. Then type the following command:
```
PM> Install-Package AutoMapper
```
|
21,814,672 |
I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service.
**This is my Controller class**
```
@RequestMapping("/*")
public class Opinion {
private FeedbackService fs;
public Opinion(FeedbackService fs){
this.fs=fs;
}
@RequestMapping(value="/givefeedback",method=RequestMethod.POST)
public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException
{
ObjectInputStream in=new ObjectInputStream(request.getInputStream());
serialize.Feedback feedback=(serialize.Feedback)in.readObject();
fs.writeFeedback(feedback);
response.setStatus(200);
}
```
**My mvc-config.xml**
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="poll_Web" class="sef.controller.Opinion">
<constructor-arg ref="feedbackService" />
</bean>
<context:component-scan base-package="sef.controller" />
</beans>
```
**My web.xml**
```
<servlet>
<servlet-name>opinionDispacher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>opinionDispacher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml
</param-value>
</context-param>
```
I am using the URL `localhost:8080/feedback/givefeedback`. The app is deployed as **feedback.war**. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
|
2014/02/16
|
[
"https://Stackoverflow.com/questions/21814672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1139023/"
] |
Downloading java dependencies is possible, if you actually really need to download them into a folder.
Example:
```
apply plugin: 'java'
dependencies {
runtime group: 'com.netflix.exhibitor', name: 'exhibitor-standalone', version: '1.5.2'
runtime group: 'org.apache.zookeeper', name: 'zookeeper', version: '3.4.6'
}
repositories { mavenCentral() }
task getDeps(type: Copy) {
from sourceSets.main.runtimeClasspath
into 'runtime/'
}
```
Download the dependencies (and their dependencies) into the folder `runtime` when you execute `gradle getDeps`.
|
23,565,370 |
I have a question regarding something I'm seeing in some VB.NET code on a project that I've had to take over. In a form the developer has declared a very simple 15sec timer.
```
Private WithEvents mtmrManualDecision As New System.Timers.Timer(15000)
```
Now, I know that this timer will trigger the mtmrManualDecision\_Elapsed event each 15 seconds after it has been started via mtmrManualDecision.Start(). I'm also familiar with stopping this timer via mtmrManualDecision.Stop(). However, I'm seeing this line of code in parts of the form (like when a button is clicked or the form is closed).
```
RemoveHandler mtmrEvaluation.Elapsed, AddressOf mtmrEvaluation_Elapsed
```
I believe this is basically stopping the timer. Why do this instead of just stop? It's not being added back or used again after this so I'm wondering why the need to do this. I don't normally use RemoveHandler unless I actually used AddHandler in my own code. I believe that the declaration of the timer using "WithEvents" automatically adds a handler for the Elapsed event and he just wants to remove it. Is this really necessary and wouldn't the garbage collection take care of removing the handler like it does with other events, etc.)?
Any clarification or ideas would be appreciated. Thank you very much.
|
2014/05/09
|
[
"https://Stackoverflow.com/questions/23565370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1218207/"
] |
>
> I believe this is basically stopping the timer.
>
>
>
No, it does not stop the timer. The timer does not stop until your program stops it, or disposes of it. Once you remove the handler, the timer will stop delivering the events to your program, but it would continue "ticking" in the background.
For example, if you remove the handler 3 seconds into the 15-second interval, and then add it back 2 seconds later, you will get an event after 10 more seconds (3 + 2 + 10 = 15).
One reason to remove a handler is to let its associated object, if any, become eligible for garbage collection. This prevents a "lingerer" memory leak. For example, consider a timer that produces an object, and stores it into a list associated with another object, which is owned by your main program. Let's say that at some point your main program drops the object hosting the list. However, the list may not become eligible for garbage collection if the event handler keeps a strong reference to the object. Unregistering for the event explicitly is one way of addressing this problem; another way is to use a [Weak Event Pattern](http://msdn.microsoft.com/en-us/library/aa970850%28v=vs.110%29.aspx).
|
20,596,588 |
I would like to be able to insert a row into an SQL table, giving it a specified id. The trouble is that the id is unique and for it to work I'd have to update the rows after the inserted row, increasing the id's by 1.
So, say I have a table like the following

I would like to insert the following row (with the id of an existing row)...

I want the table to look like this after I have inserted the row...

The id's of the rows after the inserted row need to change,like in the above example.
The reason for me doing this is to allow users to order events by importance (I'm using jQuery to order them, just not sure how to do the stuff behind the scenes)
Anything that sets me off in the right direction is appreciated, thanks in advance.
|
2013/12/15
|
[
"https://Stackoverflow.com/questions/20596588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1997661/"
] |
Firstly, best practice is to **never ever** modify the primary key of a row once it is inserted (I assume `id` is your primary key?). *Just Don't Do It™*.
**Instead**, create an additional column (called `importance`/`priority`/something, and modify that field as necessary.
---
That said, the query would look something like:
```
START TRANSACTION;
# increment every importance value that needs incrementing to make way for the new row:
UPDATE mytable SET importance = importance + 1 WHERE importance >= newimportance;
# insert the new row:
INSERT INTO mytable (title, text, importance) VALUES ('newtitle', 'newtext', newimportance);
COMMIT;
```
|
42,845,942 |
Good afternoon, I'm learning and using pyttsx for speech, the thing is that I want to use it as a "female" voice but I can not do it using this code:
```
import pyttsx as pt
from pyttsx import voice
engine = pt.init()
voices = engine.getProperty('voices')
#engine.setProperty('gender', 'female') # also does not work
engine.setProperty('female', voice.Voice.gender) #not even
engine.setProperty('female', voice.gender) #does not work
engine.setProperty('voice', voices[4].id)
engine.say("Hello World")
engine.runAndWait()
class Voice(object):
def __init__(self, id, name=None, languages=[], gender=None, age=None):
self.id = id
self.name = name
self.languages = languages
self.gender = gender
self.age = age
```
|
2017/03/16
|
[
"https://Stackoverflow.com/questions/42845942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7724033/"
] |
I used the following code to iterate through the voices to find the female voice
```
import pyttsx
engine = pyttsx.init()
voices = engine.getProperty('voices')
for voice in voices:
engine.setProperty('voice', voice.id)
print voice.id
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()
```
On my Windows 10 machine the female voice was HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS\_MS\_EN-US\_ZIRA\_11.0
So I changed my code to look like this
```
import pyttsx
engine = pyttsx.init()
engine.setProperty('voice', 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0')
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()
```
|
206,614 |
After re-installing Lubuntu 12.04 system on my laptop an older problem re-emerged after a few days and installation of different programs: without apparent reason the external mouse and sometimes other usb connected devices (including hdd) stop working. The hdd shows it has tension as it has a light there, and the external mouse flashes for a second when plugged.
[I have posted a different version of this problem before](https://askubuntu.com/q/178054/47206). I keep it for now as example of the two answers there. None of them works here.
**Logging out-in does nothing, restart does.**
The event seems entirely random, after reboot it will reappear after many days or weeks or, rarely, after a few hours.
* <http://pastebin.com/0qR8bhhX> in `var/log/syslog` after new occurrence (**with only external wired mouse and keyboard**)
What counts is at the end I guess:
```
Nov 24 14:06:55 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29953.822962] usb 3-1: USB disconnect, device number 3
Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069427] uhci_hcd 0000:00:1d.0: host controller process error, something bad happened!
Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069439] uhci_hcd 0000:00:1d.0: host controller halted, very bad!
Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069461] uhci_hcd 0000:00:1d.0: HC died; cleaning up
Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069492] usb 2-2: USB disconnect, device number 2
```
* I have noticed that **on most occasions only the external mouse and keyboard are affected, but not the external HDD. Or if it is, replugging it solves the problem**.
* I have a dual boot with WinXP: **in Windows this never happens, so it is not a hardware issue**
* **I have used Lubuntu Quantal 12.10 and the same problem happened there as well**. Upgrading to that would not be a solution
* On certain occasion **only restarting 2 or even 3 times** solved it.
---
**Using the same PC/hardware with Linux Mint 14 (Quantal) Xfce, the problem almost disappeared**(it happened *once* since then). I am not sure whether this 'solution' comes from using Xfce or Mint (I guess Mint 14 Nadia uses the same kernel as Lubuntu Quantal).
|
2012/10/26
|
[
"https://askubuntu.com/questions/206614",
"https://askubuntu.com",
"https://askubuntu.com/users/-1/"
] |
Power issues for USB 2.0
------------------------
USB 2.0 has a maximum current draw available of 500mA, however it should be noted that the +5V on several ports may actually be on the same bus. For example on a desktop case the USB ports on the front of the machine may all be on the same bus, while the ports on the back of the machine will normally be a a different bus, or have completely separate +5V supplies for each group of USB 2.0 sockets.
A low current device as defined by the USB 2.0 [standards](http://www.usb.org/developers/docs/) can draw up to 100mA (1 unit) while high current devices can draw up to 5 units (500mA). Hard drives with no external source of supply are typically high current devices.
Devices should stop working if the +5V line drops below 4.75V and this is why many high power devices can cause problems on some computers.
In addition to this the circuit that supplies +5V to each bus may refuse to re-negotiate high power capability if the device is drawing enough current to pull the +5V line too low. This is why high power devices will need to be removed and re-attached before they will work if they have failed due to a power problem, and also why a reboot does not allow them to re-attach while a full power down/up cycle may do so.
Note that if one or more low power devices are already plugged into a USB bus, there may not be enough capacity available to also run a high power device such as an external hard drive.
Using high power devices therefore needs to be planned for, and if problems exist the device needs to be used on it's own on any one bus or given a separate +5V supply.
While the USB 2.0 standards document might be a little difficult to read, there is some very good information and explanations in the [wikipedia page on the subject of USB 2.0](http://en.wikipedia.org/wiki/Universal_Serial_Bus#Power)
Also note that plugging in many low power devices such as through an external USB hub device can also cause a voltage drop on the bus supply line, causing some or all of the devices to be disabled.
The types of cables used may also affect the reliability of high power devices. For example an external hard drive plugged in via a regular long USB cable may see enough of a voltage drop at 500mA to disable itself to prevent damage to its circuitry or drive motors. These devices are typically supplied with a special short cable, or a 'Y' cable that plugs into two USB ports to help with the power problem. Note that this only a partial solution to the problem relating specifically to the cabling issue, it's doesn't actually allow more than 500mA to be supplied since adjacent USB ports are likely to be on the same 5V 500mA supply internally in the computer. Even where a separate bus is used for the second plug on the 'Y' cable it won't be able to get a high current supply since it has no data connection to request it from the USB bus. Only one of the ports will be enabled as a high current supply.
Since the very common use of USB keyboards and mice, problems can sometimes occur when these are both plugged into the same bus. Peak load currents at power-on can exceed the design specification of the USB bus and cause one or both of the devices to be disabled or to malfunction.
Solutions to these problems usually involve using only a minimum of low power devices, using only well designed and made low power devices, making sure they are plugged into different buses with separate +5V lines, and where high power devices are involved using a powered hub to help with the supply problems seen on many USB 2.0 bus supplies. If it's not possible to use a powered hub, then the high power device should only be plugged in after the computer is powered up and the current drain from low power devices has stabilised.
It should also be noted here that computers such as laptops and netbooks may have low power USB devices incorporated internally. Hardware such as internal card readers, wireless 3G adapters, and webcams are often connected internally to a USB bus. This may be a dedicated bus with it's own +5V power, or it may be shared with one or more external USB ports.
|
31,399,266 |
I installed *postgresql-common* and *postgresql-9.4* with the package manager *apt-get*.
I changed my database system from OSX to Debian 8.1 after which I have had difficulties with Permission denied errors.
The user *postgres* exists (`CREATE USER postgres;`) and database *detector* exists `CREATE DATABASE detector WITH OWNER=postgres;`).
I run successfully
```
masi@pc212:~$ sudo -u postgres psql detector -c "DROP TABLE measurements;"DROP TABLE
masi@pc212:~$ sudo -u postgres psql detector -c "CREATE TABLE measurements ( m_id SERIAL PRIMARY KEY NOT NULL, m_size INTEGER NOT NULL );"
CREATE TABLE
```
but the same unsuccessfully in Dropbox -directory
```
masi@pc212:~$ cd Dropbox/
masi@pc212:~/Dropbox$ sudo -u postgres psql detector -c "DROP TABLE measurements;"
could not change directory to "/home/masi/Dropbox": Permission denied
DROP TABLE
masi@pc212:~/Dropbox$ sudo -u postgres psql detector -c "CREATE TABLE measurements ( m_id SERIAL PRIMARY KEY NOT NULL, m_size INTEGER NOT NULL );"
could not change directory to "/home/masi/Dropbox": Permission denied
CREATE TABLE
```
Settings
--------
The command `psql` is in the SECURE\_PATH in */etc/sudoers*:
```
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
```
The command `which psql` gives `/usr/bin/psql`.
The real directory where I keep the code is */home/masi/Dropbox/det/* where possibly the Dropbox installation is affecting thing:
* drwxr-xr-x 32 masi masi 4096 Jul 14 10:27 masi/
* drwx------ 26 masi masi 4096 Jul 13 16:05 Dropbox/
* drwxr-xr-x 8 masi developers 4096 Jul 14 09:22 det/
where I can change the Dropbox to
* drwx------ 26 masi developers 4096 Jul 13 16:05 Dropbox/
but not able to increase permissions because I start to get *ls: cannot access ../../Dropbox/: Permission denied* although having fully open permissions.
This is a very strange behaviour that here fully open permissions lead to such a behaviour.
Similar errors
* this [thread](https://askubuntu.com/q/633824/25388) about nautilus-dropbox but no *nautilus-dropbox* in my system
Why Dropbox is causing such a problem to PostgreSQL?
|
2015/07/14
|
[
"https://Stackoverflow.com/questions/31399266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54964/"
] |
Some piece of answer in Petesh's comment but also read -flag is required.
Run
```
sudo chmod -R go=rx /home/masi/Dropbox
```
but avoid recursive if you can.
The command allows the subsequent `sudo -u postgres` commands. *You generally have to open up access to the directory and all parent directories enough to allow commands to work with files in the directory.* Execute s not enough in all cases; read -flag is also required.
|
23,759,319 |
I found this tabbed content and so far set it up but for the life of me cannot figure out how to change the colour of the tab to a difference colour when you hover over it.
I thought it would be the tabs label:hover but it doesn't seem to be.
My code is here:
```
body, html {
height: 100%;
margin: 0;
-webkit-font-smoothing: antialiased;
font-weight: 100;
background: #ffffff;
text-align: center;
font-family: helvetica;
}
.tabs input[type=radio] {
position: absolute;
top: -9999px;
left: -9999px;
}
.tabs {
width: 670px;
float: none;
list-style: none;
position: relative;
padding: 0;
margin: 75px auto;
}
.tabs li{
float: left;
}
.tabs label {
display: block;
padding: 10px 20px;
border-radius: 0px 0px 0 0;
color: #ffffff;
font-size: 18px;
font-weight: normal;
font-family: helvetica;
background: #f3f3f3;
cursor: pointer;
position: relative;
top: 3px;
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}
.tabs label:hover {
background: #9eab05);
top: 1px;
}
/* LABEL COLOURS */
[id^=tab]:checked + label {
background: #e3ba12;
color: white;
top: 0;
}
[id^=tabfindme]:checked + label {
background: #e3ba12;
color: white;
top: 0;
}
[id^=tabtwitter]:checked + label {
background: #0085a1;
color: white;
top: 0;
}
[id^=tabtv]:checked + label {
background: #6a2150;
color: white;
top: 0;
}
[id^=tabteach]:checked + label {
background: #d10373;
color: white;
top: 0;
}
[id^=tab]:checked ~ [id^=tab-content] {
display: block;
}
/* CONTENT COLOURS */
.findmecontent{
z-index: 2;
display: none;
text-align: left;
width: 100%;
font-size: 12px;
line-height: 140%;
padding-top: 0px;
background: #e3ba12;
padding: 15px;
color: white;
position: absolute;
top: 40px;
left: 0;
box-sizing: border-box;
-webkit-animation-duration: 0.5s;
-o-animation-duration: 0.5s;
-moz-animation-duration: 0.5s;
animation-duration: 0.5s; }
.twittercontent{
z-index: 2;
display: none;
text-align: left;
width: 100%;
font-size: 12px;
line-height: 140%;
padding-top: 0px;
background: #0085a1;
padding: 15px;
color: white;
position: absolute;
top: 40px;
left: 0;
box-sizing: border-box;
-webkit-animation-duration: 0.5s;
-o-animation-duration: 0.5s;
-moz-animation-duration: 0.5s;
animation-duration: 0.5s;
}
.tvcontent{
z-index: 2;
display: none;
text-align: left;
width: 100%;
font-size: 12px;
line-height: 140%;
padding-top: 0px;
background: #6a2150;
padding: 15px;
color: white;
position: absolute;
top: 40px;
left: 0;
box-sizing: border-box;
-webkit-animation-duration: 0.5s;
-o-animation-duration: 0.5s;
-moz-animation-duration: 0.5s;
animation-duration: 0.5s;
}
.teachcontent{
z-index: 2;
display: none;
text-align: left;
width: 100%;
font-size: 12px;
line-height: 140%;
padding-top: 0px;
background: #d10373;
padding: 15px;
color: white;
position: absolute;
top: 40px;
left: 0;
box-sizing: border-box;
-webkit-animation-duration: 0.5s;
-o-animation-duration: 0.5s;
-moz-animation-duration: 0.5s;
animation-duration: 0.5s;
}
<ul class="tabs">
<li>
<input type="radio" checked name="tabs" id="tabfindme">
<label for="tabfindme">FIND ME</label>
<div id="tab-content1" class="findmecontent animated fadeIn">
You can find me at the following venues:
<ul>
<li>BBC Television Centre</li>
<li>OutBurst Festival</li>
</ul>
</div>
</li>
<li>
<input type="radio" name="tabs" id="tabtwitter">
<label for="tabtwitter">TWITTER</label>
<div id="tab-content2" class="twittercontent animated fadeIn">
Twitterfeed
</div>
</li>
<li>
<input type="radio" name="tabs" id="tabtv">
<label for="tabtv">TELEVISION</label>
<div id="tab-content3" class="tvcontent animated fadeIn">
Click the links to see me on TV
<ul>
<li>BBC Television Centre</li>
<li>ITV</li>
</ul>
</div>
</li>
<li>
<input type="radio" name="tabs" id="tabteach">
<label for="tabteach">HOW I TEACH</label>
<div id="tab-content4" class="teachcontent animated fadeIn">
How I teach
</div>
</li>
</li>
```
|
2014/05/20
|
[
"https://Stackoverflow.com/questions/23759319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3319013/"
] |
```
.tabs label:hover {
background: #9eab05;
top: 1px;
}
```
there is a ")" <-- remove it
fiddle
<http://jsfiddle.net/n5ura/>
```
body, html {
height: 100%;
margin: 0;
-webkit-font-smoothing: antialiased;
font-weight: 100;
background: #ffffff;
text-align: center;
font-family: helvetica;
}
.tabs input[type=radio] {
position: absolute;
top: -9999px;
left: -9999px;
}
.tabs {
width: 670px;
float: none;
list-style: none;
position: relative;
padding: 0;
margin: 75px auto;
}
.tabs li{
float: left;
}
.tabs label {
display: block;
padding: 10px 20px;
border-radius: 0px 0px 0 0;
color: #ffffff;
font-size: 18px;
font-weight: normal;
font-family: helvetica;
background: #f3f3f3;
cursor: pointer;
position: relative;
top: 3px;
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}
.tabs label:hover {
background: #9eab05;
top: 1px;
}
/* LABEL COLOURS */
[id^=tab]:checked + label {
background: #e3ba12;
color: white;
top: 0;
}
[id^=tabfindme]:checked + label {
background: #e3ba12;
color: white;
top: 0;
}
[id^=tabtwitter]:checked + label {
background: #0085a1;
color: white;
top: 0;
}
[id^=tabtv]:checked + label {
background: #6a2150;
color: white;
top: 0;
}
[id^=tabteach]:checked + label {
background: #d10373;
color: white;
top: 0;
}
[id^=tab]:checked ~ [id^=tab-content] {
display: block;
}
/* CONTENT COLOURS */
.findmecontent{
z-index: 2;
display: none;
text-align: left;
width: 100%;
font-size: 12px;
line-height: 140%;
padding-top: 0px;
background: #e3ba12;
padding: 15px;
color: white;
position: absolute;
top: 40px;
left: 0;
box-sizing: border-box;
-webkit-animation-duration: 0.5s;
-o-animation-duration: 0.5s;
-moz-animation-duration: 0.5s;
animation-duration: 0.5s; }
.twittercontent{
z-index: 2;
display: none;
text-align: left;
width: 100%;
font-size: 12px;
line-height: 140%;
padding-top: 0px;
background: #0085a1;
padding: 15px;
color: white;
position: absolute;
top: 40px;
left: 0;
box-sizing: border-box;
-webkit-animation-duration: 0.5s;
-o-animation-duration: 0.5s;
-moz-animation-duration: 0.5s;
animation-duration: 0.5s;
}
.tvcontent{
z-index: 2;
display: none;
text-align: left;
width: 100%;
font-size: 12px;
line-height: 140%;
padding-top: 0px;
background: #6a2150;
padding: 15px;
color: white;
position: absolute;
top: 40px;
left: 0;
box-sizing: border-box;
-webkit-animation-duration: 0.5s;
-o-animation-duration: 0.5s;
-moz-animation-duration: 0.5s;
animation-duration: 0.5s;
}
.teachcontent{
z-index: 2;
display: none;
text-align: left;
width: 100%;
font-size: 12px;
line-height: 140%;
padding-top: 0px;
background: #d10373;
padding: 15px;
color: white;
position: absolute;
top: 40px;
left: 0;
box-sizing: border-box;
-webkit-animation-duration: 0.5s;
-o-animation-duration: 0.5s;
-moz-animation-duration: 0.5s;
animation-duration: 0.5s;
}
```
|
44,236,756 |
How do I scroll through a modal window that is created using Bootstrap's modal class? Generally we use the JavascriptExecutor and use the window.scroll/scrollBy method. But when I tried the same when a modal is popped up with long content, the scroll is happening in the actual webpage which is not focused. How do I scroll through content in a modal popup that has long content?
Example - Modal popup here: <https://v4-alpha.getbootstrap.com/components/modal/#scrolling-long-content>
|
2017/05/29
|
[
"https://Stackoverflow.com/questions/44236756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2110723/"
] |
This script captures the `-i` command, while still allowing `unittest.main` to do its own commandline parsing:
```
import unittest
class Testclass(unittest.TestCase):
@classmethod
def setUpClass(cls):
print "Hello Class"
def test_addnum(self):
print "Execute the test case"
#parser = parse_args(['-i'])
print 'simple_value =', args.inputfile
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-i', help='input file', dest='inputfile')
ns, args = parser.parse_known_args(namespace=unittest)
#args = parser.parse_args()
return ns, sys.argv[:1] + args
if __name__ == '__main__':
import sys
args, argv = parse_args() # run this first
print(args, argv)
sys.argv[:] = argv # create cleans argv for main()
unittest.main()
```
produces:
```
1113:~/mypy$ python stack44236745.py -i testname -v
(<module 'unittest' from '/usr/lib/python2.7/unittest/__init__.pyc'>, ['stack44236745.py', '-v'])
Hello Class
test_addnum (__main__.Testclass) ... Execute the test case
simple_value = testname
ok
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
```
It looks rather kludgy, but does seem to work.
The idea is to run your own parser first, capturing the `-i` input, and putting the rest back into `sys.argv`. Your definition of `parse_args` suggests that you are already trying to do that.
|
17,069,514 |
We have two tables.
```
1. information
title body name
title1 body1 author1
title2 body2 author1
title1 body1 author2
title1 body1 author3
2. interactions
name favorited user_favorited_by
author1 yes user1
author2 yes user1
author1 yes user2
author1 no user3
```
The question is: who is for each user the favourite author or authors?
The query should give us the following answer based on the example:
```
user1 author1
user1 author2
user2 author1
```
Any help appreciated.
|
2013/06/12
|
[
"https://Stackoverflow.com/questions/17069514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235532/"
] |
Here is a JOIN that works:
```
SELECT DISTINCT user_favorited_by, a.name
FROM information a
JOIN interactions b
ON a.name = b.name
WHERE favorited = 'yes'
```
Since you only have 'name' to join on, you need DISTINCT, or you could GROUP BY selected fields to remove duplicate lines from your output.
And here is a demo: [SQL Fiddle](http://sqlfiddle.com/#!2/ca2be/3/0)
|
64,195,427 |
The following code compiles:
```
val collection = listOf("a", "b")
val filter = { x: String -> x.isEmpty() }
collection.filter(filter)
```
Is it possible to define the filter using a function interface?
For example the following code doesn't compile:
```
fun interface MyFilter {
fun execute(string: String): Boolean
}
```
and
```
val filter = MyFilter { x -> x.isEmpty() }
```
gives a compilation error
```
Type mismatch.
Required:
(TypeVariable(T)) → Boolean
Found:
MyFilter
```
|
2020/10/04
|
[
"https://Stackoverflow.com/questions/64195427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4680812/"
] |
You can inherit `MyFilter` from `(String) -> Boolean`
```
fun interface MyFilter : (String) -> Boolean
fun main() {
val collection = listOf("a", "b")
val filter = MyFilter { x -> x.isEmpty() }
val newCollection = collection.filter(filter)
}
```
With your custom method:
```
fun interface MyFilter : (String) -> Boolean {
override operator fun invoke(p1: String): Boolean = execute(p1)
fun execute(param: String): Boolean
}
```
But it works only with `jvmTarget = 1.8 (or higher)` and `-Xjvm-default=all`
|
32,116,842 |
I have subroutine in my module which checks (regular) user password age using regex search on `shadow` file:
**Module.pm**
```
my $pwdsetts_dump = "tmp/shadow_dump.txt";
system("cat /etc/shadow > $pwdsetts_dump");
open (my $fh1, "<", $pwdsetts_dump) or die "Could not open file '$pwdsetts_dump': $!";
sub CollectPWDSettings {
my @pwdsettings;
while (my $array = <$fh1>) {
if ($array =~ /^(\S+)[:][$]\S+[:](1[0-9]{4})/) {
my $pwdchange = "$2";
if ("$2" eq "0") {
$pwdchange = "Next login";
}
my %hash = (
"Username" => $1,
"Last change" => $pwdchange
);
push (@pwdsettings, \%hash);
}
}
my $current_date = int(time()/86400); # epoch
my $ndate = shift @_; # n-days
my $search_date = int($current_date - $ndate);
my @sorted = grep{$_->{'Last change'} > $search_date} @pwdsettings;
return \@sorted;
}
```
Script is divided in 2 steps:
1. load all password settings
2. search for password which is older than n-days
In my main script I use following script:
```
my ($user_changed_pwd);
if (grep{$_->{'Username'} eq $users_to_check} @{Module::CollectPWDSettings("100")}) {
$user_changed_pwd = "no";
}
else {
$user_changed_pwd = "yes";
}
```
Problem occurs in first step, AoH never gets populated. I'm also pretty sure that this subroutine always worked for me and `strict` and `warnings` never complained about it, nut now, for some reason it refuses to work.
|
2015/08/20
|
[
"https://Stackoverflow.com/questions/32116842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've just run your regex against my `/etc/shadow` and got no matches. If I drop the leading `1` I get a few hits.
E.g.:
```
$array =~ /^(\S+)[:][$]\S+[:]([0-9]{4})/
```
But personally - I would suggest not trying to regex, and instead rely on the fact that [`/etc/shadow`](http://linux.die.net/man/5/shadow) is defined as delimited by `:`.
```
my @fields = split ( /:/, $array );
```
$1 contains a bunch of stuff, and I suspect what you *actually* want is the username - but because `\S+` is greedy, you might be accidentally ending up with encrypted passwords.
Which will be `$fields[0]`.
And then the 'last change' field - from [`man shadow`](http://linux.die.net/man/5/shadow) is `$fields[2]`.
|
29,256,331 |
\*\*I want to build an AngularJS application in which I want to use AngularJS for front end and REST API for back-end data. Please give me suggestions for directory structure \*\*
|
2015/03/25
|
[
"https://Stackoverflow.com/questions/29256331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3156248/"
] |
try to use LINQ
```
var result = data.Skip(data.Count - 10).Take(10);
List<SomeType> list = new List<SomeType>(result.Reverse());
```
|
67,366,685 |
I am running an Angular Application I am getting these popup in vs code whenever I am opening it. However, the ng serve command is working fine and it's serving(running) the app successfully.
But I am getting this error in console.
[](https://i.stack.imgur.com/mX73o.png)
[](https://i.stack.imgur.com/uJkvM.png)
[](https://i.stack.imgur.com/I1exq.png)
|
2021/05/03
|
[
"https://Stackoverflow.com/questions/67366685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13975105/"
] |
Angular Language Service Extension has one bug which is reported to their git repository.
My solution will work for Angular Projects which is running < Version 9.0
To resolve this issue you have two ways.
Solution 1: Downgrade extension version
1. Downgrade [https://marketplace.visualstudio.com/items?itemName=Angular.ng-template](https://i.stack.imgur.com/wyMlG.png) to 11.2.14
2. Remove Node Module
3. Run npm install
4. Run npm start or ng serve
Solution 2: (For Version 12)
1. Open Vs Code
2. Go To Files ==> Preference ==> Setting
3. Under Extension Select Use Legacy View Engine Checkbox.
4. Run npm start (If you're facing any issue then kindly close VS Code and Remove
node\_modules folder and Run npm install
[](https://i.stack.imgur.com/wyMlG.png)
|
1,628,649 |
If you count (4 4 3) as one combination, you cannot count (4 3 4) as another.
My approach is $\dfrac{4^3}{3!}$, but obviously this does not work. I don't know why it doesn't work, and I don't know how I should solve the problem.
|
2016/01/27
|
[
"https://math.stackexchange.com/questions/1628649",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/308347/"
] |
Think about AM-GM, you get
$(\frac{1}{n!})^{\frac{1}n}\le\frac{2}{n+1}$
|
53,937,335 |
**Complicated JOIN query as:**
```
SELECT
FIRST.NAME,
SECOND.FIRST_NAME,
SECOND.LAST_NAME
FROM FIRST_TABLE FIRST
LEFT JOIN SECOND_TABLE SECOND
ON (SECOND.FIRST_NAME = FIRST.NAME OR SECOND.LAST_NAME = FIRST.NAME)
```
Will result with bad performance.
***How to get better performance?***
|
2018/12/26
|
[
"https://Stackoverflow.com/questions/53937335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8142917/"
] |
THIS ANSWERS THE ORIGINAL VERSION OF THE QUESTION.
You may be better off with `exists`:
```
SELECT FIRST.ID, FIRST.NAME
FROM FIRST_TABLE FIRST
WHERE EXISTS (SELECT 1 FROM SECOND_TABLE SECOND WHERE SECOND.FIRST_NAME = FIRST.NAME) OR
EXISTS (SELECT 1 FROM SECOND_TABLE SECOND WHERE SECOND.LAST_NAME = FIRST.NAME);
```
Then for performance, you want indexes on `SECOND_TABLE(LAST_NAME)` AND `SECOND_TABLE(FIRST_NAME)`.
|
3,711,025 |
We have two `div`s. `divOne` contains information of image and `divTwo` contains information of table. Is it possible that we can set divOne as background image of `divTwo` using script?
```
divOne.innerHTML = <IMG src="http://sbc.com/xyz.jpg" />
divTwo.innerHTML = <TABLE id="content"> ....... </TABLE>
```
|
2010/09/14
|
[
"https://Stackoverflow.com/questions/3711025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415921/"
] |
`divOne.style.backgroundImage="url(http://sbc.com/xyz.jpg);";`
That should set divOne to that background image...
---
For the div Positioning give this a try...
```
divOne.style.position = "relative";
divOne.style.top = "0px";
divOne.style.left = "0px";
divOne.style.zIndex="1";
divTwo.style.position = "relative";
divTwo.style.top = "0px";
divTwo.style.left = "0px";
divTwo.style.zIndex="2";
```
|
14,163,007 |
Textbox or richtextbox, only thing i want is triggering a function when scrollbar moves.
I already found GetScrollPos and SetScrollPos. I thought of checking scrollbar position periodically but there must be a better way. So, what is the better way?
Update: Using WinForms
|
2013/01/04
|
[
"https://Stackoverflow.com/questions/14163007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/766850/"
] |
Assuming WinForms, you can try pinvoking:
```
public class MyRTF: RichTextBox {
private const int WM_HSCROLL = 0x114;
private const int WM_VSCROLL = 0x115;
private const int WM_MOUSEWHEEL = 0x20A;
protected override void WndProc(ref Message m) {
base.WndProc(ref m);
if (m.Msg == WM_VSCROLL || m.Msg == WM_HSCROLL || m.Msg == WM_MOUSEWHEEL) {
// scrolling...
}
}
}
```
|
13,238 |
What constitutes a vampire "nest"? Is it just the home of several vampires, or does it have to actually be "nest" like (i.e. dirty, dark, stinky, unpleasant)?
For instance, I've never seen the Cullen's house referred to as a nest, since they're sort of civilized. But in the first season of True Blood there were three vampires living in a house and it was referred to as a nest. Is there a distinction? Or just the preference of the author writing the vampires? Is Jean Claude's building in the Anita Blake series considered a nest?
Also, what is the first mention of a 'vampire nest' in fiction?
|
2012/03/16
|
[
"https://scifi.stackexchange.com/questions/13238",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/3102/"
] |
It depends on the series that is under consideration.
Typically, a 'nest' of vampires is used by mortals who are exterminating vampires - Blade, Buffy, etc will use the term. This plays into their human desire to distance their foes from humanity.
In works where vampires are portrayed more sympathetically, every effort is made to 'humanize' the vampires (or make them 'better than human').
I'm unable to find a reference to the first usage of 'nest' to refer to a group of vampires. The earliest I can recall is Blade (or possibly John Carpenter's Vampires) but both of those are fairly recent (in terms of movies).
|
42,865,955 |
I would like to have a pop up message appear every time a cell contains specific text. Everytime the word "Red Level" is in any of this cells (I22,I23,I34,I35,I36), I would like a MsgBox to appear.
I am using a data validation list in all those cells mentioned above, to make sure the word "Red Level" is always the same.
I wrote some code and it worked but only when I had 1 cell in my range. When I tried to add the other cell numbers to my code, it will still only work for the first cell and not for the rest.
Below is the code that worked for one cell:
```
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Worksheets("A12").Range("I22").Value = "Red Level" Then
MsgBox ("Please call maintenance immediately to refill reservoir")
End If
End Sub
```
I thought I could just add the rest of the cells to the range on my code, but that did not work.
This is what I did but did not work (The MsgBox will only appear when the word "Red Level is on I22 and not in the other cells):
```
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Sheets("A12").Range("I22,I23,I34,I35,I36").Value = "Red Level" Then
MsgBox ("Please call maintenance immediately to refill reservoir")
End If
End Sub
```
|
2017/03/17
|
[
"https://Stackoverflow.com/questions/42865955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6707084/"
] |
For this, you can do it two ways (at least). If you want to stay with `If`, you need lots of `Or`:
```
If Sheets("A12").Range("I22").Value = "Red Level" or Sheets("A12").Range("I23").Value = "Red Level" or ... Then
```
But as you can see, it'll be a really long line, which isn't the most straightforward to read. Here's an alternative:
```
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.EnableEvents = False
Dim addr() As Variant
Dim hasPrompted As Boolean
hasPrompted = False
addr = Array("$I$22", "$I$23", "$I$34", "$I$35", "$I$36")
Dim i As Long
For i = LBound(addr) To UBound(addr)
If Range(addr(i)).Value = "Red Level" And Not hasPrompted Then
MsgBox ("Please call maintenance immediately to refill reservoir")
hasPrompted = True
End If
Next i
Application.EnableEvents = True
End Sub
```
Note the second one will only fire one time, even if all cells have "Red Level", or just one cell has it. If you want to alert the user which cells have it, you can add that in, just let me know.
|
69,547,905 |
I'm trying to deploy an app on heroku but i can't if i use dotenv. This code doesn't work:
```js
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true }, () => {
console.log("Connected to db successfully");
});
```
But this does:
```js
mongoose.connect("mongodb+srv://test:[email protected]/ecommerce?retryWrites=true&w=majority", { useNewUrlParser: true }, () => {
console.log("Connected to db successfully");
});
```
When i try to use dotenv heroku throws this error:
```
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
```
|
2021/10/12
|
[
"https://Stackoverflow.com/questions/69547905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14716818/"
] |
I had to go to heroku dashboard> settings> config vars and then add the key as MONGO\_URI and the mongo url value that mongodb gave me
|
6,043,381 |
I have the following query (slightly amended for clarity):
```
CREATE PROCEDURE Kctc.CaseTasks_GetCaseTasks
@CaseNumber int
... other parameters
,@ChangedBefore datetime
,@ChangedAfter datetime
AS
SELECT Kctc.CaseTasks.CaseTaskId
...blah blah blah
FROM Kctc.CaseTasks
... some joins here
WHERE
... some normal where clauses
AND
(
(@ChangedAfter IS NULL AND @ChangedBefore IS NULL)
OR
EXISTS (SELECT *
FROM Kctc.FieldChanges
WHERE Kctc.FieldChanges.RecordId = Kctc.CaseTasks.CaseTaskId AND
Kctc.FieldChanges.TableName = 'CaseTasks' AND
Kctc.FieldChanges.DateOfChange BETWEEN
ISNULL(@ChangedAfter, '2000/01/01') AND
ISNULL(@ChangedBefore, '2050/01/01'))
)
```
This query times out whenever the user specifies values for `@ChangedBefore` or `@ChangedAfter`, therefore invoking the subquery.
The subquery checks for the existence of a record in the table called `FieldChanges` (which effectively records changes to every field in the `CaseTasks` table).
Querying `FieldChanges` isn't very efficient because it involves filtering on the text field `TableName` which isn't indexed. And I know that subqueries are inherently inefficient.
So my question in general is, is there a way to redesign the query so that it performs better?
I can't think of a way to express the subquery as a join while still returning just one `CaseTask` row when there are multiple associated `FieldChanges` (i.e. preserving the EXISTS semantic). I haven't yet indexed the `TableName` field of the `FieldChanges` table because I'm hesitant about indexing text fields.
So what should I do?
|
2011/05/18
|
[
"https://Stackoverflow.com/questions/6043381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/164923/"
] |
As a first cut you might try putting an index on the table Kctc.FieldChanges on the RecordId, TableName, and DateOfChange fields (one single index with all three fields) and see if that helps.
Share and enjoy.
|
67,588,803 |
I have a list of lists in Python that essentially represent a table. I know I should have used a pandas dataframe to accomplish this, but hindsight is 20/20. I digress...below is an example list of what I'm talking about.
The overarching list variable is comprised of these nested lists:
```
['Store number', 2, 3, 4, 1, 5]
['Variable 1', 82, 99, 44, 32, 65]
['String 1', 'cat', 'dog', 'lizard', 'alligator', 'crocodile']
```
In the current state, each index of each nested list corresponds to the same row in the table. So for store number 2, variable 1 is 82 and string 1 is cat. Say I want to sort each list to where these relationships are maintained, but we sort by ascending store number. The final lists would look like:
```
['Store number', 1, 2, 3, 4, 5]
['Variable 1', 32, 82, 99, 44, 65]
['String 1', 'alligator', 'cat', 'dog', 'lizard', 'crocodile']
```
How could I accomplish this using my current data structures?
|
2021/05/18
|
[
"https://Stackoverflow.com/questions/67588803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15154835/"
] |
You can sort a list of indexes from a `range`, based on the values in one of your lists. Then you can use the indexes reorder the original three lists:
```
store = ['Store number', 2, 3, 4, 1, 5]
var1 = ['Variable 1', 82, 99, 44, 32, 65]
str1 = ['String 1', 'cat', 'dog', 'lizard', 'alligator', 'crocodile']
sort_indexes = sorted(range(1, len(store)), key=lambda i:store[i])
store[1:] = [store[i] for i in sort_indexes]
var1[1:] = [var1[i] for i in sort_indexes]
str1[1:] = [str1[i] for i in sort_indexes]
```
Your data structure would be a lot nicer to work with if the header for each column wasn't contained in the same list. But that awkwardness doesn't actually effect this code much, since we're not directly sorting the lists anyway, we're sorting indexes instead, and there's not really any problem doing that starting at index `1` instead of `0`. If you move the headers out of the data, you'd just be able to skip the slice assignment at the end of this code (just use the list comprehension values directly).
|
18,045,410 |
I am new to Django and am trying to have a user select from a drop-down of choices, then have their choice pass to my next view class so that the record can be edited. Right now my code passes the name of the disease but not the PK from the database. It seems like a simple problem but I'm not sure how to solve it. I get the following error:
```
Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found.
```
Code is below:
**views.py**
```
def drui_index(request):
diseaseForm = DiseaseForm(request.POST)
if diseaseForm.is_valid():
#the problem is probably in the below line. The code isn't right.
new_disease = diseaseForm.cleaned_data['disease']
url = reverse('drui', kwargs={'someApp_disease_id': new_disease.pk})
return HttpResponseRedirect(url)
else:
diseaseForm = DiseaseForm()
return render_to_response("drui_index.html", {'diseaseForm': diseaseForm}, context_instance=RequestContext(request))
def drui(request, someApp_disease_id):
disease = get_object_or_404(Disease, pk=someApp_disease_id
if request.method == "POST":
diseaseForm = DiseaseForm(request.POST, instance=disease)
indicatorInlineFormSet = IndicatorFormSet(request.POST, request.FILES, instance=disease)
if diseaseForm.is_valid():
new_disease = diseaseForm.save(commit=False)
if indicatorInlineFormSet.is_valid():
new_disease.save()
indicatorInlineFormSet.save()
return HttpResponseRedirect(reverse(valdrui))
else:
diseaseForm = DiseaseForm(instance=disease)
indicatorInlineFormSet = IndicatorFormSet(instance=disease)
return render_to_response("drui.html", {'diseaseForm': diseaseForm, 'indicatorInlineFormSet': indicatorInlineFormSet, 'hide_breadcrumb': hide_breadcrumb},context_instance=RequestContext(request))
```
**forms.py**
```
class DiseaseForm(forms.ModelForm):
disease = forms.ModelChoiceField(queryset=Disease.objects.all())
class Meta:
model = Disease
```
**urls.py**
```
url(r'^drui_index/$', 'someApp.views.drui_index', name='drui_index'),
url(r'^drui/(?P<someApp_disease_id>\d+)/$', 'someApp.views.drui', name='drui')
```
**HTML for drui.html**
```
<form class="disease_form" action="{% url drui someApp_disease_id %}" method="post">{% csrf_token %}
{{ diseaseForm.as_table }}
{{ indicatorInlineFormSet.as_table }}
```
**HTML for drui\_index.html**
```
<form class="disease_form" action="{% url drui_index %}" method="post">{% csrf_token %}
{{ diseaseForm.as_table }}
```
**UPDATE**
Solved it by adding a .pk in my kwargs. But now I get a Reverse for 'drui' with arguments '('',)' and keyword arguments '{}' not found.
|
2013/08/04
|
[
"https://Stackoverflow.com/questions/18045410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2646813/"
] |
Case 2 seems the opposite as case 3, so I don't think you can combine the `Pattern`s.
For case 2, your `Pattern` could look like:
```
Pattern pattern = Pattern.compile("(\\s|^)Hello(\\s|$)", Pattern.CASE_INSENSITIVE);
```
In this case we surround the keyword by whitespace or beginning/end of input.
For case 3, your `Pattern` could look like:
```
Pattern pattern = Pattern.compile("[\\$#@\\^&]Hello(\\s|$)", Pattern.CASE_INSENSITIVE);
```
In this case, we precede the keyword with any of the special characters of your choice (note the escaped reserved characters `$` and `^`), then we accept whitespace or the end of input as the character following the keyword.
|
17,376,575 |
I'm working on a sudoku game and I have a list of sudoku games that I can save. I currently have the following serializer classes to save the games:
```
/// <summary>
/// A method to serialize the game repository
/// </summary>
/// <param name="filename">A string representation of the output file name</param>
/// <param name="savedGameRepository">The saved game repository</param>
public void SerializeRepository(string filename, SavedGameRepository savedGameRepository)
{
using (Stream stream = File.Open(filename, FileMode.OpenOrCreate))
{
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, savedGameRepository);
}
}
/// <summary>
/// A method to deserialize the game repository
/// </summary>
/// <param name="filename">A string representation of the input file name</param>
/// <returns>A SavedGameRepository object</returns>
public SavedGameRepository DeserializeRepository(string filename)
{
SavedGameRepository savedGameRepository = new SavedGameRepository();
using (Stream stream = File.Open(filename, FileMode.OpenOrCreate))
{
BinaryFormatter bFormatter = new BinaryFormatter();
if (stream.Length > 0)
{
savedGameRepository = (SavedGameRepository)bFormatter.Deserialize(stream);
}
}
return savedGameRepository;
}
```
Of course the problem with this is that the data file still displays the text associated with the sudoku solution so the user could read and cheat. I tried to use asymmetric encryption but of course the list of game objects is too long. I used symmetric encryption and it works as long as the game is not closed. Once closed and reopened the key is gone and the encrypted data file cannot be reopened. Is it possible to persist a symmetric encryption key?
|
2013/06/29
|
[
"https://Stackoverflow.com/questions/17376575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Try to save the serialized objects in a SQLite table. The database can be encrypted with a password, and it is very simple as you don't have to write any code to encrypt just add password in the connection string.
Advantages: You don't have lot of scattered files, easy to code and read write to table.
Disadvantage: If this file gets corrupt your entire save is lost.
|
6,299,460 |
I am completely new to cryptography and I need to sign a byte array of 128 bytes with an RSA key i have generated with C sharp. The key must be 1024 bits.
I have found a few examples of how to use RSA with C sharp and the code I'm currently trying to use is:
```
public static void AssignParameter()
{
const int PROVIDER_RSA_FULL = 1;
const string CONTAINER_NAME = "SpiderContainer";
CspParameters cspParams;
cspParams = new CspParameters(PROVIDER_RSA_FULL);
cspParams.KeyContainerName = CONTAINER_NAME;
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
rsa = new RSACryptoServiceProvider(cspParams);
rsa.KeySize = 1024;
}
public static string EncryptData(string data2Encrypt)
{
AssignParameter();
StreamReader reader = new StreamReader(path + "publickey.xml");
string publicOnlyKeyXML = reader.ReadToEnd();
rsa.FromXmlString(publicOnlyKeyXML);
reader.Close();
//read plaintext, encrypt it to ciphertext
byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt);
byte[] cipherbytes = rsa.Encrypt(plainbytes, false);
return Convert.ToBase64String(cipherbytes);
}
```
This code works fine with small strings (and thus short byte arrays) but when I try this with a string of 128 characters I get an error saying:
CryptographicException was unhandled: Wrong length
(OK, it might not precisely say 'Wrong length', I get the error in danish, and that is 'Forkert længde' which directly translates to 'Wrong length').
Can anyone tell me how I can encrypt a byte array of 128 bytes with a RSA key of 1024 bits in C sharp?
Thanks in advance,
LordJesus
**EDIT:**
Ok, just to clarify things a bit: I have a message, from which i make a hash using SHA-256. This gives a 32 byte array. This array is padded using a custom padding, so it ends up being a 128 byte array. This padded hash should then be *signed* with my private key, so the receiver can use my public key to verify that the message received is the same as the message sent. Can this be done with a key of 1024 bits?
|
2011/06/09
|
[
"https://Stackoverflow.com/questions/6299460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1928874/"
] |
The minimum key size for encrypting 128 bytes would be 1112 bits, when you are calling `Encrypt` with OAEP off. Note that setting the key size like this `rsa.KeySize = 1024` won't help, you need to actually generate they key of the right size and use them.
This is what worked for me:
```
using System;
using System.IO;
using System.Security.Cryptography;
namespace SO6299460
{
class Program
{
static void Main()
{
GenerateKey();
string data2Encrypt = string.Empty.PadLeft(128,'$');
string encrypted = EncryptData(data2Encrypt);
string decrypted = DecryptData(encrypted);
Console.WriteLine(data2Encrypt);
Console.WriteLine(encrypted);
Console.WriteLine(decrypted);
}
private const string path = @"c:\";
public static void GenerateKey()
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1112);
string publickKey = rsa.ToXmlString(false);
string privateKey = rsa.ToXmlString(true);
WriteStringToFile(publickKey, path + "publickey.xml");
WriteStringToFile(privateKey, path + "privatekey.xml");
}
public static void WriteStringToFile(string value, string filename)
{
using (FileStream stream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(value);
writer.Flush();
stream.Flush();
}
}
public static string EncryptData(string data2Encrypt)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
StreamReader reader = new StreamReader(path + "publickey.xml");
string publicOnlyKeyXML = reader.ReadToEnd();
rsa.FromXmlString(publicOnlyKeyXML);
reader.Close();
//read plaintext, encrypt it to ciphertext
byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt);
byte[] cipherbytes = rsa.Encrypt(plainbytes,false);
return Convert.ToBase64String(cipherbytes);
}
public static string DecryptData(string data2Decrypt)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
StreamReader reader = new StreamReader(path + "privatekey.xml");
string key = reader.ReadToEnd();
rsa.FromXmlString(key);
reader.Close();
byte[] plainbytes = rsa.Decrypt(Convert.FromBase64String(data2Decrypt), false);
return System.Text.Encoding.UTF8.GetString(plainbytes);
}
}
}
```
Note however, that I'm not using a crypto container, and thus, I don't need your `AssignParameter`, but if you need to use it, modifying the code should be easy enough.
If you ever need to encrypt large quantities of data (much larger than 128 bytes) [this article](http://pages.infinit.net/ctech/20031101-0151.html) has sample code on how to do this.
|
41,339,035 |
I do have a select box, like so:
```
<select id="fatherhoodDocument" name="fatherhoodDocument" style="width:250px;" data-bvalidator="myCyrillicDigitsAndSpaceValidator,required" data-bvalidator-modifier="myCapsModifier">
<option value="[$i18n.getString( "select" )]">[$i18n.getString( "select" )]</option>
<option value="test1">test1</option>
<option value="test2">test</option>
<option value="test3">test3</option>
</select>
```
And I have 2 hidden inputs, which should be activated and shown if one of the options above have been chosen:
```
<input type="text" id="marriageregdate" name="marriageregdate" value="" style="width:80px; display:none;" data-bvalidator="required" data-fordraft="required"/>
<input type="text" id="filliationregdate" name="filliationregdate" value="" style="width:80px; display:none;" data-bvalidator="required" data-fordraft="required"/>
```
This is the `JavaScript` code which does change the properties, if some of the options have been clicked:
```
$('#fatherhoodDocument').on('change',function(){
var selection = $(this).val();
switch(selection){
case "test1":
$("#marriageregdate").show();
$( "#marriageregdate" ).prop( "disabled", false );
$("#filliationregdate").hide();
$( "#filliationregdate" ).prop( "disabled", true );
break;
case "test2":
$("#filliationregdate").show();
$( "#filliationregdate" ).prop( "disabled", false );
$("#marriageregdate").hide();
$( "#marriageregdate" ).prop( "disabled", true );
break;
default:
$("#marriageregdate").hide();
$("#filliationregdate").hide();
}
});
```
It works just fine, untill the page has not been refreshed. Once the page is refresehed (clicked f5, or browser icon) the inputs go back to their original state, i.e hidden. But the value of the `select box` remains the same as it was chosen before.
So, my question is how to save the `code` changes too, after the page have been refreshed?
|
2016/12/27
|
[
"https://Stackoverflow.com/questions/41339035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/588519/"
] |
Well, on page load/refresh, `$('#fatherhoodDocument')` hasn't changed yet so the change handler isn't called. What you could do is assign the change handler to a variable and call that on document ready **and** on `$('#fatherhoodDocument')` change.
```
$(function () {
var ddFatherhoodDocument = $('#fatherhoodDocument');
var toggleTextboxes = function () {
var selection = ddFatherhoodDocument.val();
switch(selection) {
case "test1":
$("#marriageregdate").show();
$( "#marriageregdate" ).prop( "disabled", false );
$("#filliationregdate").hide();
$( "#filliationregdate" ).prop( "disabled", true );
break;
case "test2":
$("#filliationregdate").show();
$( "#filliationregdate" ).prop( "disabled", false );
$("#marriageregdate").hide();
$( "#marriageregdate" ).prop( "disabled", true );
break;
default:
$("#marriageregdate").hide();
$("#filliationregdate").hide();
}
}
ddFatherhoodDocument.on('change', toggleTextboxes);
toggleTextboxes();
});
```
|
14,404,801 |
```
html{
background: url(/assets/flower.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
```
How can I make this code randomly choose from a selected number of pictures as background. I am using Rails 3, so have that in mind, if that will simplify the process of making this work.
THANKS! :D
|
2013/01/18
|
[
"https://Stackoverflow.com/questions/14404801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990339/"
] |
In your view file where you would like to display the background image, add this line
```
<style type="text/css">
html {
background: url(<%= randomized_background_image %>) no-repeat center center fixed;
}
</style>
```
Now in your application\_helper
```
def randomized_background_image
images = ["assets/foo.jpg", "assets/random.jpg", "assets/super_random"]
images[rand(images.size)]
end
```
|
27,095 |
Matthew, Mark, and John record casting lots to divide Jesus' clothing. John adds the Old Testament quote from Psalm 22:18 and provides other details:
>
> When the soldiers had crucified Jesus, they took his garments and divided them into four parts, one part for each soldier; also his tunic. But the tunic was seamless, woven in one piece from top to bottom. so they said to one another, “Let us not tear it, but cast lots for it to see whose it shall be.” This was to fulfill the Scripture which says, “They divided my garments among them,
> and for my clothing they cast lots.” (John 19:23-24)
>
>
>
John records the clothing was divided into four parts and there was one piece of clothing which the soldiers did not want to tear: a tunic seamless which had been woven together "from the top."
"From the top" calls attention to the veil separating the Holy Place from the Most Holy Place which both Matthew (27:51) and Mark (15:38) record as being torn in two from the top. However, the tearing of the veil is a detail John chose to omit.
Is John intending a comparison of the tunic to the veil? If so what is the importance of the tunic remaining intact in contrast to the Temple veil which had to be torn apart?
|
2017/02/20
|
[
"https://hermeneutics.stackexchange.com/questions/27095",
"https://hermeneutics.stackexchange.com",
"https://hermeneutics.stackexchange.com/users/8450/"
] |
John gives a more detailed description of this aspect of the crucifixion than either Mark or Mathew:
>
> And they crucify Him, and divide His garments among *themselves*, casting a lot for them *to decide* who should take what. (Mark 15:24 DLNT)
>
>
> And having crucified Him, they divided His garments among *themselves*, casting a lot.
>
> (Matthew 27:35 DLNT)
>
>
> Then the soldiers, when they crucified Jesus, took His garments and made four parts— a part *for* each soldier— and the tunic. Now the tunic was seamless, woven from the top through *the* whole. So they said to one another, “Let us not tear it, but let us cast-lots for it *to decide* whose it will be”— in order that the Scripture [in Ps 22:18] might be fulfilled, the *one* saying, “They divided My garments among themselves, and they cast a lot for My clothing”. So indeed, the soldiers did these *things*. (John 19:23-24 DLNT)
>
>
>
Writing after both Mark and Matthew, John completes the record of how the clothing of Jesus was divided. This account is purposeful to include three pieces of information:
1. The Old Testament passage fulfilled
2. The number of pieces of clothing (five)
3. Identifying the piece of clothing which was not torn (a tunic - χιτὼν)
As noted by User34445 John makes the point that both aspects of Psalm 22:18 were fulfilled: the clothing was divided **and** lots were cast for the garments. In addition, there is a difference between the Masoretic Text (MT) and that John which cites:
>
> Psalm 22:18:
>
> They divide my clothes among themselves **casting lots** for my garments. (JPS Translation)
>
> They divided My garments among themselves, and they **cast a lot** for My clothing. (DLNT)
>
>
>
The Hebrew is plural (lots). John states a single lot was cast. This difference shows John has the Septuagint version of Psalm 22 in mind:
>
> John 19:23:
>
> διεμερίσαντο τὰ ἱμάτιά μου ἑαυτοῖς καὶ ἐπὶ τὸν ἱματισμόν μου ἔβαλον κλῆρον (NA28)
>
>
> Psalm 22:18:
>
> διεμερίσαντο τὰ ἱμάτιά μου ἑαυτοῖς καὶ ἐπὶ τὸν ἱματισμόν μου ἔβαλον κλῆρον (LXX)
>
>
>
John's citation is verbatim.
The singular casting of a lot does not materially affect the fulfillment of the Psalm. It shows John is pointing the reader to the Greek text of the OT.
The article of clothing which was preserved in one piece is specifically a tunic [[χιτών]](https://www.blueletterbible.org/lang/lexicon/lexicon.cfm?Strongs=G5509&t=KJV) which is found in some significant places. Two in particular:
* This was the piece of clothing the LORD made for the first man and woman when they left the Garden of Eden (Genesis 3:21).
+ Just as the first man received a tunic from the LORD God; one of the Roman soldiers received a tunic from the Lord Jesus.
* The garment for the High Priest (Exodus 28:4).
+ Jesus is the true High Priest (e.g. Hebrews 10:21)
The emphasis on not tearing the garment invites a comparison to the clothing of the High Priest which is not supposed to be torn:
>
> The priest who is chief among his brothers, on whose head the anointing oil is poured and who has been consecrated to wear the garments, shall not let the hair of his head hang loose nor tear his clothes. (Leviticus 21:10 ESV) 1
>
>
>
In particular, there is a connection to the High Priest is found on the Day of Atonement:
>
> He shall put on the holy linen coat and shall have the linen undergarment on his body, and he shall tie the linen sash around his waist, and wear the linen turban; these are the holy garments. He shall bathe his body in water and then put them on. (Leviticus 16:4 ESV)
>
>
> καὶ **χιτῶνα** λινοῦν ἡγιασμένον ἐνδύσεται καὶ περισκελὲς λινοῦν ἔσται ἐπὶ τοῦ χρωτὸς αὐτοῦ καὶ ζώνῃ λινῇ ζώσεται καὶ κίδαριν λινῆν περιθήσεται ἱμάτια ἅγιά ἐστιν καὶ λούσεται ὕδατι πᾶν τὸ σῶμα αὐτοῦ καὶ ἐνδύσεται αὐτά (LXX)
>
>
>
The tunic is removed and left in the Holy Place:
>
> “Then Aaron shall come into the tent of meeting and shall take off the linen garments that he put on when he went into the Holy Place and shall leave them there. (Leviticus 16:23 ESV)
>
>
>
Therefore Mark and Matthew record the tearing of the Temple veil opening the entrance to the Most Holy Place and John presents Jesus as the High Priest, who is and makes the sacrifice and leaves His tunic outside the Most Holy Place.
---
1. The crown of thorns fulfills this requirement
|
33,650,063 |
I need to combine two Bytes into one int value.
I receive from my camera a 16bit Image were two successive bytes have the intensity value of one pixel. My goal is to combine these two bytes into one "int" vale.
I manage to do this using the following code:
```
for (int i = 0; i < VectorLength * 2; i = i + 2)
{
NewImageVector[ImagePointer] = ((int)(buffer.Array[i + 1]) << 8) | ((int)(buffer.Array[i]));
ImagePointer++;
}
```
My image is 1280\*960 so VectorLength==1228800 and the incomming buffer size is 2\*1228800=2457600 elements...
Is there any way that I can speed this up?
Maybe there is another way so I don't need to use a for-loop.
Thank you
|
2015/11/11
|
[
"https://Stackoverflow.com/questions/33650063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5210481/"
] |
Assuming you can (re-)define `NewImageVector` as a `short[]`, and every two consecutive bytes in `Buffer` should be transformed into a `short` (which basically what you're doing now, only you cast to an `int` afterwards), you can use [Buffer.BlockCopy](https://msdn.microsoft.com/en-us/library/system.buffer.blockcopy(v=vs.110).aspx) to do it for you.
As the documentation tells, you `Buffer.BlockCopy` copies bytes from one array to another, so in order to copy your bytes in buffer you need to do the following:
```
Buffer.BlockCopy(Buffer, 0, NewImageVector, 0, [NumberOfExpectedShorts] * 2)
```
This tells `BlockCopy` that you want to start copying bytes from `Buffer`, starting at index 0, to `NewImageVector` starting at index 0, and you want to copy `[NumberOfExpectedShorts] * 2` bytes (since every short is two bytes long).
No loops, but it does depend on the ability of using a `short[]` array instead of an `int[]` array (and indeed, on using an array to begin with).
Note that this also requires the bytes in `Buffer` to be in `little-endian` order (i.e. `Buffer[index]` contains the low byte, `buffer[index + 1]` the high byte).
|
431,943 |
So I find myself needing to apply global Moran's I across ~20 variables (as in ~20 instances of univariate autocorrelation for each variable, not attempted multivariate spatial autocorrelation). I'm using R and the sf + spdep packages.
Where `data_lisa` is a sf object structured:
```
id | var_a | var_b | ... | var_n | geometry
```
...and `lw` the spatial weights list created with:
```
lw <- nb2listw(neighbours = poly2nb(data_lisa,
queen = TRUE),
style = "W",
zero.policy = TRUE)
```
Using spdep, I can apply global Moran's I for a single variable as:
```
moran.mc(data_lisa$var_a,
listw = lw,
nsim = 999,
zero.policy = TRUE)
```
...and receive all the expected results.
So I'm looking for help in how to programmatically apply this function across all of my variables.
The result of `moran.mc` is a list object which I suspect is where I'm encountering the greatest issues, as I don't have much experience interacting with lists.
Ideally the output would look something like this.
| variable | moran\_stat | pval |
| --- | --- | --- |
| var\_a | 0.064 | 0.042 |
| var\_b | 0.322 | 0.001 |
| var\_c | 0.183 | 0.001 |
How can I do this?
|
2022/05/24
|
[
"https://gis.stackexchange.com/questions/431943",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/206106/"
] |
Make a vector of your variable names either by subsetting the column names or programmatically, eg:
```
vars = names(data_lisa)[2:5]
vars = paste0("var_",letters[1:4])
```
For an example, I'm using the `COL.OLD` data you get from `?moran.mc` and this set of variables:
```
vars = c("AREA_PL","PERIMETER","CRIME","POLYID")
```
then repeat using `lapply` over the variable names, and give the returned list the names of the vars:
```
> mcs = lapply(vars, function(v){moran.mc(COL.OLD[[v]], listw=colw, nsim=10)})
> names(mcs) = vars
```
Then extract the statistic and p-value, making a data frame with the correct names:
```
> stats = data.frame(
lapply(names(mcs),
function(nm){
m=mcs[[nm]]
setNames(
list(
stat=m$statistic,
p=m$p.value
),
paste0(nm,c("_s","_p"))
)
}
)
)
```
Which produces:
```
> stats
AREA_PL_s AREA_PL_p PERIMETER_s PERIMETER_p CRIME_s CRIME_p
statistic 0.1404648 0.09090909 0.1741305 0.09090909 0.5109513 0.09090909
POLYID_s POLYID_p
statistic 0.8701314 0.09090909
```
I don't get how you want the output to be a table, since you only get one statistic per column, and not by `id` as implied in your sample table output. This is a global statistic.
Note this only uses base R packages (plus `spdep`) so should work in any R installation.
|
27,415,471 |
We are developing an app in Appcelerator Titanium and using PushWoosh to send notifications. We have tried with no success to send a notification that opens an specific page in the app.
Think of an Inbox, where the user gets its messages, when a message is received, a notification shows up notifying the user on the new message, the user clicks it and opens the app on either the inbox or the message itself. The app includes other pages/features besides the Inbox, so far we can open the app after clicking but not the inbox or the message page.
We have looked everywhere for information and we would appreciate it if you can point us to the right direction.
|
2014/12/11
|
[
"https://Stackoverflow.com/questions/27415471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2072962/"
] |
```
^(?!0?0\.00$)\d{1,2}\.\d{2}$
```
You can simply use this.See demo.
<https://regex101.com/r/qB0jV1/10>
|
53,896,970 |
I am getting coordinates with FusedLocationProviderClient in my application on a button click to store into a database. The issue is that when I reboot the phone or the emulator the `.getLastLocation()` is null and I have to click another time the button i order for this to work. Is there a way to force to get a current position if the value of `location from .lastKnownPosition()` is null?
```
// Google fused location client for GPS position
private FusedLocationProviderClient flpc;
// Vars to store GPS info
public Double latitude, longitude;
public Float accuracy;
// Google Fused Client for location
public void getLocation() {
// FusedLocationProviderClient
flpc = LocationServices.getFusedLocationProviderClient(context);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
......
return;
}
// Get the latest position from device
Task<Location> task = flpc.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location!=null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
accuracy = location.getAccuracy();
}
}
});
}
```
In my button handler I call `getLocation()` and use latitude, longitude and accuracy to store to the database.
Any help appreciated!
|
2018/12/22
|
[
"https://Stackoverflow.com/questions/53896970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975588/"
] |
When getLastLocation() is null, you need to make a LocationRequest
```
private LocationRequest locationRequest;
private LocationCallback locationCallback;
...
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(20 * 1000);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s -- %s", wayLatitude, wayLongitude));
}
}
}
};
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper())
```
If you don't need continuous updates, you can remove the request once you've received it.
```
mFusedLocationClient.removeLocationUpdates(locationCallback);
```
More info here: <https://medium.com/@droidbyme/get-current-location-using-fusedlocationproviderclient-in-android-cb7ebf5ab88e>
|
22,685,243 |
I have an html form which posts data to a servlet. However the order returned in getParameterNames() isn't the same as in the HTML Form.
How do i retrieve the parameters in the same order?
|
2014/03/27
|
[
"https://Stackoverflow.com/questions/22685243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1383948/"
] |
In your second attempt you did right: you are creating some functions, the scope of that controller is taking those functions as properties, then $scope.childOnLoad(); will call the function you created.
In fact you can define so many functions but they are not called while loading or when loads complete.
|
6,275,356 |
I have an editable checkbox in my jQGrid with the values
`editoptions: { value: "Yes:No" }`
But whatever the value is i am getting back on controller string value "Yes:No", not single value "Yes" of "No", so i am getting it like that:
When it is checked i am getting this:
```
form["MyCheckBox"] = "Yes:No".
```
When it is not checked i am getting this:
```
form["MyCheckBox"] = "No".
```
How can i do to make it work?
Or is there any way to get bool values(true/false) instead of string values ?
Need help
|
2011/06/08
|
[
"https://Stackoverflow.com/questions/6275356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/735490/"
] |
Try this:
```
editoptions: { value:"True:False" }, editable:true, edittype:'checkbox',
formatter: "checkbox", formatoptions: {disabled : false}
```
|
8,673,684 |
I can't use boost::spirit in my environment. But I would like to use STL and boost as much as possible to build my own expression evaluator. Is there such an alternative to boost::spirit?
|
2011/12/29
|
[
"https://Stackoverflow.com/questions/8673684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/749973/"
] |
The following code includes unit tests and a complete parser I wrote in an about 90 minute session at ACCU 200x (8 or 9). If you need more, it might be easy enough to extend. You can make it do doubles by defining `Parse::value_type`, or extracting it into a separate header file and make it a template class.
Or you can take the test cases and try yourself. (it uses CUTE from <http://cute-test.com>)
```
#include "cute.h"
#include "ide_listener.h"
#include "cute_runner.h"
#include <cctype>
#include <map>
namespace {
class Parser {
typedef int value_type;
typedef std::vector<value_type> valuestack;
typedef std::vector<char> opstack;
typedef std::map<std::string,value_type> memory;
public:
memory variables;
private:
void evaluateSingleOperator(char op,value_type &result,value_type operand) {
switch(op) {
case '+': result += operand; break;
case '-': result -= operand; break;
case '*': result *= operand; break;
case '/': result /= operand; break;
default: throw("invalid operand");
}
}
void evaluateStacks(valuestack &values, opstack &ops) {
while(ops.size() && values.size()>1) {
char op = ops.back(); ops.pop_back();
value_type operand = values.back(); values.pop_back();
evaluateSingleOperator(op,values.back(),operand);
}
}
bool higherPrecedenceOrLeftAssociative(char last, char current) {
return (last == current)||(last == '*' || last == '/') ;
}
bool shouldEvaluate(char op,opstack const &ops) {
return ops.size() > 0 && higherPrecedenceOrLeftAssociative(ops.back(),op);
}
std::string parseVariableName(std::istream &is) {
std::string variable;
char nextchar=0;
while ((is >> nextchar) && isalpha(nextchar)) {
variable += nextchar;
}
if (variable.size() == 0) throw std::string("internal parse error");
is.unget();
return variable;
}
int peekWithSkipWhiteSpace(std::istream &is) {
int nextchar = EOF;
while(isspace(nextchar = is.peek())) is.get();
return nextchar;
}
value_type getOperand(std::istream &is) {
int nextchar = peekWithSkipWhiteSpace(is);
if (nextchar == EOF) throw std::string("syntax error operand expected");
if (isdigit(nextchar)){
value_type operand=0;
if (!(is >> operand)) throw std::string("syntax error getting number") ;
return operand;
} else if ('(' == nextchar) {
is.get();
return parse(is);
} else if (isalpha(nextchar)) {
std::string variable= parseVariableName(is);
if( parseAssignmentOperator(is)) {
variables[variable] = parse(is);
} else {
if (!variables.count(variable)) throw std::string("undefined variable: ")+variable;
}
return variables[variable];
}
throw std::string("syntax error");
}
bool parseAssignmentOperator(std::istream &is) {
int nextchar = peekWithSkipWhiteSpace(is);
if ('=' != nextchar) {
return false;
}
is.get();
return true;
}
public:
value_type parse(std::istream &is) {
is >> std::skipws;
valuestack values;
opstack ops;
values.push_back(getOperand(is));
char op=')';
while((is >>op) && op != ')') {
if (shouldEvaluate(op, ops)) {
evaluateStacks(values, ops);
}
values.push_back(getOperand(is));
ops.push_back(op);
}
evaluateStacks(values,ops);
return values.back();
}
value_type eval(std::string s) {
std::istringstream is(s);
return parse(is);
}
};
int eval(std::string s) {
return Parser().eval(s);
}
void shouldThrowEmptyExpression() {
eval("");
}
void shouldThrowSyntaxError() {
eval("()");
}
void testSimpleNumber() {
ASSERT_EQUAL(5,eval("5"));
}
void testSimpleAdd() {
ASSERT_EQUAL(10,eval("5 +5"));
}
void testMultiAdd() {
ASSERT_EQUAL(10,eval("1 + 2 + 3+4"));
}
void testSimpleSubtract() {
ASSERT_EQUAL(5,eval("6-1"));
}
void testTenPlus12Minus100() {
ASSERT_EQUAL(-78,eval("10+12-100"));
}
void testMultiply() {
ASSERT_EQUAL(50,eval("10*5"));
}
void testDivision() {
ASSERT_EQUAL(7,eval("21/3"));
}
void testAddThenMultiply() {
ASSERT_EQUAL(21,eval("1+4 *5"));
}
void testAddThenMultiplyAdd() {
ASSERT_EQUAL(16,eval("1+4*5 -5"));
}
void testAddSubSub() {
ASSERT_EQUAL(-4,eval("1+2-3-4"));
}
void testSimpleParenthesis() {
ASSERT_EQUAL(1,eval("(1)"));
}
void testSimpleOperandParenthesis() {
ASSERT_EQUAL(2,eval("1+(1)"));
}
void testParenthesis() {
ASSERT_EQUAL(5,eval("2*(1+4)-5"));
}
void testNestedParenthesis() {
ASSERT_EQUAL(16,eval("2*(1+(4*3)-5)"));
}
void testDeeplyNestedParenthesis() {
ASSERT_EQUAL(8,eval("((2*((1+(4*3)-5)))/2)"));
}
void testSimpleAssignment() {
Parser p;
ASSERT_EQUAL(1, p.eval("a=1*(2-1)"));
ASSERT_EQUAL(8, p.eval("a+7"));
ASSERT_EQUAL(1, p.eval("2-a"));
}
void testLongerVariables() {
Parser p;
ASSERT_EQUAL(1, p.eval("aLongVariableName=1*(2-1)"));
ASSERT_EQUAL(42, p.eval("AnotherVariable=7*(4+2)"));
ASSERT_EQUAL(1, p.eval("2-(aLongVariableName*AnotherVariable)/42"));
}
void shouldThrowUndefined() {
eval("2 * undefinedVariable");
}
void runSuite(){
cute::suite s;
//TODO add your test here
s.push_back(CUTE_EXPECT(CUTE(shouldThrowEmptyExpression),std::string));
s.push_back(CUTE_EXPECT(CUTE(shouldThrowSyntaxError),std::string));
s.push_back(CUTE(testSimpleNumber));
s.push_back(CUTE(testSimpleAdd));
s.push_back(CUTE(testMultiAdd));
s.push_back(CUTE(testSimpleSubtract));
s.push_back(CUTE(testTenPlus12Minus100));
s.push_back(CUTE(testMultiply));
s.push_back(CUTE(testDivision));
s.push_back(CUTE(testAddThenMultiply));
s.push_back(CUTE(testAddSubSub));
s.push_back(CUTE(testAddThenMultiplyAdd));
s.push_back(CUTE(testSimpleParenthesis));
s.push_back(CUTE(testSimpleOperandParenthesis));
s.push_back(CUTE(testParenthesis));
s.push_back(CUTE(testNestedParenthesis));
s.push_back(CUTE(testDeeplyNestedParenthesis));
s.push_back(CUTE(testSimpleAssignment));
s.push_back(CUTE(testLongerVariables));
s.push_back(CUTE_EXPECT(CUTE(shouldThrowUndefined),std::string));
cute::ide_listener lis;
cute::makeRunner(lis)(s, "The Suite");
}
}
int main(){
runSuite();
}
```
|
35,306 |
**tl;dr**
Faculty don't think teaching is as important as their other responsibilities; how do we change that?
**Long version**
I've been working in academia for a long time and whenever I see instructors half-assing their teaching the go to excuses are that they have no time, or that it doesn't get any respect/grants/promotion/tenure/etc. I don't doubt they're busy, and I know departments don't typically reward teaching excellence (or punish teaching mediocrity...) but the students are suffering as a result.
How can we (faculty that care about teaching and staff supporting faculty) change this situation? What can we do short-term to make faculty care about teaching *now* and what can we do long-term to make departments care about excellence in teaching, and not just in research?
*Note:* I'm aware research brings in money. Keep in mind most faculty are adjuncts who aren't doing research but still have tenured research faculty that don't care about teaching as their role models.
|
2015/01/06
|
[
"https://academia.stackexchange.com/questions/35306",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/27290/"
] |
Putting in place a better system for evaluating teaching than today's student evaluation forms would be a good start. Getting serious about the assessment of student learning outcomes (rather than simply assigning grades) would also be extremely helpful.
|