qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
5,149,982 |
after exporting to p.12 in MacOSX, can i run the following 3 step in Linux? Or i must get it done in the same machine where i export to P.12 before i upload to Linux server to use with my php script?
```
openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12
openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12
openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem
```
|
2011/03/01
|
[
"https://Stackoverflow.com/questions/5149982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/633765/"
] |
```
double dArray[][];
```
is Array-of-arrays while
```
double dArray[,];
```
is a two dimentional array.
it's easy enough to look them up.
[MSDN Reference link](http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx)
|
40,262,413 |
I wanted to use CloudFlare for my website (hosted on Microsoft Azure).
I have added my domain to Cloudflare, and changed my domains nameservers to the ones I got from Cloudflare.
Furthermore, cloudflare imported my current DNS settings which are the following (my domain has been replaced with domain.com):
[](https://i.stack.imgur.com/Gnkgr.png)
I thought the migration would go smoothly, however, when I go to www.domain.com I get the error:
>
> The webpage at <http://www.domain.com/> might be temporarily down or
> it may have moved permanently to a new web address.
>
>
>
However, when I refresh a couple of times it finally loads the site.
If I go to domain.com (no www-prefix), I get the error:
>
> domain.com’s server DNS address could not be found.
>
>
>
What could be going on?
|
2016/10/26
|
[
"https://Stackoverflow.com/questions/40262413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6047390/"
] |
For the first issue...if you are seeing inconsistent responses from your Azure Website, they you should raise an Azure support ticket.
For the second issue...try verifying the CLOUDFLARE DNS resolution via <http://digwebinterface.com>, both via a recursive DNS service and by querying against the CLOUDFLARE name servers directly. If the latter is working, there must be a problem in your DNS delegation (check name server settings with your registrar, try also a delegation validation service such as <http://dnscheck.pingdom.com/>). If the latter is not working, you'll need to take it up with CLOUDFLARE.
|
443,268 |
В анкетах и формах ввода данных часто встречаются следующие конструкции:
>
> Фамилия: Говоров.
>
>
> Пол: мужской.
>
>
> Образование: высшее.
>
>
> Телефон: 89151234567.
>
>
> Адрес: г. Москва, ул. Ленина, д. 1.
>
>
>
Каким членом предложения является слово после двоеточия?
|
2018/08/05
|
[
"https://rus.stackexchange.com/questions/443268",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/189895/"
] |
В анкетах после двоеточия стоит сказуемое. Назван предмет и его признак, в этом случае предмет - это подлежащее, а признак - сказуемое. Такое определение есть у Розенталя: Сказуемое - главный член двусоставного предложения, выражающий признак предмета, названного подлежащим. Всё вроде сходится.
Цель урока: научиться решать задачи. Здесь то же самое: цель - подлежащее, научиться - сказуемое.
Если поставить тире, то получится обычное предложение, оформленное по правилам пунктуации.
Если поставить двоеточие, то получится пояснительный вариант этого же предложения с тем же значением, потому что двоеточие предупреждает о последующем пояснении.
Зачем говорить об определениях или еще как-то усложнять тему. Мы в любой момент можем остановиться и эту паузу обозначить двоеточием. Можно вспомнить пример с пропущенным обобщающим словом (на заседании присутствовали:).
|
31,004,962 |
I have a json schema defining several properties. I've moved 2 of the properties to definitions and I make references to them. I did this because I wanted to group them together and do some testing for these properties in a generic way. This works fine and all the json data is handled as before.
But, I noticed that when I read the json schema file into my javascript file, I only see the last $ref. I don't know what the cause of this is. I'd really need to know all of the properties that are referenced.
Here's an snippet of my json schema (in file schemas/schema1.json):
```
{
"type": "object",
"properties": {
"$ref": "#/definitions/groupedProperties/property1",
"$ref": "#/definitions/groupedProperties/property2"
},
"definitions": {
"groupedProperties": {
"type": "object",
"properties": {
"property1": {
"type": "string"
},
"property2": {
"type": "string"
}
}
}
}
}
```
Then I'm reading it into my js file like this (in file test.js):
```
var schemas = requireDir('./schemas')
for (var prop in schemas['schema1'].properties) {
console.log(prop)
}
```
When I iterate over the properties in the schema from my js file, all I can see is one $ref. I imagine this is because it thinks the property name is '$ref' and there can be only unique names. Is there a certain way I need to require this file so that the first $ref doesn't get clobbered?
EDIT: My syntax wasn't passing the json schema validators, although I'm not sure why, so instead of struggling with that, I decided to do it a bit differently. All I wanted was a way to group certain properties, so I put the properties back in the main schema, and changed the definition to be just an enum of the property names comprising the group. So now my schema looks like:
```
{
"type": "object",
"properties": {
"property1": {
"type": "string"
},
"property2": {
"type": "string"
}
},
"definitions": {
"groupedProperties": {
"enum": ["property1", "property2"]
}
}
}
```
And then in my js file:
```
var myGroup = (schema.definitions ? schema.definitions.groupedProperties : [])
console.log(myGroup.enum) // [ 'property1', 'property2' ]
```
|
2015/06/23
|
[
"https://Stackoverflow.com/questions/31004962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3884280/"
] |
There are a lot of problems with how you reference your definitions.
###JSON objects can not have duplicate properties
All properties in a JSON or JavaScript object are unique. The second one will overwrite the first. Consider the syntax for accessing a property to understand why. When you read your JSON into a JavaScript object, you could try accessing the `$ref` property using `schema.properties['$ref']`. If there were two, which one (or both) would you get? JavaScript has no mechanism to distinguish because it is not allowed.
###`$ref` must stand alone
When `$ref` is used in an object, it must be the only property in that object. All other properties will be ignored. This is just one more reason why having two `$ref`s doesn't work.
>
> Any members other than "$ref" in a JSON Reference object SHALL be
> ignored.
>
>
> * <https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03#section-3>
>
>
>
###`$ref` should not be used in `properties`
`$ref` should only be used to reference schemas. In this case, the `properties` keyword is using `$ref` which is an object with schema values. Using `$ref` in this way is not explicitly forbidden in the documentation for JSON Schema or JSON Reference, but it is not idiomatic JSON Schema and is consequently not supported by most validators. Even if the validator you are using does support references like this, it should be avoid because it is never necessary and can make the schema confusing and difficult to maintain.
###Your JSON-Pointers are wrong
Your JSON-Pointers do not actually point to the schemas you have defined. The correct pointer would be `#/definitions/groupedProperties/properties/property1`.
###Posible Solutions
This is what you were trying to do.
```
{
"type": "object",
"properties": {
"property1": { "$ref": "#/definitions/groupedProperties/properties/property1" },
"property2": { "$ref": "#/definitions/groupedProperties/properties/property2" }
},
"definitions": {
"groupedProperties": {
"type": "object",
"properties": {
"property1": {
"type": "string"
},
"property2": {
"type": "string"
}
}
}
}
}
```
Here is a cleaner way to include all of your `groupedProperties` at once.
```
{
"type": "object",
"allOf": [
{ "$ref": "#/definitions/groupedProperties" }
],
"definitions": {
"groupedProperties": {
"type": "object",
"properties": {
"property1": {
"type": "string"
},
"property2": {
"type": "string"
}
}
}
}
}
```
Or, since you are only using it for testing purposes, you can flip it around so the definition references the schema. You can use the definition in your tests without it affecting your schema.
```
{
"type": "object",
"properties": {
"property1": { "type": "string" },
"property2": { "type": "string" }
},
"definitions": {
"groupedProperties": {
"type": "object",
"properties": {
"property1": { "$ref": "#/properties/property1" },
"property2": { "$ref": "#/properties/property2" }
}
}
}
}
```
|
56,887,520 |
I'm fetching github repositories from api.github.com/users/ncesar/repos and i wanna get only 10 items, then after scrolling, load more items. I have tried to implement myself but i dont know how to adapt it to array slice(that is limiting my array length to 2, just for testings).
This is my current code
```
class SearchResult extends Component {
constructor() {
super();
this.state = {
githubRepo: [],
loaded: false,
error: false,
};
}
componentDidMount() {
this.loadItems(this.props.location.state.userName);
}
componentWillReceiveProps(nextProps) {
if (
nextProps.location.state.userName !== this.props.location.state.userName
) {
this.loadItems(nextProps.location.state.userName);
}
}
loadItems(userName) {
axios
.get(`${api.baseUrl}/users/${userName}/repos`)
.then((repo) => {
console.log('repo', repo);
if (repo.data.length <= 0) {
this.setState({ githubRepo: '' });
} else {
this.setState({ githubRepo: repo.data });
}
})
.catch((err) => {
if (err.response.status === 404) {
this.setState({ error: true, loaded: true });
}
});
}
render() {
const {
githubRepo, loaded, error,
} = this.state;
return (
<div className="search-result">
{error === true ? (
<h1 style={style}>User not found :(</h1>
) : (
<section id="user-infos">
<div className="row">
<div className="col-md-8">
{githubRepo
.sort((a, b) => {
if (a.stargazers_count < b.stargazers_count) return 1;
if (a.stargazers_count > b.stargazers_count) return -1;
return 0;
}).slice(0, 2)
.map(name => (
<UserRepositories
key={name.id}
repoName={name.name}
repoDescription={name.description}
starNumber={name.stargazers_count}
/>
))}
</div>
</div>
</section>
)}
</div>
);
}
}
export default SearchResult;
```
Just to clarify, the sort is ordening repos by stars count.
What i have tried:
```
//setting theses states and calling this function
page: 1,
totalPages: null,
scrolling: false,
componentDidMount() {
this.loadContacts(); //carrega os contatos iniciais
this.scrollListener = window.addEventListener('scroll', (event) => {//escuta o scroll
this.handleScroll(event);
});
}
handleScroll = () => {
const { scrolling, totalPages, page } = this.state; //pega os 3 pra fora do state
if(scrolling) return; //se ja está scrollando, retorna true
if(totalPages <= page) return; //se o total de páginas é menor ou igual a page
const lastLi = document.querySelector('ul.contacts > li:last-child');//pegando o último li
const lastLiOffset = lastLi.offsetTop + lastLi.clientHeight;
const pageOffset = window.pageYOffset + window.innerHeight;
var bottomOffSet = 20;
if(pageOffset > lastLiOffset - bottomOffSet) this.loadMore();
}
loadMore = () => {
// event.preventDefault();
this.setState(prevState => ({
page: prevState.page + 1,
scrolling: true,
}), this.loadContacts);
}
```
But i dont know where i can pass the page parameter. The explanation of this code: it was used on a API with page number and per page parameters. The problem is that Github API does not offer this in repositories list, so, this is why i'm using slice.
|
2019/07/04
|
[
"https://Stackoverflow.com/questions/56887520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8402168/"
] |
You could use the empty line as a loop-breaker:
```
while (s.hasNextLine()){ //no need for "== true"
String read = s.nextLine();
if(read == null || read.isEmpty()){ //if the line is empty
break; //exit the loop
}
in.add(read);
[...]
}
```
|
201,138 |
Wrote a long story about me moving my mothers washing machine but decided to keep it short:
Machine 8 years old, aesthetically in perfect condition other than some exposed sheet metal on the side due to a scratch. Reportedly a few of its programs don't work.
The room where I installed it was (according to the previous owner) intended for a washing machine but he never got around to it. It had water but no electrical sockets, only an improvised lamp attached to a heavy gauge 3 core electrical cable sticking out the wall.
I removed the lamp and attached a grounded outlet instead. Plugged the machine in, all the lights came on as normal. Reached over to adjust the drain hose and got a mild shock from the scratch of exposed metal on the side. Didn't try if any other parts of it would shock me too, just unplugged it.
Searched around the internet, some claim that its normal if the machine isn't grounded properly. I have no clue if the ground on that wire I connected the outlet to actually serves any purpose. The other end of the cable is connected to the electricity of the bathroom next to it but I have no clue where. The bathroom has no sockets either, only lamps. I looked under the housing of a few of the bathroom lamps, they get their electricity via a 2 core cable.
In the electrical panel, the switch that controls the bathroom and the washing machine room has a 3 core medium gauge cable leaving and disappearing into a wall. Its not the same kind of cable as either the washing machine room or the bathroom have.
So now I'm suspecting that the grounding in that room might be fake and as such would justify the shock that the machine gave me. Is that a plausible scenario? Or should I just be looking for a new washing machine?
This took place in europe, 230V is the standard. Blue and brown wires make zap, yellow/green stripe wire is supposed to be ground.
EDIT: Looked up how to test for grounding, turns out all I needed was a multimeter, I got one of those. Surely enough, the cable in the washing machine room is not grounded. Also tested other outlets around the house, the grounding works in most places, other than the washing machine room, all the basement outlets save for one, the outlets behind the house on the patio don't work at all.
|
2020/08/15
|
[
"https://diy.stackexchange.com/questions/201138",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/51018/"
] |
Well, don't be confused by what happens in North America. There, some very silly things were done to dryers regarding bootlegging ground off neutral, and so dryers are a holy terror. Not Your Problem.
Your washer hooks up just like a normal appliance - Hot, Neutral and Earth.
I suspect the root of your problem is this "improvised" electrical connection. The first thing you did - that is a cardinal sin in Britain and European influenced areas - is **you attached an appliance to a lighting circuit**. Many lighting circuits are some piddly small ampacity like 3 or 6 amps. They are simply not intended for a large appliance. Only lighting can be on those circuits. It's possible that light was herky-jerked off an appliance circuit, but you should have investigated that.
Further, it's likely the lighting cord that was run for it, was "lighting-sized". So too small to run a large appliance like a washer. Again, in Europe, never convert a lighting outlet to an appliance outlet!
Generally anytime you find hork-a-dork wiring like that, you need to go through it "with a fine-tooth comb". Think about it -- when you're *looking right at* several Code violations, it would be insane to assume the rest of it was done safely to Code.
What you really need to do is find out whether DIY is allowed in your country, and either *properly* install a receptacle outlet in the room off an appliance circuit, or wire a dedicated circuit (that's Code in *El NEC* countries like Panama and the USA), or have a professional do it if local Code requires that.
|
11,420,224 |
According to this quirksmode article, <http://www.quirksmode.org/css/display.html>
>
> A block has some whitespace above and below it and tolerates no HTML
> elements next to it, except when ordered
>
>
>
Are the whitespace above or below stated in pixels or is it just 'whitespace'?.
|
2012/07/10
|
[
"https://Stackoverflow.com/questions/11420224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492293/"
] |
In the given context, "whitespace" is a gross misnomer. Whitespace in terms of text should *never* directly interfere with the layout of non-inline block boxes; what you should see between block boxes are *margins* (usually of said boxes), which are completely different.
Margins are indeed stated in pixels. In fact, they may be stated with any CSS length unit; see the [`margin` properties](http://www.w3.org/TR/CSS21/box.html#margin-properties) in the spec. You don't specify a pixel length for whitespace directly for elements that flow inline; that is usually controlled by `font-size` instead, but when working with block boxes that should be entirely irrelevant.
|
8,029,871 |
I am working on a webapp in WinXP, Eclipse Indigo and Google web plugin.
I have a simple form that takes a value from user (e.g email) , passes it to a servlet named `SignIn.java` that processes it and saves the email value to the session.
The `SignIn` code is very simple , here is what its `doGet` mostly does:
```
String email = req.getParameter("email"); //getting the parameter from html form
...
...
HttpSession session = req.getSession(); //create a new session
session.setAttribute("email", email);
```
So far so good, I've verified that the values aren't `null` at this point. Now comes the problem, I want to redirect to another servlet (`ShowOnline.java`) that needs to do some more processing. When I write
```
resp.sendRedirect(resp.encodeRedirectURL("/ShowOnlineServlet"));
```
`ShowOnline` gets `null` session values (the same email attribute I saved a second before is now `null`)
When I write
```
getServletConfig().getServletContext().getRequestDispatcher("/ShowOnlineServlet");
```
everything is OK, the email attribute from before isn't `null`!
What is going on? `sendRedirect()` just makes your browser send a new request, it shouldn't affect the session scope. I have checked the cookies and they are fine (it is the same session from before for sure since it is the first and only session my webapp creates and furthermore I even bothered and checked the sesison ID's and they're the same on both requests).
Why would there be a difference between `sendRedirect()` and `forward()`? The easy solution would be to use `forward()` but I want to get to the bottom of this before I just let go , I think it is important for me to understand what happened. I'm not sure I like the idea of not knowing what's going on on such basic concepts (my whole webapp is very simple and basic at this point since I'm a beginner).
Any thoughts ideas or suggestions would be warmly welcome !
|
2011/11/06
|
[
"https://Stackoverflow.com/questions/8029871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1032663/"
] |
If your `SignIn` servlet is only saving a request parameter (email), then you could also replace the servlet with a [filter](https://stackoverflow.com/tags/servlet-filters/info), e.g. `SignInFilter`.
`SignInFilter` would contain the same logic as your `SignIn` servlet (copying the email from the request parameters to the session), but would call the next item in the chain (which will be your `ShowOnline` servlet) instead of doing any redirect/forward.
```
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession();
String email = req.getParameter("email");
session.setAttribute("email", email);
chain.doFilter(req, res); // continue to 'ShowOnline'
}
```
Set up your form to POST to the `ShowOnline` servlet instead, and configure your new SignInFilter to execute before `ShowOnline` (servlet mapping omitted below for brevity).
```
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<filter>
<filter-name>SignInFilter</filter-name>
<filter-class>com.example.SignInFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SignInFilter</filter-name>
<url-pattern>/ShowOnline</url-pattern>
</filter-mapping>
</web-app>
```
|
7,483,233 |
My question is a continuation of [How to serialize a TimeSpan to XML](https://stackoverflow.com/questions/637933/net-how-to-serialize-a-timespan-to-xml)
I have many DTO objects which pass `TimeSpan` instances around. Using the hack described in the original post works, but it requires me to repeat the same bulk of code in each and every DTO for each and every `TimeSpan` property.
So, I came with the following wrapper class, which is XML serializable just fine:
```
#if !SILVERLIGHT
[Serializable]
#endif
[DataContract]
public class TimeSpanWrapper
{
[DataMember(Order = 1)]
[XmlIgnore]
public TimeSpan Value { get; set; }
public static implicit operator TimeSpan?(TimeSpanWrapper o)
{
return o == null ? default(TimeSpan?) : o.Value;
}
public static implicit operator TimeSpanWrapper(TimeSpan? o)
{
return o == null ? null : new TimeSpanWrapper { Value = o.Value };
}
public static implicit operator TimeSpan(TimeSpanWrapper o)
{
return o == null ? default(TimeSpan) : o.Value;
}
public static implicit operator TimeSpanWrapper(TimeSpan o)
{
return o == default(TimeSpan) ? null : new TimeSpanWrapper { Value = o };
}
[JsonIgnore]
[XmlElement("Value")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public long ValueMilliSeconds
{
get { return Value.Ticks / 10000; }
set { Value = new TimeSpan(value * 10000); }
}
}
```
The problem is that the XML it produces looks like so:
```
<Duration>
<Value>20000</Value>
</Duration>
```
instead of the natural
```
<Duration>20000</Duration>
```
My question is can I both "eat the cake and have it whole"? Meaning, enjoy the described hack without cluttering all the DTOs with the same repetitive code and yet have a natural looking XML?
Thanks.
|
2011/09/20
|
[
"https://Stackoverflow.com/questions/7483233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80002/"
] |
Change `[XmlElement("Value")]` to `[XmlText]`. Then, if you serialize something like this:
```
[Serializable]
public class TestEntity
{
public string Name { get; set; }
public TimeSpanWrapper Time { get; set; }
}
```
You will get XML like this:
```
<TestEntity>
<Name>Hello</Name>
<Time>3723000</Time>
</TestEntity>
```
|
44,210,547 |
I've got a static-hosting enable S3 bucket. There's also a cloudfront distribution that is being powered by that bucket.
I've added a CNAME entry to the cloudfront distribution for "mywebsite.com"
and when I go to load "mywebsite.com" in my browser, it redirects to `http://my-bucket.s3-us-west-2.amazonaws.com/index.html`
Why is this redirect happening? how do I stop that hostname from being rewritten?
**Edit: here's the setup details after some suggested changes:**
* **cloudfront** - ***alternate domain***: mysite.com
* **cloudfront** - ***alternate domain***: www.mysite.com
* **cloudfront** - ***origin***: my-bucket.s3-website-us-west-2.amazonaws.com
* **route53** - ***hosted zone***: mysite.com
* **route53** - ***A record***: 12345.cloudfront.net
* **route53** - ***CNAME***: www.mysite.com --> mysite.com
**and the effects of this setup:**
* Loading: `mysite.com` --> 301 redirects to `my-bucket.s3-website-us-west-2.amazonaws.com`
* Loading: `www.mysite.com` --> 301 redirects to `my-bucket.s3-website-us-west-2.amazonaws.com`
* Loading: `my-bucket.s3-website-us-west-2.amazonaws.com` --> 200 Success
* Loading: `d1h3yk3zemxpnb.cloudfront.net` --> 301 redirects to `my-bucket.s3-website-us-west-2.amazonaws.com`
* Loading: `http://my-bucket.s3.amazonaws.com/` --> permissions error
|
2017/05/26
|
[
"https://Stackoverflow.com/questions/44210547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680578/"
] |
The issue here is a side effect of a misconfiguration. This specific behavior may go away within a few minutes or hours of bucket creation, but the underlying issue won't be resolved.
When configuring a static website hosting enabled bucket behind CloudFront, you don't want to select the bucket name from the list of buckets.
>
> On the Create Distribution page, in the Origin Settings section, for Origin Domain Name, type the Amazon S3 static website hosting endpoint for your bucket. For example, `example.com.s3-website-us-east-1.amazonaws.com`.
>
>
> **Note**
>
>
> Be sure to specify the static website hosting endpoint, not the name of the bucket.
>
>
> <http://docs.aws.amazon.com/AmazonS3/latest/dev/website-hosting-cloudfront-walkthrough.html#create-distribution>
>
>
>
Selecting the `example.com.s3.amazonaws.com` entry from the list, rather than typing in the bucket's website hosting endpoint, would be the most likely explanation of this behavior.
S3 updates the DNS for the global REST endpoint hierarchy `*.s3.amazonaws.com` with a record sending requests to the right region for the bucket within a short time after bucket creation, and CloudFront appears rely on this for sending the requests to the right place. Before that initial update is complete, S3 will return a redirect and CloudFront returns that redirect to the browser... but all of this indicates that you didn't use the static website hosting endpoint as the origin domain name.
|
11,077,426 |
I've got a ruby hash like this
```
[{user_id: 3, purchase: {amount: 2, type_id:3, name:"chocolate"},
{user_id: 4, purchase: {amount: 1, type_id:3, name: "chocolate"},
{user_id: 5, purchase: {amount: 10, type_id:4, name: "penny-candy"}]
```
I want to take the array and merge by the type\_id, sum the amounts, connect the user to the amounts, so the end result would be
```
[{type_id: 3, name: "chocolate", total_amounts:3, user_purchases[{user_id:3, amount:2},user_id:4,amount:1}],
{type_id:4, name: "penny-candy", total_amounts: 10, [{user_id:5,amount:2}]}]
```
how would I go from one type of output to the other?
|
2012/06/18
|
[
"https://Stackoverflow.com/questions/11077426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48067/"
] |
It's a group\_by problem. I'll give you 2:
```
new_array = old_array.group_by{|x| x[:purchase][:type_id]}.values.map do |group|
{:type_id => group[0][:purchase][:type_id], :total_amounts => group.map{|g| g[:purchase][:amount]}.reduce(&:+)}
end
```
and leave the other 2 as an exercise
|
664,955 |
I know it's not perhaps in the true spirit of MVC, but I just want to have a single global controller that always gets called no matter *what* the url looks like. For example, it could be:
<http://myserver.com/anything/at/all/here.fun?happy=yes&sad=no#yippie>
...and I want that to be passed to my single controller. I intend to obtain the path programmatically and handle it myself--so in other words, I don't really want any routing at all.
I've opened up the global.asax file and found where routes are registered, but I just don't know what to put for the 'url' parameter in MapRoute:
```
routes.MapRoute( "Global", "", new { controller = "Global", action = "Index" } );
```
This (with the blank 'url') works fine for the default path of '/', but if I change it to anything I get a file not found, when I want it to handle *any* url. I also tried "\*", etc. but that didn't work.
I couldn't find any definitive reference to the format that the url parameter takes.
|
2009/03/20
|
[
"https://Stackoverflow.com/questions/664955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238948/"
] |
How about:
```
routes.MapRoute("Global", "{*url}", new { controller = "Global", action = "Index" } );
```
from [this](https://stackoverflow.com/questions/19941/aspnet-mvc-catch-exception-when-non-existant-controller-is-requested) question
|
62,988,547 |
How can one get the AWS::StackName without the random generate part?
I create a stack: `aws cloudformation create-stack --stack-name test`
The stack name returned when evaluated using `AWS:StackName` will included a random generated part, e.g. `test-KB0IKRIHP9PH`
What I really want returned is the parameter without the generated part, in this case `test`,
omitting `-KB0IKRIHP9PH`
---
My use case for this is, when my containers startup, they need to get database
credential from a pre created named secret. With the random part in place the service all fail to start initially until the secrets are created.
In the code below I assign the StackName to an environment variable.
```
TaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
ContainerDefinitions:
- Name: website-service
Environment:
- Name: ENVIRONMENT_VAR
Value: !Join ["", ["CF_", {"Ref": "AWS::StackName"}]]
```
---
Here is an update as requested, to show how I create the stack. I am using a MakeFile...
```
create-test: s3
@ip_address=$$(dig @resolver1.opendns.com ANY myip.opendns.com +short); \
read -s -p "Enter DB Root Password: " pswd; \
[[ -z $$pswd ]] && exit 1 || \
aws cloudformation create-stack \
--capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM \
--stack-name test \
--template-body file://master.yaml \
--parameters ParameterKey=DBRootPassword,ParameterValue=$$pswd \
ParameterKey=DBHostAccessCidr,ParameterValue=$$ip_address/32
```
|
2020/07/20
|
[
"https://Stackoverflow.com/questions/62988547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/919918/"
] |
I test this with a simple template:
```yaml
AWSTemplateFormatVersion: 2010-09-09
Resources:
Bucket:
Type: AWS::S3::Bucket
Outputs:
Stack:
Value: !Sub ${AWS::StackName}
```
The **Stack** output variable exactly matched the name of the stack that I created. There were *no* random characters.
I launched the stack via the console.
|
78,354 |
From time to time (quite randomly), Nemo on my Linux Mint 14 Cinnamon starts looking like this

When usually it looks like this: 
Restarting Cinnamon (`Alt`+`F2`, `r`, `Enter`) doesn't help, I need to log out, and then log on.
Can someone tell me,
* (I guess, that something with [X Window System](http://en.wikipedia.org/wiki/X_Window_System) had crashed. `dmesg` doesn't show anything.) how to diagnose, what really happened? (*update: it seems it is `gnome-settings-daemon` crash*)
* how to restore the normal theme without logging off (which requires closing all programs)?
* how to minimize frequency of such things?
---
Suspicious entries in `xsession-errors.lob`
```
[0x7f9590006068] main input error: ES_OUT_SET_(GROUP_)PCR is called too late (pts_delay increased to 300 ms)
[0x7f9590006068] main input error: ES_OUT_RESET_PCR called
[0x7f9590006068] main input error: ES_OUT_SET_(GROUP_)PCR is called too late (pts_delay increased to 1108 ms)
[0x7f9590006068] main input error: ES_OUT_RESET_PCR called
```
(...)
```
[h264 @ 0x7f95790fc160] Missing reference picture
[h264 @ 0x7f95790fc160] decode_slice_header error
[h264 @ 0x7f95790fc160] mmco: unref short failure
[h264 @ 0x7f95790fc160] concealing 1620 DC, 1620 AC, 1620 MV errors
[h264 @ 0x7f95790fc160] Missing reference picture
[h264 @ 0x7f95790fc160] Missing reference picture
[h264 @ 0x7f95790fc160] Missing reference picture
```
(...)
```
No such schema 'com.canonical.unity-greeter'
```
Suspicious entries in syslog:
```
Jun 13 01:03:45 adam-N56VZ kernel: [49764.694213] gnome-settings-[4198]: segfault at 188b2 ip 00007f2e46acf0a6 sp 00007fff8acb45d0 error 4 in libgdk-3.so.0.600.0[7f2e46a8c000+7c000]
Jun 13 01:03:52 adam-N56VZ gnome-session[4098]: WARNING: Application 'gnome-settings-daemon.desktop' killed by signal 11
```
(...)
```
Jun 13 01:40:59 adam-N56VZ laptop-mode: Warning: Configuration file /etc/laptop-mode/conf.d/board-specific/*.conf is not readable, skipping.
```
---
Update:
It seems, that the this behavior can be reproduced by killing `gnome-settings-daemon`. The question remains on how to restore it? Simply running it as user or root doesn't change anything, even with restarting cinnamon (`Alt`+`F2`, `r`, `Enter`).
And the hardest question: how to prevent it from happening? Since it is a crash I guess I'll need to follow the procedure with filing bug report. But who's fault it is? Gnome's or Cinnamon's? Or maybe some other component is at fault here?
|
2013/06/05
|
[
"https://unix.stackexchange.com/questions/78354",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/17765/"
] |
It seems that `cinnamon-settings-daemon`/`gnome-settings-daemon` is not running.
You can put it in startup aplications to make sure it starts when you log in.
|
10,772,686 |
to be able to add annotations to a pdf file in linux, i have to reset the "Commenting" security setting in the pdf document.
`qpdf --decrypt input.pdf output.pdf` should remove any passwords or "encryption" ([according to this post](https://superuser.com/questions/216616/does-pdftk-respect-pdf-security-flags))
`pdftk input input.pdf output output.pdf allow AllFeatures` should set all document securities (including "Commenting") to be allowed
After applying both commands, in acroread i can still see (file -> document -> security tab) that commenting is not allowed.
How can I reset this security property?
|
2012/05/27
|
[
"https://Stackoverflow.com/questions/10772686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/989762/"
] |
The command `qpdf --decrypt input.pdf output.pdf` removes the 'owner' password. But it only works if there is no 'user' password set.
Once the owner password is removed, the `output.pdf` should already have unset *all* security protection and have allowed commenting. Needless to run your extra `pdftk ...` command then... BTW, your `allow` parameter in your `pdftk` call will not work the way you quoted your command. The `allow` permissions will only be applied if you also...
* ...either specify an encryption strength
* ...or give a user or an owner password
Try the following to find out the detailed security settings of the file(s):
```
qpdf --show-encryption input.pdf
qpdf --show-encryption output.pdf
```
|
35,181,472 |
I faced the problem that I dont understand how itertools.takewhile() code works.
```
import itertools
z = [3,3,9,4,1]
zcycle = itertools.cycle(z)
next_symbol = zcycle.next()
y = list(itertools.takewhile(lambda symbol: symbol == next_symbol or symbol == 9, zcycle))
print y
```
my code suppose to give me elements of the list from the beginning if they are the same or if element is equal to 9. So once we hit element that differs from previous one we should stop.
I expected that the outcome would be `[3, 3]` but instead I got `[3, 9]`.
Why we miss the very first element of the list?
and is it possible somehow to get output equal to `[3, 3, 9]`?
|
2016/02/03
|
[
"https://Stackoverflow.com/questions/35181472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5366684/"
] |
You removed the first `3` from the sequence here:
```
next_symbol = zcycle.next()
```
That advances `zcycle` to the next element, so it'll yield one more `3`, not two.
Don't call `next()` on the `zcycle` object; perhaps use `z[0]` instead:
```
next_symbol = z[0]
```
Now `zcycle` will yield `3`, then another `3`, then `9`, after which the `takewhile()` condition will be `False` and all iteration will stop.
|
55,022,363 |
I making a ASP.NET CORE 2.1 website. The database in Visual studio works fine, but when i deployed to the IIS which on another computer, the database not work.
In log, the error:
```
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred in the database while iterating the results of a query for context type 'WebApplication3.Data.ApplicationDbContext'.
System.ArgumentException: Keyword not supported: 'id'.
.................
```
The connectionstring in the web.config:
```
"ConnectionStrings": {
"DefaultConnection": "Server=.\\SQLEXPRESS;Database=XXXX;Trusted_Connection=True;ID=XXXXXXX;pwd=XXXXXXXXX;MultipleActiveResultSets=true "
```
},
I read lot of articles for this, but i cant add any plus tags for the connection string, wil be error, the connection string is bad?
When i run the project the in Visual Studio i can use database and i see the database in the SQL Server Managment Studio.
For the database i use the "stock database" when created a the project in visual studio.
Because i use Entity Framework i need another format connection string?
[Stock Databse](https://i.stack.imgur.com/r6B46.png)
|
2019/03/06
|
[
"https://Stackoverflow.com/questions/55022363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7850219/"
] |
Oh my jesus... I figured out the answer.. Just one f\*... word... In connenction strig DONT USE *database*, the correct word is **Initial Catalog** and maybe use user id instead of id.
Correct string:
```
"DefaultConnection": "Server=.\\SQLEXPRESS;Initial Catalog=XXX;Trusted_Connection=False;user id=XXX;pwd=XXX;MultipleActiveResultSets=true "
```
|
59,164 |
Um hervorzuheben, dass ein Wort euphemistisch gebraucht wird oder, dass es eigentlich nicht ganz seinen normalerweise zugedachten Inhalt widerspiegelt, kann man Anführungszeichen nutzen:
>
> Hans "arbeitet" schwer im Home-Office. (Hans schaut eigentlich eine Serie auf Netflix)
>
>
>
>
> Hans hat gestern seine Wohnung "aufgeräumt". (Hans hat einen Teller in den Geschirrspüler geräumt).
>
>
>
Wie verhält es sich denn, wenn das Verb geteilt ist?
>
> Hans räumt morgen seine Wohnung auf.
>
>
>
>
> a) Hans "räumt" morgen "auf"
>
> b) Hans "räumt" morgen auf
>
> c) Hans räumt morgen "auf"
>
>
>
|
2020/06/30
|
[
"https://german.stackexchange.com/questions/59164",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/30455/"
] |
Ignoriere die pedantischen Angriffe gegen die Vorstellung von Ironie in der Sprache. Wenn man ein Verb durch Anführungszeichen hervorhebt, egal zu welchem Zweck, und das Verb geteilt wird, dann stehen die Anführungszeichen natürlich um beide Teile, also ist a) richtig.
(Am Rande: Davon unabhängig muß man natürlich darauf achten, daß *eine* der Verwendungen von "" ist, ein wörtliches Zitat zu kennzeichnen, und wörtliche Zitate dürfen nicht verändert werden. Wenn also das Originalzitat das Verb ungetrennt verwendete, z.B. im Nebensatz, dann darf man es nicht so umformulieren, daß das Verb getrennt wird.)
|
15,535 |
Children at my school have become very interested in playing chess during morning break and in before/after care. However, they only have a limited amount of time to play and must clean up...so, they cannot leave pieces on the board. In this situation, what is the best way to declare a winner?
Is it fair to use point count for the pieces captured?
|
2016/10/01
|
[
"https://chess.stackexchange.com/questions/15535",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/11373/"
] |
Point count is a fair way to *start* evaluating a chess position; even the strongest computer engines do so. I see two potential problems:
1. One player might have less material but an initiative, e.g. a strong kingside attack. On this level, it is not usual to sacrifice material for an initiative, so this might not be a big problem for you.
2. What constitutes a decisive advantage? One pawn is -usually- not enough to win an endgame, but it might be, when combined with other advantages.
|
16,966,812 |
I use this layout :
```
<?xml version="1.0" encoding="UTF-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:background="#00868B">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_alignParentTop="true"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_below="@+id/title" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button ..
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="@string/getloc"
/>
<Button ..
android:layout_width="match_parent"
android:layout_height="50dp"
/>
<Button ..
android:layout_width="match_parent"
..
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
</ScrollView>
```
There is no scrollview.
I want when the user enters sth in second textview to "go down" because else the textview gets bigger but the first button is steady and blocks the view.
|
2013/06/06
|
[
"https://Stackoverflow.com/questions/16966812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/583464/"
] |
Try following the tutorial in [this link](http://net.tutsplus.com/tutorials/html-css-techniques/developing-with-sass-and-chrome-devtools/). I just set this up this morning and it's working fine for me.
This will let you inspect an element and then find what the corresponding SCSS declaration is.
|
24,472,223 |
Consider HTML code below. In that code I am dynamically adding a DIV with a class "dynamic" and I am expecting that it would pick up the CSS attributes defined for that class which in turn would show a black square. The black square, however, never appears. Am I doing anything wrong here? If not, then is there a way to define CSS attributes upfront and dynamically add elements or should I always add css attributes to the element after it was added (which seems inconvenient). Thanks.
```
<!DOCTYPE html>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function() {
$("body").append(
$("<div/>").attr("class", "dynamic")
)
});
</script>
<html>
<head>
<style>
.dynamic {
backgorund-color: black;
width: 100px;
height: 130px;
left: 10px;
top: 10px;
}
</style>
</head>
<body>
</body>
</html>
```
|
2014/06/29
|
[
"https://Stackoverflow.com/questions/24472223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128461/"
] |
In your class, you spelled background incorrectly:
```
.dynamic {
background-color: black;
width: 100px;
height: 130px;
left: 10px;
top: 10px;
}
```
I also recommend jQuery's `.addClass()` instead of `.attr()`
```
$("<div/>").addClass("dynamic")
```
<http://jsbin.com/qufeq/1/>
|
56,769,100 |
I am using officeGen to generate word documents.
>
> generateDocumentService.js
>
>
>
```
var generateReportFromTableData = function (tableData) {
console.log('tableData: ', tableData);
var docx = officegen({
type: 'docx',
orientation: 'portrait',
pageMargins: {
top: 1000,
left: 1000,
bottom: 1000,
right: 1000
}
})
docx.on('error', function (err) {
console.log(err)
})
pObj = docx.createP({
align: 'center'
})
pObj.addText('Business Process General Information', {
border: 'dotted',
borderSize: 12,
borderColor: '88CCFF',
bold: true
})
var table = [
[
{
val: 'Ref',
opts: {
cellColWidth: 2000,
b: true,
sz: '10',
shd: {
fill: '7F7F7F',
themeFill: 'Arial',
themeFillTint: '20'
},
fontFamily: 'Arial'
}
},
{
val: 'Risk Statements',
opts: {
cellColWidth: 2000,
b: true,
sz: '10',
shd: {
fill: '7F7F7F',
themeFill: 'Arial',
themeFillTint: '20'
},
fontFamily: 'Arial'
}
},
{
val: 'Max Impact',
opts: {
cellColWidth: 2000,
b: true,
sz: '10',
shd: {
fill: '7F7F7F',
themeFill: 'Arial',
themeFillTint: '20'
},
fontFamily: 'Arial'
}
},
{
val: 'Control effectiveness',
opts: {
cellColWidth: 2000,
b: true,
sz: '10',
shd: {
fill: '7F7F7F',
themeFill: 'Arial',
themeFillTint: '20'
},
fontFamily: 'Arial'
}
},
{
val: 'Recommended Risk Rating',
opts: {
cellColWidth: 2000,
b: true,
sz: '10',
shd: {
fill: '7F7F7F',
themeFill: 'Arial',
themeFillTint: '20'
},
fontFamily: 'Arial'
}
},
{
val: 'Frequency',
opts: {
cellColWidth: 2000,
b: true,
sz: '10',
shd: {
fill: '7F7F7F',
themeFill: 'Arial',
themeFillTint: '20'
},
fontFamily: 'Arial'
}
},
{
val: 'Impact',
opts: {
cellColWidth: 2000,
b: true,
sz: '10',
shd: {
fill: '7F7F7F',
themeFill: 'Arial',
themeFillTint: '20'
},
fontFamily: 'Arial'
}
},
{
val: 'Validated Review Risk Rating',
opts: {
cellColWidth: 2000,
b: true,
sz: '10',
shd: {
fill: '7F7F7F',
themeFill: 'Arial',
themeFillTint: '20'
},
fontFamily: 'Arial'
}
},
{
val: 'Rational For Risk Adjustment',
opts: {
cellColWidth: 2000,
b: true,
sz: '20',
shd: {
fill: '7F7F7F',
themeFill: 'Arial',
themeFillTint: '20'
},
fontFamily: 'Arial'
}
},
],
['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'],
['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'],
['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'],
['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'],
['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'],
['Ahmed', 'Ghrib', 'Always', 'Finds','A','Soulution', 'Finds','A','Soulution'],
]
var tableStyle = {
tableColWidth: 4261,
tableSize: 72,
tableColor: 'ada',
tableAlign: 'left',
tableFontFamily: 'Comic Sans MS',
borders: true
}
pObj = docx.createTable(table, tableStyle)
var out = fs.createWriteStream(path.join('./docs/Table Data Report.docx'))
out.on('error', function (err) {
console.log(err)
})
async.parallel(
[
function (done) {
out.on('close', function () {
console.log('Finish to create a DOCX file.')
done(null)
})
docx.generate(out)
}
],
function (err) {
if (err) {
console.log('error: ' + err)
} // Endif.
}
)
}
```
Here's the result :
[](https://i.stack.imgur.com/VtcJv.png)
Although I really love the OfficeGen framework, I couldn't find a way to choose a size for the text inside the table. It seems that either they have missed it or I couldn't find how.
For the table column headers it was possible with this property sz inside their definition:
```
{val: 'Ref',
opts: {
cellColWidth: 2000,
b: true,
sz: '10',
shd: {
fill: '7F7F7F',
themeFill: 'Arial',
themeFillTint: '20'
},
fontFamily: 'Arial'
}
}
```
But for the data inside the table, for days I couldn't find a way. Nothing inside the tableStyle definition hints to a way to do that:
```
var tableStyle = {
tableColWidth: 4261,
tableSize: 72,
tableColor: 'ada',
tableAlign: 'left',
tableFontFamily: 'Comic Sans MS',
borders: true
}
```
Any help?? Thanks!
[Generating word document with OfficeGen documentation](https://github.com/Ziv-Barber/officegen/blob/2c482ea3e83c45b4cde7ddfc6a3fe01c24b0f393/manual/README-docx.md)
|
2019/06/26
|
[
"https://Stackoverflow.com/questions/56769100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11379139/"
] |
You can try out with below code in your configuration
```
var tableStyle = {
sz: 20
tableColWidth: 4261,
tableSize: 72,
tableColor: 'ada',
tableAlign: 'left',
tableFontFamily: 'Comic Sans MS',
borders: true
}
```
**sz: 20** - this value will divide by 2 and it sets the font size ie. if you want to set size as 10 you have to set configuration as 20)
Mark this as answer . Thumps up if this works for you !!!!
|
35,134,394 |
Let's say that I have six different classes and three of them should use the same constant value. What can we do? We either:
* Define as global variable
```
A = 1
class B:
def __init__(self):
self.a = A
class C:
def __init__(self):
self.a = A
class D:
def __init__(self):
self.a = A
```
* Define as class level for 1 class and give it to another class:
```
class B:
A = 1
def __init__(self):
self.b = 2
class C:
def __init__(self, a):
self.a = a
self.b = 3
b = B()
c = B(a=b.A)
```
The second way I just made up and as for me it's dirty and not convenient. Is there any way to avoid using a global variable?
|
2016/02/01
|
[
"https://Stackoverflow.com/questions/35134394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3434076/"
] |
Use class inheritance:
```
class Holder:
a = 4
class A(Holder):
pass
print A().a
```
|
72,859,168 |
I have a pandas data frame from which I'm trying to create a dictionary based on a users age, where age is the key and the data associated with it is the value. So lets say users with age 10 will be in a dictionary {Age:10, Data:[Pole, Carl]}
[Table Image](https://i.stack.imgur.com/utCnQ.png)
|
2022/07/04
|
[
"https://Stackoverflow.com/questions/72859168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19480593/"
] |
Did you try explicitly deleting the l-value overload?
```
template <typename T>
auto f(T &&) {}
template <typename T>
auto f(T &) = delete;
```
|
517,568 |
I'm seeing a lot of the following line in `/var/log/syslog`:
```
Jun 21 14:36:15 my-server kernel: [416219.080061] iptables denied: IN=eth0 OUT= MAC=ff:ff:ff:ff:ff:ff:the-mac-address:08:00 SRC=0.0.0.0 DST=255.255.255.255 LEN=328 TOS=0x00 PREC=0x00 TTL=128 ID=10081 PROTO=UDP SPT=68 DPT=67 LEN=308
```
This seems to happen just about every minute. Is this just my server trying to broadcast something and my own iptables denying it from happening? If so, what kind of service might do such a thing, and should I allow it? I'm running Postgres 9.2.4 on Ubuntu 12.04.2, and basically no other services aside from the basic, pre-installed packages.
|
2013/06/21
|
[
"https://serverfault.com/questions/517568",
"https://serverfault.com",
"https://serverfault.com/users/31454/"
] |
Those are just DHCP messages, either your server, or another is looking to configure an interface.
|
13,055 |
I'm looking for a clear, concise and accurate answer.
Ideally as the actual answer, although links to good explanations welcome.
|
2008/08/16
|
[
"https://Stackoverflow.com/questions/13055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] |
Boxed values are [data structures](http://en.wikipedia.org/wiki/Data_structure) that are minimal wrappers around [primitive types](http://en.wikipedia.org/wiki/Primitive_type)\*. Boxed values are typically stored as pointers to objects on [the heap](http://en.wikipedia.org/wiki/Dynamic_memory_allocation).
Thus, boxed values use more memory and take at minimum two memory lookups to access: once to get the pointer, and another to follow that pointer to the primitive. Obviously this isn't the kind of thing you want in your inner loops. On the other hand, boxed values typically play better with other types in the system. Since they are first-class data structures in the language, they have the expected metadata and structure that other data structures have.
In Java and Haskell generic collections can't contain unboxed values. Generic collections in .NET can hold unboxed values with no penalties. Where Java's generics are only used for compile-time type checking, .NET will [generate specific classes for each generic type instantiated at run time](http://msdn.microsoft.com/en-us/library/f4a6ta2h.aspx).
Java and Haskell have unboxed arrays, but they're distinctly less convenient than the other collections. However, when peak performance is needed it's worth a little inconvenience to avoid the overhead of boxing and unboxing.
\* For this discussion, a primitive value is any that can be stored on [the call stack](http://en.wikipedia.org/wiki/Call_stack), rather than stored as a pointer to a value on the heap. Frequently that's just the machine types (ints, floats, etc), structs, and sometimes static sized arrays. .NET-land calls them value types (as opposed to reference types). Java folks call them primitive types. Haskellions just call them unboxed.
\*\* I'm also focusing on Java, Haskell, and C# in this answer, because that's what I know. For what it's worth, Python, Ruby, and Javascript all have exclusively boxed values. This is also known as the "Everything is an object" approach\*\*\*.
\*\*\* Caveat: A sufficiently advanced compiler / JIT can in some cases actually detect that a value which is semantically boxed when looking at the source, can safely be an unboxed value at runtime. In essence, thanks to brilliant language implementors your boxes are sometimes free.
|
17,314,513 |
I want to create a software:
- Input as a video stream H264 ( from another software)
- Output as a webcam for my friends can watch in skype, yahoo, or something like that.
I knows I need to create directshow filter to do that, but I dont know what type filter I must to create.
And when I have a filter, I dont know how to import it to my application?
I need a example or a tutorial, please help me
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17314513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2376873/"
] |
You need to create a virtual video source/camera filter. There have been a dozen of questions like this on SO, so I will just link to some of them:
* [How to write an own capture filter?](https://stackoverflow.com/questions/10086897/how-to-write-an-own-capture-filter/10087276#10087276)
* [Set byte stream as live source in Expression Encoder 4](https://stackoverflow.com/questions/8488073/set-byte-stream-as-live-source-in-expression-encoder-4)
* ["Fake" DirectShow video capture device](https://stackoverflow.com/questions/1376734/fake-directshow-video-capture-device)
Windows SDK has `PushSource` sample which shows how to generate video off a filter. `VCam` sample [you can find online](http://tmhare.mvps.org/downloads.htm) shows what it takes to make a virtual device from video source.
See also: [How to implement a "source filter" for splitting camera video based on Vivek's vcam?](http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/ce717600-750b-46c0-8a63-31d65659740b/how-to-implement-a-source-filter-for-splitting-camera-video-based-on-viveks-vcam).
NOTE: Latest versions of Skype [are picky as for video devices and ignore virtual devices for no apparent reason](http://webcache.googleusercontent.com/search?q=cache:mjhhnU-9uEUJ:https://jira.skype.com/browse/SCW-3881%3FfocusedCommentId%3D58828%26page%3Dcom.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel+&cd=1&hl=en&ct=clnk&client=firefox-beta).
|
22,830,387 |
I don't know why and how, but my jQuery code appears to be firing twice on any event.
Here's a part of my code:
`commmon.js`:
```
$(document).ready(function() {
$(".fpbtn-one").click(function() {
console.log("Click recorded!"); // Gets logged twice on click
$(this).parent().next().slideToggle();
});
// The rest of the code...
});
$(window).load(function() {
console.log("Setting up slides"); // Gets logged 2 on page load
// These get initialized twice
$("#div-1").responsiveSlides({
auto: true,
pager: true,
pause:true,
nav: false,
timeout: 3000,
speed: 500,
maxwidth: 482,
namespace: "transparent-btns"
});
$("#div-2").responsiveSlides({
auto: true,
pager: false,
pause:true,
nav: false,
speed: 2000,
maxwidth: 320,
});
});
```
---
HTML:
```
<!doctype html>
<html lang="en">
<head><link href="/assets/css/jquery.qtip.css" rel="stylesheet" type="text/css" />
<link href="/assets/custom/themes/1st-formation-theme/theme.css" rel="stylesheet" type="text/css"/>
<link href="/assets/css/efControl.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/jquery-ui.min.js"></script>
<script type="text/javascript" src="/assets/script/jquery/jquery.qtip.js"></script>
<script type="text/javascript" src="/assets/script/jquery/plugin.efiling.full.js"></script>
<meta charset="utf-8" /><script type="text/javascript">window.NREUM||(NREUM={}),__nr_require=function a(b,c,d){function e(f){if(!c[f]){var g=c[f]={exports:{}};b[f][0].call(g.exports,function(a){var c=b[f][1][a];return e(c?c:a)},g,g.exports,a,b,c,d)}return c[f].exports}for(var f=0;f<d.length;f++)e(d[f]);return e}({"4O2Y62":[function(a,b){function c(a,b){var c=d[a];return c?c.apply(this,b):(e[a]||(e[a]=[]),void e[a].push(b))}var d={},e={};b.exports=c,c.queues=e,c.handlers=d},{}],handle:[function(a,b){b.exports=a("4O2Y62")},{}],YLUGVp:[function(a,b){function c(){var a=m.info=NREUM.info;if(a&&a.agent&&a.licenseKey&&a.applicationID){m.proto="https"===l.split(":")[0]||a.sslForHttp?"https://":"http://",g("mark",["onload",f()]);var b=i.createElement("script");b.src=m.proto+a.agent,i.body.appendChild(b)}}function d(){"complete"===i.readyState&&e()}function e(){g("mark",["domContent",f()])}function f(){return(new Date).getTime()}var g=a("handle"),h=window,i=h.document,j="addEventListener",k="attachEvent",l=(""+location).split("?")[0],m=b.exports={offset:f(),origin:l,features:[]};i[j]?(i[j]("DOMContentLoaded",e,!1),h[j]("load",c,!1)):(i[k]("onreadystatechange",d),h[k]("onload",c)),g("mark",["firstbyte",f()])},{handle:"4O2Y62"}],loader:[function(a,b){b.exports=a("YLUGVp")},{}]},{},["YLUGVp"]);</script>
<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<link href="/assets/custom/files/favicon.ico" rel="shortcut icon" />
<link href="/assets/custom/images/system/apple-touch-icon.png" rel="apple-touch-icon" />
<link href="/assets/custom/images/system/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes="72x72" />
<link href="/assets/custom/images/system/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes="114x114" />
<meta content="" name="description" />
<meta content="" name="keywords" />
<meta content="NOINDEX, NOFOLLOW" name="ROBOTS" />
<title>Some title</title>
<link href="/assets/custom/files/css/reset.css" rel="stylesheet" type="text/css" />
<link href="/assets/custom/files/css/base.css?=v1" rel="stylesheet" type="text/css" />
<link href="/assets/custom/files/css/font-awesome.css" rel="stylesheet" type="text/css" />
<!--[if IE 7]>
<link rel="stylesheet" href="/assets/custom/files/css/font-awesome-ie7_min.css">
<![endif]-->
<script type="text/javascript" src="/assets/custom/files/js/adobe-type.js"></script>
</head>
<body>
<!-- BODY STUFF IN HERE (REMOVED) -->
<script type="text/javascript" src="/assets/custom/files/js/jquery-mmenu-min.js"></script>
<script type="text/javascript" src="/assets/custom/files/js/jquery-anystretch-stand-min.js"></script>
<script type="text/javascript" src="/assets/custom/files/js/common.js"></script>
<script type="text/javascript" src="/assets/custom/files/js/modernizr.js"></script>
<script type="text/javascript" src="/assets/custom/files/js/responsiveslides_min.js"></script>
<script type="text/javascript" src="/assets/custom/files/js/socialmedia.js"></script>
<script type="text/javascript" src="/assets/custom/files/js/jquery_atooltip_min.js"></script></div>
<script type="text/javascript">window.NREUM||(NREUM={});NREUM.info={"beacon":"beacon-4.newrelic.com","licenseKey":"204ccc8db2","applicationID":"1825150","transactionName":"YVNVYBACWxFTWxFcWVgZYkYLTFwMVl0dG0ZeRg==","queueTime":0,"applicationTime":187,"ttGuid":"","agentToken":"","userAttributes":"","errorBeacon":"jserror.newrelic.com","agent":"js-agent.newrelic.com\/nr-361.min.js"}</script></body>
</html>
```
What could be the reason?
|
2014/04/03
|
[
"https://Stackoverflow.com/questions/22830387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1999681/"
] |
Could it be that your code was manipulating the element that the code was loading into?
This answer may be the reason why it was happening:
[jQuery $(document).ready () fires twice](https://stackoverflow.com/questions/10727002/jquery-document-ready-fires-twice)
|
31,646,520 |
Here is my code:
```
private void textBox1_TextChanged(object sender, EventArgs e)
{
DateTime myDate = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd H:m:s",
System.Globalization.CultureInfo.InvariantCulture);
TimeChangedHandler(myDate);
}
```
If I delete 1 number from hours then it works fine, but if I delete both numbers e.x. I want to change from 11 to 22 then it crashes. So how do I make the form `"yyyy-MM-dd H:m:s"` work for all cases? Thanks!
|
2015/07/27
|
[
"https://Stackoverflow.com/questions/31646520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4551943/"
] |
If you want to indicate that the date/time is invalid, use `DateTime.TryParseExact` to *check* whether or not it's valid, without throwing an exception. Use the return value (true/false) to determine the validity.
Basically, you shouldn't expect that the value is always valid while the user is editing - just like while I'm editing code, it won't always be syntactically correct.
You need to check that it's valid when you actually *use* the value - and until then, probably just add a visual marker to indicate that it's invalid.
You may want to think about whether your `TimeChangedHandler` (whatever that is) should implicitly fire whenever the date/time provided is valid, or whether your UI should provide a more explicit "use this value" action (e.g. a button).
Also, consider using a `DateTimePicker` as a friendlier way of selecting a date and time.
Finally, I'd personally avoid using a pattern of `H:m:s`... the date part looks like ISO-8601-like, so I'd suggest using `HH:mm:ss` for complete validity - it would be odd (IMO) to see a value of `2015-07-27 7:55:5` for example.
|
40,798,676 |
I'm using a table layout for my website. It's working in IE and Chrome, even IE 8 perfectly. My entire website is in one table with three cells. The top navbar, the content, and the bottom footer navbar. The table's width and min-height is set to 100%, and the middle cell is set to height: auto. This makes the footer get pushed to at least the bottom of the window, and if there is enough content the footer is painlessly pushed farther along with the content.
But Firefox won't make the middle cell's height fill to reach the table's min-height of 100%.
Here is what it looks like in Internet Explorer and Chrome (working):
[](https://i.stack.imgur.com/3gY9Z.png)
[](https://i.stack.imgur.com/dgaAJ.png)
but in Firefox the middle cell's height isn't filling (not working):
[](https://i.stack.imgur.com/ignog.png)
Here is my CSS:
```
<style>
#tablecontainer{
width: 100%;
min-height: 100%;
}
.table-panel {
display: table;
}
.table-panel > div {
display: table-row;
}
.table-panel > div.fill {
height: auto;
}
/* Unimportant styles just to make the demo looks better */
#top-cell {
height: 50px;
background-color:aqua;
}
#middle-cell {
/* nothing here yet */
background-color:purple;
}
#bottom-cell {
height:50px;
background-color:red;
}
body {
height: 100%;
margin: 0;
}
html {
height: 100%;
}
```
Here is my HTML:
```
<body>
<div id="tablecontainer" class="table-panel">
<div id="top-cell">
<nav>
</nav>
</div>
<div id="middle-cell" class="fill">
<div class="section">
<div class="container">
<p>{{ content }}</p>
</div>
</div>
</div>
<div id="bottom-cell">
<nav>
<p>I'm the footer!</p>
</nav>
</div>
</body>
```
Here's a fiddle. <https://jsfiddle.net/mmgftmyr/> It is completely accurate, the fiddle will work in Chrome and Internet Explorer but not Firefox.
|
2016/11/25
|
[
"https://Stackoverflow.com/questions/40798676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6283055/"
] |
Problem exists in the following styles:
```
#tablecontainer {
min-height: 100%; /* change min-height to height */
width: 100%;
}
.table-panel {
display: table;
}
```
`min-height: 100%` property doesn't work properly with `min-height` always. Change `min-height` to `height` and it will work.
***Note***: `HTML` tables have special behavior with height. If you specify `height` for a `table` or and element having `display: table` and its content doesn't fit in then its height will be increased automatically according to the content. So we can always use `height` instead of `min-height` with tables.
```css
#tablecontainer{
width: 100%;
height: 100%;
}
.table-panel {
display: table;
}
.table-panel > div {
display: table-row;
}
.table-panel > div.fill {
height: auto;
}
/* Unimportant styles just to make the demo looks better */
#top-cell {
height: 50px;
background-color:aqua;
}
#middle-cell {
/* nothing here yet */
background-color:purple;
}
#bottom-cell {
height:50px;
background-color:red;
}
body {
height: 100%;
margin: 0;
}
html {
height: 100%;
}
```
```html
<div id="tablecontainer" class="table-panel">
<div id="top-cell">
<nav>
</nav>
</div>
<div id="middle-cell" class="fill">
<div class="section">
<div class="container">
<p>{{ content }}</p>
</div>
</div>
</div>
<div id="bottom-cell">
<nav>
<p>I'm the footer!</p>
</nav>
</div>
</div>
```
|
58,919,766 |
I registered Moment.js as a plugin, like this:
```
import Vue from 'vue'
import moment from 'moment'
moment.locale('pt_BR')
Vue.use({
install (Vue) {
Vue.prototype.$moment = moment
}
})
```
Now, I need to use this in my `main.js` filters
```
import './plugins/moment'
Vue.filter('formatDate', value => {
return this.$moment(value, 'YYYY-MM-DD').format('DD/MM/YYYY')
})
```
Buth this return an error:
>
> Error in render: "TypeError: Cannot read property '$moment' of
> undefined"
>
>
>
|
2019/11/18
|
[
"https://Stackoverflow.com/questions/58919766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3691686/"
] |
Looks like you can not access `this` like in the `vue` components for filter methods.
[By Evan You](https://github.com/vuejs/vue/issues/5998#issuecomment-311965292)
>
> This is intentional in 2.x. Filters should be pure functions and should not be dependent on this context. If you need this you should use a computed property or just a method e.g. $translate(foo)
>
>
>
I guess the best way is importing the `moment` on `main.js` like this:
```
import moment from 'moment'
Vue.filter('formatDate', value => {
return moment(value, 'YYYY-MM-DD').format('DD/MM/YYYY')
})
```
|
172,288 |
Multiple times I've found myself in a situation in a meeting where I'm laying out my plans for a project I've been assigned and either my manager or a co-worker identify something to be impossible and therefore I should do something else (taking the time to explain how to do it). Instead of trying to convince them that my plan is possible in the meeting (which I've learned the hard way is a very bad thing to do), I instead after the meeting go and create a proof of concept to show that it is possible and present it the next time we have a meeting about my project with pros and cons compared to the solution they presented.
Is this bad etiquette on my part and should I just go with the group and implement the suggested solution just to keep a good rapport with my coworkers (not making them look bad).
Normally if the meeting is about my co-worker's project, I won't do anything after the meeting if they choose a different path than what I would have done and if my boss or co-worker states that they don't want something implemented a particular way and they don't specify that its because they think it's impossible I respect their viewpoint and adjust my project accordingly.
If this is bad etiquette, what should I do when someone is trying to guide my project using known incorrect reasoning?
|
2021/05/08
|
[
"https://workplace.stackexchange.com/questions/172288",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/81043/"
] |
>
> If this is bad etiquette, what should I do when someone is trying to
> guide my project using known incorrect reasoning?
>
>
>
Make your case. If they reject your suggestions, ideas, and opinions then do what your boss tells you to do. It isn't your company. It isn't your decision. At the end of the day, they pay you to perform work. You may sometimes disagree with that work. That's OK.
|
65,891,422 |
I want to retrieve the original index of the column with the largest sum at each iteration after the previous column with the largest sum is removed. Meanwhile, the row of the same index of the deleted column is also deleted from the matrix at each iteration.
For example, in a 10 by 10 matrix, the 5th column has the largest sum, hence the 5th column and row are removed. Now the matrix is 9 by 9 and the sum of columns is recalculated. Suppose the 6th column has the largest sum, hence the 6th column and row of the current matrix are removed, which is the 7th in the original matrix. Do this iteratively until the desired number of columns index is preserved.
My code in Julia that **does not work** is pasted below. **Step two in the for loop is not correct because a row is removed at each iteration, thus the sum of columns are different.**
Thanks!
```
# a matrix of random numbers
mat = rand(10, 10);
# column sum of the original matrix
matColSum = sum(mat, dims=1);
# iteratively remove columns with the largest sum
idxColRemoveList = [];
matTemp = mat;
for i in 1:4 # Suppose 4 columns need to be removed
# 1. find the index of the column with the largest column sum at current iteration
sumTemp = sum(matTemp, dims=1);
maxSumTemp = maximum(sumTemp);
idxColRemoveTemp = argmax(sumTemp)[2];
# 2. record the orignial index of the removed scenario
idxColRemoveOrig = findall(x->x==maxSumTemp, matColSum)[1][2];
push!(idxColRemoveList, idxColRemoveOrig);
# 3. update the matrix. Note that the corresponding row is also removed.
matTemp = matTemp[Not(idxColRemoveTemp), Not(idxColRemoveTemp)];
end
```
|
2021/01/25
|
[
"https://Stackoverflow.com/questions/65891422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10865571/"
] |
python solution:
```py
import numpy as np
mat = np.random.rand(5, 5)
n_remove = 3
original = np.arange(len(mat)).tolist()
removed = []
for i in range(n_remove):
col_sum = np.sum(mat, axis=0)
col_rm = np.argsort(col_sum)[-1]
removed.append(original.pop(col_rm))
mat = np.delete(np.delete(mat, col_rm, 0), col_rm, 1)
print(removed)
print(original)
print(mat)
```
I'm guessing the problem you had was keeping track with information what was the index of current columns/rows in original array. I've just used a list `[0, 1, 2, ...]` and then pop one value in each iteration.
|
24,235,183 |
I feel like I have a pretty good grasp on using decorators when dealing with regular functions, but between using methods of base classes for decorators in derived classes, and passing parameters to said decorators, I cannot figure out what to do next.
Here is a snippet of code.
```
class ValidatedObject:
...
def apply_validation(self, field_name, code):
def wrap(self, f):
self._validations.append(Validation(field_name, code, f))
return f
return wrap
class test(ValidatedObject):
....
@apply_validation("_name", "oh no!")
def name_validation(self, name):
return name == "jacob"
```
If I try this as is, I get an "apply\_validation" is not found.
If I try it with `@self.apply_validation` I get a "self" isn't found.
I've also been messing around with making `apply_validation` a class method without success.
Would someone please explain what I'm doing wrong, and the best way to fix this? Thank you.
|
2014/06/16
|
[
"https://Stackoverflow.com/questions/24235183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/431333/"
] |
In case someone stumbled on this later.
To extract the data you can use regex, while for the custom median filter you can have a look [here](https://gist.github.com/bhawkins/3535131).
I will leave a copy down here in case it is removed:
```
def medfilt (x, k):
"""Apply a length-k median filter to a 1D array x.
Boundaries are extended by repeating endpoints.
"""
assert k % 2 == 1, "Median filter length must be odd."
assert x.ndim == 1, "Input must be one-dimensional."
k2 = (k - 1) // 2
y = np.zeros ((len (x), k), dtype=x.dtype)
y[:,k2] = x
for i in range (k2):
j = k2 - i
y[j:,i] = x[:-j]
y[:j,i] = x[0]
y[:-j,-(i+1)] = x[j:]
y[-j:,-(i+1)] = x[-1]
return np.median (y, axis=1)
```
|
49,481,364 |
I have an array of strings. Some of elements are empty, i.e. `''` (there are no `null`, `undefined` or strings containing only white space characters). I need to remove these empty elements, but only from the (right) end of array. Empty elements that come before non-empty elements should remain. If there are only empty strings in array, empty array should be returned.
Below is the code I have so far. It works, but I wonder - is there a way that does not require all these `if`s? Can I do it without creating in-memory copy of array?
```
function removeFromEnd(arr) {
t = [...arr].reverse().findIndex(e => e !== '');
if (t === 0) {
return arr;
} else if (t === -1) {
return [];
} else {
return arr.slice(0, -1 * t);
}
}
```
Test cases
----------
```
console.log(removeFromEnd(['a', 'b', '', 'c', '', '']));
console.log(removeFromEnd(['a', '', '']));
console.log(removeFromEnd(['', '', '', '', 'c']));
console.log(removeFromEnd(['', '', '', '']));
```
```
[ 'a', 'b', '', 'c' ]
[ 'a' ]
[ '', '', '', '', 'c' ]
[]
```
|
2018/03/25
|
[
"https://Stackoverflow.com/questions/49481364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3552063/"
] |
An alternative is using the function **[`reduceRight`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight)** along with the **[`Spread syntax`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)**.
```js
let removeFromEnd = (arr) => arr.reduceRight((a, b) => ((b !== '' || a.length) ? [b, ...a] : a), []);
console.log(removeFromEnd(['a', 'b', '', 'c', '', '']));
console.log(removeFromEnd(['a', '', '']));
console.log(removeFromEnd(['', '', '', '', 'c']));
console.log(removeFromEnd(['', '', '', '']));
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
|
234,096 |
As many I tend to misspell some words when I type. OS X is being nice and underlines them letting me know that something was not right, if use a mouse and right click on the underlined word a menu pops up and offers the correct spelling of this word.
Is there a way to trigger this menu from the keyboard?
|
2016/04/07
|
[
"https://apple.stackexchange.com/questions/234096",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/97578/"
] |
Sort of, but not quite in the same way - without the mouse to indicate which word you mean, it has to start from the top & work through them all...
`Cmd ⌘` `:` will pop up the full spell-checker with which you can then navigate through the doubtful words, but once open, you need to interact with it using the mouse, even to actually make it the front-most window.
[](https://i.stack.imgur.com/JkscV.png)
|
222,011 |
Is Tonks ability limited in that she can't transform into a full animal the way other animagi can?
If not, what's the difference?
Further more, considering *both* his parents' have transformative capabilities, does that mean Teddy Lupin has a higher chance of inheriting shape-shifting magic?
|
2019/10/22
|
[
"https://scifi.stackexchange.com/questions/222011",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/114389/"
] |
He has, in the Injustice comics
===============================
In the Injustice universe, Superman and Lex Luthor are best friends and Lex Luthor is aware of Superman's alter ego, and has been since they were both teenagers, as he was a high school friend of both Superman (Clark Kent) and Lois Lane.
|
62,069,673 |
Say that I have this part of code. If user does not enter the file names as command line arguments I want to ask him again so as to enter them now but as it seems I cannot have access in argv[1] and argv[2]. For example when the first scanf is executed segmentation fault occurs. But in this case how can I read the arguments and place them into argv[1] and argv[2]?
Thanks in advance for your help!
```
int main (int argc, char **argv)
{
if (argc != 3)
{
printf("You did not enter two files.\n");
printf("You can now enter those two files.\n");
printf("file 1: ");
scanf("%s", argv[1]);
printf("file 2: ");
scanf("%s ", argv[2]);
}
printf("%s\n", argv[1]);
printf("%s\n", argv[2]);
FILE *file1 = fopen(argv[1], "r");
FILE *file2 = fopen(argv[2], "r");
}
```
|
2020/05/28
|
[
"https://Stackoverflow.com/questions/62069673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You don't. As the popular phrase goes, every problem in computer science can be solved by an extra layer of indirection. In this case the indirection is that you define a clean interface for opening a file and pass it a `char const*`. But this pointer doesn't have to be `argv[1]`.
You have to malloc your own buffer (because **none** exists) and write to it. Using `scanf("%s",...)` for this purpose will likely create a buffer overrun as you cannot know in advance how large your buffer needs to be.
*Edit*: Every single answer given to you suggesting to use `char buffer[NUMBER]` as the buffer for `scanf` **will blow up in your face**.
|
42,372,532 |
I need to open an existing \*.xlsx Excel file, make some modifications, and then save it as a new file (or stream it to the frontend without saving). The original file must remain unchanged.
For Memory reasons, I avoid using FileInputStream (as described here: <http://poi.apache.org/spreadsheet/quick-guide.html#FileInputStream> )
```
// XSSFWorkbook, File
OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
....
pkg.close();
```
|
2017/02/21
|
[
"https://Stackoverflow.com/questions/42372532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6426882/"
] |
X and y labels are bound to an axes in matplotlib. So it makes little sense to use `xlabel` or `ylabel` commands for the purpose of labeling several subplots.
What is possible though, is to create a simple text and place it at the desired position. `fig.text(x,y, text)` places some text at coordinates `x` and `y` in figure coordinates, i.e. the lower left corner of the figure has coordinates `(0,0)` the upper right one `(1,1)`.
```
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))
axes = df.plot(kind="bar", subplots=True, layout=(2,2), sharey=True, sharex=True)
fig=axes[0,0].figure
fig.text(0.5,0.04, "Some very long and even longer xlabel", ha="center", va="center")
fig.text(0.05,0.5, "Some quite extensive ylabel", ha="center", va="center", rotation=90)
plt.show()
```
[](https://i.stack.imgur.com/8A97k.png)
The drawback of this solution is that the coordinates of where to place the text need to be set manually and may depend on the figure size.
|
52,076,282 |
I am using @ngx/translate core for lang change.
I want to define sass on the basic of
```
<body lang="en">
```
or
```
<body lang="fr">
```
by if else condition.
```
Inside my component sass i want to do something like this
@if( bodylang = en)
/these rules
else
// these rules
```
How can i achieve this?
|
2018/08/29
|
[
"https://Stackoverflow.com/questions/52076282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9419166/"
] |
As it is SCSS you are able to use CSS attribute selectors for this, for example:
```
a[target="_blank"] {
background-color: yellow;
}
```
Which in your case would be:
```
body[lang="en"] {
// Your code
}
body[lang="fr"] {
// Your code
}
```
You can also nest them like such:
```
body {
background-color: orange;
&[lang="en"] {
background-color: blue;
}
}
```
This selector is more specific than just referring to the body tag itself. This means that it will apply the regular body CSS if none of the matching langcode tags are found. You can find more attribute selectors here: <https://www.w3schools.com/css/css_attribute_selectors.asp>
|
62,101 |
Just what the title says. Suppose I know the feature that I want to be used for splitting for the root node in a tree model in XGBoost; is there a way for me to tell XGBoost to split on this feature at the root node?
|
2019/10/22
|
[
"https://datascience.stackexchange.com/questions/62101",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/84189/"
] |
I do not have the whole answer, but I believe that xgboost allows warm-starting, which implies starting from a provided point.
```
xgb.train(…,xgb_model=model_to_start_from)
```
|
54,882,263 |
The text of button is not displaying in Safari,I can return the text using jquery in the console. But it is recognising the click event e.g
```html
<div class="btn-group btn-group-lg">
<button onclick="change();" id="face-btn" type="button" class="btn btn-primary">Face</button>
```
|
2019/02/26
|
[
"https://Stackoverflow.com/questions/54882263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7430286/"
] |
I couldn't write a comment that why am writing a suggestion here,
try to add a height to your button style
This answer is based on this Articel: [Button-not-displaying-well-in-Safari](https://www.sitepoint.com/forums/showthread.php?597261-Button-not-displaying-well-in-Safari)
|
95,170 |
I was curious if the half life of Gold is 186 Days, then why does it 'Last forever' ... Wouldn't the ancient Egyptian gold artifacts be decayed to lighter elements by now like platinum? I know gold was able to withstand corrosion very well, but the relatively short half-life is kinda throwing off my understanding of why it 'last forever'.
|
2018/04/14
|
[
"https://chemistry.stackexchange.com/questions/95170",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/62802/"
] |
Gold has only one stable isotope, $\ce{^197Au}$, which has $100\%$ natural abundance, thus considered to be one of monoisotopic elements (one of 26 chemical elements which have only a single stable isotope). As a matter of facts, it is now considered to be the heaviest monoisotopic element. For more info, read [Isotopes of gold](https://en.wikipedia.org/wiki/Isotopes_of_gold).
Aside $\ce{^197Au}$, there are 36 unstable isotopes of gold been known ranging from $\ce{^169Au}$ to $\ce{^205Au}$. All of these are radioisotopes (radioactive nuclides). The $\ce{^195Au}$ isotope is the most stable amongst unstable isopopes, with a half-life ($t\_{1/2}$) of $\pu{186 d}$. The heaviest, $\ce{^205Au}$, has $t\_{1/2}$ of $\pu{31 s}$ ([ref](http://periodictable.com/Isotopes/079.205/index.p.full.html)).
|
107,732 |
I've tried researching this question myself, but the only data I can find is over huge timescales, like situations where the continents have reformed back into a Neo-Pangea.
I'm not looking for any real drastic changes in positioning, just relatively minor things like seas disappearing or continents slightly shrinking or pushing into each other.
Would there be any noteworthy changes at all, or would it be pretty much the same as today aside from some minor changes that wouldn't affect anything?
Let's just assume humanity suddenly stopped existing today for the purposes of the question, so they don't make any more changes to the world than they already have.
As always, I'm very grateful for any answers, and if you need anything clarified feel free to leave a comment and I'll do my best to clear things up.
|
2018/03/23
|
[
"https://worldbuilding.stackexchange.com/questions/107732",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/48871/"
] |
A millennium is a blink of an eye on a geological scale. But interesting things can happen in a blink of an eye. Even disegarding the changes which may happen as a result of the present climatological instability, small but important modification can occur here and there.
I have no idea of the geographical changes between today and 3000 CE; but I do know of *some* geographical changes between 1 CE and today, either because they happened in places in which I have a local interest, or because they are somehow important to various historical events, or because I found out about them by accident and found them interesting enough to remember.
Geographical changes during the last 1000 or 2000 years
-------------------------------------------------------
* While sea level is today not very different from what it was in the first century, *in some places the sea advanced or retreated considerably:*
+ Some cities which used to be seaports in the first century are now several miles inland. For example:
- In the Antiquity [Ephesus](https://en.wikipedia.org/wiki/Ephesus) and [Miletus](https://en.wikipedia.org/wiki/Miletus) were major ports on the Ionian coast; they are now several kilometers inland.
[](https://en.wikipedia.org/wiki/Miletus#/media/File:Miletus_Bay_silting_evolution_map-en.svg)
*The silting evolution of Miletus Bay due to the alluvium brought by the Maeander River during Antiquity. Map by Eric Gaba, available on Wikimedia under the CC-BY-SA-3.0 license.*
- Closer to me, in the Antiquity the city of Histria was a seaport on the western coast of the Black Sea. Now its ruins lay on the shore of a shallow lagoon, and the sea is kilometers away.
[](https://en.wikipedia.org/wiki/Histria_(ancient_city)#/media/File:Scythia_Minor_map.jpg)
*Ancient towns and colonies in Dobruja; modern coastline shown as a dotted line. Map by Bogdan, available on Wikimedia under the CC-BY-SA-3.0 license.*
+ On the other hand, in some places the sea advanced. For example, what is now the [IJselmeer](https://en.wikipedia.org/wiki/IJsselmeer) in the Netherlands used to be a low-lying plain in the first century, with a large lake known by the Romans as [Lake Flevo](https://en.wikipedia.org/wiki/Lake_Flevo). In 1287, [Saint Lucia's flood](https://en.wikipedia.org/wiki/St._Lucia%27s_flood) broke through and submerged the former river [Vlie](https://en.wikipedia.org/wiki/Vlie), creating a large shallow gulf which was called the [Zuiderzee](https://en.wikipedia.org/wiki/Zuiderzee).
[](https://en.wikipedia.org/wiki/Lake_Flevo#/media/File:50nc_ex_leg_copy.jpg)
*The region of the Netherlands in the 1st century CE. Map by the Dutch Nationale Onderzoeksagenda Archeologie (www.noaa.nl), available on Wikimedia under the CC-BY-SA-3.0 license.*
Then in 1932 the long effort of the Dutch to build the [Afsluitdijk](https://en.wikipedia.org/wiki/Afsluitdijk) was brough to completion, and the gulf was separated from the sea and became a lake, which the Dutch then proceeded to drain in order to increase the territory of their country; and now the Netherlands has a new 1500 square kilometer province, called [Flevoland](https://en.wikipedia.org/wiki/Flevoland).
* Rivers sometimes change course dramatically. For me, the most spectacular example is the [Oxus](https://en.wikipedia.org/wiki/Amu_Darya), which is today known as the Amu Darya. Until the 16th century it used to flow into the Caspian Sea, through what is now the dry [Uzboy](https://en.wikipedia.org/wiki/Uzboy) valley; it then changed its mind, abandoned the Caspian and went to empty into the Aral Sea.
[](https://en.wikipedia.org/wiki/Uzboy#/media/File:XXth_Century_Citizen%27s_Atlas_map_of_Central_Asia.png)
*The old course of the Oxus (Amu Darya), when it flew into the Caspian Sea, marked as "Old Bed of the Oxus". Map from 1903, available on Wikimedia. Public domain.*
At the beginning of the 18th century, [Peter the Great](https://en.wikipedia.org/wiki/Peter_the_Great), emperor of Russia, sent prince [Alexander Bekovich-Cherkassky](https://en.wikipedia.org/wiki/Alexander_Bekovich-Cherkassky) to find the mouth of the Oxus, with the intention of establishing a trade route from the Caspian to Transoxiana. The prince dutifully mapped the coast and returned with the sad news that the river no longer flowed into the Caspian...
* Speaking of the [Aral Sea](https://en.wikipedia.org/wiki/Aral_Sea), the Soviet Union killed it in the 20th century. The former immense lake of 68,000 square kilometers is now a desert, the [Aralkum](https://en.wikipedia.org/wiki/Aralkum_Desert).
* Speaking of the Soviet Union and Transoxiana: in the 1930s the Soviet Union conceived a titanic project to *"divert the flow of the Northern rivers in the Soviet Union, which "uselessly" drain into the Arctic Ocean, southwards towards the populated agricultural areas of Central Asia, which lack water"* (Wikipedia). The [Northern River Reversal](https://en.wikipedia.org/wiki/Northern_river_reversal) eventually grew and grew, design and planning progressed through the 1960s and 1970s, so that by 1980 the Soviets were talking of diverting 12 major Siberian rivers into the Central Asian desert. They even envisaged using atomic bombs to move massive amounts of dirt speedily. Then the Soviet Union fell; but who knows?
* Speaking of using atomic bombs to dig canals, Egypt is considering a [plan to dig a canal](https://en.wikipedia.org/wiki/Qattara_Depression_Project) from the Mediterranean to the [Qattara Depression](https://en.wikipedia.org/wiki/Qattara_Depression), flooding it and creating a solar-powered 2000 megawatt hydropower plant.
[](https://en.wikipedia.org/wiki/Qattara_Depression_Project#/media/File:All_proposed_routes.PNG)
*All proposed routes for a tunnel and/or canal route from the Mediterranean Sea towards the Qattara Depression. Map by AlwaysUnite, available on Wikimedia under the CC-BY-SA-3.0 license.*
And yes, in the 1950s the international Board of Advisers led by Prof. [Friedrich Bassler](https://en.wikipedia.org/wiki/Friedrich_Bassler) proposed to dig the canal using atomic blasts, part of President Eisenhower's [Atoms for Peace](https://en.wikipedia.org/wiki/Atoms_for_Peace) program.
* The [Frisian Islands](https://en.wikipedia.org/wiki/Frisian_Islands) on the eastern edge of the North Sea are notoriously shifty, so that the approaches to the Dutch ports have changed considerably from the Middle Ages to the present. For example, the northern part of what is now the island of [Texel](https://en.wikipedia.org/wiki/Texel) was until the 13th century the southern part of the island of [Vlieland](https://en.wikipedia.org/wiki/Vlieland); it then left Vlieland and became a separate island, the [Eierland](https://en.wikipedia.org/wiki/Eierland); in the 17th century the Dutch reclaimed the land between the Texel and Eierland, and the two islands became one.
[](https://en.wikipedia.org/wiki/Eierland#/media/File:PaysBas_delisle_1743_fragment.jpg)
*Eierland when it was a separate island. Map from 1702, available on Wikimedia. Public domain.*
Geography is not static
-----------------------
The list could be very much expanded. The Panama Canal. The proposed Nicaragua Canal. The lockless Suez Canal, which has brought the marine life of the Red Sea into the Mediterranean. The Hot Gates of Greece. The shifting barrier islands off the coast of Texas. The absent-minded [Yellow River](https://en.wikipedia.org/wiki/Yellow_River) of China. The wandering lake [Lop Nor](https://en.wikipedia.org/wiki/Lop_Nur). The unstable coastline of England -- how many of the medieval [Cinque Ports](https://en.wikipedia.org/wiki/Cinque_Ports) are still ports, that is, if they exist at all?
Geography changes wherever you look closely.
|
31,158,335 |
I encountered a strange issue. It's Wednesday now, and:
```
DateTime date;
DateTime.TryParseExact(
"Wed", "ddd", null, System.Globalization.DateTimeStyles.None, out date); // true
DateTime.TryParseExact(
"Mon", "ddd", null, System.Globalization.DateTimeStyles.None, out date); // false
```
When I change local date on computer to Monday output swaps to 'false-true'.
Why does the parser depend on current date?
|
2015/07/01
|
[
"https://Stackoverflow.com/questions/31158335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632632/"
] |
I *suspect* the problem is that you've got a very incomplete date format there. Usually, `DateTime.TryParseExact` will use the current time and date for any fields that aren't specified. Here, you're specifying the day of the week, which isn't really enough information to get to a real date... so I suspect that the text value is only being used to *validate* that it's a reasonable date, after defaulting the `DateTime` to "now". (In the cases where it does manage to parse based on just the day name, you end up with today's date.)
I've just done another test where we specify the day-of-month value as well, and that ends up with interesting results - it appears to use the first month of the current year:
```
using System;
using System.Globalization;
class Test
{
public static void Main (string[] args)
{
// Note: All tests designed for 2015.
// January 1st 2015 was a Thursday.
TryParse("01 Wed"); // False
TryParse("01 Thu"); // True - 2015-01-01
TryParse("02 Thu"); // False
TryParse("02 Fri"); // True - 2015-01-02
}
private static void TryParse(string text)
{
DateTime date;
bool result = DateTime.TryParseExact(
text, "dd ddd", CultureInfo.InvariantCulture, 0, out date);
Console.WriteLine("{0}: {1} {2:yyyy-MM-dd}", text, result, date);
}
}
```
Changing the system date to 2016 gave results consistent with finding dates in January 2016.
Fundamentally, trying to parse such incomplete as this is inherently odd. Think carefully about what you're really trying to achieve.
|
27,674,464 |
I been having problems on my onclick function to another JSP.
I wanted to check whether if the session attribute is the same as **John** or **Mark** from my **display.jsp**, then it will display on **new.jsp** with that name.
I have a **login.jsp** and successfully works on **display.jsp** where it able to display name out by using session in ValidationServlet.
After implementing the code in **display.jsp**, I keep getting requested resource () is not available.
Stuck there for 3 days already and kinda lost now.
Hope you guys could help me out with it, thanks in advance.
**This is my display.jsp code**
```
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Application</title>
</head>
<body>
<h1>Display</h1>
Welcome <b><%=session.getAttribute("name")%></b>,
<table border="0">
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td>
<form action="loan" method="post">
<input type="submit" value="New" onClick="new()"/>
</form>
<SCRIPT LANGUAGE="JavaScript">
function new(){
if (session.getAttribute("name") === "John") {
session.setAttribute("name", "John");
document.new.action="new.jsp";
}
if (session.getAttribute("name") === "Mark") {
session.setAttribute("name", "Mark");
document.new.action="new.jsp";
} else {
session.setAttribute("name", null);
document.new.action="new.jsp";
}
new.submit();
}
</SCRIPT>
</td>
<td colspan="2"></td>
</tr>
</table>
</body>
</html>
```
**This is my new.jsp code**
```
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Application</title>
</head>
<body>
<h1>New</h1>
Hello <b><%=session.getAttribute("name")%></b>
</body>
</html>
```
|
2014/12/28
|
[
"https://Stackoverflow.com/questions/27674464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3127380/"
] |
You will get the session variable like beelow:
```
var firstName='<%= session.getAttribute("name")%>';
```
|
45,964 |
Buddha talks of becoming have a cause, is dependent on something other. Like Lamp's flame and light, shadow and real object, The sun and it's aura, object and mirage.
The dependent origination generates the false 'I' which is nothing but the becoming.
Then can one conclude the cessation of becoming is also carried out by reversal of dependent origination I.e Dependent Cessation? I think that's the way!
Shadow can be ceased only when the real object is perceived, if not the shadow thinks it as real, even though it's unreal or non existing thing! Previously perceived snake was actually the rope, when the wisdom dawns upon.
This shadow is false 'I', the illusion, the non-existant thing. But only when one sees it with eyes of wisdom! Can we say that?
Some quotes of Saints have this testimony in common,
√ Cure for Pain is in Pain!\_ Rumi
√ Samudayadhamma(origination) = nirodhadhamma(cessation)\_ Buddha
I believe the becoming and cessation are two opposite sides of the same coin!
What do others have to say about this? Please don't bring here quotes of scriptures. Do we have here the seekers which can see with eyes of wisdom?
I am asking them! Others please don't bother!
|
2021/10/07
|
[
"https://buddhism.stackexchange.com/questions/45964",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/12115/"
] |
Good question, more to the point than your first one, IMO.
Regular samsaric mind is "flat", we see things and we interpret them non-ambiguously as per our ego's convictions.
Buddha's mind is "non-flat", it's not like it doesn't interpret at all, rather it produces a solution space of all possible and plausible interpretations at once. It's not a collection of individual distinct interpretations, more like a multidimensional gradient space.
This is why it's said the Buddha's mind is indescribable, Buddha has no position on things etc.
This has been described variously in Buddhist literature as openness or vastness or groundlessness or Emptiness or suchness or ambiguity or metaphorical homelessness etc.
So it's not that you need to stop the thought and become a rock or a log, not at all. Undoing the ego is about opening up and removing the boundaries, towards the fully open Buddha-mind (Bodhi-citta).
In practice this sort of open multiperspective is actually very helpful in everyday life. It makes one a lot less prone to being stuck in a box or getting into a conflict with others. So it's not just good for enlightenment, it makes one more robust in the regular life, too.
|
3,808 |
By default, `populateState` seems to limit a call to any model's `get('Items')` function to 20 items.
How can this be overridden - by re-writing `populateState`? By writing a separate function in the model? I've gone for the second option...
```
public function getAll(){
return $this->_getList($this->getListQuery());
}
```
which works, but I think there's a more Joomla-ish way of doing this - I just can't find it.
|
2014/07/30
|
[
"https://joomla.stackexchange.com/questions/3808",
"https://joomla.stackexchange.com",
"https://joomla.stackexchange.com/users/90/"
] |
To answer the question in the title about "setting" the limit, this is done in the Joomla global configuration: "Default List Limit".
To override, Joomla components generally seem to use this in the model:
Using `$limit = 0` shows all items
```
protected function populateState($ordering = null, $direction = null)
{
// set limit
$this->setState('list.limit', $limit);
// set start (eg. what record to begin pagination at)
$this->setState('list.start', $value);
}
```
|
23,977,264 |
I was wondering how I can initialize a `std::vector` of strings, without having to use a bunch of `push_back`'s in *Visual Studio Ultimate 2012*.
---
I've tried `vector<string> test = {"hello", "world"}`, but that gave me the following error:
>
> `Error: initialization with '{...}' is not allowed for an object of type "std::vector<std::string, std::allocator<std::string>>`
>
>
>
---
* Why do I receive the error?
* Any ideas on what I can do to store the strings?
|
2014/06/01
|
[
"https://Stackoverflow.com/questions/23977264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535589/"
] |
**The problem**
You'll have to upgrade to a more recent compiler version (and standard library implementation), if you'd like to use what you have in your snippet.
*VS2012* [doesn't support](http://msdn.microsoft.com/en-us/library/hh567368.aspx) `std::initializer_list`, which means that the overload among `std::vector`'s constructors, that you are trying to use, simply doesn't exist.
In other words; the example cannot be compiled with *VS2012*.
* [**msdn.com** - Support For C++11 Features (Modern C++)](http://msdn.microsoft.com/en-us/library/hh567368.aspx)
---
**Potential Workaround**
Use an intermediate *array* to store the `std::string`s, and use that to initialize the vector.
```
std::string const init_data[] = {
"hello", "world"
};
std::vector<std::string> test (std::begin (init_data), std::end (init_data));
```
|
10,598 |
Reading [the answer to a question about Sabé](https://scifi.stackexchange.com/a/10590/2565) (the Amidala stand-in) I remembered that I always wondered why she ordered the actual queen to scrub R2-D2. There were enough actual servants who could have done it, so why Padmé? If that wasn't enough, after giving the actual queen (Padmé) the order to go away, she tells Panaka to continue with the discussion. How does that make sense?
The significant piece of dialogue:
>
> AMIDALA : Thank you, Artoo Detoo. You have proven to be very loyal...Padme!
> ...
>
> AMIDALA : (Cont'd) Clean this droid up the best you can. It deserves our gratitude...(to Panaka) Continue, Captain.
>
>
>
Note that this question is two-fold:
1. Why was Padmé chosen in the first place?
2. Why would an important meeting with the ship's captain be continued without her?
|
2012/02/07
|
[
"https://scifi.stackexchange.com/questions/10598",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/2565/"
] |
1. It underscores the subterfuge - if the "queen" were deferential and reluctant to use a particular handmaiden as a servant, that would raise suspicions. If Padme wanted to be seen as a servant, she would have walk the walk.
2. I think that Sabé was well-trained enough to handle the situation. They were out of danger, and she could couch any major decision she was pressed for as "I need some time to think about it", huddle with Padme, and there you are. If you've cultivated a habit of consulting your handmaidens *anyway*, this seems perfectly logical - I suspect that the handmaidens are probably noble-born and highly educated as well.
|
60,989,333 |
I have array:
`const someArray = ['one', 'two', 'three'];`
and I have type:
`type SomeType = 'one' | 'two' | 'three';`
How can I get `SomeType` from `someArray`?
|
2020/04/02
|
[
"https://Stackoverflow.com/questions/60989333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10561224/"
] |
You can, at the cost that you have to apply `as const` assertion to `someArray`.
```
const someArray = ['one', 'two', 'three'] as const;
/* ^------- IMPORTANT!
otherwise it'll just be `string[]` */
type GetItem<T> = T extends ReadonlyArray<infer I> ? I : never;
type SomeType = GetItem<typeof someArray>; // 'one' | 'two' | 'three'
```
|
43,798 |
I have been playing piano for almost 7 years. I am trying to learn "Flight of the Bumblebee", Rachmaninoff version. The problem is that the left hand has certain chords that my fingers cannot reach. There is AEC#, C#AE, F#ADA, and maybe more. I am able to reach an octave and one note over an octave, but thats it. I have tried compromising notes to fit my finger length, but it makes the song sound different. I don't know what to do, because this is an an assignment that is due on May 31.
|
2016/04/23
|
[
"https://music.stackexchange.com/questions/43798",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/28137/"
] |
Very large chords like the one you mention are quite common in fact in classical romantic music piano literature.
Basics about this issue is, play like an arpeggio (alephzero answer). Most pianists do that indeed. This is absolutely normal, as even pianists with very long fingers can't reach some insane chords (see image; *La Campanella* from Lizst).
[](https://i.stack.imgur.com/RlXxB.jpg)
One practical way of doing this is simply working on hand/wrist (and not fingers) movement. Just bring the fingers in order for them to do their job with the help of your entire arm.
|
31,284,260 |
I am using Intellij idea IDE. Whenever I try to copy and paste any code from my browser to the IDE, it is not being pasted. Actually the last selection in the IDE is pasted every time. However if I paste it in any other application like notepad, it works fine.
What do I need to do?
|
2015/07/08
|
[
"https://Stackoverflow.com/questions/31284260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3186914/"
] |
I solved this problem by restarting intellij with the `invalidate cache\restart" menu option. Prior to restarting anything I'd had copied to the clipboard outside the IDE I couldn't paste, but afterward I could paste. I didn't investigate if just restarting would have worked. The menu option provides a nice way of closing all intellij windows at once on Windows.
|
66,507,096 |
I wanted to create something simple like void Function(struct str) to calculate paralel in barriers sync, but seems to not be so simple, so I followed this:
<https://learn.microsoft.com/en-us/windows/win32/procthread/creating-threads>
and some other topics, but without success. Couldnt find a solution. Code is all in one file.
Any advise how to fix it? make it work?
**Solved by std::thread rewrite**
[](https://i.stack.imgur.com/AzkTH.png)
|
2021/03/06
|
[
"https://Stackoverflow.com/questions/66507096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10705548/"
] |
Note how when you cast `lpParam` to a `dectectorData*` you should cast like this: `(detectorData*)lpParam` not `(detectorData)lpParam`. (Note the `*` denoting a pointer.)
|
12,573,839 |
I am a newby to design and looking now into the use of background instead of foreground images, which is a common practice.
I look at the techniques used, and see that:
* you usually need to explicitly state the dimensions of the image (and set the foreground element to these dimensions)
* you need to make the foreground element to somehow disappear with css tricks.
All this looks really hackish. So, I wonder, why on earth do all this instead of just using the native element? I am sure there is a good answer
(I did go through this [When to use IMG vs. CSS background-image?](https://stackoverflow.com/questions/492809/when-to-use-img-vs-css-background-image) , and could not figure out a clear answer)
|
2012/09/24
|
[
"https://Stackoverflow.com/questions/12573839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/440925/"
] |
The main difference is that in the `img` tag the image is *hardcoded*.
With CSS you can create different designs, switch between them, redesign the page, without altering the source code. To see the power of CSS, check <http://www.csszengarden.com/>, all the pages use the same HTML source, but with different CSS layout.
As @Shmiddty noted, if `img` is for embedded images (actual content, for example a gallery, or a picture for an article), and CSS is for design.
Also, the question you referred to, has nice list of all the use-cases: `When to use CSS background-image`.
|
2,967,436 |
How can i form of the matrix representation in the following exercise?
>
> Given the linear maps $f$ and $g$
>
>
> $$f\left(\begin{bmatrix}\lambda\_1\\ \lambda\_2\\ \lambda\_3\end{bmatrix}\right)=\begin{bmatrix}\lambda\_3-\lambda\_1\\\lambda\_2-\lambda\_1\end{bmatrix}\\ g\left(\begin{bmatrix}\mu\_1\\\mu\_2\end{bmatrix}\right)=\begin{bmatrix}\mu\_2-\mu\_1\\ -2\mu\_1\\ \mu\_1+\mu\_2\end{bmatrix}$$
>
>
> find the matrix repesentation of $g\circ f$.
>
>
>
|
2018/10/23
|
[
"https://math.stackexchange.com/questions/2967436",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/605276/"
] |
The matrix representation of $T:\Bbb R^n\to\Bbb R^m$ (in the canonical basis) is simply the matrix $$\begin{pmatrix}T(e\_1)& T(e\_2)&\cdots &T(e\_n)\end{pmatrix}.$$
This can be easily computed in this instance.
|
19,037 |
**Thought 1**
```
public interface IRepository<T> : IDisposable where T : class
{
IQueryable<T> Fetch();
IEnumerable<T> GetAll();
IEnumerable<T> Find(Func<T, bool> predicate);
T Single(Func<T, bool> predicate);
T First(Func<T, bool> predicate);
void Add(T entity);
void Delete(T entity);
void SaveChanges();
}
```
with the above approach I will go like Repository and then have a Repository
with the implementation of methods written above.
I think this frees my tests from DbContext dependency.
**Thought 2**
```
public class RepositoryBase<TContext> : IDisposable where TContext : DbContext, new()
{
private TContext _DataContext;
protected virtual TContext DataContext
{
get
{
if (_DataContext == null)
{
_DataContext = new TContext();
}
return _DataContext;
}
}
public virtual IQueryable<T> GetAll<T>() where T : class
{
using (DataContext)
{
return DataContext.Set<T>();
}
}
public virtual T FindSingleBy<T>(Expression<Func<T, bool>> predicate) where T : class
{
if (predicate != null)
{
using (DataContext)
{
return DataContext.Set<T>().Where(predicate).SingleOrDefault();
}
}
else
{
throw new ArgumentNullException("Predicate value must be passed to FindSingleBy<T>.");
}
}
public virtual IQueryable<T> FindAllBy<T>(Expression<Func<T, bool>> predicate) where T : class
{
if (predicate != null)
{
using (DataContext)
{
return DataContext.Set<T>().Where(predicate);
}
}
else
{
throw new ArgumentNullException("Predicate value must be passed to FindAllBy<T>.");
}
}
public virtual IQueryable<T> FindBy<T, TKey>(Expression<Func<T, bool>> predicate,Expression<Func<T, TKey>> orderBy) where T : class
{
if (predicate != null)
{
if (orderBy != null)
{
using (DataContext)
{
return FindAllBy<T>(predicate).OrderBy(orderBy).AsQueryable<T>(); ;
}
}
else
{
throw new ArgumentNullException("OrderBy value must be passed to FindBy<T,TKey>.");
}
}
else
{
throw new ArgumentNullException("Predicate value must be passed to FindBy<T,TKey>.");
}
}
public virtual int Save<T>(T Entity) where T : class
{
return DataContext.SaveChanges();
}
public virtual int Update<T>(T Entity) where T : class
{
return DataContext.SaveChanges();
}
public virtual int Delete<T>(T entity) where T : class
{
DataContext.Set<T>().Remove(entity);
return DataContext.SaveChanges();
}
public void Dispose()
{
if (DataContext != null) DataContext.Dispose();
}
}
```
I could now have `CustomerRepository : RepositoryBase<Mycontext>,ICustomerRepository`
`ICustomerRepository` gives me the option of defining stuff like `GetCustomerWithOrders` etc...
I am confused as to which approach to take. Would need help through a review on the implementation first then comments on which one will be the easier approach when it comes to Testing and extensibility.
|
2012/11/26
|
[
"https://codereview.stackexchange.com/questions/19037",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/7511/"
] |
You should use `Expression<Func<T, bool>>` as predicates on your interface and have the `RepositoryBase` implement that interface.
By only using `Func`, you won't get translation to L2E etc, but will have to enumerate the entire DB table before you can evaluate the `Func`.
The interface can be mocked, hence unit-tested without a physical db and also used with other ORMs.
It's generally prefered to keep `SaveChanges` and the `DbContext` in a separate `IUnitOfWork` implementation. You can pass the `UnitOfWork` to the repository constructor, which can access an internal property on the UOW exposing the `DbContext`.
By doing that you can share the same `DbContext` between repositories, and batch updates to several entity roots of different type. You also keep fewer open connections, which are the most expensive resource you have when it comes to DBs.
Not to forget they can share transactions. :)
Hence you should not dispose the DbContext in the Repository, the Repository really doesn't need to be disposable at all. But the UnitOfWork / DbContext must be disposed by something.
Also, ditch the `OrderBy` predicate to `FindBy`. Since you return an `IQueryable`, and use an `Expression` for the predicate, you can keep building the Queryable after the call. For instance `repo.FindBy(it => it.Something == something).OrderBy(it => it.OrderProperty)`. It will still be translated to "select [fields] from [table] where [predicate] order by [orderprop]" when enumerated.
Otherwise it looks good.
Here's a couple of good examples:
<http://blog.swink.com.au/index.php/c-sharp/generic-repository-for-entity-framework-4-3-dbcontext-with-code-first/>
<http://www.martinwilley.com/net/code/data/genericrepository.html>
<http://www.mattdurrant.com/ef-code-first-with-the-repository-and-unit-of-work-patterns/>
And here's how I do it:
**Model / Common / Business assembly**
No references but BCL and other possible models (interfaces/dtos)
```
public interface IUnitOfWork : IDisposable
{
void Commit();
}
public interface IRepository<T>
{
void Add(T item);
void Remove(T item);
IQueryable<T> Query();
}
// entity classes
```
**Business tests assembly**
Only references Model / Common / Business assembly
```
[TestFixture]
public class BusinessTests
{
private IRepository<Entity> repo;
private ConcreteService service;
[SetUp]
public void SetUp()
{
repo = MockRepository.GenerateStub<IRepository<Entity>>();
service = new ConcreteService(repo);
}
[Test]
public void Service_DoSomething_DoesSomething()
{
var expectedName = "after";
var entity = new Entity { Name = "before" };
var list = new List<Entity> { entity };
repo.Stub(r => r.Query()).Return(list.AsQueryable());
service.DoStuff();
Assert.AreEqual(expectedName, entity.Name);
}
}
```
**Entity Framework implementation assembly**
References Model *and* the Entity Framework / System.Data.Entity assemblies
```
public class EFUnitOfWork : IUnitOfWork
{
private readonly DbContext context;
public EFUnitOfWork(DbContext context)
{
this.context = context;
}
internal DbSet<T> GetDbSet<T>()
where T : class
{
return context.Set<T>();
}
public void Commit()
{
context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
public class EFRepository<T> : IRepository<T>
where T : class
{
private readonly DbSet<T> dbSet;
public EFRepository(IUnitOfWork unitOfWork)
{
var efUnitOfWork = unitOfWork as EFUnitOfWork;
if (efUnitOfWork == null) throw new Exception("Must be EFUnitOfWork"); // TODO: Typed exception
dbSet = efUnitOfWork.GetDbSet<T>();
}
public void Add(T item)
{
dbSet.Add(item);
}
public void Remove(T item)
{
dbSet.Remove(item);
}
public IQueryable<T> Query()
{
return dbSet;
}
}
```
**Integrated tests assembly**
References everything
```
[TestFixture]
[Category("Integrated")]
public class IntegratedTest
{
private EFUnitOfWork uow;
private EFRepository<Entity> repo;
[SetUp]
public void SetUp()
{
Database.SetInitializer(new DropCreateDatabaseAlways<YourContext>());
uow = new EFUnitOfWork(new YourContext());
repo = new EFRepository<Entity>(uow);
}
[TearDown]
public void TearDown()
{
uow.Dispose();
}
[Test]
public void Repository_Add_AddsItem()
{
var expected = new Entity { Name = "Test" };
repo.Add(expected);
uow.Commit();
var actual = repo.Query().FirstOrDefault(e => e.Name == "Test");
Assert.IsNotNull(actual);
}
[Test]
public void Repository_Remove_RemovesItem()
{
var expected = new Entity { Name = "Test" };
repo.Add(expected);
uow.Commit();
repo.Remove(expected);
uow.Commit();
Assert.AreEqual(0, repo.Query().Count());
}
}
```
|
26,777,043 |
For example:
```
<p class="Pa0" style="margin: 0in 0in 0pt;"><span class="A1"><span style="font-size: 10pt;">Giving this flyer to your class customers Giving this flyer to your class customers Giving this flyer to your class customers Giving this flyer to your class customers Giving this flyer to your class customers Giving this flyer to your class customers Giving this flyer to your class customers Giving this flyer to your class customers Giving this flyer to your class customers Giving this flyer to your class customers Giving this flyer to your class customers Giving this flyer to your class customers Giving this flyer to your class customers</span></span></p>Giving this flyer to your class customers Giving this flyer to your class customers
```
Regex:
```
<[^<>]+>[^<>.!?]{250}
```
It should select all the first 250 characters ignoring html tags. It ignores first html tag occurance but selects the second
|
2014/11/06
|
[
"https://Stackoverflow.com/questions/26777043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109946/"
] |
Of course there is something more elegant out there, but as you didn't try that hard to format your question, I'm gonna try something different, just for the sake of it. It works, nonetheless.
```
var str = @"<p>something here<H3>Title</H3></p>";
// Add and remove "<" chars on the stack. When we don't have any "<"
// chars on the stack, it means we're in the contents sections of the tag.
var stack = new Stack<string>();
// Avoid peeking an empty stack.
stack.Push("base");
// This will be your resulting string and number of chars.
var result = "";
var resultLimit = 5;
foreach (var ch in str)
{
// Limit reached.
if (result.Count() == resultLimit)
break;
// Entering a tag.
if (ch == '<')
{ stack.Push("start"); continue; }
// Leaving a tag.
if (ch == '>')
{ stack.Pop(); continue; }
// We're not in a tag at the moment, so take this char.
if (stack.Peek() != "start")
result += ch;
}
```
|
3,529,430 |
I try to generate a trigger, in the trigger statement I have to set a column of type decimal(17,3) with the actual timestamp or the seconds of unix timestamp, but could not find a solution.
|
2010/08/20
|
[
"https://Stackoverflow.com/questions/3529430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/275837/"
] |
One definition of foldr is:
```
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f acc [] = acc
foldr f acc (x:xs) = f x (foldr f acc xs)
```
The [wikibook on Haskell](http://en.wikibooks.org/wiki/Haskell/List_processing) has a nice graph on foldr (and on other folds, too):
```
: f
/ \ / \
a : foldr f acc a f
/ \ -------------> / \
b : b f
/ \ / \
c [] c acc
```
I.e. `a : b : c : []` (which is just `[a, b, c]`) becomes `f a (f b (f c acc))` (again, taken from wikibook).
So your example is evaluated as `let f = (\x y -> 2*x + y) in f 5 (f 6 (f 7 4))` (let-binding only for brevity).
|
53,495,531 |
We are extracting a large amount of JSON objects from an EVE Online API, and deseralizing them into EveObjModel objects using Newtonsoft.Json.JsonConvert. From there we want to create a list of unique objects, i.e. the most expensive of each type\_id. I have pasted the dataContract below as well.
**The problem:** This code below can handle smaller sets of data, but it is not viable with larger amounts. Currently, we are running it through and it takes more than 50 minutes (and counting). What can we do to reduce the time it takes to run through larger sets of data to a bearable level?
Thank you for your time. Fingers crossed.
```
// The buyList contains about 93,000 objects.
public void CreateUniqueBuyList(List<EveObjModel> buyList)
{
List<EveObjModel> uniqueBuyList = new List<EveObjModel>();
foreach (EveObjModel obj in buyList)
{
int duplicateCount = 0;
for (int i = 0; i < uniqueBuyList.Count; i++)
{
if (uniqueBuyList[i].type_id == obj.type_id)
duplicateCount++;
}
if (duplicateCount == 1)
{
foreach (EveObjModel objinUnique in uniqueBuyList)
{
if (obj.type_id == objinUnique.type_id && obj.price > objinUnique.price)
{
// instead of adding obj, the price is just changed to the price in the obj.
objinUnique.price = obj.price;
}
else if (obj.type_id == objinUnique.type_id && obj.price == objinUnique.price)
{
//uniqueBuyList.RemoveAll(item => item.type_id == obj.type_id);
}
else
{
// Hitting this mean that there are other objects with same type and higher price OR its not the same type_id
}
}
}
else if (duplicateCount > 1)
{
// shud not happn...
}
else
{
uniqueBuyList.Add(obj);
}
continue;
}
foreach (EveObjModel item in uniqueBuyList.OrderBy(item => item.type_id))
{
buyListtextField.Text += $"Eve Online Item! Type-ID is: {item.type_id}, Price is {item.price}\n";
}
}
```
This is our EveObjModel class
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace EveOnlineApp
{
[DataContract]
public class EveObjModel
{
[DataMember]
public bool is_buy_order { get; set; }
[DataMember]
public double price { get; set; }
[DataMember]
public int type_id { get; set; }
}
}
```
|
2018/11/27
|
[
"https://Stackoverflow.com/questions/53495531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7766834/"
] |
It's not surprising that the process is slow, because the algorithm you are using (with nested loop) has at least quadratic O(N\*N) time complexity, which with such size of data sets is really slow.
One way is to use LINQ `GroupBy` operator, which internally uses hash based lookup, hence has theoretically O(N) time complexity. So you group by `type_id` and for each group (list of elements with the same key) take the one with the maximum `price`:
```
var uniqueBuyList = buyList
.GroupBy(e => e.type_id)
.Select(g => g.OrderByDescending(e => e.price).First())
.ToList();
```
Of cource you don't need to sort the list in order to take the element with the max `price`. A better version is to use `Aggregate` method (which is basically `foreach` loop) for that:
```
var uniqueBuyList = buyList
.GroupBy(e => e.type_id)
.Select(g => g.Aggregate((e1, e2) => e1.price > e2.price ? e1 : e2))
.ToList();
```
Another non LINQ based way is to sort the input list by `type_id` ascending, `price` descending. Then do a single loop over the sorted list and take the first element of each `type_id` group (it will have the maximum `price`):
```
var comparer = Comparer<EveObjModel>.Create((e1, e2) =>
{
int result = e1.type_id.CompareTo(e2.type_id);
if (result == 0) // e1.type_id == e2.type_id
result = e2.price.CompareTo(e1.price); // e1, e2 exchanged to get descending order
return result;
});
buyList.Sort(comparer);
var uniqueBuyList = new List<EveObjModel>();
EveObjModel last = null;
foreach (var item in buyList)
{
if (last == null || last.type_id != item.type_id)
uniqueBuyList.Add(item);
last = item;
}
```
The complexity of this algorithm is O(N\*log(N)), so it's worse than the hash based algorithms (but much better than original). The benefit is that it uses less memory and the resulting list is already sorted by `type_id`, so you don't need to use `OrderBy`.
|
19,131,927 |
```
void replace3sWith4s(int[] replace){
for (int i = 0;i<replace.length;i++){
if (replace[i]==3);{
replace[i]=4;
}
}
}
```
My program is replacing all numbers with #4 but I want to have an array that contains 3,
takes an integer array, and changes any element that has the value 3 to instead have the value 4.
|
2013/10/02
|
[
"https://Stackoverflow.com/questions/19131927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2837656/"
] |
```
if (replace[i]==3);
^^^
```
Remove the semicolon.
It should be
```
if (replace[i]==3) {
replace[i]=4;
}
```
The semicolon changes the meaning to
```
if (replace[i]==3)
;//do nothing
// Separate New block
{
replace[i]=4;
}
```
|
22,343 |
I saw this question somewhere in the Internet(I forgot the source) and I think this forum is a good place to ask it.
According to what I know, the atoms in a persons body are replaced every certain amount of years:
<https://skeptics.stackexchange.com/questions/18427/are-all-the-atoms-in-our-bodies-replaced-on-a-regular-basis>
Then, if a persons body atoms are replaced every x years, should the person be prosecuted today for a crime that he/she committed x years ago, when today that person is physically another person(different atoms)?
And lets say hypothetically that 0.00001% of atoms are never replaced, should 0.99999% of the sentence in years be eliminated (the person is 0.00001% responsible for the crime) ?
This is a related question in the forum:
[Am I still the same person as I was yesterday?](https://philosophy.stackexchange.com/questions/2747/am-i-still-the-same-person-as-i-was-yesterday)
|
2015/03/15
|
[
"https://philosophy.stackexchange.com/questions/22343",
"https://philosophy.stackexchange.com",
"https://philosophy.stackexchange.com/users/13954/"
] |
Atoms do not contain little tags that say "I am part of user63152", and whose unique properties determine the actions of user63152. Indeed, aside from differences in isotopes, and a handful of observables like nuclear spin, atoms of the same type are indistinguishable from each other.
Thus, we needn't care whether the atoms are replaced every minute, every decade, or never. That ongoing entity which is you is you by virtue of emergent properties (like thought) which are robust to changes in which atoms you are made from. So while time may have *some* bearing on how we choose to prosecute crime, it should *not* be because there has been some swapping around of functionally equivalent parts.
|
71,708,084 |
I am just looking for some advice on if there is a more efficient way to write the below, make it a little more DRY?
```
<h2>{{ title }}</h2>
<p>{{ subtitle }}</p>
```
As I am making the same check for this.name on both title and subtitle I thought there could be a between way than my current implementation, any ideas?
```
computed: {
title() {
if (this.name === 'discounts_offers') {
return this.$t('discounts.title')
}
if (this.name === 'newsletter') {
return this.$t('newsletters.title')
}
if (this.name === 'product_upgrade') {
return this.$t('upgrade.title')
}
return this.name
},
subtitle() {
if (this.name === 'discounts_offers') {
return this.$t('discounts.subtitle')
}
if (this.name === 'newsletter') {
return this.$t('newsletters.subtitle')
}
if (this.name === 'product_upgrade') {
return this.$t('upgrade.subtitle')
}
return this.name
},
}
```
|
2022/04/01
|
[
"https://Stackoverflow.com/questions/71708084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4146183/"
] |
How about something like this?
```js
data() {
return {
map: {
discounts_offers: "discounts",
newsletter: "newsletters",
product_upgrade: "upgrade"
}
}
},
computed: {
title() {
return this.map[this.name] ? this.$t(`${this.map[this.name]}.title`) : this.name
},
subtitle() {
return this.map[this.name] ? this.$t(`${this.map[this.name]}.subtitle`) : this.name
},
}
```
|
58,557,803 |
I'm want to add **OR** condition in the JSON query of Cube.js. But once I added one more condition in the filter it always adds **AND** condition in SQL query.
Below is the JSON query that I'm trying.
```
{
"dimensions": [
"Employee.name",
"Employee.company"
],
"timeDimensions": [],
"measures": [],
"filters": [
{
"dimension": "Employee.company",
"operator": "contains",
"values": [
"soft"
]
},
{
"dimension": "Employee.name",
"operator": "contains",
"values": [
"soft"
]
}
]
}
```
It generates below SQL query.
```sql
SELECT
`employee`.name `employee__name`,
`employee`.company `employee__company`
FROM
DEMO.Employee AS `employee`
WHERE
`employee`.company LIKE CONCAT('%', 'soft', '%')
AND
`employee`.name LIKE CONCAT('%', 'soft', '%')
GROUP BY
1,
2;
```
What is the JSON query for Cube.js if I want to generate below SQL
```sql
SELECT
`employee`.name `employee__name`,
`employee`.company `employee__company`
FROM
DEMO.Employee AS `employee`
WHERE
`employee`.company LIKE CONCAT('%', 'soft', '%')
OR
`employee`.name LIKE CONCAT('%', 'soft', '%')
GROUP BY
1,
2;
```
|
2019/10/25
|
[
"https://Stackoverflow.com/questions/58557803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12118067/"
] |
API support for logical operators isn't shipped yet. Meanwhile there're several workarounds:
1. Define dimension that mimics **OR** behavior. In your case it's
```js
cube(`Employee`, {
// ...
dimensions: {
companyAndName: {
sql: `CONCAT(${company}, ' ', ${name})`,
type: `string`
}
}
});
```
2. Define segments. Those can be also generated: <https://cube.dev/docs/schema-generation>
```js
cube(`Employee`, {
// ...
segments: {
soft: {
sql: `${company} LIKE CONCAT('%', 'soft', '%') OR ${name} LIKE CONCAT('%', 'soft', '%')`
}
}
});
```
|
43,374,103 |
Being rather new to socket programming and threading in general, my issue might be stemming from a misunderstanding of how they work. I am trying to create something that acts as both a client and a server using threading.
Following:
<https://docs.python.org/3/library/socketserver.html#asynchronous-mixins>
I created a client class to go with the server and executed both from a main class. The server supposedly launches normally and doesn't give any errors but when I try to connect from the client, it fails on the following:
```
# In client connection
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((ip, port))
```
the error I am getting is:
```
Traceback (most recent call last):
File "./<project>", line 61, in <module>
client.start_client(serverInfo)
File "/home/<username>/Documents/Github/project/client.py", line 54, in <startclient>
<connectionMethod>(cmd)
File "/home/<username>/Documents/Github/project/client.py", line 112, in <connectionMethod>
sock.connect((remoteHOST,remotePORT))
ConnectionRefusedError: [Errno 111] Connection refused
```
Even when I modify the server from the code in the referenced python page (just to run on a specific port, 1234), and try to connect to that port with
```
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(('127.0.0.1',1234))
sock.sendall('Test message')
```
I get the same problem
```
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ConnectionRefusedError: [Errno 111] Connection refused
```
Why is the server refusing connections? No firewall rules or iptables are in place, running the example that has the client and socket together as is from the site works but even removing the `server.shutdown()` line it still kills itself immediately.
Am I missing something?
The behaviour I am expecting is:
```
./programA
<server starts on port 30000>
```
```
./programB
<server starts on port 30001>
<client starts>
```
--- input/output ---
FROM CLIENT A:
```
/connect 127.0.0.1 30001
CONNECTED TO 127.0.0.1 30001
```
ON CLIENT B:
```
CONNECTION FROM 127.0.0.1 30000
```
Basically once the clients connect the first time they can communicate with each other by typing into a prompt which just creates another socket targeting the 'remote' IP and PORT to send off the message (instant messaging). The sockets are afterwords left to close because they aren't actually responsible for receiving anything back.
I would appreciate any help I can get on this.
|
2017/04/12
|
[
"https://Stackoverflow.com/questions/43374103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2763113/"
] |
You could do something like below. Your elements need a `float:left;`.
Though there are far better ways to handle this. You should really change your HTML to use `span` instead of `div` to achieve the final solution.
```css
/* CSS used here will be applied after bootstrap.css */emergency{
color: #1D1060;
}
.alert-color{
color: #0F75BC;
}
.normal{
color:#6DC2E9;
}
.sys-cond-list ul li span{
color: #4B5D6B;
}
.sys-cond-list{
font-size: 12px;
}
#currState{
color: #3379A3;
float:left;
margin:24px 0 0 10px;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-sm-10" style="float: left">
<div class="system-cond" style="position: absolute">
<p style="text-align: left;float:left;">Our current<br>condition is: <strong>
</strong></p><div id="currState"><strong>Normal</strong></div><p></p>
</div>
</div>
</div>
</div>
```
|
355,341 |
Recently the Reopen Votes queue has been overrun with questions that have been closed, then edited by a user who is not the asker after the closure, and their edit has been approved.
95% of the time this happens, this approved edit does nothing to attempt to fix the question's content, but consists merely of formatting tweaks - which has the sole effect of (a) gaining rep for the editor (b) pushing the question into the Reopen Votes queue where shmucks like myself have to take a look at it to confirm that yes, it is still terribad and should never be reopened.
My procedure so far has been to go back to the stupidly-edited question and mod flag them with a comment that the edit is bad and whoever approved it should be review-banned, but seriously... that isn't instant, I have better things to do with my day, and I'm not the one who approved the bad edit and caused the problem in the first place, so why should I have to suffer?
I haven't thought long and hard about this, but I feel that some ways this could be mitigated (aside from review-banning the a\*\*hats who are accepting these useless reviews) are:
* If a question was closed as a dupe, don't nominate it for reopening if it's edited by someone other than the asker.
* If a question is closed, and someone who is not the asker edits it after the fact, show a warning banner on the edit screen - something to the effect of "This question was closed due to serious problems; please do not edit it unless you are certain you can materially improve its content to make it answerable".
* If an edit in the Suggested Edits queue is for a closed question and was not performed by the asker of the question, show a warning banner on that suggested edit for that particular question to reviewers.
Please proceed to shoot holes in my suggestions and/or tell me I'm a terrible human being. You could also provide your own thoughts and suggestions on how this can be addressed, if you're feeling constructive. ;)
Also if there is a better way to deal with bad suggested edits than mod-flagging the offending questions, please advise.
|
2017/08/19
|
[
"https://meta.stackoverflow.com/questions/355341",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/70345/"
] |
Here's a better suggestion: edits should only cause questions to go into the reopen queue if the OP is the editor.
Let's consider every possible close reason, and then decide who is more likely to make an edit that makes the question reopen-worthy:
* Duplicate: If the question is not a duplicate, the OP is the one who is most able to disambiguate it from the dupe-target.
* Off-topic/General Computing/Hardware: If the question is not hardware-related, the OP is the best person to be able to explain why this is not the case.
* Off-topic/Server: Ditto
* Off-topic/Recommendation: If a question looks like a recommendation question but is instead a "how to achieve X" question, it is possible that people who aren't the OP can explain the difference.
* Off-topic/MCVE: The OP is the person who has the code; therefore, they are in the best position to provide the code.
* Off-topic/No-Repro: Such questions usually don't get reopened. But if they do, it is usually by the OP providing further information/clarification. Which the OP is uniquely suited to do.
* Unclear: The OP is the person most likely to be able to provide sufficient information to clarify the problem. Others may be able to guess sometimes, but only the OP *knows*.
* Too Broad: The OP is the *only one* who can narrow it down. They're the only one who knows exactly what they're looking for.
* Opinion-based: The OP is the person most capable of finding a more objective form of their question. If someone else has a more objective form, they can ask it anew themselves.
Note that there are a lot of "most likely" equivocation in the above statements. Yes, I recognize that it is *possible* for other people to provide that information in those cases. So what?
If the OP is not engaged enough to fix the problem with their question themselves, then they're not really in a position to ask someone else to do it. Therefore, only edits by the OP should be considered when putting something in the reopen queue.
Furthermore, the OP already failed once. We need to teach the OP how to fix their question's problems. And that's not done by fixing them for them. By only considering OP edits, we make sure that other people coming along to fix it won't get the same effect. This rewards OPs who actually work to improve their questions.
|
802,877 |
i get following errors when trying to open programs over ssh.
```
$ thunar
Thunar: Cannot open display:
$ libreoffice
Failed to open display
$ firefox
Error: GDK_BACKEND does not match available displays
$ keepassx
keepassx: cannot connect to X server
$ keepass2
Unhandled Exception:
System.TypeInitializationException: The type initializer for 'System.Windows.Forms.XplatUI' threw an exception. ---> System.ArgumentNullException: Could not open display (X-Server required. Check your DISPLAY environment variable)
Parameter name: Display
at System.Windows.Forms.XplatUIX11.SetDisplay (IntPtr display_handle) <0x41b3c8a0 + 0x00b9b> in <filename unknown>:0
at System.Windows.Forms.XplatUIX11..ctor () <0x41b3ab20 + 0x001df> in <filename unknown>:0
at System.Windows.Forms.XplatUIX11.GetInstance () <0x41b3a8d0 + 0x0005b> in <filename unknown>:0
at System.Windows.Forms.XplatUI..cctor () <0x41b3a160 + 0x00137> in <filename unknown>:0
--- End of inner exception stack trace ---
at System.Windows.Forms.Application.EnableVisualStyles () <0x41b38870 + 0x0001b> in <filename unknown>:0
at KeePass.Program.Main (System.String[] args) <0x41b376c0 + 0x0008b> in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.TypeInitializationException: The type initializer for 'System.Windows.Forms.XplatUI' threw an exception. ---> System.ArgumentNullException: Could not open display (X-Server required. Check your DISPLAY environment variable)
Parameter name: Display
at System.Windows.Forms.XplatUIX11.SetDisplay (IntPtr display_handle) <0x41b3c8a0 + 0x00b9b> in <filename unknown>:0
at System.Windows.Forms.XplatUIX11..ctor () <0x41b3ab20 + 0x001df> in <filename unknown>:0
at System.Windows.Forms.XplatUIX11.GetInstance () <0x41b3a8d0 + 0x0005b> in <filename unknown>:0
at System.Windows.Forms.XplatUI..cctor () <0x41b3a160 + 0x00137> in <filename unknown>:0
--- End of inner exception stack trace ---
at System.Windows.Forms.Application.EnableVisualStyles () <0x41b38870 + 0x0001b> in <filename unknown>:0
at KeePass.Program.Main (System.String[] args) <0x41b376c0 + 0x0008b> in <filename unknown>:0
:06:22 PM~/Documents$ gimp
Cannot open display:
$ wireshark
QXcbConnection: Could not connect to display
Aborted (core dumped)
$ gedit
Failed to connect to Mir: Failed to connect to server socket: No such file or directory
Unable to init server: Could not connect: Connection refused
(gedit:23724): Gtk-WARNING **: cannot open display:
```
i've always been able to open aplications over ssh, this just started yesterday. using ubuntu 16.04 on both machines.
please DO NOT flag this as a repeat question, the following solutions didn't help:
<https://superuser.com/questions/310197/how-do-i-fix-a-cannot-open-display-error-when-opening-an-x-program-after-sshi>
[gksu: Gtk-WARNING \*\*: cannot open display: :0](https://askubuntu.com/questions/614387/gksu-gtk-warning-cannot-open-display-0)
[Gtk-WARNING \*\*: cannot open display: on Ubuntu Server](https://askubuntu.com/questions/471906/gtk-warning-cannot-open-display-on-ubuntu-server)
[(nautilus:13581): Gtk-WARNING \*\*: cannot open display:](https://askubuntu.com/questions/659299/nautilus13581-gtk-warning-cannot-open-display)
if specific info is needed, please ask, i'll do my best to answer.
|
2016/07/25
|
[
"https://askubuntu.com/questions/802877",
"https://askubuntu.com",
"https://askubuntu.com/users/572440/"
] |
It is necessary for you to tell us 3 things.
1. What command did you use to launch your ssh session.
Did you run
```
$ ssh -Y whatever.com
```
or
```
$ ssh -X whatever.com
```
If you had neither -X nor -Y, X11 forwarding won't work
2. Have you edited the ssh client configuration file on the client machine? If you changed that, tell us exactly what.
If you don't want to type -X every time you need X11 forwarding, it can
be set as default by editing /etc/ssh/ssh\_config. That's not the machine's server config, it is default for all clients. At the bottom of mine, I have
```
ForwardAgent yes
ForwardX11 yes
ForwardX11Trusted yes
```
I expect these changes will have no effect until you log out, but I may be wrong about that.
3. On the server machine, did you enable X11 forwarding?
On the server, in the file /etc/X11/sshd\_config, it will be necessary
to turn on X11 forwarding with a line like
```
X11Forwarding yes
```
Please note that change will not have an effect until the server is restarted, or at least its ssh server is restarted.
Let us know how that works. If it fails, report the config files and what you ran.
|
20,211,678 |
i have this (a rough e.g):
```
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label .../>
<TextBox .../>
<Button Content="Add new input row" ... />
</StackPanel>
</StackPanel>
```
pretty self explanatory, i want to add a new Horizontal StackPanel with every click on the button..
is that possible?
thank you!
|
2013/11/26
|
[
"https://Stackoverflow.com/questions/20211678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1900641/"
] |
You could use `strsplit` to split your string and then access the array element that you are interested in.
```
mystring = '245 0.00000000 2456171.50000000 1030492816.000 5.14501001 1 IG 5 -1.188022 .... 5.032154 90';
split = strsplit(mystring);
```
If your version of MATLAB is too old and `strsplit` isn't included, then it can be downloaded from [MATLAB central](http://www.mathworks.co.uk/matlabcentral/fileexchange/21710-string-toolkits/content/strings/strsplit.m).
Then you could use `str2num` or `str2double` to turn each string you are interested in into a number.
```
col5 = str2double(split(5));
% or
mycols = str2double(split([5 37 117]));
```
[strsplit reference](http://www.mathworks.co.uk/help/matlab/ref/strsplit.html)
[str2num reference](http://www.mathworks.co.uk/help/matlab/ref/str2num.html)
[str2double reference](http://www.mathworks.co.uk/help/matlab/ref/str2double.html)
|
29,386,877 |
I am using php to get json data and here is response.
```
{"array":[{"Category":{"charity_id":"2","charity_name":"GiveDirectly","charity_amt":"0.20"}}]}
```
and here is my Objective-c code
```
NSError *err;
NSURL *url=[NSURL URLWithString:@"url"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:&err];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
if ([json isKindOfClass:[NSDictionary class]]){
NSArray *yourStaffDictionaryArray = json[@"array"];
if ([yourStaffDictionaryArray isKindOfClass:[NSArray class]]){
for (NSDictionary *dictionary in yourStaffDictionaryArray) {
for(NSDictionary *dict in dictionary[@"Category"]){
NSLog(@"%@",[[((NSString*)dict) componentsSeparatedByString:@"="] objectAtIndex:0] );
}
}
}
}
```
But this only returns the name's not the value. I have searched most of the question on this site but nothing helped be. Please help me i am new to iOS.
Thanks
Dictionary output is
```
{
"charity_amt" = "0.20";
"charity_id" = 2;
"charity_name" = GiveDirectly;
}
```
|
2015/04/01
|
[
"https://Stackoverflow.com/questions/29386877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4341319/"
] |
I will suggest you use pl-upload jQuery plugin, I personally use this plugin and this is pretty easy and uploading is very fast.
Here are some of example :
[Read a blog here](http://django-posts.blogspot.in/2014/11/ajax-based-plupload-using-django.html)
[Code example you look here](https://github.com/vitalyvolkov/plupload-django-example)
|
94,886 |
So I have a server that has a few harddrives in it, all formatted and mounted. However I'm told there is another drive attached to it. How do I find out what drives are attached? How do I find out the device filename for this new drive (that's not mounted)
|
2009/12/16
|
[
"https://serverfault.com/questions/94886",
"https://serverfault.com",
"https://serverfault.com/users/8950/"
] |
`fdisk -l`
|
38,632,792 |
I use the following JQuery function to restrict users from writing numeric values in the textbox. The code works fine but the problem is that it also restrict users from using other characters like full stop(.), comma(,), $, @ and other signs..It also does not allow users to use the options of copy and past. I only want to restrict the users from writing numeric values or numbers but the user should be allowed to use other characters.
```
$(function() {
$('.txtOnly').keydown(function(e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});
```
|
2016/07/28
|
[
"https://Stackoverflow.com/questions/38632792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5588049/"
] |
Hope this helps:
```
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-1.12.2.js"></script>
</head>
<body>
<input class="txtOnly" id="txtOnly" name="txtOnly" type="text" />
<script>
$( document ).ready(function() {
$( ".txtOnly" ).keypress(function(e) {
var key = e.keyCode;
if (key >= 48 && key <= 57) {
e.preventDefault();
}
});
});
</script>
</body>
</html>
```
|
4,374,426 |
Hello there
i've written a small functions that takes two lists and compares them for duplicating pairs,
and returns a boolean value.
For instance ([1,2,3],[2,1,4]) returns false and ([1,2,3],[3,4,5]) returns true
But i would like the argument to take any given amount of lists, instead of just two.
Here's my program so far:
```
def check(xrr, yrr):
x = xrr[:]
x.sort()
y = yrr[:]
y.sort()
for i in range(len(x)-1):
if x[i]==y[i]:
return False
return True
```
But also it isnt exactly working correctly yet, as ([1,2,3],[1,4,5]) also returns false.
Any hints and ideas is highly appreciated
|
2010/12/07
|
[
"https://Stackoverflow.com/questions/4374426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/457142/"
] |
As a naive implementation, you can define a list of lists and hash the internal representation. For instance:
```
def check(given):
hash = {}
for li in given:
for val in li:
if val in hash:
return False
hash[val] = 1
return True
```
This works if your input data sets contain a small number of unique elements relative to memory. If you expect to receive extremely large data sets, you might need to consider a more elaborate approach.
Also notable is this will return `False` for repeating elements within the same data set, and for repeating values at any location within the data set. This is trivial to refactor, or to rewrite entirely as the other solutions listed here.
|
5,437,501 |
I have a concern of using GPL v2 and GPL v3 licensed software in commercial production environment. I would like to use HaProxy as a load balancing solution. Is it safe against copy-left? I won't modify anything from source code and the architecture of the system requires the use of a load balancer.
It will be embedded in a larger distributed system. So what we sell is the whole system. On another site, we will need to install the load balancer again and could mix with something else. I think it's the "Distributing" term which is confusing me.
|
2011/03/25
|
[
"https://Stackoverflow.com/questions/5437501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395146/"
] |
If you're distributing (unmodified) binaries along with a product you ship, then you're required to distribute the source with them, or provide a way for people to request the sources. This is not a situation where you can ignore the GPL, but it's not going to be a real problem for you. The GPL won't infect your proprietary software unless you link to it.
Distributing in this sense means giving (or selling) to customers. If you're just using a distributed (multi-node) system inside your company, then you're entirely in the clear, as yan says.
Incidentally, the [GPLv2](http://www.gnu.org/licenses/gpl-2.0.html) ([v3 here](http://www.gnu.org/licenses/gpl-3.0.html)) is written to be read by non-lawyers. I strongly recommend you take a look at it. If English isn't your first language, [translations](http://www.gnu.org/licenses/old-licenses/gpl-2.0-translations.html) are available in many languages.
|
21,212,121 |
I am new to jquery, Please help me resolve the below issue.
I have a modal popup and inside the popup i have two asp buttons(Search and close). Onclick of the search button i want to perform a validation and then fire the server button click event and on click of the close button i want to close the dialog.
**Problems faced:**
1. Onclick of search the jquery validation is happening but the server side event is not getting fired.
2. Onclick of close, the dialog is getting closed only for the first time but after click of the search button once, the close JQUERY is not getting fired.
**Below is the code:**
***button to open dialog***
```
<asp:Button ID="btnOpenDialog" runat="server" Text="Change"/>
```
***jquery to open dialog***
```
$("[id*=btnOpenDialog]").live("click", function () {
$("#modal_dialog").dialog({
title: "Details",
modal: true,
width: "700px"
});
return false;
})
```
***The dialog with the asp buttons***
```
<div id="modal_dialog" style="display:none">
<asp:Label ID="lblError" runat="server" Visible="true" ForeColor="Red"></asp:Label>
<asp:Label ID="lblLastName" runat="server" Text="Last Name"></asp:Label>
<asp:TextBox ID="txtLastName" Width="100px" runat="server"></asp:TextBox>
<asp:Label ID="lblFirstName" runat="server" Text="First Name"> </asp:Label>
<asp:TextBox ID="txtFirstName" Width="100px" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" UseSubmitBehavior="false" runat="server" Text="Search" OnClick="btnSearch_Click"/>
<asp:Button ID ="btnClose" Text="Close" runat="server"></asp:Button>
</div>
```
***The btnSearch JQUERY***
```
$("[id*=btnSearch]").live("click", function (e) {
//e.preventDefault();
var firstName = $("#<%= txtFirstName.ClientID %>").val();
var lastName = $("#<%= txtLastName.ClientID %>").val();
if(firstName == "" & lastName == "")
{
$("#<%= lblError.ClientID %>").text("Enter minimum two characters in either first name or last name");
return false;
}
else
{
$("#<%= lblError.ClientID %>").text("");
$("#hdnFirstNameInitiator").val($("#<%= txtFirstName.ClientID %>").val());
$("#hdnLastNameInitiator").val($("#<%= txtLastName.ClientID %>").val());
return true;
}
})
```
***The close button JQUERY***
```
$("[id*=btnClose]").live("click", function (e) {
//e.preventDefault();
$("#modal_dialog").dialog('close');
return true;
})
```
Also if possible please brief me about e.preventDefault() and appendTo functions in jquery.
Please Help.
Thanks in advance,
|
2014/01/19
|
[
"https://Stackoverflow.com/questions/21212121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3211156/"
] |
Add a constructor
```
template <typename Type2> Pos2(const Pos2<Type2> &other)
{ x = other.x; y = other.y; }
```
|
47,350,199 |
Environment:
Asp Net MVC app(.net framework 4.5.1) hosted on Azure app service with two instances.
App uses Azure SQL server database.
Also, app uses MemoryCache (System.Runtime.Caching) for caching purposes.
Recently, I noticed availability loss of the app. It happens almost every day.
[](https://i.stack.imgur.com/ExZnC.png)
[](https://i.stack.imgur.com/ZmXAq.png)
Observations:
The memory counter Page Reads/sec was at a dangerous level (242) on instance RD0003FF1F6B1B. Any value over 200 can cause delays or failures for any app on that instance.
What 'The memory counter Page Reads/sec' means?
How to fix this issue?
|
2017/11/17
|
[
"https://Stackoverflow.com/questions/47350199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5841485/"
] |
>
> What 'The memory counter Page Reads/sec' means?
>
>
>
We could get the answer from this [blog](https://www.sqlshack.com/sql-server-memory-performance-metrics-part-3-sql-server-buffer-manager-metrics-memory-counters/). The recommended Page reads/sec value should be under **90**. Higher values indicate **insufficient memory** and **indexing issues**.
>
> “Page reads/sec indicates the number of physical database page reads that are issued per second. This statistic displays the total number of physical page reads across all databases. Because physical I/O is expensive, you may be able to minimize the cost, either by using a larger data cache, intelligent indexes, and more efficient queries, or by changing the database design.”
>
>
>
---
>
> How to fix this issue?
>
>
>
Based on my experience, you could have a try to [enable Local Cache in App
Service](https://learn.microsoft.com/en-us/azure/app-service/app-service-local-cache-overview#enable-local-cache-in-app-service).
>
> You enable Local Cache on a per-web-app basis by using this app setting: **WEBSITE\_LOCAL\_CACHE\_OPTION = Always**
>
>
> By default, the local cache size is **300 MB**. This includes the /site and /siteextensions folders that are copied from the content store, as well as any locally created logs and data folders. To increase this limit, use the app setting **WEBSITE\_LOCAL\_CACHE\_SIZEINMB**. You can increase the size up to **2 GB (2000 MB)** per web app.
>
>
>
|
229,329 |
I have a huge collection of PDF. Mostly it consists of research papers, of self-created documents but also of scanned documents.
Right now I drop them all in one folder and give them precise names with tags in the filename.
But even that gets impractical, so **I am looking for a PDF library management application**. I am thinking of something like [Yep](http://www.ironicsoftware.com/yep/) for Mac, with the following features:
* PDF cover browsing (with large preview, larger than Nautilus allows)
* tagging of PDF (data should be readable cross-platform)
* possibility to share across network (thus rather flat files than database)
* if possible: cross-platform
Mendeley seemed to be a good choice, but I am not only having academic papers and don't want to fill it all metadata that is required there.
The only alternative I could find thus far is [Shoka](http://www.mauropiccini.it/shoka/), but the features are limited and developments seems to have stopped already.
|
2012/12/15
|
[
"https://askubuntu.com/questions/229329",
"https://askubuntu.com",
"https://askubuntu.com/users/78383/"
] |
One possibility is [Calibre](http://calibre-ebook.com).
It is an ebook management program which permits conversion to various ebook formats but is cross-platform and can manage databases of pdf files (and not only).
If you decide to install I suggest you do so manually as the version in the repos is not very up to date. Follow the instructions on the site.
A screenshot:

Another possibility is [Zotero](http://www.zotero.org/)
It is is bibliography manager but permits adding book details directly through a browser Amazon.com and other sites, pdf attachments and more.

To import the pdf's into Zotero you can [see this page](http://libguides.northwestern.edu/content.php?pid=68444&sid=1179558).
|
17,197,129 |
I have a datagrid which populates a datatable, I want to export the DataTable to excel on click of a button. I am using MVVM for this application. So is it ok to implement the export feature in my view?
Secondly, as i am using xaml and desktop application, how do i capture the grid and its details.
Can any one suggest me some pointers? I am new to this.
Thanks,
Sagar
|
2013/06/19
|
[
"https://Stackoverflow.com/questions/17197129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1653540/"
] |
This is what i have done and it helped me:
```
private readonly ICommand m_ExportButtonClick;
private string ExcelFilePath = "";
public ICommand ExportButtonClick { get { return m_ExportButtonClick; } }
private void OnRunExport()
{
try
{
if (queryDatatable == null || queryDatatable.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
Excell.Application excelApp = new Excell.Application();
excelApp.Workbooks.Add();
// single worksheet
Excell._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (int i = 0; i < queryDatatable.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = queryDatatable.Columns[i].ColumnName;
}
// rows
for (int i = 0; i < queryDatatable.Rows.Count; i++)
{
// to do: format datetime values before printing
for (int j = 0; j < queryDatatable.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = queryDatatable.Rows[i][j];
}
}
// check fielpath
if (ExcelFilePath != null && ExcelFilePath != "")
{
try
{
workSheet.SaveAs(ExcelFilePath);
excelApp.Quit();
MessageBox.Show("Excel file saved!");
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
+ ex.Message);
}
}
else // no filepath is given, the file opens up and the user can save it accordingly.
{
excelApp.Visible = true;
}
}
catch (Exception ex)
{
MessageBox.Show("There is no data to export. Please check your query/ Contact administrator." + ex.Message);
}
}
#endregion
```
|
71,940,399 |
I want to create an trigger inside an procedure. but after some research I got to know that it is not possible. can u suggest me another way I can achieve the below actions. (I cant share exact data and queries due to some reason. please refer similar queries.)
***What I want***
I have created an temporary table containing data i need.
eg. `CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;`
I want to inset data in table `table2` when data is inserted in temp1, which i can achieve by creating a `TRIGGER`. but the problem is I want to give a value in `table2` which will be dynamic and will be taken from nodejs backend. so i created a `PROCEDURE` which takes parameter `neededId`. but i cant created trigger inside a procedure. is their any other way i can achieve this?
***Procedure I Created***
*here `neededId` is the foreign key I get from backend to insert*
```
DELIMITER $$
USE `DB`$$
CREATE PROCEDURE `MyProcedure` (IN neededID int)
BEGIN
DROP TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1 SELECT id, col_1 FROM table1 WHERE col_1=2;
DROP TRIGGER IF EXISTS myTrigger;
CREATE TRIGGER myTrigger AFTER INSERT ON temp1 FOR EACH ROW
BEGIN
INSERT into table2("value1", "value2", neededId);
END;
END$$
DELIMITER ;
```
|
2022/04/20
|
[
"https://Stackoverflow.com/questions/71940399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17349359/"
] |
```
const idx = headings.findIndex(el => el.text === 3 && el.type === "♠")
headings.splice(idx,1)
```
|
1,078,704 |
I am using XUbuntu 18.04 and I am struggling to install my scanner. I have tried everything i have been able to find on both Brother homepage and AskUbuntu.
I have newest brsaneconfig4, brscan-skey and rules.
Command `brsaneconfig4 -`q returns:
```
(...)
Devices on network
0 DCP-7055W "DCP-7055W" I:192.168.1.28
```
Command `scanimage -L` returns:
```
device `brother4:net1;dev0' is a Brother DCP-7055W DCP-7055W
```
While command `brscan-skey -l` returns:
```
DCP-7055W : brother4:net1;dev0 : 192.168.1.28 Not responded
```
I have `libsane-brother4.so` installed in `/usr/lib64/sane`, `/usr/lib/sane` and `/usr/lib/x86_64-linux-gnu/sane`
Command `dpkg -l | grep Brother` returns:
```
ii brother-udev-rule-type1 1.0.2 all Brother udev rule type 1
ii brscan-skey 0.2.4-1 amd64 Brother Linux scanner S-KEY tool
ii brscan4 0.4.6-1 amd64 Brother Scanner Driver
ii dcp7055wcupswrapper:i386 3.0.1-1 i386 Brother DCP-7055W CUPS wrapper driver
ii dcp7055wlpr:i386 3.0.1-1 i386 Brother DCP-7055W LPR driver
ii printer-driver-brlaser 4-1 amd64 printer driver for (some) Brother laser printers
ii printer-driver-ptouch 1.4.2-3 amd64 printer driver Brother P-touch label printers
```
and my `libsane` file has following content:
```
#
# udev rules
#
ACTION!="add", GOTO="brother_mfp_end"
SUBSYSTEM=="usb", GOTO="brother_mfp_udev_1"
SUBSYSTEM!="usb_device", GOTO="brother_mfp_end"
LABEL="brother_mfp_udev_1"
SYSFS{idVendor}=="04f9", GOTO="brother_mfp_udev_2"
ATTRS{idVendor}=="04f9", GOTO="brother_mfp_udev_2"
GOTO="brother_mfp_end"
LABEL="brother_mfp_udev_2"
ATTRS{bInterfaceClass}!="0ff", GOTO="brother_mfp_end"
ATTRS{bInterfaceSubClass}!="0ff", GOTO="brother_mfp_end"
ATTRS{bInterfaceProtocol}!="0ff", GOTO="brother_mfp_end"
#MODE="0666"
#GROUP="scanner"
ENV{libsane_matched}="yes"
#SYMLINK+="scanner-%k"
LABEL="brother_mfp_end"
```
I have tried everything without any significant success. At some point I have had working scanner, but after reboot it was no longer visible in SimpleScan. How can i make this work? What is missing?
|
2018/09/26
|
[
"https://askubuntu.com/questions/1078704",
"https://askubuntu.com",
"https://askubuntu.com/users/864165/"
] |
I came across the posting [Brother MFC-L2700DW printer can print, can’t scan](https://askubuntu.com/questions/970831/brother-mfc-l2700dw-printer-can-print-cant-scan) by oscar1919 on Ask Ubuntu. I have a Brother multi-function printer but a different model than that specified by Oscar.
Oscar indicated that some of the installation files may be copied into the wrong folder. For 64-bit Linux, the instructions were to check that the folder /usr/lib/x86\_64-linux-gnu/sane exists.
However, In my case, this folder was indeed present, but it was empty. The subsequent instructions were, essentially to copy the files libsane-brother\* from the /usr/lib64/sane/ folder to /usr/lib/x86\_64-linux-gnu/sane.
On my system, the three files to be copied were: libsane-brother2.so, libsane-brother2.so.1 and libsane-brother2.so.1.0.7.
Once these files were located in the /usr/lib/x86\_64-linux-gnu/sane folder, Simple Scan sprung to life and scanned a test document.
|
71,110 |
Some people erased three author names including mine from a paper previously submitted (and rejected by three different journals) and got it accepted by Case Reports In Emergency Medicine.
I presented the publishing editor of the journal multiple clear proofs of the plagiarism. Although the journal declares that it complies with COPE, the publishing editor is dragging feet not to publish a retraction about this article despite the proofs. Instead, they are trying to overlook the situation by involving the politically driven hospital administration from where the paper was submitted from. This in turn caused violation of my rights both as a human and as a researcher. I am currently subjected to serious mobbing by the hospital administration secondary to the inconclusive behaviour of the journal. This mobbing includes the change in my workplace and an official warning because "I ruined reputation of the hospital by contacting the publishing editor".
I also sent a message to COPE but there is no response.
Would anyone suggest any further action?
|
2016/06/10
|
[
"https://academia.stackexchange.com/questions/71110",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/56431/"
] |
Working with the editor, until that process is finished, is probably the only thing to do at first. It will undoubtedly be a long process, with delays, so patience and persistence will be necessary. Try not to let the mobbing get to you, and try to remain calm and professional at all times, despite any pressure others may exert.
If the editors, in the end, are unable to come to a resolution you accept, then the options will be (essentially) to escalate the situation or to let it go. But making an action of that kind while the editors are still working would be premature, in my opinion.
|
34,695,078 |
I'm having a problem updating php in Linux Redhat.
I updated by
```
yum install php56w
```
But it says there's no repository for php56w.
So I updated httpd by
```
yum update httpd
```
But since then, all websites(which is using php) are not working, they're showing 500 Internal server error.
This seems to be permission error, but I've no idea how to fix.
Anyone please help.
|
2016/01/09
|
[
"https://Stackoverflow.com/questions/34695078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4319602/"
] |
Which RHEL version?
If it's RHEL 6 and you're upgrading the PHP version, you should use the PHP 5.6 software collection (<https://access.redhat.com/products/Red_Hat_Enterprise_Linux/Developer/#dev-page=5>).
If it's RHEL 7 - I don't recall the default PHP version. :/
|
22,486,798 |
The following MPMoviePlayerController will not present in my iOS application.
I am trying to make it appear when my tableView row is selected:
```
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:videoUrl]];
[player setFullscreen:YES];
[player play];
[self.tableView addSubview:player.view];
}
```
Any ideas?
|
2014/03/18
|
[
"https://Stackoverflow.com/questions/22486798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3434331/"
] |
`$result` is a boolean because the query you are executing is failing! A failed query gives off boolean `'false'`.
Check you query. Try setting $start with a value before using it in your query.
|
424,214 |
Where can I exponentiate a $3\times 3$ matrix like $\left[\begin{array}{ccc}
0 & 1 & 0\\
1 & 0 & 0\\
0 & 0 & 0
\end{array}\right]$
online?
Is there some website where this is possible?
Thank you very much.
|
2013/06/19
|
[
"https://math.stackexchange.com/questions/424214",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/83056/"
] |
Depending on which matrix exponential you want, you can use:
* [*Wolfram Alpha 1st option: $e^{A}$*](http://www.wolframalpha.com/input/?i=matrixexp%28%7B%7B0%2C1%2C0%7D%2C%7B1%2C0%2C0%7D%2C%7B0%2C0%2C0%7D%7D%29)
* [*Wolfram Alpha 2nd option: $e^{At}$*](http://www.wolframalpha.com/input/?i=matrixexp%28t+%7B%7B0%2C1%2C0%7D%2C%7B1%2C0%2C0%7D%2C%7B0%2C0%2C0%7D%7D%29)
This is actually a command in Mathematica.
I would be surprised if were not available in other [*CAS programs*](http://en.wikipedia.org/wiki/List_of_computer_algebra_systems) and some of those are online, like [*Sage*](http://www.sagemath.org/doc/reference/matrices/sage/matrix/matrix_symbolic_dense.html), [*Maxima*](http://www.ma.utexas.edu/pipermail/maxima/2006/003031.html) and others.
|
66,184,300 |
I have a df with customer\_id, year, order and a few other but unimportant columns. Every time when i get a new order, my code creates a new row, so there can be more than one row for each customer\_id. I want to create a new column 'actually', which includes 'True' if a customer\_id bought in 2020 or 2021. My Code is:
```
#Run through all customers and check if they bought in 2020 or 2021
investors = df["customer_id"].unique()
df["actually"] = np.nan
for i in investors:
selected_df = df.loc[df["customer_id"] == i]
for year in selected_df['year'].unique():
if "2021" in str(year) or "2020" in str(year):
df.loc[df["customer_id"] == i, "actually"] = "True"
break
#Want just latest orders / customers
df = df.loc[df["actually"] == "True"]
```
This works fine, but quite slow. I want to use Pandas groupby function, but didnt find a working way so far. Also i avoid loops. Anyone an idea?
|
2021/02/13
|
[
"https://Stackoverflow.com/questions/66184300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11203274/"
] |
you can create the column name 'Actually' something like this.
```
list1=df['Customer_id'][df.year==2020].unique()
list2=df['Customer_id'][df.year==2021].unique()
df['Actually']=df['Customer_id'].apply( lambda x : x in list1 or x in list2)
```
|
6,590,891 |
I want to create a computed column that is the concatenation of several other columns. In the below example, fulladdress is null in the result set when any of the 'real' columns is null. How can I adjust the computed column function to take into account the nullable columns?
```
CREATE TABLE Locations
(
[id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[fulladdress] AS (((([address]+[address2])+[city])+[state])+[zip]),
[address] [varchar](50) NULL,
[address2] [varchar](50) NULL,
[city] [varchar](50) NULL,
[state] [varchar](50) NULL,
[zip] [varchar](50) NULL
)
```
Thanks in advance
|
2011/07/06
|
[
"https://Stackoverflow.com/questions/6590891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156611/"
] |
This gets messy pretty quick, but here's a start:
```
ISNULL(address,'') + ' '
+ ISNULL(address2,'') + ' '
+ ISNULL(city,'') + ' '
+ ISNULL(state,'') + ' '
+ ISNULL(zip,'')
```
(If `isnull` doesn't work, you can try `coalesce`. If neither work, share what DMBS you're using.)
|
18,979 |
Can any chess engine tell you why a move is bad or good? For example, say a chess engine says the score against my opponent is currently +2 in my favor. I then make a move and my score drops to say 1.4. Can any engine tell me what I did wrong such that my score dropped from 2 to 1.4 (assuming I didn't hang a piece or pawn etc.)
It seems to me that having chess programmers make their programs even stronger is now pointless and it would be much more beneficial to the average chess player if they could have their programs instruct us why a move is bad (or good), assuming they currently cannot do this.
|
2017/10/29
|
[
"https://chess.stackexchange.com/questions/18979",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/443/"
] |
**Sort of (but not really) - and it's actually getting *harder* for engines to do this for you.** To understand why, you have to understand how the evaluation goes. Engines typically can make snap evaluations on a given position, giving it a raw point value. Then, whatever the position is, they play forward, trying to find the line forward that optimizes that score for both sides.
It's important to understand, that '2.0' or '1.4' score *aren't* the evaluation/score for the current position. Instead, it's the evaluation N moves down the line, with each side playing the best move the engine found. This is why the "Current evaluation score" jumps around while the computer is thinking. It's not that the 'score' for a position changed - it's just that it found a different line moving forward that ended up in a different position (which had a different score.)
In the past, engines sucked. Not just because of sub-optimal algorithms, but because of very slow hardware - if you think compounding interest is powerful, it's nothing compared to [Moore's Law](https://en.wikipedia.org/wiki/Moore%27s_law). So computers back then were just looking a few moves into the future. Which made it relatively easy for a human to follow the logic - your score went down because you're losing your knight the next turn.
But now? If your score went from '2.0' to '-0.3', it's possible it's because, due to some unavoidable tactics over the next 7 moves, that you'll have to give up the exchange in order to avoid losing your queen or getting checkmated. But it's hard to show the leap from "Here's the position now" and "Well, I evaluated 20 billion positions going forward, and trust me when I say that you sacrificing the rook for their bishop was the best you could hope for."
Occasionally a move from a grandmaster winning game is said to be "invisible" to a chess engine. Only after the move is made, the engine recognizes the high value of the move. This weakness in the engine could easily be remedied by more exhaustive checking of possible moves.
|
51,019,433 |
I'm trying to develop a plugin, and I'm not the best at developing plugins. I do ofc know php, and oop, but the wp functions is pretty difficult to understand, and also the codex.
I'm trying to make an "ORDERS" page, where you can click on a button, to go to `view_order.php` where it will fetch all the data from the specific ID.
I got it all to work, to fetch out of the right table etc, but the problem is, that i have a `<a href` like this:
```
<a href="view_order.php?id=<?php echo $row->id; ?> ">
```
(It finds the id, so no problems there) but when i click on it, it will go to
>
> <http://localhost/wp-admin/view_order.php?id=3>
>
>
>
and ofc say that it can't find the page. I'm a bit confused here. What can i do?
|
2018/06/25
|
[
"https://Stackoverflow.com/questions/51019433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8533033/"
] |
use this as a reference
```
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
```
|
31,409,502 |
I have a `table` that I want to select the very first `TH` only if it contains a `caption`. I thought it might be something like this:
```css
.myTable caption + tr th:first-child
{
/* stuff */
}
```
It's instead selecting nothing. Is this a bug in CSS or just my logic?
See my JSFiddle: <https://jsfiddle.net/ukb13pdp/1/>
```css
.objectTable th:first-child
{
background-color: blue;
color: white;
}
.objectTable caption + tr th:first-child
{
background-color: red;
}
```
```html
<table class='objectTable'>
<caption>Caption Table</caption>
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
<br/><br/>
<span>No Caption Table</span>
<table class='objectTable'>
<tr>
<th>C</th>
<th>D</th>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>
```
|
2015/07/14
|
[
"https://Stackoverflow.com/questions/31409502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096126/"
] |
The cause here is exactly the same as the one described in [this related question](https://stackoverflow.com/questions/5568859/why-doesnt-table-tr-td-work-when-using-the-child-selector) about the use of child selectors with `tr`. The problem is that `tr` elements are made children of an implicit `tbody` element, so what ends up being the sibling of the `caption` is that `tbody` and not the `tr`:
```
.myTable caption + tbody th:first-child
```
As an aside, if your `th` elements reside in a header row they should ideally be contained in a `thead` element and the data rows contained in explicit `tbody` element(s):
```
<table class=myTable>
<caption>Table with header group</caption>
<thead>
<tr><th>Header<th>Header
<tbody>
<tr><td>Row 1<td>Row 1
<tr><td>Row 2<td>Row 2
</table>
```
And selected using
```
.myTable caption + thead th:first-child
```
|
120,326 |
I am a beginning graduate student in Mathematics. I have a professor who always brings up the fact that my GPA is not great in my undergraduate degree even though my performance is above the norm in the institution I am enrolled at the moment, so far I got straight A's in the graduate courses that I have completed. He always tries to point out at my flaws in my undergraduate years to humiliate me in front of other professors and my colleagues. What would be a wise reply/reaction to such abuse?
I feel bad about it cause I feel like I am harassed and I don't reply.
I am also currently taking a course with that professor.
|
2018/11/19
|
[
"https://academia.stackexchange.com/questions/120326",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/99012/"
] |
As I understand you, you are being *publicly* shamed (in front of fellow grad students) by this professor by dint of your undergrad record.
If you are in the US, this is violating FERPA by revealing your academic record. Other countries have similar privacy laws. File a FERPA complaint and wipe that smug smile off his face.
I'm no expert and I suspect each school is different. But this is a federal law and I think most schools would take such a blatant violation seriously. I'm pretty sure this prof would get his leash yanked pretty hard.
Note that it could backfire. You could an enemy who will make your graduate experience miserable. But I'm betting against it. There have been a number of times when I just let a jerk be a jerk because I thought my life would go more smoothly, but found out later that if I had stood up for myself, I would have gotten a standing ovation from 99% of the people around me. This prof is a jerk and his colleagues will likely appreciate him being called out.
Also, in the case of harassment and rights violations, the perpetrator is warned against retaliation in any form. And someone will be watching for it. Someone behind those closed doors will tattle. I think you are perfectly safe.
### My experience
When I taught small classes, I would write all the test scores on the board, so that students could see where they ranked. One young lady thought I was violating FERPA with this tattled on me. I got hauled into the chairs office where he was accompanied with one of those university JD types (the law students who never pass the bar, but get jobs at universities being annoying.) and the dean. They were ready to have a field day with me. They had already talked to other students and had corroboration that I had, in fact, written all the scores on the board. The JD was salivating.
We talked at cross purposes for a while, then they figured out that I was writing numbers only. No names. No personal information was being displayed. They were so disappointed. An administrator gets to be administrative so rarely and here they had an open-and-shut case go up in smoke.
So the point here is that at this school at this time, FERPA violations were a big deal. I suspect that in the current safe-room environment, they might be a bigger deal. Telling the class that that guy right there has a low GPA could traumatize him for life, eh?
|
37,383,507 |
Friends, I would like a permanent solution to a script to change password without email access cpanel.
I tried the cpanel api but I could not ...
Could you help me?
I need a page where the User enter the email address and new password, after which the password is changed ...
Please help me ...
|
2016/05/23
|
[
"https://Stackoverflow.com/questions/37383507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6249483/"
] |
```
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if (![mediaType isEqualToString:(NSString *)kUTTypeMovie])
return;
mediaURl = [info objectForKey:UIImagePickerControllerMediaURL];
//NSLog(@"mediaURL %@",mediaURl);
moviePath = mediaURl.absoluteString;
// NSLog(@"moviePath %@",moviePath);
tempFilePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
NSLog(@"filepath %@",tempFilePath);
//if you want only file name
NSArray *ar = [tempFilePath componentsSeparatedByString:@"/"];
NSString *filename = [[ar lastObject] uppercaseString];
NSLog(@"filename %@",filename);
}
```
Let me know if you have any issues
|
35,122,934 |
I have my config/mail 'driver' set to mandrill, host, port, etc. including in services.php mandrill secret set.
Sending Mail works fine locally, but on the live server I get:
>
> Class 'GuzzleHttp\Client' not found
>
>
>
I have tried "guzzlehttp/guzzle": "~5.3|~6.0", and then back to "guzzlehttp/guzzle": "~4.0", no luck. I have done composer update, and dump-autoload still no luck on my live server. Been through every other associated Stackoverflow question and still can't resolve.
|
2016/02/01
|
[
"https://Stackoverflow.com/questions/35122934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3820348/"
] |
Please follow these simple steps:
**First:** Place this on top of your class
```
use Guzzlehttp\Client;
```
**Second:** Inside your function, instead of using
```
$client = new Client();
```
use
```
$client = new \GuzzleHttp\Client();
```
**reference:**
<http://docs.guzzlephp.org/en/latest/quickstart.html>
|
70,638 |
I have an ASCII-art box and I need a program to open it.
Examples
--------
Input:
```
-------
| |
|_____|
```
Output:
```
/
/
/
/
/
/
/
| |
|_____|
```
Specification
=============
* The first line will only consist of `-`, at least 3 of them
* The middle rows will start with `|` have spaces, and end with `|`
+ All the middle rows will be the same
* The last row will start with `|` have `_` and end with a `|`
* All rows will be the same length
Opening the box:
* Each `-` should be replaced by a `/` in ascending lines and position.
|
2016/01/31
|
[
"https://codegolf.stackexchange.com/questions/70638",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/40695/"
] |
JavaScript ES6, 57 bytes
------------------------
```
s=>s[r="replace"](/-+/,s=>s[r](/-/g,`
$'/`))[r](/-/g,' ')
```
Outputs a leading newline. Works by taking the row of `-`s and converting them into a triangle, then replacing the `-`s with spaces.
Edit: Saved 5 bytes thanks to @edc65.
|
70,631,273 |
I'm very enthausiast about vuejs but the composition API made me get lost slightly on reactivity:
In a .vue child component a prop is passed (by another parent component), movies:
```
export default {
props:{
movies: Array
},
setup(props){}
```
.
Placing in the **setup** function body of this child component:
```
A) console.log("props: ",props) // Proxy {}
```
[above EXPECTED] above tells me that the props object is a reactive proxy object.
```
B) console.log("props.movies: ",props.movies); // Proxy {}
```
[above UNEXPECTED] above tells me that the props key 'movies' is a reactive proxy object as well, why? (thus why is not only the main props object reactive? Maybe I should just take this for granted *(and e.g. think of it as the result of a props = reactive(props) call)*
--> ANSWER: props is a \*\*deep \*\* reactive object (thanks Michal Levý!)
```
C) let moviesLocal = props.movies ; // ERROR-> getting value from props in root scope of setup will cause the value to loose reactivity
```
[above UNEXPECTED] As props.movies is a reactive object, I'd assume that I can assign this to a local variable, and this local variable then also would become reactive. Why is this not the case (I get the error shown above)
```
D) let moviesLocal = ref(props.movies);
moviesLocal.value[0].Title="CHANGED in child component";
```
[above UNEXPECTED]
I made a local copy in the child component (moviesLocal). This variable I made reactive (ref). Changing the value of the reactive moviesLocal also causes the 'movies' reactive object in the parent object to change, why is that ? *This even holds if I change D: let moviesLocal = ref(props.movies); to let moviesLocal = ref({...props.movies});*
Thanks a lot! Looking forward to understand this behaviour
|
2022/01/08
|
[
"https://Stackoverflow.com/questions/70631273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1345112/"
] |
Use `toRef` to maintain reactivity.
```
const moviesLocalRef = toRef(props, 'movies')
```
See <https://v3.vuejs.org/api/refs-api.html#toref>
The rule is that a `reactive` object child property must always be accessed from the root of the object. `a.b.c.d`. You cannot just `break off a piece and modify it`, because the act of resolving from the root is what allows Vue to track changes.
In your case, the internal property is the same, but Vue has lost the ability to track changes.
As a side note, you can also create a computed reference.
```
const moviesLocalRef = computed(()=>props.movies)
```
Whether you use a `computed ref` or `toRef`, you will need to access your property using `theRef.value` outside of templates. As I state in conclusion, this is what allows Vue to maintain the reactivity.
Conclusion
==========
Here is how I have chosen to think about Vue3 reactivity.
The act of `dereferencing a property` from an object is what triggers the magic.
For a `reactive object`, you need to start with the `reactive object` and then `drill down` to your property of interest. For a `ref`, you need to unbox the `value` from the `ref`. Either way, there is always a `get` operation that triggers the internal mechanism and notifies Vue who is watching what.
This `drilling down` happens automatically in templates and watchers that are aware they received a reference, but not anywhere else.
See <https://v3.vuejs.org/guide/reactivity.html#how-vue-tracks-these-changes>
|
72,091 |
In Michael Ende's novel *The Neverending Story*, the character Yikka, a talking mule, keeps saying that her intuition comes from being "half an ass (donkey)." "When one is only half an ass, and not a whole one, one knows things." I don't have a German translation of the book to get the original phrase, but... is there something in German language or culture that explains this line? She uses it as an explanation of how she was able to sense the identity of a stranger, and how she sometimes knows what her human rider is thinking. ???
|
2022/11/03
|
[
"https://german.stackexchange.com/questions/72091",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/54378/"
] |
In German it is
>
> Wenn man bloß ein halber Esel ist wie ich und kein ganzer, dann fühlt man so was.
>
>
>
This is a somewhat mysterious statement and there is nothing in German language or culture that explains it. I think one can only make conjectures about its meaning.
1. Naive explanation.
The word "Esel" (donkey) is often used as synonym for a fool. Perhaps this is the reason why the translator used the word "ass" instead of "donkey". This could mean that Yikka wants to say that she is not foolish enough to ignore the truth.
2. Psychological explanation. See Gronemann, Helmut: Phantásien – Das Reich des Unbewussten. „Die unendliche Geschichte“ von Michael Ende aus der Sicht der Tiefenpsychologie. Zürich: Schweizer Spiegel Verlag 1985. Also see [here](https://phaidra.univie.ac.at/open/o:1262377) p. 79.
*Nach Ansicht Helmut Gronemanns versinnbildlicht der Esel das Unbewusste, das Pferd dagegen verkörpert das Bewusstsein. Das Gespür des Maultieres besteht demnach in der Fähigkeit, beide psychischen Komponenten zu vereinigen. Das höhere Wissen des Tieres versinnbildlicht so die Geschlossenheit, die Bastian erst erreichen muss.*
Translation via DeepL:
*According to Helmut Gronemann, the donkey symbolizes the unconscious, while the horse embodies the conscious. The sense of the mule thus consists in the ability to unite both psychic components. The higher knowledge of the animal thus symbolizes the unity that Bastian must first achieve.*
By the way, here is the [German text](http://maxima-library.org/knigi/knigi/b/25523?format=read).
|
36,354,704 |
My iOS app has a pretty common setup: it makes HTTP queries to an API server that responds with JSON objects. These JSON objects are then parsed to appropriate Swift objects.
Initially I divided properties into required properties and optional properties, mostly based on my API server's database requirements. For example, `id`, `email`, and `name` are require fields so they use non-optional types. Others can be `NULL` in database, so they are optional types.
```
class User {
let id: Int
let email: String
let profile: String?
let name: String
let motive: String?
let address: String?
let profilePhotoUrl: String?
}
```
Recently, I started wondering whether this was a good setup at all. I found out that although some properties might be always in the database, that does not mean that those properties will always be included in the JSON response.
For example, in the User profile page, all these fields are needed to properly display the view. Therefore, JSON response will include all these fields. For a view that lists users' names, however, I would not need `email` or `id`, and JSON response should probably not include those properties either. Unfortunately, this will cause error and crash the app when parsing JSON response into Swift object since the app expects `id`, `email`, `name` to be always not-nil.
I'm thinking of changing all properties of Swift objects into optionals, but it feels like throwing away all the benefits of this language-specific feature. Moreover, I will have to write many more lines of code to unwrap all these optionals somewhere else in the app anyway.
On the other hand, JSON objects are by their nature not very interoperable with strict static typing and nil-checking of Swift so it might be better to simply accept that annoyance.
Should I transition to models with every property as optionals? Or is there a better way? I'd appreciate any comment here.
|
2016/04/01
|
[
"https://Stackoverflow.com/questions/36354704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264622/"
] |
There are three ways you can go with this:
1. Always send all the JSON data, and leave your properties non-optional.
2. Make all the properties optional.
3. Make all the properties non-optional, and write your own `init(from:)` method to assign default values to missing values, as described in [this answer](https://stackoverflow.com/a/44575580/7258538).
All of these should work; which one is "best" is opinion-based, and thus out of the scope of a Stack Overflow answer. Choose whichever one is most convenient for your particular need.
|
8,401,785 |
Debugging a package procedure and am getting a no data found when there is in fact data.
Testing just the SELECT
```
SELECT trim(trailing '/' from GL_SECURITY) as DUMMY
FROM b2k_user@b2k
WHERE sms_username = 'FUCHSB';
```
This happily returns my value : '23706\*706'
As soon as i try to have this selected INTO i get a NO\_DATA \_FOUND error
(commented out the error handling i put in)
```
set serveroutput on
DECLARE
p_BAS_user_name varchar2(20);
v_gl_inclusion varchar2(1000);
v_gl_exclusions varchar2(1000);
BEGIN
--inputs
p_BAS_user_name := 'FUCHSB';
dbms_output.put_line(p_BAS_user_name);
----- GOOD -----
--BEGIN
SELECT trim(trailing '/' from GL_SECURITY) as DUMMY
INTO v_gl_inclusion
FROM b2k_user@b2k
WHERE sms_username = p_BAS_user_name;
--EXCEPTION
-- WHEN NO_DATA_FOUND THEN
-- v_gl_inclusion := 'SUPER EFFING STUPID';
--END;
dbms_output.put_line(v_gl_inclusion);
END;
Error report:
ORA-01403: no data found
ORA-06512: at line 12
01403. 00000 - "no data found"
*Cause:
*Action:
FUCHSB
```
I can catch the error just fine except for the fact that based on the 1st query i know 100% there is a value for FUCHSB in the database.
Any ideas.. I'm really starting to despise Oracle. Yes this query is being run over a datalink as seen in the 1st query the data is there.
Thanks
---
SOLVED strange behavior in SQL developer caused me to overlook potential whitespace:
It looks as though SQL Developer when running the standalone select applies its own trimming comparator when doing the 'WHERE sms\_username = p\_BAS\_user\_name;' portion.. turns out when sitting in the package it does not.. bunch of white space was causing the issue.. still strange that it returns on the normal select. Thanks though!
|
2011/12/06
|
[
"https://Stackoverflow.com/questions/8401785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1083699/"
] |
I'm pretty sure I found the cause of this behaviour: I'm guessing that the column is actually of type CHAR and not VARCHAR2.
Consider the following:
```
SQL> CREATE TABLE t (a CHAR(10));
Table created.
SQL> INSERT INTO t VALUES ('FUCHSB');
1 row created.
SQL> SELECT * FROM t WHERE a = 'FUCHSB';
A
----------
FUCHSB
SQL> DECLARE
2 l VARCHAR2(20) := 'FUCHSB';
3 BEGIN
4 SELECT a INTO l FROM t WHERE a = l;
5 END;
6 /
DECLARE
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
```
Conclusion:
* When working with the CHAR datatype, declare your PL/SQL variables as CHAR.
* When possible, prefer the VARCHAR2 datatype for table column definition. The CHAR datatype is just a bloated VARCHAR2 datatype and doesn't add any feature over the VARCHAR2 datatype (consuming more space/memory is not a feature).
|
3,888,867 |
Currently I am studying Standard Template Library (STL).
In this program I am storing some long values in Associative Container and then sorting them according to unit's place (according to the number in unit's place).
**Code :**
```
#include <iostream>
#include <set>
#include <functional>
using namespace std;
class UnitLess
{
public:
bool operator()(long first, long second)
{
long fu = first % 10;
long su = second % 10;
return fu < su;
}
};
typedef set<long, UnitLess> Ctnr;
int main(void)
{
Ctnr store;
store.insert(3124);
store.insert(5236);
store.insert(2347);
store.insert(6415);
store.insert(4548);
store.insert(6415);
for(Ctnr::iterator i = store.begin(); i != store.end(); ++i)
{
cout << *i << endl;
}
}
```
But I don't understand why our Professor has overloaded () operator ?
Thanks.
|
2010/10/08
|
[
"https://Stackoverflow.com/questions/3888867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92487/"
] |
The class's purpose is to implement a function that sorts the elements in the set in a given way. This is known as a predicate.
It is implemented as a functor, i.e. by allowing the function operator to be used on an object (this is what std::set does beneath the hood). Doing so is the common way for STL and similar code to call custom objects. (A function pointer is more limited than a function object (a.k.a. functor)
So it's used like this:
```
Unitless functor;
functor(123, 124); // returns true or false
```
std::set is a sorted binary tree, so it calls the Unitless's ()-operator several times on each insert to determine where each long value should go.
Try compiling and putting some printf/std::cout in there and see what happens.
Also, be aware that callbacks like this (i.e. when you can't see the call to your code) are scary and confusing in the beginning of your learning curve.
* Then you get used to it and use them all over, because they are neat.
* Then your code gets scary and confusing again and you avoid them like the plague.
* Then you become a duct-tape programmer and use them only where appropriate, but never elsewhere.
;)
|
810 |
I've had a suspicion for a while that there are simply not enough active users (or users with enough rep) on Fitness.SE to pass a community close vote.
It looks like I might be correct. [Shog9](https://fitness.meta.stackexchange.com/questions/809/2019-a-year-in-moderation)'s previous post shows the statistic:
```
Action Moderators Community¹
---------------------------------------- ---------- ----------
Questions closed 261 5
```
Obviously we can't compare Fitness.SE to Stack Overflow but the percentage is quite different:
```
Action Moderators Community¹
----------------------------------------- ---------- ----------
Questions closed 33,862 306,210
```
Personally, I have voted to close questions before. Questions that were so blatantly off-topic that I didn't have to think twice. They've hung up around 3 or 4 close votes before a mod either gives the 5th vote or closes it at 4.
Would it be worthwhile to reduce the required number of close votes on Fitness?
|
2020/01/08
|
[
"https://fitness.meta.stackexchange.com/questions/810",
"https://fitness.meta.stackexchange.com",
"https://fitness.meta.stackexchange.com/users/31284/"
] |
This is now live!
Thanks so much for your patience here while we got things worked out on our end. I've reviewed your history with closure on two points and find that it does look like this would be a good change to make here.
The first thing I look at is the percentage of questions that get a first close flag or vote that get handled. Here, that's not bad -
[](https://i.stack.imgur.com/5tIgd.png)
So, this looks generally good. While there's definitely some months where things are a bit more rough, in general, we're looking at decent percentages - not perfect, of course, but not bad... so now we turn to the second graph - how many questions per month were handled by moderators versus community members, both closes and reopens.
[](https://i.stack.imgur.com/ePU33.png)
When I see this, the high percentage kinda makes sense - if you're not clear on what this shows, it's indicating that the mods are doing the bulk of the closures here. The purple line is the questions closed per month and the yellow line just below it (and sometimes obscured by it) is the ones that the moderators did the closure for, in the end. It doesn't mean community members weren't participating at all, just that a mod had to cast a vote to close.
While we definitely don't want mods doing all the work as it creates a potentially asymmetric close/reopen process where it's much easier to close than reopen - unless mods are also watching reopens - we also understand that, on smaller sites, this may not be particularly taxing. While the mods are doing a lot of the lifting, the questions closed per month is generally less than one per day, meaning that it's not onerous.
That being said, the community should still be able to handle this without moderator involvement. One of my hopes when I make these changes is that community members will feel more empowered to participate. When five votes were needed, it can feel impossible that you'll ever get enough votes without a mod stepping in. When only three or needed, hopefully that's less of a concern.
Because we ran the big test on many sites that JNat linked to in the comments, we feel pretty secure that this is a safe change to make, so I won't be monitoring it closely. If you have any concerns down the line, please let me know but, for the most part, y'all can consider this change permanent. I'll likely check the numbers in a few months to ensure nothing looks problematic but I won't post an update unless there's something particularly worth mentioning.
If you have any questions, please let me know!
|
230 |
It's time to propose the topics for our Challenge Week!
Some notes:
1. Propose one topic per answer (make it CW by checking the checkbox under your answer);
Write them like
`## Topic <br><br>
"description"`.
2. No maximum of proposals, but don't just propose tons of stuff. Propose things that could stimulate questions and answers.
3. Vote other proposals **up** if you like them, and **down** if you don't.
4. Include a short description or notes, otherwise the system won't let you post your answer.
For each Challenge Week, we'll take the most voted proposal (excluding the already asked ones), so keep proposing! Don't wait for others to propose!
Any questions? Use the comments below. :)
|
2012/01/24
|
[
"https://linguistics.meta.stackexchange.com/questions/230",
"https://linguistics.meta.stackexchange.com",
"https://linguistics.meta.stackexchange.com/users/111/"
] |
Syntax
------
The rules and the study of rules that study the construction of sentences in a given language.
|
21,604,866 |
This is the code that I'm using. I can hear that the notification is working, but no text.
```
@Override
public void onReceive(Context context, Intent arg1) {
showNotification(context);
}
private void showNotification(Context context) {
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MyActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setContentTitle("My notification")
.setContentText("Hello World!");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
```
|
2014/02/06
|
[
"https://Stackoverflow.com/questions/21604866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450116/"
] |
if you are using support-v4 library the use this code
```
private void showNotification(Context context) {
PendingIntent pIntent = PendingIntent.getActivity(context, 0,
new Intent(context, DashBoard.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
mBuilder.setContentIntent(pIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.getNotification());
}
```
|