INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Update addon to 1.3.2 RELEASE
we have created some addons in 1.1.5 RELEASE. Since we are migrating from windows to linux environment, we saw that there are some bugs that ocurr in linux running the addons with this release. So in response to a created issue, we got recommended to use the latest release (that is assumed to include fixes for some bugs including this in particular that is happening to us: < In order to make it compatible our addons to 1.3.2 RELEASE is it possible to update these ones? | There is no automatic way to archive it: There are a lot of changes between this versions.
Without know the functionality provided by your add-ons, I only can think in two ways to migrate your add-ons to the new Spring Roo version:
1. Modify the dependencies of your _pom.xml_ files and fix all problems you found.
2. Create a new add-on project using command `addon create` of new Spring Roo version and migrate functionality in parts.
IMHO the second way could be _lower painful_ than first one but it depends on your add-on complexity.
Good luck! | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "spring roo"
} |
What is a commandline utility to shorten input?
what's a commandline tool to take input from stdin, remove the first X character, and place the output to stdout?
Similar to how tail can skip the X lines and display the rest, but for characters on each line instead of lines in each file. | The `cut` command might fit your needs:
echo "1234567890" | cut -c 6-
Outputs:
67890 | stackexchange-askubuntu | {
"answer_score": 4,
"question_score": 1,
"tags": "command line"
} |
How to route to or navigate to a route programmatically in nextjs class component?
I am building a simple app using nextjs. most of my components are functional components. However, I have a class component to handle form.
I want to redirect to the home page after the form is submitted. `console.log(this.router)` gives undefined. Since it is a class component I can't use `useRouter()` hook. How do I get reference to router in class components in next.js? | Finally I got the answer,
import Router from 'next/router'
and use `Router.push(...)`
With Next 13 onwards, import router from `next/navigation` | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "javascript, node.js, reactjs, next.js, router"
} |
The following circle has the diameter of 10cm, what is the distance from any of the small circles to the edge of the main circle?
<
I've tried about everything but I cant figure it out! Please Help! | Again is it only pythagoras theorem. $ has a unique solution
I am stuck at the following exercise:
> Consider a signal $u^*$ and a noisy signal $u_0$. I need to argue that the following problem
>
> $$\min_{u\in \mathbb{R}^n} \frac{1}{2}\|u-u_0\|^2+\alpha S_\mu(u)$$ where $\alpha>0$ and $S_\mu (u) := \sum_{i=1}^n \sqrt{(Au)_i^2+\mu^2} - \mu$ for $A=\begin{pmatrix}-1&1&...&...&0\\\ 0&-1&1&...&0\\\ 0&0&-1&...&0\\\ ...&...&...&...&0\\\ 0&...&0&-1&1\\\ 0&...&0&0&0 \end{pmatrix}$
>
> has a unique solution.
However, I do not see how to do this. In a similar question this was done by reducing the problem to a quadratic functional, but I do not think that this is possible here due to the presence of roots. Could you please give me a hint? | Define $$\Phi\colon u\mapsto \frac{1}{2}\|u-u_0\|^2 + \alpha S_\mu(u).$$ Notice that $\Phi$ is continuous and $\Phi(u) \to \infty, \|u\|\to\infty$. By Weierstrass theorem, $\Phi$ admits a global minimum $u^*$. Now, note that for each $i \in \\{1,\dots,n\\}$, the function $u\mapsto \sqrt{(Au)^2_i + \mu^2}$ is convex and the function $u \mapsto \|u-u_0\|^2$ is strictly convex. It follows that $\Phi$ is a strictly convex function (being the sum of convex functions and a strictly convex function). Suppose $v^*\neq u^*$ is another global minimum for $\Phi$. Then, by the strict convexity of $\Phi$, we have \begin{equation*} \Phi\Big(\frac{u^*+v^*}{2}\Big) < \frac{1}{2}\Phi(u^*)+\frac{1}{2}\Phi(v^*) = \Phi(u^*), \end{equation*} a contradition. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "optimization, nonlinear optimization, signal processing"
} |
How to generate a random partition from an iterator in Python
Given the desired number of partitions, the partitions should be nearly equal in size. This question handles the problem for a list. They do not have the random property, but that is easily added. My problem is, that I have an iterator as input, so `shuffle` does not apply. The reason for that is that I want to randomly partition the nodes of graph. The graph can be very large, so I am looking for a solution that does not just create an intermediate list.
My first idea was to use `compress()` with a random number function as selector. But that only works for two partitions. | You could just create k list. When you receive a value, pick a random integer x between 0 and k-1, and put that value into the x-th list.
On average each list will contain N/k elements, but with a standard deviation of √(N * 1/k * (1-1/k)).
def random_partition(k, iterable):
results = [[] for i in range(k)]
for value in iterable:
x = random.randrange(k)
results[x].append(value)
return results | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, random, iterator, partitioning"
} |
Use $location to go back using angular
I have a url to a api which shows json. I want to be able to click that json and if i press the back button/ custom button, the browser will kinowthe previous state of the url.
Im not sure how to properly use the $location attribute in angular to to do that.
Thanks in advance. | If you want something very simple just try
$scope.backBtnClick = function() {
window.history.back();
}; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, angularjs"
} |
How to call a function from a string stored in a variable?
I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:
function foo ()
{
//code here
}
function bar ()
{
//code here
}
$functionName = "foo";
// I need to call the function based on what is $functionName | `$functionName()` or `call_user_func($functionName)` | stackexchange-stackoverflow | {
"answer_score": 525,
"question_score": 339,
"tags": "php, dynamic function"
} |
Clojure(Script) empty namespace
For an embedded DSL I'd like to remove all the core functions and require the ones I need one by one. Is it possible and how? | You can use the `:refer-clojure` directive in your `ns` declaration to specify only the core functions you need:
(ns my-namespace
(:refer-clojure :only [defn])) | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "clojure, clojurescript"
} |
Почему ничего не пишет в консоль в Unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Main : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Space key was pressed.");
}
if (Input.GetKeyUp(KeyCode.Space))
{
Debug.Log("Space key was released.");
}
}
} | Вы не добавили свой скрипт в какой-либо unity объект.
Ваш скрипт написан правильно, возможно проблема в том что вы не добавили свой скрипт к Unity объекту. | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, unity3d, консоль"
} |
What is the default value of `ExecSearchPath=` in a systemd unit file?
`man systemd.exec` says concerning `ExecSearchPath=`:
> Takes a colon separated list of absolute paths relative to which the executable used by the Exec*= (e.g. ExecStart=, ExecStop=, etc.) properties can be found. ExecSearchPath= overrides $PATH if $PATH is not supplied by the user through Environment=, EnvironmentFile= or PassEnvironment=. Assigning an empty string removes previous assignments and setting ExecSearchPath= to a value multiple times will append to the previous setting.
What is the default value of `ExecSearchPath=`? | The default binary search path is described in the section on command lines:
> If the command is not a full (absolute) path, it will be resolved to a full path using a fixed search path determined at compilation time. Searched directories include `/usr/local/bin/`, `/usr/bin/`, `/bin/` on systems using split `/usr/bin/` and `/bin/` directories, and their `sbin/` counterparts on systems using split `bin/` and `sbin/`. It is thus safe to use just the executable name in case of executables located in any of the "standard" directories, and an absolute path must be used in other cases. Using an absolute path is recommended to avoid ambiguity. Hint: this search path may be queried using **systemd-path search-binaries-default**.
The default value of `ExecSearchPath` itself is empty, which triggers the behaviour above.
(Note that `ExecSearchPath` is very recent, it was added in systemd 250.) | stackexchange-unix | {
"answer_score": 4,
"question_score": 3,
"tags": "systemd, systemd unit"
} |
Entity Framework interceptor for log Debug.Write web.config
I want to create a Debug.Write logger on my project while development time. So I can do this on code configuration like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Action<string> print = message => Debug.WriteLine(message);
Database.Log =print;
}
But I want to add this on web.config file as entity framework section element. Is there any way to do this?
<interceptors>
<interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
??????
</interceptor>
</interceptors> | You can configure the interceptor either by using config file or code-based configuration.
See the following on how to do this (includes demo):
<
Assuming you have the following interceptor
EFCommandInterceptor: IDbCommandInterceptor
**Config**
<entityFramework>
<interceptors>
<interceptor type="EF6DBFirstTutorials.EFCommandInterceptor, EF6DBFirstTutorials">
</interceptor>
</interceptors>
</entityFramework>
**Code**
public class EF6CodeConfig : DbConfiguration
{
public EF6CodeConfig()
{
this.AddInterceptor(new EFCommandInterceptor());
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, entity framework, entity framework 6"
} |
Non repeating random numbers
As a part of my project I need to create non repeating 2 or 3 digit random numbers by giving a set of numbers. I don't want to implement a list or array for that, since I should get 1 random number for each function call.
I tried to do that using SecureRandom class of Java. I got help from some of the sites as well, but I am stuck in between, can we shuffle the VALUES and get it done? But I don't know how that could be done. Can anyone help me?
import java.security.SecureRandom;
public class RandomNumber {
private static final RandomNumber rnd= new RandomNumber();
private static final char[] VALUES = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
private static final SecureRandom srn= new SecureRandom();
public String createID()
{
byte[] bytes = new byte[3];
srn.nextBytes(bytes);
} | Fisher-yates shuffle algorithm is the way to go. Its efficient for shuffling. and it works in linear time.
here is algo
To shuffle an array a of n elements:
for i from n − 1 downto 1 do
j ← random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
and the code
for(int i=VALUES.length-1; i>0; i--){
int rand = (int) (Math.random()*i);
char temp = VALUES[i];
VALUES[i] = VALUES[rand];
VALUES[rand] = temp;
} | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 5,
"tags": "java, random"
} |
jquery mail validation submits the form
I have a jquery to validate my email id,but after validation it submits form instead of preventing it.
my code is
$(document).ready(function(e) {
$('#personaledits').click(function(e) {
$('#persemail').each(function(e) {
email_address = $(this);
email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
if(!email_regex.test(email_address.val())){ alert('Please enter valid email'); e3.preventDefault(); return e.preventDefault(); return false; }
});
});
}); | Try this:
$(document).ready(function () { // event is not required here
$('#personaledits').click(function (e) {
$('#persemail').each(function () {
email_address = $(this);
email_regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
if (!email_regex.test(email_address.val())) {
alert('Please enter valid email');
e.preventDefault(); // You need to prevent the click event here
return false;
}
});
});
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, jquery, email validation"
} |
Trigger button click on other element
I have "copy-button" component which using in many place of the app and allows to copy information to clipboard. It has two bindings buttonText: '@', buttonClass: '@', which allows to change text of the button and add class for styling. What i need to do is change the view of copy-button and add icons instead of default button. But i can't trigger click event on this icon.
<div class="copy_code_bttn_block">
<copy-button button-text="b" button-class="copy_bttn"></copy-button>
<i class="icon-copy-code"></i>
</div> | copyButton.html
<button ng-click="onAdd()">Add
<i class="icon-copy-code" ng-if="isIcon === true"></i>
</button>
copyButton.component.js
angular
.module('app')
.component('copyButton', {
templateUrl: 'copyButton.html',
controller: copyButtonController,
bindings: {
onAdd: '&',
isIcon: '='
}
});
here onAdd can be in copyButtonController or in parent controller
use of copyButton component
<copy-button on-add="ctrl.add()" is-icon="true">Test</copy-button> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, angularjs"
} |
Restrict SharePoint access for 1 ActiveDirectory group
I have a **SP 2016 farm** running for some time. The Users are synced with our **Active Directory**. But now I have to restrict the use of our SharePoint to everyone except 1 **AD Group**.
What would the best approach be?
If you need further information, please ask. | In Central Admin, Web application management, highlight the web application you'd like to restrict for a group. Select User Policy from the ribbon and type the group name and select "Deny All". Click finish and test.
" to the denial policy, and my farm account, which is site collection admin also got an denial exception.
 C1,C2 FROM table1 GROUP BY C2)
