qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
sequence | response
stringlengths 0
115k
|
---|---|---|---|---|
105,849 | So in 3 we learn about the Virgo II lander, but really not much else in the space program. What else happened? Were there space stations, probes to other planets? | 2015/10/23 | [
"https://scifi.stackexchange.com/questions/105849",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/40833/"
] | Ultimately, we have speculative evidence that *Project: Safehouse*, aka the *Societal Preservation Program*, which tasked the Enclave to oversee the vaults, had but one supreme objective.
>
> The purpose of the [vault experiments](http://fallout.wikia.com/wiki/Vault) was to help prepare the Enclave for either re-colonizing Earth or colonizing another planet if Earth turned out to be uninhabitable.
>
>
>
Space flight was always part of the plan but it's unclear how far that part had been developed during the 23 years the program operated before the bombs fell.
---
Cool stuff in space:
[Archimedes](http://fallout.wikia.com/wiki/Archimedes_I), **New Vegas**
>
> It should be distinguished from Archimedes II, the second iteration of the system, which is an **orbital based laser system** and can target any outdoor location in the Mojave Wasteland.
>
>
>
[Highwater-Trousers](http://fallout.wikia.com/wiki/Highwater-Trousers), **Fallout 3**
>
> Highwater-Trousers is a computer program that was meant as a last resort, to be activated when an invading enemy had the SatCom Arrays under siege. From SatCom Array NW-05a it was possible to activate the program from the control terminal and call in **nuclear strikes from an orbiting platform**.
>
>
>
[B.O.M.B.](http://fallout.wikia.com/wiki/B.O.M.B.-001_design_document), **Van Buren Project** (game canceled)
>
> The Ballistic Orbital Missile Base 001 (abbreviated B.O.M.B.-001) is a large, donut shaped U.S. **space station** capable of firing twenty-four nuclear-tipped ballistic missiles. While it is currently staffed with eight individuals, it is capable of housing six people long term. A sister station, B.O.M.B.-002, existed alongside B.O.M.B.-001 until some point after the Great War. The layout for B.O.M.B.-001 shows areas designated for living, recreation, medical treatment, and a separate area for the station's true purpose; a nuclear missile control and launch center.
>
>
>
[USSA](http://fallout.wikia.com/wiki/United_States_Space_Administration), **Fallout 2** (unreliable source, although it does present a possible tie-in with the Hubologists having a space shuttle)
>
> United States Space Administration
>
>
> The following is based on Fallout 2 cut content and has not been confirmed by canon sources.
>
>
> The U.S. government's real plan to survive a nuclear war was simply to find another planet to live on after having helped to destroy the Earth. **A spacecraft designed to ferry the human race to another planet was either under construction or ready to go before the Great War broke out.** The plan was for the government to flee to the Enclave's Oil Rig, wait out the conflict and then pack up the populations of the Vaults to head into space. The Vaults were funded by the U.S. government and, accordingly, the government had control over them. Ostensibly, they were intended to allow a selection of privileged United States citizens to survive the Great War. Secretly, however, a large part of the Vault Project (Project Safehouse) had a far more sinister goal.
>
>
>
---
[Come Fly With Me](http://fallout.wikia.com/wiki/Come_Fly_With_Me) is a side quest in **Fallout: New Vegas**, primarily conducted at the *REPCONN test site*, which still has three somewhat functional rockets.
[REPCONN Aerospace](http://fallout.wikia.com/wiki/REPCONN_Aerospace) (**R**ocket **E**ngineering and **P**roduction **CO**mpa**N**y of **N**evada) was an up-and-coming regional aerospace firm based in Nevada that specialized in rocket manufacture, primarily for the U.S. government. Its original purpose was to develop orbital propulsion systems.
>
> The company was purchased by the giant RobCo company just before the Great War, in a hostile takeover. New security countermeasures were installed, and more militaristic plans were undertaken, especially after the discovery of a special radioactive igniting agent that interested senior RobCo management staff.
>
>
>
---
[ArcJet Systems](http://fallout.wikia.com/wiki/ArcJet_Systems), **Fallout 4**
>
> ArcJet Systems was a pre-War military and civilian aerospace contractor in the United States, **specializing in communications, propulsion systems, and custom-built high-tech aviation equipment**. One known facility is located in Cambridge. They produced electronics and rockets used by the USSA until 2077.
>
>
> In 2075, ArcJet began working on a **nuclear-powered rocket, the XMB booster engine**, in hopes of convincing the United States Space Administration to award them the lucrative contract for their Mars Shot Project.
>
>
>
The [Mars Shot Project](http://fallout.wikia.com/wiki/Mars_Shot_Project), was a plan by the USSA for a manned mission to Mars, and was scheduled for launch in July of 2078.
---
Space probes are the real question.
Did we launch the Voyager space probes or their equivalents during the once every 175y planetary alignment? If we could find a representation of Saturn in the Fallout universe with one solid ring around it, then we would know that we did *not* launch them, as only after Voyager 2 visited Saturn did we learn that it had many separate rings.
That's a somewhat moot point though, considering it's a game made by a company whose logo is a V2 shaped '50s rocket orbiting the Earth, and that **building space probes without transistors is highly unlikely.** See [divergence](http://fallout.wikia.com/wiki/Divergence), which demarcates the critical point at which our history divides with the Fallout universe, as the invention of the transistor.
Some of the late '70s tech that the Voyagers employed was digital and necessarily so. The fragility and power consumption of vacuum tubes is too great to achieve what we've come to expect from modern space probes. In Fallout:
>
> Miniaturized electronic capacity was never developed past [American society's] prime. This is why small television, radio, newspapers and even word of mouth are still prevalent. ([reddit](https://www.reddit.com/r/falloutlore/comments/2eysug/why_wasnt_the_transistor_invented_in_1947/))
>
>
>
Even the Apollo Program rockets used integrated circuits; tubes were almost nonexistent on-board them. Be that as it may, man *did* land on the moon in the Fallout universe, and the Great War of 2077 left many years leading up to itself in which we *probably* began exploring the cosmos.
---
*All your histories are belong to us now*.
Of noticeable lack are basically all [**Soviet accomplishments**](https://en.wikipedia.org/wiki/Soviet_space_program) (Wiki), which were [exemplary in the real world](https://space.stackexchange.com/questions/14645/why-was-venus-rather-than-mars-targeted-for-the-first-interplanetary-landings/14659#14659). Here (below) we have evidence of a possible re-write of history as apposed to a divergence. To the victor may have gone the spoils:
>
> [Defiance 7](http://fallout.wikia.com/wiki/Defiance_7) was the space capsule in which Captain Carl Bell of the United States Space Administration (USSA) made his historic flight, becoming the first human in space, on May 5, 1961. This claim was disputed by both the Soviet Union and China. Captain Bell's flight lasted twelve minutes and seven seconds, and made a full revolution around the Earth. Bell died when the capsule crashed on its return to Earth.
>
>
> Notes
>
> It is not possible to complete an orbit of the Earth in a "coasting" spacecraft in less than 89 minutes. Most likely this is a minor writing error; otherwise, an implausibly complex explanation would be required. It should also be noted that the 1950s-esque science of the Fallout universe differs from the actual physics of our universe, so this is another explanation. It is also entirely plausible that the US government lied about this "accomplishment", and the error was in fact a subtle hint towards this fact.
>
>
>
[Carl Bell](http://fallout.wikia.com/wiki/Carl_Bell), Note:
>
> In the real world, May 5, 1961 was the date of the flight of the first American in space, Alan Shepard. Unlike the Fallout universe, the actual first man in space was Soviet cosmonaut Yuri Gagarin, who became the first person to orbit the Earth on April 12, 1961.
>
>
>
Maybe the moon landings were faked after all; the Russians beat us to it.
All links are in-site or from [fallout.wikia.com](http://fallout.wikia.com/wiki/Fallout_Wiki) unless noted. |
45,804,686 | Given a variable number of strings, I'd like to one-hot encode them as in the following example:
```
s1 = 'awaken my love'
s2 = 'awaken the beast'
s3 = 'wake beast love'
# desired result - NumPy array
array([[ 1., 1., 1., 0., 0., 0.],
[ 1., 0., 0., 1., 1., 0.],
[ 0., 0., 1., 0., 1., 1.]])
```
Current code:
```
def uniquewords(*args):
"""Create order-preserved string with unique words between *args"""
allwords = ' '.join(args).split()
return ' '.join(sorted(set(allwords), key=allwords.index)).split()
def encode(*args):
"""One-hot encode the given input strings"""
unique = uniquewords(*args)
feature_vectors = np.zeros((len(args), len(unique)))
for vec, s in zip(feature_vectors, args):
for num, word in enumerate(unique):
vec[num] = word in s
return feature_vectors
```
The issue is in this line:
```
vec[num] = word in s
```
Which picks up, for instance, `'wake' in 'awaken my love'` as `True` (rightly so, but not for my needs) and gives the following, slightly-off result:
```
print(encode(s1, s2, s3))
[[ 1. 1. 1. 0. 0. 1.]
[ 1. 0. 0. 1. 1. 1.]
[ 0. 0. 1. 0. 1. 1.]]
```
I've seen [a solution](https://stackoverflow.com/questions/4154961/find-substring-in-string-but-only-if-whole-words) using `re` but am not sure how to apply here. How can I correct the one-liner above? (Getting rid of the nested loop would be nice too, but I'm not asking for general code editing unless it's kindly offered.) | 2017/08/21 | [
"https://Stackoverflow.com/questions/45804686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7954504/"
] | If you do a slight refactoring so that you treat each sentence as a list of words thoughout, it removes a lot of the `split`ting and `join`ing you're having to do, and naturalises the behaviour of `word in s` a bit. However, a `set` is preferred for membership testing, as it can do this in `O(1)`, and you should only construct one per argument iterated over, so your code would result in this:
```
import numpy as np
import itertools
def uniquewords(*args):
"""Create order-preserved string with unique words between *args"""
allwords = list(itertools.chain(*args))
return sorted(set(allwords), key=allwords.index)
def encode(*args):
"""One-hot encode the given input strings"""
args_with_words = [arg.split() for arg in args]
unique = uniquewords(*args_with_words)
feature_vectors = np.zeros((len(args), len(unique)))
for vec, s in zip(feature_vectors, args_with_words):
s_set = set(s)
for num, word in enumerate(unique):
vec[num] = word in s_set
return feature_vectors
print encode("awaken my love", "awaken the beast", "wake beast love")
```
with the correct output of
```
[[ 1. 1. 1. 0. 0. 0.]
[ 1. 0. 0. 1. 1. 0.]
[ 0. 0. 1. 0. 1. 1.]]
```
Once you've done this, you might realise you don't really need membership testing at all, and you can just iterate over s, only bothering with words that need to be set to `1`. This approach may be significantly faster over larger datasets.
```
import numpy as np
import itertools
def uniquewords(*args):
"""Dictionary of words to their indices in the matrix"""
words = {}
n = 0
for word in itertools.chain(*args):
if word not in words:
words[word] = n
n += 1
return words
def encode(*args):
"""One-hot encode the given input strings"""
args_with_words = [arg.split() for arg in args]
unique = uniquewords(*args_with_words)
feature_vectors = np.zeros((len(args), len(unique)))
for vec, s in zip(feature_vectors, args_with_words):
for word in s:
vec[unique[word]] = 1
return feature_vectors
print encode("awaken my love", "awaken the beast", "wake beast love")
``` |
5,183,807 | I have this code in my view page.
```
<td>
Mandate Name:
</td>
<td>
<%= Html.TextBox("MandateName")%>
</td>
```
I wrote MVC2 Validation for this name.
something like this.
```
//[Validator(typeof(MandateValidator))]
[MetadataType(typeof(Mandate_Metadata))]
public partial class Mandate {
public class Mandate_Metadata
{
[StringLength(250, ErrorMessage = "Mandate name cannot exceed 250 characters!")]
[Required(ErrorMessage = "Mandate Name Required!")]
public string MandateName { get; set; }
[StringLength(3000, ErrorMessage = "Description cannot exceed 3000 characters!")]
public string MandateDescription { get; set; }
}
}
```
but some how my validation is not working on this field could any body help me what's wrong I am doing here?
thanks | 2011/03/03 | [
"https://Stackoverflow.com/questions/5183807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268349/"
] | do you have anything like
```
<%= Html.ValidationMessageFor(model => model.MandateName)%>
```
in your view?
Check out SottGu's [post on Model Validation](http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx) with mvc2. |
13,841,212 | I have working web service. I had to use same code and develop REST web service. I have done it. When I was debugging it I found one unusual thing. Static constructors are not being called when I am debugging my `RESTWebService` project.
All business logic is inside one DLL. Both `WebService` and `RESTWebService` projects use this DLL. Following are those static constructor which are present inside DLL. These constructors initialize some static values.
```
//Logger.cs
static Logger()
{
try
{
m_LogLevel = ....;
m_LogFilePath = ....;
}
catch
{
throw;
}
}
//Common.cs
static Common()
{
ERROR_CODES = ....;
DB_CONNECTION_STRING = ....;
DB_NOTIFICATION_CONNECTION_STRING = ....;
DATA_PROVIDER_INVARIANT_NAME = ....;
}
```
All values initialized in constructor are declared as static.
In case of `WebService` project it is initializing all static variables through static constructor. I have verified it by keeping break point to this static constructor. It will hit all static constructor and in the end public constructor of my web service.
But this is not happening in case of `RESTWebService`. All environment is exactly like my `WebService`. But it does not hit static constructor's break point and directly hits `RestWebService`'s public constructor.
What would be the reason behind this? I am new to WCF. Is there any other thing with RESTWebService? | 2012/12/12 | [
"https://Stackoverflow.com/questions/13841212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1099228/"
] | Don't check if it was called via a breakpoint - instead, when an instance/service mthod is called, check if the values are actually initialized. Or try to log something from the static constructor and see if it was called.
The static constructor may be called before you have a chance to debug/break on it. |
523,140 | [1] Total number of 3-digit numbers which do not contain more than 2 different digits.
[2] Total number of 5-digit numbers which do not contain more than 3 different digits.
$\underline{\bf{My\; Try}}::$ I have formed different cases.
$\bullet$ If all digits are different, like in the form $aaa$, where $a\in \{1,2,3,.....,9\}$
$\bullet$ If all digits are different, like in the form $aba$ , where $a\in \{1,2,3,4,....,9\}$
$\bullet$ If one digit is zero and the other is non-zero, like $a00$ or $aa0$, where $a\in \{1,2,3,4,....,9\}$
But I do not understand how I can get a solution.
Please explain it to me. | 2013/10/12 | [
"https://math.stackexchange.com/questions/523140",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/14311/"
] | The fact that a $3$-digit number, by most definitions, cannot begin with $0$ complicates the analysis.
The case where there is only one digit is easy, there are $9$ possibilities.
We now count the $3$-digit numbers which have $2$ different digit.
There are two subcases (i) $0$ is one of the digits, and (ii) all the digits are non-zero.
**Case (i):** There are $9$ choices for the other digit. For each such choice, either we have two $0$'s ($1$ number) or one zero. If we have one $0$, it can be out in one of $2$ places. That gives a total of $(9)(3)$.
**Case (ii):** There are $9$ choices for the first digit. We can either choose to use it twice, in which case we have $2$ choices of where to put the second occurrence, or use it once. The other digit can be chosen in $8$ ways, for a total of $(9)(3)(8)$.
Add up. We get $252$.
**Another way:** There are $(9)(10)(10)$ $3$-digit numbers. There are $(9)(9)(8)$ with digits all different. Subtract. We get $252$.
We leave the more complicated $5$-digit question to you. It is slightly simpler to take more or less the second approach. It is easy to count the $5$-digit numbers, and also the $5$-digit numbers where the digits are all different. Some elements of the first approach will have to be borrowed to deal with the case exactly $4$ distinct digits. |
37,484,134 | I have this table structure, where all the columns have a different click method to them. The first column is not so wide, so it's pretty hard to click on it in a mobile browser, but i want to keep it like that, because of the borders.
Is there a way, where the clickable area of the first column could overlap invisibly the second column?
Here's a picture where I try to show what I'm trying to achieve :
[![enter image description here](https://i.stack.imgur.com/X6IJa.png)](https://i.stack.imgur.com/X6IJa.png)
Here is the HTML (note i'm using special row and column elements because of the onsen UI i'm wrapping my application in)
```
<ons-row>
<ons-col class="firstcolumn" width="32px">
<div class="item-thum" style="width:60px;" ng-click="confirm(item, item.id)">
<div style="overflow-x: hidden; overflow-y: hidden; padding-left: 3px;">
<ons-icon size="30px" icon="ok"></ons-icon>
</div>
</div>
</ons-col>
<ons-col ng-click="Details(item, item.id)" class="secondcolumn">
<div class="titlediv">
<header>
<span class="item-title">{{item.name}}</span>
</header>
</div>
</ons-col>
</ons-row>
```
You can see that in my current code the **col2** has an click event handler which always fires if i click anywhere near the second column. | 2016/05/27 | [
"https://Stackoverflow.com/questions/37484134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3609107/"
] | The first thing that comes to mind is to:
1. Give the first col a greater z-index then the second col
```
.firstcolumn{
z-index : 2;
}
.secondcolumn{
z-index : 1;
}
```
2. Extend the padding-right of col1 to cover the bit of col2 you want to be clickable for col1.
I think that's most of the work you would have to do, let me know how it goes.
EDIT: Point 2 might not be needed/appropriate as per the comments below. |
7,771,607 | I've already do my research but I think I don't know how to ask so I'll try to explain...
Im looking for a way to ask for the first entry saved on a Scaffold...
Like
If I have in the table Products:
* Sweeter
* Pants
* Scarf
* Tennis
and I write `@first_prod = Products.first` (or something like that) on my model or in my view `<%= Products.each.first %>` (or something like that) Rails give me the first prouduct in this case - Sweeter...
Thanks in advance... | 2011/10/14 | [
"https://Stackoverflow.com/questions/7771607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/992653/"
] | In rails you can define a few default ways to get the content from a model.
In your case i would create a scope.
in your model enter the following:
```
scope ordered, :order => "Product.created_at ASC"
```
When you call
```
Product.ordered
```
It will return all your products ordered by when they were created.
If you then want the very first product you just to
```
Product.ordered.first
```
In the case you just want to get the item in one specific place you could do the following (instead of what i mentioned above)
Product.find(:first, :order => 'created\_at ASC')
If my explanation is not clear, just let me know and i'll try to refrase |
16,308,375 | I'm writing a simple MVC4 application in which I chose the internet application template when I created the project. When I right click **\_Layout.cshtml** and go to **view in page inspector**, I receive a screen in the page inspector view that says
>
> "Server Error in '/' Application.
> ---------------------------------
>
>
> The resource cannot be found.
> Description: HTTP 404. The resource you are looking for (or one of its dependencies) > > could have been removed, had its name changed, or is temporarily unavailable. Please > review the following URL and make sure that it is spelled correctly.
>
>
> **Requested URL: /Shared/\_Layout**
>
>
>
>
> ---
>
>
> Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18034
>
>
>
However, the **\_layout.cshtml** shows up fine when launching debug mode for the solution. Also, the other cshtml pages are showing up fine in page inspector mode.
Views/\_ViewStart.cshtml
------------------------
**Browse to URL property**: ~/Views/\_ViewStart.cshtml
```
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
```
Views/Shared/\_Layout.cshtml
----------------------------
**Browse to URL property**: ~/Views/Shared/\_Layout
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title - Movie App</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">@Html.ActionLink("MVC Movie", "Index", "Home")</p>
</div>
<div class="float-right">
<section id="login">
@Html.Partial("_LoginPartial")
</section>
<nav>
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</nav>
</div>
</div>
</header>
<div id="body">
@RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
@RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© @DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
```
If you need more information to help solve this problem, please ask and I'll post it. | 2013/04/30 | [
"https://Stackoverflow.com/questions/16308375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1691849/"
] | Okay, I still stand by my comment that it is not meant to view the layout file as a standalone piece. However, I was a little curious as to the issue of viewing the layout.
If you look at the provided link, you will see how to properly use the Page Inspector. Please look at item number 5. That will give you some details on how to view pieces of your \_layout file.
<http://www.asp.net/mvc/tutorials/mvc-4/using-page-inspector-in-aspnet-mvc> |
1,520,231 | I am trying to integrate a calendar plugin like google calendar with custom database and code with asp.net MVC in C#.
It needs to handle Day/Week/Month Events in the Calendar as like google calendar.
I found the similar plugin in jquery <http://www.webappers.com/2009/08/04/jquery-weekly-calendar-plugin-inspired-by-google-calendar/>. But it shows only the Week
Do anyone have a reference to this? Please suggest | 2009/10/05 | [
"https://Stackoverflow.com/questions/1520231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111435/"
] | I'd try [FullCalendar](http://arshaw.com/fullcalendar/) |
41,282,587 | I have a 2-dimensional lattice (L\*L) with fixed boundaries and considering N-S-W-E sites as 4 neighbours to each site. Each site is assigned an float value. For each site I am calculating average of values of its neighbouring sites added to its own value. I want to solve this using convolv2d from scipy.signal. Following is my code:
```
# xi_out = constant1*xi + constant2*(sum of xi's neighbours)/no_of_xi's_neighbours
import numpy as np
from scipy.signal import convolve2d
L = 6 # each side of 2D lattice
a, b = (0.1, 0.5) # two constants
arr = np.random.rand(L, L) # example 2D array
# (3,3) window representing 4 neighbours which slides over 'arr'
kernel = np.array([[0, b, 0],
[b, a, b],
[0, b, 0]])
neighbors_sum = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0)
print(neighbors_sum)
```
I can not find a way to divide sum of neighbouring values for each site by number of its neighbours.
In following manner I can find number of neighbours for each site but do not know how to incorporate these values into 'result'. Can somebody suggest me how can I achieve that or is there a simpler in-built method in convolve2d to do that ?
```
arr = np.ones((L,L), dtype=np.int)
kernel = np.array([[0, 1, 0],
[1, 0, 1],
[0, 1, 0]])
neighbors_count = convolve2d(arr, kernel, mode='same', boundary='fill', fillvalue=0)
print(neighbors_count)
``` | 2016/12/22 | [
"https://Stackoverflow.com/questions/41282587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7245071/"
] | Try this to understand your response structure.
```
$.getJSON("myjasonfile.json", function(json) {
console.log(json); // access the response object
console.log(json.data); // access the array
console.log(json.data[0]); // access the first object of the array
console.log(json.data[0].number); // access the first object proprty of the array
});
``` |
51,487 | I have a document library containing a lot of personal information. Originally only admins could see the library but now it has been decided that users need to see their own information. Admins have Full Control and users have Read. The default view shows only documents where the user's name appears in a certain field. So Default View, Name="[Me]" so they can only see their own files. This works fine but it doesn't stop users from opening the library in Explorer view. How can I stop them doing this?
Any suggestions?
Note: I do not have access to Central Administration | 2012/11/13 | [
"https://sharepoint.stackexchange.com/questions/51487",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/7433/"
] | ^ Disregard the first, I think I misread your question. The answer in this link may help you instead: <http://social.msdn.microsoft.com/Forums/gu-IN/sharepoint2010customization/thread/5faea89f-f3ea-4b4b-b4c0-2c0cc7e6ceee> |
1,266,731 | I moved to Kubuntu 20.04 recently.Two days ago I installed pyenv and using pyenv i installed python(3.6.8) then I looked for available python versions from pyenv using this command.
```
samip@samip-Inspiron-3521:~$ pyenv versions
3.6.8
```
But it only showed me this recently installed version but my system has python 3.8.2 installed but anyway i used the 3.6.8 as global version using this command
```
samip@samip-Inspiron-3521:~$ pyenv global 3.6.8
```
But now i cannot switch back to system version.
```
samip@samip-Inspiron-3521:~$ pyenv global system
pyenv: system version not found in PATH
```
I am new to linux and programming please give me step-by-step solution.
```
samip@samip-Inspiron-3521:~$ echo $PATH
/home/samip/.pyenv/plugins/pyenv-virtualenv/shims:/home/samip/.pyenv/shims:/home/samip/.pyenv/bin:/home/samip/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
``` | 2020/08/13 | [
"https://askubuntu.com/questions/1266731",
"https://askubuntu.com",
"https://askubuntu.com/users/1116117/"
] | The problem on a fresh Kubuntu 20.04 installation is that there is no python executable. The `/usr/bin` only has `python2` and `python3` but pyenv checks for `python` to determine if a system version is available.
As a workaround create a python executable yourself:
```
ln -s /usr/bin/python3 /usr/bin/python
``` |
24,762,520 | We have the demo [here](http://angular-ui.github.io/ui-utils/#/mask) on the angular-ui page.
Wondering how we can write a mask with optional extension number.
`(999) 999-9999 ext. 999` will make the extension required. | 2014/07/15 | [
"https://Stackoverflow.com/questions/24762520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/863637/"
] | I shared this same problem with you. There is a completely undocumented optional character feature for this component. I could only find it by reading the source code.
The solution for your mask would be:
```
(999) 999-9999 ext. ?9?9?9
```
Question marks in your mask will flag the next character as optional. Trust me, it works.
Sorry for taking so long to answer. |
84,796 | I seem to be asking questions that often belong to other overflow sites.
Where can I browse the list of current overflow sites so I can choose one where to ask the question? | 2011/03/25 | [
"https://meta.stackexchange.com/questions/84796",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/159333/"
] | Look up and left in this page. There you will see the Stack Exchange™ MultiCollider SuperDropdown™. Second tab is what you want.
Or hop on over to <http://stackexchange.com> and check the [Sites tab](https://stackexchange.com/sites).
The page footer also lists all sites which have been officially launched. |
1,956,757 | How can I replace the last two matched string
`string s= "{\"test\":\"value\"}";`
From this string "s" I need to remove the double quotes of the value.
But I need generic, like the value may be any string in feature.
I need this to be done in `C#`. | 2009/12/24 | [
"https://Stackoverflow.com/questions/1956757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/171365/"
] | This [example](http://answers.oreilly.com/topic/340-how-to-quickly-find-the-last-match-in-a-string-in-c/) shows how to search a string using regex from right to left. You might find it of use. |
1,228,440 | I am having trouble writing a typeof statement which would be using a variable from a config file the code is like this
```
Type t = new typeof ("My.other.class" + configValue[0]);
```
configValue being the dynamic value I get from the app.config file.
The error I get is "type expected" it is fine if I type out the class directly so I am assuming my formatting is incorrect. How should this be written? | 2009/08/04 | [
"https://Stackoverflow.com/questions/1228440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/88765/"
] | The `typeof` keyword is for compile-time use. Use the [`Type.GetType(string)`](http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx) API instead. |
45,797,025 | This is my database table:
[![Database table](https://i.stack.imgur.com/fXsjl.jpg)](https://i.stack.imgur.com/fXsjl.jpg)
I want to display this table (5 columns) on my page when clicking a button (List Users).
But I'm getting the following as output:
[![Output table](https://i.stack.imgur.com/vMaLQ.jpg)](https://i.stack.imgur.com/vMaLQ.jpg)
My code is:
```
<?php
$db = "*"; //masked for security
$host = "*"; //masked for security
$user = "*";//masked for security
$pwd = "*; //masked for security
$con = mysqli_connect($host,$user,$pwd,$db);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT login_id,user_name,password,user_role,status_id FROM login";
$select = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($select);
echo "Number of rows : ";
echo $num_rows;
$row = mysqli_fetch_array($select, MYSQLI_ASSOC);
echo "<table>
<tr>
<th>Login ID</th>
<th>User name</th>
<th>Password</th>
<th>User Role</th>
<th>Status ID</th>
</tr>";
foreach ($row as $rows)
{
echo "<tr>";
echo "<td>" . $rows['login_id'] . "</td>";
echo "<td>" . $rows['user_name'] . "</td>";
echo "<td>" . $rows['password'] . "</td>";
echo "<td>" . $rows['user_role'] . "</td>";
echo "<td>" . $rows['status_id'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
```
Please help me find the error in this code. | 2017/08/21 | [
"https://Stackoverflow.com/questions/45797025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1745446/"
] | I've reached out to Fabric support and got an answer:
>
> The Latest Releases page shows all builds that have been used by at
> least 10% of your Daily Active Users (DAU) on any single day in the
> past 30 days or at least 4% of DAU on the current day. What's likely
> happening is that 3.5.9 isn't hitting the criteria just yet.
>
>
> As a workaround, if you manually add the version and build to the URL
> i.e. ".../dashboard/latest\_release/launch\_status?build=3.5.9" you can
> see the latest release information for that build.
>
>
> |
25,962,690 | I created a Simple Setup Project by using Windows Form Application with C# that doing only insert Data in Database.
My Database is in Ms Access.First i try to install it on my own Computer it works great, it install all drive in any location and work properly.
In my other computer there are 4 Drive C,D,E,F.
The problem is that when i install it to my other Computer it install in all Drive(C,D,E,F) and run also but when it install on C Drive it Install Successfully, Run Successfully but when I Click on Insert Button it gives me Error and the full Error is that :
```
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.Data.OleDb.OleDbException (0x80004005): Operation must use an
updateable query.
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult
hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior
behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior
behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at Management.Form1.button1_Click(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32
msg, IntPtr wparam, IntPtr lparam)
************** Loaded Assemblies **************
mscorlib
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.34014 built by: FX45W81RTMGDR
CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
Management
Assembly Version: 1.0.0.0
Win32 Version: 1.0.0.0
CodeBase: file:///C:/Program%20Files/Vikram%20Manufacture/Access%20Product/Management.exe
----------------------------------------
System.Windows.Forms
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.33440 built by: FX45W81RTMREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.33440 built by: FX45W81RTMREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.34003 built by: FX45W81RTMGDR
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Configuration
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.33440 built by: FX45W81RTMREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Data
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.33440 built by: FX45W81RTMREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.Data/v4.0_4.0.0.0__b77a5c561934e089/System.Data.dll
----------------------------------------
System.Core
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.33440 built by: FX45W81RTMREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------
System.Xml
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.33440 built by: FX45W81RTMREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
System.Transactions
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.33440 built by: FX45W81RTMREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.Transactions/v4.0_4.0.0.0__b77a5c561934e089/System.Transactions.dll
----------------------------------------
System.EnterpriseServices
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.33440 built by: FX45W81RTMREL
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.EnterpriseServices/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.EnterpriseServices.dll
----------------------------------------
************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.
For example:
<configuration>
<system.windows.forms jitDebugging="true" />
</configuration>
When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.
```
I am using Visual Studio 2010 , Windows Form Application C# , Database MS Access 2013. | 2014/09/21 | [
"https://Stackoverflow.com/questions/25962690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834541/"
] | It's difficult to pinpoint the exact reason why your application raises this exception, but a few common pointers that might help you.
The exception is raised when you are using a class in your code that isn't available when it runs. In this case, it seems you are unable to use org.apache.http.protocol.HttpContext. Most likely, you created an application that does include the Amazon AWS jar, but lacks the Apache HTTPClient jar.
If you used gradle/maven to create your application, include it in your dependencies. It it's a plain Java program, ensure the required JARs are available in your classpath (e.g. the same place as you currently have the Amazon jar located). |
6,529,505 | I have a class that extends Activity and implements ViewFactory.
I have found some tutorials and code examples that show how to setup a [textSwitcher](http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/TextSwitcher1.html) and [imageSwitcher](http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/ImageSwitcher1.html).
With both examples you have to create:
```
public View makeView() {
return x;
}
```
Where x is either the textView or ImageView.
Here is an example of what I tried to use:
```
@Override
public View makeView() {
ImageView iView = new ImageView(this);
iView.setScaleType(ImageView.ScaleType.FIT_CENTER);
iView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
iView.setBackgroundColor(0xFFFFFFFF);
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return iView;
}
```
I can only return one of the views so I get a forced close when I try to run it with a textSwitcher called.
Any ideas? Is there a better way to do this?
Thank you,
Neil | 2011/06/30 | [
"https://Stackoverflow.com/questions/6529505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/756623/"
] | As Stéphane stated before me, create an inner class implementing ViewFactory
```
public class TextSwitcherFactory implements ViewFactory
{
@Override
public View makeView() {
TextView t = new TextView(Latest.this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
}
```
Then when calling the TextSwitcher from xml and setting the factory, instead of `mSwitcher.setFactory(this);`, use `mSwitcher.setFactory(new TextSwitcherFactory());`
e.g.
```
mSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher1);
mSwitcher.setFactory(new TextSwitcherFactory());
``` |
194,987 | You are given a matrix of forward and back slashes, for instance:
```
//\\
\//\
//\/
```
A slash cuts along the diagonal of its cell corner-to-corner, splitting it in two pieces.
Pieces from adjacent (horizontally or vertically) cells are glued together.
Your task is to count the number of resulting pieces. For the same example, the pieces are easier to see in this illustration - 8 of them:
[![enter image description here](https://i.stack.imgur.com/XKYpq.png)](https://i.stack.imgur.com/XKYpq.png)
Write a function or a complete program. Input is a non-empty matrix in any convenient form. You may choose any pair of values (characters or numbers) to represent `/` and `\`; in the tests below we use 0=`/` and 1=`\`. Loopholes forbidden. Shortest wins.
```
in:
[[0,0,1,1],
[1,0,0,1],
[0,0,1,0]]
out:
8
in:
[[1]]
out:
2
in:
[[1,0],
[1,1],
[0,1],
[0,0]]
out:
6
in:
[[1,0,1,1,0,1,0,0,0,1,1,1],
[1,0,1,0,1,1,1,1,1,1,1,0],
[1,1,1,0,1,1,0,1,1,1,1,0],
[0,1,0,1,0,1,0,0,1,0,1,1],
[1,1,1,1,0,0,1,1,1,0,0,1]]
out:
19
in:
[[1,0,1,1,0,1,0,0,0,1,1,1,1,0,1,0,1],
[1,1,1,1,1,1,0,1,1,1,0,1,1,0,1,1,1],
[1,0,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1],
[1,0,0,1,1,1,0,0,1,0,0,1,0,1,1,1,1],
[0,1,0,0,0,0,1,0,1,0,0,1,0,1,1,1,1],
[0,1,0,0,1,0,0,0,1,0,1,0,0,1,1,1,0],
[0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,1,0]]
out:
27
in:
[[0,1,1,1,1,1,1,1,0,0,1,0,1,0,0,0,0],
[1,1,1,0,0,0,1,1,1,1,1,0,1,1,0,1,0],
[1,0,0,1,1,1,0,0,0,1,0,1,0,0,1,1,1],
[0,0,0,1,1,0,1,0,0,0,1,1,0,1,1,1,0],
[1,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,0],
[0,1,0,1,0,0,0,1,0,1,0,1,0,1,1,0,0],
[0,1,1,1,0,0,1,0,1,0,0,0,0,1,1,1,1]]
out:
32
``` | 2019/10/28 | [
"https://codegolf.stackexchange.com/questions/194987",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/24908/"
] | [MATL](https://github.com/lmendo/MATL), 21 bytes
================================================
```
3XytPJ*-X*Xj~4&1ZIunq
```
The input is a matrix with `1` for `\` and `j` (imaginary unit) for `/`.
[Try it online!](https://tio.run/##y00syfn/3ziisiTAS0s3Qisiq85EzTDKszSv8P//6CydLB1DHUNrBUMdMNNaASKSFQsA) Or [verify all test cases](https://tio.run/##dVE9C8IwEN39FZ0cyjkcunV10cnBoVgKuj5UEOrg4l@PttfkcklKKYTc@8h797gNd3d12/YznI71pq1bfHdrvhzez5fbn10HAjFxUzFNx6aSG/SrjsefMM6mexnK5UgSIM0SXsQP9RMFillhAFIOlO0ZrOpyWnZXISXHdsY85C2ZpxCOxgbknw@jtQDhAiwqgRMjA/mnzko1OMQlg5Dlh9@DjZR5yf5LBcNuE4VSgmK817Tm2VpTZ0n80/sf).
With some extra code, you can [see the different pieces in random colours](https://matl.suever.net/?code=3XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0). Or [increase the resolution for a better looking result](https://matl.suever.net/?code=10XytPJ%2a-X%2aXj~4%261ZItunq7B~w3%26r%26v2ZG1YG&inputs=%5Bj%2C1%2C1%2C1%2C1%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%3B+1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%2C1%2Cj%2C1%2C1%2Cj%2C1%2Cj%3B+1%2Cj%2Cj%2C1%2C1%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2C1%2C1%2C1%3B+j%2Cj%2Cj%2C1%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2C1%2Cj%2C1%2C1%2C1%2Cj%3B+1%2C1%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%3B+j%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2C1%2Cj%2C1%2C1%2Cj%2Cj%3B+j%2C1%2C1%2C1%2Cj%2Cj%2C1%2Cj%2C1%2Cj%2Cj%2Cj%2Cj%2C1%2C1%2C1%2C1%5D&version=21.0.0).
Explanation
-----------
Consider input `[1,j; 1,1; j,1; j,j]` as an example. This corresponds to
```
\/
\\
/\
//
```
`3Xy` creates a 3×3 identity matrix:
```
1 0 0
0 1 0
0 0 1
```
`tP` pushes a copy of this matrix and flips it vertically. `J*` multiplies each entry by the imaginary unit, to give
```
0 0 j
0 j 0
j 0 0
```
`-` subtracts the two matrices:
```
1 0 -j
0 1-j 0
-j 0 1
```
`X*` takes the input matrix implicitly and computes the Kronecker product. This replaces each entry in the input matrix by its product with the above 3×3 matrix:
```
1 0 -j j 0 1
0 1-j 0 0 1+j 0
-j 0 1 1 0 j
1 0 -j 1 0 -j
0 1-j 0 0 1-j 0
-j 0 1 -j 0 1
j 0 1 1 0 -j
0 1+j 0 0 1-j 0
1 0 j -j 0 1
j 0 1 j 0 1
0 1+j 0 0 1+j 0
1 0 j 1 0 j
```
`Xj` takes the real part:
```
1 0 0 0 0 1
0 1 0 0 1 0
0 0 1 1 0 0
1 0 0 1 0 0
0 1 0 0 1 0
0 0 1 0 0 1
0 0 1 1 0 0
0 1 0 0 1 0
1 0 0 0 0 1
0 0 1 0 0 1
0 1 0 0 1 0
1 0 0 1 0 0
```
Note how the above matrix is a "pixelated" version of
```
\/
\\
/\
//
```
`~` applies logical negation, that is, swaps `0` and `1`:
```
0 1 1 1 1 0
1 0 1 1 0 1
1 1 0 0 1 1
0 1 1 0 1 1
1 0 1 1 0 1
1 1 0 1 1 0
1 1 0 0 1 1
1 0 1 1 0 1
0 1 1 1 1 0
1 1 0 1 1 0
1 0 1 1 0 1
0 1 1 0 1 1
```
`4&1ZI` specifies `4`-connectivity, and finds connected components considering `1` as foreground and `0` as background. The result is a matrix of labelled connected components, where each original `1` is replaced by an integer label:
```
0 3 3 3 3 0
1 0 3 3 0 5
1 1 0 0 5 5
0 1 1 0 5 5
2 0 1 1 0 5
2 2 0 1 1 0
2 2 0 0 1 1
2 0 4 4 0 1
0 4 4 4 4 0
4 4 0 4 4 0
4 0 4 4 0 6
0 4 4 0 6 6
```
`unq` computes the number of unique elements and subtracts `1`. This gives the number of components, which is implicitly displayed. |
9,329,114 | Does anyone know of a 'pluck' plugin that matches the underscore array method?
```
pluck_.pluck(list, propertyName)
```
A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.
```
var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]
```
Google is not helping me much today.
Any pointers much appreciated | 2012/02/17 | [
"https://Stackoverflow.com/questions/9329114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135687/"
] | You can do it with an expression;
```
var arr = $.map(stooges, function(o) { return o["name"]; })
``` |
28,914 | I have read Steven Pinker's Sense of Style, which is a great book.
In chapter 4, he talks about how to form lucid coherent sentences, and in chapter 5, called "Arcs of Coherence", he extends his analysis of coherence to relations between sentences within a paragraph (and also somewhat about coherence between subsequent paragraphs).
I think his analysis is truly brilliant, about how a text is not merely tree-like, because there are connections between sentences apart from the tree-like structure of chapter -> paragraph -> Sentence -> words. His analysis of how to make a paragraph coherent by connecting sentences in specific ways is truly very helpful.
Also he has a brilliant analysis (more in chapter 4) of how lucid prose is created by taking into account the effect that the order of words has on the memory of the reader.
However, he does not really extend this analysis to the level of chapters/pages. He does not really address the question of "how do we write entire chapters so as to make them coherent with each other". "How do we make connections between sentences in different sections/chapters, so as to make them coherent".
**So my question is: For people who have read Steven Pinker's chapter on Arcs of Coherence and found it as useful as I did, do you know any other writers who have similar insights, but about how to connect elements of a larger text, to make the larger structure of the text more coherent?** | 2017/06/26 | [
"https://writers.stackexchange.com/questions/28914",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/24575/"
] | It seems to me that what Pinker is describing at the sentence and paragraph level is substantially what most books on story are describing at the level of a document as a whole. Stories have a coherent shape and that shape has been mapped in various ways by different authors, but broadly the same shape underlies what all or most of them describe.
Coherence, the property of all the bits of a thing going together in a way that makes sense, is a fundamental property of writing at any scale. The ways in which coherence works, however, may be different at different scales. That is, how the pieces are connected and how long you have to connect the pieces up before you lose the reader may differ as you scale up or down.
Some of the most prominent books on the shape of stories are:
* *Story* by Robert McKee
* *The Writer's Journey* by Christopher Vogler
* *Aspects of the Novel* by EM Forster
But there are many such works, covering both fiction and non fiction. |
13,623,126 | I have a two variables:
```
boost::array my_boost_array_variable_1<float, 3>;
boost::array my_boost_array_variable_2<float, 3>;
```
now I want to call a C function with the following signature:
```
int MPI_Allreduce ( void *sendbuf, void *recvbuf, ...);
```
I want to pass the address of a particular element of my `my_boost_array_variable_1` and `my_boost_array_variable_2` as a first and second parameter of MPI\_Allreduce:
```
MPI_Allreduce(&my_boost_array_variable_1[2],
&my_boost_array_variable_2[2], ...
```
or should I rather do:
```
MPI_Allreduce(my_boost_array_variable_1.c_array() + 2,
my_boost_array_variable_2.c_array() + 2, ...
```
UPDATE:
The C functions expect a continuous chunk of data, that starts at void \*sendbuf. The question here if these two calls are correct in this regard. Does &my\_boost\_array\_variable\_1[2] point to the same location as my\_boost\_array\_variable\_1.c\_array() + 2 ? Are these calls equivalent? | 2012/11/29 | [
"https://Stackoverflow.com/questions/13623126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18775/"
] | For me first is more clear then second. But in reality i think they are equal. |
4,584 | This post is about Zephir's answer [here](https://physics.stackexchange.com/questions/16227/what-is-the-kinematics-of-a-particle-with-complex-mass/18678#18678). To quote him,
>
> **In AWT (dense aether model)** all particles have **complex mass terms due the quantum fluctuations.** A the case of **photons and neutrinos the complex mass becomes pronounced**. With respect to high density of atom nuclei the mesons are have complex mass too. These particles are doing **tachyonic "jumps"** in space-time and they undergo quantum decoherence and oscillations.
>
>
>
Note the bolded words.
1. The idea he is basing his claims on is "AWT", Aether Wave Theory, a non-mainstream idea. . If you check his profile, he is the one who started this non-mainstream busisness.
2. The post is clearly a promotion.
3. The logic is fully flawed, and non-mainstream.
So I flagged it (a long time back) as non-mainstream. However, the flag was declined (during my suspension, or just before, so I couldn't refute earlier.) saying that I was pointing out "technical innacuracies in the post".
What is this supposed to indicate? That the answer was mainstream? I would like an explanation for how advertising one's own non-mainstream ideas is mainstream, or acceptable? Does this mean that non-mainstream ideas in answers are acceptable? | 2013/07/16 | [
"https://physics.meta.stackexchange.com/questions/4584",
"https://physics.meta.stackexchange.com",
"https://physics.meta.stackexchange.com/users/23119/"
] | This makes sense, deleted.
I think this may have been during the period of time when a couple of members of this site (you included) were generating a lot of incorrect non-mainstream flags (about wrong posts, not non mainstream posts). Basically it was a "crying wolf" situation. At first glance this does indeed look like a "wrong" post if you don't know that AWT is non mainstream. I'm going through Zephir's profile now and checking for more such posts. |
4,757,392 | I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far:
```
function randStr($length) {
$result = null;
$replace = array('/', '+', '=');
while(!isset($result[$length-1])) {
$result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND)));
}
return substr($result, 0, $length);
}
```
Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not.
1. `mcrypt_create_iv` seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64\_encode effect on this kind of binary data, do I actually decrease entropy, when I base64\_encode it?
2. How does second parameter for `mcrypt_create_iv` affect my results? php.net manual states that `MCRYPT_RAND` is 'system random number generator'. Is it OS specific and if so, how good values are created? | 2011/01/21 | [
"https://Stackoverflow.com/questions/4757392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/294696/"
] | 1. base64\_encoding won't decrease entropy, it is just a different representation of the same data.
2. It is OS specific, but I think the random values created are good enough with this function. Under PHP 5.3 you have to seed the generator beforehand, it can be a problem if you use this code on different servers. |
18,471 | According to Catholic thought, if we are washed of Original Sin at the time of baptism, why do we transmit Original Sin to our children? In other words, how is it that my child is born with Original Sin when I was freed from Original Sin at the time of my baptism? | 2013/08/18 | [
"https://christianity.stackexchange.com/questions/18471",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/5459/"
] | I think you misunderstood the role of Baptism in Catholicism.
Cathecism of the Catholic Church-1263 says
>
> [1263] By Baptism all sins are **forgiven**, original sin and all personal
> sins, as well as all punishment for sin. In those who have been
> reborn nothing remains that would impede their entry into the Kingdom
> of God, neither Adam's sin, nor personal sin, nor the consequences of
> sin, the gravest of which is separation from God.
>
>
>
It doesn't say original sin is washed away, it says it is forgiven. Forgiven doesn't mean you don't have original sin anymore; it only means your sins are forgiven.
Our sins cannot be washed away by merely washing with water nor any kind of Baptism. Only the blood of Jesus Christ can wash away our sins.
>
> *1 John 1:7 (NIV)* But if we walk in the light, as he is in the light,
> we have fellowship with one another, and the **blood of Jesus**, his Son,
> **purifies us from all sin**.
>
>
> *Revelation 7:14 (NKJV)* And I said to him, “Sir, you know.” So he said
> to me, “These are the ones who come out of the great tribulation, and
> **washed their robes** and made them white **in the blood of the Lamb**.
>
>
> *Revelation 22:14 (DRA)* Blessed are they that **wash their robes in the
> blood of the Lamb**: that they may have a right to the tree of life, and
> may enter in by the gates into the city.
>
>
> |
26,061,764 | I'm trying to manage some event.
I've my main project, written in C#, and I've added another project, written in VB.NET.
In the VB.NET project, I've a class, raising an event:
```
Public Class newMessageArgs
Inherits EventArgs
Public Property messageCode As String
Public Property appName As String
End Class
Public Class EventRaiser
Event NewMessage As EventHandler
Sub MessageEvent(ByVal typeEvent As String, ByVal messageCode As String, appName As String)
If typeEvent = "newMessage" Then
Dim args As newMessageArgs = New newMessageArgs()
args.appName = appName
args.messageCode = messageCode
RaiseEvent NewMessage(Me, args)
End If
End Sub
End Class
```
The method raising the event, is called from my VB.NET code, but I have to handle it with my C# code. How can I do it?
This event isn't binded to any xaml element.
CODE UPDATED:
Trying to handle the event:
screenshot: <http://imgur.com/JmdA7YM>
```
attivazione.EventRaiser raiser = new attivazione.EventRaiser();
raiser.NewMessage += raiser_NewMessage; //error: "no overloads for raiser_NewMessage matches the delegate system.eventhandler", underlining red raiser_NewMessage
private void raiser_NewMessage(object sender, newMessageArgs e)
{
//handle your event here
}
```
Attivazione is the name of the class in VB.NET that raises the event. | 2014/09/26 | [
"https://Stackoverflow.com/questions/26061764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/819161/"
] | Are you intend something like this?
```
var raiser = new EventRaiser();
raiser.NewMessage += raiser_NewMessage;
private void raiser_NewMessage(object sender, EventArgs e)
{
//handle your event here
}
```
But `newMessageArgs` class and `NewMessage` event should be public in your VB code.
And of course, you should add reference to assembly with your VB code into C# project. |
11,369,040 | I need to return the actual text description of the db connection, and any other relevant info about the DB.
Why? I call a service and the expected data comes back perfectly.
Now, when I do the same call inside of a secure tunnel, I get completely different results.
All indications say that the code is working in both cases.
So, I can only imagine that it's hooking up to a different DB...
So...I would like to have the function return the server name and the actual db being queried against - even the path where the DB resides would be awesome! | 2012/07/06 | [
"https://Stackoverflow.com/questions/11369040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/777828/"
] | I hope I've understood correctly:
```
function test() {
var db = ScriptDb.getMyDb();
var result = db.query({id: 434})
var quals = result.next().qualifications;
var hasQual = false;
for (var i = 0; i < quals.length; i++) {
if (quals[i].name == 'QUAL1' && quals[i].issueDate > 20050101) {
hasQual = true;
break;
}
}
Logger.log(hasQual);
}
``` |
32,876,250 | I downloaded a Pycharm community mac OSX version. But after installation, each time I try to open it. It gives me this error. I can't find any information about this error after I google the error.
[![enter image description here](https://i.stack.imgur.com/QzNEO.png)](https://i.stack.imgur.com/QzNEO.png)
Thank you. | 2015/09/30 | [
"https://Stackoverflow.com/questions/32876250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1076975/"
] | OK. It turn out be a permission problem. Just chmod 777 the directory(mkdir before). Then this problem is solved |
56,100,559 | I've migrated to `androidx` and after a ton of time with it, I can't move away from the error below. I've integrated `multidex` but I still get the error.
This is the exception:
>
> FAILURE: Build failed with an exception.
>
>
>
>
What went wrong:
>
> Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForBetaDebug'.
> java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
>
>
>
I can't make it work. Here's my build.gradle. Any ideas?
```
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.+'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
repositories {
maven { url 'https://maven.fabric.io/public' }
}
android {
compileSdkVersion 28
buildToolsVersion '27.0.3'
signingConfigs {
releaseSign {
storeFile file("$rootProject.projectDir/keystore_release.jks")
storePassword 'xxxxxxx'
keyAlias 'xxxxxxx'
keyPassword 'xxxxxxx'
}
}
// Butterknife requires Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "com.xxxxxxx.xxxxxxx"
minSdkVersion 19
targetSdkVersion 28
versionCode 10
versionName "1.0.10"
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.releaseSign
}
}
flavorDimensions "default"
productFlavors {
beta {
applicationId "com.xxxxxxx.xxxxxxx.beta"
dimension "default"
resValue "string", "app_name", "xxxxxxx Beta"
buildConfigField "String", "BASE_URL", '"http://xxxxxxx.net"'
buildConfigField "Boolean", "IS_BETA", "true"
buildConfigField "String", "TENANT", '"xxxxxxx"'
}
production {
applicationId "com.xxxxxxx.driver"
dimension "default"
resValue "string", "app_name", "Driver"
buildConfigField "String", "BASE_URL", '"http://apxxxxxxx"'
buildConfigField "Boolean", "IS_BETA", "false"
buildConfigField "String", "TENANT", '"xxxxxxx"'
}
}
packagingOptions {
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/notice'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license'
exclude 'META-INF/license.txt'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha06'
implementation 'com.jakewharton:butterknife:10.1.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'me.grantland:autofittextview:0.2.1'
implementation 'com.android.volley:volley:1.1.1'
implementation 'org.greenrobot:eventbus:3.1.1'
implementation 'com.github.ybq:Android-SpinKit:1.2.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.crashlytics.sdk.android:crashlytics:2.10.0'
implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-messaging:18.0.0'
implementation 'androidx.multidex:multidex:2.0.1'
def work_version = "2.0.1"
implementation "androidx.work:work-runtime:$work_version"
// Optional - RxJava2 support
implementation "androidx.work:work-rxjava2:$work_version"
def futures_version = "1.0.0-beta01"
implementation "androidx.concurrent:concurrent-futures:$futures_version"
}
apply plugin: 'com.google.gms.google-services'
``` | 2019/05/12 | [
"https://Stackoverflow.com/questions/56100559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064171/"
] | This is a great question!
Your rectangle can be thought of as 4 lines:
```
(x, y) → (x+width, y) # top
(x+width, y) → (x+width, y+height) # right
(x, y+height) → (x+width, y+height) # bottom
(x, y) → (x, y+height) # left
```
Taking your intersecting line, it's possible to use the [two-lines intersecting formula](https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection) to determine if any of these lines intersect (but be careful of parallel lines!)
However the formula (specified in linked Wikipedia article) determines if the lines intersect anywhere on the 2D plane, so it needs to be further refined. Obviously the code can quickly throw away any intersections that occur outside the window dimensions.
Once the "infinite-plane" collision-point has been determined (which is a reasonably quick determination), then a more fine-grained intersection can be determined. Using [Bresenham's algorithm](https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm), enumerate all the points in the intersecting line, and compare them with a 1-pixel rectangle based on each side of your square. This will tell you which side of the rectangle intersected.
If you only need to know if the rectangle was hit, just check the whole rectangle with `pygame.Rect.collidepoint()` for each point in the line.
[![enter image description here](https://i.stack.imgur.com/47K0D.gif)](https://i.stack.imgur.com/47K0D.gif)
Of course once you have all those points generated, it's easily to not bother with the 2D line collision, but for long lines the code must make a lot of checks. So testing the 2D intersection first really speeds it up. |
42,504 | Ce [proverbe](http://www.linternaute.fr/proverbe/377/au-royaume-des-aveugles-les-borgnes-sont-rois/#:%7E:text=Au%20royaume%20des%20aveugles%2C%20les%20borgnes%20sont%20rois.%22&text=Entour%C3%A9%20de%20personnes%20ignorantes%20ou,intelligence%20passe%20pour%20un%20g%C3%A9nie.&text=Ce%20proverbe%20provient%20de%20la,par%20%C3%89rasme.) provient de la Grèce antique, et il est cité en français dès le XVIème s. par Érasme. Il signifie :
>
> Un médiocre paraît remarquable parmi des gens sans valeur ;
> il est facile pour un ignorant de briller parmi de plus ignorants que lui ;
> entouré de personnes ignorantes ou stupides, un individu doté d'un maigre savoir ou d'une maigre intelligence passe pour un génie ; etc.
>
>
>
Peut-on l'utiliser couramment ou son emploi est considéré non politiquement correct ?
>
> P.ex. : Dans une classe tous les élèves hormis un ont obtenu une note
> inférieure à 11 en maths. La meilleure note est 12 sur 20. Peut-on
> dire pour cet élève que "*au royaume des aveugles, le borgne est roi*"
> ?
>
>
> | 2020/07/08 | [
"https://french.stackexchange.com/questions/42504",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/16020/"
] | J’ai déjà entendu plusieurs fois cette expression et elle est pour moi toujours couramment utilisée, en tout cas comprise.
En revanche, elle est effectivement politiquement peu correcte. Pour cela, je ne la vois être utilisée que dans certains cas : car (1) elle dénote toujours un certain sarcasme et (2) relève plutôt d’un style littéraire.
Donc une manière de l’utiliser serait dans cet esprit :
>
> Dans une classe tous les élèves hormis un ont obtenu une note inférieure à 11 en maths. La meilleure note est 12 sur 20. X, qui a eu la meilleure note, est très heureux, même si sa note reste passable. Mais comme le proverbe le dit, **au royaume des aveugles, le borgne est roi**.
>
>
> |
8,228,047 | Well, I'm a linux newbie, and I'm having an issue with a simple bash script.
I've got a program that adds to a log file while it's running. Over time that log file gets huge. I'd like to create a startup script which will rename and move the log file before each run, effectively creating separate log files for each run of the program. Here's what I've got so far:
[pastebin](http://pastebin.com/mDVuSZ5k)
```
DATE=$(date +"%Y%m%d%H%M")
mv server.log logs/$DATE.log
echo program
```
When run, I see this:
```
: command not found
program
```
When I cd to the logs directory and run dir, I see this:
```
201111211437\r.log\r
```
What's going on? I'm assuming there's some syntax issue I'm missing, but I can't seem to figure it out.
---
UPDATE: Thanks to shellter's comment below, I've found the problem to be due to the fact that I'm editing the .sh file in Notepad++ in windows, and then sending via ftp to the server, where I run the file via ssh. After running dos2unix on the file, it works.
New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file? | 2011/11/22 | [
"https://Stackoverflow.com/questions/8228047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023673/"
] | ```
mv server.log logs/$(date -d "today" +"%Y%m%d%H%M").log
``` |
34,372,419 | I would like to make an ImageView ? AND WHEN i touch it it change background, when i drag finger far of it it become normal i don't know how to do, thanks
```
imgButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
cmp++;
txt2.setText(" " + cmp);
//Quant on touche l'image :
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
imgButton.getDrawable().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
}
// si Je bouge le dois sur l'image et ....
if (event.getActionMasked() == MotionEvent.ACTION_MOVE) {
//... et que le doit quitte l'image
if (event.getX() < 0 || event.getX() > v.getWidth() || event.getY() < 0 || event.getY() > v.getHeight()) {
imgButton.getDrawable().setColorFilter(0x00000001, PorterDuff.Mode.SRC_ATOP);
}
if (event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0 && event.getY() < v.getHeight()) {
// ... et que le doit revient vers L'image
imgButton.getDrawable().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
}
}
// Si je lève le doits et...
if (event.getActionMasked() == MotionEvent.ACTION_UP) {
// .... sur l'image :
if (event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0 && event.getY() < v.getHeight()) {
//Finger back to the view
imgButton.getDrawable().setColorFilter(0x00000001, PorterDuff.Mode.SRC_ATOP);
Intent i = new Intent(MainActivity.this, game.class);
startActivity(i);
}
}
return true;
}
});
``` | 2015/12/19 | [
"https://Stackoverflow.com/questions/34372419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872660/"
] | You could go with `serverVersion`. But as you can see in the picture, you still get `Glassfish V3.1` with Glassfish 4.1.
[![serverVersion screen](https://i.stack.imgur.com/WwqDv.png)](https://i.stack.imgur.com/WwqDv.png)
Now, `ApplicationServerFullVersion` will bring better results: `GlassFish Server Open Source Edition 4.1 (build 13)`
[![ApplicationServerFullVersion screen](https://i.stack.imgur.com/P0KNN.png)](https://i.stack.imgur.com/P0KNN.png) |
414,742 | In [J.J. Sakurai's](https://en.wikipedia.org/wiki/J._J._Sakurai) *[Modern Quantum Mechanics](https://en.wikipedia.org/wiki/J._J._Sakurai#Textbooks)*, the same operator $X$ acts on both, elements of the [ket](https://en.wikipedia.org/wiki/Bra%E2%80%93ket_notation#Ket_notation) space and the [bra](https://en.wikipedia.org/wiki/Bra%E2%80%93ket_notation) space to produce elements of the ket and bra space, respectively. Mathematically, an operator is simply a map between two spaces.
So, how can *the same operator* act on the ket as well as the bra space? | 2018/07/02 | [
"https://physics.stackexchange.com/questions/414742",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/170225/"
] | This is what computer scientists would call [(ad-hoc) polymorphic](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)) or “overloaded” functions: basically, an operator $X$ on the Hilbert space $\mathcal{H}$ is not just one function $X: \mathcal{H}\to\mathcal{H}$, but a family of two functions
$$
X = \{ X\_{\mathcal{H}}, \quad X\_{\mathcal{H}^\ast} \}
$$
with
$$
X\_{\mathcal{H}}: \mathcal{H}\to\mathcal{H}, \quad X\_{\mathcal{H}^\ast}: \mathcal{H}^\ast\to\mathcal{H}^\ast
$$
Since a Hilbert space's dual space (the “space of bra-vectors”) is a different space from $\mathcal{H}$ itself, it's always unambiguous which of the two functions you mean when applying $X$ to either a ket or a bra.
And the definition of $X\_{\mathcal{H}^\ast}$ follows directly from the one of $X\_{\mathcal{H}}$ vice versa. This is easy to see in one direction:
$$
\bigl(X\_{\mathcal{H}^\ast}(\langle f|)\bigr)(|v\rangle) = \langle f| \bigl(X\_\mathcal{H}(|v\rangle)\bigr)
$$
In the other direction, we need to invoke the [Riesz representation theorem](https://en.wikipedia.org/wiki/Riesz_representation_theorem): for any $|v\rangle \in \mathcal{H}$, let
$$\begin{align}
\langle X\_v^\ast| & \in\mathcal{H}^\ast
\\ \langle X\_v^\ast| &:= X\_{\mathcal{H}^\ast}\bigl(\langle . , v\rangle\bigr).
\end{align}$$
where by $\langle . , v\rangle$ I mean the function
$$\begin{align}
v^\ast & \in \mathcal{H}^\ast
\\ v^\ast(w) & := \langle w,v\rangle
\end{align}$$
(This is now *not* an application of dual-vectors, but the actual scalar product that comes with the Hilbert space!)
Then Riesz tells us that this corresponds to one unique element $X\_v\in\mathcal{H}$, so we can define
$$
X\_{\mathcal H}(|v\rangle) := X\_v.
$$
And because physicists are lazy (good trait, although some overdo it), they avoid all the “obvious” parentheses etc., and just assume the reader will know how the operator needs to be applied, which space it lives in, etc.. Swapping between a bra- and a ket-version of a state implicitly always invokes the Riesz representation theorem, but this is seldom talked about. |
19,440,525 | I have a bean whose business logic loads beans of a certain type from the ApplicationContext in order to process them.
For my jUnit tests, I would like to create some dummy beans within my unit test class and see if my bean under test properly processes them. However, I am not sure what the best way to accomplish this is.
If I just declare my inner class within my test class, Spring will not have it as part of its application context. I realize that I could inject my application context within my jUnit class, and then use appContext.registerPrototype() to add it, however, I thought there might be a cleaner way using annotations.
I've tried to annotate the internal class with @Component, but not surprisingly, it did not work.
```
public class PatchEngineTest extends TestBase {
@Component
protected class Patch1 extends PatchBaseImpl implements Patch{
public void applyPatch() throws Exception {
// does nothing
}
}
@Autowired PatchRepository patchRepository;
@Autowired Patch1 patch1;
@Test
public void test() {
fail("Not yet implemented");
}
}
```
Not surprisingly, I get the following error message:
```
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ia.patch.PatchEngineTest$Patch1] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
```
Is there any way of doing this? | 2013/10/18 | [
"https://Stackoverflow.com/questions/19440525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827480/"
] | You need to make your inner class `static`; Spring can't instantiate a non-`static` inner class as a bean. If there really is a valid reason why it needs to be non-`static`, you could create it manually in an `@Bean` method. |
724,698 | I have genuine windows 10 in my lappy. I tried to dual boot with Ubuntu but accidentally I replaced my windows with ubuntu. So now I have only ubuntu in my pc and I lost my genuine windows. How to get back my windows OS.I dont even have my back up image of my windows | 2016/01/23 | [
"https://askubuntu.com/questions/724698",
"https://askubuntu.com",
"https://askubuntu.com/users/496793/"
] | If you really deleted the Windows partition, Ubuntu is not going to get it back for you. Sorry.
Not knowing if this computer originally came with Windows 10, I will make the assumption it's fairly new and did. You could post more info per <https://askubuntu.com/help/how-to-ask> :>)
When you start there should be a recovery partition. Look for the option to choose a boot device, perhaps F12, hold that key down and see if a recovery partition is a choice for bootup. Some computers hide this info at the start, and it's manufacturer specific, so you should consult your computer manual, again we don't know what model you have.
If you really overwrote everything then your best best is likely to contact the manufacturer. I am not aware that you can download windows 10 cold from the Internet. If for example you bought it from Best Buy or another retailer perhaps they can help.
This is probably a question for a more Windows oriented StackExchange site like <https://superuser.com/>
The only option that's relevant to askubuntu is that you could open a terminal window and run the command `fdisk -l` and see if there's still a recovery partition. If you are not familiar with Linux be very careful running fdisk, you should not need to use `sudo` to get this listing. |
148,438 | My home’s A/C has an external circuit breaker. Do I need to switch it off for the winter? | 2018/10/10 | [
"https://diy.stackexchange.com/questions/148438",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/44694/"
] | There is no need to switch off the external breaker serving the outside condensing unit. I have never done so in 40 years at our house. I have never heard of anyone doing so, and I have never heard it recommended. In our installation the external box adjacent to the condensing unit contains a double pole switch, not a breaker, but I only shut this off to service the unit. However, my experience is in the relatively warm winters of Dallas, Texas. |
29,619,208 | I implement `GoogleApiClient` as bellow:
```
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0 /* clientId */, this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addConnectionCallbacks(this)
.build();
```
But in `onConnected` method I check mGoogleApiClient => value null.
In this case I try to re-build googleApiClient but I get error:
```
java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0
```
Please help me understand why mGoogleApiClient is sometimes NULL althought it's connected :|. (Notes. I checked all source code, I never set GoogleApiClient to NULL).
Thanks!
**Update**
My problem now solved after I try use latest version of play-service.
Thanks everybody for help. | 2015/04/14 | [
"https://Stackoverflow.com/questions/29619208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205503/"
] | I had the same problem. All I did to solve it is remove `.enableAutoManage(this, 0 /* clientId */, this)` because it just doesn't work properly from what I assumed. Then, override these methods in your activity:
```
@Override
public void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
public void onStop() {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
```
Technically, that is what `.enableAutoManage(this, 0 /* clientId */, this)` was supposed to do, except that now, everything works as it should. |
13,250,030 | I'm using this CoverFlow :
<http://www.inter-fuser.com/2010/02/android-coverflow-widget-v2.html>
I want to be able to change View when I click on a button, the button being a back/forward icon which will take you to the previous/next item in the coverflow.
I have modded the coverflow slightly so that I use an XML layout instead.
Here is my onCreate() method:
```
setContentView(R.layout.main);
CoverFlow coverFlow = (CoverFlow)findViewById(R.id.coverflow);
coverFlow.setAdapter(new ImageAdapter(this));
ImageAdapter coverImageAdapter = new ImageAdapter(this);
coverFlow.setAdapter(coverImageAdapter);
coverFlow.setSpacing(-20);
coverFlow.setSelection(0, true);
coverFlow.setAnimationDuration(1000);
tv = (TextView)findViewById(R.id.textView1);
coverFlow.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getBaseContext(), String.valueOf(arg2), Toast.LENGTH_SHORT).show();
}
});
coverFlow.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
tv.setText(String.valueOf(arg2));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do something
}
});
```
My XML:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/home_background"
android:orientation="vertical" >
<com.demo.app.coverflow.CoverFlow
android:id="@+id/coverflow"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="39dp"
android:layout_marginLeft="35dp"
android:background="@drawable/button_left" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="39dp"
android:layout_marginRight="35dp"
android:background="@drawable/button_right" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="55dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="hello"
android:textColor="@color/White"
android:textSize="16dp" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginRight="170dp"
android:layout_marginTop="15dp"
android:src="@drawable/unsa_logo" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="14dp"
android:layout_marginTop="23dp"
android:src="@drawable/pnc_logo" />
</RelativeLayout>
``` | 2012/11/06 | [
"https://Stackoverflow.com/questions/13250030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1067944/"
] | While I was trying to find out how to add the animation I came across this which does everything in just one line :
go left
`coverFlow.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(0, 0));`
go right
`coverFlow.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(0, 0));`
(just add each line to their respective button onclick methods
Hope this can help anyone else who finds them self in the same situation as I was :) |
38,378,060 | I have data which is represented as a list of positive double numbers, and a list containing the intervals which will be used to group the data. The interval is always sorted.
I tried to group the data with the following implementation
```
List<Double> data = DoubleStream.generate(new Random()::nextDouble).limit(10).map(d -> new Random().nextInt(30) * d).boxed().collect(Collectors.toList());
HashMap<Integer, List<Double>> groupped = new HashMap<Integer, List<Double>>();
data.stream().forEach(d -> {
groupped.merge(getGroup(d, group), new ArrayList<Double>(Arrays.asList(d)), (l1, l2) -> {
l1.addAll(l2);
return l1;
});
});
public static Integer getGroup(double data, List<Integer> group) {
for (int i = 1; i < group.size(); i++) {
if (group.get(i) > data) {
return group.get(i - 1);
}
}
return group.get(group.size() - 1);
}
public static List<Integer> group() {
List<Integer> groups = new LinkedList<Integer>();
//can be arbitrary groupping
groups.add(0);
groups.add(6);
groups.add(11);
groups.add(16);
groups.add(21);
groups.add(26);
return groups;
}
```
Is it possible to perform this kind of groupping/reducing by performing directly the logic on data, through collectors?
In addition, thinking about the complexity of the process, this should take n^2 since we iterate over two list (or stream). Now it's not in parallel but i think it's possible to perform getGroup() in paralel. Any Insight should TreeSet or List should be used for better performance? | 2016/07/14 | [
"https://Stackoverflow.com/questions/38378060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3212878/"
] | Use a [`TreeSet.ceiling()`](https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html#ceiling-E-) to find the "group" boundary value.
*Example*
```
TreeSet<Double> groups = new TreeSet<>();
groups.add( 5d); // [-Inf, 5]
groups.add(10d); // ] 5, 10]
groups.add(15d); // ] 10, 15]
groups.add(20d); // ] 15, 20]
groups.add(25d); // ] 20, 25]
groups.add(30d); // ] 25, 30]
groups.add(Double.POSITIVE_INFINITY); // ] 30, +Inf]
Random rnd = new Random();
for (double value = 0d; value <= 30d; value += 5d) {
double down = Math.nextDown(value);
double up = Math.nextUp(value);
System.out.printf("%-18s -> %4s %-4s -> %4s %-18s -> %4s%n",
down, groups.ceiling(down),
value, groups.ceiling(value),
up, groups.ceiling(up));
}
for (int i = 0; i < 10; i++) {
double value = rnd.nextDouble() * 30d;
double group = groups.ceiling(value);
System.out.printf("%-18s -> %4s%n", value, group);
}
```
*Output*
```none
-4.9E-324 -> 5.0 0.0 -> 5.0 4.9E-324 -> 5.0
4.999999999999999 -> 5.0 5.0 -> 5.0 5.000000000000001 -> 10.0
9.999999999999998 -> 10.0 10.0 -> 10.0 10.000000000000002 -> 15.0
14.999999999999998 -> 15.0 15.0 -> 15.0 15.000000000000002 -> 20.0
19.999999999999996 -> 20.0 20.0 -> 20.0 20.000000000000004 -> 25.0
24.999999999999996 -> 25.0 25.0 -> 25.0 25.000000000000004 -> 30.0
29.999999999999996 -> 30.0 30.0 -> 30.0 30.000000000000004 -> Infinity
3.7159199611763514 -> 5.0
7.685306184937567 -> 10.0
2.6949924484301633 -> 5.0
17.594251973883363 -> 20.0
24.005899441664994 -> 25.0
7.720531186142164 -> 10.0
22.82402791692674 -> 25.0
22.68288732263466 -> 25.0
13.056624829892243 -> 15.0
8.504511505971251 -> 10.0
``` |
32,537,729 | I installed libsql-translator-perl on Ubuntu 15.04 and ran it with
```
sqlt -f SQLite -t MySql /tmp/test.sql /tmp/out.sql
```
test.sql contains only this:
```
CREATE TABLE X (id INTEGER);
```
It failed with
```
Use of uninitialized value $name in pattern match (m//) at /usr/share/perl5/SQL/Translator.pm line 610.
```
I looked at this file, it contains
```
sub load {
my $name = shift;
my @path;
push @path, "" if $name =~ /::/; # error here
```
The call stack shows that it was called with
```
SQL::Translator::load(undef, 'SQL::Translator::Producer')
```
from here
```
sub _load_sub {
my ($tool, @path) = @_;
my (undef,$module,$func_name) = $tool =~ m/((.*)::)?(\w+)$/;
if ( my $module = load($module => @path) ) { # <<<<<<<
my $sub = "$module\::$func_name";
return wantarray ? ( \&{ $sub }, $sub ) : \&$sub;
}
return undef;
}
```
I don't know enough Perl to unpick this any further. Does anyone know what might be going on? Thanks. | 2015/09/12 | [
"https://Stackoverflow.com/questions/32537729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/458742/"
] | The error message tells you that `$name` is undefined; it is set to the first argument, i.e. the value of `$module` in `_load_sub`, which is set to the second captured match in `m/((.*)::)?(\w+)$/`: everything in the value of `$tool` before the first occurrence of `::`, if `::` occurs, and undefined otherwise.
So `$tool` does not contain the string `::`; the matching pattern accounts for this (by including the `?` metacharacter), but the code in `load` doesn't. Looks like a bug in the code. [The documentation](http://search.cpan.org/~ilmari/SQL-Translator-0.11021/lib/SQL/Translator.pm) lists several ways to report this or verify whether this has been reported or fixed before.
You can debug Perl code by running it with `perl -d` - see [its manual](http://perldoc.perl.org/perldebug.html). |
32,506,415 | I'm trying to load google font to my webapp (angular based but not relevant) and I'm getting this error:
```
Failed to decode downloaded font: https://fonts.googleapis.com/css?family=Open+Sans
```
The relevant part of my webpack.config.js is:
```
loaders: [
{test: /\.less$/, loader: "style!css!less", exclude: /node_modules|bower_components/},
{test: /\.woff(2)$/, loader: "url?limit=10000&minetype=application/font-woff"}
]
```
and my style.less is:
```
@font-face {
font-family: "myFont";
font-style: normal;
src: url(https://fonts.googleapis.com/css?family=Open+Sans);
}
body {
font-family: "myFont";
}
```
My guess is that it is not really related to the webpack part but the font inclusion itself. Unfortunately I lack the knowledge to figure out where exactly is the problem. | 2015/09/10 | [
"https://Stackoverflow.com/questions/32506415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4470201/"
] | I'd suggest you have a look at this article by Paul Irish from 2009 named [Bulletproof @font-face syntax](http://www.paulirish.com/2009/bulletproof-font-face-implementation-syntax/)
It explains very well and in all detail how to get webfonts up and running across all (or at least all capable) browsers. |
15,746,542 | I have a problem with sorting my sentence values in descending order:
I typed this command in unix:
```
sort fileInput -t"(" -k2r >fileSort
```
Here's the input file:
```
comité de conciliation de décision du parlement européen et du (0.00098379)
les amendements CARD CARD CARD CARD CARD CARD et CARD (-0.00025165)
la protection des consommateurs sur la proposition de directive du (0.00077120)
```
and here's the output file:
```
comité de conciliation de décision du parlement européen et du (0.00098379)
les amendements CARD CARD CARD CARD CARD CARD et CARD (-0.00025165)
la protection des consommateurs sur la proposition de directive du (0.00077120)
```
The file is not well sorted
Any idea please? | 2013/04/01 | [
"https://Stackoverflow.com/questions/15746542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2215112/"
] | Add `-n` and `-g` options for numeric sort like this:
```
sort -t"(" -ngk2r
``` |
1,003,201 | Is there a way to list runtime-only (i.e. no `--permanent`) changes in firewalld? I would like to see a diff in my configuration to make sure no change will get lost in case of a `--reload`. | 2020/02/15 | [
"https://serverfault.com/questions/1003201",
"https://serverfault.com",
"https://serverfault.com/users/364632/"
] | as far as I can see no tool that offers you that possibility, but you can create it yourself.
I add a runtime acl to port 54/tcp:
```
# firewall-cmd --add-port=54/tcp
```
Then I can save the runtime rules to a file:
```
# firewall-cmd --list-all > /tmp/runtime_rules
```
And I save the permanent rules to another file:
```
# firewall-cmd --list-all --permanent > /tmp/permanent_rules
```
Finally I use diff to compare both
```
# diff /tmp/runtime_rules /tmp/permanent_rules
1c1
< FedoraWorkstation (active)
---
> FedoraWorkstation
4c4
< interfaces: wlp2s0
---
> interfaces:
7c7
< ports: 1025-65535/udp 1025-65535/tcp 54/tcp
---
> ports: 1025-65535/udp 1025-65535/tcp
```
And there you have the port I added on the runtime rules, not on the permanent one. |
49,547,744 | I am trying to deploy Lambda functions using AWS Cloud9. When I press deploy, all of my functions are deployed/synced at the same time rather than just the one I selected when deploying. Same thing when right clicking on the function and pressing deploy. I find this quite annoying and wondering if there is any work around? | 2018/03/29 | [
"https://Stackoverflow.com/questions/49547744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4718413/"
] | When you click deploy Cloud9 runs `aws cloudformation package` and `aws cloudformation deploy` on your `template.yaml` file in the background. (source: I developed the Lambda integration for AWS Cloud9).
Because all your files are bundled into one serverless application and there is only one CloudFormation stack they can only be all deployed at once with CloudFormation.
If you're only making a code change for one function and are not modifying any configuration settings you could update that one function from the command line with the command:
```
zip -r - . | aws lambda update-function-code --function-name <function-name>`
```
Run this in the same folder as your `template.yaml` file, replacing `<function-name>` with it's full generated name like `cloud9-myapp-myfunction-ABCD1234` (You can see the full name under the remote functions list in the AWS Resources panel). |
33,402,360 | I am attempting to create a random number generator for any number of numbers in a line and then repeating those random numbers until a "target" number is reached.
The user will enter both the number of numbers in the sequence and the sequence they are shooting for. The program will run the random numbers over and over until the target sequence is hit, then the program will spit out the number of repetitions it took.
My problem is that it keeps going on forever, seemingly never hitting the break function because num doesn't equal target or something.
So far I have this and i think i am pretty close
```
#Module to get amount of numbers in the sequence
def getRange():
Range =int(input("How many digits in your number?"))
return Range
#Target Sequence input
def getTarget():
Target= []
Target =input("What is your target sequence?")
return Target
def lotteryNo(Range):
import random
integer = []
for number in range(0 , Range):
integer.append(random.randint(0, 9))
return integer
def printDigits(Range,Target):
print("Your target list is",Target)
for rep in range(10000000):
num=(lotteryNo(Range))
print(num)
if num == Target:
rep=rep + 1
print("The number of repetitions is",rep)
break
else:
rep=rep+1
def main():
Range=getRange()
Target=getTarget()
printDigits(Range,Target)
main()
#End
``` | 2015/10/28 | [
"https://Stackoverflow.com/questions/33402360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5344823/"
] | The issue with your comparison is that you're testing `Target` which is a string against `num` which is a list of integers. That will never match, no matter what integers and what string you're dealing with. You need to compare two like-types to get a meaningful result.
It looks like you wanted your `getTarget` function to return a list, since you're initializing `Target` to an empty string. However, when you overwrite it with `Target = input(...)`, the list is discarded.
You probably want something like `Target = list(map(int, input()))`, which converts each character of the input string to an integer and then packs them all into a list. Another way of writing that would be `Target = [int(digit) for digit in input()]`.
One further suggestion, unrelated to your current issue: Python's common naming convention is to use `lower_case_names_with_underscores` for variable and function names, reserving `UpperCaseNames` for classes. You don't have to follow this convention, but it's probably a good idea if you're going to share your code with anyone. You can read [PEP 8](https://www.python.org/dev/peps/pep-0008/) for more style suggestions. |
38,356,333 | Another beginners question here, coming from Delphi you always have access to another forms controls but in my early days with C# / Visual Studio I am faced with a problem which is proving more difficult than it should be.
I have been getting started by writing a simple notepad style application, I have my main form and a secondary form used to select a line number.
From my main form, I call the goto line number form like so:
```
private void mnuGoTo_Click(object sender, EventArgs e)
{
Form gotoForm = new GoToForm();
var dialogResult = gotoForm.ShowDialog();
if (dialogResult == DialogResult.OK)
{
// get the text from gotoForm.editLineNumber.Text
MessageBox.Show(gotoForm.editLineNumber.Text); // doesn't work
}
}
```
As you can see from the commented code I have a `TextBox` control called `editLineNumber` which is on my other form (`GoToForm`).
My problem (and likely a beginner question) is why does `editLineNumber` not show in the `intellisense` menu when I type `gotoForm.`?
How do I access the `editLineNumber` control from the form `GoToForm`?
The error message for the `// doesn't work` commented line is:
>
> Error CS1061 'Form' does not contain a definition for 'editLineNumber'
> and no extension method 'editLineNumber' accepting a first argument of
> type 'Form' could be found (are you missing a using directive or an
> assembly reference?)
>
>
>
Unless I am missing something obvious, why are controls that exist on another form not publically available to all forms? I understand that C# / Visual Studio is different to Delphi but the way Delphi lets you access and see all controls on all forms without any extra works seems more logical to me. Why does C# / Visual Studio hide controls on secondary forms, for what purpose can this be beneficial? | 2016/07/13 | [
"https://Stackoverflow.com/questions/38356333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4645457/"
] | The `editLineNumber` control is private. You can change it to be public, but that's discouraged.
Instead, create a property in `GoToForm` that returns the value you want.
```
public string LineNumber
{
get { return this.editLineNumber.Text; }
}
```
Now you can just reference your new property:
```
if (dialogResult == DialogResult.OK)
{
MessageBox.Show(gotoForm.LineNumber);
}
``` |
29,845,218 | I,m trying to write a regex to check if the given string is like
a + b, 2 + a + b, 3 + 6 \* 9 + 6 \* 5 + a \* b, etc...
Only + and \* operators.
I tried
`if (str.matches("(\\d|\\w \\+|\\*){1,} \\d|\\w"))`
Unfortunately it only handles cases like 3 \* 7 ... (numeric \* numeric).
Waiting for your answers, thanks for reading me. | 2015/04/24 | [
"https://Stackoverflow.com/questions/29845218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4807032/"
] | Put `*` and `+` inside a character class.
```
str.matches("\\w(?:\\s[+*]\\s\\w)+");
```
[DEMO](https://regex101.com/r/dI4uH0/2) |
66,436,586 | I have the below list :-
```
someList = ["one","three","four","five","six","two"]
```
I want to change position of "two" i.e after "one" and rest string should be shifted as they are.
Expected Output : -
>
> someList = ["one","two","three","four","five","six",]
>
>
> | 2021/03/02 | [
"https://Stackoverflow.com/questions/66436586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8048800/"
] | You can pop 2 from current index and insert to new index
```py
l.insert(1, l.pop(-1))
``` |
12,331,968 | I have code like this I need to access the `mysample` variable of static class `InnerClass` in the `getInnerS()` method which is inside the the `NestedClass`. I tried accessing it by creating a new object for `InnerClass` but i am getting `java.lang.StackOverflowError`.
```
public class NestedClass{
private String outer = "Outer Class"; //NestedClass instance variable
NestedClass.InnerClass innerClass = new NestedClass.InnerClass();
void getOuterS(){
System.out.println(outer);
}
void getInnerS(){
System.out.println(innerClass.mysample);
}
static class InnerClass{
private String mysample = "Inner Class"; //InnerClass instance variable,
NestedClass a = new NestedClass();
void getIn(){
System.out.println(mysample);
}
void getOut(){
System.out.println(a.outer);
}
}
public static void main(String[] args){
NestedClass nestedClass = new NestedClass();
NestedClass.InnerClass nestedInner = new NestedClass.InnerClass();
nestedClass.getOuterS();
nestedClass.getInnerS();
nestedInner.getIn();
nestedInner.getOut();
}
}
``` | 2012/09/08 | [
"https://Stackoverflow.com/questions/12331968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1604151/"
] | In `InnerClass` constructor:
```
NestedClass a = new NestedClass();
```
So, you create a new `NestedClass`, which creates a new `InnerClass`, which creates itself its own `NestedClass`, with the corresponding `InnerClass`.... No wonder the stackoverflow.
If you want to access the enclosing class, you should use (inside `InnerClass` methods)
```
NestedClass.this
``` |
4,402,482 | I can't get PHPMyAdmin to connect to my Amazon RDS instance. I've granted permissions for my IP address to the DB Security Group which has access to this database I'm trying to access. Here's what I'm working with...
```
$cfg['Servers'][$i]['pmadb'] = $dbname;
$cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][$i]['relation'] = 'pma_relation';
$cfg['Servers'][$i]['table_info'] = 'pma_table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma_column_info';
$cfg['Servers'][$i]['history'] = 'pma_history';
$cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
/* Uncomment the following to enable logging in to passwordless accounts,
* after taking note of the associated security risks. */
// $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
/* Advance to next server for rest of config */
$i++;
}
$cfg['Servers'][$i]['auth_type'] = 'http'; //is this correct?
$cfg['Servers'][$i]['user'] = 'MASTER-USER';
$cfg['Servers'][$i]['password'] = 'MASTER-USER-PASSWORD';
$cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'MY-DB.us-east-1.rds.amazonaws.com';
$cfg['Servers'][$i]['connection_type'] = 'socket';
$cfg['Servers'][$i]['port'] = PORT;
```
I'm not sure if my configuration is correct.
I'm getting this error:
>
> #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 110
>
>
>
Does anyone have any advice? | 2010/12/09 | [
"https://Stackoverflow.com/questions/4402482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197606/"
] | I found most of the answers in this question lack explanation. To add RDS server in phpMyAdmin installed in EC2, you can first login to your EC2 via SSH. Then, issue the following command to edit the Config file of phpMyAdmin (use `vi`, `nano` or any other favorite text editing tool):
```
sudo vi /etc/phpMyAdmin/config.inc.php # Amazon Linux
sudo vi /etc/phpmyadmin/config.inc.php # Ubuntu Linux
```
Find the following lines in `config.inc.php`:
```
/*
* End of servers configuration
*/
```
Append the following lines **above** the "End of servers configuration" line:
```
$i++;
$cfg['Servers'][$i]['host'] = 'xxxxx.xxxxxxxxxx.us-east-1.rds.amazonaws.com';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['verbose'] = 'YOUR_SERVER_NAME';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysql';
$cfg['Servers'][$i]['compress'] = TRUE;
```
which `YOUR_SERVER_NAME` is the name being displayed in phpMyAdmin login page's selection box. If you remove this line, the whole RDS hostname will be displayed in the selection box (which is too long, obviously). Remember to save the `config.inc.php`.
There are several other config settings, which you can find the details in the [official documentation](https://docs.phpmyadmin.net/en/latest/config.html).
---
**Note:** The other answer suggests auto login with preset username & password in Config file:
```
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '__FILL_IN_DETAILS__';
$cfg['Servers'][$i]['password'] = '__FILL_IN_DETAILS__';
```
which is **extremely dangerous** if your phpMyAdmin is exposed to public. You don't want to show your database schema to everyone, do you? If you really want to use automatic login, make sure your phpMyAdmin is accessible via specific IPs only. |
139,990 | If an algorithm for $SAT$ runs in $O(n^{\log n})$ time, and if $L$ belongs to $\mathsf{NP}$, is there an algorithm for $L$ that runs in $O(n^{\log n})$ time? | 2021/05/06 | [
"https://cs.stackexchange.com/questions/139990",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/136310/"
] | As $\mathrm{SAT}$ is $\mathrm{NP}$-complete, we know that there is a polytime reduction from our language $L$ to $\mathrm{SAT}$. However, this reduction can involve a polynomial blowup of the input size. This means that an input $w$ to $L$ could be mapped to a formula $\phi\_w$ such that $|\phi\_w| \approx |w|^k$ for some constant $k$.
Running our hypothetical algorithm for $\mathrm{SAT}$ on $\phi\_w$ takes time $O(|\phi\_w|^{\log |\phi\_w|}) = O((|w|^k)^{\log |w|^k}) = O(|w|^{k^2 \log |w|})$ time. But $O(n^{k^2 \log n}) \neq O(n^{\log n})$.
Thus, there is no immediate reason why the assumption would yield an $O(n^{\log n})$-algorithm for $L$. |
8,305,527 | What is a regular expression to allow letters only, with no spaces or numbers, with a length of 20 characters?
Some examples of acceptable usernames:
```
ask1kew
supacool
sec1entertainment
ThatPerson1
Alexking
```
Some examples of unacceptable usernames:
```
No_problem1
a_a_sidkd
Thenamethatismorethen20characterslong
``` | 2011/11/29 | [
"https://Stackoverflow.com/questions/8305527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/604023/"
] | This should work if you're limiting yourself to ASCII:
```none
/\A[a-z0-9]{,20}\z/i
```
That will also match an empty string though so you might want to add a lower limit (5 in this example):
```none
/\A[a-z0-9]{5,20}\z/i
```
If you wanted to be adventurous and allow non-ASCII letters and you're using Ruby 1.9 then you could use this:
```none
/\A\p{Alnum}{5,20}\z/
/\A\p{Alnum}{,20}\z/ # If no lower limit on length is desired.
``` |
37,938,413 | Is there a function or something in laravel which I can use to make first letter uppercase in breadcrumbs?
This is what I'm using right now but in my links and routes are all lowercase letters and if I go and try to update all will be very time consuming..
```
<ul class="breadcrumb">
<li>
<i class="glyphicon glyphicon-home"></i>
<a href="{{ URL::to('/') }}">Home</a> /
@for($i = 0; $i <= count(Request::segments()); $i++)
<a href="">{{Request::segment($i)}}</a>
@if($i < count(Request::segments()) & $i > 0)
/
@endif
</li>
@endfor
</ul>
```
Or this isn't correct way of making breadcrumbs in laravel 4.2? | 2016/06/21 | [
"https://Stackoverflow.com/questions/37938413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Yes and no.
It is not possible at the time of writing, if you want to do it only with browser client side javascript, because twitter does not allow cross site requests.
Browsers execute javascript code in a sandbox environment, which does not allow you to do a request to another domain as yours, except the 3rd party domain explicitly allows it. This is called [Http Access Control (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)
However the twitter api can of course be consumed by a javascript app, which is not running in a browser.
So if you want this functionality for your website and you want to code it only in javascript, you would have to write a backend api for your website in nodejs or use another 3rd party service like @RationalDev suggested |
4,022,426 | I am new to Iphone.How to create file browser in iphone ?
I wish to show all the files and folders in the iphone.How to do this? | 2010/10/26 | [
"https://Stackoverflow.com/questions/4022426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/482568/"
] | Unless you are on a jailbroken phone, your app can only access files within its own "sandbox".
There are [three folders](http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/RuntimeEnvironment/RuntimeEnvironment.html#//apple_ref/doc/uid/TP40007072-CH2-SW12) your app can access, which contain data specific to your application. Your app will not be able to access file data outside these folders.
With that caveat in mind, you would likely use:
1. [`NSFileManager`](http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSFileManager_Class/Reference/Reference.html) and [`NSDirectoryEnumerator`](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDirectoryEnumerator_Class/Reference/Reference.html) to build a data source to a table view
2. [`UITableView`](http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html) to present the list of files and folders obtained from step 1
3. [`UINavigationController`](http://developer.apple.com/library/ios/#documentation/uikit/reference/UINavigationController_Class/Reference/Reference.html) to provide a navigation stack for walking through a hierarchy of folders: a stack of `UITableView` instances
to browse the list of accessible files and folders within your application's sandbox. |
9,735,164 | How can I make `find` apply my shell's defined functions and aliases inside its *exec* parameter?
For example I have defined a function analogous to **bzip2** but using **7z**:
>
> function 7zip() { for f in $@; do ls -alF "$f"; 7za a -t7z -m0=lzma
> -mx=9 -mfb=64 -md=64m -ms=on "$f.7z" "$f" && touch -r "$f" "$f.7z" && rm -fv "$f" && ls -alF "$f.7z"; done; }
>
>
>
When I find files older than 7 days to compress:
```
find . -mtime +7 -name "G*.html" -execdir 7zip {} +
```
Rather than expanding **7zip** it errors Command Not Found.
This is all inside a shell script. | 2012/03/16 | [
"https://Stackoverflow.com/questions/9735164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1069375/"
] | You can export a function definition with:
```
export -f 7zipi
```
but using an indentifier whose name begins with a number is asking for trouble. Try changing the name to something sensible. (eg "f7zipi", or "\_7zipi") |
34,352,840 | I am using an extendible hash and I want to have strings as keys. The problem is that the current hash function that I am using iterates over the whole string/key and I think that this is pretty bad for the program's performance since the hash function is called multiple times especially when I am splitting buckets.
**Current hash function**
```
int hash(const string& key)
{
int seed = 131;
unsigned long hash = 0;
for(unsigned i = 0; i < key.length(); i++)
{
hash = (hash * seed) + key[i];
}
return hash;
}
```
The keys could be as long as 40 characters.
**Example of string/key**
```
string key = "from-to condition"
```
I have searched over the internet for a better one but I didn't find anything to match my case. Any suggestions? | 2015/12/18 | [
"https://Stackoverflow.com/questions/34352840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4484809/"
] | You should prefer to use `std::hash` unless measurement shows that you can do better. To limit the number of characters it uses, use something like:
```
const auto limit = min(key.length(), 16);
for(unsigned i = 0; i < limit; i++)
```
You will want to experiment to find the best value of 16 to use.
I would actually expect the performance to get worse (because you will have more collisions). If your strings were several k, then limiting to the first 64 bytes might well be worth while.
Depending on your strings, it might be worth starting not at the beginning. For example, hashing filenames you would probably do better using the characters between 20 and 5 from the end (ignore the often constant pathname prefix, and the file extension). But you still have to measure. |
3,412,699 | Suppose you have the product of two expressions: $ 2^5$ \* $ 2^2$, the result will be : $ 2^{5+2}$ = $ 2^7$. This is because we know the exponent rule that if they have the same base, we can add the power. Is there a way to express the product of two expressions of different bases and powers into 1 expression with one base and power, like: $ 3^7$ \* $ 4^8$ = $ a^b$ | 2019/10/28 | [
"https://math.stackexchange.com/questions/3412699",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/711602/"
] | No, the definition you gave is correct. Take for example $\mathbb N$ with discrete metric. Of course $\mathbb N$ is dense in it self. If you use $\mathcal B(x\_0,\varepsilon )\setminus \{x\_0\}$ instead of $\mathcal B(x\_0,\varepsilon )$, then when $\varepsilon <1$ and $n\in\mathbb N$, you'll get $$\mathcal B(n,\varepsilon )\setminus \{n\}=\emptyset,$$
what contradict density. |
40,734,246 | Consider the following (simplified) example where two lambda functions call each other, one of which also takes another function as an argument. I need to use lambda functions, since the functions also pass modified, nested functions between each other.
```
#include <iostream>
using namespace std;
auto f = [](int n, auto h)
{
if(n >= 5) return n;
cout << "h is some function " << h(4.0) << end;
auto func = [](int m){ return m*h(m); }; // some nested function
return g(n+1,func);
};
auto g = [](int n, auto h)
{
if(n >= 5) return n;
cout << "h is some function " << h(5.0) << end;
auto func = [](int m){ return m*h(m); }; // some nested function
return f(n+1,func);
};
int main()
{
auto initial_function = [](int m){ return m*m; };
f(1, initial_function);
return 0.0;
}
```
This returns the usual error *undeclared identifier 'g'* which was to expect since there is no header file. So my question is: What is the proper syntax to declare the two lambda functions? | 2016/11/22 | [
"https://Stackoverflow.com/questions/40734246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4114626/"
] | You need to capture the lambda inside `g` (or vice versa). `g` and `f` are variables which are **pointing** to a (unnamed) function. Making these lambdas doesn't make sense. Lambdas work best when you need a function in local scope. You will have to convert at-least one of them as a function and do a forward-declare for it to get this code working
```
int f(int n);
auto g = [](int n)
{
if(n >= 5) return n;
return f(n+1);
};
int f(int n)
{
if(n >= 5) return n;
return g(n+1);
}
int main()
{
f(1);
return 0.0;
}
```
Based on OP's edit, probably what the OP needs is
```
template<typename T1, typename T2>
auto g(int n, const T1& f, const T2& h)
{
if(n >= 5) return n;
cout << "h is some function " << h(5.0) << end;
return f(n+1);
}
```
To be called as:
```
auto h = [](int m) { return m*m; };
auto f = [h](int m) { return n >= 5 ? n : return g(n+1, f, h); };
g(n, f, h);
``` |
1,701 | Throughout both my academic and professional career I've encountered situations where in such roles (as most of us would have), where as a happy go lucky graduate who doesn't know it all (but thought I did) would attend meetings and I wouldn't know what certain industry terminology meant or understood certain aspects of the project cycle.
I would become really pedantic about asking stupid questions that should be (what I felt) well known. But, I wouldn't ask them in the meeting (especially in a group setting) purposely to not look stupid.
To overcome this I would do two things:
* I would always go home (after the day is done) and look up the terminology/subject matter and teach myself that way, so if the topic comes up again I'd be armed with the newly obtained knowledge.
* I would wait until my superior came up to me and if they mentioned it, I would have a look of confusion on my face and then ask the question. (But this to me, seemed like I wasn't listening in the meeting and/or unprofessional).
Which made me contemplate the best time to ask these questions to make myself seem less like I wasn't paying attention but more because I'm willing to learn.
---
So, when is it okay to ask "stupid" questions in the workplace? | 2017/08/12 | [
"https://interpersonal.stackexchange.com/questions/1701",
"https://interpersonal.stackexchange.com",
"https://interpersonal.stackexchange.com/users/2167/"
] | **Note**: as the question specifically aims at meetings, this answer aligns to that scenario.
You'll have to weigh up the problems you face, either look attentive and eager to learn by overcoming your fear of looking stupid or keep doing what you're currently doing. But, my advice is if someone knows and you don't, **just ask**.
[Asking more questions is not only effective](https://www.inc.com/alison-davis/why-asking-dumb-questions-is-so-darn-smart.html), you learn a hell of a lot from asking even the most simple ones. Don't worry too much, though. You have several times you can ask and whom to ask (depending on your confidence):
1. *If and only if* you aren't disrupting the meeting or the person hosting the meeting, just ask the question there and then. i.e.
>
> "Sorry, could you elaborate on that?"
>
>
>
or
>
> "Sorry, what does XYZ mean?"
>
>
>
this will not only quench your worry about not looking like you're paying attention, it also has multiple benefits: You'll learn (rather than waiting the rest of the day to go home and read up on it) about it there and then, but it can also set the tone for the meeting (someone else might be in the same boat, and you've just set the bar for the types of questions you can ask, thus, an opportunity to learn more from more questions from your peers).
2. After the meeting pull the person who ran the meeting to the side (if you didn't want to disrupt them, or didn't want to engage within a group setting) and ask them to elaborate further on what they said. I'm sure most people wouldn't mind (unless it's something you've learnt in the office before and should already know)
3. If the person is a superior and you want to keep face with them, you can simply pull a trusted colleague to one side after the meeting and ask them about one of the problems you faced or compare notes (they might have something written down you didn't know about), sometimes with other programmers, I would compare notes and [rubberduck](https://en.wikipedia.org/wiki/Rubber_duck_debugging) them and learn that way. But, in a normal office environment, just simply ask them:
>
> "Hey, you know when they mentioned XYZ in the meeting, do you know any
> more about that? I'm looking to learn a little more."
>
>
>
These options may make you come across as "stupid", but you'll also come across as someone who is willing to own up when they don't know something and someone who is wanting to learn more about the topic at hand.
**Further Reading:**
* [Why asking stupid questions is the smartest thing to do.](https://www.stroudinternational.com/latest-insights/stupid-questions)
* [Why you should ask stupid questions.](http://www.yuhiro.de/why-you-should-ask-stupid-questions/) |
38,100,970 | I'm trying to figure out how to make an embedded video only readable by a specific player. Here's the context:
I have a website that hosts videos for streaming. All videos are private. My clients would like to be able to generate an embedding code snippet that would allow him to post this video to whichever site he desires. (ultimately this means that the video stream is no longer private but now made public).
Now this is the tricky part. The client **does not** want these videos to be scannable via their URLs, meaning that if the video url is <http://my.domain.com/videoToken>, any bots/users/programs hitting that URL will not see the video, however the player needs to load the video from that same URL.
Anyone know what secure options I have for implementing this? There are some DRM solutions out there, are those of any help for this use case?
Thanks in advance.
PS: if this is not possible for whatever reason, what's the next closest thing? | 2016/06/29 | [
"https://Stackoverflow.com/questions/38100970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1658211/"
] | What if we put something similar to the following on a .htacces file?
```
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http://(www\.)?my.domain\.com/.*$ [NC]
RewriteRule .*\.(mp4|avi)$ http://www.my.domain.com/forbidden.mp4 [R,NC,L]
# or serve a standard 403 forbidden error page
# RewriteRule .*\.(mp4|avi)$ - [F,L]
</ifModule>
```
Maybe that's not the solution, but the idea of use mod\_rewrite to control access to video on an HTTP\_REFERER basis could be developed. |
6,825,198 | I have a large text string and about 200 keywords that I want to filter out of the text.
There are numerous ways todo this, but I'm stuck on which way is the best:
1) Use a for loop with a gsub for each keyword
3) Use a massive regular expression
Any other ideas, what would you guys suggest | 2011/07/26 | [
"https://Stackoverflow.com/questions/6825198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340939/"
] | A massive regex is faster as it's going to walk the text only once.
Also, if you don't need the text, only the words, at the end, you can make the text a Set of downcased words and then remove the words that are in the filter array. But this only works if you don't need the "text" to make sense at the end (usually for tags or full text search). |
15,843,230 | i have an XML that we were able to generate using HAPI libraries and use XSL to change the format of the XML. I am using the following template. The current template looks at the OBX.5 segment for a digital value and then interprets the OBX6 (units of measure). However I am trying to also interpret the OBX6 when they come from one of the clients in a style as duplicates with the caret `^` in between (ex: `%^%` or `mL^mL`). My current template ignores this but I would like to be able to get the value of the segment substring before or after the `^`.
```
<xsl:template match="hl7:OBX.6[matches(./../hl7:OBX.5, '^\d+(\.\d+)?$') and index-of($percentList, .) or index-of($mgdlList, .) or index-of($mlList, .) or index-of($mmList, .) or index-of($mgList, .))]">
<result><xsl:value-of select="./../hl7:OBX.5" /></result>
<xsl:when test="index-of($percentList, .)">
<units>%</units>
</xsl:when>
...
<xsl:when test="index-of($mlList, .)">
<units>ml</units>
</xsl:when>
<xsl:otherwise>
<units><xsl:value-of select="./hl7:CE.1" /></units>
</xsl:otherwise>
...
</xsl:template>
```
The result should produce
```
<result>38.0</result>
<units>%</units>
```
from
```
<OBX.5>38.0</OBX.5>
<OBX.6>
<CE.1>%^%</CE.1>
</OBX.6>
```
Thanks in advance! | 2013/04/05 | [
"https://Stackoverflow.com/questions/15843230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/552782/"
] | **Use**:
```
tokenize(hl7:CE.1, '\^')[1]
```
**Here is a simple XSLT 2.0 - based verification:**
```
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="OBX.6">
<xsl:sequence select="tokenize(CE.1, '\^')[1]"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
```
**when this transformation is applied on the following XML document** (derived from the provided XML fragment and made well-formed):
```
<t>
<OBX.5>38.0</OBX.5>
<OBX.6>
<CE.1>%^%</CE.1>
</OBX.6>
</t>
```
**the wanted, correct result is produced:**
```
%
``` |
2,653,047 | So I'm trying to register for the MPMoviePlayerDidExitFullscreenNotification notification in my universal app (iPhone and iPad).
Problem is, OS 3.1.3 doesn't support this notification, and just crashes.
I've tried version checking, like so:
```
if ([MPMoviePlayerController instancesRespondToSelector:@selector(setShouldAutoplay:)])
{//Check for shouldSetAutoplay, this ensures that we are running at least 3.2
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinish:) name:(NSString*)class2 object:[self player]];
```
Doesn't work, still crashes. How do I do this? | 2010/04/16 | [
"https://Stackoverflow.com/questions/2653047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/310175/"
] | Since MPMoviePlayerDidExitFullscreenNotification is a symbol, it must be known at (dynamic) link time for any versions. Run time check doesn't help.
To solve this, you need to delay loading of this to run time. You could use `dlsym`:
```
NSString* x_MPMoviePlayerDidExitFullscreenNotification
= dlsym(RTLD_DEFAULT, "MPMoviePlayerDidExitFullscreenNotification");
if (x_MPMoviePlayerDidExitFullscreenNotification != nil) {
[[NSNotificationCenter defaultCenter] addObserver:self ...];
}
```
Alternatively, you may make MPMoviePlayerDidExitFullscreenNotification [a weak symbol](https://stackoverflow.com/questions/274753/how-to-make-weak-linking-work-with-gcc) so when `dyld` doesn't find that symbol, instead of crashing it will just set it to NULL.
Finally, since MPMoviePlayerDidExitFullscreenNotification is just a constant string, you could simply use
```
… name:@"MPMoviePlayerDidExitFullscreenNotification" …
```
But the content of that string is implementation detail. There's no guarantee (although rare) that Apple won't change it to something else in the later versions. |
21,951,969 | In Eclipse, there is an option Export -> JAR File. Then we select desirable classes which want to export to output jar.
How can we do that in IntelliJ? | 2014/02/22 | [
"https://Stackoverflow.com/questions/21951969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361910/"
] | I don't know if you need this answer anymore, but I had the same issue today and I figured out how to solve it.
Please, follow these steps:
1. File -> Project Structure (Ctrl + Alt + Shift + S);
2. Go to the "Artifacts" Menu -> click on the "+" button -> JAR -> From modules with dependencies...
3. Select the module you want to generate the Jar file;
4. Don't select any main class;
5. On the JAR files from libraries menu, select "extract to the target JAR" option -> Click Ok;
6. Name your jar file -> select the output directory -> Click "Apply" and "Ok";
7. After these steps, go to: Build -> Build Artifacts...
8. A flying menu will appear with the artifact that you have previously created;
9. Click Build and it's done.
Hope that that helps you and everyone that have this issue.
I wasted all day trying generate the jar file on Eclipse with FatJar and I couldn't generate it. |
36,502,572 | ```
function convertToRoman(num) {
//seperate the number in to singular digits which are strings and pass to array.
var array = ("" + num).split(""),
arrayLength = array.length,
romStr = "";
//Convert the strings in the array to numbers
array = array.map(Number);
//Itterate over every number in the array
for (var i = 0; i < array.length; i++) {
//Calculate what power of ten the digit is by minusing it's index from the array length and passing it to variable "tenToPowerOf"
var tenToPowerOf = arrayLength - array.indexOf(array[i]) - 1,
low = "",
mid = "",
upp = "";
//Set the low, mid and high variables based on their tenToPowerOf value
switch (tenToPowerOf) {
case 0:
low = "I";
mid = "V";
upp = "X";
break;
case 1:
low = "X";
mid = "L";
upp = "C";
break;
case 2:
low = "C";
mid = "D";
upp = "M";
break;
case 3:
low = "M";
mid = "¯V";
upp = "¯X";
break;
}
//Check for digit value and add it's Roman Numeral value (based on it's power from the above switch statement) to romStr
//The problem is, switch "remembers" the value of low, mid and high from the last time it itterated over the number. Thus 99 becomes "XCXC" and not "XCIX".
switch (array[i]) {
case 1:
romStr += low;
break;
case 2:
romStr += low.repeat(2);
break;
case 3:
romStr += low.repeat(3);
break;
case 4:
romStr += low + mid;
break;
case 5:
romStr += mid;
break;
case 6:
romStr += mid + low;
break;
case 7:
romStr += mid + low.repeat(2);
break;
case 8:
romStr += mid + low.repeat(3);
break;
case 9:
romStr += low + upp;
break;
case 10:
romStr += upp;
break;
default:
break;
}
}
//return array;
return romStr;
}
convertToRoman(99);
```
* Yes, I have spent my share share of time looking for a relevant answer before asking (1.5+ hours).
* The function converts numbers in to Roman Numerals.
+ It takes a number argument passed to it
+ Splits the number in to digits
+ Converts then in to an array
+ Then based on the number's power of ten (or position relevant to the length of the number) sets the low mid and high values
+ These values are then applied in the order dictated by Roman Numerals and pushed to a string
+ Finally, the string is returned.
* It works with numbers that have digits occurring no more than once. The reason for this is because when the switch case is matched more than once in the for loop, it applies the low, mid and high values from the previous iteration.
* The question is in the title but I would also like to ask for a solution to the problem that I am trying to solve please.
* I will gladly provide more information and will answer every question | 2016/04/08 | [
"https://Stackoverflow.com/questions/36502572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5950725/"
] | It seems to me your problem is in the use of `array.indexOf(array[i])` to calculate the power. Guess what, if you have the same value in your array twice, **the first found index is returned**, not the index of your *current* element.
Guess what the index of your current element actually is? → `i`
No need for `indexOf`.
Nothing to do with `switch`. |
28,828,145 | I got a table named "Stock" as shown below.
```
+-----------+--------------+---------------+---------+
| client_id | date | credit | debit|
+-----------+--------------+---------------+---------+
| 1 | 01-01-2015 | 50 | 0 |
| 2 | 01-01-2015 | 250 | 0 |
| 2 | 01-01-2015 | 500 | 0 |
| 2 | 02-01-2015 | 0 | 500 |
| 1 | 02-01-2015 | 0 | 40 |
| 1 | 02-01-2015 | 0 | 80 |
| 3 | 05-01-2015 | 3000 | 0 |
| 2 | 06-01-2015 | 0 | 350 |
| 4 | 06-01-2015 | 0 | 1000 |
| 4 | 06-01-2015 | 0 | 2000 |
| 4 | 07-01-2015 | 500 | 0 |
| 5 | 07-01-2015 | 500 | 0 |
| 5 | 08-01-2015 | 500 | 0 |
| 1 | 09-01-2015 | 0 | 100 |
+-----------+--------------+---------------+---------+
```
The result I am expecting is something like:
```
+---------+-----------+-------------+--------+---------+----------+
|client_id| date |Open_Balance | credit | debit | balance |
+---------+-----------+-------------+--------+---------+----------+
| 1 |01-01-2015 | 0 | 50 | 0 | 50 |
| 1 |02-01-2015 | 50 | 0 | 40 | 10 |
| 1 |02-01-2015 | 10 | 0 | 80 | -70 |
| 1 |09-01-2015 | -70 | 0 | 100 | -170 |
| 2 |01-01-2015 | 0 | 250 | 0 | 250 |
| 2 |01-01-2015 | 250 | 500 | 0 | 750 |
| 2 |02-01-2015 | 750 | 0 | 500 | 250 |
| 2 |06-01-2015 | 250 | 0 | 350 | -100 |
| 3 |05-01-2015 | 0 | 3000 | 0 | 3000 |
| 4 |06-01-2015 | 0 | 0 | 1000 | -1000 |
| 4 |06-01-2015 | -1000 | 0 | 2000 | -3000 |
| 4 |07-01-2015 | -3000 | 500 | 0 | -2500 |
| 5 |07-01-2015 | 0 | 500 | 0 | 500 |
| 5 |08-01-2015 | 500 | 500 | 0 | 1000 |
+---------+-----------+-------------+--------+---------+---- -----+
```
I need balances and 'Open balances' to be calculated by client\_id and date order as shown above. Please help. | 2015/03/03 | [
"https://Stackoverflow.com/questions/28828145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4608311/"
] | Here how you can do it..
```
select
s.client_id,
s.date,
s.op_balance as Open_Balance,
s.credit,
s.debit,
s.balance
from
(
select
t.client_id,
t.date,
t.credit,
t.debit,
@tot_credit := if(@prev_client = t.client_id, @tot_credit + t.credit,t.credit) as tot_cred,
@tot_debit := if(@prev_client = t.client_id,@tot_debit + t.debit,t.debit) as tot_deb,
@cur_bal := if(@prev_client = t.client_id, @tot_credit - @tot_debit,t.credit-t.debit) as balance,
(@cur_bal + t.debit) - t.credit as op_balance,
@prev_client := t.client_id
from(
select * from stock order by client_id,date
)t,(select @prev_client:=0,@cur_bal:=0,@tot_credit:=0,@tot_debit:= 0,@open_balance:=0)r
)s
```
**[DEMO](http://www.sqlfiddle.com/#!2/2f7c1/18)**
Also I have noticed that the same data you have date column which I have used to do the sort per client id, but its good to have datetime for date so that the sorting does not get confused with same date or may be a primary key in the table. |
3,241,286 | The problem is to solve this:
$$a^2 + b^2 =c^4 \text{ }a,b,c\in \Bbb{N}\text{ }a,b,c<100$$
My idea: To see this problem I at first must see idea with Pythagorean triplets, and to problem is to find hypotheses of length square number. Is there any easier approach to this problem? | 2019/05/27 | [
"https://math.stackexchange.com/questions/3241286",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/259483/"
] | I think, the way with using Pythagorean triplets is the best.
Let $\gcd(a,b,c)=1$.
Thus, there are natural $m$ and $n$ with different parity such that $m>n$ and $\gcd(m,n)=1$ and
$a=2mn,$ $b=m^2-n^2$.
Thus, $c^2=m^2+m^2$ and by the same way there are naturals $p$ and $q$ with a different parity, such that $p>q$, $\gcd(p,q)=1$ and $m=2pq$ and $n=p^2-q^2$.
Thus, $a=4pq(p^2-q^2)$, $b=4p^2q^2-(p^2-q^2)^2=6p^2q^2-p^4-q^4$ and $c=p^2+q^2$.
Can you end it now?
For example, for $p=2$ and $q=1$ we obtain: $(a,b,c)=(24,7,5)$. |
41,411,432 | Simple Code:
```
<div id="right">
<h2>Zamiana jednostek temperatury</h2>
temperatura w <sup>o</sup>Celsjusza<br>
<input type="text" id="cyfry" name="cyfry"><br>
<button onclick="fahrenheit()">Fahrenheit</button>
<button onclick="kelwin()">Kelwin</button>
<span id="wynik"></span>
</div>
```
And Script:
```
function fahrenheit(){
var x=Document.getElementById("cyfry");
parseInt(x);
x = (x*1,8)+32;
document.getElementById("wynik").innerHTML=x;
}
function kelwin(){
var x=Document.getElementById("cyfry");
parseInt(x);
x = x + 273,15;
document.getElementById("wynik").innerHTML=x;
}
```
As you can see all I want to do is convert units in Celsius to Fahrenheit or Calvins, but I get an error:
```
Uncaught TypeError: Document.getElementById is not a function
at fahrenheit (script.js:2)
at HTMLButtonElement.onclick (index.html?cyfry=:32)
```
Thanks a lot in advance and Happy New Year!
After some changes I have problem that answer is always 40 in Fahrenheit and 15 on Calvin:
```
function fahrenheit(){
var x=document.getElementById("cyfry").value;
parseFloat(x);
var y = ((x*1,8)+32);
document.getElementById("wynik").innerHTML=y;
}
function kelwin(){
var a=document.getElementById("cyfry").value;
parseFloat(a);
var b = (a + 273,15);
document.getElementById("wynik").innerHTML=b;
```
} | 2016/12/31 | [
"https://Stackoverflow.com/questions/41411432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7361359/"
] | You should use document.getElementById **not** Document.getElementById . Heres a working solution. Hope it helps!
```js
function fahrenheit(){
var x=document.getElementById("cyfry");
parseInt(x);
x = (x*1,8)+32;
document.getElementById("wynik").innerHTML=x;
}
function kelwin(){
var x=document.getElementById("cyfry");
parseInt(x);
x = x + 273,15;
document.getElementById("wynik").innerHTML=x;
}
```
```html
<div id="right">
<h2>Zamiana jednostek temperatury</h2>
temperatura w <sup>o</sup>Celsjusza<br>
<input type="text" id="cyfry" name="cyfry"><br>
<button onclick="fahrenheit()">Fahrenheit</button>
<button onclick="kelwin()">Kelwin</button>
<span id="wynik"></span>
</div>
``` |
15,760,336 | These two views are inside of `RelativeLayout`. The IDE throws an error there is no `@id/et_pass`, but if I set `@+id/et_pass` it is OK. Why is that?
```
<ImageView
android:id="@+id/devider_zero"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/et_pass" <!-- Error is here -->
android:src="@drawable/registration_line" />
<EditText
android:id="@+id/et_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/devider_first"
android:background="@android:color/transparent"
android:layout_gravity="left"
android:ellipsize="start"
android:ems="8"
android:hint="@string/password"
android:inputType="textPassword"
android:layout_marginTop="@dimen/register_layout_edittext_margin_top"
android:maxLines="1" />
``` | 2013/04/02 | [
"https://Stackoverflow.com/questions/15760336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/397991/"
] | You did not allocate any memory for the pointer to point at. You can do so like this:
```
int *a = malloc(sizeof(*a));
```
or like this:
```
int value;
int *a = &value;
```
If you allocate with `malloc` then you'll want to call `free` on the pointer when you are finished using it.
Accessing an uninitialized pointer leads to undefined behaviour. In your program it led to segmentation fault, one very common outcome of uninitialized pointer access. |
65,854,355 | I'm doing a project and I'm having problems moving files into different subfolders. So for example, I have 2 files in the main folder, I want to read the first line, and if the first line has the word "Job", then I will move to the subfolder (main\_folder/files/jobs). My code looks like this:
```
# Get all file names in the directory
def file_names():
files = [file for file in listdir(source_dir) if file.endswith('csv')]
return files
# Read files and separate them
def categorize_files(files):
for file in files:
with open(file, mode='r', encoding='utf8') as f:
text = f.readline().split(",")
if 'Job ID' in text[0]:
## Problem Here ##
move_files(file, 'jobs/')
f.close()
print("This is a job related file")
else:
print("no")
return True
# Move files
def move_files(file_name, category):
print(file_name)
print(category)
return shutil.move(source_dir + file_name, destination_dir + category + file_name)
```
So from my research, I'm guessing the file is still open (?) so I tried closing it. And move on, but somehow I end up having one file in the subfolder, and the original files still in the main folder. The error looks like this:
```
Traceback (most recent call last):
File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 557, in move
os.rename(src, real_dst)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' -> 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/files/jobs/file_14.csv'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 38, in <module>
categorize_files(files)
File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 22, in categorize_files
move_files(file, 'jobs/')
File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 35, in move_files
return shutil.move(source_dir + file_name, destination_dir + category + file_name)
File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 572, in move
os.unlink(src)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv'
```
Can someone please explain why I'm having a problem? Any advice will be greatly appreciated.
++ I also tried closing the file. And even restart the computer and never opened any files. Still get the same error.. | 2021/01/23 | [
"https://Stackoverflow.com/questions/65854355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11639529/"
] | The error happens because you are trying to move a file while it is active and being read inside the `with` statement. The problem should be fixed if you un-indent the `if` statement by one layer. This should close the file and allow it to be moved. Here is the code:
```
# Read files and separate them
def categorize_files(files):
for file in files:
with open(file, mode='r', encoding='utf8') as f:
text = f.readline().split(",")
if 'Job ID' in text[0]:
## Problem Here ##
move_files(file, 'jobs/')
f.close()
print("This is a job related file")
else:
print("no")
return True
``` |
14,138,188 | [the error and the class http://puu.sh/1ITnS.png](http://puu.sh/1ITnS.png)
When I name the class file Main.class, java says it has the wrong name, and when I name it shop.Main.class it says that the main class can't be found. Can anyone help?
```
package shop;
import java.text.DecimalFormat;
public class Main
{
public static void main(String args[])
{
Cart cart = new Cart(new Catalogue());
printOrder(cart);
}
public static void printOrder(Cart cart)
{
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Your order:");
for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size();
itemIndex++)
if (cart.itemsInCart.products.get(itemIndex).quantity != 0)
System.out.println(cart.itemsInCart.products.get(itemIndex).quantity
+ " " + cart.itemsInCart.products.get(itemIndex).name
+ " $"+ df.format(cart.itemsInCart.products.get(itemIndex).price)
+ " = $" + df.format
((cart.itemsInCart.products.get(itemIndex).quantity
* cart.itemsInCart.products.get(itemIndex).price)));
double subtotal = 0;
int taxPercent = 20;
double tax;
double total;
for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size();
itemIndex++)
subtotal += cart.itemsInCart.products.get(itemIndex).quantity
* cart.itemsInCart.products.get(itemIndex).price;
tax = subtotal * taxPercent / 100;
total = subtotal + tax;
System.out.print("Subtotal: $" + df.format(subtotal)
+ " Tax @ " + taxPercent + "%: $" + df.format(tax)
+ " Grand Total: $" + df.format(total));
}
}
```
Ignore between the following two lines
–––––––––––––––––––––––––
Edit Summary
Oops! Your edit couldn't be submitted because:
Your post does not have much context to explain the code sections; please explain your scenario more clearly.
cancel
––––––––––––––––––––––--- | 2013/01/03 | [
"https://Stackoverflow.com/questions/14138188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1774214/"
] | keep it Main.class and try `java shop.Main` from command line in java folder |
44,135,248 | I am trying to retrieve data from excel and put them into the following format in python:
```
dataset={
'User A': {'Lady in the Water': 2.5,
'Snakes on a Plane': 3.5,
'Just My Luck': 3.0,
'Superman Returns': 3.5,
'You, Me and Dupree': 2.5,
'The Night Listener': 3.0},
'Gene Seymour': {'Lady in the Water': 3.0,
'Snakes on a Plane': 3.5,
'Just My Luck': 1.5,
'Superman Returns': 5.0,
'You, Me and Dupree': 3.5,
'The Night Listener': 3.0
}}
```
Where the excel file looks like
```
User A User B
Lady in the Water 2.5 3
Snakes on a Plane 3.5 3.5
Just My Luck 3 1.5
Superman Returns 3.5 5
You, Me and Dupree 2.5 3.5
The Night Listener 3 3
``` | 2017/05/23 | [
"https://Stackoverflow.com/questions/44135248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7677413/"
] | The `pandas` module makes this pretty easy:
```
import pandas as pd
df = pd.read_excel('workbook.xlsx', index_col=0)
dataset = df.to_dict()
```
In this code the `pd.read_excel` function collects all data from the excel file and stores it into a pandas [DataFrame](https://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe) variable. Dataframes come with an enormous amount of very powerful [built-in methods for data reorganization and manipulation](https://github.com/pandas-dev/pandas/blob/master/doc/cheatsheet/Pandas_Cheat_Sheet.pdf). One of these methods is the `to_dict`, which is used in the code here to convert the data to nested dictionaries. |
28,645 | I'm developing a finite volume solver for the simple twodimensional advection equation with constant velocities $u, v$ and constant mesh spaces $\Delta x$:
$$ \frac{\partial \rho}{\partial t} + u \frac{\partial \rho}{\partial x} + v \frac{\partial \rho}{\partial y} = 0$$
where $u,v > 0$.
According to [this lecture](http://www.mpia.de/homes/dullemon/lectures/hydrodynamicsII/chap_4.pdf), the piecewise linear update scheme in 1D is
$$ \rho\_i^{n+1} = \rho\_i^n - \frac{u \Delta t}{\Delta x} ( \rho\_i ^n - \rho\_{i-1}^n) - \frac{u \Delta t}{\Delta x} \frac{1}{2} (s\_i^n - s\_{i-1}^n)(\Delta x - u\Delta t) $$
where $s\_i^n$ is a slope, that may be chosen as
Centered slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i-1}}{2\Delta x}$ (Fromm's method)
Upwind slope: $s\_i^n = \frac{\rho\_{i} - \rho\_{i-1}}{\Delta x}$ (Beam-Warming method)
Downwind slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i}}{\Delta x}$ (Lax-Wendroff method)
and any of these choices results in second-order accurate methods.
I implemented these methods in 1D, and they work as expected. In the plot below is the 1D advection for $u=1$ with periodic boundaries for a step function at various time steps with 1000 cells. An integer time step means that the curve has gone that many times through the whole domain.
[![1d advection results](https://i.stack.imgur.com/tkiLb.png)](https://i.stack.imgur.com/tkiLb.png)
For the 2D method, I evaluate the new value simultaneously in both directions, according to the 2d advection equation as above, while approximating the divergence terms by the piecewise linear scheme as stated above.
If I only let the density advect in one direction, i.e. $u = 0, v=1$ or $u=1, v=0$, I get the expected results, corresponding to the 1D solution. If I choose the timestep to be $\Delta t = [u/\Delta x + v/\Delta y]^{-1}$ as [wikipedia suggests](https://en.wikipedia.org/wiki/Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition) (as opposed to $t< [u/\Delta x + v/\Delta y]^{-1}$), I even get perfect advection without diffusion, as it is predicted by the 1d case.
But if I give both $u$ and $v$ nonzero values, e.g. $u = v = \sqrt{2}/2$, at some point, apparently at some point in time, the solution becomes unstable, and I do not know why. This happens for any choice of the slope. Or does it only look unstable to the inexperienced me, but is in fact just the interference of the oscillations produced by the piecewise linear scheme without any slope limiters? (The situation gets a bit better with a minmod or Van Leer slope limiter).
Below you can see the results of a 2d simulation at various time steps for $nx = ny = 200$ for a 2D step function, using the downwind slope. (The timesteps are 0, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 5.0, 10.0)
[![2d advection results](https://i.stack.imgur.com/ClEOV.png)](https://i.stack.imgur.com/ClEOV.png)
Can anyone tell me how/why this apparent instability occurs, and what to do against it? | 2018/01/18 | [
"https://scicomp.stackexchange.com/questions/28645",
"https://scicomp.stackexchange.com",
"https://scicomp.stackexchange.com/users/26461/"
] | It turns out that the main problem here was that I thought just naively extending the 1D advection
$$ \rho^{n+1}\_{i} = \rho^n\_{i} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2} - \rho^n\_{i+1/2}) $$
to 2D just by adding the $y$ term like this:
$$ \rho^{n+1}\_{i,j} = \rho^n\_{i,j} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2,j} - \rho^n\_{i+1/2,j}) + v\frac{\Delta t}{\Delta x}(\rho^n\_{i, j-1/2} - \rho^n\_{i,j+1/2}) $$
would be a good idea.
It isn't.
Suppose we have $u = v = 1$. Then what one would naturally expect is that the value $\rho\_{i-1, j-1}$ advects to the position $\rho\_{i, j}$ over one adequately chosen timestep. But looking at the formula above which I tried to implement, the value of $\rho\_{i-1, j-1}$ never comes into play. Hence the stencil that I'm using is inadequate.
Looking for example at the upper left corner of the square with higher density in the initial conditions, what happens is that we do get diffusion from the right and from below, but do not interact with the cell one place below and to the left, so more material will advect into the cell. Over many time steps, the result is that "stripes" perpendicular to the direction of advection will develop.
Instead, I should have been using an adequate multidimensional technique. Since I wanted to extend my 1D solvers to 2D, a proper extension is dimensional splitting, where you compute an intermediate state first:
$$ \rho^{n+1/2}\_{i} = \rho^n\_{i} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2, j} - \rho^n\_{i+1/2, j}) $$
called the "$x$-sweep", and then we do the "$y$-sweep":
$$ \rho^{n+1}\_{i} = \rho^{n+1/2}\_{i} + v\frac{\Delta t}{\Delta x}(\rho^{n+1/2}\_{i,j-1/2} - \rho^{n+1/2}\_{i,j+1/2}) $$
This way, the values "on the corners" are taken care of.
Another really cool thing about this dimensional splitting is that one can show that if we keep the time steps $\Delta t$ constant and switch the order of the sweeps every step, the method will become second order accurate in time for basically no extra effort. This is called "Strang splitting".
To demonstrate: Here is what happens if no dimensional/Strang splitting is used:
[![no strang splitting](https://i.stack.imgur.com/KNGiG.png)](https://i.stack.imgur.com/KNGiG.png)
notice the stripes I was talking about.
And this is what happens if the only change is doing proper Strang splitting:
[![with strang splitting](https://i.stack.imgur.com/gSTvd.png)](https://i.stack.imgur.com/gSTvd.png) |
21,107,057 | Is it possible automatically add `Access-Control-Allow-Origin` header to all responses which was initiated by ajax request (with header `X-Requested-With`) in Pyramid? | 2014/01/14 | [
"https://Stackoverflow.com/questions/21107057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813758/"
] | I've solved the problem using `set_request_factory`:
```
from pyramid.request import Request
from pyramid.request import Response
def request_factory(environ):
request = Request(environ)
if request.is_xhr:
request.response = Response()
request.response.headerlist = []
request.response.headerlist.extend(
(
('Access-Control-Allow-Origin', '*'),
('Content-Type', 'application/json')
)
)
return request
config.set_request_factory(request_factory)
``` |
811,624 | I saw this definition in one of the computer science book but I am unable to recall the theorem name. Can someone please provide the reference?
$$\lim\_{n \to \infty} \frac{f(n)}{g(n)} = c > 0$$ means there is some $n\_{0}$ beyond which the ratio is always between $\frac{1}{2}c$ and $2c$. | 2014/05/27 | [
"https://math.stackexchange.com/questions/811624",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/20411/"
] | Notice that $\|Ax\| \le \|x\|$. So $\sigma(A)$ is contained in the closed unit disk $D^{c}$. To find the resolvent $(A-\lambda I)^{-1}$, try to solve $(A-\lambda I)x = y$ for $x$, and see if it can be done. First, see if there are any eigenfunctions $Ax=\lambda x$. If there were such an $x$, then $|\lambda| \le 1$ and $x=(x\_1,x\_2,x\_3,\cdots)$ would satisfy
$$
(x\_2-\lambda x\_1,x\_3-\lambda x\_2,x\_4-\lambda x\_3,\cdots)=0,\\
x\_2=\lambda x\_1,\; x\_3=\lambda x\_2,\;x\_4=\lambda x\_3.
$$
Assuming $x\_1=1$, there is a solution $(1,\lambda,\lambda^{2},\lambda^{3},\cdots)$. This solution is valid only for $|\lambda| < 1$ because, otherwise, $x \notin l^{2}$. In other words, $\sigma\_{P}(A)=\{ \lambda \in \mathbb{C} : |\lambda| < 1\}$ is the open unit disk. And $\sigma(A)=\{ \lambda \in\mathbb{C} : |\lambda|\le 1\}$ because $\sigma(A)$ is closed, contains the open unit disk, and is contained in the closed unit disk.
The adjoint of $A$ is the shift $B(x\_1,x\_2,x\_3,\cdots)=(0,x\_1,x\_2,x\_3,\cdots)$. Notice that $\|Bx\|=\|x\|$ for all $x \in l^{2}$. $B$ has no point spectrum because $Bx=\lambda x$ implies $(x\_1,x\_2-\lambda x\_1,x\_3-\lambda x\_2,\dots)=0$, which forces $x\_1=0, x\_2=\lambda x\_1=0,etc.$. So the range of $(A-\lambda I)$ is dense for all $\lambda$, which puts the unit circle $\{ \lambda \in\mathbb{C} : |\lambda|=1\}$ in the continuous spectrum of $A$. $A$ has no residual spectrum. |
44,702,855 | We are trying to run rbenv on El-Capitan 10.11.6. When we try to run rbenv command in the terminal we got the following error message:
```
command not found
```
We googled how to solve that issue and one possible solution is to add the "rbenv" to the system PATH, we followed the steps stated in [this link](http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.WUvUPUX5yL9). When we run the "$PATH" to check whether or not the rbenv path was added properly into the system PATH, we got the the same result:
```
command not found
```
The result of "$PATH" command is:
```
qwe-Mac-mini:~ amrbakri$ rbenv
-bash: rbenv: command not found
qwe-Mac-mini:~ asd$ echo $PATH
/Users/asd/.rbenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/MacGPG2/bin
```
Can you please tell me how to add the path of rbenv properly? And what did I do wrong in the previous steps so that I can fix it. | 2017/06/22 | [
"https://Stackoverflow.com/questions/44702855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3732958/"
] | Assuming your source is stored in `exampleScriptFile`:
```js
// polyfill
const fs = { readFileSync() { return 'console.log(`${EXAMPLE_3}`);'; } };
// CONSTANTS
const EXAMPLE_1 = 'EXAMPLE_1';
const EXAMPLE_2 = 'EXAMPLE_2';
const EXAMPLE_3 = 'EXAMPLE_3';
const exampleScriptFile = fs.readFileSync('./exampleScriptFile.js');
// What I want is to just use a JS file because it is neater.
eval(exampleScriptFile);
```
### Update
Perhaps I wasn't clear. The `./exampleScriptFile.js` should be:
```
console.log(`${EXAMPLE_3}`);
``` |
422,828 | I need to make the word "Table" within paragraph clickable.
I have tried this [When referencing a figure, make text and figure name clickable](https://tex.stackexchange.com/questions/230828/when-referencing-a-figure-make-text-and-figure-name-clickable). But I got "???" instead.
[![enter image description here](https://i.stack.imgur.com/9Ia1y.jpg)](https://i.stack.imgur.com/9Ia1y.jpg) | 2018/03/23 | [
"https://tex.stackexchange.com/questions/422828",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/156895/"
] | Automatic way, see the `\autoref` feature of `hyperref`:
```
from the \autoref{tab:first}
```
Manually with `\hyperref`:
```
from the \hyperref[tab:first]{Table \ref*{tab:first}}
``` |
1,032,510 | This is an exercise in *Naive Set Theory* by P. R. Halmos.
>
> If $\text{card }A=a$, what is the cardinal number of the set of all
> one-to-one mappings of $A$ onto itself? What is the cardinal number of
> the set of all countably infinite subsets of $A$?
>
>
>
It is easy to see that, for the first question, the cardinal number is less than or equal to $a^a$, and for any finite set the cardinal number is $a!$; for the second one, the cardinal number is less than or equal to $2^a$, and for any finite set the cardinal number is $0$.
I guess for infinite sets the equality holds in both questions. Is that correct? Can anyone give some suggestions on what to do next?
**Edit**: As is suggested by Arthur, the second cardinal number is at most $a^\omega$. | 2014/11/21 | [
"https://math.stackexchange.com/questions/1032510",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/119490/"
] | No. Counterexample: $c=1$ and $f(x)=k>0$ for all $x$. |
56,565,986 | I have a dataframe with full of ip addresses.
I have a list of ip address that I want to remove from my dataframe.
I wanted to have a new dataframe "filtered\_list" after all the ip addresses are removed according to "lista".
I saw an example at [How to use NOT IN clause in filter condition in spark](https://stackoverflow.com/questions/44899392/how-to-use-not-in-clause-in-filter-condition-in-spark). But I can't seem to get it to work even before doing a "not" on the filter Please help.
**Example:**
```
var df = Seq("119.73.148.227", "42.61.124.218", "42.61.66.174", "118.201.94.2","118.201.149.146", "119.73.234.82", "42.61.110.239", "58.185.72.118", "115.42.231.178").toDF("ipAddress")
var lista = List("119.73.148.227", "118.201.94.2")
var filtered_list = df.filter(col("ipAddress").isin(lista))
```
I am encountering the following error message:
```
java.lang.RuntimeException: Unsupported literal type class scala.collection.immutable.$colon$colon List(119.73.148.227, 118.201.94.2)
at org.apache.spark.sql.catalyst.expressions.Literal$.apply(literals.scala:77)
at org.apache.spark.sql.catalyst.expressions.Literal$$anonfun$create$2.apply(literals.scala:163)
at org.apache.spark.sql.catalyst.expressions.Literal$$anonfun$create$2.apply(literals.scala:163)
at scala.util.Try.getOrElse(Try.scala:79)
at org.apache.spark.sql.catalyst.expressions.Literal$.create(literals.scala:162)
at org.apache.spark.sql.functions$.typedLit(functions.scala:113)
at org.apache.spark.sql.functions$.lit(functions.scala:96)
at org.apache.spark.sql.Column$$anonfun$isin$1.apply(Column.scala:787)
at org.apache.spark.sql.Column$$anonfun$isin$1.apply(Column.scala:787)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:35)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
at scala.collection.AbstractTraversable.map(Traversable.scala:104)
at org.apache.spark.sql.Column.isin(Column.scala:787)
... 52 elided
``` | 2019/06/12 | [
"https://Stackoverflow.com/questions/56565986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9272452/"
] | You could use the except method on dataframe.
```
var df = Seq("119.73.148.227", "42.61.124.218", "42.61.66.174", "118.201.94.2","118.201.149.146", "119.73.234.82", "42.61.110.239", "58.185.72.118", "115.42.231.178").toDF("ipAddress")
var lista = Seq("119.73.148.227", "118.201.94.2").toDF("ipAddress")
var onlyWantedIp = df.except(lista)
``` |
316,791 | I am getting the following error when I try to connect to a Minecraft server:
[![Connection refused: no further information](https://i.stack.imgur.com/31C7S.jpg)](https://i.stack.imgur.com/31C7S.jpg)
This is all servers, not just one.
The error says:
>
> io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information:
>
>
> Version 1.12
>
>
>
I've tried:
* Restarting Minecraft
* Restarting Computer
* Uninstalling and Reinstalling Mincraft
* Uninstalling and Reinstalling Java
* Altering Firewall
* Restarting Internet
* I've messed with my port, made a second windows account, reset netsh winsock
* Checked hosts
* Made a new WINDOWS account
The overlay in the bottom right is Geforce's Overlay for game capturing. I don't have any mods installed.
A Mojang support ticket wouldn't help. Im desperate. | 2017/08/23 | [
"https://gaming.stackexchange.com/questions/316791",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/195593/"
] | I have the same error on my local network, it looks like a firewall issue on the host/server side. For me, to troubleshoot I used [nmap](https://nmap.org/). The LAN game showed up in multiplayer as 10.0.0.21:49299. nmap reported that port from that IP as closed/filtered; i.e. a firewall issue.
To confirm it is a firewall issue, [turn off the firewall](https://www.howtogeek.com/242375/how-to-troubleshoot-minecraft-lan-game-problems/) (momentarily). See if you're able to connect while the firewall is disabled. |
20,848,810 | I've read many articles and posts about executing NAnt scripts using TFS build, none of which have satisfied my needs.
I have a NAnt script that has been developed over the years to automatically build, test and deploy our websites to an internal staging and external demo environments.
Usually, the team has been so small that builds have been a manual process. The intention had always been to integrate this script into a CI environment.
Recently, we switched our source control to TFS 2012 with the aim of using TFS build with our existing NAnt script.
From what I can see so far, it is possible to execute a NAnt script with TFS build, but it is not possible to not specify a .sln file for TFS build to build first when creating a new build definition.
Ideally, I want NAnt to control the entire build/test/deploy process and for TFS Build to just butt out and just utilise the Checkin triggers TFS provides to trigger the NAnt build.
I've played with the idea of writing my own TFS checkin interceptor. Has anyone else solved this problem already?
Many thanks
Could anyone answering please stick the specific question being asked and not deviate by suggesting alternate (paid for or not) CI tools such as CCNet or TeamCity.
Cheers | 2013/12/30 | [
"https://Stackoverflow.com/questions/20848810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767428/"
] | Here is how you can do it:
1) Download Nant.exe from <http://sourceforge.net/projects/nant/files/> and check-in the bin directory which has Nant.exe.
2) Create a msbuild file (say msbuild.proj) with following code(change Path) and check-in the file.
```
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="RunNant">
<Exec Command="bin\nant.exe; -buildfile:master.build build"/>
</Target>
</Project>
```
3) Go to Process tab in your build definition and then go to "Items to Build" --> "Projects to Build" --> Select(icon on the right) --> Add --> Change "Items of type" to "MSBuild project files" and then select the .proj file you checked-in.
![enter image description here](https://i.stack.imgur.com/weDyk.png)
4) Run your build and it should work. See below log that shows that it ran the Nant build file.
```
Build started 12/31/2013 4:55:20 AM.
Project "C:\a\src\F\Test Projects\TestProject\msbuild.proj" on node 1 (default targets).
RunNant:
bin\nant.exe; -buildfile:master.build build
NAnt 0.92 (Build 0.92.4543.0; release; 6/9/2012)
Copyright (C) 2001-2012 Gerry Shaw
http://nant.sourceforge.net
Buildfile: file:///C:/a/src/F/Test Projects/TestProject/master.build
Target framework: Microsoft .NET Framework 4.0
Target(s) specified: ; build
[solution] Starting solution build.
``` |
36,294,466 | UDF:
```
bigquery.defineFunction(
'newdate', // Name of the function exported to SQL
[], // Names of input columns
[
{name: 'date', type: 'timestamp'}
, {name: 'datestr', type: 'string'}
],
function newDate(row, emit) {
var date = new Date(); // current date and time
emit({
date: date
, datestr: date + ''
});
}
);
```
SQL:
```
SELECT date, datestr
FROM (newDate(SELECT "ignored" AS inputA))
```
Output:
```
1459282876835809 Tue Mar 29 2016 13:21:16 GMT-0700 (PDT)
``` | 2016/03/29 | [
"https://Stackoverflow.com/questions/36294466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2259571/"
] | That's an unfortunate oversight on our part.
Many Google servers run using Pacific time (semi-jokingly referred to as "Google standard time"). When launching BigQuery, we tried to standardize on UTC instead, but we missed this case. We may try to find an opportunity to fix it, but unfortunately we risk breaking existing users if we do so, so no promises.
Thanks for the heads up! |
62,753,397 | I write button.xml and qweb in **manifest**.py but it not worked.
button.xml (static/src/xml/button.xml)
```
<?xml version="1.0" encoding="UTF-8"?>
<templates>
<t t-extend="ListView.buttons">
<t t-jquery="button.o_list_button_add" t-operation="after">
<button name="xxx" type="button" t-if='widget.modelName == "billing.info.functions"'
class="btn btn-sm btn-default o_import_button o_import_import">Upload
</button>
</t>
</t>
</templates>
```
**manifest**.py
```
'qweb': [
"static/src/xml/button.xml"
],
``` | 2020/07/06 | [
"https://Stackoverflow.com/questions/62753397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13876116/"
] | The first thing I notice is that you are iterating through `i in range(0, int(pages))`, however, the pages only start on line 1 (line 0 consists of n & q).
So your for loop should like more like (you also want to do +1 because you want to count the last page, otherwise python only goes 'uptil but not including'):
```py
for i in range (1, pages + 1):
words = int(file.readline().strip())
```
Here, we are putting the .strip() function so that we don't get an error while converting this to an int. By default, text files have `\n` (enter characters) at the end of each line and python doesn't understand the meaning of `int("5\n")`. The strip() function helps get rid of the enter character and any trailing 'whitespaces'.
Now, you would want to store the number of words per line somewhere, and for this you can either use a dictionary (<https://www.w3schools.com/python/python_dictionaries.asp>), or a list.
List indices start at 0, but the line with the number of words per page starts at 1 and even though you could get away with using lists, dictionaries would be more intuitive.
```py
words_per_page = {}
```
You can look at the link I have provided to understand how these work. We can then add the words to the dictionary:
```py
for i in range (1, int(pages) + 1):
number_of_words = int(file.readline().strip())
words_per_page[i] = number_of_words
```
Then, you can iterate through each line with the questions. Here, we start the for loop at the line just after the line where the number of words per page ends:
```py
all_questions = []
for question_index in range(pages + 2, 1 + pages + questions):
all_questions.append(file.readline().strip())
```
From this, you will get 1 dictionary of the page number as the key and words per page as the value and a list with all the questions. Then you could iterate through these and get the number of words in the pages:
```py
for page_number in all_questions:
no_of_words = words_per_page[int(page_number)]
# You can then store this variable somewhere or write to a text file
```
Now, I haven't tested any of this code, but the idea behind everything is the same. If you do get any errors, make sure to leave a comment. |
69,139,132 | I'm using the weightloss dataset:
```
structure(list(id = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L), .Label = c("1", "2",
"3", "4", "5", "6", "7", "8", "9", "10", "11", "12"), class = "factor"),
diet = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("no", "yes"), class = "factor"),
exercises = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("no", "yes"
), class = "factor"), t1 = c(10.43, 11.59, 11.35, 11.12,
9.5, 9.5, 11.12, 12.51, 11.35, 11.12, 11.12, 10.2, 11.12,
9.96, 12.05, 8.11, 12.05, 12.05, 12.28, 10.66, 11.35, 10.2,
10.2, 9.5, 10.2, 12.98, 13.21, 10.2, 11.59, 12.05, 11.59,
12.05, 11.82, 11.12, 12.51, 11.59, 10.43, 11.35, 11.82, 10.2,
13.67, 10.66, 10.2, 12.05, 11.82, 10.43, 12.74, 11.35), t2 = c(13.21,
10.66, 11.12, 9.5, 9.73, 12.74, 12.51, 12.28, 11.59, 10.66,
13.44, 11.35, 12.51, 12.74, 13.67, 14.37, 14.6, 12.98, 12.05,
14.37, 14.6, 11.82, 14.13, 13.21, 12.51, 12.98, 11.12, 9.73,
13.44, 13.67, 12.98, 11.35, 12.05, 15.29, 11.82, 12.05, 12.51,
14.83, 13.9, 13.21, 14.13, 15.06, 12.98, 11.35, 12.51, 14.13,
12.74, 11.35), t3 = c(11.59, 13.21, 11.35, 11.12, 12.28,
10.43, 11.59, 12.74, 9.96, 11.35, 10.66, 11.12, 15.76, 16.68,
17.84, 14.6, 17.84, 17.61, 18.54, 16.91, 15.52, 17.38, 19,
14.13, 14.6, 14.6, 12.05, 15.52, 13.9, 12.74, 13.21, 14.83,
14.6, 10.89, 15.52, 12.98, 14.37, 15.06, 13.44, 14.13, 15.29,
14.6, 15.06, 15.52, 13.9, 14.37, 15.06, 15.06)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -48L))
```
So far it looks like at least here I can separate the scores:
```
weight <- weightloss
summary <- weight %>%
get_summary_stats(type = "mean_sd")
summary
```
Which gives me this:
```
A tibble: 3 x 4
variable n mean sd
<chr> <dbl> <dbl> <dbl>
1 t1 48 11.2 1.09
2 t2 48 12.7 1.42
3 t3 48 14.2 2.26
```
I'm trying to run a RMANOVA on this, but I would like to get a boxplot for every one of the three groups, all in a single plot. However, I'm not sure how to plot the x and y in this case. I tried using this for the x:
```
trial_type <- c("t1","t2","t3")
factor(trial_type)
```
But thats where I'm stuck...I'm not sure how you get the y in this case. The y is clearly the scores from each trial. I tried grouping by this factor to see if that would sort out the scores in some way, but I haven't figured that out either.
I'm just not sure how you plot this into ggplot. Any help would be great! I can imagine this is a very useful skill to learn for any data that uses trials. | 2021/09/11 | [
"https://Stackoverflow.com/questions/69139132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16631565/"
] | ```
Icon(
Icons.add_circle_outline,
color: Colors.white,
size: 30,
),
```
You can use flutter built in icon. |
39,559,845 | I have the following transaction:
```
typedef enum {READ = 0, WRITE = 1} direction_enum;
//Transaction
class axi_transaction extends uvm_sequence_item();
bit id = 0; //const
bit [31:0] addr;
bit [2:0] size = 0'b100;//const
direction_enum rw;
bit [31:0] transfers [$];
//factory registration
`uvm_object_utils_begin(axi_transaction)
`uvm_field_int(id, UVM_ALL_ON)
`uvm_field_int(addr, UVM_ALL_ON)
`uvm_field_int(size, UVM_ALL_ON)
`uvm_field_enum(rw, UVM_ALL_ON)
`uvm_field_int(transfers, UVM_ALL_ON)
`uvm_object_utils_end
//constructor
function new(string name = "axi_transaction");
super.new(name);
endfunction: new
endclass: axi_transaction
```
I want to extend the new function, so I can initializes the transaction in the sequence with arguments which initialize some of the transaction members (like addr, transfers) by:
```
ax_trx = axi_transaction::type_id::create();
```
How to write the constructor of the transaction and how do I initialize the transaction from the sequencer? | 2016/09/18 | [
"https://Stackoverflow.com/questions/39559845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6465067/"
] | You cannot add arguments to the class constructor when using the UVM factory. In general this is not good OOP programing practice for re-use because if you do add arguments to either the base class or extended class, you have to modify every place where the class gets constructed.
A better option is to use the uvm\_config\_db or set the individual fields you need to after constructing the object.
```
ax_trx = axi_transaction::type_id::create();
ax_trx.addr = some_address
ax_trx.transfers = '{word1,word2,word3};
``` |
61,717,941 | I have configured the connection to IBM MQ using application properties. As below,
```
ibm.mq.conn-name=localhost(1415)
ibm.mq.queue-manager=QMGR
ibm.mq.channel=QMGR.SVR.CON.C
ibm.mq.user=xxxxx
ibm.mq.password=xxxxx
```
I have class annotated @service which has method as below that reads messages from queue,
```
@Service
public class JMSService {
@Inject
private JmsTemplate queueTemplate;
public JmsMessageBean readMessage(String responseQueueName, Logger logger) throws JMSException, Exception {
JmsMessageBean bean = new JmsMessageBean();
MQQueue queue = new MQQueue(responseQueueName);
queue.setTargetClient(WMQConstants.WMQ_CLIENT_NONJMS_MQ);
queueTemplate.setReceiveTimeout(JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT);
Message message = queueTemplate.receive(queue);
if(message!=null){
String jmsCorrelationID = hexStringToByteArrayToString(message.getJMSCorrelationID());
bean.setJmsCorrelationID(jmsCorrelationID);
bean.setMessage(message.getBody(Object.class));
bean.setJmsMessageID(message.getJMSMessageID());
}
return bean;
}
}
```
and i m running a scheduler at fixedRate of 50milliseconds and calling above method in the scheduler,
```
@Component
public class QueueConnectionService{
@Scheduled(fixedRate = 50)
public void connectQueueManager() {
JmsMessageBean bean = null;
int umacIndex;
String body = "";
try {
bean = jmsService.readMessage(env.getProperty("inwardQueueName"), inwardqueue);
if (bean != null && bean.getMessage() != null) {
String messagetxt = "";
if (bean.getMessage().getClass().getSimpleName().equals("String")) {
messagetxt = (String) bean.getMessage();
} else {
byte[] messagebytes = (byte[]) bean.getMessage();
messagetxt = new String(messagebytes);
}
umacIndex = messagetxt.indexOf("{UMAC:");
if (umacIndex > 0)
message = messagetxt.substring(0, umacIndex);
else
message = messagetxt;
//sending this message to further processing
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
This is working but I m sure this is not the right and efficient way to read messages from queue and probably wrong implementation when there can be large amount messages. And the spring TaskSchedulerPool will be overloaded as there are other data migration schedulers. Please verify and suggest me efficient methods in reading messages from IBM MQ. thank you. | 2020/05/10 | [
"https://Stackoverflow.com/questions/61717941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9180615/"
] | As @JoshMc suggested, you should use a `JmsListener`.
There is good [JMS Getting Started Guide](https://spring.io/guides/gs/messaging-jms/) from Spring. For you it will look like this (definition for `myFactory` you can see in the mentioned Spring guide):
```
package hello;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class Receiver {
@JmsListener(destination = "${inwardQueueName}", containerFactory = "myFactory")
public void receiveMessage(javax.jms.Message message) throws javax.jms.JMSException {
String messagetxt = "";
if (message instanceof javax.jms.TextMessage) {
messagetxt = message.getBody(String.class);
}
...
}
}
``` |
30,223,119 | I would like to know how to create a clickable button in HTML format that sits on in the center of a header image.
I have tried to use the button tags along with the href attribute along with the img tags to try to wrap the code around the desired image but it doesn't work. An example of the result that I am trying to achieve can be found in the header on [github.com](http://github.com). | 2015/05/13 | [
"https://Stackoverflow.com/questions/30223119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4897118/"
] | You need to call `WebView.enableSlowWholeDocumentDraw()` before creating *any* WebViews in your app.
That is, if you have a WebView somewhere in your static layout, make sure you call `WebView.enableSlowWholeDocumentDraw()` before your first call to `setContentView()` that inflates a layout with WebView.
Also make sure that your WebView is indeed big. For example, if its layout size is set to `match_parent`, then your WebView will have the size of the screen, and this is what will be captured. You need to set some artificially high values for width and height. This question contains a nice illustration for that: [WebView.draw() not properly working on latest Android System WebView Update](https://stackoverflow.com/questions/30078157/webview-draw-not-properly-working-on-latest-android-system-webview-update) |
3,130,701 | How to kill a running thread in java | 2010/06/28 | [
"https://Stackoverflow.com/questions/3130701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/297115/"
] | You can ask the thread to interrupt, by calling [`Thread.interrupt()`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#interrupt%28%29)
Note that a few other methods with similar semantics exist - `stop()` and `destroy()` - but they are *deprecated*, because they are [unsafe](http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html). Don't be tempted to use them. |
36,425,945 | I want to display picture from access and show that on a form in vb.net
I have this for display information:
```
info.TextBox5.Text = DataGridView1.SelectedRows(0).Cells(5).Value
```
Now I tried something like this for pictures:
```
info.PictureBox1.Image = DataGridView1.SelectedRows(0).Cells(6).Value
```
But I got an error:
>
> Can not associate the type of Object ' System.Byte []' to type '
> System.Drawing.Image ' .
>
>
>
Can you help me? | 2016/04/05 | [
"https://Stackoverflow.com/questions/36425945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5433094/"
] | Based on Google Maps [docs](https://developers.google.com/maps/faq#usage-limits):
>
> Excess usage over the complimentary quota for each Google Maps API
> service is calculated at the end of each day.
>
>
> Web service APIs offer 2,500 free requests per day. If you enable
> billing to access higher quotas, once you exceed 2,500 requests in a
> day, you will be billed $0.50 USD / 1,000 additional requests, up to
> 100,000 daily.
>
>
> The Google Maps JavaScript API, Google Static Maps API, and Google
> Street View Image API offer 25,000 free map loads per day. If your
> site generates excess usage every day for 90 consecutive days, Google
> will attempt to contact you with information about payment options.
>
>
> Learn more about what happens if you exceed the usage limits.
>
>
> If you chose to enable billing you will need to provide your credit
> card details. Your excess usage will continue to be calculated at the
> end of each day, and the total charged to the credit card provided at
> the end of every month, priced as given below.
>
>
>
So, unsless you want to hack Google, who is owner of this forum, the answer is no. |
163 | I was tasked with figuring out whether carbon or nitrogen has a more negative electron affinity value. I initially picked nitrogen, just because nitrogen has a higher $Z\_\mathrm{eff}$, creating a larger attraction between electrons and protons, decreasing the radius, causing a higher ionization energy, and therefore decreasing the electron affinity value, but I was actually wrong, and the solutions manual explains it as this:
>
> "As you go from C to N across the Periodic Table you would normally expect N to have the more negative electron affinity. However, N has a half-filled p subshell, which lends it extra stability; therefore, it is harder to add an electron."
>
>
>
Are there any major exceptions to the rules when comparing electron affinity? I'm hesitant to use nitrogen as an exception, because I don't know how far it extends. If nitrogen has a more positive EA than carbon, does that also extend to boron, aluminium, or phosphorus?
I later found that this also applies when comparing silicon and phosphorus. The explanation given was the same.
What exceptions should be noted when comparing electron affinities? Are there any at all? And how far does the exception with atoms with half-filled p subshells extend? | 2012/04/29 | [
"https://chemistry.stackexchange.com/questions/163",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/85/"
] | This exception rule is actually orbital filling rule. For two electrons to be in same orbital they need to have different spins (Pauli exclusion principal). This electron pairing requires additional energy and thus it is easier to add electrons if there are free orbitals. When element has a half-filled p sublevel all 3 orbitals have one electron and pairing takes place (difference between energy levels of 2p and 3s is greater than electron pairing energy).
Electron pairing effects have significant impact to physical properties of coordination complexes (like color and magnetic properties). |
36,105,068 | I am currently learning Meteor and I found out something that intrigued me.
I can load HTML and CSS assets from a JS file using the import statement.
```
import '../imports/hello/myapp.html';
import '../imports/hello/myapp.css';
import * as myApp from '../imports/hello/myapp.js';
```
This was a surprise to me so I ran to google but could not find this behavior documented in the specification for ES6 `import` or in Meteor's Docs.
So my questions are:
* Can I rely on this behavior to build my apps?
* Will my app will break when Meteor gets around to fix it -- if it's a bug --?
**Notes**
* I am using Meteor v1.3, not sure if this works also with previous versions.
* You can download the app to see this behavior from [Github](https://github.com/pgpbpadilla/meteor-playground/tree/so-es6-meteor-import-bounty) | 2016/03/19 | [
"https://Stackoverflow.com/questions/36105068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/400544/"
] | After going through the implementation of the built files for my app
I found out why this works.
**HTML**
Files are read from the file system and their contents added to the global Template object, e.g.,
```
== myapp.html ==
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
</body>
```
results in the following JS code:
```
Template.body.addContent((function () {
var view = this;
return [
HTML.Raw("<h1>Welcome to Meteor!</h1>\n\n "),
Spacebars.include(view.lookupTemplate("hello"))
];
}));
```
Which is wrapped in a function with the name of the file as it's key:
```
"myapp.html": function (require, exports, module) {
Template.body.addContent((function () {
var view = this;
return [
HTML.Raw("<h1>Welcome to Meteor!</h1>\n\n "),
Spacebars.include(view.lookupTemplate("hello"))];
}));
Meteor.startup(Template.body.renderToDocument);
Template.__checkName("hello");
Template["hello"] = new Template("Template.hello", (
function () {
var view = this;
return [
HTML.Raw("<button>Click Me</button>\n "),
HTML.P("You've pressed the button ",
Blaze.View("lookup:counter",
function () {
return Spacebars.mustache(view.lookup("counter"));
}), " times.")
];
}));
},
```
So all of our HTML is now pure JS code which will be included by using `require` like any other module.
**CSS**
The files are also read from the file system and their contents are embedded also in JS functions, e.g.
```
== myapp.css ==
/* CSS declarations go here */
body {
background-color: lightblue;
}
```
Gets transformed into:
```
"myapp.css": ["meteor/modules", function (require, exports, module) {
module.exports = require("meteor/modules").addStyles("/* CSS declarations go here */\n\nbody {\n background-color: lightblue;\n}\n");
}]
```
So all of our CSS is also now a JS module that's again imported later on by using `require`.
**Conclusion**
All files are in one way or another converted to JS modules that follow similar rules for inclusion as AMD/CommonJS modules.
They will be included/bundled if another module refers to them. And since all of them are transformed to JS code
there's no magic behind the deceitful syntax:
```
import '../imports/hello/myapp.html';
import '../imports/hello/myapp.css';
```
They both are transpiled to their equivalent forms with `require` once the assets have been transformed to JS modules.
Whereas the approach of placing static assets in the `imports` directory is not mentioned in the official documentation,
this way of importing static assets works.
This seems to be at the core of how Meteor works so I'd bet this functionality is going to be there for a long while.
I don't know if to call this a feature maybe a more appropriate description is unexpected consequence but that would
only be true from the user's perspective, I assume the people who wrote the code understood this would happen and perhaps even
designed it purposely this way. |
3,852,932 | I am working application in which i calling `presentModalViewController` and once finished(calling `dismissModalViewControllerAnimated:YES`) it should immediately call `popToRootViewControllerAnimated`.
But the issue is `dismissModalViewControllerAnimated:YES` is working properly but `popToRootViewControllerAnimated`is not working after it.
The code is shown below:
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
[self.navigationController popToRootViewControllerAnimated:YES];
``` | 2010/10/04 | [
"https://Stackoverflow.com/questions/3852932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384150/"
] | Try something like this:
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
[self performSelector:@selector(patchSelector) withObject:nil afterDelay:0.3];
-(void)patchSelector{
[self.navigationController popToRootViewControllerAnimated:YES];
}
```
It is not so neat but it should work.
**UPDATE:**
You should use
```
[self dismissModalViewControllerAnimated:YES];
```
instead
```
[self.navigationController dismissModalViewControllerAnimated:YES] ;
```
The object that is presenting the modal is the view controller, not the navigation controller. |
58,369,989 | Need help passing state as a prop to another state component. I'm very new to React and I'm not sure what I'm doing wrong. When I console.log inside the Timer component it displays undefined but when I console.log in the Main component it displays the object perfectly.
```
class Main extends React.Component {
constructor() {
super()
this.state = {
isLoaded: false,
itemsP:{}
}
}
componentDidMount() {
fetch("https://api.spacexdata.com/v3/launches/next")
.then(response => response.json())
.then(
(resData) =>
this.setState({
isLoaded: true,
itemsP: resData
})
)
}
render() {
console.log(this.state.itemsP) //this will console.log the object from the api
return (
<main>
<Timer nextLaunch={this.state.itemsP} />
</main>
)
}
}
//Timer component
class Timer extends React.Component{
constructor(props) {
super(props)
this.state = {
nextDate: props.nextLaunch.launch_date_utc
}
}
render() {
console.log(this.state.nextDate) //will console log UNDEFINED why is this?
return (
<div>
//display something....
</div>
)
}
}
```
[here](https://docs.spacexdata.com/?version=latest#c75a20cf-50e7-4a4a-8856-ee729e0d3868) is the link for the API that I'm using for reference. | 2019/10/14 | [
"https://Stackoverflow.com/questions/58369989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6383688/"
] | @tlrmacl might have answered it there. It's missing the `this` keyword. In theory, you might be assigning the initial value still to the state.
It is due to how react lifecycle works
On your `componentDidMount()`, you are calling setState after the jsx gets mounted to the DOM. `this.state.itemsP` is given an initial value of `{}` then after the mount, it will receive its new value from `comopnentDidMount()`
Inside your `Timer` component, you are assigning the first value of `this.props.nextLaunch` to a new state. It doesn't have the chance to update the value. Instead of doing this:
```
this.state = {
nextDate: props.nextLaunch.launch_date_utc
}
```
use `props.nextLaunch.launch_date_utc` directly:
```
console.log(props.nextLaunch.launch_date_utc)
```
For more information check out this tweet by Dan Abramov [here](https://twitter.com/dan_abramov/status/981712092611989509) |
52,436,015 | I'm trying to mimic the Web Audio API multitrack demo from the 'Mozilla Web Audio API for games' Web doc.
<https://developer.mozilla.org/en-US/docs/Games/Techniques/Audio_for_Web_Games#Web_Audio_API_for_games>
The only caveat I have is that I want the previous track to stop, once a new track is clicked (instead of playing layered on top of each other).
An example would be, click drums, the drums start playing, then click guitar, the drums stop and the guitar starts right where the drums left off.
Any ideas? Are there better tools/libraries for handling web audio?
<http://jsfiddle.net/c87z11jj/1/>
```
<ul>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-leadguitar.mp3">Lead Guitar</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-drums.mp3">Drums</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-bassguitar.mp3">Bass Guitar</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-horns.mp3">Horns</a></li>
<li><a class="track" href="http://jPlayer.org/audio/mp3/gbreggae-clav.mp3">Clavi</a></li>
</ul>
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var offset = 0;
var context = new AudioContext();
function playTrack(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
var audiobuffer;
// Decode asynchronously
request.onload = function() {
if (request.status == 200) {
context.decodeAudioData(request.response, function(buffer) {
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
console.log('context.currentTime '+context.currentTime);
if (offset == 0) {
source.start();
offset = context.currentTime;
} else {
source.start(0,context.currentTime - offset);
}
}, function(e) {
console.log('Error decoding audio data:' + e);
});
} else {
console.log('Audio didn\'t load successfully; error code:' + request.statusText);
}
}
request.send();
}
var tracks = document.getElementsByClassName('track');
for (var i = 0, len = tracks.length; i < len; i++) {
tracks[i].addEventListener('click', function(e){
console.log(this.href);
playTrack(this.href);
e.preventDefault();
});
}
``` | 2018/09/21 | [
"https://Stackoverflow.com/questions/52436015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10241361/"
] | Simply store the BufferSources somewhere in the outer scope and then call their `stop()` method.
I took the liberty to rewrite a bit your loading logic, you shouldn't create a new request every time you start a new track, in that case you loose the main advantages of AudioBuffers against Audio element: they're truly fast to instantiate.
```js
var active_source = null;
function stopActiveSource() {
if (active_source) {
active_source.onended = null; // manual stop, no event
active_source.stop(0);
}
}
// instead of requesting a new ArrayBuffer every time
// store them in a dictionnary
var buffers = {};
var context = new(window.AudioContext || window.webkitAudioContext)();
function playTrack(url) {
// get fom our dictionnary
var buffer = buffers[url];
// stop the active one if any
stopActiveSource();
// create a new BufferSource
var source = context.createBufferSource();
// it is now the active one
active_source = source;
source.onended = function() {
active_source = null;
};
source.buffer = buffer;
source.connect(context.destination);
source.start(0);
}
// start by getting all AudioBuffers
var tracks = document.getElementsByClassName('track');
for (var i = 0, len = tracks.length; i < len; i++) {
tracks[i].addEventListener('click', function(e) {
playTrack(this.href);
e.preventDefault();
});
getBuffer(tracks[i].href);
}
function getBuffer(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function(evt) {
context.decodeAudioData(request.response, store);
};
request.send();
function store(buffer) {
buffers[url] = buffer;
}
}
```
```html
<base href="https://dl.dropboxusercontent.com/s/">
<ul>
<li><a class="track" href="kbgd2jm7ezk3u3x/hihat.mp3">HiHat</a></li>
<li><a class="track" href="h2j6vm17r07jf03/snare.mp3">Snare</a></li>
<li><a class="track" href="1cdwpm3gca9mlo0/kick.mp3">Kick</a></li>
<li><a class="track" href="h8pvqqol3ovyle8/tom.mp3">Tom</a></li>
</ul>
``` |
34,538,571 | I am trying run cucumber tests using maven with following command
```
mvn test -Dcucumber.options="--tag @debug1"
```
This command works fine, however if i try something like following, i get error
```
mvn test -Dcucumber.options="--tag @debug1 @debug2"
```
Is there a way to pass in multiple tag names with cucumber run-time options? | 2015/12/30 | [
"https://Stackoverflow.com/questions/34538571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3062121/"
] | * To run scenarios with `@debug1` and `@debug2`:
**Old version of Cucumber-jvm:**
```
mvn test -Dcucumber.options="--tags @debug1 --tags @debug2"
```
**Actual version of Cucumber-jvm:**
```
mvn test -Dcucumber.options="--tags '@debug1 and @debug2'"
```
* To run scenarios with `@debug1` or `@debug2`:
**Old version of Cucumber-jvm:**
```
mvn test -Dcucumber.options="--tags @debug1,@debug2"
```
**Actual version of Cucumber-jvm:**
```
mvn test -Dcucumber.options="--tags '@debug1 or @debug2'"
``` |
9,803,396 | I am looking for a lightweight, reliable and fast key/value database for storing binary data. Simple without server. Most of popular key/value databases like CDB and BerkeleyDB does not natively store `BLOB`. What can be the best choice that I missed?
My current choice is SQLite, but it is too advanced for my simple usage. | 2012/03/21 | [
"https://Stackoverflow.com/questions/9803396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943340/"
] | As it was previously pointed out, BerkeleyDB does support opaque values and keys, but I would suggest a better alternative: LevelDB.
**LevelDB:**
Google is your friend :), so much so that they even provide you with an embedded database: [A fast and lightweight key/value database library by Google.](https://github.com/google/leveldb)
**Features:**
* Keys and values are arbitrary byte arrays.
* Data is stored sorted by key.
* Callers can provide a custom comparison function to override the sort order.
* The basic operations are Put(key,value), Get(key), Delete(key).
* Multiple changes can be made in one atomic batch.
* Users can create a transient snapshot to get a consistent view of data.
* Forward and backward iteration is supported over the data.
* Data is automatically compressed using the Snappy compression library.
* External activity (file system operations etc.) is relayed through a virtual interface so users can customize the operating system interactions.
* Detailed documentation about how to use the library is included with the source code. |
2,225,263 | Suppose I have a simple table, like this:
```
Smith | Select
Jones | Select
Johnson | Select
```
And I need to write a Selenium test to select the link corresponding to Jones. I can make it click the "Select" in the 2nd row, but I would rather have it find where "Jones" is and click the corresponding "Select". I'm thinking I may need to incorporate JQuery to accomplish this? | 2010/02/08 | [
"https://Stackoverflow.com/questions/2225263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16012/"
] | Use an xpath expression like "//tc[.//text() = 'Jones']/../tc[2]/a" which looks for a table cell whose text contents are 'Jones' and then naviagates up to that cells parent, selects the second table cell of that parent, and then a link inside the second table cell. |
117,095 | **Your task:**
Find the most efficient mowing path around the dark green bushes that mows (passes over) all of the grass (light green).
[![enter image description here](https://i.stack.imgur.com/hSmSr.png)](https://i.stack.imgur.com/hSmSr.png)
---
For those who cannot view the image above, there are 9 rows of 16, as follows:
```
- dark squares signify grass
- stars signify bushes
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
■ * * * * ■ ■ * * * ■ * * * * ■
■ * ■ ■ * ■ * ■ ■ ■ ■ * ■ ■ ■ ■
■ * ■ ■ * ■ ■ * ■ ■ ■ * ■ ■ ■ ■
■ * ■ * * ■ ■ ■ ■ ■ ■ ■ ■ * * ■
■ * ■ ■ ■ ■ ■ ■ * ■ ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ ■ ■ ■ * ■ * ■ ■ ■ ■
■ * ■ ■ ■ ■ * * * ■ ■ * * * * ■
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
```
---
**Rules:**
1. The mower can move only horizontally and vertically.
2. "Efficient" means the fewest number of total moves made.
3. You can start from any square you pick.
4. You must stay in bounds and cannot mow over, under, or through any bushes.
"Efficient" can also be thought of as minimizing the number of squares that are mowed more than once.
**Example:**
Here is an example of a 128-move mowing:
* orange squares mowed twice, red square mowed 3 times
* squares mowed more than once remain marked with their original number
[![enter image description here](https://i.stack.imgur.com/El9Gp.png)](https://i.stack.imgur.com/El9Gp.png)
---
For those who cannot view images:
```
- *** signifies a bush
- ### signifies the order mowed
- squares mowed more than once remain marked with their original number
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016
128 *** *** *** *** 073 074 *** *** *** 056 *** *** *** *** 017
127 *** 093 094 *** 072 *** 060 059 058 055 *** 037 038 039 018
126 *** 092 095 *** 071 070 *** 062 063 054 *** 036 041 040 019
125 *** 091 *** *** 078 069 068 067 064 033 034 035 *** *** 020
124 *** 090 089 088 079 080 081 *** 065 032 *** 044 045 046 021
123 *** 099 100 087 086 085 082 083 *** 031 *** 049 048 047 022
122 *** 118 101 102 103 *** *** *** 109 030 *** *** *** *** 023
121 120 117 116 115 104 105 106 107 108 029 028 027 026 025 024
```
---
There are 106 squares to be mowed, however, the optimal score is greater than 106.
**If your answer uses less moves than the lowest-move answer so far AND you suspect it could be optimal, then post it!**
**Otherwise, please don't post it**, even if it is significantly different than any other answer posted. The idea behind this request is to prevent answers that do not trend toward the optimal solution. | 2022/07/15 | [
"https://puzzling.stackexchange.com/questions/117095",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/463/"
] | >
> **Optimal : 111 moves**
>
>
>
> [![enter image description here](https://i.stack.imgur.com/cqYPf.png)](https://i.stack.imgur.com/cqYPf.png)
>
>
>
> [Visual of path](https://i.stack.imgur.com/WiFNJ.png)
>
>
>
Others of the same length exist, such as [this](https://i.stack.imgur.com/8daZH.png), [this](https://i.stack.imgur.com/fr6Av.png) and [SQLNoob's](https://puzzling.stackexchange.com/a/117100/18250), and several more.
---
Proof of optimality (see [FlorianF's](https://puzzling.stackexchange.com/a/117101/18250) for a more concrete proof:
>
> This problem can be split up in to certain areas, conveniently around the P, S and E, and we can deal with 'entrances' and 'exits'.
>
>
>
> [![enter image description here](https://i.stack.imgur.com/eF2t2.png)](https://i.stack.imgur.com/eF2t2.png)
>
>
>
> We must start in the P or the yellow squares would all have to be covered twice. Starting elsewhere may save 1/2, but would cost 3, whereas starting in the P saves 3, and costs 1.
>
>
>
> We must also end on a red square (you can technically end in several places in the E, [such as in the middle](https://i.stack.imgur.com/8daZH.png), but they all have the same result and just navigate the E slightly differently) as ending elsewhere will cause massive costs around the top/bottom of the E.
>
>
>
> The blue squares are always a +2, which is obvious as we are starting in the P.
>
>
>
> Now the pink squares are less obvious, but they best way to cover them is to dip in and out of them for a +3. By cutting through them you enter the edge, and no matter how you re-enter the inside areas, you will create a new isolated area that is more than +3 to cover, as no length along the edge is shorter than +3, they are all minimum 5 squares.
>
>
>
> So optimal paths that start in the P, dip in and out of the pinks for a +3, take the unavoidable +2 on the blues, and finish in the E can have a best score of **111 moves**
>
>
>
TL;DR:
>
> An optimal path must start inside the P and finish around one of the red squares at the end of the E. The blue squares in the S are then always a +2, and a +3 arises from dipping in and out of the pinks meaning that 111 is optimal
>
>
> |
135,851 | Related to [Poker Hand Evaluator](https://codereview.stackexchange.com/questions/135649/poker-hand-evaluator). This it **not** the same. This is take best from all combinations of 7. The other is all combinations of 5.
Poker is 52 cards - 4 suits and 13 ranks:
* Texas holdem
* Hand is exactly 5 cards
* Order of hands
+ Straight-flush
all same suite and in order
ace high is royal straight flush
+ Quad four of same rank
+ Boat three of one rank and two of another rank
+ Flush all the same suit
+ Straight e.g. 56789
ace 0 counts as both low and high 01234 and 9,10,11,12,0
+ Two pair
+ One pair
+ High card
There are 23,294,460 distinct 7 card combinations in a deck of 52. I am not interested in a random sampling (Monte Carlo). Will add the as on option later but need the option to run all and have the correct answer from wiki.
This program makes the best 5 cards hand from every combination of 7 and tallies. That is how a poker game works. You have 2 hole cards and then 5 cards on the board. You make the best 5 cards card had from you hole cards plus the board.
Combination of 7 is harder in there are a lot more combination. Cannot assume if you have a straight and a flush you have a straight-flush as they may not be the same 5 cards. This separates a royal straight flush from a straight flush but they can be combined into just straight flush if that is faster.
Not interested in parallel processing. Have a pattern for doing that. For this question just optimize the raw code.
This code gives the correct answers to [poker hand probability](https://en.wikipedia.org/wiki/Poker_probability). It runs in about 200 seconds.
How to optimize this code to run faster? Or make it cleaner and not run any slower.
```
public void Deal7c()
{
Stopwatch sw = new Stopwatch();
sw.Start();
int counter = 0;
int counterFlush = 0;
int counterStraight = 0;
int counterStraightFlush = 0;
int counterStraightAndFlush = 0;
int counterRoyalFlush = 0;
int counterQuad = 0;
int counterBoat = 0;
int counterTrips = 0;
int counterPairTwo = 0;
int counterPairOne = 0;
int counterHigh = 0;
Card[] CardArray = new Card[7]; // hand plus board
bool haveStraight;
bool haveQuad;
bool haveBoat;
bool haveFlush;
int flushSuite;
bool haveStraightFlush;
bool haveRoyalFlush;
int flushCount;
int straightCount;
int straightCount2;
bool haveAce;
int? lastRank;
int firstCard;
//byte* rankArray = stackalloc byte[13];
//byte* rankCount = stackalloc byte[5];
int[] rankArray = new int[13];
int[] rankCount = new int[5];
Debug.WriteLine("");
for (int i = 51; i >= 6; i--)
{
Debug.WriteLine("Deal7a i = " + i + " milliseconds " + sw.ElapsedMilliseconds.ToString("N0"));
CardArray[0] = new Card(i % 13, i / 13);
for (int j = i - 1; j >= 5; j--)
{
CardArray[1] = new Card(j % 13, j / 13);
for (int k = j - 1; k >= 4; k--)
{
CardArray[2] = new Card(k % 13, k / 13);
for (int l = k - 1; l >= 3; l--)
{
CardArray[3] = new Card(l % 13, l / 13);
for (int m = l - 1; m >= 2; m--)
{
CardArray[4] = new Card(m % 13, m / 13);
for (int n = m - 1; n >= 1; n--)
{
CardArray[5] = new Card(n % 13, n / 13);
for (int p = n - 1; p >= 0; p--)
{
CardArray[6] = new Card(p % 13, p / 13);
counter++;
//if (rand.Next(4) != 0)
// continue;
haveStraight = false;
haveFlush = false;
haveStraightFlush = false;
haveRoyalFlush = false;
haveBoat = false;
haveQuad = false;
for (int q = 0; q <= 12; q++)
rankArray[q] = 0;
for (int c = 0; c < 7; c++)
rankArray[CardArray[c].Rank]++;
// this will build up the rank count
rankCount[0] = 0; // none - not used but it needs to be here to make this work
rankCount[1] = 0; // single - not used but it needs to be here to make this work
rankCount[2] = 0; // pair
rankCount[3] = 0; // trips
rankCount[4] = 0; // quad
for (int c = 0; c <= 12; c++)
rankCount[rankArray[c]]++;
if (rankCount[4] == 1)
haveQuad = true;
else if (rankCount[3] == 2) // with 7 could have two trips
haveBoat = true;
else if (rankCount[3] == 1 && rankCount[2] > 0)
haveBoat = true;
if (!haveQuad && !haveBoat && rankCount[2] != 3) // cannot make a straight or flush with a quad or boat
{
// flush
flushSuite = -1;
for (int f = 0; f <= 3; f++)
{ // can only have one flush in 7 cards
flushCount = 0;
for (int c = 0; c < 7; c++)
{
if (CardArray[c].Suit == f)
flushCount++;
}
if (flushCount >= 5)
{
haveFlush = true;
flushSuite = f;
break;
}
}
//straight
//first ace high
haveStraight = rankArray[0] > 0 &&
rankArray[12] > 0 &&
rankArray[11] > 0 &&
rankArray[10] > 0 &&
rankArray[9] > 0;
if (!haveStraight)
{
for (int s = 12; s >= 4; s--)
{
haveStraight = rankArray[s] > 0 &&
rankArray[s - 1] > 0 &&
rankArray[s - 2] > 0 &&
rankArray[s - 3] > 0 &&
rankArray[s - 4] > 0;
if (haveStraight)
break;
}
}
if (haveStraight && haveFlush)
{ // now for the difficult task of straightFlush
// this is kind of expensive but at least it does hot happen a lot
// note in 7 you could have gap and still have a straight xyxxxxx
counterStraightAndFlush++;
straightCount = 0;
haveAce = false;
for (int c = 0; c < 7; c++)
{
if (CardArray[c].Suit == flushSuite)
{
straightCount++;
if (CardArray[c].Rank == 0)
haveAce = true;
}
}
if (straightCount >= 5)
{
straightCount2 = 0;
lastRank = null;
firstCard = 0;
foreach (Card c in CardArray.Where(x => x.Suit == flushSuite).OrderByDescending(x => x.Rank))
{
//Debug.WriteLine(c.Rank + " " + c.Suit);
if (lastRank == null)
{
firstCard = c.Rank;
}
else
{
if (c.Rank == lastRank - 1)
{
straightCount2++;
if (haveAce && straightCount2 == 3 && firstCard == 12)
{
haveRoyalFlush = true;
haveFlush = false;
haveStraight = false;
break;
}
else if (straightCount2 == 4) //the first card is not in the straightCount
{
haveStraightFlush = true;
haveFlush = false;
haveStraight = false;
break;
}
}
else
{
if (straightCount < 6)
break;
straightCount2 = 0; // this is the
firstCard = c.Rank;
}
}
lastRank = c.Rank;
}
}
}
}
// hands in order
if (haveRoyalFlush)
counterRoyalFlush++;
else if (haveStraightFlush)
counterStraightFlush++;
else if (haveQuad)
counterQuad++;
else if (haveBoat) // with 7 could have two trips
counterBoat++;
else if (haveFlush)
counterFlush++;
else if (haveStraight)
counterStraight++;
else if (rankCount[3] == 1)
counterTrips++;
else if (rankCount[2] >= 2) // with 7 could have 3 trips
counterPairTwo++;
else if (rankCount[2] == 1)
counterPairOne++;
else
counterHigh++;
}
}
}
}
}
}
}
sw.Stop();
Debug.WriteLine("");
Debug.WriteLine("Deal7a");
Debug.WriteLine("stopwatch millisec " + sw.ElapsedMilliseconds.ToString("N0"));;
Debug.WriteLine("hand count " + counter.ToString("N0"));
int sum = counterHigh + counterPairOne + counterPairTwo + counterTrips + counterStraight
+ counterFlush + counterBoat + counterQuad + counterStraightFlush + counterRoyalFlush;
Debug.WriteLine("royalFlush counter " + counterRoyalFlush.ToString("N0") + " " + (100m * counterRoyalFlush / sum).ToString("N4"));
Debug.WriteLine("straightFlush counter " + counterStraightFlush.ToString("N0") + " " + (100m * counterStraightFlush / sum).ToString("N4"));
Debug.WriteLine("quad count " + counterQuad.ToString("N0") + " " + (100m * counterQuad / sum).ToString("N4"));
Debug.WriteLine("boat count " + counterBoat.ToString("N0") + " " + (100m * counterBoat / sum).ToString("N3"));
Debug.WriteLine("flush counter " + counterFlush.ToString("N0") + " " + (100m * counterFlush / sum).ToString("N3"));
Debug.WriteLine("straight counter " + counterStraight.ToString("N0") + " " + (100m * counterStraight / sum).ToString("N3"));
Debug.WriteLine("trips count " + counterTrips.ToString("N0") + " " + (100m * counterTrips / sum).ToString("N3"));
Debug.WriteLine("two pair count " + counterPairTwo.ToString("N0") + " " + (100m * counterPairTwo / sum).ToString("N2"));
Debug.WriteLine("one pair counter " + counterPairOne.ToString("N0") + " " + (100m * counterPairOne / sum).ToString("N2"));
Debug.WriteLine("high card counter " + counterHigh.ToString("N0") + " " + (100m * counterHigh / sum).ToString("N2"));
Debug.WriteLine("sum " + sum.ToString("N0"));
Debug.WriteLine("");
}
struct Card
{
public Card(int Rank, int Suit)
{
rank = Rank;
suit = Suit;
}
Int32 rank;
Int32 suit;
public int Rank { get { return rank; } }
public int Suit { get { return suit; } }
}
``` | 2016/07/25 | [
"https://codereview.stackexchange.com/questions/135851",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/105946/"
] | When checking for a flush, instead of looping through the cards 4 times, you could have an array of length 4 where each position represents a suit. Then loop over the 7 cards one time and use a switch statement to increment the element that corresponds to the suit. Then loop over the array and check if any of the elements is 5 or more.
If you want to get really down in the bit twiddling, consider changing your && conditionals to & non-short circuiting conditions where it makes sense. Your haveStraight section where you are doing 4 conditional ANDs on simple conditions seems like a strong candidate, for example. The reason is that the compiler will likely be able optimize the code much better if you get rid of the conditional branching. Usually this won't make a big enough difference to matter but since you are doing this many millions of times, it could be substantial.
Another bit-twiddling approach that might be faster is to take the rank array and write the results into a short where each bit represents whether the corresponding element was greater than 0 (set the 13th and 0th bit for the aces.) Then you can bitwise AND the value with 31 (binary 11111) and see if it equals 31. Right shift 1 and compare again. Do this 9 times or until you find a match.
Lastly, you could take advantage of the fact that in your inner most loop, only one card is changing. You would have to restructure your code substantially but you could avoid all the recalculations of the other 6 cards each time by adjusting for that one card. You can keep doing this recursively up the tree for the loops but the return on that will be progressive less for each level you move up.
Here's an example of using a single pass loop to evaluate the straight:
```
int contig = rankArray[0] > 0 ? 1 : 0;
for (int r = 12; r >= 0; r--) {
contig = rankArray[r] > 0 ? contig + 1 : 0;
if (contig > 4) {
haveStraight = true;
break;
} else if (contig + r < 4) {
/* not sure this if this helps or hurts */
break;
}
}
```
Does that align with what you did? |