qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
64,804,824 | I am learning HTML and I am trying to align different icons in a line but in a different positions. The first element should be aligned to the left and the others aligned to the right.
```
E1| |E2|E3|E4
```
I am not sure how to implement that. Should I use a `table`? Or a `div` with `<li>` elements?
I tried to use a table with a blank column but it's not working
```css
td {
background-color: yellow;
border: 1px solid black;
}
```
```html
<table>
<tr>
<td width="60%"> test </td>
<td> blank </td>
<td> 1 </td>
<td> 2 </td>
<td> 3 </td>
</table>
``` | 2020/11/12 | [
"https://Stackoverflow.com/questions/64804824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14086404/"
] | Errors and lines beginning with `>>>` suggest you're still inside Python2 interpreter. You need to exit it before trying to run Python3. You can do that by pressing the `Ctrl` and `d` buttons on your keyboard at the same time, or typing `exit()`.
After exiting, you should be able to run `python3`. | looks like your python is linked to python2.7 instead of python3.
just type python3 on commandline, this should solve your problem. you can check the version by typing python3 --version on commandline.
the same should work for pip3 |
339,378 | Let $E$ and $F$ be Banach spaces, and let $\mathfrak L\_{co}(E,F)$ denote the space of bounded linear operators $E \to F$ equipped with the topology of uniform convergence on the absolutely convex compact subsets of $E$.
Defant and Floret [DF93, §5.5] point out that there is a natural linear map
$$ D\_F : F' \mathop{\tilde\otimes\_\pi} E \to (\mathfrak L\_{co}(E,F))' $$
which is surjective. (No continuity claims are made.) Furthermore, they prove [DF93, §5.7] that $D\_F$ is injective if $F$ is reflexive or if $F'$ or $E$ has the approximation property, so in that case one has an isomorphism $F' \mathop{\tilde\otimes\_\pi} E \cong (\mathfrak L\_{co}(E,F))'$ of vector spaces. They conclude with:
>
> *We do not know whether or not $D\_F$ is always injective.*
>
>
>
**Question.** Has this since been settled? Can someone provide (a reference to) a proof or a counterexample?
---
Some background: $D\_F$ is defined by taking the natural map
$$ \Phi\_F : \mathfrak L(E,F) \stackrel{1}{\hookrightarrow} \mathfrak L(E,F'') \stackrel{1}{\cong} (E \mathop{\tilde\otimes\_\pi} F')' \stackrel{1}{\cong} (F' \mathop{\tilde\otimes\_\pi} E)'. $$
It is shown that $\Phi\_F$ is continuous as a map $\mathfrak L\_{co}(E,F) \to [(F' \mathop{\tilde\otimes\_\pi} E)',\text{weak-$\*$}]$, and then $D\_F$ is defined as the adjoint of this map. (I guess one could deduce some continuity property of $D\_F$ from this, but the authors steer clear of that, presumably to focus on questions related to Banach spaces.)
Another way to interpret the question is this: the map $D\_F$ (or $\Phi\_F$) gives rise to a bilinear map $(F' \mathop{\tilde\otimes\_\pi} E) \times \mathfrak L(E,F) \to \mathbb{F}$. One readily verifies that this is simply the natural map
$$ \left(\sum\_{n=1}^\infty y\_n' \mathop{\otimes} x\_n \, , \, T\right) \mapsto \sum\_{n=1}^\infty y\_n'(Tx\_n). $$
Since we have $\mathfrak L(E,F) \stackrel{1}{\hookrightarrow} (F' \mathop{\tilde\otimes\_\pi} E)'$, it is clear that $F' \mathop{\tilde\otimes\_\pi} E$ separates points on $\mathfrak L(E,F)$. The question whether $D\_F$ is injective is equivalent to the question whether $\mathfrak L(E,F)$ separates points on $F' \mathop{\tilde\otimes\_\pi} E$ (so that the bilinear map becomes a dual pairing).
Yet another equivalent formulation: is the image of $\Phi\_F$ weak-$\*$ dense in $(F' \mathop{\tilde\otimes\_\pi} E)'$?
---
**References.**
[DF93] A. Defant, K. Floret, *Tensor Norms and Operator Ideals* (1993), Mathematics Studies 176, North-Holland. | 2019/08/28 | [
"https://mathoverflow.net/questions/339378",
"https://mathoverflow.net",
"https://mathoverflow.net/users/120251/"
] | This question was settled in 2012 by Petr Hájek and Richard J. Smith [HS12]. They prove the following beautiful result (reformulated here to match the notation from the question).
>
> **Theorem** (cf. [HS12, Theorem 2.5])**.** Let $F$ be a Banach space with the AP. Then the following conditions are equivalent:
>
>
> * $F'$ has the AP.
> * For every Banach space $E$, the map $F' \mathbin{\tilde\otimes\_\pi} E \to (\mathfrak L\_{co}(E,F))'$ is injective.
> * The map $F' \mathbin{\tilde\otimes\_\pi} F'' \to (\mathfrak L\_{co}(F'',F))'$ is injective.
>
>
>
As there are known examples of Banach spaces with the AP whose dual fails the AP, the question is settled in the negative.
---
**References.**
[HS12]: Petr Hájek, Richard J. Smith, *Some duality relations in the theory of tensor products*, Expositiones Mathematicae, volume 30 (2012), issue 3, pages 239–249. <https://doi.org/10.1016/j.exmath.2012.08.004> | It follows from [this answer of Bill Johnson](https://mathoverflow.net/a/199260) that it can already fail if $E = F$, so the question has been settled in the negative. |
65,935,051 | I am building an application using docker-compose (file 1) and I was wondering how I could communicate the host IP address to the docker-compose file. The application is composed of a db, a frontend and a backend. The aim of it is that I want to access my application from other computers on the local network. It works fine for the front but when I want to communicate with the backend, it does not work anymore. I suspect it's due to the fact that the front is trying to send data to localhost (which is not the correct one for another computer on the local network). Thus, I would like to communicate to the front application the IP address of the host directly in the docker-compose file, so it can communicate with the backend ! Any idea ?
**File 1**
```
version: "3.7"
services:
db:
build:
context: ./database
command: --default-authentication-plugin=mysql_native_password --sql_mode=""
restart: always
cap_add:
- SYS_NICE # CAP_SYS_NICE
volumes:
- db_data:/var/lib/mysql
ports:
- ${MYSQL_PORT}:${MYSQL_PORT}
environment:
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_TCP_PORT: ${MYSQL_PORT}
env_file: ./.env
back:
depends_on:
- db
build:
context: ./backend
target: development
volumes:
- ./backend:/app
- /app/node_modules
restart: "no"
ports:
- ${BACKEND_PORT}:${BACKEND_PORT}
env_file: ./.env
front:
depends_on:
- back
- db
build:
context: ./frontend
target: development
stdin_open: true
volumes:
- ./frontend:/app
- /app/node_modules
restart: "no"
ports:
- ${FRONTEND_PORT}:${FRONTEND_PORT}
env_file: ./.env
volumes:
db_data: {}
```
Here is the api url I am using on the frontend env to communicate with the backend, which I would to be replaced with the host IP dynamically.
**File 2**
```
const dev = {
...env,
apiUrl: "http://localhost:3000/api",
};
```
Thank you so much for you help!
Best | 2021/01/28 | [
"https://Stackoverflow.com/questions/65935051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11139767/"
] | What you want is called [shell command substitution](https://unix.stackexchange.com/questions/440088/what-is-command-substitution-in-a-shell).
Something like: `MYVAR=$(ip route get 1 | awk '{print $NF;exit}')`
Unfortunately, command substitution is NOT supported in compose.
Compose supports only "static" shell variables aka [shell variable expansion](https://docs.docker.com/compose/compose-file/compose-file-v3/#variable-substitution).
Your best bet would be to **declare mandatory variable** with an appropriate error message.
```
# requires for the var to be pre-declared in shell
environment:
API_URL: ${API_URL:?"Variable API_URL must present in shell."}
# alternatively you could provide some default value
environment:
API_URL: ${API_URL:-192.0.2.2}
```
---
Another solution may be to play with `envsubst` to edit your compose file in-place.
Check [this answer](https://stackoverflow.com/a/33186458/4486909) for examples.
---
Also note that there is no such thing as "host's ip address" :)
It's kinda conventional and a pretty vague [term](https://serverfault.com/a/569556/405997).
>
> "Primary IP" is an alias for "whatever your system uses when it
> originates traffic to the default route". In the absence of source
> phrases on that route, that's the first address of the interface used
> (more or less).
>
>
>
Thus, you need to be careful when writing your command to define "host's IP".
In simple network configurations this one is likely to work more or less fine.
`ip route get 1 | awk '{print $NF;exit}'`
But better check this [discussion](https://stackoverflow.com/questions/13322485/how-to-get-the-primary-ip-address-of-the-local-machine-on-linux-and-os-x) and make sure your eventual command returns what you expect. | You should add an environment variable to your frontend configuration which specifies the URL to the api endpoint and use the hostname of the backend container in the URL. The documentation for [Networking in Compose](https://docs.docker.com/compose/networking/) details default hostname and networks used for containers.
Modify your docker compose file as follows:
```yaml
services:
front:
environment:
API_URL: http://back:${BACKEND_PORT}/api
```
Modify your javascript file as follows:
```js
const dev = {
...env,
apiUrl: process.env.API_URL || 'http://localhost:3000/api'
};
``` |
435,591 | *За* -- довольно распространённый предлог, который употребляется с винительным или творительным падежом. В предложении:
>
> «Если бы вы знали, что это **был за чудный человек**, пани»
>
>
>
падеж явно именительный! Что нарушает вообще какую бы то ни было сколько-нибудь разумную синтаксическую трактовку данного предложения.
И теперь вопрос: что за конструкция здесь используется и в качестве какой части речи здесь употребляется слово *за*? | 2017/11/30 | [
"https://rus.stackexchange.com/questions/435591",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/5032/"
] | *Что за* (в данном случае *за* не предлог, а часть сложной частицы) — это разговорная восклицательная частица, употребляющаяся в трех случаях:
1) при усилении вопроса;
2) при усилении качества или свойства;
**3) при выражении эмоциональной оценки (восхищения, возмущения, осуждения и т. п.)**.
В вашем примере третий случай: рассказчик восхищается неким человеком (а вполне возможно, что испытывает резко противоположные чувства).
Иногда эта частица может «разрываться» словами *был*, *это* и т. п., что, собственно, и можно наблюдать в приведенном предложении. | А я рассматривала бы это предложение по-другому. Здесь ЭТО - подлежащее в именительном падеже, его можно заменить местоимением ОН.
ЧЕЛОВЕК - дополнение в винительном падеже с предлогом ЗА. |
37,148 | Is there a word that can be used to mean two previous places? I want to reference something two paragraphs ago; *former* would work if it was only one before, and I cannot use *penultimate* because it may be confused with the second to last of the entire work. | 2011/08/08 | [
"https://english.stackexchange.com/questions/37148",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/11738/"
] | In the very [first comment of this blog,](http://blogs.nature.com/nwerneck/2011/01/18/relative-citation-impact-by-country---2009) someone stated:
>
> I edited the post including two paragraphs before the image, explaining with more details how it is created.
>
>
>
I believe that the one way to state "two paragraphs" before would be to do as the fellow did above: just say it! You'll be understood without doubt.
Edit: One other way would be to use *former*. *Former* doesn't necessarily work only if it was the only one before. It [refers to anything:](http://dictionary.reference.com/browse/former)
>
> preceding in time; prior or earlier
>
>
>
Thus, you could possibly say:
>
> In a former paragraph, it was stated....
>
>
> | Try *penprevious* (made up word, parallel with *penultimate*). |
28,035,688 | I have a class with a function that updates attributes of its objects. I'm trying to figure out which is more pythonic: should I explicitly return the object I'm updating, or simply update the `self` object?
For example:
```
class A(object):
def __init__(self):
self.value = 0
def explicit_value_update(self, other_value):
# Expect a lot of computation here - not simply a setter
new_value = other_value * 2
return new_value
def implicit_value_update(self, other_value):
# Expect a lot of computation here - not simply a setter
new_value = other_value * 2
self.value = new_value
# hidden `return None` statement
if __name__ == '__main__':
a = A()
a.value = a.explicit_value_update(2)
a.implicit_value_update(2)
```
I've looked around, but haven't seen any clear answers on this.
EDIT: Specifically, I'm looking for both readability and execution time. Would there be an advantage in either category for either function? | 2015/01/20 | [
"https://Stackoverflow.com/questions/28035688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/362703/"
] | In my opinion, using `__new__` in such a way is really confusing for other people who might read your code. Also it requires somewhat hackish code to distinguish guessing file system from user input and creating `Nfs` and `LocalDrive` with their corresponding classes.
Why not make a separate function with this behaviour? It can even be a static method of `FileSystem` class:
```
class FileSystem(object):
# other code ...
@staticmethod
def from_path(path):
if path.upper().startswith('NFS://'):
return Nfs(path)
else:
return LocalDrive(path)
```
And you call it like this:
```
data1 = FileSystem.from_path('nfs://192.168.1.18')
data2 = FileSystem.from_path('/var/log')
``` | **Edit [[BLUF]](https://en.wikipedia.org/wiki/BLUF_(communication)):** there is no problem with the answer provided by @martineau, this post is merely to follow up for completion to discuss a potential error encountered when using additional keywords in a class definition that are not managed by the metaclass.
I'd like to supply some additional information on the use of `__init_subclass__` in conjuncture with using `__new__` as a factory. The answer that @martineau has posted is very useful and I have implemented an altered version of it in my own programs as I prefer using the class creation sequence over adding a factory method to the namespace; very similar to how `pathlib.Path` is implemented.
To follow up on a comment trail with @martinaeu I have taken the following snippet from his answer:
```
import os
import re
class FileSystem(object):
class NoAccess(Exception): pass
class Unknown(Exception): pass
# Regex for matching "xxx://" where x is any non-whitespace character except for ":".
_PATH_PREFIX_PATTERN = re.compile(r'\s*([^:]+)://')
_registry = {} # Registered subclasses.
@classmethod
def __init_subclass__(cls, /, **kwargs):
path_prefix = kwargs.pop('path_prefix', None)
super().__init_subclass__(**kwargs)
cls._registry[path_prefix] = cls # Add class to registry.
@classmethod
def _get_prefix(cls, s):
""" Extract any file system prefix at beginning of string s and
return a lowercase version of it or None when there isn't one.
"""
match = cls._PATH_PREFIX_PATTERN.match(s)
return match.group(1).lower() if match else None
def __new__(cls, path):
""" Create instance of appropriate subclass. """
path_prefix = cls._get_prefix(path)
subclass = FileSystem._registry.get(path_prefix)
if subclass:
# Using "object" base class method avoids recursion here.
return object.__new__(subclass)
else: # No subclass with matching prefix found (and no default).
raise FileSystem.Unknown(
f'path "{path}" has no known file system prefix')
def count_files(self):
raise NotImplementedError
class Nfs(FileSystem, path_prefix='nfs'):
def __init__ (self, path):
pass
def count_files(self):
pass
class LocalDrive(FileSystem, path_prefix=None): # Default file system.
def __init__(self, path):
if not os.access(path, os.R_OK):
raise FileSystem.NoAccess('Cannot read directory')
self.path = path
def count_files(self):
return sum(os.path.isfile(os.path.join(self.path, filename))
for filename in os.listdir(self.path))
if __name__ == '__main__':
data1 = FileSystem('nfs://192.168.1.18')
data2 = FileSystem('c:/') # Change as necessary for testing.
print(type(data1).__name__) # -> Nfs
print(type(data2).__name__) # -> LocalDrive
print(data2.count_files()) # -> <some number>
try:
data3 = FileSystem('foobar://42') # Unregistered path prefix.
except FileSystem.Unknown as exc:
print(str(exc), '- raised as expected')
else:
raise RuntimeError(
"Unregistered path prefix should have raised Exception!")
```
This answer, as written works, but I wish to address a few items (potential pitfalls) others may experience through inexperience or perhaps codebase standards their team requires.
Firstly, for the decorator on `__init_subclass__`, per the [PEP](https://www.python.org/dev/peps/pep-0487/#requiring-an-explicit-decorator-on-init-subclass):
>
> One could require the explicit use of `@classmethod` on the `__init_subclass__` decorator. It was made implicit since there's no sensible interpretation for leaving it out, and that case would need to be detected anyway in order to give a useful error message.
>
>
>
Not a problem since its already implied, and the Zen tells us "explicit over implicit"; never the less, when abiding by PEPs, there you go (and rational is further explained).
In my own implementation of a similar solution, subclasses are not defined with an additional keyword argument, such as @martineau does here:
```
class Nfs(FileSystem, path_prefix='nfs'): ...
class LocalDrive(FileSystem, path_prefix=None): ...
```
When browsing through the [PEP](https://www.python.org/dev/peps/pep-0487/#implementation-details):
>
> As a second change, the new `type.__init__` just ignores keyword arguments. Currently, it insists that no keyword arguments are given. This leads to a (wanted) error if one gives keyword arguments to a class declaration if the metaclass does not process them. Metaclass authors that do want to accept keyword arguments must filter them out by overriding `__init__`.
>
>
>
Why is this (*potentially*) problematic? Well there are several questions (notably [this](https://stackoverflow.com/q/42281697/6741482)) describing the problem surrounding additional keyword arguments in a class definition, use of metaclasses (subsequently the `metaclass=` keyword) and the overridden `__init_subclass__`. However, that doesn't explain why it works in the currently given solution. The answer: `kwargs.pop()`.
If we look at the following:
```
# code in CPython 3.7
import os
import re
class FileSystem(object):
class NoAccess(Exception): pass
class Unknown(Exception): pass
# Regex for matching "xxx://" where x is any non-whitespace character except for ":".
_PATH_PREFIX_PATTERN = re.compile(r'\s*([^:]+)://')
_registry = {} # Registered subclasses.
def __init_subclass__(cls, **kwargs):
path_prefix = kwargs.pop('path_prefix', None)
super().__init_subclass__(**kwargs)
cls._registry[path_prefix] = cls # Add class to registry.
...
class Nfs(FileSystem, path_prefix='nfs'): ...
```
This will still run without issue, but if we remove the `kwargs.pop()`:
```
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs) # throws TypeError
cls._registry[path_prefix] = cls # Add class to registry.
```
The error thrown is already known and described in the PEP:
>
> **In the new code, it is not `__init__` that complains about keyword arguments, but `__init_subclass__`, whose default implementation takes no arguments**. In a classical inheritance scheme using the method resolution order, each `__init_subclass__` may take out it's keyword arguments until none are left, which is checked by the default implementation of `__init_subclass__`.
>
>
>
What is happening is the `path_prefix=` keyword is being "popped" off of `kwargs`, not just accessed, so then `**kwargs` is now empty and passed up the MRO and thus compliant with the default implementation (receiving no keyword arguments).
To avoid this entirely, I propose not relying on `kwargs` but instead use that which is already present in the call to `__init_subclass__`, namely the `cls` reference:
```
# code in CPython 3.7
import os
import re
class FileSystem(object):
class NoAccess(Exception): pass
class Unknown(Exception): pass
# Regex for matching "xxx://" where x is any non-whitespace character except for ":".
_PATH_PREFIX_PATTERN = re.compile(r'\s*([^:]+)://')
_registry = {} # Registered subclasses.
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls._registry[cls._path_prefix] = cls # Add class to registry.
...
class Nfs(FileSystem):
_path_prefix = 'nfs'
...
```
Adding the prior keyword as a class attribute also extends the use in later methods if one needs to refer back to the particular prefix used by the subclass (via `self._path_prefix`). To my knowledge, you cannot refer back to supplied keywords in the definition (without some complexity) and this seemed trivial and useful.
So to @martineau I apologize for my comments seeming confusing, only so much space to type them and as shown it was more detailed. |
69,718,039 | I am making this JS calculator project, which I want to make responsive. But it's not quite working properly.
I want to make the width of the .calculator slightly bigger when the screen becomes smaller because in the that way all the buttons can be shown properly(especially the operator ones).
Here is the codepen I have worked on:<https://codepen.io/tanjimanim/pen/jOwoYrV?editors=0110>
and the media query I have written.
```
@media screen and (min-device-width: 320px) and (max-device-width: 630px) {
.calculator {
width: 60%;
}
}
``` | 2021/10/26 | [
"https://Stackoverflow.com/questions/69718039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13689497/"
] | Use this code section in your CSS:
```
@media screen and (min-width: 320px) and (max-width: 630px) {
.calculator {
width: 60%;
}
button
{
padding:16px 0px;
}
}
```
`device-width` has been deprecated.
And to show all the `operator buttons` on all mobile device remove padding left and right from selector `button`.
[Have a look in this screenshot](https://i.stack.imgur.com/lHdje.png) | The device-width properties has been deprecated so use `min-width` instead. You can read on [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-width)
so change
* `min-device-width` to `min-width`
* `max-device-width` to `max-width`
```
@media screen and (min-width: 320px) and (max-width: 630px) {
.calculator {
width: 60%;
}
}
``` |
418,884 | I want to do something like:
```
command || log $error_from_last_command
```
Is there a way to use `||` and still access `stderr` like a pipe?
*My intention here is to process the error message from `command`, using `log`, but only if `command` fails.
I'm reading through the marked duplicate but I don't see how to apply that to my situation.* | 2018/01/22 | [
"https://unix.stackexchange.com/questions/418884",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/16792/"
] | If you want to use the output of a program in another that only runs after the first command completed, it's probably easiest to store the output in a file.
```
errfile=$(mktemp)
if ! somecommand 2> "$errfile" ; then
log < "$errfile" # or log "$(cat "$errfile")" ?
fi
rm "$errfile"
```
Piping the output would require the commands to run at the same time, but we only get the exit code when the first command finishes.
`log < "$errfile"` above would of course direct the error message to stdin of `log` (like you'd get with a pipe). To get it as a command line argument, use `log "$(cat "$errfile")"` (one argument), or `log $(cat "$errfile")` (with word splitting, `log` sees multiple arguments), or `log "$(< "$errfile")"` (non-standard, works at least in Bash). | If it would be sufficient for your purposes to know the *exit code* of the first element of the pipe (or any element of any pipe), you can avail yourself of the `bash` variable `PIPESTATUS`, which according to the `bash` man page is: "An array variable ... containing a list of exit status values from the processes in the most-recently-executed foreground pipeline ...".
I realize that technically you are asking for something a bit different, but you might consider whether using this variable might meet your need in a way you didn't originally anticipate. |
6,685,621 | So I got this error:
>
> Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\scanner\mine.php on line 112
>
>
>
On this line:
```
if(preg_match("inurl:", $text) {
```
Its part of a "Clean" function:
```
function Clean($text) {
if(preg_match("inurl:", $text) {
str_replace("inurl:", "", $text);
return htmlspecialchars($text, ENT_QUOTES);
} else {
return htmlspecialchars($text, ENT_QUOTES);
}
}
```
How can I fix it? | 2011/07/13 | [
"https://Stackoverflow.com/questions/6685621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/763725/"
] | Two problems, One closing ) and a missing semicolon after str\_replace, also you should know your str\_replace won't do anything in your code so i added $text = ... :)
```
function Clean($text) {
if(preg_match("inurl:", $text)) {
$text = str_replace("inurl:", "", $text);
return htmlspecialchars($text, ENT_QUOTES);
} else {
return htmlspecialchars($text, ENT_QUOTES);
}
}
``` | The if clause is superfluous anyway. The following function is equivalent to the original version (sans the non-compiling regex pattern).
```
function Clean($text)
{
$text = str_replace("inurl:", "", $text);
return htmlspecialchars($text, ENT_QUOTES);
}
```
If the string you want to replace is not found in the haystack, str\_replace won't do anything. So it is safe to run the function unconditionally.
In the original version, you'd also have to surround the regex pattern for preg\_match with delimiters (see: <http://www.php.net/manual/en/regexp.reference.delimiters.php>). (In this case, strpos would do the job, too.) |
46,677,774 | I'm trying to use the `isNaN` global function inside an arrow function in a Node.js module but I'm getting this error:
`[eslint] Unexpected use of 'isNaN'. (no-restricted-globals)`
This is my code:
```
const isNumber = value => !isNaN(parseFloat(value));
module.exports = {
isNumber,
};
```
Any idea on what am I doing wrong?
PS: I'm using the AirBnB style guide. | 2017/10/11 | [
"https://Stackoverflow.com/questions/46677774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4705426/"
] | In my case, I wanted to treat 5 (integer), 5.4(decimal), '5', '5.4' as numbers but nothing else for example.
If you have the similar requirements, below may work better:
```
const isNum = num => /^\d+$/.test(num) || /^\d+\.\d+$/.test(num);
//Check your variable if it is a number.
let myNum = 5;
console.log(isNum(myNum))
```
To include negative numbers:
```
const isNum = num => /^-?\d+$/.test(num) || /^-?\d+\.\d+$/.test(num);
```
This will remove your issue of global use of isNaN as well.
If you convert the isNum function to a normal ES5 function, it will work on IE browser as well. | For me this worked fine and didn't have any problem with ESlint
`window.isNaN()` |
50,227,596 | I went through the documentation to edit kubernetes resource using [`kubectl edit`](https://kubernetes-v1-4.github.io/docs/user-guide/kubectl/kubectl_edit/) command. Once I execute the command, the file in YAML-format is opened in the editor where I can change the values as per requirement and save it. I am trying to execute these steps by means of `sed`. How can the following steps be achieved?
1. Execute `kubectl edit` for a deployment resource
2. Set a value from `true` to `false` (using sed)
3. Save the changes
I tried to achieve this in the following way :
```
$ kubectl edit deployment tiller-deploy -n kube-system | \
sed -i "s/\(automountServiceAccountToken:.*$\)/automountServiceAccountToken: true/g"`
``` | 2018/05/08 | [
"https://Stackoverflow.com/questions/50227596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1117320/"
] | Your command is missing a backtick. But even though you put it there, it won't work. The reason is because when you do `kubectl edit ...`, it edits the file on vim. I am not sure sed would work on vim though. Even though if it does, the output goes to a file, so you get the `Vim: Warning: Output is not to a terminal` error, which I don't know how to solve.
I would recommend you to get the file and save it. Replace the desired parameters and run it again:
```
kubectl get deploy tiller-deploy -n kube-system -o yaml > tiller.yaml && sed -i "s/automountServiceAccountToken:.*$/automountServiceAccountToken: true/g" tiller.yaml && kubectl replace -f tiller.yaml
```
I tried the command above and it worked.
Note: no need to add `-n kube-system` as the yaml file already contains the namespace. | I just found a less convoluted way of doing this:
```
KUBE_EDITOR="sed -i s/SOMETHING TO CHANGE/CHANGED/g" kubectl edit resource -n your-ns
``` |
71,010 | I am looking for an AntiVirus for Ubuntu, and have researched potential products. I do not want a paid product, but i do want a user friendly interface.
**I do not want rants about how unnecessary it is on Ubuntu.**
My considerations are:
* [avast! Linux Home Edition](http://www.avast.com/linux-home-edition#tab4) (Free with Registration, 27.7MB)
* [AVG Anti-Virus Free Edition For Linux](http://free.avg.com/gb-en/download.prd-alf) (Free, 138MB)
* [Avira AntiVir Personal](http://www.avira.com/en/support-download-free-antivirus) (Free, 54.46MB)
* [Bitdefender for Unices](http://www.bitdefender.co.uk/business/antivirus-for-unices.html) (Free with Registration, 27.7MB)
* [ClamAV](http://www.clamav.net/lang/en/download/) (Open-Source, Free, 45.8MB)
My concerns are:
1. Ease of Scan
2. Ease of Update
3. Ease of Schedule
4. Detection Rates
Which, if any, come with good GUIs?
Note: I am willing to do complicated setup, so long as my great aunt can use it. | 2011/10/23 | [
"https://askubuntu.com/questions/71010",
"https://askubuntu.com",
"https://askubuntu.com/users/24819/"
] | There is also BitDefender Antivirus Scanner which is a free download.
It keeps out of the way until you need it or you can set it to run in the background as in windows.
<http://www.bitdefender.co.uk/business/antivirus-for-unices.html>
Once on this page there is a link on the left hand side to 'Request a Free License
(for personal use only)'
Get it from [here](http://download.bitdefender.com/SMB/Workstation_Security_and_Management/BitDefender_Antivirus_Scanner_for_Unices/Unix/Current/EN_FR_BR_RO/Linux/). | Subjective question, but I would add ClamAV to plus ones. |
39,461,992 | I want set shadow with `UICollectionViewCell`, like this:

I write code in Custom Cell
```
override func awakeFromNib() {
super.awakeFromNib()
layer.shadowColor = UIColor(red: 0.7176470757, green: 0.7176470757, blue: 0.7176470757, alpha: 1.0000000000).CGColor
layer.shadowOffset = CGSizeMake(0, 4)
layer.shadowRadius = 2
layer.shadowOpacity = 1
}
```
but can't set cell shadow. All subview by set shadow:

How can I solve this problem? | 2016/09/13 | [
"https://Stackoverflow.com/questions/39461992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3977282/"
] | **Go to the collectionviewcell.m and add these manually.**
I did this to fix it.
```
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
//////// make shadow of total view
self.clipsToBounds = NO;
self.layer.masksToBounds = NO;
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = 0.5;
self.layer.shadowColor = [UIColor blackColor].CGColor;
self.layer.shadowOffset = CGSizeMake(0, 1);
self.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
// make radius of the cell
self.layer.cornerRadius = 5;
}
return self;
}
```
It will add effects and if you want to add some ui then code inside it. | Add this line too:
```
layer.masksToBounds = false
```
By default it is `true` and limits the Cell within its frame size, by setting it to `false` allows cell's shadow to be visible outside its frame. |
22,158,154 | Every question I search for about the warning
>
> Warning: Null value is eliminated by an aggregate or other SET operation.
>
>
>
Typically people want to treat the NULL values as 0. I want the opposite, how do I modify the following stored procedure to make it return NULL instead of 1?
```
CREATE PROCEDURE TestProcedure
AS
BEGIN
select cast(null as int) as foo into #tmp
insert into #tmp values (1)
select sum(foo) from #tmp
END
GO
```
I thought it would be `SET ANSI_NULLS ON` (I tried before the declaration, within the procedure itself, and before executing the procedure in my test query) but that did not appear to change the behavior of `SUM(`. | 2014/03/03 | [
"https://Stackoverflow.com/questions/22158154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80274/"
] | The `sum()` function automatically ignores `NULL`. To do what you want, you need an explicit checK:
```
select (case when count(foo) = count(*) then sum(foo) end)
from #tmp;
```
If you want to be explicit, you could add `else NULL` to the `case` statement.
The logic behind this is that `count(foo)` counts the number of non-NULL values in `foo`. If this is equal to all the rows, then all the values are non-NULL. You could use the more verbose:
```
select (case when sum(case when foo is null then 1 else 0 end) > 0
then sum(foo)
end)
```
And, I want to point out that the title is quite misleading. `1 + NULL = NULL`. The issue is with the aggregation functions, not the arithmetic operators. | Looking for a null value with `EXISTS` may be the fastest:
```
SELECT
CASE WHEN EXISTS(SELECT NULL FROM tmp WHERE foo IS NULL)
THEN NULL
ELSE (SELECT sum(foo) from tmp)
END
``` |
22,732,857 | So basically I have a class for a TicTacToe game and a derived class just to practice using inheritance. The class has several methods and all should work perfectly fine but in the main function, when I finally make three objects of the derived class I get three errors "use of unassigned local variable 'boardOne'" "use of unassigned local variable 'boardTwo'" and "use of unassigned local variable 'boardThree'". I do not understand why this is, they are objects, not variables.
```
public class TicTacToe
{
protected char[] boardCells = new char[9];
public int boardSpacesUsed;
public TicTacToe() //constructor
{
boardCells[0] = '1';
boardCells[1] = '2';
boardCells[2] = '3';
boardCells[3] = '4';
boardCells[4] = '5';
boardCells[5] = '6';
boardCells[6] = '7';
boardCells[7] = '8';
boardCells[8] = '9';
boardCells[9] = '\0';
int boardSpacesUsed = 0;
}
public void playerOneMove()
{
bool space = false;
char cell = '\0';
while (space == false)
{
Console.WriteLine("Please enter cell number you wish to mark: ");
cell = Convert.ToChar(Console.ReadLine());
switch (cell)
{
case '1':
if (boardCells[0] == 'X' || boardCells[0] == 'O')
{
Console.WriteLine("Illegal Move");
}
else
{
boardCells[0] = 'X';
space = true;
}
break;
case '2':
if (boardCells[1] == 'X' || boardCells[1] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[1] = 'X';
space = true;
}
break;
case '3':
if (boardCells[2] == 'X' || boardCells[2] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[2] = 'X';
space = true;
}
break;
case '4':
if (boardCells[3] == 'X' || boardCells[3] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[3] = 'X';
space = true;
}
break;
case '5':
if (boardCells[4] == 'X' || boardCells[4] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[4] = 'X';
space = true;
}
break;
case '6':
if (boardCells[5] == 'X' || boardCells[5] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[5] = 'X';
space = true;
}
break;
case '7':
if (boardCells[6] == 'X' || boardCells[6] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[6] = 'X';
space = true;
}
break;
case '8':
if (boardCells[7] == 'X' || boardCells[7] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[7] = 'X';
space = true;
}
break;
case '9':
if (boardCells[8] == 'X' || boardCells[8] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[8] = 'X';
space = true;
}
break;
default:
Console.WriteLine("Cell Does NOT Exist!");
break;
}// end of switch statement
}//end of while loop
boardSpacesUsed++;
}// end of playerOneMove();
public void CPUMove() //method marks cell for CPU
{
int iCell = 0;
bool space = false;
while (space == false)
{
Random rand = new Random();
iCell = rand.Next(1, 9);
switch (iCell) //switch statement to mark the cell
{
case 1:
if (boardCells[0] == 'X' || boardCells[0] == 'O')
{
space = false;
}
else
{
boardCells[0] = 'O';
space = true;
}
break;
case 2:
if (boardCells[1] == 'X' || boardCells[1] == 'O')
space = false;
else
{
boardCells[1] = 'O';
space = true;
}
break;
case 3:
if (boardCells[2] == 'X' || boardCells[2] == 'O')
space = false;
else
{
boardCells[2] = 'O';
space = true;
}
break;
case 4:
if (boardCells[3] == 'X' || boardCells[3] == 'O')
space = false;
else
{
boardCells[3] = 'O';
space = true;
}
break;
case 5:
if (boardCells[4] == 'X' || boardCells[4] == 'O')
space = false;
else
{
boardCells[4] = 'O';
space = true;
}
break;
case 6:
if (boardCells[5] == 'X' || boardCells[5] == 'O')
space = false;
else
{
boardCells[5] = 'O';
space = true;
}
break;
case 7:
if (boardCells[6] == 'X' || boardCells[6] == 'O')
space = false;
else
{
boardCells[6] = 'O';
space = true;
}
break;
case 8:
if (boardCells[7] == 'X' || boardCells[7] == 'O')
space = false;
else
{
boardCells[7] = 'O';
space = true;
}
break;
case 9:
if (boardCells[8] == 'X' || boardCells[8] == 'O')
space = false;
else
{
boardCells[8] = 'O';
space = true;
}
break;
}
}
boardSpacesUsed++;
}
public void getBoardCells()
{
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
Console.WriteLine(" " + boardCells[0] + " | " + boardCells[1] + " | " + boardCells[2]);
Console.WriteLine("__" + "_" + "__|__" + "_" + "__|__" + "_");
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
Console.WriteLine(" " + boardCells[3] + " | " + boardCells[4] + " | " + boardCells[5]);
Console.WriteLine("__" + "_" + "__|__" + "_" + "__|__" + "_");
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
Console.WriteLine(" " + boardCells[6] + " | " + boardCells[7] + " | " + boardCells[8]);
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
}
public bool playerOneWinCheck(ref int score)
{
bool check = false;
if (boardCells[0] == 'X' && boardCells[1] == 'X' && boardCells[2] == 'X')
{
check = true;
score++;
}
if (boardCells[3] == 'X' && boardCells[4] == 'X' && boardCells[5] == 'X')
{
check = true;
score++;
}
if (boardCells[6] == 'X' && boardCells[7] == 'X' && boardCells[8] == 'X')
{
check = true;
score++;
}
if (boardCells[0] == 'X' && boardCells[3] == 'X' && boardCells[6] == 'X')
{
check = true;
score++;
}
if (boardCells[1] == 'X' && boardCells[4] == 'X' && boardCells[7] == 'X')
{
check = true;
score++;
}
if (boardCells[2] == 'X' && boardCells[5] == 'X' && boardCells[8] == 'X')
{
check = true;
score++;
}
if (boardCells[0] == 'X' && boardCells[4] == 'X' && boardCells[8] == 'X')
{
check = true;
score++;
}
if (boardCells[6] == 'X' && boardCells[4] == 'X' && boardCells[2] == 'X')
{
check = true;
score++;
}
if (check == true)
return true;
else
return false;
}
public bool CPUWinCheck(ref int score) //Method to check to see if CPU won INCRAMENTS SCORE UP ONE IF ANYTHING HOLDS TRUE
{
bool check = false;
if (boardCells[0] == 'O' && boardCells[1] == 'O' && boardCells[2] == 'O')
{
check = true;
score++;
}
if (boardCells[3] == 'O' && boardCells[4] == 'O' && boardCells[5] == 'O')
{
check = true;
score++;
}
if (boardCells[6] == 'O' && boardCells[7] == 'O' && boardCells[8] == 'O')
{
check = true;
score++;
}
if (boardCells[0] == 'O' && boardCells[3] == 'O' && boardCells[6] == 'O')
{
check = true;
score++;
}
if (boardCells[1] == 'O' && boardCells[4] == 'O' && boardCells[7] == 'O')
{
check = true;
score++;
}
if (boardCells[2] == 'O' && boardCells[5] == 'O' && boardCells[8] == 'O')
{
check = true;
score++;
}
if (boardCells[0] == 'O' && boardCells[4] == 'O' && boardCells[8] == 'O')
{
check = true;
score++;
}
if (boardCells[6] == 'O' && boardCells[4] == 'O' && boardCells[2] == 'O')
{
check = true;
score++;
}
if (check == true)
return true;
else
return false;
}
~TicTacToe()
{
for (int c = 0; c <= 10; c++)
{
boardCells[c] = '\0';
}
boardSpacesUsed = 0;
}
}
public class ThreeD : TicTacToe
{
public void threeDWinCheck(ThreeD boardOne, ThreeD boardTwo, ThreeD boardThree, ref int score) //new function to check to see ThreeD wins
{
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[0] == 'X' && boardThree.boardCells[0] == 'X')
{
score++;
Console.WriteLine("did it make it");
}
if (boardOne.boardCells[1] == 'X' && boardTwo.boardCells[1] == 'X' && boardThree.boardCells[1] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[2] == 'X' && boardThree.boardCells[2] == 'X')
score++;
if (boardOne.boardCells[3] == 'X' && boardTwo.boardCells[3] == 'X' && boardThree.boardCells[3] == 'X')
score++;
if (boardOne.boardCells[4] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[4] == 'X')
score++;
if (boardOne.boardCells[5] == 'X' && boardTwo.boardCells[5] == 'X' && boardThree.boardCells[5] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[6] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[7] == 'X' && boardTwo.boardCells[7] == 'X' && boardThree.boardCells[7] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[8] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[1] == 'X' && boardThree.boardCells[2] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[1] == 'X' && boardThree.boardCells[0] == 'X')
score++;
if (boardOne.boardCells[3] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[5] == 'X')
score++;
if (boardOne.boardCells[5] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[3] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[7] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[7] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[3] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[3] == 'X' && boardThree.boardCells[0] == 'X')
score++;
if (boardOne.boardCells[1] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[7] == 'X')
score++;
if (boardOne.boardCells[7] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[1] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[5] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[5] == 'X' && boardThree.boardCells[2] == 'X')
score++;
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[0] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[2] == 'X')
score++;
}
public void CPUThreeDWinCheck(ThreeD boardOne, ThreeD boardTwo, ThreeD boardThree, ref int score) //new function to check CPU ThreeD wins
{
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[0] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[1] == 'O' && boardTwo.boardCells[1] == 'O' && boardThree.boardCells[1] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[2] == 'O' && boardThree.boardCells[2] == 'O')
score++;
if (boardOne.boardCells[3] == 'O' && boardTwo.boardCells[3] == 'O' && boardThree.boardCells[3] == 'O')
score++;
if (boardOne.boardCells[4] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[4] == 'O')
score++;
if (boardOne.boardCells[5] == 'O' && boardTwo.boardCells[5] == 'O' && boardThree.boardCells[5] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[6] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[7] == 'O' && boardTwo.boardCells[7] == 'O' && boardThree.boardCells[7] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[8] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[1] == 'O' && boardThree.boardCells[2] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[1] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[3] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[5] == 'O')
score++;
if (boardOne.boardCells[5] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[3] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[7] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[7] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[3] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[3] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[1] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[7] == 'O')
score++;
if (boardOne.boardCells[7] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[1] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[5] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[5] == 'O' && boardThree.boardCells[2] == 'O')
score++;
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[2] == 'O')
score++;
}
~ThreeD()
{
for (int c = 0; c < 10; c++)
{
boardCells[c] = '\0';
}
}
}
static void Main(string[] args)
{
ThreeD boardOne; //1st of three objects for first board
ThreeD boardTwo; //2nd
ThreeD boardThree; //3rd
int boardSelection = 0; //picks witch object to mark in
int counter = 0; //counter for while loop
int playerOneScore = 0; //score for user
int CPUScore = 0; //score for cpu
int CPUBoardSelection = 0;
Random rand = new Random();
int randomNum = rand.Next(1, 2);
if (randomNum == 1) // if randomNum = 1, user goes first
{
Console.WriteLine("You first");
while (true)
{
boardOne.getBoardCells();
boardTwo.getBoardCells();
boardThree.getBoardCells();
Console.WriteLine("Choose which board you wish to mark in. (1 - 3)"); //promts you to pick board
bool board = false;
``` | 2014/03/29 | [
"https://Stackoverflow.com/questions/22732857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3471066/"
] | Yes, the compiler is *right*: you're trying to use *unassigned variables*:
```
static void Main(string[] args)
{
// It's just a declaration; no value assigned to boardOne; boardOne contains trash
ThreeD boardOne;
// It's just a declaration; no value assigned to boardTwo; boardTwo contains trash
ThreeD boardTwo;
// It's just a declaration; no value assigned to boardThree; boardThree contains trash
ThreeD boardThree;
....
if (randomNum == 1)
{
Console.WriteLine("You first");
while (true)
{
boardOne.getBoardCells(); // <- And here you're trying to access the trash
```
It should be something like that:
```
static void Main(string[] args)
{
// boardOne is declared and assigned
ThreeD boardOne = new ThreeD();
// boardTwo is declared and assigned
ThreeD boardTwo = new ThreeD();
// boardThree is declared and assigned
ThreeD boardThree = new ThreeD();
....
if (randomNum == 1)
{
Console.WriteLine("You first");
while (true)
{
boardOne.getBoardCells(); // <- Quite OK
``` | your missing creating object instance
ThreeD boardOne = new ThreeD();
ThreeD boardTwo = new ThreeD();
ThreeD boardThree = new ThreeD(); |
148,542 | Let $A\_\bullet$ be a dg-algebra over a field $k$. Let $M\_\bullet$ (resp. $N\_\bullet$) be a right (resp. left) $A\_\bullet$-module. There is then a notion of the **derived tensor product**:
$$M\_\bullet\otimes^L\_{A\_\bullet}N\_\bullet=\bigoplus\_{p\geq 0}M\_\bullet\otimes(A\_\bullet)^{\otimes p}\otimes N\_\bullet$$
(where $\otimes$ is $\otimes\_k$) with differential given by the internal differential on each direct summand plus an alternating sum of all possible maps multiplying adjacent elements (decreasing $p$ by one). We can rewrite this as:
$$(M\_\bullet\otimes^L\_{A\_\bullet}N\_\bullet)\_j=\bigoplus\_{p\geq 0}(M\_\bullet\otimes(A\_\bullet)^{\otimes p}\otimes N\_\bullet)\_{j-p}$$
But now (based on my limited understanding) it is not clear to me why we shouldn't instead take direct product instead of direct sum, and define:
$$(M\_\bullet\otimes^L\_{A\_\bullet}N\_\bullet)\_j=\prod\_{p\geq 0}(M\_\bullet\otimes(A\_\bullet)^{\otimes p}\otimes N\_\bullet)\_{j-p}$$
Note that with this definition the differential still makes sense.
The definition with the direct sum seems to be standard. On the other hand, I have encountered a context where I want to write down a certain element in $M\_\bullet\otimes^L\_{A\_\bullet}N\_\bullet$, but it lies in the direct product (and not in the direct sum). Hence my question is:
>
> Which of the two definitions of $M\_\bullet\otimes^L\_{A\_\bullet}N\_\bullet$ given above is correct, and why?
>
>
>
Note that when $A\_\bullet$ is concentrated in nonnegative degrees, taking direct product instead of direct sum makes no difference, since for fixed $j$, the factors on the right become trivial for sufficiently large $p$. Hence this question is only non-vacuous when $A\_\bullet$ is nontrivial in negative degrees. | 2013/11/11 | [
"https://mathoverflow.net/questions/148542",
"https://mathoverflow.net",
"https://mathoverflow.net/users/35353/"
] | Omitting the stars, what you have written down is a two-sided bar construction $B(M,A,N)$,
unreduced since you have not assumed that $A$ is augmented. Note that in degree $n$ it
is the direct sum over $p+q=n$ of the elements of the $p$th term in degree $q$. One
conceptual way of thinking about it is that that we can write
$B(M,A,N) = M\otimes\_A B(A,A,N)$. Depending on taste and background, one can view
$B(A,A,N)$ as a kind of projective resolution of $N$, a point of view that goes back
to Cartan and Eilenberg, or one can view $B(A,A,N)$ as a cofibrant approximation of
$N$ in model theoretic terms. For a recent exposition that explains and compares
these points of view (allowing $k$ to be a general commutative ring) see <http://arxiv.org/pdf/1310.1159.pdf>.
For either point of view, you want sums and not products. | In the case when $M=N=A$, your question reduces to the comparison between the usual direct sum Hochschild chain complex versus the direct product chain complex. It is important to use the direct sum chain complex in proving that Hochschild homology is a homotopy invariant of $A$. To see this, observe that the Hochschild differential decomposes to $d\_1+d\_2$ with $d\_i$ induced by $m\_i$ of $A$. In the case of direct sum, we can start with $d\_1$ to compute Hochschild homology using spectral sequence method, which would yield the same complex if $A$ and $B$ are quasi-isomorphic. This argument fails in the direct product case. |
218,181 | We all know some individuals who don’t express their opinions as:
>
> I *think* this is going to happen...
>
>
>
Instead, they express it as if it were fact or news, e.g.:
>
> Next month the price of (something) *is going to* increase by 10 percent.
>
>
>
What do you call such people? And are there any idioms or sayings to describe them? | 2015/01/03 | [
"https://english.stackexchange.com/questions/218181",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/89324/"
] | The term I'd use is [**rumour-monger** (BrE) or **rumormonger** (AmE):](http://www.oxforddictionaries.com/us/definition/english/rumour-monger)
>
> NOUN
>
>
> *derogator*y
>
>
> A person who spreads rumours.
>
>
> EXAMPLE SENTENCES
>
>
> *A list of six names was compiled by the gossips and rumour-mongers of Belgravia, among them key figures from high society - aristocracy, government ministers and film stars.*
>
>
> *The rumour-mongers have portrayed me as a hard-bitten political adventuress devoid of all human feeling.*
>
>
> *What will these crazy rumour-mongers think of next?*
>
>
>
(Definition and examples from Oxforddictionaries.com) | I'd call him **"an unreliable source"** Not an idiom, but it seems to translate what you are looking for.
"Forget what he said about us getting a bonus in December. He is a most unreliable source." |
22,398,987 | I'm doing an online course on "Programming, Data Structure & Algorithm". I've been given an assignment to "find the most frequent element in a sequence using arrays in C (with some constraints)". They've also provided some test-cases to verify the correctness of the program. But I think I'm wrong somewhere.
Here's the complete question from my online course.
>
> INPUT
>
>
> Input contains two lines. First line in the input indicates N,
> the number of integers in the sequence. Second line contains N
> integers, separated by white space.
>
>
> OUTPUT
>
>
> Element with the maximum frequency. If two numbers have the
> same highest frequency, print the number that appears first in the
> sequence.
>
>
> CONSTRAINTS
>
>
> 1 <= N <= 10000
>
>
> The integers will be in the range
>
>
> [-100,100].
>
>
>
And here's the test cases.
Test Case 1
Input:
```
5
1 2 1 3 1
```
Output:
```
1
```
Input:
```
6
7 7 -2 3 1 1
```
Output:
```
7
```
And here's the code that I've written.
```
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < -100 && input < 100)
++counter[input];
}
maximum = counter[0];
for (i = 1; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
}
}
printf("%d", maximum);
return 0;
}
```
Please tell me where I'm wrong. Thank you.
EDIT:
I've modified the code, as suggested by @zoska. Here's the working code.
```
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < 100 && input > 0)
++counter[input + 100];
else
++counter[input];
}
maximum = counter[0];
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = i - 100;
}
}
printf("%d", maximum);
return 0;
}
``` | 2014/03/14 | [
"https://Stackoverflow.com/questions/22398987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Additionally to problem pointed out by Paul R is:
You are printing maximum occurrences of number, not the number itself.
You're going to need another variable, which will store the number with maximum occurences. Like :
```
maximum = count[0];
int number = -100;
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
number = i - 100;
}
}
printf("number %d has maximum occurences: %d", number, maximum);
```
Also you should iterate through an array from 0 to size-1:
So in all cases of your loops it should be :
```
for(i = 0; i < 201; i++)
```
Otherwise you won't be using count[0] and you will only have a range of -99...100. | I would prefer checking in one loop itself for the maximum value just so that the first number is returned if i have more than one element with maximum number of occurances.
FInd the code as:
```
#include<stdio.h>
int main()
{
int n,input;
scanf("%d",&n);
int count[201] ={0};
int max=0,found=-1;
for(int i=0;i<n;i++)
{
scanf("%d",&input);
count[input+100]++;
if(max<count[input+100])
{
max= count[input+100];
found=input;
}
}
printf("%d",found);
return 0;
}
``` |
67,327,244 | I have 3 dataframes with different columns with each row having diferent IDs (for all 3 DF).
I have appended all of those rows id in a Dataframe4 and sorted.
and I'm trying to read each line of the 3 dataframes in the right order, based on the dataframe4 sorted.
but i'm stuck here:
```py
df1 = pd.DataFrame({
'rowid': ['1', '4'],
'Column2': ['1100', '1100']
})
df2 = pd.DataFrame({
'rowid': ['2', '5', '7', '9', '11', '13'],
'Column3': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],
'Column4': ['wer', 'cad', 'sder', 'dse', 'sdf', 'csd']
})
df3 = pd.DataFrame({
'rowid': ['3', '6', '8', '10', '12', '14'],
'Column3': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],
'Column4': ['wer', 'cad', 'sder', 'dse', 'sdf', 'csd'],
'Column5': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],
'Column6': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],
})
df4 = pd.DataFrame({
'rowid': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
})
for df in df4:
d = df4["rowid"]
for i in df1, df2, df3:
j = d.isin(i['rowid'])
res = [k for k, val in enumerate(j) if val]
print(res)
```
**Any ideas?**
**the simple append and sort won't work because of different columns, i'll read each line as txt**
**Desired Output:**
```
1, 1100
2, xxr, wer
3, xxr, wer, xxr, xxr
4, 1100
5, xxv, cad
6, xxv, cad, xxv, xxv
...
14, xxz, csd, xxz, xxz
``` | 2021/04/30 | [
"https://Stackoverflow.com/questions/67327244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10676834/"
] | 1. [Concat](https://pandas.pydata.org/docs/reference/api/pandas.concat.html#pandas-concat) df1, df2, df3 together.
2. Build a sorter to order based on the values in df4. (See. [sorting by a custom list in pandas](https://stackoverflow.com/q/23482668/15497888))
3. [Apply](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html#pandas-dataframe-apply) and use [', '.join](https://docs.python.org/3/library/stdtypes.html#str.join) on all [notnull](https://pandas.pydata.org/docs/reference/api/pandas.Series.notnull.html#pandas-series-notnull) values in the row.
4. Join the whole dataframe with '\n':
```py
import pandas as pd
df1 = pd.DataFrame({
'rowid': ['1', '4'],
'Column2': ['1100', '1100']
})
df2 = pd.DataFrame({
'rowid': ['2', '5', '7', '9', '11', '13'],
'Column3': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],
'Column4': ['wer', 'cad', 'sder', 'dse', 'sdf', 'csd']
})
df3 = pd.DataFrame({
'rowid': ['3', '6', '8', '10', '12', '14'],
'Column3': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],
'Column4': ['wer', 'cad', 'sder', 'dse', 'sdf', 'csd'],
'Column5': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],
'Column6': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],
})
df4 = pd.DataFrame({
'rowid': ['1', '2', '3', '4', '5', '6', '7', '8', '9',
'10', '11', '12', '13', '14']
})
# Concat DataFrames Together
merged = pd.concat((df1, df2, df3))
# Build Sorter
sorterIndex = dict(zip(df4['rowid'], range(len(df4['rowid']))))
# Apply Rank to each Index
merged['rank'] = merged['rowid'].map(sorterIndex)
# Sort By Rank and Remove Column
merged = merged.sort_values('rank').drop(columns=['rank'])
# Join Not Nulls with ', '
output = merged.apply(lambda s: ', '.join(s[s.notnull()]), axis=1)
# Display Output on New Lines
print('\n'.join(output))
```
Output:
```
1, 1100
2, xxr, wer
3, xxr, wer, xxr, xxr
4, 1100
5, xxv, cad
6, xxv, cad, xxv, xxv
7, xxw, sder
8, xxw, sder, xxw, xxw
9, xxt, dse
10, xxt, dse, xxt, xxt
11, xxe, sdf
12, xxe, sdf, xxe, xxe
13, xxz, csd
14, xxz, csd, xxz, xxz
``` | I merged the dataframe then made rowid as index. Finally I sorted rowid in ascending.
Hope this would work
```
import pandas as pd
df1 = pd.DataFrame({
'rowid': ['1', '4'],
'Column2': ['1100', '1100']})
df2 = pd.DataFrame({
'rowid': ['2', '5', '7', '9', '11', '13'],
'Column3': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],
'Column4': ['wer', 'cad', 'sder', 'dse', 'sdf', 'csd']})
df3 = pd.DataFrame({
'rowid': ['3', '6', '8', '10', '12', '14'],
'Column3': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],
'Column4': ['wer', 'cad', 'sder', 'dse', 'sdf', 'csd'],
'Column5': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],
'Column6': ['xxr', 'xxv', 'xxw', 'xxt', 'xxe', 'xxz'],})
merged = pd.concat((df1, df2, df3))
merged
merged = merged.set_index("rowid")
merged = merged.sort_index()
merged
``` |
4,073,303 | We filmed a spokesperson on a green screen and have the video files ready in multiple formats.
With Flash we could use the wmode transparent within the param and embed tags, but is there something similar to this with the video and source tags in HTML5? Is it even possible to properly save .m4v or .ogv videos so that we can play these files with transparent backgrounds on our browsers?
Thanks | 2010/11/01 | [
"https://Stackoverflow.com/questions/4073303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/494100/"
] | While this isn't possible with the video itself, you could use a canvas to draw the frames of the video except for pixels in a color range or whatever. It would take some javascript and such of course. See [Video Puzzle](http://www.infinything.com/CanvasVidPuzzle.html) (apparently broken at the moment), [Exploding Video](http://www.craftymind.com/factory/html5video/CanvasVideo.html), and [Realtime Video -> ASCII](http://betaweb.csug.rochester.edu/~jparish/public/canvas/video.html) | webm format is the best solution for Chrome > 29, but it is not supported in Firefox IE and Safari, the best solution is using Flash (wmode="transparent"). but you have to forget "ios". |
10,575,558 | I'm reading more open source javascript frameworks and found more ways of how to create anonymous functions, but whats is different and best way?
```
(function() {
this.Lib = {};
}).call(this);
(function() {
var Lib = {}; window.Lib = Lib;
})();
(function(global) {
var Lib = {}; global.Lib = Lib;
})(global);
``` | 2012/05/13 | [
"https://Stackoverflow.com/questions/10575558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1366538/"
] | ```
(function() {
this.Lib = {};
}).call(this);
```
Defines the `Lib` property of the Object it's called on, and is immediately called on `this` which is typically the `window`. It may instead refer to the Object that owns the method in which it is called.
```
(function() {
var Lib = {}; window.Lib = Lib;
})();
```
Defines the `Lib` property of `window` regardless of where it's called (although it's also called immediately).
```
(function(global) {
var Lib = {}; global.Lib = Lib;
})(global);
```
Defines the `Lib` property of the object passed to the function. It's called immediately, but will result in an error unless you've defined a value for `global` in the current scope. You might pass `window` or some namespacing Object to it.
---
These aren't actually different ways of defining "anonymous functions", they all use the standard way of doing this. These are different methods of assigning values to global (or effectively global) properties. In this sense, they are basically equivalent.
Of more significance would be, for instance, how they define methods and properties of the objects they return/construct/expose (that is, how they build `Lib` itself).
All of these functions return `undefined` and only the first could be usefully applied as a constructor (with the use of `new`), so it would seem they are nothing more than initializers for the frameworks. | All of them are effectively equivalent (but less efficient and more obfuscated) to:
```
var Lib = {};
```
Immediately invoked function expressions (IIFEs) are handy for contianing the scope of variables that don't need to be available more widely and conditionally creating objecs and methods, but they can be over used.
Note that in the last example, I think you mean:
```
(function(global) {
...
})(this);
``` |
28,407,342 | I have this table (say TABLE1):
```
ID1 | ID2 | NAME
```
where (ID1, ID2) is the composite PK.
And this another table (say TABLE2):
```
ID | COD1 | COD2 | DATA | INDEX
```
where ID is the PK.
I need to join this tables on `((TABLE1.ID1 = TABLE2.COD1) AND (TABLE1.ID2 = TABLE2.COD2))`
My problem is that, for each ID of TABLE2, I have many tuples with different INDEX. I only want join the tuple that its INDEX is the MAX of its group (COD1, COD2).
For instance, if I have:
```
ID1|ID2|NAME
10 10 JOSH
ID|COD1|COD2|DATA|INDEX
1 10 10 YES 0
2 10 10 NO 1
3 11 10 OH 0
```
I want to get:
```
ID1|ID2|NAME|DATA
10 10 JOSH NO
```
I have tried this but it doesn't work:
```
SELECT ID1, ID2, NAME, DATA
FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.ID1 = T2.COD1 AND T1.ID2 = T2.COD2
GROUP BY ID1, ID2, NAME, DATA HAVING INDEX = MAX(INDEX)
```
Thanks. | 2015/02/09 | [
"https://Stackoverflow.com/questions/28407342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3026283/"
] | A slightly different solution:
```
select t1.id1, t1.id2, t1."NAME", t3."DATA"
from table1 t1
left join
(
select max("INDEX") as maxindex, cod1, cod2
from table2
group by cod1, cod2
) tt on tt.cod1 = t1.id1 and tt.cod2 = t1.id2
left join table2 t2 on t2."INDEX" = tt.maxindex;
```
If all tuples have different and unique values INDEX, these example is OK. But if some tuples have the same value, it is necessary to write an additional subquery (e.g. select max(ID) from table2) to determine appropriate lines.
P.S. It's best not to use any keyword for your own tables or columns (e.g. INDEX, DATA ...).
[How To Handle Table Column Named With Reserved Sql Keyword?](https://stackoverflow.com/questions/11629966/how-to-handle-table-column-named-with-reserved-sql-keyword)
[Got an Oracle Table Named as Reserved Word, Which problems may arise?](https://stackoverflow.com/questions/4750211/got-an-oracle-table-named-as-reserved-word-which-problems-may-arise) | try
```
SELECT ID1,ID2,NAME
FROM TABLE1
join
(select ID,DATA, max(Index) themax
FROM TABLE2
WHERE (your condition)
group by ID) temp on table1.Index = themax
WHERE (your condition)
``` |
10,700,179 | I am making a Device Discovery windows application in C#. Is this possible to know the device type if I have MAC address or IP address?
device type means either it is computer or router or mobile or any other device?
Note: HostName entry is not useful for it because Host Name is defined by User. for example i may assign "Nokia N70" name to my computer.
Thanks in anticipation. | 2012/05/22 | [
"https://Stackoverflow.com/questions/10700179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1389475/"
] | You can get the manufacturer from the MAC address. In order to get any more information you'd need to do a port scan to do a 'fingerprint' of the device in question.
Application such as [NMAP](http://nmap.org/) use this approach. | IP Address: No. The Internet Protocol address can not help you figure out which device is being used
As for the MAC address: See [this](http://www.coffer.com/mac_find/) website.
Basicly, each vendor 'owns' a range of MAC addresses, this specific website can ever offer you the range used for each vendor. pretty neat. |
41,470,296 | Assume there is a function `doRequest(options)`, which is supposed to perform an HTTP request and uses `http.request()` for that.
If `doRequest()` is called in a loop, I want that the next request is made after the previous finished (serial execution, one after another). In order to not mess with callbacks and Promises, I want to use the async/await pattern (transpiled with Babel.js to run with Node 6+).
However, it is unclear to me, how to wait for the response object for further processing and how to return it as result of `doRequest()`:
```
var doRequest = async function (options) {
var req = await http.request(options);
// do we need "await" here somehow?
req.on('response', res => {
console.log('response received');
return res.statusCode;
});
req.end(); // make the request, returns just a boolean
// return some result here?!
};
```
If I run my current code using *mocha* using various options for the HTTP requests, all of the requests are made simultaneously it seems. They all fail, probably because `doRequest()` does not actually return anything:
```
describe('Requests', function() {
var t = [ /* request options */ ];
t.forEach(function(options) {
it('should return 200: ' + options.path, () => {
chai.assert.equal(doRequest(options), 200);
});
});
});
``` | 2017/01/04 | [
"https://Stackoverflow.com/questions/41470296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2044940/"
] | ```
https.get('https://example.com', options, async res => {
try {
let body = '';
res.setEncoding('utf-8');
for await (const chunk of res) {
body += chunk;
}
console.log('RESPONSE', body);
} catch (e) {
console.log('ERROR', e);
}
});
``` | I tried to make the second function from the accepted answer readable.
```
function actuallyDownloadFile( url ) {
return new Promise ( ( resolve, reject ) => {
const request = http.get( url );
request.on( 'response', ( response ) => {
console.log( 'Doing magic...' );
resolve( response );
} );
request.on( 'error', ( err ) => {
console.error( 'An error occurred' );
resolve( err );
} );
} );
}
async function downloadFile( url ) {
try {
const response = await actuallyDownloadFile( url );
console.log( response );
} catch ( err ) {
console.error( err );
}
}
``` |
42,308,193 | I have a date column `CreateDate (datetime, not null)` in my table.
Using the following where clause:
```
Where
-- Code for 12 Months Back at a Time
CreateDate >= dateadd(month,datediff(month, 0, getdate())-12,0)
```
If I run my report say on March 1, 2017, I should get 12 months of data. I do.
I would like to order by `CreateDate` and get the following order
```
Mar 2017
Feb 2017
Jan 2017
Dec 2016
Nov 2016
Oct 2016
Sep 2016
Aug 2016
Jul 2016
Jun 2016
May 2016
Apr 2016
```
Here is the complete query:
```
SELECT DISTINCT
tblCourtAttorneysAssigned.CourtAssignment AS [CourtAssignment],
tblCourtAttorneysAssigned.AttorneyBarNumber AS [AttorneyBarNumber],
tblCourtAttorneysAssigned.AttorneyFirstName AS [AttorneyFirstName],
tblCourtAttorneysAssigned.AttorneyLastName AS [AttorneyLastName],
--tblCourtAttorneysAssigned.CaseNo,
--tblPeople.LastName,
--tblPeople.FirstName,
tblCourtAttorneysAssigned.HowAssigned AS [HowAssigned],
CONVERT( VARCHAR(10), tblCourtAttorneysAssigned.CreateDate, 101) AS[CreateDate]
FROM tblBookIn
INNER JOIN tblOffense ON tblBookIn.BookInID = tblOffense.BookInID
INNER JOIN tblPeople ON tblBookIn.PersonID = tblPeople.PersonID
INNER JOIN tblCourtAttorneysAssigned ON tblOffense.CaseNo = tblCourtAttorneysAssigned.CaseNo
WHERE CourtAssignment LIKE 'M%'
AND
-- Code for 12 Months Back at a Time
CreateDate >= dateadd(month,datediff(month, 0, getdate())-12,0)
ORDER by
[CreateDate] asc
--courtassignment ASC,
-- AttorneyLastName ASC;
```
Thanks | 2017/02/17 | [
"https://Stackoverflow.com/questions/42308193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2051440/"
] | I am guessing you are using `order by CreateDate desc` but you have aliased CreateDate in your query to be something like `format(CreateDate, 'MMM yyyy') as CreateDate`
So your `order by` will need to know you want it to use the original value instead of the new value that is being returned with the same name.
Try `order by mytablename.CreateDate desc`
---
Update after question edited to include query:
change your `order by` to:
```
order by tblCourtAttorneysAssigned.CreateDate desc
``` | Thanks all, I have resolved the issue by removing the Convert on the date field and fixing the format in SSRS.
Thanks, |
9,081,598 | I have the following code:
```
long[] conIds = GetIDs();
dc.ExecuteCommand("UPDATE Deliveries SET Invoiced = NULL WHERE ID IN {0}",conIds);
```
I'd expect that to work, but the executecommand statement throws an exception stating that
>
> A query parameter cannot be of type int64[].
>
>
>
Why is this? | 2012/01/31 | [
"https://Stackoverflow.com/questions/9081598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/460407/"
] | You are passing an array of longs into a placeholder where a string is expected. You need to convert the array into a concatenated string with comma delimiters. Then, pass that into the command text.
Depending on where else you are using the `GetIDs` method, you could simplify your code by having that method return an array of strings. Then you can easily use `String.Join` here to convert that array to the concatenated text that you want. | You can't do this. SQL parameters must be single values.
You can make this work by converting your array to a list of comma separated values.
See [here](https://stackoverflow.com/questions/182060/where-in-array-of-ids) for an example.
```
command.CommandText = command.CommandText.Replace(
"@conIDs",
string.Join(conIDs.Select(b => b.ToString()), ",")
);
```
In general, it's better to serialize your SQL and use a table valued parameter for this sort of thing. See [this question](https://stackoverflow.com/questions/337704/parameterizing-an-sql-in-clause/337817#337817) for instructions. |
12,481,434 | I am using Jquery PrettyPhoto to have a slide show, however it does not let the users to download the images. Anyone know how can I add a link to it so users will be able to download the images?
Here is my code: (I am using prettyPhoto Widget in Yii, but any answer in general for prettyPhoto will be great)
```
<?php
$this->beginWidget('ext.prettyPhoto.PrettyPhoto', array(
'id'=>'pretty_photo',
// prettyPhoto options
'options'=>array(
'opacity'=>0.60,
'modal'=>true,
),
));
?>
<div class="column4-front image-gallery">
<a href="/files/show/<?php echo $data->image; ?>" rel="prettyPhoto[pp_gal]" title="<?php echo $data->caption; ?>">
<img src="/files/show/thumb/<?php echo $data->image; ?>" />
</a>
</div>
<?php $this->endWidget('widgets.prettyPhoto');?>
``` | 2012/09/18 | [
"https://Stackoverflow.com/questions/12481434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1353497/"
] | Easy!
HTML **(title is empty!)**
```
<a id="photo_link" href="http://link_to_image_or_video" rel="prettyPhoto" title="">
<img src="images/play-video.png" alt="" title="" width="380" height="147" />
</a>
```
JS (inside the document ready)
```
//do not show title on download link hover (download button)
$("#photo_link").hover(function(e){
$(this).attr('data-title', $(this).attr('title'));
$(this).removeAttr('title');
},
function(e){
$(this).attr('title', $(this).attr('data-title'));
});
//add download link on the fly on click of photo link
$("#photo_link").on('click', function(){
$(this).attr('title', '<div class="center"><a href="#download_link" class="btn btn-primary btn-lg"><strong>Download</strong></a></div>');
});
```
No PrettyPhoto JS changes are necessary. Here is the simple idea. Yours to play inside Yii
framework.
Even easier: Only JS (include JS in your view)
```
$("a[rel^='prettyPhoto']").prettyPhoto({
social_tools: '<div class="center"><a id="get_started" href="#contact" class="btn btn-primary btn-lg"><strong>Download</strong></a></div>',
default_width: 800,
default_height: 450
});
``` | OK, I solved my problem, [here](http://www.catpin.com/prettyphoto.php) is an example that I found. They have added the link to download the photo like this:
```
<ul class='gallery clearfix'>
<li>
<a href='./uploads/1f.jpg' rel='prettyPhoto[gallery1]' title='Nature Photo One' >
<img src='./uploads/1t.jpg' border='0' alt='' link='<a href="download.php?f=1f.jpg" class="url">Download This Photo</a>' />
</a>
</li>
// REST OF THE IMAGES
</ul>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("a[rel^='prettyPhoto']").prettyPhoto({theme: 'light_rounded'});
});
</script>
```
There is a need to make some changes to the jquery.prettyphoto.js file. I used v 3.1.2 which can be downloaded [here](http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/)
This is the changes I made using the example that I mentioned [before](http://www.catpin.com/prettyphoto.php)
```
(function($) {
$.prettyPhoto = {version: '3.1.4'};
$.fn.prettyPhoto = function(pp_settings) {
pp_settings = jQuery.extend({
//....
social_tools: '<div class="pp_social"><span class="pp_link"></span></div>'
// I deleted the rest in social_tools since I wasn't going to use them, you can just add this to the begining of it.
}, pp_settings);
//....
/*
* Initialize prettyPhoto.
*/
$.prettyPhoto.initialize = function() {
//...
pp_links=(isSet)?jQuery.map(matchedObjects,function(n,i){if($(n).attr('rel').indexOf(theRel)!=-1)return($(n).find('img').attr('link'))?$(n).find('img').attr('link'):"";}):$.makeArray($(this).find('img').attr('link'));
//...
}
//...
$.prettyPhoto.open = function(event) {
//....
if(pp_links[set_position]!=""){$pp_pic_holder.find('.pp_link').show().html(unescape(pp_links[set_position]));}else{$pp_pic_holder.find('.pp_link').hide();}
//....
}
```
And if you want to use it with the [prettyphoto extention](http://www.yiiframework.com/extension/prettyphoto/) in yii. You can replace the javaScript file with the file that you modified. Then:
```
<?php
$this->beginWidget('ext.prettyPhoto.PrettyPhoto', array(
'id'=>'pretty_photo',
// prettyPhoto options
'options'=>array(
'opacity'=>0.60,
'modal'=>true,
'theme'=> 'light_rounded'
),
));
?>
<div class="column4-front image-gallery">
<a href="/files/immagini/<?php echo $data->image; ?>" rel="prettyPhoto[pp_gal]" title="<?php echo $data->caption; ?>">
<img src="/files/immagini/thumb/<?php echo $data->image; ?>" link='<a href="<?php echo $this->createUrl('compania/downloadimage',array('f'=>$data->image)); ?>" class="url">Scarica questo foto</a>'/>
</a>
</div>
<?php $this->endWidget('widgets.prettyPhoto');?>
```
And add this to the related controller, for me CompaniaController:
```
public function actionDownloadImage()
{
$filename = $_GET['f'];
$fileDir='path to image';
Yii::app()->request->sendFile(
$filename,
file_get_contents($fileDir.$filename)
);
}
``` |
8,115,997 | I exported my matlab structs to text files so that I can read them in clojure.
I have a text file like:
```
name
Ali
age
33
friends-ages
30
31
25
47
```
know I can read this file, but what's the clojure way to convert it into something like:
```
(def person1
{:name "Ali"
:age 33
:friends-ages [30 31 25 47]})
```
or lets make it easier:
```
name
Ali
age
33
```
to:
```
(def person1
{:name "Ali"
:age 33})
``` | 2011/11/14 | [
"https://Stackoverflow.com/questions/8115997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/487855/"
] | Assuming each file has a single record,
```
(defn parse [f]
(let [[_ name _ age _ & friends] (.split (slurp f) "\n")]
{:name name :age age :friends (map read-string friends)}))
(parse "../../../Desktop/t.txt")
```
you get,
```
{:name "Ali", :age "33", :friends-ages (30 31 25 47)}
``` | I ended up writing an .m file to export my .mat files to text, then imported them by something like the following:
```
(use '[clojure.string :only (split join)])
(defn kv [[k v]]
[(keyword k) v])
(let [a (split (slurp (java.io.FileReader. fileName)) #"\n")]
(def testNeuron (into {} (map kv (partition 2 a)))))
```
Thanks to the answers by Hamza and Jouni.
The actual code is more like this:
```
(def dataPath "/home/ali/Dropbox/Projects/Neurojure/")
(def testFileName "dae062.c1.cylinder.DID.txt")
(defn kv [[k v]]
[(keyword k)
(if (< 0 (count (re-seq #"\d\d\d\dSpikes|\d\d\d\dOcodes|\d\d\d\dOSpikes" k)))
(into [] (map (fn [x] (Integer/valueOf x)) (split v #",")))
(try (Integer/valueOf v)
(catch NumberFormatException _ v)))])
(let [a (split (slurp (java.io.FileReader. (str dataPath testFileName))) #"\n")]
(def testNeuron (into {} (map kv (partition 2 a)))))
```
and the converted data file looks like this:
```
ConvertDate
18-Nov-2011
Name
/bgc/data/dae/062/dae062.mat
frameperiod
83.2500000037253
Spike2Version
1.27
unstored
167
rfstr
cm=rf-3.10,9.61:0.00x0.00,-135deg pe20 -2.0,-3.0 fx=0.00,fy=0.00cm=rf-3.10,9.61:0.00x0.00,-135deg pe20 -2.0,-3.0 fx=0.00,fy=0.00
rf
-3.1,9.61,0,0,-135,20,-2,-3,0,0
trange
47371169.75,100193717.5
psych
1
rc
0
Options
expname
cylinder.dxXIdD
Start
94745610.75
End
100193717.5
Area
MT
Ex
perimenter Ali
Trial=>0001Start
47377343
Trial=>0001TrialStart
47377343
Trial=>0001End
47397224.25
Trial=>0001dur
19881.2500000075
Trial=>0001uStim
0
Trial=>0001op
40980
Trial=>0001Trial
1860
Trial=>0001id
15897
Trial=>0001Startev
47377149.5
Trial=>0001serdelay
-46.25
Trial=>0001bstimes
47377195.75
Trial=>0001delay
147.25
Trial=>0001TrueEnd
47397224.25
Trial=>0001CorLoop
0
Trial=>0001dx
0
Trial=>0001Spikes
-1402,-1232,1577,1931,2165,2222,2478,2773,2903,3229,3745,3820,4071,4588,4920,5141,5752,6440,6490,6664,6770,7042,7958,8081,8307,8622,8732,9021,9082,9343,9619,9695,9877,10357,10668,10943,11105,11364,11720,12272,12499,12762,12907,13621,14121,14351,14542,14588,15104,15420,15501,16331,16596,16843,17476,17698,17996,18169,18401,18532,18706,19029,19081,19418,19603,19750,20222
Trial=>0001count
65
Trial=>0001OptionCode
+do+aa+sq+72+se+fc+fb+ap+wt+cf+ws+ts+sw+bw+cs+2a+bm+gm+x2+sp+da+ao+cS+C3+CF
Trial=>0001me
0
Trial=>0001OSpikes
-1976,-1802,-1423,-1360,-1268,-1248,-1140,-244,-220,-164,632,681,730,760,779,786,867,879,924,1062,1161,1252,1268,1431,1533,1632,1946,2210,2235,2273,2285,2296,2305,2496,2532,2541,2732,2787,2806,2822,2840,3095,3292,3431,3598,3614,3837,4100,4482,4504,4515,4651,4768,4794,4936,5020,5160,5184,5300,5314,5710,5764,6431,6453,6471,6553,6561,6584,6791,7018,7124,7880,7905,7940,7968,8011,8315,8330,8352,8568,8666,8748,8756,8766,8797,8836,9038,9297,9328,9360,9471,9632,9639,9721,9939,10196,10363,10375,10387,10410,10931,10953,10969,10986,11038,11118,11135,11405,11692,12018,12163,12258,12492,12512,12525,12884,12899,12919,13156,13183,13638,13674,13842,13988,14110,14298,14310,14321,14606,14617,15124,15132,15150,15289,15341,15620,16293,16305,16342,16364,16441,16604,16692,16932,16997,17059,17086,17210,17368,17495,17626,17639,17651,17677,17718,18013,18247,18353,18553,18691,18722,18887,18941,19438,19774,19938,19959,19967,20004,20240,20306,20500,20623
Trial=>0002Start
47406914
Trial=>0002TrialStart
47406914
Trial=>0002End
47426795.25
Trial=>0002dur
19881.2499999925
...
``` |
44,971 | I live in a town where fresh or whole milk is not readily available.
I was wondering if I could make cheese from UHT Milk.
If so, what kind of cheese and what method I should use?
Or rather, Should I? | 2014/06/19 | [
"https://cooking.stackexchange.com/questions/44971",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/25507/"
] | The self-appointed Cheese Queen, Ricky, recommends making mozzarella from dry-milk powder and added cream if you're in an area where you can only get UHT milk: [Mozzarella from Instant Nonfat Dry Milk and Cream](http://cheesemaking.com/store/pg/262-MozzarellaDryMilk.html).
That may be a better option that trying Mozzarella from UHT milk. Which, as @Jolenealaska points out, is [known to be pretty bad](http://www.cheesemaking.com/ultrapasteurizedmilkforcheese.html).
Alternately, you could try non-rennet cheese -- but my personal experience has been that mozzarella is a lot more fun. | Yes, you can use UHT mik to make a rennet cheese.
You would need to use calcium chloride and the double amount of rennet.
Then the curds will be like rice.
You press it, and you have cheese. |
30,645,022 | I've read [here](https://stackoverflow.com/a/2530007/589192) about the difference between functions and methods in scala. It says that methods can be slightly faster than functions. But when passing a method `m` as an argument using `m _`, m is implicitly converted to a function.
1. Is the performance difference significant enough to ponder avoiding Functions when it is going to be a bottleneck in my program?
2. Is there a way to pass a method as an argument without converting it to a Function? | 2015/06/04 | [
"https://Stackoverflow.com/questions/30645022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/589192/"
] | 1. Kind of irrelevant to by **2**. But in general, forget about performance, methods are more readable than function declarations. They might be a little faster in some situations from compiler optimizations, but:
2. You cannot pass a method as an argument without converting it to a function. A method is a special language construct, and not an object itself. You must use eta-expansion to convert it to one if you want to use it as an object. | 1. No.
2. No. In the extremely rare case where this kind of microperformance was important, you'd want to pass the object that the method is on, and either modify the receiving function to accept that, or make the object implement one of the `FunctionN` interfaces so that it can be used as a function. |
27,982,333 | I've got a query as below:
```
IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL BEGIN
drop table #Temp1
end
SELECT * into #Temp1
from (
SELECT 1, NULL, NULL, NULL, NULL
UNION ALL SELECT 2, NULL, NULL, NULL, NULL
UNION ALL SELECT 3, NULL, NULL, NULL, NULL
UNION ALL SELECT 4, NULL, NULL, NULL, NULL
UNION ALL SELECT 5, NULL, NULL, NULL, NULL
UNION ALL SELECT 6, NULL, NULL, NULL, NULL
UNION ALL SELECT 7, NULL, NULL, NULL, NULL
UNION ALL SELECT 8, NULL, NULL, NULL, NULL
UNION ALL SELECT 9, NULL, NULL, NULL, NULL
)
as databases (tempid, tasknr, devcat, taskop, taskcl)
IF OBJECT_ID('tempdb..#Temp1a') IS NOT NULL BEGIN
drop table #Temp1a
end
SELECT * into #Temp1a
from (
select
cast(ROW_NUMBER() OVER(PARTITION BY parent_change ORDER BY number)as int) as tempid
,number as tasknr
,category as cat
,orig_date_entered as taskop
,case when (CM3TM1.status = 'closed') then CM3TM1.date_entered else NULL end as taskcl
FROM CM3TM1
WHERE parent_change IN ('C45168')
and category = 'NEU Development'
)
as databases (tempid, tasknr, devcat, taskop, taskcl)
UPDATE
#Temp1
SET
#Temp1.tasknr = #Temp1a.tasknr,
#Temp1.devcat = #Temp1a.devcat
FROM
#Temp1a
INNER JOIN
#Temp1
ON
#Temp1.tempid = #Temp1a.tempid
```
and I'm getting
>
> Msg 245, Level 16, State 1, Line 38 Conversion failed when converting
> the varchar value 'T85158' to data type int.
>
>
>
T85158 is related to 'tasknr' column.
I need to update such NULL table with different types of data where number of rows is changeable. I had tried to add `,cast((number) as int) as tasknr`
but it didn't help.
Please let me know how to make this work correctly. | 2015/01/16 | [
"https://Stackoverflow.com/questions/27982333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4418039/"
] | Two possible answers
1. **You Can't:** Because you can't pass objects from one activity to another (until and unless it is Parcelable) in android
2. **You Can:** You can use `shared preferences` to pass primitive data from one activity to another OR you can use single instance (singleton) class to set/get `objects` from one place to another. | You can create a class that extends Application class and create a singleton of that object inside it. This way you can access this object in all of your activity.
```
public class GlobalClass extends Application {
NetworkHandler nH = null;
public NetworkHandler getNetworkHandler() {
if (nH == null) {
nH = new NetworkHandler();
}
return nH;
}
}
```
in your AndroidManifest.xml mention the name your class
```
<application
android:name=".GlobalClass " >
```
You can access this object in any class using following code.
```
GlobalClass gObj = (GlobalClass) this.getApplication();
NetworkHandler nH = gObj.getNetworkHandler()
``` |
15,896,699 | I am trying to show the following in the ER diagram:
```
There are instructors and courses, a course is taught by only one instructor
whereas an instructor can give many courses.
```


My question is, is there any difference between two diagrams, in other words, does it matter which line we turn into an arrow, or what only matters is only the direction of the arrow?
Also, if we think about the mapping cardinalities; is it 1 to many or many to 1? If we think in terms of courses, then it is many to one but if we think in terms of instructors, then it is one to many. How do we decide this?
Thank you. | 2013/04/09 | [
"https://Stackoverflow.com/questions/15896699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2237469/"
] | In ER diagrams when the relationship is denoted the arrows are not used. Some instructors use this arrow when they want to decide the cardinalities but that is just to get the cardinality (1:1, 1:M and N:M)
I have attached the ER diagram for this in Chen notation and also using Crow Notation you can use either of them.

Deciding the cardinality for a relationship is a practical scenario there is no hard and pass rule to obtain it. What you need to do is start from one side of the relationship and take one tuple (instance) and see how many tuples from the other entity participate for the relationship. Then do the vise versa. Then you know the participation number of tuples) from each entity to the relationship. Think about set theory and functions in mathematics when you decide the cardinality (ie Set of instructors, Set of Courses and set of Teaches relationship type) then this is so easy but if you are not from a mathematic background just think of practical scenario.
**For Example**
a) For 1 instructor he or she can teach Many (M) courses
b) For 1 Course there is only 1 instructor
so in instructor side there is always 1 in a) and b) but in Courses there is M and 1 in a) and b) there for Instructor:Course cardinality is 1:M | I don't think the other answer is fully correct.
I would say that one *should* use arrows, and one should use a notation that gives a meaningful name to *each direction* of the relationship. In this case it will be "teaches" in one direction, and "is taught by" in the other. Either use arrows next to the names or put the name near to the entity to which it refers. You could use one line (with two arrow heads) or two lines (with one arrow each).
I would also suggest that cardinality is just one kind of constraint, and the notation should reflect that. For example, the two names for the relationship could be "teaches (many)" and "is taught by (exactly one)". The point is you might have "teaches (one or two)" or "is taught by (exactly two)" and so on.
It is better to be explicit and clear about exactly what your constraints really are. |
9,486,039 | I have many entities that have the `IsActive` property. For internal reasons, I need all those fields to be nullable. On the other hand, for every entity I may have to do a double test in tens of places in the application:
(null are treated as true)
```
if (language.IsActive == null || language.IsActive.value)
```
If I create a method like
```
class Language
{
public bool IsActiveLanguage()
{
return language.IsActive == null || language.IsActive.value;
}
}
```
It still won't hide the property (at least from inside the class) so it's error prone.
I tried to find a way to override, but of course I can't change the return type to plain `bool`.
What would you do to avoid redundancy in this case? | 2012/02/28 | [
"https://Stackoverflow.com/questions/9486039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/457500/"
] | If your property is `Nullable<>` and a `null` value means `true`, you could use this instead of an explicit null check:
```
language.IsActive.GetValueOrDefault(true);
``` | Why don't you just hide this implementation detail in the getter:
```
private bool? _IsActive;
public bool IsActive { get { return !_IsActive.HasValue ||_IsActive; } }
```
EDIT: After realizing the properties are generated and can't be modified
You could declare a new type, called ThreeValBool, which is essentially a bool?, and add an implicit cast from it to bool, like so:
```
struct ThreeValBool
{
private bool? _value;
public static implicit operator bool(ThreeValBool tvb)
{
return !tvb._value.HasValue || tvb.value;
}
}
```
Obviously you need to add a way to set the value...
Make your properties of that type (hopefully the designer will let you do that). |
54,238,142 | I have a dataframe that I would like to delete rows from, based on a value in a specific column.
As an example, the dataframe appears something like this:
```
a b c d
1 1 2 3 0
2 4 NA 1 NA
3 6 4 0 1
4 NA 5 0 0
```
I would like to remove all rows with a value greater than 0 in column d. I have been trying to use the following code to do this:
```
df <- df[!df$d > 0, ]
```
but this is appearing to have the effect of deleting all the value is rows with an NA value in column d. I was assuming that a `na.rm = TRUE`argument was needed but I wasn't sure where to fit it in the function above.
Cheers,
Ant | 2019/01/17 | [
"https://Stackoverflow.com/questions/54238142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10743287/"
] | We need to select the rows where `d` is not greater than 0 OR there is `NA` in `d`
```
df[with(df, !d > 0 | is.na(d)), ]
# a b c d
#1 1 2 3 0
#2 4 NA 1 NA
#4 NA 5 0 0
```
Or we can also use `subset`
```
subset(df, !d > 0 | is.na(d))
```
or `dplyr` `filter`
```
library(dplyr)
df %>% filter(!d > 0 | is.na(d))
```
---
The `!d > 0` part can also be reversed to
```
subset(df, d < 1 | is.na(d))
```
to get the same result. | If u add a `|`all rows that has a `NA` will match. The condition `!df$d > 0` will get executed for those in `d` that are not a `NA`. So I think you were looking for:
```
df[is.na(df$d) | !df$d > 0, ]
```
Wheras, the below wont include the rows that has a `NA` in column `d` and that does not match the condition `!df$d > 0`
```
df[!is.na(df$d) & !df$d > 0, ]
``` |
12,574 | I need to delete one or multiple rows from my table with where condition.
Eg: 1. Delete from search where id=1 and customerid=2
EG: 2. Delete from search where customerid=2
After some browsing found this code and added to my model
```
public function deleteByCondition($id,$uid)
{
$table = $this->getMainTable();
$result = $this->_getWriteAdapter->delete($table,array('id'=>$id,'customerid'=>$uid));
}
```
But it didn't help. Then got another code which didn't help either.
```
public function deleteByCondition($id,$uid)
{
$table = $this->getMainTable();
$where = $this->_getWriteAdapter()->quoteInto('id = ? AND',$id).$this->_getWriteAdapter()->quoteInto("$customerid = ? ", $uid);
$result = $this->_getWriteAdapter->delete($table,array('id'=>$id,'customerid'=>$uid),$where);
}
```
I know we can execute the raw sql query but am thinking there must be other way to do coz i think its not the proper way to open the write connection any where and update DB.
Now i need to delete with where condition. can someone help ? | 2014/01/02 | [
"https://magento.stackexchange.com/questions/12574",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/2552/"
] | If we need to create an order then ask the user for payment, we will place the order using the Purchase Order method and send the customer a PayPal invoice. Once we receive the payment we send the order confirmation email. | The way that Magento would want you to do this is to prepare the order for them. In EE 1.12+ you can see and edit items in a customer's shopping cart. You can also edit their default billing and shipping addresses for them.
In essence, with no code or an extension required, you have the ability to prepare a customer's shopping cart for them to finalize by checking out. This is not an ideal solution if you do not run EE and it is not meant to be a full answer (most likely not worthy of a bounty) but it is a feature many do not know about.
Best of luck. |
11,488,988 | When I try to compile [this program](http://ideone.com/7KfWn), I get an "unreachable statement" error in line 21:
```
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.lang.StringBuilder;
class FilePrep {
public static void main(String args[]) {
}
public String getStringFromBuffer() {
try {
Path file = Paths.get("testfile2.txt");
FileInputStream fstream = new FileInputStream("testfile2.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String inputLine = null;
StringBuffer theText = new StringBuffer();
while((inputLine=br.readLine())!=null) {
theText.append(inputLine+" ");
}
return theText.toString();
System.out.println(theText); // <-- line 21
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
return null;
}
}
}
```
The full compiler output is:
```
Main.java:21: error: unreachable statement
System.out.println(theText);
^
Main.java:28: error: missing return statement
}
^
2 errors
```
I *think* the `return` statements are in the right places...they seem to be to me at least, and the program seems so simple compared to the one that I cloned it from, that I'm having a really hard time figuring out why this statement is unreachable.
What did I do wrong while copying the code, and how do I need to correct it? | 2012/07/15 | [
"https://Stackoverflow.com/questions/11488988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1267125/"
] | When the `return` statement is executed, the method relinquish control to its caller. That is why the `println` will not run; that's why the compiler complains.
Unreachable statements are certain and reliable indicators of a logical error in your program. It means that you put in statements that will not be executed, but you assume that they would be. The compiler analyzes the flow, and reports these statements to you as error messages. | The `return` statement always should be at the end or last line of the definition block. If you keep any statements after the `return` statement those statements are unreachable statements by the controller. By using `return` statement we are telling control should go back to its caller explicitly.
For example
```
public class Z
{
public int test()
{
System.out.println(10);
return 10;
System.out.println(20);
}
}
```
In this example we get compile time error as `unreachable code` because control cannot reach to last statement for execution.
So, always `return` statement should be the last statement of a definition block. |
74,851 | the setting premises are explained in this other question [Survival of an Industrial Revolution city after being transported to a fantasy world](https://worldbuilding.stackexchange.com/questions/73534/survival-of-an-industrial-revolution-city-after-being-transported-to-a-fantasy-w)
What I had in mind today is this: on Stitch theres an area (say less than 10 miles radius) where the underground is made of a very lightweight material; imagine a cone that starts from the surface and ends reaching the planet core that is made of this alien material (I imagine this material similar to cork wood). The surface area looks like a kinda normal temperate valley, but when you enter it you almost immediately start being in low gravity, almost like walking on the moon.
Is there any way to make this premise scientifically based and not in any way be magic related? | 2017/03/21 | [
"https://worldbuilding.stackexchange.com/questions/74851",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/34401/"
] | There's a problem here: unless gravity is very different in this world you're not going to feel much lighter. you don't just experience gravity from the things directly bellow you. You're also going to get pulled towards the rest of the planet. At best gravity would be a tiny tiny tiny bit different at the center of the area.
<https://en.wikipedia.org/wiki/Shell_theorem>
Take it to extremes: even if the entire world was hollow, if the total mass of the shell was similar was similar you would still experience a gravitational pull towards the center point as if the shell was not actually hollow. | Replace the area with some other fluid that is denser than normal air. This will increase buoyancy and create the illusion that things are much lighter than they are. |
13,826,351 | JQuery is kind of new to me and I set up a search suggestions system using ajax that works great but works pretty slow due to the onKeyUp limitation. After some reading I found that I can set a timer on the event. So what I am trying to do is set a timer on the 'prod-name-input' input field onKeyUp event, so that it is called every 2 seconds. I found a few examples for this online, but I wasn't able to apply any of them to my code successfully, I was wondering if someone can walk me through how this works? many thanks in advance.
My input field
```
<input onKeyUp="search(this.value)" type="text" class="prod-name-input"/>
```
JS
```
function search(searchword) {
$('.smart-suggestions').load('invoice-get-data.php?searchword=' + searchword);
}
``` | 2012/12/11 | [
"https://Stackoverflow.com/questions/13826351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316524/"
] | The fastest way would actually be to use the keydown event. (it acts on the key being down rather than being released which is always sooner.)
```
var timer;
$(".prod-name-input").keydown(function(){
var self = this;
clearTimeout(timer);
timer = setTimeout(function(){
$(".smart-suggestions").load('invoice-get-data.php?searchword=' + self.value);
},250);
});
```
This loads results if the user stops typing for more than 1/4 of a second. If too many requests are happening, increase the delay to 500.
I'll go over the code line by line with comments:
```
// declare a variable that will hold a reference to the timer we create
var timer;
// bind a keydown event to all existing elements that have the prod-name-input class
$(".prod-name-input").keydown(function(){
// store a reference to the clicked element so we can access it inside of setTimeout()
var self = this;
// clear existing timer stored in the timer variable (if any)
clearTimeout(timer);
// create a new timer and store it in the timer variable
timer = setTimeout(function(){
// load content
$(".smart-suggestions").load('invoice-get-data.php?searchword=' + self.value);
// give the timer a 250ms delay (0.25 seconds or 1/4 of a second)
},250);
});
``` | There is a throttle function in underscore.js that handles this scenario. You can see their [annotated source](http://underscorejs.org/docs/underscore.html#section-62) for exact code, or if you use underscore.js in your project, some usage documentation [here](http://underscorejs.org/#throttle) |
3,782,197 | I have been trying to set up a DatabaseConnectionPool for a web app for the last couple of days with no success. I have read the relevant sections of the Tomcat docs and a great deal around the subject and think I'm doing everything right, but obviously not because I keep on getting the following error:
```
Cannot create PoolableConnectionFactory (Access denied for user ''@'localhost' (using password: YES))
```
I'm not getting the error when I start Tomcat running, but when I try to run the following servlet:
```
package twittersearch.web;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import twittersearch.model.*;
public class ConPoolTest extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
Context ctx = null;
DataSource ds = null;
Connection conn = null;
try {
ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/twittersearchdb");
conn = ds.getConnection();
if(conn != null) {
System.out.println("have a connection from the pool");
}
} catch(SQLException e) {
e.printStackTrace();
} catch(NamingException e) {
e.printStackTrace();
} finally {
try {
if(conn!=null) {
conn.close();
}
} catch(SQLException e) {
e.printStackTrace();
}
}
}
}
```
The context for the webapp is:
```
<?xml version='1.0' encoding='utf-8'?>
<Context>
<!-- Configure a JDBC DataSource for the user database -->
<Resource name="jdbc/twittersearchdb"
type="javax.sql.DataSource"
auth="Container"
user="root"
password="mypwd"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/twitter"
maxActive="8"
maxIdle="4"/>
</Context>
```
What I really don't understand is why the error isn't saying that the access is denied to 'root'@'localhost' when I've specified that that's the user.
What I've tried:
Do I have a duplicate context.xml? No. I deleted the default on in Tomcat 6.0/conf. I tried putting a context.xml in [mywebappname]/META-INF/context.xml but not only did this not work, but resulted in the creation of a file named TwitterSearch.xml which was autogenerated and put in the Tomcat 6.0/conf/Catalina/localhost directory. So now I'm just editing that one and thats the only one I have.
Is it the version of Tomcat? Well, I completely reinstalled the latest version of Tomcat 6.0 so I don't think it's that.
Are we missing some jars? I have the tomcat-dbcp.jar, jconnector.jar and all the other ones that I think I'm meant to have in the Tomcat 6.0/lib directory.
When I look at the passwords in the MySQL database they seem to have been coded for security purposes into a long alpha-numeric string. Is this normal? Should I have this in my context.xml or just the normal password?
I really don't know how I can sort this out and would really appreciate some expert advice.
Many thanks in advance.
Joe | 2010/09/23 | [
"https://Stackoverflow.com/questions/3782197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2106959/"
] | In your configuration context.xml for the webapp you have to change user="root" by username="root" | In my case (MySql v.5.7) I got this error due to creation of the user via GRANT command:
```
GRANT ALL PRIVILEGES ON *.* TO myuser@localhost IDENTIFIED BY 'mypassword' WITH GRANT OPTION;
```
Using CREATE command instead, resolved the above error:
```
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON *.* TO myuser@localhost WITH GRANT OPTION;
```
Hope it'll helps somebody |
19,982,113 | I have the following extension method to find an element within a sequence, and then return two `IEnumerable<T>`s: one containing all the elements before that element, and one containing the element and everything that follows. I would prefer if the method were lazy, but I haven't figured out a way to do that. Can anyone come up with a solution?
```
public static PartitionTuple<T> Partition<T>(this IEnumerable<T> sequence, Func<T, bool> partition)
{
var a = sequence.ToArray();
return new PartitionTuple<T>
{
Before = a.TakeWhile(v => !partition(v)),
After = a.SkipWhile(v => !partition(v))
};
}
```
Doing `sequence.ToArray()` immediately defeats the laziness requirement. However, without that line, an expensive-to-iterate `sequence` may be iterated over twice. And, depending on what the calling code does, many more times. | 2013/11/14 | [
"https://Stackoverflow.com/questions/19982113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8368/"
] | You can use the `Lazy` object to ensure that the source sequence isn't converted to an array until one of the two partitions is iterated:
```
public static PartitionTuple<T> Partition<T>(
this IEnumerable<T> sequence, Func<T, bool> partition)
{
var lazy = new Lazy<IEnumerable<T>>(() => sequence.ToArray());
return new PartitionTuple<T>
{
Before = lazy.MapLazySequence(s => s.TakeWhile(v => !partition(v))),
After = lazy.MapLazySequence(s => s.SkipWhile(v => !partition(v)))
};
}
```
We'll use this method to defer evaluating the lazy until the sequence itself is iterated:
```
public static IEnumerable<TResult> MapLazySequence<TSource, TResult>(
this Lazy<IEnumerable<TSource>> lazy,
Func<IEnumerable<TSource>, IEnumerable<TResult>> filter)
{
foreach (var item in filter(lazy.Value))
yield return item;
}
``` | Generally, you just return some object of your custom class, which implements `IEnumerable<T>` but also provides the results on enumeration demand only.
You can also implement `IQueryable<T>` (inherits IEnumerable) instead of `IEnumerable<T>`, but it's rather needed for building reach functionality with queries like the one, which `linq for sql` provides: database query being executed only on the final enumeration request. |
62,715,853 | I want to create specific version of redis to be used as a cache. Task:
* Pod must run in web namespace
* Pod name should be cache
* Image name is lfccncf/redis with the 4.0-alpine tag
* Expose port 6379
* The pods need to be running after complete
This are my steps:
* `k create ns web`
* `k -n web run cache --image=lfccncf/redis:4.0-alpine --port=6379 --dry-run=client-o yaml > pod1.yaml`
* vi pod1.yaml
* pod looks like this
[](https://i.stack.imgur.com/7lkup.png)
* `k create -f pod1.yaml`
When the expose service name is not define is this right command to fully complete the task ?
`k expose pod cache --port=6379 --target-port=6379`.
Is it the best way to keep pod running using command like this command: `["/bin/sh", "-ec", "sleep 1000"]` ? | 2020/07/03 | [
"https://Stackoverflow.com/questions/62715853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11568656/"
] | You should not use `sleep` to keep a redis pod running. As long as the redis process runs in the container the pod will be running. | The best way to go about it is to take a stable helm chart from <https://hub.helm.sh/charts/stable/redis-ha>. Do a helm pull and modify the values as you need.
Redis should be definde as a Statefulset for various reasons. You could also do a
```
mkdir my-redis
helm fetch --untar --untardir . 'stable/redis' #makes a directory called redis
helm template --output-dir './my-redis' './redis' #redis dir (local helm chart), export to my-redis dir
```
then use [**Kustomise**](https://kustomize.io/) if you like.
You will notice that a redis deployment definition is not so trivial when you see how much code there is in the stable chart.
You can then expose it in various ways, but normally you need the access only within the cluster.
If you need a fast way to test from outside the cluster or use it as a development environment check the official ways to do that. |
341,551 | I think the approach can be with `adjustbox` but not sure.
Pseudocode:
* *If height overfull, turn the image 90 degree clockwise, apply all images the width constraint now*
* *Do not pass max width (= `\linewidth`) in any case*.
In other words, preudocode
* If the image is too high originally, rotate it 90 so the biggest dimension will now be width. Scale the width to `width=\linewidth`.
Pseudocode
```
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\begin{figure}
% If image height overfull, rotate the image 90 degree clockwise. Apply now to it width constaint.
\includegraphics[if HEIGHT overfull, rotate 90 degree clockwise; width=\linewidth]{1.jpg}
\end{figure}
\end{document}
``` | 2016/11/29 | [
"https://tex.stackexchange.com/questions/341551",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/13173/"
] | Here is a general approach that you can follow:
```
\documentclass{article}
\usepackage{graphicx}
\newsavebox{\imgbox}
\begin{document}
\begin{figure}
\savebox{\imgbox}{% Store image in a box
\includegraphics[height=<h>,width=<w>,keepaspectratio]{example-image}}%
\ifdim\ht\imgbox > <H>
% Do something to the box
\else
\usebox{\imgbox}%
\fi
\end{figure}
\end{document}
```
In essence, you want to condition on the size of the included image. If it's too tall (or too wide), you may want to manipulate it otherwise. So, you store the image in a box (say, `\imgbox`), and then you can test the height - `\ht\imgbox` - or the width - `\wd\imgbox` against some other dimensions.
---
Specific to your application, you could do the following:
```
\begin{figure}
\savebox{\imgbox}{% Store image in a box
\includegraphics[height=\textheight,width=\linewidth,keepaspectratio]{example-image}}%
\ifdim\ht\imgbox > \textheight
\resizebox{\linewidth}{!}{\rotatebox{90}{\includegraphics{example-image}}}%
\else
\usebox{\imgbox}% Use resized image as-is
% \resizebox{\linewidth}{!}{\usebox{\imgbox}}% ...maybe resize to fit width
\fi
\end{figure}
``` | Does the following do what you want? The first normal `\includegraphics` produces an overfull `\vbox` (visible by the empty first page since the image is shifted to the second one), whereas `\includegraphicsoptrotate` rotates the image (and shrinks it to `\textwidth`).
```
\documentclass{article}
\usepackage{graphicx}
\newlength\graphicsheight
\newcommand\includegraphicsoptrotate[1][]%
{\settowidth\graphicsheight{\includegraphics[#1]{#2}}%
\ifdim\graphicsheight>\textheight
\includegraphics[#1,height=\linewidth,angle=90,origin=c]{#2}%
\else
\includegraphics[#1,width=\linewidth]{#2}%
\fi
}
\begin{document}
\noindent
\includegraphics[scale=2]{example-image-a}
\noindent
\includegraphicsoptrotate[scale=2]{example-image-a}
\end{document}
```
[](https://i.stack.imgur.com/2cZgkt.png)[](https://i.stack.imgur.com/9lCCct.png)[](https://i.stack.imgur.com/cViiIt.png) |
1,490,286 | Consider the infinite series $\; \displaystyle \sum\_{n=0}^{\infty} \left(\frac{1}{ 4}\right)^{\!n/2}.$
Find the sum of this series.
Formula for calculating sum of the series is:
$$\frac{a}{1 - r}$$
Where Riemann sum must either look as:
$\sum\_{n=0}^{\infty} a \cdot r^n\;\;$ or $\;\;\; \sum\_{n=1}^{\infty} a \cdot r^{n-1}$
So one way to figure out this problem is to rewrite the given Riemann sum as two sums, one for even and the other for odd n.
Edit:
Kind of like this:
$\sum (\frac{1}{4})^n + \sum \frac{1}{2} \cdot (\frac{1}{4})^{\frac{2n}{2}} $
For even, standard is 2k, for odd just simply 2k + 1.
In my case there's fraction involved in the exponent, so I get:
$\sum (\frac{1}{4})^{2n}{2} + \sum (\frac{1}{4})^{ \frac{2n +1}{2}}$ ->
$\sum (\frac{1}{4})^{2n}{2} + \sum (\frac{1}{4})^{ \frac{2n}{2} + \frac{1}{2}}$ ->
$\sum (\frac{1}{4})^n + \sum (\frac{1}{4})^{ \frac{2n}{2}} \cdot (\frac{1}{4})^{ \frac{1}{2}} $ | 2015/10/21 | [
"https://math.stackexchange.com/questions/1490286",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/250002/"
] | Alternately use index laws:
$$\sum\_{n=0}^{\infty} \left(\frac{1}{ 4}\right)^{\frac{n}{2}}=\sum\_{n=0}^{\infty} \left(\left(\frac{1}{ 4}\right)^{\frac{1}{2}}\right)^n$$
$$=\sum\_{n=0}^{\infty} \left(\frac{1}{2}\right)^n$$ | I think it is $$\sum (\frac{1}{4})^{\frac{n}{2}}=\sum (\frac{1}{4})^{\frac{2n}{2}}+\sum (\frac{1}{4})^{\frac{2n+1}{2}}=\sum (\frac{1}{4})^{\frac{2n}{2}}+\sum (\frac{1}{4})^{\frac{2n}{2}}\times \frac{1}{2}$$ |
10,434,686 | I am trying to insert a post with this code:
```
$my_post = array(
'post_type' => "essays",
'post_title' => 'TEST 3',
//'post_content' => $content,
'post_status' => 'draft',
'post_author' => 1,
//'post_category' => $cat,
'tags_input' => 'TQM,tag',
);
$post_id = wp_insert_post($my_post);
```
Everythings works ok except the tags, it does not insert any of them.
Any idea? | 2012/05/03 | [
"https://Stackoverflow.com/questions/10434686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1055503/"
] | Use the `wp_set_object_terms()` function:
<http://codex.wordpress.org/Function_Reference/wp_set_object_terms>
```
wp_set_object_terms($post_id , $arrayoftags, $name_of_tag_taxonomy, false);
```
Good luck | tags and post categories ought to be entered as an array, even if it's only one. So `'tags_input' => 'TQM,tag'` should be `'tags_input' => array('TQM,tag')` |
1,875,885 | I'm using Elixir in a project that connects to a postgres database. I want to run the following query on the database I'm connected to, but I'm not sure how to do it as I'm rather new to Elixir and SQLAlchemy. Anyone know how?
`VACUUM FULL ANALYZE table`
**Update**
The error is: "UnboundExecutionError: Could not locate a bind configured on SQL expression or this Session". And the same result with session.close() issued before. I did try doing metadata.bind.execute() and that worked for a simple select. But for the VACUUM it said - "InternalError: (InternalError) VACUUM cannot run inside a transaction block", so now I'm trying to figure out how to turn that off.
**Update 2**
I can get the query to execute, but I'm still getting the same error - even when I create a new session and close the previous one.
```
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# ... insert stuff
old_session.commit()
old_session.close()
new_sess = sessionmaker(autocommit=True)
new_sess.configure(bind=create_engine('postgres://user:pw@host/db', echo=True))
sess = new_sess()
sess.execute('VACUUM FULL ANALYZE table')
sess.close()
```
and the output I get is
```
2009-12-10 10:00:16,769 INFO sqlalchemy.engine.base.Engine.0x...05ac VACUUM FULL ANALYZE table
2009-12-10 10:00:16,770 INFO sqlalchemy.engine.base.Engine.0x...05ac {}
2009-12-10 10:00:16,770 INFO sqlalchemy.engine.base.Engine.0x...05ac ROLLBACK
finishing failed run, (InternalError) VACUUM cannot run inside a transaction block
'VACUUM FULL ANALYZE table' {}
```
**Update 3**
Thanks to everyone who responded. I wasn't able to find the solution I wanted, but I think I'm just going to go with the one described here [PostgreSQL - how to run VACUUM from code outside transaction block?](https://stackoverflow.com/questions/1017463/postgresql-how-to-run-vacuum-from-code-outside-transaction-block). It's not ideal, but it works. | 2009/12/09 | [
"https://Stackoverflow.com/questions/1875885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183355/"
] | Dammit. I knew the answer was going to be right under my nose. Assuming you setup your connection like I did.
```
metadata.bind = 'postgres://user:pw@host/db'
```
The solution to this was as simple as
```
conn = metadata.bind.engine.connect()
old_lvl = conn.connection.isolation_level
conn.connection.set_isolation_level(0)
conn.execute('vacuum analyze table')
conn.connection.set_isolation_level(old_lvl)
```
This is similar to what was suggested here [PostgreSQL - how to run VACUUM from code outside transaction block?](https://stackoverflow.com/questions/1017463/postgresql-how-to-run-vacuum-from-code-outside-transaction-block)
because underneath it all, sqlalchemy uses psycopg to make the connection to postgres. Connection.connection is a proxy to the psycopg connection. Once I realized this, this problem came back to mind and I decided to take another whack at it.
Hopefully this helps someone. | If you have access to SQLAlchemy session, you can execute arbitrary SQL statements via its `execute` method:
```
session.execute("VACUUM FULL ANALYZE table")
``` |
26,403,861 | I want to send simple email with no attachment using default email application.
I know it can be done using Process.Start, but I cannot get it to work. Here is what I have so far:
```
string mailto = string.Format("mailto:{0}?Subject={1}&Body={2}", "to@user.com", "Subject of message", "This is a body of a message");
System.Diagnostics.Process.Start(mailto);
```
But it simply opens Outlook message with pre-written text. I want to directly send this without having user to manually click "Send" button. What am I missing?
Thank you | 2014/10/16 | [
"https://Stackoverflow.com/questions/26403861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1539189/"
] | You need to do this :
```
string mailto = string.Format("mailto:{0}?Subject={1}&Body={2}", "to@user.com", "Subject of message", "This is a body of a message");
mailto = Uri.EscapeUriString(mailto);
System.Diagnostics.Process.Start(mailto);
``` | I'm not sure about `Process.Start()` this will probably always only open a mail message in the default Mail-App and not send it automatically.
But there may be two alternatives:
* Send directly via [SmtpClient](https://stackoverflow.com/questions/9201239/send-e-mail-via-smtp-using-c-sharp) Class
* using [Outlook.Interop](https://stackoverflow.com/questions/11223462/how-to-send-a-mail-using-microsoft-office-interop-outlook-mailitem-by-specifying) |
46,161,918 | I noticed when in vi mode in bash (i.e. the mode enabled with "set -o vi"), that some commands, such as "diw", that work in vim but not in vi, don't work on the bash command line. Is there an easy way to configure bash so that its keybindings will support vim commands? I would like to be able to enter vim commands on the command line without having to actually start the vim program, as described in [this question](https://stackoverflow.com/questions/23230990/bashs-vim-mode-not-vi). | 2017/09/11 | [
"https://Stackoverflow.com/questions/46161918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3302997/"
] | The best way of doing this that I know of would be to use [athame](https://github.com/ardagnir/athame).
It can be a surprisingly powerful experience in some cases. I particularly like it for interacting with a repl.
>
> Athame patches your shell to add full Vim support by routing your keystrokes through an actual Vim process. Athame can currently be used to patch readline (used by bash, gdb, python, etc) and/or zsh (which doesn't use readline).
>
>
>
[](https://i.stack.imgur.com/xCAv5.gif)
Alternatively I find spacemacs with the eshell to be a reasonably functional if strange solution. | Teach vi-command-mode `diw` to any software that uses readline (such as bash) by adding this to your ~/.inputrc:
```
set keymap vi-command
"diw": "bde"
``` |
827,326 | What's a good hex editor/viewer for the Mac? I've used xxd for viewing hexdumps, and I think it can be used in reverse to make edits. But what I really want is a real hex editor. | 2009/05/05 | [
"https://Stackoverflow.com/questions/827326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17188/"
] | To view the file, run:
```
xxd filename | less
```
To use Vim as a hex editor:
1. Open the file in Vim.
2. Run `:%!xxd` (transform buffer to hex)
3. Edit.
4. Run `:%!xxd -r` (reverse transformation)
5. Save. | 1. Open file with Xcode and press Command + Shift + J
2. Right click file name in
left pane
3. Open as -> Hex |
13,842,560 | I want an hist and a density on the same plot, I'm trying this:
```
myPlot <- plot(density(m[,1])), main="", xlab="", ylab="")
par(new=TRUE)
Oldxlim <- myPlot$xlim
Oldylim <- myPlot$ylim
hist(m[,3],xlim=Oldxlim,ylim=Oldylim,prob=TRUE)
```
but I can't access myPlot's xlim and ylim.
Is there a way to get them from myPlot? What else should I do instead? | 2012/12/12 | [
"https://Stackoverflow.com/questions/13842560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/512225/"
] | Using `par(new=TRUE)` is rarely, if ever, the best solution. Many plotting functions have an option like `add=TRUE` that will add to the existing plot (including the plotting function for histograms as mentioned in the comments).
If you really need to do it this way then look at the `usr` argument to the `par` function, doing `mylims <- par("usr")` will give the x and y limits of the existing plot in user coordinates. However when you use that information on a new plot make sure to set `xaxs='i'` or the actual coordinates used in the new plot will be extended by 4% beyond what you specify.
The functions `grconvertX` and `grconvertY` are also useful to know. They could be used or this purpose, but are probably overkill compared to `par("usr")`, but they can be useful for finding the limits in other coordinate systems, or finding values like the middle of the plotting region in user coordinates. | I think the best solution is to fix them when you plot your density.
Otherwise hacing in the code of plot.default (plot.R)
```
xlab=""
ylab=""
log =""
xy <- xy.coords(x, y, xlab, ylab, log)
xlim1 <- range(xy$x[is.finite(xy$x)])
ylim1 <- range(xy$y[is.finite(xy$y)])
```
or to use the code above to generate xlim and ylim then call your plot for density
```
dd <- density(c(-20,rep(0,98),20))
plot(dd,xlim=xlim1,ylim=ylim1)
x <- rchisq(100, df = 4)
hist(x,xlim=xlim1,ylim=xlim1,prob=TRUE,add=TRUE)
```
 |
10,247,279 | I have latitude, longitude and a radius. Can you please help me in finding the another latitude and longitude from given points (latitude and longitude) and radius. | 2012/04/20 | [
"https://Stackoverflow.com/questions/10247279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1346155/"
] | %comspec% /k runs *another* command prompt, and then keeps cmd.exe around. Until that cmd.exe returns, your batch file won't continue.
Even if you replace /k with /c (which doesn't keep cmd.exe around), it won't work, because the environment variables from the new command prompt aren't preserved in this one.
You simply need:
```
call %VS100COMNTOOLS%\vsvars32.bat
```
Or
```
call %VS100COMNTOOLS%\..\..\VC\vcvarsall.bat x86
``` | I solved it in another way. I used the full path of the tf.exe. And it works in the command prompt.
The call answer doens't worked for me. |
238,480 | In our solar system, Europa, a moon of Jupiter, has a large and warm ocean under the icy crust. However, due to it having a rocky core and the icy crust, there is no light in the ocean. I want to make writing life, society, and technology easier by making natural light sources on Europa exist long before life evolved.
In this way, life on Europa can have functional eyes and form a society like Jar Jar Binks's in Star Wars. What kind of geological change needs to happen to make a "illuminated ocean" in Europa possible? | 2022/11/23 | [
"https://worldbuilding.stackexchange.com/questions/238480",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/37911/"
] | **Cracks**
[](https://i.stack.imgur.com/sBkR4.jpg)
<https://www.nasa.gov/jpl/europas-stunning-surface>
<https://space.stackexchange.com/questions/2226/what-causes-the-cracks-on-europa-to-form>
The ice crust of Europa has cracks. Big old ones, small new ones. These cracks are brown presumably from accumulated tholins: carbon and nitrogen rich molecules.
From underneath, a crack will be brighter than adjacent ice. It will also be a place where there will be a bloom of life because of the carbon and nitrogen rich stuff coming thru. Things that can see the light can find the resources.
And then: Jar Jar! | I think it really depends on what kind of an atmosphere you want to create for your world
As previous comments have suggested, you could use bioluminescence to have life.
If you want to, you could use the fact that all materials emit light assuming they are above 0 Kelvin. This would create infrared light rather than visible though.
You could also use some kind of radiation source or maybe even the core of the earth.
Or maybe the civilisation came from another planet where there was more life |
455,191 | I know this question is asked but there is no solution for me. I tried unlocker, fileassassin, lockhunter and commnd prompt to delete file but it didn't work. | 2012/07/30 | [
"https://superuser.com/questions/455191",
"https://superuser.com",
"https://superuser.com/users/142420/"
] | Boot your system with a Linux live CD then you should be able to delete it.
If you don't have a CD burner you can try using a flash drive with [YUMI](http://www.pendrivelinux.com/yumi-multiboot-usb-creator/). | Or you can reboot the system to force delete a file, here are the steps:
Step1: Press Win logo key + R and then type: MSConfig.
Step2: Now, turn to Boot tab and then tick Safe Boot from Boot Options section.
Step3: Once you click on the OK button, the system will ask you to restart the system.
After successfully booting into Safe Mode, launch File Explorer and try to delete unwanted files. |
10,390 | G'day,
Why has the meaning of community-wiki shifted towards "[a way to stop your post being closed](https://meta.stackexchange.com/questions/11740/what-are-community-wiki-posts-on-stack-overflow)" from the original intent of allowing almost anyone to edit the question and provide answers so that the question itself becomes a reference document for the topic under discussion?
Just intrigued and making the question community wiki! (-
Some expansion
--------------
If you read many posting here on meta, you will get a consistent message. The purpose of community wiki is to allow collaborative creation of real answers to real questions.
When I look at the questions that end up community wiki, that is not what I see. What I see is that it is used to establish a gray zone between concrete questions with concrete answers (on the one hand) and opinion/discussion on the other. By and large, opinion/discussion gets closed as 'not a real question' or 'subjective and argumentative.' But some number of posts that are not concrete questions with specific answers are allowed to remain -- so long as they are cwiki. The justification for this seems to be 'well, this tripe is too tasty to discard, but no one should get any rep for it.'
I can't think of a single occasion on which I've seen a cwiki question or answer serving as a vehicle for collaboration, or allowing low-rep users to stick an editorial oar into the river of text.
People aren't editing the question or collaboratively editing a single answer to reach a high polish. They are all posting different answers. Dozens of answers. Hundreds of answers. TL;DR No one is going to read all that stuff.
Maybe this is a good thing, and maybe not. It certainly leads to some level of confusion and whining about unequal treatment. (See recent meta question about career questions, e.g.)
I end up thinking that what we need here is to get our story straight. Given the recent ex cathedra pronouncement about leaving some humor questions open, wouldn't it be less stressful to write up and stick to a policy that covers this stuff, instead of having a policy that talks about one phenomenon and a practice that does something else? | 2009/07/28 | [
"https://meta.stackexchange.com/questions/10390",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/2974/"
] | Here's a concrete example of why...
[Common-mistakes questions](https://stackoverflow.com/questions/tagged/common-mistakes)
There were a few of these asked yesterday. They're entertaining, and potentially even useful for programmers new to the target language.
They're also *huge* rep-farms. Sure, some people actually put a bit of effort into their answers, providing code samples and lengthy descriptions of **why** *xxxx* is a mistake. But chances are, if you already know the language being discussed you'll show up and immediately recognize several common mistakes that you agree with. Rather than re-posting them, you up-vote them. End result: lots of easy reputation for whoever is first to post the most egregious mistakes, **regardless** of whether or not they put any real effort into the write-up.
And these are some of the *best* [multi-answer questions](https://meta.stackexchange.com/questions/9782/what-about-a-multi-answer-question)! Further down on the list, you'll find polls, discussions, GTKY questions... Each emphasizing more and more the ability to post a popular answer quickly over any need for technical merit.
Don't get me wrong; i've no issue with a *little bit* of this. Reputation is not so holy that we must protect its integrity at the expense of all else. The problem comes in keeping them from overrunning the site... One popular thread begets many imitations - see again the link above.
Originally, we just closed them. That... led to bad feelings. Charges of inconsistency, as the immitations were closed more readily than the originals. "Why favor C# over SQL? Why allow 'favorite books' but not 'programming hero'?" Things got out of hand.
CW provided, at least for a time, a compromise solution: the questions can stay open and on the site, so long as they're marked CW. Not everyone agreed, mind you - but the general attitude seemed to be, "we'll look the other way for CW".
Now that appears to be falling apart as well. Suggestions - even polite suggestions - that a question should be CW may be met with derision. Name-calling ("CW police") has become more common. And that's inevitable - CW wasn't meant for this, it was never a solution that either side could really get behind whole-heartedly, and as the site continues to grow it becomes less and less practical to explain this to new users. The time of CW as a compromise may be coming to an end.
But the noise prompted by visions of easy popularity isn't going to go away. I'm starting to suspect the end result may be a site where the concept of "user-moderation" is abandoned in favor of an ever-growing population of official Moderators. But, this may be too negative. We'll have to wait and see... | Taking the existing points further; yes, this (the (ab)use of CW to mean "look the other way, please") is a major problem on SU. I'd be tempted to wonder whether a zero-tolerance approach on SU might help stabilise things (combined with a none-too-forgiving purge of the existing questions). i.e. if it isn't an actual sensible computer question, then kill it. Regardless of CW or the person doing the asking. Even if it is Joel.
Since it is officially beta, I think it would still be OK to risk a little bit of pushback to get the site integrity up. At the moment, I have concerns...
But then; if SU, why not SO/SF too? Of course, then we have to avoid MSO becoming the dumping ground of "fun".
Don't get me wrong; I don't object to fun (I'm not a sourpuss, honest), but it maybe that these questions cause more problems than the levity it provides warrants.
One saving grace is that people are slowly running out of ideas that can't be quickly closed as duplicates, and **most** of the community are happy for such things to get closed. Or deleted; I had no guilt ***whatsoever*** in simply deleting [this one](https://stackoverflow.com/questions/1200584/what-is-your-favourite-xkcd) (you'll need 10k or ♦ to see it) while it was still only 15 seconds old; and for those who *can't* see it... "What is your favourite XKCD?" (it wasn't marked wiki, but that wasn't really part of my decision-making process...) |
4,321,456 | Is there a way to get `find` to execute a function I define in the shell?
For example:
```
dosomething () {
echo "Doing something with $1"
}
find . -exec dosomething {} \;
```
The result of that is:
```
find: dosomething: No such file or directory
```
Is there a way to get `find`'s `-exec` to see `dosomething`? | 2010/12/01 | [
"https://Stackoverflow.com/questions/4321456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303896/"
] | To provide additions and clarifications to some of the other answers, if you are using the bulk option for `exec` or `execdir` (`-exec command {} +`), and want to retrieve all the positional arguments, you need to consider the handling of `$0` with `bash -c`.
More concretely, consider the command below, which uses `bash -c` as suggested above, and simply echoes out file paths ending with '.wav' from each directory it finds:
```
find "$1" -name '*.wav' -execdir bash -c 'echo "$@"' _ {} +
```
The Bash manual says:
>
> If the `-c` option is present, then commands are read from the first non-option argument command\_string. If there are arguments after the command\_string, they are assigned to positional parameters, starting with `$0`.
>
>
>
Here, `'echo "$@"'` is the command string, and `_ {}` are the arguments after the command string. Note that `$@` is a special positional parameter in Bash that expands to all the positional parameters **starting from 1**. Also note that with the `-c` option, the first argument is assigned to positional parameter `$0`.
This means that if you try to access all of the positional parameters with `$@`, you will only get parameters starting from `$1` and up. That is the reason why Dominik's answer has the `_`, which is a dummy argument to fill parameter `$0`, so all of the arguments we want are available later if we use `$@` parameter expansion for instance, or the `for` loop as in that answer.
Of course, similar to the accepted answer, `bash -c 'shell_function "$0" "$@"'` would also work by explicitly passing `$0`, but again, you would have to keep in mind that `$@` won't work as expected. | Not directly, no. Find is executing in a separate process, not in your shell.
Create a shell script that does the same job as your function and find can `-exec` that. |
2,586,530 | All,
I am using Zend Framework and Zend\_Session to do global session management for my application. I plan to clear all sessions on logout and hence am using the following code:
```
if($this->sessionExists())
{
$this->destroy();
}
```
But it seems like it's not doing a good job.. I am getting an error:
```
PHP Warning: session_destroy() [<a href='function.session-destroy'>
function.session-destroy</a>]: Trying to destroy uninitialized session
```
How can I get rid of this error? Is there an alternative to sessionExists()? | 2010/04/06 | [
"https://Stackoverflow.com/questions/2586530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229853/"
] | [XmlPullParser](http://developer.android.com/intl/de/reference/org/xmlpull/v1/XmlPullParser.html) is a streaming pull XML parser and should be used when there is a need to process quickly and efficiently all input elements.
You can try something like this:
```
private void pullParserSample(FileInputStream xml) {
int lists = 0;
int notes = 0;
int eventType = -1;
try {
XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser();
xpp.setInput(new InputStreamReader(xml));
eventType = xpp.getEventType();
do {
switch ( eventType ) {
case XmlPullParser.START_TAG:
final String tag = xpp.getName();
if ( "Note".equals(tag) ) {
notes++;
}
else if ( "List".equals(tag) ) {
lists++;
}
break;
}
} while ((eventType = xpp.next()) != XmlPullParser.END_DOCUMENT) ;
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "lists=" + lists + " notes=" + notes);
}
``` | Look at implementing a org.xml.sax.ContentHandler and sending it to an org.xml.sax.XMLReader.
These classes are bundled with Android SDK. This is a 'forward parser' approach which involves your ContentHandler being shown each XML element (tag, attribute, text) as the document is processed from start to end. The forward parser approach is light on memory use and a lot faster than building a DOM. |
59,362,344 | I am reading this function and not at all understanding how this can work.
```
() => console.log(i) || Promise.resolve(i++ > 3)
```
Can a kind soul explain how a console.log can participate in a conditional?
I can even trans-pile this in typescript. | 2019/12/16 | [
"https://Stackoverflow.com/questions/59362344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496136/"
] | `console.log(...)` returns `undefined`, which is falsy; so the expression after the or `||` operator will always execute. This is just shorthand for:
```
() => {
console.log(i);
return Promise.resolve(i++ > 3);
}
``` | [`console.log(...)`](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) returns `undefined`, which evaluates to a [falsy value](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). |
35,307 | The following situation is probably familiar for many working people:
>
> * **Boss**: "We're gonna do this project like A, B, E, D"
> * **Everyone**: (stumped) "Uh, what about C? Why is E before D? That's not how the alphabet works?"
> * **Boss**: (realizing he might have made a mistake) "Well, yeah, we don't have the {time/resources} to look back on earlier made decisions, we have to move forward, so stop discussing and carry on!"
> * **Everyone**: "ugh..."
>
>
>
In my beginning years, when this situation happened I fought for the correct thing and demanded (with varying success) to do the project the correct "A B C D" way. My colleagues however seemed to be able to deal with this perrfectly fine. They seemed to have way less frustrations and can always bring up a high amount of relativism. After some introspection I figured out the real problem is not (or at least only partially) my boss. The real problem is me **not being able to do my job when I feel there are better ways to do it**, even though that's what I'm being paid for. My boss seems more happy with a dumb slave than with a critical subordinate. I have my reasons to not back down however:
* I'm a perfectionist, I dislike chaotic/not-well-thought-out plannings
* I love my job (despite the situation), and I get a kick whenever I deliver quality. I get demotivated when I have to deliberately introduce flaws into our products.
* I'm critical: I don't want to dance like a mindless puppet to my boss's whims.
* I want the company, and myself, to grow. Crappy products feels like going in the opposite direction.
* Crappy products ALWAYS bite you in the ass at a later time - or at least our customer departments.
Apart from the not so realistically "Just quit and change jobs!", what advice could you give me to deal with this situation? I feel like I know myself, my company and my boss, and I feel like its impossible to really change either fundamentally. But maybe I can start looking at things differently.
EDIT: I'm a bit disgusted by some of the answers this question has received. This question is NOT about "Help, I'm a perfectionist and I want everything to be perfect and now I'm missing deadlines and not doing my job properly, please give me a reality check."
I work hard and deliver quality work on time. What's REALLY going on here is my boss asking me to do things in a way that's unbelievably akward, and I constantly have to either correct him, or suck it up and leave flaws in the system. What I consider flaws, many of our non-so-perfectionist employees consider to be flaws too. Thus, it is not me just me who recognizes the flaws. The difference is: they can suck it up and be cool and calm. When I suck it up I get frustrated and demotivated. How can a person try to improve that? The answer is definitely not "changing jobs". | 2014/10/23 | [
"https://workplace.stackexchange.com/questions/35307",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/14442/"
] | There's a time for perfectionism and there's a time for doing what you're told.
You have a boss, part of that person's responsibility is to direct you in your duties. One of the aspects of this is the schedule. You can certainly continue doing the responsible thing by bringing up things you believe need to addressed. Your boss will certainly continue to either use those suggestions or throw them out according to his/her interpretation of the needs of the business.
However, if you want to have a productive relationship then you need to realize your position in the bigger picture. Do the best job you can with within the bounds that have been dictated. If this feels like a problem then you should work towards leveling up to be in the Boss position so you can impose your will upon your own minions.
One thing to remember "iterate fast, iterate often" is a very common phrase in the development world. It recognizes that nothing will ever be perfect but if you can get it "good enough" then you just might have a winner. It also highlights that you *may* have the opportunity to come back and fix those other things that need to be done. Or, if not, then you probably didn't need to spend time on those things anyway.
This is at the heart of Agile programming and a radical departure from other methodologies, such as Waterfall, which strove to architect the Perfect System(tm) and have been proven to be utter failures.
The last thing I'll leave you with is "Perfection is in the eye of the beholder." What you consider to be a perfectly constructed class hierarchy another might consider to be an overwhelming morass of ineffectiveness. | >
> The real problem is me not being able to do my job in a crappy way, even though that's what I'm being paid for
>
>
>
I'm not going to suggest a change of job, as the thing here is your feelings, not the current position.
You need to reconcile yourself that you work for a business, there is always a compromise between quality and time.
To be honest, in my experience, perfectionism is usually the worst thing, I've worked with people who have re-started approaches to a task (sometimes multiple times), striving for the perfect solution. The result is even more botched, as they never really understood what was really wanted, so it usually gets to the point where someone else has to step in to hack a solution in order to get something out the door on time (so even more compromised).
In software development, Agile is a big thing now. It's based on an iterative model:
* Do just enough to cover what you need to do for this iteration
* Get feedback
* Refine it next time round
(over simplification)
This actually gets to a more perfect solution as the refining helps the requester fine tune what they actually want, so we get closer to the target than trying to hit it perfectly first time.
My advice, probably worth spending some time on the other side, either in the management of the project, or the business, to see the factors that are driving the compromises.
I always felt I became a better software architect when I also had to become a development manager, I had to learn to balance the ideals with the business's real world needs. |
52,705,061 | In my React Native project, Gradle build gave me this error :
```
> Task :app:processDebugGoogleServices
Parsing json file: /Users/valentinmourot/ODE/Dev/mobile-app/android/app/google-services.json
/Users/valentinmourot/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/234563a256b75883624274d32dc30b63/res/values-v24/values-v24.xml:3:5-157: AAPT
: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.
/Users/valentinmourot/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/234563a256b75883624274d32dc30b63/res/values-v24/values-v24.xml:4:5-135: AAPT: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.
/Users/valentinmourot/.gradle/caches/transforms-1/files-1.1/appcompat-v7-27.1.1.aar/234563a256b75883624274d32dc30b63/res/values-v26/values-v26.xml:13:5-16:13: AAPT: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.
```
Some threads said it was due to a mis configuration in the `build.gradle` file. Here's mine :
```
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "-----------"
minSdkVersion 19
targetSdkVersion 23
versionCode 8
versionName "0.0.8"
ndk {
abiFilters "armeabi-v7a", "x86"
}
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86"
}
}
buildTypes {
release {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
def versionCodes = ["armeabi-v7a":1, "x86":2]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
compile project(':react-native-view-overflow')
compile(project(':react-native-firebase')) {
transitive = false
}
compile "com.google.android.gms:play-services-base:15.0.0"
compile "com.google.firebase:firebase-core:15.0.2"
compile project(':react-native-i18n')
compile project(':react-native-vector-icons')
compile project(':react-native-fs')
compile project(':react-native-image-to-base64')
compile project(':rn-fetch-blob')
compile fileTree(dir: "libs", include: ["*.jar"])
compile "com.android.support:appcompat-v7:23.0.3"
compile "com.facebook.react:react-native:+"
compile project(':react-native-smart-splash-screen')
compile project(':react-native-cookies')
compile "com.google.firebase:firebase-analytics:15.0.2"
compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
transitive = true
}
compile "com.google.firebase:firebase-perf:15.1.0"
compile "com.google.firebase:firebase-messaging:15.0.2"
compile project(':react-native-image-picker')
compile project(':react-native-mixpanel')
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
apply plugin: 'com.google.gms.google-services'
```
The erros seems to be linked to google-services (Firebase ?). I don't know why `appcompat-v7-27.1.1` is used here.
The error raised after an update of Android Studio.
Here's my React Native environment :
```
React Native Environment Info:
System:
OS: macOS High Sierra 10.13.6
CPU: x64 Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz
Memory: 59.94 MB / 8.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 10.9.0 - /usr/local/bin/node
Yarn: 1.9.4 - /usr/local/bin/yarn
npm: 6.4.1 - /usr/local/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0
Android SDK:
Build Tools: 23.0.1, 26.0.2, 27.0.3
API Levels: 23, 25, 26, 27
IDEs:
Android Studio: 3.2 AI-181.5540.7.32.5014246
Xcode: 10.0/10A255 - /usr/bin/xcodebuild
npmPackages:
@types/react: 16.4.14 => 16.4.14
@types/react-native: 0.57.1 => 0.57.1
react: 16.5.0 => 16.5.0
react-native: 0.57.1 => 0.57.1
npmGlobalPackages:
react-native-cli: 2.0.1
```
Thanks for your help ! :)
Post-Scriptum :
Sometimes the error is different (seems to come from react-native-i18n) :
```
> Task :react-native-i18n:compileDebugJavaWithJavac
Note: /Users/valentinmourot/ODE/Dev/mobile-app/node_modules/react-native-i18n/android/
src/main/java/com/AlexanderZaytsev/RNI18n/RNI18nModule.java uses or overrides a deprec
ated API.
Note: Recompile with -Xlint:deprecation for details.
/Users/valentinmourot/.gradle/caches/transforms-1/files-1.1/appcompat-v7-28.0.0.aar/b8
5fe69b67b83a703766c9386b9fdeb8/res/values-v24/values-v24.xml:3:5-157: AAPT: Error retr
ieving parent for item: No resource found that matches the given name 'android:TextApp
earance.Material.Widget.Button.Borderless.Colored'.
/Users/valentinmourot/.gradle/caches/transforms-1/files-1.1/appcompat-v7-28.0.0.aar/b85fe69b67b83a703766c9386b9fdeb8/res/values-v24/values-v24.xml:4:5-135: AAPT: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.
/Users/valentinmourot/.gradle/caches/transforms-1/files-1.1/appcompat-v7-28.0.0.aar/b85fe69b67b83a703766c9386b9fdeb8/res/values-v26/values-v26.xml:13:5-16:13: AAPT: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'
```
... or sometimes another : `> Task :react-native-cookies:compileDebugJavaWithJavac` with the same messages. | 2018/10/08 | [
"https://Stackoverflow.com/questions/52705061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6111343/"
] | Have you tried running `gradlew clean` in the `android/` dir?
Sometimes I get this error and doing this fixes it, although I don't know what causes it. | update to:
```
api "com.android.support:appcompat-v7:28.0.0"
```
while there are further outdated versions. |
69,108,369 | I have an array of floats and I need to return the index of the N smallest values. What I'm thinking (if there's a better way, please sing out) is to convert the array to an array of tuples where the [0] entry is the original float and the [1] entry is the index in the array.
Then I sort the array by the [0] entries and then for the top N entries, return the [1] value.
So the question is, how can I convert an array of floats to an array of tuples with the [0] entry from the original array. I know how to do this with a for loop, but I'm asking this question to see if numpy has a call that can do this. | 2021/09/08 | [
"https://Stackoverflow.com/questions/69108369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/509627/"
] | If you would like to get the indices of the N smallest values you can use the argpartition funtion such as:
```
import numpy as np
N = 3
array = np.array([0.0, 0.1, 0.2, 3.0, 0.4, 0.5, 0.1])
smallest_indices = np.argpartition(array, N)[:N]
```
So for (say) N = 3 the output would be:
```
>>> print(smallest_indices)
[1 0 6]
>>> print(array[smallest_indices])
[0.1 0.0 0.1]
``` | You could do it with enumerate and sorted w/a key. Or you can use numpy like in [this post.](https://stackoverflow.com/questions/6910641/how-do-i-get-indices-of-n-maximum-values-in-a-numpy-array)
```
n = 4
f = [2.0,1.0,3.0,4.0,5.0]
[n[0] for n in sorted([(c,x) for c,x in enumerate(f)], key=lambda x:x[1], reverse=True)[:n]]
```
Output
```
[4,3,2,0]
``` |
34,067,009 | I have a `UICollectionView` in my view controller. It has been setup and its working fine.
I am trying to zoom a cell when a button inside the cell itself has been pressed.
The code I have zooms the cell however, I cannot find the way to force the cell selected to go to the front of the other cells.
Right now the cell selected its always behind the cell before the selected.
How can I force the cell selected to zoom in front of the other cells?
```
@IBAction func detailBtnAction(sender:UIButton){
let indexUser = (sender.layer.valueForKey("indexBtn")) as! Int
let indexPath = NSIndexPath(forItem: indexUser, inSection: 0)
let feedCell = feedCollectionView.cellForItemAtIndexPath(indexPath)
feedCell?.bringSubviewToFront(feedCollectionView)
feedCell?.contentView.bringSubviewToFront(feedCollectionView)
UIView.animateWithDuration(1.0) { () -> Void in
feedCell?.transform = CGAffineTransformMakeScale(5, 5)
}
}
``` | 2015/12/03 | [
"https://Stackoverflow.com/questions/34067009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2075848/"
] | It seems you have the order of things mixed up a little.
From the docs :
>
> Moves the specified subview so that it appears on top of its siblings.
>
>
> func bringSubviewToFront(\_ view: UIView)
>
>
> Parameters
>
>
> view - The subview to move to the front.
>
>
> This method moves the specified view to the end of the array of views in the subviews property.
>
>
>
So your call :
`feedCell?.contentView.bringSubviewToFront(feedCollectionView)`
actually means that the cells contentview should move the `feedCollectionView` to front.
Now, this is some educated guess based on the naming, but it should rather look like that :
`feedCollectionView.bringSubviewToFront(feedCell?)`
You can pass the cell itself there, as it inherits from `UIView`. | To bring cell to the front. You can remove cell then after add again: `
`mCollectionView.reloadData()
mCollectionView.performBatchUpdates(nil, completion: {
(result) in
var indexPath = IndexPath(row: 0, section: 0)
var cell = mCollectionView.cellForItem(at: indexPath)
cell.removeFromSuperview()
mCollectionView.addSubview(cell)})` |
3,105,258 | I'm currently using boost-python to wrap a small C++ library and make it usable from Python. However, I'd like to stop using boost (mainly due to reasons relating to building/linking). So what other options are there?
Is there something that's equally convenient to use? | 2010/06/23 | [
"https://Stackoverflow.com/questions/3105258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34996/"
] | Take a look at [SWIG](http://www.swig.org/). | [Cython](http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html)'s syntax is very Pythonic, breaking the rules only where necessary. |
19,246,258 | I have here my code. Data on the database are filtered by the title, how can i filter data by title or author? I think it is on these lines of codes on Catalogue.java:
```
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
```
Here are my codes:
**Catalogue.java**
```
package com.cvsu.catalogue.db;
import com.cvsu.catalogue.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
//import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
@SuppressLint("NewApi")
public class Catalogue extends Activity {
private CollectionsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
public final static String TITLE_EXTRA = "com.cvsu.catalogue.db._TITLE";
public final static String AUTHOR_EXTRA = "com.cvsu.catalogue.db._AUTHOR";
public final static String LOCATION_EXTRA = "com.cvsu.catalogue.db._LOCATION";
public final static String CALLNUMBER_EXTRA = "com.cvsu.catalogue.db._CALLNUMBER";
public final static String PUBLISHER_EXTRA = "com.cvsu.catalogue.db._PUBLISHER";
public final static String DATEPUBLISHED_EXTRA = "com.cvsu.catalogue.db._DATEPUBLISHED";
public final static String DESCRIPTION_EXTRA = "com.cvsu.catalogue.db._DESCRIPTION";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalogue_title);
dbHelper = new CollectionsDbAdapter(this);
dbHelper.open();
//Generate ListView from SQLite Database
displayListView();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCollections();
// The desired columns to be bound
String[] columns = new String[] {
CollectionsDbAdapter.KEY_TITLE,
CollectionsDbAdapter.KEY_AUTHOR,
CollectionsDbAdapter.KEY_LOCATION,
CollectionsDbAdapter.KEY_CALLNUMBER,
CollectionsDbAdapter.KEY_PUBLISHER,
CollectionsDbAdapter.KEY_DATEPUBLISHED,
CollectionsDbAdapter.KEY_DESCRIPTION
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.txtTitle,
R.id.txtAuthor,
//R.id.location,
//R.id.callnumber,
//R.id.publisher,
//R.id.datepublished,
//R.id.description,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.book_info_title,
cursor,
columns,
to,
0);
final ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listview, View view,
int position, long id ) {
// Get the cursor, positioned to the corresponding row in the result set
/*Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String bookTitle =
cursor.getString(cursor.getColumnIndexOrThrow("title"));
Toast.makeText(getApplicationContext(),
bookTitle, Toast.LENGTH_SHORT).show();*/
Intent i = new Intent (CatalogueTitle.this, BookInfoPage.class);
i.putExtra(TITLE_EXTRA, String.valueOf(id));
i.putExtra(AUTHOR_EXTRA, String.valueOf(id));
i.putExtra(LOCATION_EXTRA, String.valueOf(id));
i.putExtra(CALLNUMBER_EXTRA, String.valueOf(id));
i.putExtra(PUBLISHER_EXTRA, String.valueOf(id));
i.putExtra(DATEPUBLISHED_EXTRA, String.valueOf(id));
i.putExtra(DESCRIPTION_EXTRA, String.valueOf(id));
startActivity(i);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
}
});
}
public static void main(String[] args) {
}
}
```
**Collections.Java**
>
>
> ```
> package com.cvsu.catalogue.db;
>
> public class Collections {
>
> String title = null;
> String author = null;
> String location = null;
> String callnumber = null;
> String publisher = null;
> String datepublished = null;
> String description = null;
>
> public String getTitle() {
> return title;
> }
> public void setTitle(String title) {
> this.title = title;
> }
> public String getAuthor() {
> return author;
> }
> public void setAuthor(String author) {
> this.author = author;
> }
> public String getLocation() {
> return location;
> }
> public void setLocation(String location) {
> this.location = location;
> }
> public String getCallNumber() {
> return callnumber;
> }
> public void setCallNumber(String callnumber) {
> this.callnumber = callnumber;
> }
> public String getPublisher() {
> return publisher;
> }
> public void setPublisher(String publisher) {
> this.publisher = publisher;
> }
> public String getDatePublished() {
> return datepublished;
> }
> public void setDatePublished(String datepublished) {
> this.datepublished = datepublished;
> }
> public String getDescription() {
> return description;
> }
> public void setDescription(String description) {
> this.description = description;
> }
> }
>
> ```
>
>
**CollectionsDbAdapter.java**
```
package com.cvsu.catalogue.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class CollectionsDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_AUTHOR = "author";
public static final String KEY_LOCATION = "location";
public static final String KEY_CALLNUMBER = "callnumber";
public static final String KEY_PUBLISHER = "publisher";
public static final String KEY_DATEPUBLISHED = "datepublished";
public static final String KEY_DESCRIPTION = "description";
private static final String TAG = "CollectionsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "LibraryCollections";
private static final String SQLITE_TABLE = "Collections";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_TITLE + "," +
KEY_AUTHOR + "," +
KEY_LOCATION + "," +
KEY_CALLNUMBER + "," +
KEY_PUBLISHER + "," +
KEY_DATEPUBLISHED + "," +
KEY_DESCRIPTION + "," +
" UNIQUE (" + KEY_CALLNUMBER +"));";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
onCreate(db);
}
}
public CollectionsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CollectionsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCollections(String title, String author,
String location, String callnumber, String publisher, String datepublished, String description) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_AUTHOR, author);
initialValues.put(KEY_LOCATION, location);
initialValues.put(KEY_CALLNUMBER, callnumber);
initialValues.put(KEY_PUBLISHER, publisher);
initialValues.put(KEY_DATEPUBLISHED, datepublished);
initialValues.put(KEY_DESCRIPTION, description);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public Cursor fetchCollectionsByTitle(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_TITLE + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchCollectionsByAuthor(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_AUTHOR + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllCollections() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
``` | 2013/10/08 | [
"https://Stackoverflow.com/questions/19246258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2858096/"
] | ```
@Override
public Cursor runQuery(CharSequence constraint) {
Cursor cur = null;
database.openDataBase();
if(constraint!=null){
cur = database.selectDataWithConstrain(constraint.toString());
}
return cur;
}
```
using this constarint write a query in your Database Class and get the data required either title or author
```
public Cursor selectDataWithConstrain(String c) {
// TODO Auto-generated method stub
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tbl_xxx WHERE title LIKE '%"+c+"%'", null);
return cursor;
}
``` | ```js
public Cursor fetchdatabyfilter(String inputText, String filtercolumn) throws SQLException {
Cursor row = null;
String query = "SELECT * FROM " + dbTable;
if (inputText == null || inputText.length() == 0 ) {
row = sqlDb.rawQuery(query, null);
} else {
query = "SELECT * FROM " + dbTable + " WHERE " + filtercolumn + " like '%" + inputText + "%' ";
row = sqlDb.rawQuery(query, null);
}
if (row != null)
{
row.moveToFirst();
}
return row;
}
mainactivity:
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return db.fetchdatabyfilter(constraint.toString(),"title" );
}
});
``` |
13,257,379 | How can I open `vi` editor from my java application?
I have already tried this
```
Process p = new ProcessBuilder("xterm","-e","vi /backup/xyz/test/abc.txt").start();
int exitVal = p.waitFor();
System.out.println("Exited with error code "+exitVal);
```
But this opens `vi` in a new terminal. **I want the vi editor to open in the same terminal that my application is running** | 2012/11/06 | [
"https://Stackoverflow.com/questions/13257379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1803996/"
] | I was gonna give you the solution but I better explain you about the lookbehind modifier.
In regex each time you "match" a `h` for example, that `h` will add 1 to the pointer of where the regex is at the moment so you dont want to "add" nothing to the pointer. You just want to look if the `from` is preceded by a `;\s\b` or the start of the string. You don't want to match the VOID because there are voids everywhere!!
So, an example: `(?<a)b` that would match a `b` that has an `a` before it. So it just does the next: When a `b` found it looks before it, if there is an `a` it matches the regex.
So... `(?<=[;\s\b]|^)from:(\w+\.\w+)` Would match a `from` that right before it has `[;\s\b] OR ^ (The string start)`
[DEMO](http://regex101.com/r/mQ0zR4)
Pretty easy, huh!? | There is a concept called (negative) lookbehind, which asserts that your current position is (not) preceded by certain things. I guess, in this case I would go with a positive lookbehind, and assert that `from` is preceded by a the start of the string, a line-break or a `;`:
```
preg_match('|(?<=^|;)from:(.*?);|m', $string, $match);
```
Make sure to you multi-line mode `m`, so that `^` will also match at the start of each line and not just at the start of the string.
If you **only** wanted to exlude `l` and `_` in front of `from` but accept any other characters, then a negative lookbehind might be what you are looking for:
```
preg_match('|(?<![l_])from:(.*?);|m', $string, $match);
```
The convenient thing about lookbehinds is, that they are not included in the actual match. They just check what's there without actually consuming it. [Here is some reading.](http://www.regular-expressions.info/lookaround.html) |
3,731,756 | Let $(\Omega,\mathcal{F},P)$ be a probability space and $\mathcal{H}\subset\mathcal{G}\subset\mathcal{F}$ two $\sigma$-algebras. We know from Jensen's inequality, that for $X\in L^2(\Omega,\mathcal{F},P)$
$$
\mathbb{E}[|\mathbb{E}[X|\mathcal{H}]|^2]\leq\mathbb{E}[|X|^2].
$$
Can this be generalized to an inequality like
$$
\mathbb{E}[|\mathbb{E}[X|\mathcal{H}]|^2]\leq\mathbb{E}[|\mathbb{E}[X|\mathcal{G}]|^2]\leq\mathbb{E}[|X|^2]\
$$
even if $X$ is not necessarily $\mathcal{G}$-measurable?
I couldn't find a proof of that version (I don't even know if it even holds or we need further restrictions) but I'm pretty sure it was used in this paper <https://arxiv.org/abs/1907.06474> only justified by
>
> As the conditional expectation is an orthogonal projection, we clearly have that ...
>
>
>
Thanks for any help! | 2020/06/23 | [
"https://math.stackexchange.com/questions/3731756",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/691199/"
] | The easiest way (in my opinion) to see that the matrix is positive definite is to check two things: is the matrix symmetric (yes and easily checkable) and are all the eigenvalues positive (yes, but less obvious).
You can quickly see that the eigenvalues are all positive using the Gershgorin circle theorem (<https://en.wikipedia.org/wiki/Gershgorin_circle_theorem>). In short, all the eigenvalues (for your matrix) live in (at least) one of the balls: $B(25, 20)$ (ball centered at 25 of radius 20), $B(18, 15)$, and $B(11, 5)$. All of those balls are strictly positive, so all your eigenvalues are positive.
Symmetry combined with all positive eigenvalues implies positive definite. | Here is an expanded proof that the form is positive definite using Gaussian elimination. Using simultaneous row-and-column operations, we have
$$
\pmatrix{25 & 15 & -5 \\
15 & 18 & 0 \\
-5 & 0 & 11} \leadsto
\pmatrix{25&0&-5\\0&9&3\\-5 & 3 & 12
}
\leadsto
\pmatrix{25&0&0\\0&9&3\\0 & 3 & 12
}
\leadsto
\pmatrix{25&0&0\\0&9&0\\0&0&11}.
$$
So, the matrix is positive definite. But why does this method work? The key is to see that every row-reduction step corresponds to grouping variables to remove coefficients.
For instance, the elementary corresponding to the first step was
$$
E = \pmatrix{1&0&0\\-3/5 & 1 & 0\\0 & 0 & 0},
$$
which is to say that
$$
M\_1 = \pmatrix{25&0&-5\\0&9&3\\-5 & 3 & 12
} = EBE^T.
$$
We want to see why $B$ will be positive definite if and only if $B$ is positive definite. To that end, note that
$$
M\_1 = EBE^T \implies B = E^{-1}M\_1E^{-T}.
$$
Note that
$$
E^{-T}x = \pmatrix{1&3/5&0\\0&1&0\\0&0&1}\pmatrix{a\\b\\c} = \pmatrix{a + 3b/5\\ b\\ c}
$$
So, the quadratic form
$$
Q(x) = x^TBx = x^TE^{-1}BE^{-T}x = (E^{-T}x)^TB (E^{-T}x)
$$
can be written as
$$
Q(x) = 25(a + 3b/5)^2 + 10(a + 3b/5)c + 18b^2 + 11c^2.
$$
With that, we can see that if the quadratic form
$$
x^TM\_1x = 25a^2 + 10ac + 18b^2 + 11c^2
$$
is positive definite, then so is $Q(x)$. This connection is maintained until the final step, where we arrive that $M\_3$ and the associated quadratic form
$$
x^TM\_3x = 25a^2 + 9b^2 + 11c.
$$
Because this quadratic form was positive definite, so was the one associated with $M\_2,M\_1,$ and $B$. |
3,282,103 | I have been trying to figure this out for quite sometime (reading online blogs and articlaes), but so far unsuccessful.
What are delegates? What are Lambda Expressions? Advantages and disadvantages of both? Possible best practice of when to use one or the other?
Thanks in advance. | 2010/07/19 | [
"https://Stackoverflow.com/questions/3282103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/279521/"
] | Delegates are methods that you can use as variables, like strings etc. For example you can declare a delegate method with one argument:
```
delegate void OneArgumentDelegate(string argument);
```
It doesn't do anything, much like an interface. If you have a method in any class with one argument like this:
```
void SomeMethod(string someArgument) {}
```
It *matches* the signature of the delegate, and thus can be assigned to a variable of its type:
```
OneArgumentDelegate ThisIsAVariable = new OneArgumentDelegate(SomeMethod);
OneArgumentDelegate ThisIsAlsoAVariable = SomeMethod; // Shorthand works too
```
These can then be passed as arguments to methods and invoked, like so:
```
void Main()
{
DoStuff(PrintString);
}
void PrintString(string text)
{
Console.WriteLine(text);
}
void DoStuff(OneArgumentDelegate action)
{
action("Hello!");
}
```
This will output `Hello!`.
Lambda expressions are a shorthand for the `DoStuff(PrintString)` so you don't have to create a method for every delegate variable you're going to use. You 'create' a temporary method that's passed on to the method. It works like this:
```
DoStuff(string text => Console.WriteLine(text)); // single line
DoStuff(string text => // multi line
{
Console.WriteLine(text);
Console.WriteLine(text);
});
```
Lambda expressions are just a shorthand, you might as well create a seperate method and pass it on. I hope you understand it better now ;-) | **Delegate** is an object that hold a reference to a function. Several different delegates may point to the same function. A *delegate*'s type defines the footprint of a function it may point to.
**Lambda expression** is a function that doesn't have name. The only way to execute this function is to have a *delegate* pointing to the function. *Lambda expressions* are usually defined in place where you need a delegate to a function with a given footprint. This is useful to make code less verbose and at the same time more descriptive and flexible
I would suggest that you use a named function and a delegate to it whenever you have some code that is going to be called from different places. A common example is an event listener that you want to attach to several event producers.
Another point to consider writing a separate function is the complexity of the code. It isn't going to help anyone if you write a whole program inside a lambda expression.
On the other hand, you often need some trivial processing that you want to be executed in a callback manner. This is the point where you might *love* the lambda expressions.
What is very nice about lambda expressions that they inherit the scope they were defined in, so that you can easily your variables inside the lambda expression, and thus pass a lot of info inside. You should be careful though, see the Remarks section of
[this](http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx) article.
Labdas are brilliant in conjunction with LINQ.
To conclude, I have to quote [yet another](http://msdn.microsoft.com/en-us/library/bb397687.aspx) must-read msdn section:
>
> When you use method-based syntax to call the Where method in the Enumerable class (as you do in LINQ to Objects and LINQ to XML) the parameter is a delegate type System.Func. A lambda expression is the most convenient way to create that delegate. When you call the same method in, for example, the System.Linq.Queryable class (as you do in LINQ to SQL) then the parameter type is an System.Linq.Expressions.Expression where Func is any Func delegates with up to sixteen input parameters. Again, a lambda expression is just a very concise way to construct that expression tree. The lambdas allow the Where calls to look similar although in fact the type of object created from the lambda is different.
> |
3,826,600 | Does anyone know how to do a polymorphic association in `Mongoid` that is of the relational favor but not the embedding one.
For instance this is my `Assignment` model:
```
class Assignment
include Mongoid::Document
include Mongoid::Timestamps
field :user
field :due_at, :type => Time
referenced_in :assignable, :inverse_of => :assignment
end
```
that can have a polymorphic relationship with multiple models:
```
class Project
include Mongoid::Document
include Mongoid::Timestamps
field :name, :type => String
references_many :assignments
end
```
This throws an error saying unknown constant Assignable. When I change the `reference` to `embed`, this all works as documented in [Mongoid's documentation](http://mongoid.org), but I need it to be `reference`.
Thanks! | 2010/09/29 | [
"https://Stackoverflow.com/questions/3826600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126749/"
] | From Mongoid Google Group it looks like this is not supported. Here's the [newest relevant post](http://groups.google.com/group/mongoid/browse_thread/thread/63acbea4780fedab/3393314de457a95a?lnk=gst&q=polymorphic#3393314de457a95a) I found.
Anyway, this is not to hard to implement manually. Here's my polymorphic link called Subject.
Implementing inverse part of relation might be somewhat more complicated, especially because you will need same code across multiple classes.
```
class Notification
include Mongoid::Document
include Mongoid::Timestamps
field :type, :type => String
field :subject_type, :type => String
field :subject_id, :type => BSON::ObjectId
referenced_in :sender, :class_name => "User", :inverse_of => :sent_notifications
referenced_in :recipient, :class_name => "User", :inverse_of => :received_notifications
def subject
@subject ||= if subject_type && subject_id
subject_type.constantize.find(subject_id)
end
end
def subject=(subject)
self.subject_type = subject.class.name
self.subject_id = subject.id
end
end
``` | Rails 4+
========
Here's how you would implement **Polymorphic Associations** in *Mongoid* for a `Comment` model that can belong to both a `Post` and `Event` model.
The `Comment` Model:
```rb
class Comment
include Mongoid::Document
belongs_to :commentable, polymorphic: true
# ...
end
```
`Post` / `Event` Models:
```rb
class Post
include Mongoid::Document
has_many :comments, as: :commentable
# ...
end
```
---
**Using Concerns:**
In Rails 4+, you can use the Concern pattern and create a new module called `commentable` in `app/models/concerns`:
```rb
module Commentable
extend ActiveSupport::Concern
included do
has_many :comments, as: :commentable
end
end
```
and just `include` this module in your models:
```rb
class Post
include Mongoid::Document
include Commentable
# ...
end
``` |
28,181,395 | I have the following regular expression:
```
>>> re.findall(r'\r\n\d+\r\n',contents)[-1]
'\r\n1621\r\n'
>>> re.findall(r'\r\n\d+\r\n',contents)[-1].replace('\r','').replace('\n','')
'1621'
```
How would I improve the regular expression such that I don't need to use the python `replace` methods?
Note that the digit must be surrounded by those characters, I can't do a straight `\d+`. | 2015/01/27 | [
"https://Stackoverflow.com/questions/28181395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/651174/"
] | Simply use parenthesis:
```
re.findall(r'\r\n(\d+)\r\n',contents)[-1]
```
That way you match the given pattern and only get the parenthesis content in `findall` result. | You could use look-ahead and look-back assertions:
```
re.findall(r'(?<=\r\n)\d+(?=\r\n)',contents)[-1]
``` |
12,294 | We all know the limits of a married person.We all know the definition of cheating in Buddhism.
But Buddhism existed in a time Porn did not exist.
So if a married person watch porn is it cheating? | 2015/10/31 | [
"https://buddhism.stackexchange.com/questions/12294",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/7141/"
] | Technically, watching porn doesn't break the 3rd precept, but it weakens it. In other words, it weakens the merits you gain by keeping to the precept apart from accumulating bad karma. | Donating porn/nude arts, women to men for evil purposes, bulls for cows to breed, alcohol and arranging dances(probably sexually arousing) are considered evil charity which are sinful. So clearly porn is not something good but sinful whether or not it falls under physically cheating. |
21,482,840 | Can somehow an invalid System.Guid object be created in .Net (Visual Basic or C#). I know about Guid.Empty method but it is not what I am searching for. For example with invalid symbols or spaces or being too short or longer than an valid one etc.
Thanks! | 2014/01/31 | [
"https://Stackoverflow.com/questions/21482840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1752845/"
] | >
> Can a Guid be created with invalid symbols or spaces or being too short or longer than an valid one etc?
>
>
>
No - a Guid is just a 128-bit number that can be *represented* in 5 groups of hexadecimal numbers. There's no way for the string representation of a `Guid` to contain anything other than 32 hex characters (and possibly 4 hyphens or a few other formatting characters).
You can create a *string* that does not represent a valid `Guid`, but there's no way to put that into a `Guid` object. | You should be able to do this using the [constructor](http://msdn.microsoft.com/en-us/library/96ff78dc%28v=vs.110%29.aspx) for Guid:
```
Guid badGuid = new Guid("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
```
If this throws an exception then it means the runtime will not allow you to construct an invalid Guid, and you don't need to test for that scenario. Note that according to the docs it must be given the correct number of characters, so that case is definitely not testable. On a different note, are you sure you're testing the behavior of your code, because it sounds like you're trying to write tests for extremely specific framework features which is not the purpose of unit testing your code. |
45,393,432 | In This Code When I Select the output text I see this:
[](https://i.stack.imgur.com/FKQsC.jpg)
How can I fix it?
```css
p {
font-family: 'Cairo', sans-serif;
line-height: 15px;
}
```
```html
<link href="https://fonts.googleapis.com/css?family=Cairo" rel="stylesheet">
<p>
Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla Pla
</p>
``` | 2017/07/29 | [
"https://Stackoverflow.com/questions/45393432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8351459/"
] | I compared my code with this example <http://machinelearningmastery.com/text-generation-lstm-recurrent-neural-networks-python-keras/>
by carefully block out line-by-line and run again. After a whole day, finally, I found what was wrong.
When making char-int mapping, I used
```
# title_str_reduced is a string
chars = list(set(title_str_reduced))
# make char to int index mapping
char2int = {}
for i in range(len(chars)):
char2int[chars[i]] = i
```
A set is an unordered data structure. In python, when a set is converted to a list which is ordered, the order is randamly given. Thus my char2int dictionary is randomized everytime when I reopen python.
I fixed my code by adding a sorted()
```
chars = sorted(list(set(title_str_reduced)))
```
This forces the conversion to a fixed order. | assume you have a code like this:
```
model = some_model_you_made(input_img) # you compiled your model in this
model.summary()
model_checkpoint = ModelCheckpoint('yours.h5', monitor='val_loss', verbose=1, save_best_only=True)
model_json = model.to_json()
with open("yours.json", "w") as json_file:
json_file.write(model_json)
model.fit_generator(#stuff...) # or model.fit(#stuff...)
```
Now turn your code into this:
```
model = some_model_you_made(input_img) #same model here
model.summary()
model_checkpoint = ModelCheckpoint('yours.h5', monitor='val_loss', verbose=1, save_best_only=True) #same ckeckpoint
model_json = model.to_json()
with open("yours.json", "w") as json_file:
json_file.write(model_json)
with open('yours.json', 'r') as f:
old_model = model_from_json(f.read()) # open the model you just saved (same as your last train) with a different name
old_model.load_weights('yours.h5') # the model checkpoint you trained before
old_model.compile(#stuff...) # need to compile again (exactly like the last compile)
# now start training with the checkpoint...
old_model.fit_generator(#same stuff like the last train) # or model.fit(#stuff...)
``` |
59,616,212 | ```
namespace LEARNING
{
public class Human
{
public string nameOne;
public string nameTwo;
public int ageOne;
public bool hasagetwo;
public int ageTwo;
public bool isalive;
public void Info()
{
Console.WriteLine("Name =" + nameOne + "," + nameTwo);
}
}
class Program
{
static void Main(string[] args)
{
/* Class Stuff */
Human humanOne = new Human();
Human.nameOne = "Adrian";
Human.hasagetwo = true;
Console.WriteLine(humanOne.nameOne);
Human.Info();
/* Basic Things Down There */
const string stringOne = "String";
const string notes = "The Fact that String One has the Value of 'String One' is :";
Console.WriteLine(notes);
Console.WriteLine(stringOne == "StringOne");
int a = 10;
int b = 3;
int c = 11;
Console.WriteLine(++a);
Console.WriteLine(a - b);
Console.WriteLine(a == c);
Console.WriteLine(b != a);
Console.WriteLine(a = c);
Console.WriteLine(a != c && a == 10);
Console.WriteLine(b != 6 || a == c);
Console.WriteLine(!(a == b));
/* Classes Down There */
Human Adrian = new Human();
}
}
}
```
>
> CS0120 C# An object reference is required for the non-static field, method, or property
>
>
> | 2020/01/06 | [
"https://Stackoverflow.com/questions/59616212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12662959/"
] | You're trying to set object property values, but you are doing it through the class by mistake
```
Human humanOne = new Human();
Human.nameOne = "Adrian";
Human.hasagetwo = true;
// ....
Human.Info();
```
should be
```
Human humanOne = new Human();
humanOne.nameOne = "Adrian";
humanOne.hasagetwo = true;
// ...
humanOne.Info();
```
Think about it this way, what if you made 2 human objects? If `Human.` was the way to access, how would you know which of the two you were setting? The exception to this is static fields and methods, but to access the actual instances you refer to those instances themselves. | Change
```
Human.nameOne = "Adrian";
Human.hasagetwo = true;
Console.WriteLine(humanOne.nameOne);
Human.Info();
```
to
```
humanOne.nameOne = "Adrian";
humanOne.hasagetwo = true;
Console.WriteLine(humanOne.nameOne);
humanOne.Info();
```
You are trying to assign instance variables to a type (Human), you have to assign them to the instance of the type (humanOne) instead. |
1,700,861 | Is there a closed form results for this integral
$$
\int\_{0}^{\pi}\frac{1}{a-cos\theta}d\theta
$$
where a > 1. | 2016/03/16 | [
"https://math.stackexchange.com/questions/1700861",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/288511/"
] | With residue calculus we can evaluate it without any difficulty.
Setting $z = e^{i\theta}$ we have
$$\cos\theta = \frac{1}{2}(z + z^{-1})$$
So
$$\frac{1}{2}\int\_0^{2\pi}\frac{-i}{z\left(a - \frac{1}{2}\left(z + \frac{1}{z}\right)\right)}\ \text{d}z$$
We denote
$$f(z) = \frac{-i}{z\left(a - \frac{1}{2}\left(z + \frac{1}{z}\right)\right)} = \frac{i}{z^2 - za + 1}$$
Since $a > 1$ you will get real or complex roots respectively for $a \geq 2$ and $1 < a < 2$.
If you know how to compute residues, after putting in the unit circle you will have to compute
$$2\pi i \sum\_{\alpha} \text{res}(f(z), z\_{\alpha})$$
**In the end**
$$\int\_0^{\pi}\frac{1}{a - \cos\theta}\ \text{d}\theta = \frac{\sqrt{\frac{a+1}{a-1}}\pi}{1+a}$$
Which **since $a > 1$** becomes
$$\int\_0^{\pi}\frac{1}{a - \cos\theta}\ \text{d}\theta = \frac{\pi}{\sqrt{a^2-1}}$$ | Two methods have already been given on paths to obtain the integral's value. It is fairly evident that the general integral can take on the form
$$\int \frac{d\theta}{a - \cos\theta} = - \frac{2}{\sqrt{1-a^2}} \, \tanh^{-1}\left(\frac{(a+1) \, \tan\left(\frac{\theta}{2}\right)}{\sqrt{1-a^2}} \right).$$
For the limits given it is seen that $\tan\left(\frac{\pi}{2}\right) = \infty$ and $\tan\left(\frac{0}{2}\right) = 0$. Using $\tanh^{-1}(\infty) = - \frac{\pi i}{2}$ and $\tanh^{-1}(0) = 0$ then the integral in question becomes
$$\int\_{0}^{\pi} \frac{d\theta}{a - \cos\theta} = \frac{\pi}{\sqrt{a^2 - 1}}.$$ |
54,419,928 | I've got hundreds files that are named with the following scheme:
XX - YY Title.ext
However, they don't always sort properly because XX and YY can be 1 or 2 digit numbers. I would like to rename the files such that XX and YY are always 2 digits by adding a leading zero if necessary.
For example, I'm currently getting sorting that looks like this:
```
1 - 1 BillyBob.ext
1 - 10 Jimmy2.ext
1 - 2 Stewy3.ext
10 - 1 Cletus.ext
2 - 1 Homer.ext
```
What I want is this:
```
01 - 01 BillyBob.ext
01 - 02 Stewy3.ext
01 - 10 Jimmy2.ext
02 - 01 Homer.ext
10 - 01 Cletus.ext
```
I've successfully changed the XX part using the code:
```
rename -n 's/\d+/sprintf("%02d", $&)/e' *
```
However, I cannot seem to figure out how to property execute something that will act on the YY part.
\*\*\*\*Appended to orignial post\*\*\*\*
More specifically, I don't know how to act on the YY part without also acting on any numeric charters that appear later in the filename.
\*\*\*\*End appended content\*\*\*\*
Any help is appreciated.
Thanks! | 2019/01/29 | [
"https://Stackoverflow.com/questions/54419928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5321658/"
] | For completeness: this can also be solved directly on the (UNIX) shell with the `sort` from GNU coreutils:
```sh
$ cat dummy.txt
1 - 1 BillyBob.ext
1 - 10 Jimmy.ext
1 - 2 Stewy.ext
10 - 1 Cletus.ext
2 - 1 Homer.ext
$ sort --field-separator=- -k 1n -k 2n <dummy.txt
1 - 1 BillyBob.ext
1 - 2 Stewy.ext
1 - 10 Jimmy.ext
2 - 1 Homer.ext
10 - 1 Cletus.ext
```
i.e.
* use `-` as field separator,
* sort by first field numerically, and
* sort by second field numerically | Try this Perl one-liner
```
perl -lne ' s/(\d+)\s-\s(\d+)\s+(\S+)/sprintf("%02d-%02d %s",$1,$2,$3)/ge; $kv{$_}=1 ; END { print join("\n",sort keys %kv) } '
```
with inputs
```
$ cat notorious.txt
1 - 1 BillyBob.ext
1 - 10 Jimmy.ext
1 - 2 Stewy.ext
10 - 1 Cletus.ext
2 - 1 Homer.ext
$ perl -lne ' s/(\d+)\s-\s(\d+)\s+(\S+)/sprintf("%02d-%02d %s",$1,$2,$3)/ge; $kv{$_}=1 ; END { print join("\n",sort keys %kv) } ' notorious.txt
01-01 BillyBob.ext
01-02 Stewy.ext
01-10 Jimmy.ext
02-01 Homer.ext
10-01 Cletus.ext
$
``` |
60,953,810 | I'm using `wp_enqueue_style` to enqueue [this Google Font file](https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,300;0,400;0,700;1,400&family=Neuton:ital,wght@0,300;0,400;0,700;1,400&display=swap). Here is my code:
`wp_enqueue_style( 'google-fonts', 'https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,300;0,400;0,700;1,400&family=Neuton:ital,wght@0,300;0,400;0,700;1,400&display=swap', [] );`
This is in my functions.php file.
However, when I view source on my loaded page, the URL for that font file is cut down to: <https://fonts.googleapis.com/css2?family=Neuton%3Aital%2Cwght%400%2C300%3B0%2C400%3B0%2C700%3B1%2C400>&display=swap&ver=5.3.2
As you can see, the first family param has been removed after being outputted through `wp_enqueue_style`. Is there a way to fix this without doing anything hacky? I think there may be an outdated way to build the URL for both font families to come through, but I'd rather be able to use what Google now provides. My original URL inside `wp_enqueue_style` is the URL generated by Google Fonts for me to embed. | 2020/03/31 | [
"https://Stackoverflow.com/questions/60953810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4630362/"
] | This actually has to do with PHP and the way it parses query parameters.
<https://www.php.net/manual/en/function.parse-str.php>
In any case, the current workaround is to pass "null" to the version parameter to have WordPress not add a "ver" to the URL.
```
wp_enqueue_style( 'google-fonts', 'https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,300;0,400;0,700;1,400&family=Neuton:ital,wght@0,300;0,400;0,700;1,400&display=swap', [], null );
```
That ending "null" will eliminate the problem, since WordPress won't try to add any additional parameters to the URL, thus not running it through PHP's query string handling functions.
This may be addressed more directly in a future WordPress update. However, having no version on these external URLs makes sense regardless. | The same query parameter is defined twice (`family`) so WordPress removes one. This is a normal thing in a typical context: if there is a repeated query parameter, only the last one is used. WordPress makes use of this "rule" when enqueuing the URL.
I can't tell you why Google Fonts changed the syntax from the `|` separator (like so: `https://fonts.googleapis.com/css?family=Montserrat|Neuton&display=swap`) to this repeated `family` parameter, but it looks like it might be because of the complexity like you see in your URL. One thing is for sure: this is going to cause some trouble like you're running into now. Either WordPress will need to adjust for this, or Google Fonts will have to update/revert their URL syntax. This probably won't happen today.
In this case, you're better off making the change yourself for now, by using the Classic Site (in the Google Fonts navbar) to build out your font URL instead. I know you won't get as many options (looks like you're trying to use variable fonts, which are fantastic!), so it is a bit disappointing.
You can, alternatively, download the files and self-host these fonts. It's a performance boost in many cases, too. |
444,845 | An open disk with radius $r$ centered at $\mathbf{p}$ is $D(\mathbf{p}, r)=\{\mathbf{q} \mid d(\mathbf p, \mathbf q) < r\}$, and the Minkowski sum of two sets $A$ and $B$ is $A \oplus B=\{\mathbf p + \mathbf q \mid \mathbf p \in A, \mathbf q \in B \}$.
How can you show that $D(\mathbf{a}, r\_a) \oplus D(\mathbf{b}, r\_b) = D(\mathbf{a} + \mathbf{b}, r\_a + r\_b)$?
*Attempt:*
\begin{align}
D(\mathbf{a}, r\_a) \oplus D(\mathbf{b}, r\_b) &=
\{\mathbf p + \mathbf q \mid \mathbf p \in D(\mathbf{a}, r\_a), \mathbf q \in D(\mathbf{b}, r\_b) \} \\&=
\{\mathbf p + \mathbf q \mid \mathbf p \in \{\mathbf{x} \mid d(\mathbf a, \mathbf x) < r\_a\}, \mathbf q \in \{\mathbf{y} \mid d(\mathbf b, \mathbf y) < r\_b\} \\&=
\{\mathbf p + \mathbf q \mid d(\mathbf a, \mathbf p) < r\_a, d(\mathbf b, \mathbf q) < r\_b \}
\end{align}
And here I got stuck. As best as I can tell, now I would need to prove that $$d(\mathbf a, \mathbf p) < r\_a, d(\mathbf b, \mathbf q) < r\_b \iff d(\mathbf a + \mathbf b, \mathbf p + \mathbf q) < r\_a + r\_b$$ but this seems false to me. I tried adding the two inequalities together, but that doesn't seem to give me that condition unless $\mathbf a - \mathbf p$ and $\mathbf b - \mathbf q$ are parallel. | 2013/07/16 | [
"https://math.stackexchange.com/questions/444845",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/31941/"
] | To show $A = B$ it is usually the easiest to split into two parts $A \subseteq B$ and $A \supseteq B$.
First, if $p \in D(a,r\_a)$ and $q \in D(b,r\_b)$ then $p + q \in D(a+b, r\_a+r\_b)$. This is simple using the triangle inequality: $$|(p+q)-(a+b)| < |p-a| + |q-b|.$$
Secondly, if $u \in D(a+b, r\_a + r\_b)$, then we need to find a point $v$ such that $v \in D(a,r\_a)$ and $u-v \in D(b,r\_b)$. A good candidate is to split the distance between $u$ and $a+b$ in ratio $r\_a : r\_b$, that is (the $-b$ is to adjust for the center of the disk)
$$v = \frac{r\_a\cdot u + r\_b \cdot (a+b)}{r\_a + r\_b}-b.$$
Now,
$$|v-a| = \left|\frac{r\_a\cdot u + r\_b \cdot (a+b)}{r\_a + r\_b}-b-a\right|
= r\_a\frac{|u-(a+b)|}{r\_a+r\_b}\leq r\_a$$
and
$$|(u-v)-b| = \left|\frac{r\_b\cdot u -r\_b\cdot(a+b)}{r\_a + r\_b}+b-b\right|
= r\_b\frac{|u-(a+b)|}{r\_a+r\_b}\leq r\_b.$$
I hope this helps ;-) | I would take the following route. Hopefully it is more intuitive.
It is clear that $$D(b, r\_b)\oplus D(0, r\_0)=D(b, r\_b+r\_0)$$
and that
$$a+D(b, r)=D(a+b, r).$$
(Here $a+ \text{"some set"}$ denotes translation). So we write
$$D(a, r\_a)=a+D(0, r\_a).$$
Therefore
\begin{equation}\begin{split}
D(a, r\_a)\oplus D(b, r\_b) &= [a+D(0, r\_a)]\oplus D(b, r\_b) \\
&=a+[D(0, r\_a)\oplus D(b, r\_b)]\\
&=a+ D(b, r\_a+r\_b) \\
&= D(a+b, r\_a+r\_b).
\end{split}
\end{equation} |
13,077,241 | I am trying to merge multiple linux commands in one line to perform deployment operation.
For example
```
cd /my_folder
rm *.jar
svn co path to repo
mvn compile package install
``` | 2012/10/25 | [
"https://Stackoverflow.com/questions/13077241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/216431/"
] | I've found that using ; to separate commands only works in the foreground. eg :
`cmd1; cmd2; cmd3 &` - will only execute `cmd3` in the background, whereas
`cmd1 && cmd2 && cmd3 &` - will execute the entire chain in the background IF there are no errors.
To cater for unconditional execution, using parenthesis solves this :
`(cmd1; cmd2; cmd3) &` - will execute the chain of commands in the background, even if any step fails. | FYI,
if you need to run multiple commands in one-line in if-else, you can group the commands with parenthesis. See this [page](https://www.gnu.org/software/bash/manual/html_node/Command-Grouping.html) for more details.
You can replace the semicolon (**;**) with **&&** or **||** depending on what you need. Please note that parenthesis creates a sub-shell to execute the commands.
Following command executes the cmd1, cmd2, and cmd3 commands if a file called **file\_name** exists; otherwise, cmd4, cmd5, and cmd6.
```
[ -f file_name ] && (cmd1; cmd2; cmd3) || (cmd4; cmd5; cmd6)
``` |
4,960,211 | I asked a question regarding this yesterday, but it was muddled and didn't make sense, so I'm going to boil it down to the core issue.
I have an `entries` table. When a new record is saved, the `entries_controller` adds a time to the `date` column, which is recorded as a datetime. In the `new` method, I declare a new DateTime as so:
```
@entry.date = DateTime.new( params[:year].to_i, params[:month].to_i, params[:day].to_i )
```
I then include it as a hidden field with formtastic:
```
<%= f.input :date, :as => :hidden %>
```
Once the entry is saved to the database, the date field looks like `2011-02-10 00:00:00`. Everything is working as planned so far, but when I try to retrieve that entry by querying against the `date` field, I get `nil`.
I've tried:
```
search_date = DateTime.new(2011,2,10)
Entry.find_by_date(search_date)
=> nil
```
I've even tried to search by string, which doesn't make sense since it's a datetime field.
```
search_time = '2010-02-10 00:00:00'
Entry.find_by_date(search_date)
=> nil
```
What am I doing wrong here? Why can't I retrieve the record by date? | 2011/02/10 | [
"https://Stackoverflow.com/questions/4960211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142486/"
] | If you want to use input instead of raw\_input in python 2.x,then this trick will come handy
```
if hasattr(__builtins__, 'raw_input'):
input=raw_input
```
After which,
```
testVar = input("Ask user for something.")
```
will work just fine. | This is my work around to fail safe in case if i will need to move to python 3 in future.
```
def _input(msg):
return raw_input(msg)
``` |
6,470,059 | I overrode the Equals() of my class to compare ID values of type Guid.
Then Visual Studio warned:
>
> ... overrides Object.Equals(object o) but
> does not override Object.GetHashCode()
>
>
>
So I then also overrode its GetHashCode() like this:
```
public partial class SomeClass
{
public override bool Equals(Object obj)
{
//Check for null and compare run-time types.
if (obj == null || this.GetType() != obj.GetType()) return false;
return this.Id == ((SomeClass)obj).Id;
}
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
}
```
It seems to work. **Have I done this correctly?** Remember Id is of type Guid. **Does it matter that my class is an Entity Framework object?** | 2011/06/24 | [
"https://Stackoverflow.com/questions/6470059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | As others have said, the use of Reflection in Equals seems dodgy. Leaving that aside, let's concentrate on GetHashCode.
The primary rule for GetHashCode that you must not violate is **if two objects are equal then they must both have the same hash code**. Or, an equivalent way of saying that is **if two objects have different hash codes then they must be unequal.** Your implementation looks good there.
You are free to violate the converse. That is, if two objects have the same hash code then they are permitted to be equal or unequal, as you see fit.
I am assuming that "Id" is an immutable property. If "Id" can change over the lifetime of the object then you can have problems when putting the object in a hash table. Consider ensuring that only immutable properties are used in computing equality and hash code.
Your implementation looks good but the fact that you are asking the question indicates that you might not have a solid grasp of all the subtle factors that go into building an implementation of GetHashCode. A good place to start is my article on the subject:
<http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/> | Traditionally `Equals` is implemented in such a way that two objects will only be "Equal" if they are exactly the same in every way. For example, if you have two objects that represent the same object in the database, but where one has a different `Name` property than the other, the objects aren't considered "Equal", and should avoid producing the same "Hashcode" if possible.
It is better to err on the side of "not equal" than to risk calling two objects equal that aren't. This is why the default implementation for objects uses the memory location of the object itself: no two objects will ever be considered "equal" unless they are exactly the same object. So I'd say unless you want to write both `GetHashCode` and `Equals` in such a way that they check for equality of all their properties, you're better off not overriding either method.
If you have a data structure (like a `HashSet`) where you specifically want to determine equality based on the ID value, you can provide a specific `IEqualityComparer` implementation to that data structure. |
83,747 | Can anyone share a knowledge how to
\_ secure LND node
\_ backup node with all Channels
I think only a seed will not be sufficient.
What is your plan B in case of disaster? How to do an Emergency restore, migration to other server, or set up high availability solution?
thanks | 2019/01/17 | [
"https://bitcoin.stackexchange.com/questions/83747",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/88332/"
] | You can secure an LND node in the same way how you would secure any host on the internet. You can for example use `ufw` to set up a firewall. You could also have a physical firewall in front of you node. Also a big step towards security would be to run no other software on the node.
As for backups it is a little bit more tricky. The seedwords will not include the state of all of your channels. With the current channel design you cannot restore an old backup. As an old channel state would - following the protocol - allow your channel partners to claim all bitcoins in that channel. However you can use a distributed file system or a distributed data base to store your channel state. If configured properly writing to the file system or database will certainly be slower as all calls have to be synchronized and blocking.
Also you could at least have a raid system that helps if a disk crashes.
Generally you can shutdown your lightning node and migrate it to another computer by copying the database. As mentioned again it is tricky as you really have to make sure that you don't migrate old state. I have a [video showing this for c-lightning](https://www.youtube.com/watch?v=-S7pQOw36vI). The process for lnd should be similar. | Newer versions (0.6) of LND support channel backups/restore without restarting. So doing a backup of the seed plus channels should help, but I think you need to to frequent backups, maybe with every channel transaction, to have always the latest state of the channels.
Also I secure my LND keeping it into a docker container, with restricted access only to port 9735, and using the GRPC from inside the container or from a private network. |
611,883 | How do I write a regex to match any string that doesn't meet a particular pattern? I'm faced with a situation where I have to match an (A and ~B) pattern. | 2009/03/04 | [
"https://Stackoverflow.com/questions/611883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65184/"
] | The complement of a regular language is also a regular language, but to construct it you have to build the [DFA](http://en.wikipedia.org/wiki/Deterministic_finite_automata) for the regular language, and make any valid state change into an error. See [this](http://nitsan.org/~maratb/cs164/lminus.html) for an example. What the page doesn't say is that it converted `/(ac|bd)/` into `/(a[^c]?|b[^d]?|[^ab])/`. The conversion from a DFA back to a regular expression is not trivial. It is easier if you can use the regular expression unchanged and change the semantics in code, like suggested before. | My answer here might solve your problem as well:
<https://stackoverflow.com/a/27967674/543814>
* Instead of Replace, you would use Match.
* Instead of group `$1`, you would read group `$2`.
* Group `$2` was made non-capturing there, which you would avoid.
Example:
`Regex.Match("50% of 50% is 25%", "(\d+\%)|(.+?)");`
The first capturing group specifies the pattern that you wish to avoid. The last capturing group captures everything else. Simply read out that group, `$2`. |
3,629,330 | I am using core plot in one of my iPhone projects. Is it possible to change the color for a selected slice in a pie chart (using CPPieChartDataSource, CPPieChartDelegate)? | 2010/09/02 | [
"https://Stackoverflow.com/questions/3629330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193545/"
] | I added this to my .m file (which is the data source file for the pie chart). The colors are ugly -- just used them to test as they are really different than the defaults. And there are only three slices in my chart, hence the hard-coded 3 colors. I found the Core Plot documentation helpful for all this. [Here's the link to the fillWithColor method documentation](http://core-plot.github.io/iOS/interface_c_p_t_fill.html#a2172ba68fdb3550b58a39cdcd3f9f2a1). NOTE: You need to use CPT as a prefix now, not the old CP.
```
-(CPTFill *)sliceFillForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index;
{
CPTFill *color;
if (index == 0) {
color = [CPTFill fillWithColor:[CPTColor purpleColor]];
} else if (index == 1) {
color = [CPTFill fillWithColor:[CPTColor blueColor]];
} else {
color = [CPTFill fillWithColor:[CPTColor blackColor]];
}
return color;
}
```
Sorry if I messed up the answer entry -- this is my first ever post on StackOverflow | Swift version:
```
func sliceFillForPieChart (pieChart: CPTPieChart, recordIndex: UInt) -> CPTFill {
switch (recordIndex+1) {
case 1:
return CPTFill(color:CPTColor.greenColor());
case 2:
return CPTFill(color:CPTColor.redColor());
default:
return CPTFill(color:CPTColor.orangeColor());
}
}
``` |
14,828,199 | I have the following array:
```
my @anim = ('rn4,mm8,bosTau2,canFam2,dasNov1,echTel1',
'rn4,mm8,oryCun1,bosTau2,canFam2,dasNov1,echTel1');
```
It contain multiple strings, each string are comma separated.
What I want to do is to sort them based on the greatest members of the string.
Hence what I tried to do is this:
```
my @animsort = sort{scalar(split(",",$b)) <=> scalar(split(",",$a))} @anim;
```
But it gives this error:
```
Use of implicit split to @_ is deprecated at ./scripts/mycode.pl line 35
```
What's the correct way to do it? | 2013/02/12 | [
"https://Stackoverflow.com/questions/14828199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/67405/"
] | If you want to sort by the count of elements in each string, your code will do that. I am not getting any errors with your posted code in Perl 5.16. Do you have an older version of Perl? (I found [some evidence](https://stackoverflow.com/questions/2436160/why-does-perl-complain-use-of-implicit-split-to-is-deprecated) that your code may generate the error in older versions).
Here is another option:
```
my @animsort = sort{(() = $b =~ /,/g) <=> (() = $a =~ /,/g)} @anim;
```
This sorts by counting the commas, rather than actually splitting the string. The funny `() =` syntax is to make sure the regex is treated as being in list context, so we can count the matches. | Regexp could sole everything or you could remove the warnings with 'no warnings;' pragma locally.
```
my $comma_re = qr!,!;
my @animsort = sort{$b =~ s!$comma_re!!g <=> $a =~ s!$comma_re!!g} @anim;
print Dumper(\@anim,\@animsort);
``` |
286,072 | I've seen a few users with a gold badge in a tag answer a question, and then immediately close the question as duplicate.
[Here's an example](https://stackoverflow.com/questions/28509772) of a question which it happened on (**EDIT**: The answer has been removed, and is now only viewable to users with 10k+ reputation. This question is not only about this one post, but about all posts that this happens on).
The problem with this is that it probably cannot be solved. If I was in the same position, I would probably answer the question before closing it, to make sure the user gets a good answer.
There's already been something discussed about this on [Closing a question as a duplicate, then answering it](https://meta.stackoverflow.com/questions/265957), but that had to do with voting to close the question, this was done without any voting, due to the mighty Mjölnirs being able to close/reopen questions without voting.
I personally don't see anything wrong with this, as long as the user isn't doing it for personal gain (it would be fine if they made the answer community wiki). Are there any guidelines on what gold-badge users supposed to do with respect to this? | 2015/02/14 | [
"https://meta.stackoverflow.com/questions/286072",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/2767207/"
] | I think it's bad form to answer a question then **immediately** close it as a duplicate. If it's a duplicate, just close it. By answering it then immediately closing it, it sends a signal that you're hoping for upvotes on your answer, while depriving others of the opportunity to answer as well. That's not a very level playing field. The dupe hammer is intended to get duplicate questions closed faster, not closed right after gold badge owners can post an answer.
---
Having said that (a few years ago), I will add that it's important to look at the timeline of events before we jump to the conclusion that someone is tactically close voting.
Several times I've answered a question after a cursory search, then noticed that someone else found a canonical version and cast a close vote. I then added my close vote, since I think that's the right thing to do. I'll usually delete my answer and repost it on the original question in those cases (if my answer adds anything), but it's not strictly necessary to do that. (For example, if you're pointing out exactly what line of code is causing an exception on a duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it), it doesn't really make sense to move that answer.) | I got linked here because [I did the exact same](https://stackoverflow.com/questions/50304062/append-to-list-in-python/50304080#50304080) - the questions is a variant of the "I added a list to a list in a loop and afterwards it contains the same list n times) - just with the twist of adding dicts to the list.
I voted to close as dupe of [how-to-clone-or-copy-a-list](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) and answered with a code example and a solution to explain the similarity - and as I thought I got
>
> @Patrick Artner, i do not want to copy any list. i want to create new list with dictionary.
>
>
>
as comment because the reasoning for marking this as dupe was not instantly clear to the question owner.
The reasoning for me is:
* if marked as dupe it can be deleted down the road
* by me answering with a code example the owner gets helped along now
To make it clear, I do not answer "all" dupes I mark, just if I want to add some code to explain the reasoning behind me "duping" it - and that only if it does not fit into a comment.
Question is deleted and the person who linked me here retracted his comment on my answer...
I do not have the "close-hammer" - I just vote to close, so its mabye different than the original case here. |
33,101,771 | When running an Oozie java action on a freshly installed Hadoop HDP 2.2.2.4, and for example tries to access hdfs it accesses the wrong filesystem:
`java.lang.IllegalArgumentException: Wrong FS: hdfs:/tmp/text.txt, expected: file:///`
It can be fixed by included the core-site.xml in the Oozie action:
```
<file>hdfs:/path-to-core-site.xml-on-hdfs</file>
```
But what is the reason and what is the proper fix? | 2015/10/13 | [
"https://Stackoverflow.com/questions/33101771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/630269/"
] | Change it to this:
```
$scope.registerClick(e) {
if (e.target.classList.contains('parent')){
// The .parent div is clicked
} else if (e.target.parentNode.classList.contains('parent')){
// Some child of the .parent div is clicked
} else {
var elem = e.target;
while(elem.tagName != 'body' || !elem.classList.contains('parent')){
elem = elem.parentNode;
}
if (elem.classList.contains('parent')){
console.log('DIV .parent')
} else {
console.log('Body tag reached. No .parent element found');
}
}
}
```
`e.target` is the clicked element. Use it to determine which element was clicked. This is a **clean JavaScript solution**. You wont even need the `$scope.registerClick(e) {` part if can attach the event like so:
```
someDiv.onclick = function(){/* Same code as above. */}
```
if you use the latter approach, 'this' points to the `div`, so you can that the validations a little bit. | You can do something like
```js
var app = angular.module('my-app', [], function() {})
app.controller('AppController', function($scope) {
$scope.registerClick = function($event) {
//if has jQuery
if ($($event.target).closest('.parent').length) {
console.log('clicked parent');
$scope.jQuery = true;
} else {
$scope.jQuery = false;
}
var isParent = false;
if (angular.isFunction($event.target.closest)) {
isParent = !!$event.target.closest('.parent');
} else {
var tmp = $event.target;
do {
isParent = tmp.classList.contains('parent');
tmp = tmp.parentNode;
} while (tmp && tmp.classList && !isParent);
}
$scope.native = isParent;
};
})
```
```css
.parent {
border: 1px solid grey;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="my-app">
<div ng-controller="AppController" ng-click="registerClick($event)">
<div>outside</div>
<div class="parent">
parent
<div>div</div>
<div>div</div>
</div>
<div>
jQuery: {{jQuery}}
</div>
<div>
native: {{native}}
</div>
</div>
</div>
``` |
4,654,196 | I am trying to create an initialisation function that will call multiple functions in the class, a quick example of the end result is this:
```
$foo = new bar;
$foo->call('funca, do_taxes, initb');
```
This will work fine normally with call\_user\_func function, but what I really want to do is do that inside the class, I haven't a clue how to do this, a quick example of my unworking code is as follows:
```
class bar {
public function call($funcs) {
$funcarray = explode(', ', $funcs);
foreach($funcarray as $func) {
call_user_func("$this->$func"); //???
}
}
private function do_taxes() {
//...
}
}
```
How would I call a dynamic class function? | 2011/01/11 | [
"https://Stackoverflow.com/questions/4654196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/560900/"
] | It's actually a lot simpler than you think, since PHP allows things like [variable variables](http://php.net/manual/en/language.variables.variable.php) (and also variable object member names):
```
foreach($funcarray as $func) {
$this->$func();
}
``` | when we want to check whether a class function/method exists within the class,
then this could help
inside class...
```
$class_func = "foo";
if(method_exists($this , $class_func ) ){
$this->$class_func();
}
public function foo(){
echo " i am called ";
}
``` |
1,616,187 | Suppose I have a chain complex of chains $C\_n$. Then one can obtain the homology groups of this complex. Now if I choose any abelian group $G$ and I consider the cochain group $C\_n^\*=Hom(C\_n,G)$ then I can obtain the cohomology groups. Now the question is: If I form the cocohomology group by considering $C\_n^{\*\*}=Hom(Hom(C\_n,G),G)$ and defining the cocoboundary maps in the obvious ways, will I obtain the Homology groups again? | 2016/01/17 | [
"https://math.stackexchange.com/questions/1616187",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/304440/"
] | Not in general.
Suppose that all of the $C\_n = \oplus\_{i = 0}^{\infty} \mathbb{k}$, with differentials $0$, and let $G = \mathbb{k}$. Then $Hom(C\_n, \mathbb{k}) = \Pi\_{i = 0}^{\infty} \mathbb{k}$. Taking the $\mathbb{k}$ dual again gives something containing as a subspace $\Pi\_{i = 0}^{\infty} \mathbb{k}$, with zero as the differentials. The cohomology groups are different, as $(\Pi\_{i = 0}^{\infty} \mathbb{k})^\* \not = \oplus\_{i = 0}^{\infty} \mathbb{k}$
If you have torsion in your chain groups: for example $\mathbb{Z}/2$ as some component of some $C\_n$, this data will disappear when you double dual. (You can concoct an example again with zero differentials.)
I guess one situation in which you can say that they will be the same is when you are working in the category of finite dimensional vector spaces.
In the more common algebraic topology situation (for example cellular homology), then $C\_\*$ is a bounded complex of finitely generated free $R$ modules, where $R$ is a PID. In this case one can say something by repeated applications of the universal coefficients theorem and computational facts about exts - the formula you'll get for ${}\_iH$ (the ith cocohomology) will be some messy combination of direct sums and compositions of Exts and Homs, involving the groups $H^{i}, H^{i-1}, H\_i, H\_{i-2}$: <https://en.wikipedia.org/wiki/Universal_coefficient_theorem>
(Maybe somebody with more sophistication than me can interpret this in terms of composition of the left derived functors of $Hom(\\_,G)$?)
Maybe you can play around with that to get some conditions under which the cocohomology agrees. | If $G = \mathbb R$ (or any field), and $C$ is the simplical chain complex associated to a countably infinite discrete space (e.g., the integers), then $H\_0 = Z\_0$ will be an infinite direct sum of copies of the reals, but $Z^0$ will be the dual space of that, and the double dual will not be isomorphic to the original (because of the inifinite dimensions), hence I believe that the $0$th co-cohomology will not be the same as the $0$th homology. |
35,710,619 | Say I have the following collection of `Student` objects which consist of Name(String), Age(int) and City(String).
I am trying to use Java's Stream API to achieve the following sql-like behavior:
```
SELECT MAX(age)
FROM Students
GROUP BY city
```
Now, I found two different ways to do so:
```
final List<Integer> variation1 =
students.stream()
.collect(Collectors.groupingBy(Student::getCity, Collectors.maxBy((s1, s2) -> s1.getAge() - s2.getAge())))
.values()
.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.map(Student::getAge)
.collect(Collectors.toList());
```
And the other one:
```
final Collection<Integer> variation2 =
students.stream()
.collect(Collectors.groupingBy(Student::getCity,
Collectors.collectingAndThen(Collectors.maxBy((s1, s2) -> s1.getAge() - s2.getAge()),
optional -> optional.get().getAge())))
.values();
```
In both ways, one has to `.values() ...` and filter the empty groups returned from the collector.
Is there any other way to achieve this required behavior?
These methods remind me of `over partition by` sql statements...
Thanks
---
**Edit:** All the answers below were really interesting, but unfortunately this is not what I was looking for, since what I try to get is just the values. I don't need the keys, just the values. | 2016/02/29 | [
"https://Stackoverflow.com/questions/35710619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1909995/"
] | Do not always stick with `groupingBy`. Sometimes `toMap` is the thing you need:
```
Collection<Integer> result = students.stream()
.collect(Collectors.toMap(Student::getCity, Student::getAge, Integer::max))
.values();
```
Here you just create a `Map` where keys are cities and values are ages. In case when several students have the same city, merge function is used which just selects maximal age here. It's faster and cleaner. | ```
Here is my implementation
public class MaxByTest {
static class Student {
private int age;
private int city;
public Student(int age, int city) {
this.age = age;
this.city = city;
}
public int getCity() {
return city;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return " City : " + city + " Age : " + age;
}
}
static List<Student> students = Arrays.asList(new Student[]{
new Student(10, 1),
new Student(9, 2),
new Student(8, 1),
new Student(6, 1),
new Student(4, 1),
new Student(8, 2),
new Student(9, 2),
new Student(7, 2),
});
public static void main(String[] args) {
final Comparator<Student> comparator = (p1, p2) -> Integer.compare( p1.getAge(), p2.getAge());
final List<Student> studets =
students.stream()
.collect(Collectors.groupingBy(Student::getCity,
Collectors.maxBy(comparator))).values().stream().map(Optional::get).collect(Collectors.toList());
System.out.println(studets);
}
}
``` |
20,814 | What are some good reference books for learning the subtleties of OSX? I found it fairly easy to pick up, but some things are kinda weird (like switching the default web browser, I had to get my friend who's a Mac expert to guide me through it).
Our library had 2 O'Reilly books on Mac OSX but a lot of the stuff mentioned in the books seemed like unnecessary fluff to me. | 2009/08/10 | [
"https://superuser.com/questions/20814",
"https://superuser.com",
"https://superuser.com/users/1162/"
] | While not a book, [Mac OS X Hints](http://www.macosxhints.com/) is a good place for tips and tricks. | MAX OS X for Unix geeks is a fab resource |
4,522,031 | Completely stuck on solving this question,
Any hints or ideas? I tried expanding but got nowhere with it, it seems to be more complicated than some $a^2\geq 0$. | 2022/08/31 | [
"https://math.stackexchange.com/questions/4522031",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1090851/"
] | Picking up from your last step, assuming $ a, b \neq 0$, we have
\begin{align\*}
a - b = \sqrt{b} - \sqrt{a} & \iff (a - b)(\sqrt{b} + \sqrt{a}) = b - a \\
& \iff (a - b)(\sqrt{a} + \sqrt{b} + 1) = 0 \\
& \iff a - b = 0 \quad \text{or} \quad \sqrt{a} + \sqrt{b} + 1 = 0 \\
& \iff a = b \quad \text{(Since $ \sqrt{a} + \sqrt{b} + 1 \neq 0 $ for any $ a $ or $ b $)}
\end{align\*}
So all in all we have $ f(a) = f(b) $ if and only if $a = b $ or $ a = b = 0$, or we can absorb the latter condition into the former one and says $ f(a) = f(b) $ if and only if $ a = b$. | I would approach this by showing the function is increasing. Once you know $f$ is increasing, then suppose $f(a)=f(b)$ and $a\lt b$. But then because $f$ is increasing, $f(a)\lt f(b)$, a contradiction.
And there is a similar contradiction when $f(a)=f(b)$ and $a\gt b$.
So the only conclusion is that when $f(a)=f(b)$, $a$ must equal $b$.
---
Now how do we know $f$ is increasing? If $a\lt b$, then $a+\sqrt{a}\lt b+\sqrt{a}$. And then as long as we know $x\mapsto \sqrt{x}$ is increasing, we can move on to write $a+\sqrt{a}\lt b+\sqrt{b}$. This is the defintion for $f$ to be increasing.
---
Now how do we know $x\mapsto\sqrt{x}$ is increasing? I'm not sure how deep down into fundamentals you need to reach. But there are several ways to establish that. I'll leave this answer at this much. |
54,729,678 | I am trying to display items in a shopping cart. I made a "BagItem" component to display the information about the item, which comes from an object which is in the cart array in state, in redux. I also made a "Bag" component, which is where I map over the cart information and return the "BagItem" component.
Everything seems to be working with the map function. When I console.log the information in the BagItem component, I see all the properties I need to display. The problem is that in the Bag Component, the BagItem component will not render. When I load my webpage, I see the StoreNav and the subtotal text, but the BagItem component does not display.
I am very new to React and I'm sure there is something obvious I'm missing. I've been trying to figure it out all day, and I'd be very grateful for any help you can give.
BAG COMPONENT:
```
import React, { Component } from "react";
import { connect } from "react-redux";
import StoreNav from "../store/StoreNav";
import BagItem from "../bag/BagItem";
import { getCart } from "../../ducks/reducer";
class Bag extends Component {
constructor(props) {
super(props);
this.state={}
}
componentDidMount(){
this.props.getCart()
console.log(this.props.cart)
}
componentDidUpdate(){
this.props.getCart()
}
render() {
const bagList =
this.props.cart && this.props.cart.map(element => {
console.log(this.props.cart)
return <BagItem
element={element}
id={element.id}
key= {`${element.id}${element.name}${element.price}${element.image}${element.size}${element.sleeves}${element.fabric}${element.length}`}
name={element.name}
image={element.image}
size={element.size}
price={element.price}
sleeves={element.sleeves}
fabric={element.fabric}
length={element.length}
/>
})
return (
<div>
<StoreNav />
{bagList}
<p>Subtotal</p>
</div>
);
}
}
const mapStateToProps = state => {
return {
cart: state.cart
};
};
export default connect(
mapStateToProps,
{ getCart: getCart }
)(Bag);
```
BAGITEM COMPONENT
```
import React, { Component } from "react";
import { connect } from "react-redux";
import "./bagitem.css";
import { getCart } from "../../ducks/reducer";
class BagItem extends Component {
componentDidMount(){
this.props.getCart()
console.log(this.props.cart[0][0].name)
}
render() {
return (
<div className="bag-item-component-container">
<div className="bag-item-component">
<div className="bag-item-row1">
<div>Size</div>
<div>Quantity</div>
<div>Price</div>
<div>Remove</div>
</div>
{/* <div className="bag-item-row2">
placeholder
</div> */}
<div className="bag-item-image-and-details-container">
<div className="img1">
<img className="item-image" alt="" src={this.props.cart[0][0].image} />
</div>
<div>{this.props.cart[0][0].name}
<div className="details">
<div>sleeves</div>
<div>length</div>
<div>fabric</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {
cart: state.cart
};
};
export default connect(
mapStateToProps,
{ getCart: getCart }
)(BagItem);
``` | 2019/02/17 | [
"https://Stackoverflow.com/questions/54729678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11073321/"
] | The condition in the while loop doesn't work the way you think.
```
while (inputFile.eof() || drinkMachine.totalDrinks == 20)
```
When doing input extraction in a loop you should *first* do the extraction, check if it succeeds, then continue. `eof()` checks if the eofbit (end-of-stream bit) in the stream is set, which occurs when the previous extraction failed. Typically when doing extraction you check stream validity with `fail()`.
```
while (inputFile >> drinkMachine.totalDrinks && !inputFile.fail() && drinkMachine.totalDrinks == 20)
```
We can get rid of `!inputFile.fail()` since every stream has a built in `operator bool()` so it checks `fail()` implicitly:
```
while (inputFile >> drinkMachine.totalDrinks && drinkMachine.totalDrinks == 20)
```
Your other issues are pointed out by Acorn. | There are several errors in your code.
First, you need to access your `drinkMachine` object to get to `arrayDrink` here:
```
{
inputFile >> arrayDrink[i].name;
inputFile >> arrayDrink[i].price;
inputFile >> arrayDrink[i].NumDrinksOfSameType;
}
```
See what you do in the loop:
```
for (int i = 0; i < drinkMachine.totalDrinks; i++)
```
---
Another one: you are trying to call `create` with a type, rather than an object:
```
create(DrinkMachine);
```
Instead, you need to define a `DrinkMachine` object and then pass it to `create`. |
2,522,603 | How can I call a webmethod of one application from another application, when both are developed in C#? | 2010/03/26 | [
"https://Stackoverflow.com/questions/2522603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168414/"
] | All of the suggested solutions should be working. But I think that you need to prevent the anchor's default action.
Add this code within a <script> tag in the <head> section of your document.
```
$(document).ready(function(){
$("#contact").click(function(event){
event.preventDefault(); //stops the browser from following the link
$("#contactable").click(); //opens contact form
alert("Showing mycontactform"); //remove this when it's working
});
});
```
You will need to add an 'id' tag to your contact anchor:
```
<a href="#" id="contact" title="Contact Us">CONTACT US</a>
```
You will also need to make sure you include jQuery in the <head> section of your document.
Add this line after the <head> tag:
```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
``` | I have to admit defeat on this one. I don't believe there is a solution based on the above answers (although I know they work in test environments), they just don't work in my exact case.
The reason for this is that if you do a view source on <http://www.thebalancedbody.ca/> the DIV `#contactable`
Is not exposed in the source so no matter what I do these approaches won't work. The associated javascript for the pop out form is here, maybe that will give some clues?
```
/*
* contactable 1.2.1 - jQuery Ajax contact form
*
* Copyright (c) 2009 Philip Beel (http://www.theodin.co.uk/)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Revision: $Id: jquery.contactable.js 2010-01-18 $
*
*/
//extend the plugin
(function($){
//define the new for the plugin ans how to call it
$.fn.contactable = function(options) {
//set default options
var defaults = {
name: 'Name',
email: 'Email',
message : 'Message',
subject : 'A contactable message',
label_name: 'Name',
label_email: 'E-Mail',
label_website: 'Website',
label_feedback: 'Your Feedback',
label_send: 'SEND',
recievedMsg : 'Thankyou for your message',
notRecievedMsg : 'Sorry but your message could not be sent, try again later',
disclaimer: 'Please feel free to get in touch, we value your feedback',
hide_email: 'false',
hide_website: 'false',
fileMail: 'mail.php',
hideOnSubmit: true
};
//call in the default otions
var options = $.extend(defaults, options);
//act upon the element that is passed into the design
return this.each(function(options) {
//construct the form
div_form = '<div id="contactable"></div><form id="contactForm" method="" action=""><div id="loading"></div><div id="callback"></div><div class="holder">';
div_form += '<p><label for="name">'+defaults.label_name+' <span class="red"> * </span></label><br /><input id="name_mc" class="contact" name="name" /></p>';
if(defaults.hide_email == 'false'){
div_form += '<p><label for="email">'+defaults.label_email+' <span class="red"> * </span></label><br /><input id="email_mc" class="contact" name="email" /></p>';
}
if(defaults.hide_website == 'false'){
div_form += '<p><label for="email">'+defaults.label_website+' <span class="red"> * </span></label><br /><input id="website_mc" class="contact" name="url" /></p>';
}
div_form += '<p><label for="comment">'+defaults.label_feedback+' <span class="red"> * </span></label><br /><textarea id="comment_mc" name="comment" class="comment" rows="4" cols="30" ></textarea></p>';
div_form += '<p><input class="submit" type="submit" value="'+defaults.label_send+'"/></p>';
div_form += '<p class="disclaimer">'+defaults.disclaimer+'</p></div></form>';
$(this).html(div_form);
//show / hide function
$('div#contactable').toggle(function() {
$('#overlay').css({display: 'block'});
$(this).animate({"marginLeft": "-=5px"}, "fast");
$('#contactForm').animate({"marginLeft": "-=0px"}, "fast");
$(this).animate({"marginLeft": "+=387px"}, "slow");
$('#contactForm').animate({"marginLeft": "+=390px"}, "slow");
},
function() {
$('#contactForm').animate({"marginLeft": "-=390px"}, "slow");
$(this).animate({"marginLeft": "-=387px"}, "slow").animate({"marginLeft": "+=5px"}, "fast");
$('#overlay').css({display: 'none'});
});
//validate the form
$("#contactForm").validate({
//set the rules for the fild names
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
url: {
required: true,
url: true
},
comment: {
required: true
}
},
//set messages to appear inline
messages: {
name: "",
email: "",
url: "",
comment: ""
},
submitHandler: function() {
$('.holder').hide();
$('#loading').show();
name_val = $('#contactForm #name_mc').val();
if(defaults.hide_email == 'false') email_val = $('#contactForm #email_mc').val();
else email_val = 'nothing';
if(defaults.hide_website == 'false') website_val = $('#contactForm #website_mc').val();
else website_val = 'nothing';
comment_val = $('#contactForm #comment_mc').val();
$.post(defaults.fileMail,{subject:defaults.subject, name: name_val, email: email_val, website: website_val, comment:comment_val},
function(data){
$('#loading').css({display:'none'});
if( data == 'success') {
$('#callback').show().append(defaults.recievedMsg);
if(defaults.hideOnSubmit == true) {
//hide the tab after successful submition if requested
$('#contactForm').animate({dummy:1}, 2000).animate({"marginLeft": "-=450px"}, "slow");
$('div#contactable').animate({dummy:1}, 2000).animate({"marginLeft": "-=447px"}, "slow").animate({"marginLeft": "+=5px"}, "fast");
$('#overlay').css({display: 'none'});
}
} else {
$('#callback').show().append(defaults.notRecievedMsg);
}
});
}
});
});
};
})(jQuery);
```
The other file that maybe useful is this:-
```
<?php
/*
Plugin Name: Magic Contact
Plugin URI: http://blog.hunk.com.mx/magic-contact/
Description: is a simple and Elegant contact form for Wordpress, taking as it bases to <a href="http://theodin.co.uk/blog/ajax/contactable-jquery-plugin.html">Contactable</a> (jQuery Plugin) By <a href="http://theodin.co.uk/">Philip Beel</a>, After enabling this plugin visit <a href="options-general.php?page=magic-contact.php">the options page</a> to configure settings of sending mail.
Version: 0.1
Author: Hunk
Author URI: http://hunk.com.mx
Copyright 2010 Edgar G (email : ing.edgar@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
register_activation_hook( dirname(__FILE__) . '/main.php', 'magic_contact_activate' );
function magic_contact_activate(){
if(!get_option('init_contact')){
update_option( 'recipient_contact', get_bloginfo('admin_email') );
update_option( 'subject_contact', 'A contactable message' );
update_option( 'label_name_contact', 'Name' );
update_option( 'label_email_contact', 'E-Mail' );
update_option( 'label_website_contact', 'Website' );
update_option( 'label_feedback_contact', 'Your Message' );
update_option( 'label_send_contact', 'SEND' );
update_option( 'recievedMsg_contact', 'Thank you for your message' );
update_option( 'notRecievedMsg_contact', 'Sorry, your message could not be sent, try again later' );
update_option( 'disclaimer_contact', 'Please feel free to get in touch, we value your feedback' );
update_option( 'hide_email_contact', 'false' );
update_option( 'hide_website_contact', 'false' );
update_option( 'init_contact', 1 );
}
}
// Add action links
add_action('plugin_action_links_' . plugin_basename(__FILE__), 'AddPluginActions');
function AddPluginActions($links) {
$new_links = array();
$new_links[] = '<a href="options-general.php?page=magic-contact.php">' . __('Settings') . '</a>';
return array_merge($new_links, $links);
}
add_action('admin_menu', 'mc_admin_actions');
function mc_admin_actions(){
add_options_page("Magic Contact", "Magic Contact", 'manage_options',"magic-contact.php", "magic_contact_menu");
}
function magic_contact_menu(){
if ( isset($_POST['submit']) ) {
if ( function_exists('current_user_can') && !current_user_can('manage_options') )
die(__('Cheatin’ uh?'));
update_option( 'recipient_contact', $_POST['recipient_contact'] );
update_option( 'subject_contact', $_POST['subject_contact'] );
update_option( 'label_name_contact', $_POST['label_name_contact'] );
update_option( 'label_email_contact', $_POST['label_email_contact'] );
update_option( 'label_website_contact', $_POST['label_website_contact'] );
update_option( 'label_feedback_contact', $_POST['label_feedback_contact'] );
update_option( 'label_send_contact', $_POST['label_send_contact'] );
update_option( 'recievedMsg_contact', $_POST['recievedMsg_contact'] );
update_option( 'notRecievedMsg_contact', $_POST['notRecievedMsg_contact'] );
update_option( 'disclaimer_contact', $_POST['disclaimer_contact'] );
if ( isset( $_POST['hide_email_contact'] ) ) update_option( 'hide_email_contact', 'true' ); else update_option( 'hide_email_contact', 'false' );
if ( isset( $_POST['hide_website_contact'] ) ) update_option( 'hide_website_contact', 'true' ); else update_option( 'hide_website_contact', 'false' );
}
include 'form-admin.php';
}
add_action('template_redirect', 'script_magic_contact');
function script_magic_contact(){
$base = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__));
wp_enqueue_script( 'jquery.contactable', $base . 'contactable/jquery.contactable.js', array('jquery') , 3.1);
wp_enqueue_script( 'jquery.validate', $base . 'contactable/jquery.validate.pack.js', array('jquery') , 3.1);
wp_enqueue_script( 'my_contactable', $base . 'my.contactable.php', array('jquery') , 3.1);
wp_enqueue_style( 'contactable', $base . 'contactable/contactable.css' );
}
add_action('wp_footer','div_magic_contact');
function div_magic_contact(){
echo '<div id="mycontactform"> </div>';
}
?>
``` |
4,147,401 | I was thinking about a building a CMS, and I want to implement the wordpress-like permalink for my posts. How do I do that?
I mean, How do I define the custom url structure for my pages? | 2010/11/10 | [
"https://Stackoverflow.com/questions/4147401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257944/"
] | I would say that anonymous functions show their beauty when there is good library classes/functions that use them. They are not that sexy by themselves. In the world of .net there is technology called LINQ that makes huge use of then in very idiomatic manner. Now back to PHP.
First example, sort:
```
uasort($array, function($a, $b) { return($a > $b); });
```
You can specify complex logic for sorting:
```
uasort($array, function($a, $b) { return($a->Age > $b->Age); });
```
Another example:
```
$data = array(
array('id' => 1, 'name' => 'Bob', 'position' => 'Clerk'),
array('id' => 2, 'name' => 'Alan', 'position' => 'Manager'),
array('id' => 3, 'name' => 'James', 'position' => 'Director')
);
$names = array_map(
function($person) { return $person['name']; },
$data
);
```
You see how nicely you can produce array of names.
Last one:
```
array_reduce(
array_filter($array, function($val) { return $val % 2 == 0; },
function($reduced, $value) { return $reduced*$value; }
)
```
It calculates product of even numbers.
**Some philosophy.** What is function? A unit of functionality that can be invoked and unit of code reuse. Sometimes you need only the first part: ability to invoke and do actions, but you don't want to reuse it at all and even make it visible to other parts of code. That's what anonymous functions essentially do. | If you need to create a callback (to make a concrete example, lets say its a comparison function for usort) anonymous functions are usually a good way to go. Particularly if the definition of the function is dependent on a few inputs (by this i mean a closure, which is NOT synonymous with anon function)
```
function createCallback($key, $desc = false)
{
return $desc ?
function($a, $b) use ($key) {return $b[$key] - $a[$key];} :
function($a, $b) use ($key) {return $a[$key] - $b[$key];};
}
usort($myNestedArray, createCallback('age')); //sort elements of $myNestedArray by key 'age' ascending
usort($myNestedArray, createCallback('age', true); //descending
``` |
270,170 | I have a content type that has 2 fields on it:
* image (multiple values)
* image description (multiple values)
I have 6 images and 6 descriptions. I want to use a view to show each image with each description. I have tried playing around with the "Display all values in the same row" settings but just can't get this to work. It displays the same image repeatedly (6 times) and then the descriptions are all correct, then repeats the next image 6 times again.
I am tearing my hair out here, how do I get a view to simply out output:
Image 1, Description 1
Image 2, Description 2
and so on?
I have included an image of current output plus the way the fields were set up on the node. I have set them up this way as I need to import a lot of them.[](https://i.stack.imgur.com/zQRGt.jpg)
[](https://i.stack.imgur.com/Fn09Q.jpg) | 2018/09/30 | [
"https://drupal.stackexchange.com/questions/270170",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/20344/"
] | If you want the name of the term, use `[webform_submission:values:profil:entity:field_personnel_sexe:name]`.
If you have another field for the *personnel\_sexe*, for example you want to show the description, you can:
1. Change display for *Token*
[](https://i.stack.imgur.com/mhTNP.png)
2. Use `[webform_submission:values:profil:entity:field_personnel_sexe:description]`
as token for the description field | You can you **:htmldecode:striptags** at the end of your token.
Care of the security (seen on the token tree page) :
>
> This suffix has security implications.
> Use :htmldecode with :striptags.
> :striptags removes all HTML tags from returned value.
>
>
> |
9,767,391 | Given the following integers and calculation
```
from __future__ import division
a = 23
b = 45
c = 16
round((a/b)*0.9*c)
```
This results in:
```
TypeError: 'int' object is not callable.
```
How can I round the output to an integer? | 2012/03/19 | [
"https://Stackoverflow.com/questions/9767391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/695457/"
] | Somewhere else in your code you have something that looks like this:
```
round = 42
```
Then when you write
```
round((a/b)*0.9*c)
```
that is interpreted as meaning a function call on the object bound to `round`, which is an `int`. And that fails.
The problem is whatever code binds an `int` to the name `round`. Find that and remove it. | Stop stomping on `round` somewhere else by binding an `int` to it. |
55,043 | I use Postgresql 8.4 and I wanted to know what type of RAID is mostly used for databases.
I read everywhere that RAID10 is the best suited and RAID5 not a good option.
ex: <http://www.revsys.com/writings/postgresql-performance.html>
My server is a Dell Poweredge 2950. Dell support told me that they dont have a lot of customers using RAID10. Most of times they use RAID5 + raid controller cache ON.
What do you think about that? What RAID level do you use for your database servers?
Thanks ! | 2009/08/17 | [
"https://serverfault.com/questions/55043",
"https://serverfault.com",
"https://serverfault.com/users/16344/"
] | Please find [here](http://wiki.postgresql.org/wiki/HP_ProLiant_DL380_G5_Tuning_Guide) a performance and scaling reports, about HP Proliant DL380 G5.
the tests are based on various file systems (jfs, xfs, reiserfs, ext2 and ext3). | RAID5 is used because it's easier to setup and think about than RAID10. You don't require an even number of disks and more people are familiar with it.
In the past, we have always done RAID5 (Dell PowerEdge 2650-2950), but in our latest machine (running MS-SQL, not PostgreSQL) I tested both RAID10 and RAID5. I found that for our workload, RAID10 gave us a moderate performance increase (~10%).
If you have the time, I would suggest setting the server up both ways and running normal DB tasks (backups and restores, whatever jobs or reports you might do). |
167,114 | Do you know how can I set the width of a modal window opened by a lightning component action? In the edit options I can set only the height but is not enough because the content of my table is not completely shown.
Here is the code:
```
<aura:component access="GLOBAL" implements="force:hasRecordId,force:appHostable,flexipage:availableForAllPageTypes,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" controller="OrganizeEnvelopeController" >
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:attribute name="plico" type="Envelope__c" />
<aura:attribute name="fixedDocs" type="Bit2Sign__Fixed_Document__mdt[]" />
<div class="c-container">
<lightning:layout horizontalAlign="space">
<lightning:layoutItem flexibility="auto" padding="around-small" size="6">
<aura:text value="Tipologia Plico: "/>
<aura:text value="{!v.plico.Bit2Sign__Tipologia_Invio__c}"/>
</lightning:layoutItem>
<lightning:layoutItem flexibility="auto" padding="around-small" size="6">
<aura:text value="Descrizione Plico: "/>
<aura:text value="{!v.plico.Name}"/>
</lightning:layoutItem>
</lightning:layout>
</div>
<aura:text value="Elenco Documenti"/>
<table class="slds-table slds-table--bordered slds-table--cell-buffer">
<thead>
<tr class="slds-text-title--caps">
<th scope="col">
<div class="slds-truncate" title="Nome documento">Nome documento</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Tipologia Documento">Tipologia Documento</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Stato">Stato</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Firmatari">Firmatari</div>
</th>
<th scope="col">
<div class="slds-truncate" title="File">File</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Action">Action</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.fixedDocs}" var="docs">
<tr>
<td>{!docs.Label}</td>
<td>{!docs.__Document_Type__c}</td>
<td>{!docs.__State__c}</td>
<td>{!docs.__Firmatari__c}</td>
<td><lightning:input aura:id="file" type="file" label=" " name="file" multiple="true" accept=".pdf, .doc, .docx" onchange="{!c.save}"/></td>
<td><lightning:button label="" iconName="utility:delete" iconPosition="left"/></td>
</tr>
</aura:iteration>
<c:OrganizeEnvelopeRow />
{!v.body}
</tbody>
</table>
</aura:component>
``` | 2017/04/03 | [
"https://salesforce.stackexchange.com/questions/167114",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/19222/"
] | Okay, So I had the same requirement where I needed to increase the pop-up size. So I have gone through various link also this. But none of them seems working for me. I tried to put the css suggested by @Amulyaranjan in style class but that also didn't work for me. it seems like component css load first and than the component css override that css.
Other solution could be include the style tag in the component but that too is not supported after spring '18. SO somehow I needed that CSS suggested by @Amulyaranjan or @crmprogdev. So for that what I did is same as mentioned in many of the above comments but the only difference is I put that StyleSheet in the Static Resources
```
.slds-modal__container{
max-width: 70rem !important;
width:80% !important;
}
```
above is my stylesheet and I put this style sheet in my component.
>
> <ltng:require styles="{!$Resource.popupCSS}" />
>
>
>
and below is my scree-shot of the quick action.
It looks like style in the ltng:require load in last after all styles get loaded. So, this hack saves my life.
[](https://i.stack.imgur.com/SH34s.png) | 1) Create this static resource: QuickActionModalStyle
```
.slds-modal__container{
max-width:80rem !important;
width:80% !important;
}
```
Adjust width as per your requirements.
2) Use this new static resource with at the beginning of your component.
```
<ltng:require styles="{!$Resource.QuickActionModalStyle}" />
``` |
29,422,949 | So I'm working through this homework, and am totally stuck at putting Excel formulas in my code. This is the prompt:
>
> 3. Use Excel functions in the code (with Application.WorksheetFunction) to calculate
> the statistics and assign the corresponding values to variables of type double. Use the
> range name ScoresData when referring to the range which is provided as an argument
> to the functions. Remember – when using Excel functions in the code, the range
> specifications need to be done using VB syntax.
> 4. Open a single message box showing the values stored in the variables (see image on
> below). Tips:
>
>
> a. You can use the constant vbNewLine to break a line in the prompt. For example:
> MsgBox “there is so much material in BIT 311” & vbNewLine & “Oich!” –
> will place a line break after 311.
>
>
> b. You can use the constant vbTab to add a Tab space between two parts of the
> prompt. For example: MsgBox “Average:” & vbTab & Average
>
>
> 5. Finally, assign the macro to a button on the worksheet.
>
>
>
And my current code (not working) is:
```
Sub ScoresStatistics()
Dim Average As Double
Dim StandDev As Double
Dim Min As Double
Dim Max As Double
Dim ScoresData As Range
Range("A1").End(xlDown).Name = "ScoresData"
Average = Application.WorksheetFunction(Average(ScoresData))
StandDev = Application.WorksheetFunction(StDev.P(ScoresData))
Min = Application.WorksheetFunction(Minimum(ScoresData))
Max = Application.WorksheetFunction(Maximum(ScoresData))
MsgBox "Here are summary measures for the scores:" & vbNewLine & "Average:" & vbTab & Average & vbNewLine & "Standard Deviation:" & vbTab & StandDev & vbNewLine & "Minimum:" & vbTab & Min & vbNewLine & "Maximum:" & vbTab & Max
End Sub
``` | 2015/04/02 | [
"https://Stackoverflow.com/questions/29422949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4735757/"
] | Since you're consuming multiple items, would suggest to use consumeAsync for multiple items method by passing your list of purchases. You can find it inside [TrivialDrive](http://developer.android.com/training/in-app-billing/preparing-iab-app.html) sample app for Iab ver 3
```
/**
* Same as {@link consumeAsync}, but for multiple items at once.
* @param purchases The list of PurchaseInfo objects representing the purchases to consume.
* @param listener The listener to notify when the consumption operation finishes.
*/
public void consumeAsync(List<Purchase> purchases, OnConsumeMultiFinishedListener listener) {
```
Use onConsumeMultiFinished as your callback
```
public void onConsumeMultiFinished(List<Purchase> purchases, List<IabResult> results);
```
It should take care of sending proper async consume requests. Update you code and post any problems. | change your class to these
```
public class BankClass {
public int itemId;
public int quantity;
public String Price;
public BankClass(int _itemId,int _quantity,String _Price){
itemId = _itemId;
quantity = _quantity;
Price = _Price;
}
public int getItemId() {
return itemId;
}
public String getPrice() {
return Price;
}
public int getQuantity() {
return quantity;
}
}
```
in listitem click change these all code like bewlo
```
BankClass currentItem = BankList.get(position);
CoinItemID = currentItem.getItemId();
if (currentItem.getQuantity() == 100)
{
CoinItemID = currentItem.getItemId();
String payload = "";
mHelper.launchPurchaseFlow(BankActivity.this, SKU_hundred, RC_REQUEST,
mPurchaseFinishedListener, payload);
}
``` |
178,925 | How to make the double lines to only one bold (thick) line ?
```
\documentclass[french]{beamer}
\usepackage{babel}
\usepackage{adjustbox}
\usepackage{array}
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}
\begin{document}
\begingroup
\defbeamertemplate{enumerate item}{image}{\small\includegraphics[height=1.8ex]{images/gofor}}
\makeatletter
\def\@listii{\leftmargin\leftmarginii
\topsep 2ex
\parsep 0\p@ \@plus\p@
\itemsep \parsep}
\makeatother
\begin{frame}{Conclusion}
\begin{table}
\centering
\caption{Comparatif entre ATL et MFC}
\vspace{0.4cm}
\begin{tabular}{
| C{0.07\textwidth}
*{3}{|C{\dimexpr0.22\textwidth-2\tabcolsep\relax}}
||C{\dimexpr0.22\textwidth-2\tabcolsep\relax} |
}
\hline
& {\fontsize{9}{9}\selectfont Gestion avancée des threads} & {\fontsize{9}{9}\selectfont Gestion de la mémoire} & {\fontsize{9}{9}\selectfont Vitesse d'exécution} & {\fontsize{9}{9}\selectfont Difficulté} \\
\hline
MFC & \adjustbox{valign=c}{\includegraphics[height=1.8ex]{example-image-a}} & \adjustbox{valign=c}{\includegraphics[height=1.8ex]{example-image-a}} & \adjustbox{valign=c}{\includegraphics[height=1.8ex]{example-image-a}} & \textcolor{green}{F}\\
\hline
ATL & \adjustbox{valign=c}{\includegraphics[height=1.8ex]{example-image-a}} &\adjustbox{valign=c}{\includegraphics[height=1.8ex]{example-image-a}\includegraphics[height=1.8ex]{example-image-a}} & \adjustbox{valign=c}{\includegraphics[height=1.8ex]{example-image-a}\includegraphics[height=1.8ex]{example-image-a}\includegraphics[height=1.8ex]{example-image-a}} & \textcolor{red}{D} \\
\hline
\end{tabular}
\end{table}
\end{frame}
\endgroup
\end{document}
``` | 2014/05/18 | [
"https://tex.stackexchange.com/questions/178925",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/49762/"
] | Two vertical rules separated by a space (of `\tabcolsep` in `tabular`) is given by `||` in the column specification. To remove the space between them, use `|@{}|`. If you want it thicker, you can use `|@{}|@{}|`, or add more `@{}|`'s.

```
\documentclass{beamer}
\begin{document}
\begin{frame}
\begin{tabular}{c | c || c |@{}| c |@{}|@{}| c |@{}|@{}|@{}| c |@{}|@{}|@{}|@{}| c}
A & B & C & D & E & F & G
\end{tabular}
\end{frame}
\end{document}
``` | I would recommend *not* using vertical rules, so the problem of thicker rules vanishes. But here's how you can do it.
```
\documentclass{beamer}
\usepackage{array}
\newcolumntype{I}{% I for a thick rule
!{\vline width 1pt}%
}
\newcolumntype{J}[1]{% variable thickness rule
!{\vline width #1}%
}
\begin{document}
\begin{frame}
\begin{tabular}{c | c || c I c J{2pt} c J{3pt} c }
A & B & C & D & E & F
\end{tabular}
\end{frame}
\end{document}
```
The specifier `I` gives a rule 1pt thick; change 1pt to suit your needs. With `J` you specify a thickness.
 |
7,846,581 | I have a base class that depends on another class for some special caching. I also wrote the special caching class.
I can test it so special caching class is passed as a mock to make sure the base class works as expected or I can use a real class to make sure that the whole thing works as expected.
If I use the real class I don't have to duplicate test logic in testing the cache class since this is the only use case for it (for now).
The best idea could be to write both tests (using mock and using real class), but it might be confusing to other developers why I test it twice.
Should I use mock here or the real class? | 2011/10/21 | [
"https://Stackoverflow.com/questions/7846581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30453/"
] | Why should you mock the real class if it does the job?
My advice would be:
* test your class features in its test case, except caching,
* test caching in the cache test case
I wouldn't be confused by that, as long as the tests of your cache class are exhaustive: if caching leads to problems, caching tests should fail, and not your outer class. | I've been in similar situations where I had a class in production code which was backed up by a couple of unit tests. These unit tests created mock objects to pass into the production code class. That meant I was able to run the unit tests without any dependencies.
Now, I also required to use that production class as part of a BDD (using SpecFlow) test. This type of testing was more integration, in that I actually created a real object (instead of a mock) which the production class required.
So from my experience I created a mock object only for the unit tests, whilst creating a real object for my integration tests. This is very subjective though, but for me it's worked out fine. |
44,213,176 | I suddenly started getting this error when trying to build. This was all working a few weeks ago with no changes that I know of. The issue seems to be related to `react-native-fbsdk`, but looking through its build.gradle it does not list `support.appcompat-v7.25.x`. Any advice?
```
A problem occurred configuring project ':app'.
> A problem occurred configuring project ':react-native-fbsdk'.
> Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugCompile'.
> Could not find com.android.support:appcompat-v7:25.3.1.
Searched in the following locations:
file:/Users/a/.m2/repository/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.pom
file:/Users/a/.m2/repository/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.jar
https://jcenter.bintray.com/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.pom
https://jcenter.bintray.com/com/android/support/appcompat-v7/25.3.1/appcompat-v7-25.3.1.jar
```
**build.gradle**
```
apply plugin: "com.android.application"
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
import com.android.build.OutputFile
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
def enableSeparateBuildPerCPUArchitecture = false
def enableProguardInReleaseBuilds = false
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "___"
minSdkVersion 16
targetSdkVersion 23
versionCode 22
versionName "1.5.0"
ndk {
abiFilters "armeabi-v7a", "x86"
}
manifestPlaceholders = [manifestApplicationId: "___",
onesignal_app_id: "___",
onesignal_google_project_number: "___"]
multiDexEnabled true
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
}
signingConfigs {
release {
storeFile file(MYAPP_RELEASE_STORE_FILE)
storePassword MYAPP_RELEASE_STORE_PASSWORD
keyAlias MYAPP_RELEASE_KEY_ALIAS
keyPassword MYAPP_RELEASE_KEY_PASSWORD
}
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86"
}
}
buildTypes {
release {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
signingConfig signingConfigs.release
}
}
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
def versionCodes = ["armeabi-v7a":1, "x86":2]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
compile project(':react-native-device-info')
compile project(':react-native-code-push')
compile project(':react-native-image-crop-picker')
compile project(':react-native-image-picker')
compile project(':react-native-fs')
compile project(':react-native-vector-icons')
compile project(':react-native-material-kit')
compile project(':react-native-config')
compile project(':react-native-onesignal')
compile project(':react-native-push-notification')
compile project(':react-native-android-permissions')
compile project(':react-native-android-keyboard-adjust')
compile project(':react-native-fbsdk')
compile (project(':react-native-fbads')) {
exclude group: 'com.google.android.gms'
}
compile 'com.facebook.android:audience-network-sdk:4.18.+'
compile 'com.google.ads.mediation:facebook:4.18.+'
compile 'com.google.firebase:firebase-core:10.2.0'
compile 'com.google.firebase:firebase-crash:10.2.0'
compile 'com.google.firebase:firebase-ads:10.2.0'
compile project(':react-native-billing')
compile project(':react-native-blur')
compile project(':instabug-reactnative')
compile project(':mobile-center-analytics')
compile project(':mobile-center-crashes')
compile (project(':react-native-appodeal')) {
exclude group: 'com.facebook.ads'
exclude (group: 'javax.inject', module: 'javax.inject')
}
compile project(':cheetah')
compile fileTree(dir: "libs", include: ["*.jar"])
compile "com.android.support:appcompat-v7:23.0.1"
compile "com.facebook.react:react-native:+" // From node_modules
compile "com.facebook.fresco:animated-gif:0.12.0"
compile "com.android.support:multidex:1.0.1"
}
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply plugin: 'com.google.gms.google-services'
``` | 2017/05/27 | [
"https://Stackoverflow.com/questions/44213176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736601/"
] | I've had the same problem (*appcompat-v7:25.3.1*), on an android project, but not using react.
I first tried to clean the gradle cache (~/.gradle/caches), like explained [here](https://stackoverflow.com/questions/23025433/how-to-clear-gradle-cache), but it didn't help.
Then I looked at the SDK Manager.
Android Support libraries are normally installed via sdkmanager.
The libraries are then stored in a local maven repository : `<SDK_HOME>/sdk/extras/android/m2repository/`.
For example, for `appcompat-v7` the list of versions installed is in `<SDK_HOME>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/maven-metadata.xml`.
So, for the **Android Support Repository (revision: 47.0.0)**, the last version was normally *25.3.1*.
To fix my problem, I had to **uninstall** the Android Support Repository via the SDK Manager, then **reinstall it**.
I also found another way to fetch support libraries : remotely.
After reading here (<https://developer.android.com/topic/libraries/support-library/setup.html#add-library>) and modifying `<PROJECT_ROOT>/build.gradle` like this :
```
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
```
Then I tried to use a newer version of *appcompat-v7:25.4.0* that was not in my local maven repository, and it worked !
The list of this Google Maven repository's versions of this library can be seen there : <https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/maven-metadata.xml>. | Since gradle doesn't support declaring repositories on a per-artifact basis yet.
I modified my build.gradle (not app/build.gradle) to force all dependency to react-native to specific version:
```
allprojects {
configurations.all {
resolutionStrategy {
eachDependency { DependencyResolveDetails details ->
if (details.requested.group == 'com.facebook.react' && details.requested.name == 'react-native') {
def file = new File("$rootDir/../node_modules/react-native/package.json")
def version = new groovy.json.JsonSlurper().parseText(file.text).version
details.useVersion version
}
}
}
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.