as t2 on t1.C1=t2.C1 and t1.C2=t2.C2
Order by C2
Output
C1 C2 C3
3 AA 15
3 AA 16
3 AA 56
2 BB 53
2 BB 89
Live Demo
> < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "sql server"
} |
I feel I am being voted down on multiple posts without any apparent reason!
> **Possible Duplicate:**
> Serial Downvoting Victim
I get a feeling that my posts have been targeted by a particular user and voted down without any apparent reason! I come back online today to find that 5 of my posts have been voted down within a minute, so it's a little hard to believe that it's because my questions are frivolous! Is there any way we could find out and block the person who is doing such an activity from visiting our profile? It's just that it's really hard to earn rep which I need to start a bounty and when I see my posts voted down for no apparent reason, it just annoys me! | There is a background job to detect such serial downvotes. If it recognizes this as a series, it will undo the downvotes and reassign the reputation. It works for serial upvotes as well.
The detection algorithm, for good reasons, is not public. Otherwise malicious downvoters would game it easily. I would expect a minimum of rules like this: downvotes are from the same person, there are more than a certain number with a certain time frame.
You can always have a moderator look at it. Flag one of the posts for moderator attention and point to the other posts in question. A moderator could do a recalc as well to have your rep recalculated if necessary. | stackexchange-meta | {
"answer_score": 7,
"question_score": 4,
"tags": "support, serial voting"
} |
Swift: get index of start of a substring in a string
Is there a way to search a string for the index of the start of a substring?
Like, `"hello".indexOf("el")` would return 1. Thanks | You can reach using the `rangeOfString` function that finds and returns the range of the first occurrence of a given string within a given range like in the following way:
var text = "Hello Victor Sigler"
if let indexOf = text.rangeOfString("Victor")?.startIndex {
println(indexOf) //6
}
I hope this help you. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "string, swift, indexof"
} |
Show that a curve which is perpendicular to a vector exactly twice is the unknot
If I know that the tangent vector $T(s)$ of $\gamma(s)$, a smooth closed curve in $\mathbb{R}^3$, is perpendicular to some vector $\vec{v}$ exactly twice, say at $s_0$ and $s_1$, how can I show that $\gamma$ isn't knotted? I'm not allowed to use Fary-Milnor. I can see the picture, though.
Vector $\vec{v}$ gives us a family of planes. If one of these planes meets $\gamma$, then the intersection will contain one or two points. The plane will contain exactly one point of $\gamma$ when $T$ is perpendicular to $\vec{v}$ at either $s_0$ or $s_1$. Otherwise, as can be seen if we move the plane slightly away from $\gamma(s_0)$, $\gamma$ punches through the plane twice. | This is actually part of one of the possible proofs of Fáry-Milnor. As you pass planes orthogonal to $\vec v$ from the low point to the high point of the curve, you can have only two points of intersection (by a Rolle's Theorem argument). Joining those two points by a line segment in each of those planes will fill out a spanning disk for the curve, so it is unknotted. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "differential geometry, integral geometry"
} |
Hiding nib file in target application package and package organization issue
When I create an project of OS X normally, and then build it. When I click "Show Package Contents" on the target app, in its ./Contents/Resources directory, all resources (nib files, image files, sound files, etc) are put together.
* * *
Now there are **several questions** :
**< 1>** Can I hide my nib files from user to keep the completeness of it?
**< 2>** This may similar with the first one: can I package other resource files or encrypted them in on or several target file so that user could not modify them? Just like Windows applications do?
**< 3>** Can I organize my resources by directory in target package content? For example, if I show the package content of Firefox, all files are organized pretty. | 1) .nib files are readonly by default in XCode 4, the user cannot view or edit them.
2) Binary encryption can be done perhaps adopting from iOS to osx: Executable encryption check anti piracy measure
3) Organization can be done via drag and drop of folders: Create your folder in the filesystem, then drag it to the resource folder in XCode. In the following dialog select create folder reference for any added folder. The folder should be blue. This folder is copied to your bundle with its contents. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "xcode, macos, build, release"
} |
Finding successive <br /> elements, using jQuery
Imagine that I have this HTML snippet:
<div></div>
<br />
<div></div>
<br />
<img src='' alt='' />
<p></p>
<br />
<br />
<br />
<div></div>
<a href=''></a>
<br />
Which has no definite rule at all. The only thing I know, is that **3** consecutive `<br />` elements exist somewhere. Now, I need to find the **three consecutive`<br />` elements** using jQuery, and remove anything after them.
How can I do that? | $('br + br + br').nextAll().remove();
If there are potential text nodes to be removed, do this:
var el = $('br + br + br')[0],
nxt;
while( nxt = el.nextSibling ) {
el.parentNode.removeChild( nxt );
}
Or with more jQuery:
var el = $('br + br + br')[0],
nxt;
while( nxt = el.nextSibling ) {
$( nxt ).remove();
} | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "jquery, jquery selectors"
} |
Сборка C# в рантайме. Зачем разделять string на части перед компиляцией?
Наткнулся на следующую инструкцию. На примере программы Привет мир, отправляемой в компилятор, показано как можно получить нужный PE-файл из строки. Но я никак не могу понять, зачем здесь разделили строку на отдельные, если конкретно тут нет никакого форматирования.
string code = @"
using System;
namespace First
{
public class Program
{
public static void Main()
{
" +
"Console.WriteLine(\"Hello, world!\");"
+ @"
}
}
}
";
**Вопросы:** Зачем это нужно конкретно здесь? Это такая специфичность компиляции at Runtime? Может быть это всё просто заморочки автора?
Спасибо. | Не думаю, что здесь есть какой-либо в этом смысл, строку можно записать вот так, и ничего не изменится:
string code = @"
using System;
namespace First
{
public class Program
{
public static void Main()
{
Console.WriteLine(""Hello, world!"");
}
}
}
";
Быть может, автор поста просто не знал, как в verbatim string literal экранировать кавычки. | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "c#, компиляция"
} |
asterisk Call ID in sipml5
How do I get asterisk call Id (uniqueid in `cdr` table) (for instance, 1487150355.465) in sipml5 client. As far as I looked, I see only < which has (afaic) no relation to asterisk id.
I know I can set additional headers in asterisk and set there call id, but it cannot be done for some organizational reasons. Thanks. | Asterisk unique channel id(not call id) assigned to channel. By default asterisk not send that via sip or other protocol.
So no, you can't get it without do something on asterisk. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "asterisk, sipml"
} |
Quality and Speed of SQL Query
I want to know how much first query effect to speed of query or server Consider we have **50K** request during one minute .
First query:
SELECT CONVERT(NUMERIC(13,1), ROUND(width, 1, 1)) FROM Home
.
And for second query we use `round` on client side, it means combination of client and server side
SELECT width FROM Home | You could use a tool such as SQL Query Stress to put a load on your server. This will allow you to simulate as many users as you want to execute the query as many times as you like;
<
You could then use a tool such as Brent Ozar's fantastic sp_AskBrent to get some important metrics out of the system.
<
Ultimately it's going to be down to you to see how your server performs in each instance and make a decision on which route to go down. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "sql, sql server"
} |
comparing nil to integer in Objective-C
In the following case where `string` is an `NSString`
if (string.length < 1)
{
return;
}
and `string` turns out to be `nil` the `if` statement will still evaluate correctly because in this case `nil` evaluates to `0`.
However, is this recommended practice (by Clang or Apple) and are there any arguments against this and doing something closer to:
if (!string || string.length < 1)
{
return;
} | It's very common to do something like:
if (string.length) {
// string is not nil and the string has a non-zero length
} else {
// either string is nil or the length is zero
}
There is no need, in such a case, to check to see if `string` is `nil` or not.
When `string` is `nil`, you end up doing `[nil length]`. Calling any method on a `nil` pointer results in a value of "zero". How the "zero" is interpreted depends on the method's return type.
Primitive types appear as 0. `BOOL` appears as `NO`. Pointers appear as `nil`. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "objective c, compare, null"
} |
Is this a bug with the comment markdown syntax?
> **Possible Duplicate:**
> WMD unable to render markup inside words
Here's a comment I left on a post earlier:
The only thing is that I was wanting to assemble bytecode, not *dis*assemble it. :-)
I put the asterisks around dis because I wanted those three letters to be italicized. Should they have been? | No. It won't work in the middle of words.
It's part of the Three Markdown Gotchas. | stackexchange-meta | {
"answer_score": 2,
"question_score": 0,
"tags": "support, comments, markdown"
} |
Using the smaller of two values in SQL condition
I have a database of videos with a field for both the video width, and height.
I have queries set up to get videos of a specific resolution however it fails to return any videos that are portrait/vertical.
I would like to be able to do something like `WHERE MIN(width, height) == 1080` but to my knowledge, this isn't possible.
Is there anyway I can get my desired effect in SQLite? | SQLite supports multi argument `min` function which behaves like `LEAST` function.
**min(X,Y,...)**
> The multi-argument min() function returns the argument with the minimum value. The multi-argument min() function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. If none of the arguments to min() define a collating function, then the BINARY collating function is used. Note that min() is a simple function when it has 2 or more arguments but operates as an aggregate function if given only a single argument.
So you must be able to use it in the WHERE clause as you have mentioned in the question | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "sql, database, sqlite"
} |
Declare a variable with type of other type's variable type
The title looks complex. Let me try to open the topic. Have a look at a type used:
export interface IUser {
id: string;
displayName: string;
email?: string;
imageUrl?: string;
disabled?: boolean;
since?: Date;
}
There is a piece of the code where I need to declare a new variable - `id`. I expect this variable to be the type to be the same that `IUser` has as its `id`. In this case it would be `string`, but if the `IUser` is changed, I'd rather not change the variable type manually, but use something like:
`let id:typeOf(IUser.id)` | You can use square brackets to define type.
export interface IUser_1 {
id: string;
}
const id_1: IUser_1['id'] = 'foo';
export interface IUser_2 {
id: number;
}
const id_2: IUser_2['id'] = 7; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, typescript"
} |
PostgreSQL импорт из файла
Какой самый быстрый способ импортировать файл CSV в базу данных кроме COPY. Данных очень много, около 125 млн записей.
Загружаются они по крону раз в день. Парсить и заливать по одной строке не айс. Дифф никак не получить, только файл целиком со всеми записями. Все это на Symfony, если как то поможет или есть встроенные инструменты. | Единственный быстрый способ загрузить такое кол-во записей в базу, это использовать команду COPY
COPY table(column1, column2) FROM 'list_data.csv' DELIMITER ',' CSV HEADER;
Для 125 млн записей импорт занимает около минуты. эта команда требует прав root. Для запуска без прав администратора есть мета команда \copy
\copy table(column1, column2) FROM '/path/to/csv/data.csv' DELIMITER ',' CSV | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, postgresql, symfony, symfony2, doctrine"
} |
How can I select a word specified in textView
I have some text in a `textView` and I want all phrases that are as the `Note` in my text select them and change the their color to the red color. How can I do this? Is there a method for this? | try this
String text = "Some text in the text view.";
String searchText = "the";
int startPos = -1, endPos = -1;
if(text.toLowerCase().contains(searchText.toLowerCase())){
startPos = text.toLowerCase().indexOf(searchText.toLowerCase());
endPos = startPos + searchText.length();
Spannable spanText = Spannable.Factory.getInstance().newSpannable(text);
if (startPos != -1){
spanText.setSpan(new ForegroundColorSpan(Color.RED), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
yourTextView.setText(spanText);
}
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android"
} |
Windows 7: every popup window is maximized
I know this is a quite odd question, and I don't really know how to provide more elements to help you find a question. All I can say is that, suddenly, every window that has the chance to maximize itself will start maximized. One of the many examples is Chrome's preferences window, that should be a fairly small window but opens at full screen (1920x1080). Do someone have a clue?
Please help me in finding some more elements to get a proper solution. | I finally find the answer. It was Ati Catalyst's Desktop Manager: I disabled "Preserve Application Position and Size" in it and my popups now are ok. | stackexchange-superuser | {
"answer_score": 0,
"question_score": 1,
"tags": "windows 7, 64 bit"
} |
How can I parse this one?
Used XStream lib, but no children XML was difficult to parse in Java.
Wanting to parse Simple XML File but don't know how to do it.
Is there any effective way to parse ?
> _**< xml version="1.0" encoding="UTF-8" ? > < error > < ![CDATA[ Hello ]] > < /error >_**
thanks in advance. | You can retrieve the CDATA using sax using characters() callback. Here is the example | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, xml, sax, xstream"
} |
Why does 15.04 gnome-terminal not have the Unity-style scrollbars?
I really like the "overlay-scrollbars" that were introduced in Unity. Here is a screenshot: !Unity scrollbar
In 14.04, the gnome-terminal had overlay-scrollbars. But I installed 15.04 (full install, not update) and now gnome-terminal has the old-style scrollbars. The old-style looks like this:
!Old-style scrollbar
Is there anything I can do to get the overlay-scrollbar in gnome-terminal on 15.04? Did Ubuntu remove this style scrollbar from gnome-terminal or is there something wrong with my installation? | Try installing the `overlay-scrollbar` type typing in the following from a terminal window:
sudo apt-get install overlay-scrollbar
From a terminal type in the following to enable the scrollbar overlays:
gsettings reset com.canonical.desktop.interface scrollbar-mode overlay-auto
To disable the scrollbar overlays, type in:
gsettings set com.canonical.desktop.interface scrollbar-mode normal
Hope this helps. **;)** | stackexchange-askubuntu | {
"answer_score": 3,
"question_score": 2,
"tags": "unity, 15.04, gnome terminal, overlay scrollbars"
} |
What are some IT jobs where you don't sit at a desk for 8-10hrs a day?
Like a lot of people in IT I sit at a desk for 8-10hrs/day working on stuff that needs to get done "now". That usually means eating unhealthy lunches at my desk, and sometimes dinner too. This does terrible things to your health. I have been trying to work some exercise into the workday but I was thinking it would be great if I worked somewhere where I was exercising all the time (walking around, lifting servers, etc.).
Does anyone have a job in IT (or know someone) where you are actually moving around (not sitting) doing something for most of the day? | Any job you can do sitting down should be doable standing up. There's even an ad that appears on this and other sites for a vertically telescopic desk to allow for both positions.
In all my jobs the only person dictating whether it's a sit down job or not has been myself. If sitting doesn't suit you then you need to take steps to change it. It's not the job, it's the person who decides. | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 7,
"tags": "untagged"
} |
How can I report an app that contains ads but didn't provide a privacy policy url to Apple?
How can I report an app that contains ads but didn't provide a privacy policy url to Apple? I have tried to google myself, but I couldn't find a way to report it. | An app that doesn't have a privacy policy isn't necessary breaking any of Apple's rules or guidelines. The requirement that all these apps must have a privacy policy is quite new, and only apps or app updates submitted to the App Store after October 3rd 2018 need to comply.
You can use the following link to contact Apple's customer service:
<
Choose "Apps and Software" and then "App Store". | stackexchange-apple | {
"answer_score": 2,
"question_score": 0,
"tags": "privacy"
} |
Is (a sort of) converse to MVT True or False?
Suppose that $f$ is differentiable in a neighborhood of $c$. Then there are numbers $a$ and $b$ with $a<c<b$ so that $\frac{f(b)-f(a)}{b-a}=f'(c)$.
Is this true or false?
I'm pretty sure its false, but how can I show this? I think I can use the example $f'(c)=0$, but how would I do this?
Thanks in advance. | $f(x)=x^3$ with $c=0$ is a counterexample. This is so since $f'(c)=0$, but for all $a<c<b$ $f(b)-f(a)>0$, and hence $\frac{f(b)-f(a)}{b-a}>0\ne f'(c)$. | stackexchange-math | {
"answer_score": 5,
"question_score": 2,
"tags": "real analysis"
} |
Blog permalink pages missing formatting in Jekyll
I've created a site/blog with Jekyll and it works great except that the individual blog pages `2012/03/14/title-of-blog-post.html` are not formatted, there is no or css includes, just the `<p>`,`<h1>` tags got from processing markdown.
Is there something to be altered in the `_config.yml` to sort this, or do I need to add a script? | Make sure that you have basic YAML front matter the defines the layout at the start of your raw file. For example:
---
layout: default
---
Also, make sure that your source file is named with an extension that will get parsed. For example, to output:
2012/03/14/title-of-blog-post.html
Your source file should be:
_posts/2012-03-14-title-of-blog-post.md
It's probably one of those two things that's causing the issue. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "jekyll"
} |
How to detect if WebGL is available when using IEWebGL?
Currently I detect if WebGL is available with creating a canvas and trying to get the context for `"webgl"` and `"experimental-webgl"`. If both return `null`, WebGL will be disabled. Now the Problem is, when the user has IEWebGL installed the application itself works fine, but both getContext's return null, so the availability check returns false. When I visit the tutorial at the IEWebGL website ( I can see that they are doing it exactly like I am. Am I missing something? Some code:
var contextNames = ["webgl", "experimental-webgl"];
var isEnabled = false;
for(var i = 0, length = contextNames.length; i < length; i++)
if(canvas[0].getContext(contextNames[i]))
isEnabled = true; | You don't create a canvas element in IEWebGL, you use a object elment instead. Try to replace your canvas element with this and see if it works:
<object type="application/x-webgl" id="canvas"></object> | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, webgl"
} |
What is the dotted blue underlining when I use dictation on OS X?
When I use the dictation feature in OS X, sometimes some of my text has got dotted blue underlining below it after entry:
!enter image description here
What does this mean? Am I able to use it to correct the mistakes in the text more easily?
I am using OS X 10.8. | This highlighting "hyperlinks" the text, if the system is unsure of what you said. It will typically take a couple of best guesses, and display them as options from which you can choose from. You can see the suggestions by right-clicking the word or `control` clicking it.
It also selects the text when you click on it, which allows you to simply type a replacement if the options provided aren't correct.
This article may provide helpful information on dictation. | stackexchange-apple | {
"answer_score": 4,
"question_score": 3,
"tags": "macos, voice dictation"
} |
How to programmatically construct components at runtime using C++ Builder?
Very basic C++ Builder question. I want to create a TButton at runtime. I would have thought that the following code would do it, but I see no button on the form:
__fastcall TForm2::TForm2(TComponent* Owner): TForm(Owner)
{
TButton* b = new TButton(this);
b->Height = 100;
b->Width = 100;
b->Left = 0;
b->Top = 0;
b->Caption = "Testing";
b->Visible = true;
b->Enabled = true;
}
Thanks for any help! | You need to set the button's `Parent` (the surface it displays on):
b->Parent = this; | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 5,
"tags": "runtime, components, c++builder"
} |
How to view/save/load work space in ruby's interactive mode
I need an interactive environment to play with some algorithm stuff. I want to be able to view what's been defined (data, function) so far and be able save/load so I can continue from a previous saved snapshot if something went wrong. Since I chose ruby as my main scripting language, I hope it had these features built in.
If ruby interactive mode does not provide these functionality, what else you recommend for that?
Thanks | You should check out the sketches gem which let's you prototype code in a temporary file in your preferred editor. I don't think it supports snapshots.
In irb I would use it as follows:
>> sketch
# Write some code in an editor ...
# Lists sketches and their code
>> sketches
# Reopens the first sketch from above
>> sketch 1
If you want a more powerful interactive prototyping environment, see boson. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "ruby"
} |
Check if user has typed something while script is running
I have to write a script that prints every three seconds the % of CPU used by user or by system. If the user types a specific string, the output must switch back and forth.
How can I check for input without interrupting the output stream? The read command would stop it, I'm running out of ideas. | You can use the read command with the timeout option `read -t`. For example the below script detects the string 'cc'. You can also specify the number of characters to read with `-N` so that user does not have to press enter.
flag=0
while true; do
sleep 3
if [[ $flag -eq 0 ]];then
echo user
else
echo sys
fi
read -t 0.25 -N 2 input
if [[ $input = "cc" ]] ; then
[[ $flag -eq 0 ]] && flag=1 || flag=0
fi
done | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "bash, shell, unix, sh"
} |
Border is not showing correctly when i made a listing with div
I have data listing section made with div. Each row in my listing contains
<div class="itemBox" style="width:25px;">4</div>
<div class="itemBox" style="width:60px; height: auto;"> CPT4</div>
<div class="itemBox" style="width:60px; height: auto;">43633</div>
<div class="itemBox" style="width:60px; height: auto;"></div>
Css for itemBox is
.itemBox {
border-right: 1px dotted #ccc;
min-height: 15px;
padding: 5px 0;
}
**When one itemBox div have larger text content the border in that row won't show correctly** .Is there any way to fix this issue?.
byte1, (byte)byte2, (byte)byte3, 0x33 }
In alternative you can use `Convert.ToByte`, which throws an `OverflowException` if values are less than 0 or greater than 255. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "c#, arrays, arduino"
} |
Converting PEM to PKCS12 using intermediate certificate
I'd like to convert a PEM(+key) certificate to a `*.p12` file. I know this is how I do it when I don't have an intermediate certificate:
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
How do I do it when I have an intermediate certificate? | You need to concatenate all the PEM files into one, then convert it to PKCS#12:
$ cat certificate.crt intermediate.crt > bundle.crt
$ openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in bundle.crt | stackexchange-serverfault | {
"answer_score": 16,
"question_score": 7,
"tags": "openssl"
} |
Login/logout use case
Suddenly I've been in need of making an use case and I've stumped over a dilemma with the login/logout.
A co-worker tells me that they should be a use case by themselves like:
[login, admin stuff, logout]
But my brain yells at me that login should be an include of the use cases that needs a login while logout should be an extend of login.
[admin stuff -include> login -extends> logout]
So, which one? | Models are rarely right or wrong in absolute terms; they are simply more or less useful for a given purpose. Use cases are models of actions that users of your system are supposed to carry out. From your (too brief) description, I'd probably model Login and Logout as two separate, independent use cases.
Why would you extend one from the other? What is the commonality that they would share from your viewpoint? | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "use case"
} |
正規表現の文字クラスについて
* * *
**Q1.**
[ ]
> \d [ ]
* * *
**Q2.**
\d C
class \d {} | > Q1.
> [ ]
`\d``[0-9]``[0-9]``[``-``]`
`[``]``0-9``0123456789`
`[``]``(``)`/
> Q2.
>
>
* Wikipedia
* MSDN | stackexchange-ja_stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "正規表現"
} |
Find two submodules $E_1$ and $E_2$ such that $\textrm{Ass}(E_1) \cup \textrm{Ass}(E_2) \subsetneq \textrm{Ass}(E_1 + E_2)$
I'm looking for a module $E$ of a commutative ring $A$ with two submodules $E_1$ and $E_2$ such that the associated primes of $E_1 + E_2$ strictly contain the union of the associated primes of $E_1$ and $E_2$. There's a short exact sequence
$$ 0 \to E_1 \to E_1 + E_2 \to (E_1 + E_2)/E_1 \to 0 $$
where the last term is isomorphic to $E_2/(E_1 \cap E_2)$. So if they have trivial intersection the sequence splits and we have equality $\textrm{Ass}(E_1) \cup \textrm{Ass}(E_2) = \textrm{Ass}(E_1 + E_2)$. But I suspect that if the intersection is nontrivial there's a counterexample to this, I just can't think of what it would be. It won't work for something simple like $\mathbb{Z}$-modules, and I don't think it will work in general for integral domains. Or you might even need a non-Noetherian ring. I'm not sure. | Let $R=k[x,y]/(x^2-xy, y^2-xy)$, $E_1=(x), E_2=(y)$
Then $Ass(E_1) = Ass (E_2) = (x-y)$ but $E_1+E_2$ contains the element $x-y$... | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "commutative algebra, modules"
} |
How to say "Don't count on me" in Cantonese?
The context:
A: Want to get lunch on Saturday?
B: Don't count on me. My game may last until 1 PM.
Several suggestions were offered for how to say, "Don't count on me" in Cantonese, but none seemed right.
Here were three suggestions, but none had the right connotation:
1.
2.
3.
What's the right way to say, "Don't count on me" in Cantonese?
Thanks! | This answer has been edited:
There's no direct translation since the term "Don't count on me" in Cantonese is used in a sense of "don't rely on me" instead of "do not make decision base on me". Here's an alternative:
In oral: ""
: Don't expect me
: to come for sure ( is a slang for come, the formal word is )
So now you have told people you will come but it's not sure. | stackexchange-chinese | {
"answer_score": 2,
"question_score": 2,
"tags": "cantonese, hong kong"
} |
Missing output, using range() in Python
I am not getting the user output for an end-of-chapter problem in the Python book I'm reading.
Question is:
> Write a program that counts for the user. Let the user enter the starting number, the ending number, and the amount by which to count.
This is what i came up with:
start = int(input("Enter the number to start off with:"))
end = int(input("Enter the number to end.:"))
count = int(input("Enter the number to count by:"))
for i in range(start, end, count):
print(i)
after this input nothing happens except this:
Enter the number to start off with:10
Enter the number to end.:10
Enter the number to count by:10 | `range(10, 10, 10)` will generate an empty list because `range` constructs a `list` from `start` to `stop` **EXCLUSIVE** , so you're asking Python to construct a `list` starting from 10 going up to 10 but not including 10. There are exactly 0 integers in between 10 and 10 so Python returns an empty list.
In [15]: range(10, 10, 10)
Out[15]: []
There's nothing to iterate over so nothing will be printed in the loop. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 1,
"tags": "python"
} |
AsyncTask forever loop in Android
Currently I use this code for execute a task :
AsyncTask<Object, Integer, Void> task = new Task(getApplicationContext(), this.findViewById(android.R.id.content));
task.execute();
Now, I would like repeat this task forever in while loop, when the task is finished I would launch a new task..
How can I proceed ?
I know for get the status of task I can use : `task.getStatus();` But after ? | I don't know the details of your codes but here is a recursive solution,
AsyncTask has the `onPostExecute` method. Just call the another Task again in that method. However, if the Task is finished (you control it with whatever flag), start the new activity
protected void onPostExecuteTask(Object result) {
if(!flag){
//Run the Task again
}else{
//Start the new activity
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "java, android, android asynctask"
} |
PHP Syntax Error: mysqli_stmt_bind_param()
I've never worked with PHP and am powering through this code in order to get my Android device to store three variables on a web server. My error is coming from the last line of the following piece of code:
$name = $_POST[“name”];
$password = $_POST[“password”];
$username = $_POST[“username”];
$statement = mysqli_prepare($con, 'INSERT INTO `user`(name,username,password) VALUES(?,?,?)');
mysqli_stmt_bind_param($statement, “sss”, $name, $username, $password);
My file name is Register.php and the error is:
> Warning: mysqli_stmt_bind_param() [function.mysqli-stmt-bind-param]: Number of elements in type definition string doesn't match number of bind variables in /home/a9208046/public_html/Register.php on line 11
Can someone please help? Thank you. | You are using smart quotes `“`; if you had proper error-reporting you would see:
Notice: Use of undefined constant “sss” - assumed '“sss”' in /in/MnZR4 on line 3
This explains the problem; what you intend to be a 3 character string ends up being 5 characters, hence the error. Use normal quotes and it works fine. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, mysqli"
} |
How to specify multiple buildtypes in devenv tasks, CruiseControl.net
I want to do Clean and Build in devenv. I just noticed that buildtype flag can have only one item (Clean;Build not allowed). Do you have any idea how to specify multiple BuildTypes?
<tasks>
<devenv>
<solutionfile>C:\Source\Developer.sln</solutionfile>
<configuration>Release</configuration>
<buildtype>Build</buildtype> // How to do Clean and build here???
<executable>C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\devenv.com</executable>
<buildTimeoutSeconds>900</buildTimeoutSeconds>
</devenv>
</tasks> | You need two tasks. Each `<devenv>` block corresponds to one `devenv.com` invocation. The options to `devenv.com` only allow you to `/Clean` or `/Rebuild` instead of building. If you want to clean first and then build normally you will need to invoke `devenv.com` twice and therefore you need two tasks. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, visual studio, msbuild, cruisecontrol.net, devenv"
} |
How to create a bitmap like creating .csv file on android
We can create an csv file and save it in memory card as given in link
As same way I want to create Bitmap. So please help me how to create bitmap write some text on it? | you can use `Canvas` and `drawText()`.
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmp);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
c.drawText("Hello world!", xPos, yPos, paint);
bmp.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(destFilePath);
You can also set the font and text-size via the `Paint`-object. See How to set font and `Paint.setTextSize()`. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, bitmap"
} |
Ноль (нуль) - числительное или существительное?
Какой частью речи является слово "ноль" ("нуль")? | Видимо, проблема в том, что словом "ноль" **сейчас** обозначают и число и цифру. Различие "ноль-нуль", упомянутое **LiveStreet** , размыто. В разговорном языке для обоих случаев используют "ноль", а в многочисленных жаргонах (кроме математического) - "нуль"...
Видимо, надо смотреть по контексту (когда "ноль" рассматривается как цифра - существительное, когда как число - числительное). | stackexchange-rus | {
"answer_score": 1,
"question_score": 3,
"tags": "части речи"
} |
Android disable autocomplete for a certain string
I have an AutoCompleteTextView set up right now, but I want to prevent it from auto-completing a certain string (the user has to input it manually to get a result). Right now it is auto-completing for the entire list, but I was wondering if there is any way to make the auto-completion selective.
Thanks! | Although I haven't done this myself, but i think if you provide your own implementation of getFilter method in Adapter you can control if any results will be shown or not. So basically you will define the class
public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable
and then override getFilter method
@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
......
}
@Override
protected void publishResults(CharSequence contraint, FilterResults results) {
....
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "android, autocomplete, autocompletetextview"
} |
Google App Engine "no module named requests" PyDev
I downloaded and installed requests library for Python 2.7. Using the shell I can make "import requests" and actually use it without problems.
Thing is that when running Google App Engine it can't find it and prompts the error:
ImportError: No module named requests
I'm using PyDev-Eclipse as IDE for my project and tried adding the path (/usr/local/lib/python2.7/dist-packages/requests) both in
Project > properties > PyDev - PYTHONPATH > External Libraries
and in
Window > preferences > Pydev -Interpreter > Libraries
and none worked! Still having the same issue when trying to run my GAE app
Anyone could help?
Thanks! | Any 3rd party lib you use must be physically included in your project and deployed to appengine. This means it is not sufficient to just install with easy_install or pip
See the docs < | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 4,
"tags": "google app engine, pydev"
} |
How to create a new container from container?
Is there a way to create a new StructureMap container from an existing one? I want to have all the dependencies from the fisrt container plus another ones in the new container. | A nested container pulls all non-transient instances (Singleton, HttpContext, ThreadLocalStorage scoped etc) from its parent container. Once disposed, it will dispose all transient objects that implements `IDisposable` in it.
You create a nested container using:
using (IContainer nested = ObjectFactory.Container.GetNestedContainer())
{
var service = nested.GetInstance<IService>();
service.DoSomething();
}
Nested containers are generally used when you need fine grained control over the lifetime of the transients in them, such as creating and disposing of objects used in a per `HttpRequest` scenario. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, inversion of control, ioc container, structuremap"
} |
Wildcard for terms in phrase - Lucene
Google's query syntax allows to search phrases like "as * as a skyscraper" where the asterisk can match any term (or terms). Is there a way to achieve the same thing in Lucene? The proximity operator ~ could be of use but it is not what I exactly want. | Try a SpanNearQuery. Mark Miller's SpanQuery Blog Post explains how to use it, and the examples are similar to what you describe. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "lucene, wildcard"
} |
Disk ceramic capacitor reading
I'm struggling to decide if this capacitor is 150pF or 68pF (and in the latter case, what does the `151K` stand for?)

And what I need to do is style every third div in this container which I've done with:
.positionDivs div:nth-child(3n){
background-color:black;
}
but I also (and this is the part I can't work out!) need to style the centre column. In the example above this would be numbers 2, 5 and 8.
Could anyone assist please? | Just subtract one from what you have to select the previous div:
.positionDivs div:nth-child(3n-1){
background-color:red;
}
**jsFiddle example** | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "html, css, css selectors"
} |
Magento 2 : modules install but not showing in admin panel
Please stop me tearing what is left of my hair out.
Magento 2.2.4, two modules installed via composer. Cleared var/page_cache, var/view_preprocessed, var/cache, pub/static, generated/. Then run :
bin/magento setup:upgrade
Modules show up fine in the list that scrolls past. Modules also list as enabled in app/etc/config.php
Then run
bin/magento setup:di:compile
bin/magento cache:clean
bin/magento cache:flush
bin/magento setup:static-content:deploy
The modules show up in pub/static/adminhtml/Magento/backend/en_US and generated/code, but there is absolutely no sign of them in the admin panel itself.
What am I missing? They deploy fine on the dev site which is running the same structure. | Solved. Just realised that I needed flush the PHP OpCache! | stackexchange-magento | {
"answer_score": 1,
"question_score": 1,
"tags": "magento2"
} |
htaccess direct domain and subdomain?
I have a problem where I want to redirect all traffic [301 permanent] from
www.example.com --> www.website2.com
blog.example.com --> blog.example.com
So redirect all domains/subdomains on "Example.com" to website2.com EXCEPT for the blog on example.com ? Little unsure how to set this up using .htaccess on "example.com" ?
Really appreciate any help. | Somewhat similar to this question:
RewriteCond %{HTTP_HOST} !(^blog\.example\.com$)
RewriteRule (.*) [R=permanent,QSA,L]
Line by line:
In case the `Host:` header ("%{HTTP_HOST}") is _not_ ("!") `blog.example.com` (no other string matches that regex), execute the following rewrite:
for a pattern matching anything (".*", that is, for any URL), redirect to the same path on www.website2.com (e.g. < will get redirected to < ). | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": ".htaccess, redirect"
} |
How is moha (मोह) different from kaama (काम)?
To my best understanding moha (मोह) is enchantment and kaama (काम) is desire. However, I am looking for textual references differentiating the two! | Sri Krishna says in Gita about desire - काम and delusion - मोह.
> ध्यायतो विषयान्पुंसः सङ्गस्तेषूपजायते।
>
> सङ्गात् संजायते **कामः** कामात्क्रोधोऽभिजायते।।2.62।।
>
> In the case of a person who dwells on objects, there arises attachment for them. From attachment grows **hankering** (strong desire), from hankering springs anger.
>
> क्रोधाद्भवति **संमोहः** संमोहात्स्मृतिविभ्रमः।
>
> स्मृतिभ्रंशाद् बुद्धिनाशो बुद्धिनाशात्प्रणश्यति।।2.63।।
>
> From anger follows delusion; from **delusion** , failure of memory; from failure of memory, the loss of understanding; from the loss of understanding, he perishes.
So desire - काम is the grand father of the delusion - मोह | stackexchange-hinduism | {
"answer_score": 4,
"question_score": 3,
"tags": "desire, kama"
} |
How to save(assign) the output from lapply into individual variables in R?
I have a very simple question but I've stocked in it! I have a list as an output :
as an example :
lapply(1:40, function(x){ (1+x)})
output:
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
till
[[40]]
[1] 41
I wondered how can I assign each of the outputs of this list to a new variable by using a loop? something like this
`a<- [[2]]; b <- [[3]]; ... az <- [[40]]` and so one.
Thanks in advance, | Here is my solution, it requires that your output of `lapply` is stored with the name `ll` but it can be easily modified I think.
ll <- lapply(1:40, function(x){ (1+x)})
nam <- "list_output_"
val <- c(1:length(ll))
for(i in 1:length(val)){
assign(
paste(nam, val, sep = "")[i], ll[[i]]
) }
The output will be `list_output_1` and so on. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "r, loops, save, lapply, assign"
} |
Question about circumcircle and tangent & angle bisectors at a point of the triangle
If the tangent at $A$ to the circumcircle $ABC$ meets $BC$ at $X$ then prove $XA=XD=XD'$ where $D$ and $D'$ are the points where the internal and external bisectors of $A$ meet $BC$ respectively.
I have not been able to find/use any theorems relating to the fact that $AX$ is a tangent. | 
Then $\angle XAD = \angle XAB + \angle BAD = \angle ACB + \angle CAD$ (angle bisector) $=\angle BDA$ (exterior angle of triangle)
This equality gives $XA = XD$.
The other part can be done by observing the interior and exterior angle bisectors are perpendicular. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "geometry, euclidean geometry"
} |
Filter out approved code reviews in gerrit
I have a few (~20) reviews in "Incoming reviews" section, and I would like to either move or filter out those that I did "Code-review" +2 or +1 myself. Preferably move to the other section "approved incoming reviews" or other comparable solution. Currently gerrit grays out subjects you approve, but it also grays out any other projects you post some comments. So it does not filter those efficiently, and you have to revisit every project. That is time waste.
I have tried to remove myself from the project after the approval, but such action removes approval as well.
Is it even possible? | A suggestion:
1) Click on **_YOUR-NAME_** > **_Settings_**
2) Click on **_Preferences_**
3) In **_My Menu_** add the following:
Name = Review (or other name you want)
URL = #/q/reviewer:self+status:open+label:Code-Review=0%2Cuser=self
4) Click on **_Save Changes_**
Now if you click on the new menu item: **_My_** > **_Review_** you will see all open changes you're a reviewer but don't have voted yet. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "gerrit"
} |
There is really something like Objective C++?
I'm reading a post about iPhone programming and I've noticed that the talk about Objective C++, the code shown in the post looks mainly like Objective-C but there also are several snippets in C++. Is it really possible to program Cocoa from C++? | In addition to the other comments, I would add that Objective-C++ is not exactly the same as "program Cocoa from C++" because there is no C++ to Cocoa bridge involved.
In Objective-C++, you program the Cocoa API entirely with Objective-C objects/syntax. The Cocoa API remains unchanged, so you need to communicate with it in the same way (using Objective-C strings, Objective-C arrays and Objective-C objects).
The difference with Objective-C++, compared to plain Objective-C, is that you can _also_ use C++ objects (containing Objective-C objects, contained by Objective-C objects or just along-side Objective-C objects). | stackexchange-stackoverflow | {
"answer_score": 15,
"question_score": 3,
"tags": "c++, objective c, cocoa, macos, objective c++"
} |
UK 2m Morse Simplex
I got my foundation licence and a Baofeng. Just curious if it's in the license boundaries that I could make a little Morse weather station?
It would be controlled by computer and transmit once every 5/10 minutes, with my call sign of course. | My understanding of the rules is that your idea would be perfectly legal. According to the OFCOM terms (PDF file):
> 10(1) The Licensee may conduct Unattended Operation of Radio Equipment provided that any such operation is consistent with the terms of this Licence. Additional restrictions which apply to the Unattended Operation of Beacons are specified in Schedule 2 to this Licence.
Basically, as long as you conform to the normal rules (correct band, power, stating your call sign regularly, etc) it's acceptable. | stackexchange-ham | {
"answer_score": 1,
"question_score": 3,
"tags": "legal, united kingdom, automation"
} |
Accessing windows 2003 firewall settings with RRAS enabled
Windows Server 2003 (VPS)
Trying to install MySQL, but the service isn't starting - suspect the port is being blocked by the firewall.
One of my Google searches lead me to which seems to indicate I need to change my RRAS settings in order to access the firewall settings.
I've set up the RRAS so I can VPN into another network, so I'm reluctant to change them without understanding what the impact will be.
* Is there a way to access the windows firewall settings without modifying RRAS settings?
* How do I check if the firewall is even running?
* Is the RRAS change (disable NAT?) going to cause problems with my VPN connection?
-Adam | Windows Firewall/ICS and RRAS often don't play nice with each other. It has something to do with an IPNAT.sys conflict as mentioned in that article. If you don't want Windows Firewall running on that box at all, your best bet will be to do the following:
Disable RRAS (temporarily) by going to Administrative Tools -> RRAS, right click on your server name, click 'Disable...'
Go to your server's network connections, open up the properties box, click on the 'Advanced' tab, click on the 'Settings...' button for Windows Firewall. Turn Windows Firewall off. Click ok, etc.
Go back to the RRAS config window, right click on your server name again, click 'Enable...' and test things out. | stackexchange-serverfault | {
"answer_score": 2,
"question_score": 2,
"tags": "windows server 2003, mysql, vpn, firewall, rras"
} |
Is there another way to represent this summation?
I wish to calculate $\sum_{x=1}^{n}\sum_{y=1}^{n} f(x,y)$ where $x>2y$. I can do this by changing $y$'s upperbound to the floor of $(x-1)/2$ but this makes simplification of the summation harder later. Is there a way using inclusion-exclusion to simplify this sum? | No need to evaluate a floor. Since $x > 2y$, $x \geq 2y + 1:$
$$\sum_{y=1}^n \sum_{x=2y+1}^n f(x,y).$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "number theory, summation"
} |
Anet A6 ERR MAXTEMP BED error
Out of the blue my A6 printer displays a ERR MAXTEMP BED error and shows about 100 degrees on the bed even when just powered on.
A quick thermistor check shows that it's working properly : about 80 kOhm at room temperature, similar to other units (didn't bother to really check the specs).
Swapping the bed thermistor for the head thermistor connector does not change the temperature readings : the one connected to the bed input gets 100 degrees, while the other one works as expected, proving that the connector and thermosensor are ok.
It has to be in the board. How do I fix it? | I'm posting the answer here hoping that will help anyone that encounters a similar issue. A post on another site indicated that these boards are known to be problematic.
After some digging, I came up with the schematics of this part of the mainboard :
;
**output**
 = C(5+3-1,2) = \frac{7\times6}{1\times2} = 21$
Thanks! | When dealing with combinations (order doesn't matter) with repetition, you use this formula (where n = things to choose from and r = number of choices):
$\frac{(n+r-1)!}{r!(n-1)!}$
In your example problem you would then have n = 3, r = 5:
$\frac{(3+5-1)!}{5!(3-1)!} = \frac{7!}{5!2!} = \frac{7*6}{2*1} = 21$, so yes you are doing it right! | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "combinatorics"
} |
Jersey - Json Libraries for GET & PUT
Why do I need the json jersey dependencies on client side for
service.path("rest").path("object").path(id).accept(MediaType.APPLICATION_JSON).get(ObjectDTO.class);
but not for
service.path("rest").path("object").path(id).accept(MediaType.APPLICATION_JSON).put(ClientResponse.class, object);
Server side looks like this:
@GET
@Path("/{objectId}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
...
@PUT
@Path("/{objectId}")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
...
In first case I get a json stream, in second case I send a stream. So why do I need the libraries just for getting the stream? | Ok. It is caused by the accept header: for my put request it isnt necessary to set that. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "json, rest, jersey"
} |
asp .net mvc2. how to create a clone like tadalist
I am currently learning asp.net MVC2. I was trying to do a simple project similar to tadalist.com
Could you please guide me to some articles on how to create the dynamic textboxes and how to capture the user input for persistance?
Thanks | This may help. Try the demo.
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "asp.net mvc"
} |
Laravel tinker not working
I am facing a weird issue, Its quite simple, I am finding the first user in `User` model :
D:\xampp\htdocs\next-gen>php artisan tinker
Psy Shell v0.7.2 (PHP 7.0.6 ΓÇö cli) by Justin Hileman >>>
$user=App\User::first()
`[Symfony\Component\Debug\Exception\FatalThrowableError]
Parse error: syntax error, unexpected '1' (T_LNUMBER), expecting variable (T_VARIABLE)`
The above error comes up, With other models the following method works. | There was an issue in my `User` Model, I was passing the raw values in parameters.
Thanks | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, laravel, laravel 5"
} |
Constants in ruby
I have a string like below,
STRING_FIRST = "Abcd. Efgh. ijkl"
I need to declare the above string as constant in ruby. But it gives complie time error on first dot(.).
Can any one please help.
Updating the actual code alike.
class class_name << Test::Unit:TestCase
include module1
STRING_FIRST = "Abcd. Efgh. ijkl"
def method1
xxx
end
end | In Ruby 1.9.3 I get a different error, and as Frederick Cheung points out, rightly so:
syntax error, unexpected tLSHFT, expecting '<' or ';' or '\n'
You're inheriting using the shift operator, which is incorrect. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "ruby, string, constants"
} |
Regex: Split at Next Newline After Word
I have a statement like this:
> blah
> blah
> John did this
> blah
> blah
> John did that
> etc.
I need this text split at the newline at the end of the lines that start with John. The text after John isn't consistent, but the last line always start with John. Splitting it at 'John' is easy, I just don't know how to say 'split at next newline after the word John'.
.split(/(.*?John*?\n)+/g)
Above splits it with John becoming its own entry, when I want it to stay with the stuff above it.
_EDIT_
Output should be:
> (blah
> blah
> John did this)
> (blah
> blah
> John did that)
> (etc...
Where the parenthesis represent the split boundary/single array entry. | I think it will work for you:
.split(/.+John.+\n/g)
`.` any element
`+` 1 or more times
`John`
`.+` any elements 1 ore more times
`\n` new line
`g` global. Not stop at the first split.
_Edit_
With this: `.split(/(.*?John*?\n)+/g)`, you are matching:
`.*` any elements 0 ore more times
`John*?` John 0 ore more times. `?` doesn't have sense here.
`\n` new line
So this is not matching anything but John again after John, or new line. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "jquery, regex, split"
} |
Date difference in minutes in Python
How do I calculate the difference in time in minutes for the following timestamp in Python?
2010-01-01 17:31:22
2010-01-03 17:31:22 | from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 17:31:22', fmt)
print (d2-d1).days * 24 * 60 | stackexchange-stackoverflow | {
"answer_score": -44,
"question_score": 97,
"tags": "python, datetime"
} |
How to get network image height and width using Glide?
I am trying to get height and width of network image. I am using Glide to display image.
Code I've used in Java is:
Glide.with(getContext().getApplicationContext())
.asBitmap()
.load(path)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap bitmap,
Transition<? super Bitmap> transition) {
int w = bitmap.getWidth();
int h = bitmap.getHeight()
mImageView.setImageBitmap(bitmap);
}
});
How can I achieve this in Kotlin? | Glide.with(context.applicationContext)
.asBitmap()
.load(path)
.into(object : SimpleTarget<Bitmap?>() {
override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap?>?) {
val w = bitmap.width
val h = bitmap.height
mImageView.setImageBitmap(bitmap)
}
}) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "android, kotlin, android glide"
} |
Load a library in a model in CodeIgniter
Why won't my model load the encryption library?
class User_model extends Model {
function User_model() {
parent::Model();
$this->check_login();
}
function check_login() {
$this->load->library('encrypt');
$email = $this->encrypt->decode($email);
....
}
}
This giving me a PHP error: Call to a member function decode() on a non-object on line X -- where X is the $this->encrypt->decode($email); line?
_Edited to show that the problem was that check_login was called from the constructor_ | I was calling check_login from within the constructor, and that was causing the problems.
The solution is to call `$this->_assign_libraries();` right after loading a library in a constructor.
Thanks to this codeignitor forum thread: < | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 13,
"tags": "codeigniter"
} |
Как читать URL во Vuejs?
У меня есть непонятная немного для меня задача. Есть страница, на которой есть 5 групп радиокнопок. Пользователь может их отметить, и тогда будет выведен контент. Но есть кейс, в котором по специальному урлу (например .com/?radio1=cas&radio2=des) Пользователь должен попасть на страницу, в которой эти кнопки сразу должно быть отмечены. Есть у кого идеи, какую документацию покопать, или как сделать?
То есть другими словами, мне нужно, чтобы урл, отмечал данные из даты. Например если есть переменная radio1, значит брать ее значение и подставлять в дату. Хотя я могу ошибаься, возможно есть другой путь | В router.js делаете примерно вот так (ну или вешаете хук на конкретный маршрут).
....
import store from '@/store';
....
....
....
router.beforeEach((to, from, next) => {
if (Object.keys(to.query).length !== 0) store.commit('setRadioData', to.query);
next({ name: to.name, params: to.params });
});
В Vuex проверяете что там вам пришло, записываете в state. В компоненте v-model для радио кнопок берете из computed свойства с сеттером и геттером.
Если что-то не знаете как сделать пишите в коментах - распишу подробнее. | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "vue.js"
} |
how to represent a consequence relation in a use case?
I'm making a use case diagram for an android application and i want to represent a "consequence" relation but i don't know what to use exactly.To be more clear, i'm calculating something and depending of the result i'm calculating something else, how to repesent that ?
Thank you | A use case diagram shows an objective not working, for that use an activity or sequence diagram. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "uml, use case"
} |
Magento 1.9.2 - show "category page & layout" on front home page (RWD theme)
How to show exactly the same Category Page on Homepage?
* without banners, without home boxes, no 1 column layout
* just full Category Page (i.e. with sidebar, filters, layered nav, 2-3 columns layout, product listing), and NOT only product from particular category - again, standard category page to be shown, just like you click on category link.
Any help? | There are a couple of options:
1. Find out the ID of the category you want to to display, creating it if necessary. Then go to `System > Configuration > Web > Default Pages` in your admin and enter the following for the `Default web url` option: catalog/category/view/id/99 (where 99 is the id of the category).
2. Create a normal CMS page, assign it as the homepage in `System > Configuration > Web > Default Pages` then call a category list.phtml with
`{{block type="catalog/product_list" category_id="99" template="catalog/product/list.phtml"}}` | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "magento, layout, html, categories"
} |
Extract information of a raster overlayed on another raster with a lower resolution directly in python
I have two aligned rasters with the same extent, one has a resolution of 5 meters and the other of 125 meters. I would like to place the 5 meter one over the 125 meter one and assign to these smaller pixels the value of the large pixel on which they land on. How can I do this in pure python code? The raster I/O is not a problem. | Here's one way, using Numpy and GDAL.
Read your 125m resolution raster into an array that is 25x larger in each dimension. GDAL's I/O function decimates for you and this feature is available in Rasterio (< and I assume also in osgeo.gdal. Ask the methods to write into an array that's bigger than the source image, and they upsample.
Using the gdalwarp utility with "nearest" interpolation would give you the same result.
GDAL: <
Rasterio: < | stackexchange-gis | {
"answer_score": 3,
"question_score": 2,
"tags": "python, raster, python 2.7, overlay"
} |
If, like Edward Snowden, your passport was revoked or cancelled, how could you travel?
As per the news, NSA whistle-blower Edward Snowden has had his passport revoked by the United States Government.
From the article:
> It was not immediately clear how Snowden was able to travel,
However, he was able to fly from Hong Kong to Russia, and apparently plans to continue on to Latin America / Cuba.
**With a revoked passport, how is one legally able to travel internationally??** | Very simple:
From the US State Department Website last sentence.
> A federal or state law enforcement agency may request the denial of a passport on several regulatory grounds under 22 CFR 51.70 and 51.72. The principal law enforcement reasons for passport denial are a federal warrant of arrest, a federal or state criminal court order, a condition of parole or probation forbidding departure from the United States (or the jurisdiction of the court), or a request for extradition. The HHS child support database and the Marshals Service WIN database are checked automatically for entitlement to a passport. Denial or revocation of a passport does not prevent the use of outstanding valid passports.
So if you have a passport that is valid. Until you're in the country that shares information with country revoking the passport and chooses to comply with this revocation the only country you're not going to be able to enter would be the country issuing the passport. | stackexchange-travel | {
"answer_score": 37,
"question_score": 60,
"tags": "passports, legal, international travel, paperwork"
} |
Difficulty understanding condition variable wait
I am having difficulty understanding the condition variable statement
cv.wait(lk, []{return i == 1;});
from this link
what role does the lambda function play here.
Does the above statement mean "Stop blocking when the mutex held by the unique_lock lk is free and i==1 " | Predicate is used to check if the wait condition should go to waiting state again or stop blocking the thread so the thread will continue running. When you awake the wait condtition with notify then it makes a check using predicate and decides what to do next - sleep again or let the thread keep working.
There is a self explaining code on the link provided by you:
while (!pred()) {
wait(lock);
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, multithreading"
} |
Passing data from Html.Action to the partial view
I'm still relatively new to MVC 3. I need to pass data from my @Html.Action methods through the controller to a partial view.
So here is my flow.
I'll call @Html.Action like this:
@Html.Action("SidebarMain", "Home", new List<int>(new int[] {1, 2, 3}))
Then it will hit my Controller. Here is my method in my Home Controller:
public ActionResult SidebarMain(List<int> items)
{
return View(items);
}
Then my Partial View should be able to access the data like so:
@model List<int>
@{
ViewBag.Title = "SidebarMain";
Layout = null;
}
<div>
@foreach (int item in Model)
{
<div>@item</div>
}
</div>
BUT: I'm getting a null exception for the Model, meaning It's not passing through. | Try this:
Html.Action("SidebarMain", "Home", new { items = new List<int>(new int[] {1, 2, 3}) })
And put a breakpoint in your SidebarMain Action to see, if you are getting `items` | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "c#, asp.net, .net, asp.net mvc 3, asp.net mvc 3 areas"
} |
The origin of "break of day"
I was quite surprised to know that "break of day" actually means "dawn", that is, the beginning of the day.
But, the phrase "break of day" sounds much more like the end of the day, not the beginning of it. So, I'm quite interested in the origin of it. | Daybreak (n.) is quite an old expression:
> * 1520s, from day + break (n.).
>
Break:
> * Meaning "to disclose" is from early 13c.
>
(Etymonline)
Ngram shows that both expressions, _daybreak and break of day_ , have been used from the 16th century.
At the crack of dawn is a similar expression:
> * Fig. at the earliest light of the day. Jane was always awake at the crack of dawn. The birds start singing at the break of dawn. (McGraw-Hill Dictionary)
> | stackexchange-english | {
"answer_score": 3,
"question_score": 1,
"tags": "phrase origin"
} |
How to erase reverse_iterator correctly when erase and push_back happens?
I have a list container, which looks like:
std::list<int> l = {1,2,3,4,5,6,7,8};
i often erase elements, so i choose `std::list`.
but, i also want to find the elemnt in O(1), so i record the reverse_iterator.
For Example:
l.push_back(9);
auto s = l.rbegin(); // record the iterator of 9, in order to erase it in the future fastly.
cout << *s << endl;
l.push_back(10);
auto s2 = l.rbegin();
but when i erase like this:
l.erase(std::next(s).base()); // s the iterator of 9, in my brain
i want to erase 9, but actually, it erase 10.
I have two questions:
why i should use `next`? actually my `*s` can get the element, which is different with `.end()`.
how can i make the erase happen in my previous saved iterator? | l.rbegin().base() == l.end(), which is not the position of the last element, but the end of the list. and `push_back` again won't affect this existing iterator, it is still pointing to the end of the list.
Then std::next(l.rbegin()).base() == l.end() - 1, which now is pointing to the last element `10`.
So if you want to remember the position of the `9`, you better use a normal iterator instead of a reverse one, or, use a reverse iteractor whose base pointing to `9`, and that should be `auto s = std::next(l.rbegin())`, and erase it as `l.erase(s.base())`.
the rule is `&*r == &*(i-1)` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, stl"
} |
Why should we use semantic HTML5 elements such as header and footer instead of div?
I'm designing a website, but some websites use semantic HTML5 tags like `<header>` or `<footer>` instead of div.
My question is, why do they use them like this, is there any harm in terms of SEO when using normal divs? | These tags come with HTML5 and all of these tags have a meaning. For example, the purpose of using the `<footer>` tag is for the Google bot to understand that this section is the footer of the site. If you're using a regular div, Google bots may have trouble understanding that it's the footer of the website. The more convenience you provide to Google bots, the better your website will be crawled and SEO done. Also, there is no harm in SEO if you don't use them. | stackexchange-webmasters | {
"answer_score": 0,
"question_score": 2,
"tags": "seo, html, technical seo, semantic elements"
} |
Using apply() over a list
I have a list with 100 vectors indexed by:
[[1]]
[1]
[[2]]
[1]
[[3]]
[1]
.
.
.
[[100]]
[1]
Each vector has 3 entries.
I would like to apply a function separately for each of the vectors. The function returns a single number for each vector so the result of the apply() would be a 100 element vector.
How can this be done using apply?
I know I can use apply for matrices by indexing 1 or 2 depending on row or column but can it also be used for lists? | You are looking for `sapply`:
l <- list(1:3, 2:4, 5:7)
sapply(l, sum)
# [1] 6 9 18
This answer might help you in the future. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -5,
"tags": "r, list, apply"
} |
Concatenating string and binary data in python
My goal is to write mongo queries where id is binary. I have hexadecimal data which is converted to binary string and fed to query. my code:
b=binascii.a2b_hexdata('#hexadecimal string#')
query=_collection.find({'_id':b})
This works fine. But I want to generalize this for any query. I tried this:
query_string={'a':"{'_id':"+b+"}"}
query=_collection.find(query_string)
This throws error. This is evident as I'm trying to concatenate binary and string(unicode) characters. So I tried decoding b with utf-8, but it throws error. Is there any way to concatenate binary and string data? | In the mongo query form query as a dictionary. for ex:
b=binascii.hexdata('/string/')
query={'id':b}
#if you want to add another condition like a.Status
query['a.status']=/your value/
result=_collection.find(query) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "python, string, concatenation, binary data"
} |
Lat long api does'not work
After a long search and implementation i am here to need your help..I am using google api to calculate lat long; for this in code i call the api like below mentioned
$jsondata=file_get_contents(@'maps.googleapis.com/maps/api/geocode/json?address="75300+Karachi+PK"&sensor=false’');
but it return me null array data; but if same url of api if i type on browser like ` then it shows me the data in array
what i get mostly in searches that the error is because more than 2500 requests, however i am not sending a 2500 requests obviously.
really appreciate any help; please guide id there is any mistake in my code | $jsondata=file_get_contents(' | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, google maps"
} |
Have you heard Gokigen Naname?
> Here is a regular **Gokigen Naname** a.k.a **Slalom** a.k.a **Slant** puzzle.
> An online (mobile-friendly) version is available here.
 on each cell.
> * Each number in a circle denotes the number of slashes touching it.
> * The slashes should not form a loop.
> | Complete (Hello, it's me, I'm back!)
>  When you see two adjacent '3's, They must be two back to back T-shapes (see that on row 4)
> 2) When you see two '1's on opposite corners of the same square, the slant must not connect the '1's.
> 3) When you make a sure line for an '1', the figure surrounding the '1' will resemble a power button (yeah, give some imagination)
Comments:
A very fun puzzle! Finally got my brain turning after my long break from PSE... ;) | stackexchange-puzzling | {
"answer_score": 6,
"question_score": 8,
"tags": "logical deduction, grid deduction"
} |
Using Regex in JavaScript to get an array of numbers from string including negatives and floats
I want to retrieve all numbers, even negatives and decimals, from a string using JavaScript. Ideally, these numbers would be in an array.
Examples:
'1 2.5 5' ---> [1, 2.5, 5]
'-4.7 abcd56,23' ---> [-4.7, 56, 23]
Here's what I have:
function processUserInput() {
let rawUserInput = document.getElementById("number-input").value;
let negativeNumRegex = /^-?[0-9]\d*(\.\d+)?$/g;
return negativeNumRegex.exec(rawUserInput);
}
UPDATE: This is correct
/-?[.\d]+/g | It rarely makes sense to have an expression with anchors at both ends and the `g` flag. (It can, with an alternation, but other than that it usually doesn't.)
I'd probably use something simpler: `/-?[.\d]+/g`
const rex = /-?[.\d]+/g;
console.log('1 2.5 5'.match(rex));
console.log('-4.7 abcd56,23'.match(rex));
.as-console-wrapper {
max-height: 100% !important;
}
Note that that doesn't validate against things like `4..2` and such. Exercise left to the reader. :-) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": -1,
"tags": "javascript, regex"
} |
Align text vertically to middle not taking affect
I need to align text near an icon to middle. See the admin word near the user icon in this sandbox:
<
I have this css, but it's not taking affect:
.HeaderToolbar {
background-color: black;
color: white;
fill: white;
width: 100%;
margin: 0 auto;
align-items: baseline;
vertical-align: middle;
/*white-space: nowrap;*/
}
![enter image description here]( | You need to add a class to your element and then add a css to your class:
display: flex;
justify-content: flex-start;
align-items: center; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "css"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.