INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Context Menu for user setup on first use?
I'm trying to set up a menu that appears when the user starts the app for the 1st time, so they can set it up by choosing from 1 of 6 items. It needs to start automatically dependent on a boolean value taken from sharedPreferences. I have been trying to create a context menu, but its not working and I'm not sure if its the right way to go about it. Has anyone done this and is context menu the right way to go? If not, please could you point me in the right direction. Many thanks
|
You shouldn't be using a ContextMenu for this kind of design. You should be using a Custom Dialog for the configuring of your app. Using perhaps a ViewSlider to allow multiple configuration screens or just one View with all the configuration options in a ScrollView.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "android, menu"
}
|
How to create an indexed vector base on another vector?
I'm trying to create an indexed vector based on another vector. Here is the source vector:
a <- c("A", "A", "B", "C", "D", "E", "E", "E")
and the resulting indexing vector should look like this:
x <- c(1, 2, 1, 1, 1, 1, 2, 3)
I tried this, but this does not produce the correct result:
a <- c("A", "A", "B", "C", "D", "E", "E", "E")
rle.a <- rle(a)
m <- max(rle.a$lengths)
rep(1:m, each=rle.a$lengths)
How to proceed?
|
I found the solution:
a <- c("A", "A", "B", "C", "D", "E", "E", "E")
rle.a <- rle(a)
sequence(rle.a$lengths)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "r, seq, rep"
}
|
How to parse specific data from JSON request
I'm getting into coding, and I'm wondering how I'd go about retrieving the data for "tag_id": 4 specifically.
I know that to get the data for status, but how would I go about getting specific data if there are multiple entries?
r = requests.get('url.com', headers = user_agent).json()
event = (r['status'])
print(event)
//////////////////
{
"status": "SUCCESS",
"status_message": "blah blah blah",
"pri_tag": [
{
"tag_id": 1,
"name": "Tag1"
},
{
"tag_id": 2,
"name": "Tag2"
},
{
"tag_id": 3,
"name": "Tag3"
},
{
"tag_id": 4,
"name": "Tag4"
}
]
}
|
The for loop answer is sufficient, but this is a good chance to learn how to use list comprehensions, which are ubiquitous and "pythonic":
desired_tag_name = [tag["name"] for tag in event["pri_tag"] if tag["tag_id"] == 4]
List comprehensions are advantageous for readability (I know it may not seem so the first time you look at one) and because they tend to be much faster.
There is a bounty of documentation and blog posts out there to understand the syntax better, and I don't prefer any particular one over another.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, json, python requests"
}
|
Return the variable value as string in python
Suppose I have two variables:
_first = True
_second = _first
print (getValue(_second))
>>> _first
Is there a way to implement getValue(or anything else) in that way ? I don't care about the real value (boole\int\string etc..) , just the name of the assigned variable.
Thanks
|
Variables don't refer to each other. When you use `_second = _first`, you aren't making _second refer to _first, you're making it refer to the value that _first refers to. This might clear some things up: Facts and Myths about Names and Values in Python.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, file, variables"
}
|
how to use maven with osgi in eclipse?
I'm new with maven and OSGi and **i want to use OSGi with maven**. At the beginning i search but i haven't find some article that fit my needs. SO i decided to ask here.
**I have understand that i have to use maven-bundle-plugin but i don't know how to use it on eclipse**. Please if you know how to integrate it on eclipse explain me it.
I have already downloaded the m2e integration from Eclipse's marketplace and i have installed it.
<
I have also followed the steps of this tutorial but in my case doesn't appear the maven option on the context menu.
|
If you want to develop OSGi bundles or run OSGi container and get the bundles as maven dependencies, you might find this unfinished tutorial useful: <
Please note that such tutorials get out-of-date easily as the tools are rapidly improved for OSGi. E.g.: The tutorial I mentioned will be reviewed soon if bnd-maven-plugin can be used instead of maven-bundle-plugin.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "eclipse, maven, osgi"
}
|
Ошибка argument label '(String:)' do not match any available overloads
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "idTable") as! TableViewCell
let URL = NSURL(String: arrayOfURL[indexPath.row])
//let URL = NSURL(string: "
cell.videoView.loadRequest(NSURLRequest(url: URL! as URL) as URLRequest)
cell.titleLabel.text = "asdas"
return cell
}
|
исправь строку
let URL = NSURL(String: arrayOfURL[indexPath.row])
на:
let URL = NSURL(string: arrayOfURL[indexPath.row])
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, swift3"
}
|
Render to response to a redirected url in Django
In a form submission scenario, form is post to "/submit". I want to redirect user to "/sucess" on success and pass render some message to a template at new url. How to do this in Django? render_to_response doesn't do redirect and HttpResponseRedirect doesn't do template rendering.
|
If your success page needs a dynamic message, you need to pass it there somehow. You can either do this via GET parameters in the URL you are redirecting to - eg `return HttpResponseRedirect('/success/?msg=My+success+message+here')` \- or by setting some values in the session, which the success view can pick up.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "django, redirect, httpresponse"
}
|
where does pkg-info takes its information from?
Where does pkg-info takes its information from? More precisely, where & what information do I need to put in my .deb package for pkg-info?
|
I don't use a distro that uses pkginfo, but as far as i know there is a pkginfo file that is part of the package. The file will contain all info about the packages, including installation info.
try
man 4 pkginfo
in the terminal :D
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 1,
"tags": "linux, debian, dpkg"
}
|
how to make a long url spread into two lines
I have a very narrow column and a three-word URL that is pushing wider that the column's original width.
can i force the three words to spread over two or three lines and keep the URL link intact?
I am using css to style a custom drupal theme and the length/name of this url is a Drupal node name turned into a tab via the QuickTabs module, so I need to manage it via css, preferrably. I have the feeling this is a very easy fix, but I have searched thru Google and I cannot find anything that works for me.
Thanx in advance.
|
Try using:
word-wrap: break-word;
I don't think its supported in all browsers though.
See < for an example
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "css, url, drupal 6, hyperlink, line breaks"
}
|
How do i get a third party library to build automatically using gradle build scripts?
i want to build jansson c library automatically. How do i tell gradle to do that automatically.
Usually manual commands are necessary to compile and install third party native libraries. Is it possible to compile and install it automatically ?
|
jansson has CMakeLists.txt; configure your app/build.gradle to build your native code.
android {
...
defaultConfig {...}
buildTypes {...}
// Encapsulates your external native build configurations.
externalNativeBuild {
// Encapsulates your CMake build configurations.
cmake {
// Provides a relative path to your CMake build script.
path "CMakeLists.txt"
}
}
}
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, gradle, android gradle plugin, build.gradle"
}
|
understanding the concept of changing an image source
I have a problem in understanding the concept of changing an image source. I have a function that create an image on stage .I want the image to be changed when the user clicks on it. can any one give me an example? Thanks for Help
|
Here's how to change the image when an node is clicked:
* Listen for click events on the node.
* In the click handler, change the node's image property to a new image object.
* redraw the layer
Example code:
myNode.on('click',function(){
this.image( newImageObject );
layer.draw();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "javascript, html5 canvas, kineticjs"
}
|
Is there any specific license should be used for Google Drive SDK?
Is it compatible with Apache License Version 2.0?
Though it have samples used Apache license, couldn't find any documentation of sdk which officially mentioned about the license.
Thanks.
|
The Java SDK code is hosted at <
It is stated there as Apache 2.0
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "licensing, google drive api"
}
|
Auto generate multiple rows from one query php mysql
I am new here and I have coders block, please assist, I am trying to get multiple results from one query and create new rows of values from it.e.g I want row 1 to generate row 2 and 3 where row 1 is a general transaction, row 2 is interest made from row 1 which is 1% and commission made in row 3 at 0.5%, is it possible to generate a query that will output the following results?
Date | End Date | Shop | Trans | Amount | Ref No
-----------|-------------|--------|----------|----------|---------
16/9/2016 | 16/10/2016 | FGB | Payed | 10 000 | 251
15/10/2016 | xxxxxxxxx | xxx | xxxx | 100 | 251
15/10/2016 | xxxxxxxxx | xxx | xxxx | 50 | 251
These results should be in one table is it this possible? Thanks In Advance.
|
In mysql you cannot make new row out like that. **But** you can create columns.
In that case you can run example like
select
*,
Amount * 0.01 as interest,
Amount * 0.005 as commission
from your_mega_table;
And if you modify your code you can get 3 versions of row with different amounts.
Otherwise you need to do some kind of cron script or trigger or stored procedure in database, that will solve your case.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "php, mysql"
}
|
Common python rpc and cli interface
I have a cli app which uses argparse and would like to add an rpc interface with pyjsonrpc.
It seems I will have to duplicate a lot of code and maintain two interfaces which I would rather not do.
Is there a way generate one from the other or have an abstract interface that generates both?
|
I couldn't find an adequate solution so I decided to write a small lib that generates the cli and rpc interface from a basic definition class.
Once its refined I will add it to the pypi, currently its available at <
Edit: pypi package 'apigen' is now available <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, command line interface, rpc, argparse"
}
|
how to set password for user at run time in chef
How to set password for user creation in chef , at run time . instead of the encrypting mechanism using openssl and setting it in user resource in chef.
instead of the following method:
openssl passwd -1 "theplaintextpassword"
$1$JJsvHslV$szsCjVEroftprNn4JHtDi.
then setting it in user resource
user "random" do
supports :manage_home => true
comment "Random User"
uid 1234
gid "users"
home "/home/random"
shell "/bin/bash"
password "$1$JJsvHslV$szsCjVEroftprNn4JHtDi."
end
Is there any alternative ..??
|
You could try generating the password ciphertext using Ruby in your cookbook:
require 'digest/sha2'
password = "pass@123"
salt = rand(36**8).to_s(36)
shadow_hash = password.crypt("$6$" + salt)
After running this, `shadow_hash` contains the following string: `$6$vf1ehwzs$VAxaPBAeXjvEMboee.xbJgMOXlCrJ.eJDPkqP.16fGyAqjq1IDkh0OpEXFRo1W04G7tl02YMQz7dKmGKLVaRd/`
You can then use it in the `user` resource:
user "random" do
supports :manage_home => true
comment "Random User"
uid 1234
gid "users"
home "/home/random"
shell "/bin/bash"
password shadow_hash
end
From <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 6,
"tags": "knife, chef infra"
}
|
How to get "ID" value from "name[ID][OTHER]" in attribute of element using jquery?
I have a form which use for adding some information names like `name[ID][other]`
<select id="ADD_ICON" name="ADD_LINK[123][ICON]" class="bs-select form-control change_add_link" data-show-subtext="true" data-width="65px">...
now I want to work with this in jQuery. For that I have to access to the ID of this element. How I can get the `ID` \- in the example above - how I can get `123`?
|
Basically you are asking for this line of code. I would recommend trying to google your question first.
var name=$(select).attr('name');
var matches = name.match(/\[(.*?)\]/);
var number=matches[1];
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery, html, regex, attributes"
}
|
フォルダ選択ダイアログで選択したフォルダの絶対パスを取得したい
test
HTML
<input type="file" id="dirselect" onChange="test(this.files)" webkitdirectory directory />
Javascript
function test(files) {
var i;
var res = document.getElementById("res");
res.innerHTML = "";
for (i=0; i<files.length; i++) {
res.innerHTML += files[i].fileName + "<br />";
}
}
|
`HTMLInputElement.webkitdirectory`ChromeChromeFirefoxEdge`directory`
`<input type="file">`
|
stackexchange-ja_stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "javascript, html5"
}
|
How to build installers for .NET Core app?
I develop my NET Core app+Electron.NET. It is cross-platform app. How to build installers for .NET Core app for Windows? Linux? Mac OS? What tool to use?
|
Since Electron.NET version **5.22.12** , they switched to **electron builder**. An installer will be created automatically here. The settings can be made in the **electron.manifest.json** file. The documentation of the settings can be found at <
The information about the migration can be found on the start page at the bottom: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "asp.net core, installation, electron.net"
}
|
What does “flustrated” mean, and is it a word?
What does the _flustrated_ mean? Is it even a word? I am using Lingea Lexicon and it doesn’t know this word, but the Internet is full of it.
I find myself getting mad at people for using it both in English and in my own language (Czech), because if it actually has a meaning, I am afraid that those who use it doesn't even know it and use it with the meaning of _frustrated_ , which is wrong.
I dug into it a while back, which only deepened my opinion about people who use it; see Urban Dictionary: _flustrated_.
|
Certainly _flustrated_ “is a word”, although it does not appear to be especially well thought of. The OED reports that the verb **_flustrate_** has been used for more than 300 years; it simply means _fluster_.
Here’s one amusing citation:
> * 1876 Mrs. Oliphant _Curate in Charge_ (ed. 5) II. iv. 100 — The head of the college was slightly flustrated, if such a vulgar word can be used of such a sublime person.
>
It is, however, marked _vulgar_ or _jocular_ — as so too is **_flustration_** (originally sometimes spelled _flusteration_ ), which has been around nearly as long and is reported to mean:
> The condition of being flustered; ‘fluster’, agitation.
I would probably avoid using _flustrate_ and its inflected and derived forms in formal contexts unless I were trying to convey a folksy, jocular, or ironic feel, such as in reported speech. But I wouldn’t let it confusticate or bebother me, either.
|
stackexchange-english
|
{
"answer_score": 11,
"question_score": 6,
"tags": "meaning, etymology, slang, colloquialisms, is it a word"
}
|
Create Out-Of-Process COM in C#/.Net?
I need to create an out-of-process COM server (.exe) in C# that will be accessed by multiple other processes on the same box. The component has to be a single process because it will cache the information it provides to its consumers in memory.
Note: the processes that will access my COM Server are mostly Matlab processes, thus the **necessity** for a COM interface.
I have seen threads regarding creating in-process COM components in .Net on stack overflow (Create COM ...) and on the web, but am having a hard time to find a way to create out-of-process components with .Net.
How is this achievable? Any suggested references?
Thanks.
|
One option is serviced components.aspx) \- i.e. host it in COM+ as the shell exe. See also the howto here.aspx).
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 24,
"tags": "c#, com"
}
|
How to make a single key that is both primary and foreign in t-sql
The code is what I tried previously the
create table DroppedPatients
(
PatientKey nchar(15) not null,
primary key (PatientKey),
PatientKey nchar(15) not null references Patient(PatientKey)
)
However, I don't know how to make a single key as shown in the picture?
 not null primary key foreign key references Patient(PatientKey)
)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "sql server, tsql"
}
|
Vuetify VTooltip trigger only on activator click
I wanted to trigger Vuetify tooltip `VTooltip` only when the activator is clicked rather than hovered. I tried to bind it with a variable but still triggered on hover.
methods: {
doCopy(){
// copy logic
this.showCopied = true;
setTimeout(() => {
this.showCopied = false
}, 1000)
}
}
<VTooltip v-model="showCopied">
<template #activator="{ on }">
<VBtn v-on="on" @click="doCopy"> COPY </VBtn>
</template>
</VTooltip>
|
It turns out I have to disable the default event handler of the activator. Simply removing default event object `(on)` binding solves the issue.
<VTooltip v-model="showCopied">
<template #activator={}>
<VBtn @click="doCopy"> COPY </VBtn>
</template>
</VTooltip>
[UPDATED] based on @Kael Watts-Deuchar answer **NB** : the v-model biding is mandatory
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 7,
"tags": "vue.js, vuejs2, vuetify.js"
}
|
Mapping from relational database
For one to one relationships things are easy.
When it comes to one to many or many to many problems appear...
I am not using an ORM tool now for many reasons and i am wondering when i want to get data whether it is better to reassemble one to many relationship using multiple queries or in code..
For example.. Having a class Category and a class Product...
A product table has a collumn for category id (one category many products).
So for my full catalog is it better to execute 2 queries to get the categories and products i want and then populate for each category its products List ? (It is very easy with LINQ) ..
Or i should call query for each category ? Like `select id from products where category_id=5;`
Also i dont know how to name the functions like to set whether i want to fetch the other side of the relationship or not..
|
If you want to retrieve all categories and all their products, you can either select all categories and then select all products in two queries, or you can select in one query and group.
To use just one query, select an inner join for your two tables
SELECT c.*, p.*
FROM Category c INNER JOIN Product p ON c.CategoryId = p.CategoryId
and then construct business objects from the resulting dataset
result.GroupBy(r => r.CategoryId).Select(group =>
new Category(/* new Category using c.* columns */)
{
Products = /* new list of Products from p.* values */
});
But I have to ask - why aren't you using an ORM?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, sql, database, dao"
}
|
Calling an sql file inside another sql file
I have an sql file with certain parameters which I need to make as generic ones.
Below is the code base in C:\sql\main.sql:
`SET @NAME = 'XYZ'`
`source C:/abc.sql`
I need all the occurences of NAME to be replaced by XYZ in abc.sql file.Which basically contains a set of insert statements.I ran the below command :
`mysql -u myusername -p DB < C:\sql\main.sql`
But after executing it throws and error saying:
`ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SOURCE C:/abc' at line 2`
All I need to do is call an sql file C:\abc.sql in C:\sql\main.sql and then execute C:\sql\main.sql . Can anyone help me on this?
|
I just tested this and I think the only problem with your script (`main.sql`) is the statements are not terminated with semicolons.
Try adding a semicolon to the end of the line:
SET @NAME = 'XYZ';
I was able to verify that the user-defined variable `@NAME` is in-scope when the second file (`abc.sql`) executes with the following in the second file:
SELECT @NAME;
# Output:
XYZ
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "mysql, sql"
}
|
No content is added to ask the textarea
I have a textarea:
<script type="text/javascript">
$(document).ready(function(){
$("textarea").append("Hola");
}
</script>
<script src="
<textarea name="txt"></textarea>
what I want is that when you load the page adding the word "Hello" to textarea but not because it does not work ...
|
3 problems :
* you're missing a closing parenthesis (the console should show it)
* you must use val to change the value of an input.
* you use jQuery before you import it
Use
<script src="
<script type="text/javascript">
$(document).ready(function(){
$("textarea").val("Hola");
});
</script>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "jquery, textarea, append"
}
|
Find the derivative of the inverse of this real function $f(x) = 2x + \cos(x)$
I don't know how to attack this problem. The last I've tried is using a differential equation, but I don't know how to solve it.
Let $y$ be $f^{-1}(x)$. Knowing that $x=f(y)= 2y + \cos(y)$ and derivating I obtained the following non-linear first order differential equation: $y' \cdot (2-\sin(y))=1$
I would thank you if you can help me.
Edit: I haven't said, but it is trivial to check that the function is injective, so it has an inverse, because $\forall x \in \mathbb{R}$ $f'(x) \neq0$
|
Given function $$ y= 2 x + \cos x \tag{1} $$ Inverse function $$ x = 2y + \cos y \tag{2}$$ Differentiating with respect to $x$ $$ 1 = 2 y^{'} - \sin y \, y^{'} $$ $$ y^{'} = \dfrac{1}{2-\sin y} $$
Cannot be further put in terms of $x$ as (1) and (2) are transcendental.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "calculus, ordinary differential equations"
}
|
Regex Question - Exclude Certain Characters
If I want to exclude /* in regex how would I write it?
I have tried:
[^/[*]]
([^/][^*])
But to no avail...
|
You must match `not /`, OR `/ followed by not *`:
([^/]|/[^*])+/?
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "java, regex"
}
|
Find the distribution function of $Y=aX+b$
> A random variable $X$ has distribution function $F$. What is the distribution function of $Y=aX+b$ where $a,b$ are real values?
There are three cases to consider, they are $a>0,a<0$ and $a=0$ because we need to change $x=(y-b)/a$. When $a=0$, the distribution function of $Y$ is $1$ if $b\leq y$ and $0$ if $b>y$. When $a>0$, I would have $\mathbb{P}(X\leq (y-b)/a)=F((y-b)/a)$. But I don't know how to calculate the case $a<0$.
|
Let the distribution function of $Y$ be $F'$. Since you have solved the case $a \geq 0$, we focus on the case $a < 0$ below. We have: \begin{align} \Pr(Y \leq y) =&~\Pr(aX + b \leq y) = \Pr(aX \leq y - b) = \Pr(X \geq \frac{y-b}{a}) \\\ =&~1 -F(\frac{y-b}{a}) + \Pr(X = \frac{y-b}{a}) \end{align} because $1 - F(\frac{y - b}{a}) = \Pr(X > \frac{y - b}{a})$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "probability, probability distributions"
}
|
Need to make lists with the values from another list. These lists must contain only a specific type of value
Need to make lists with the values from another list. These lists must contain only a specific type of value i.e. strings, integers lists, tuples, etc. This is the original list.
x = [55.5,'hello','abc',10,'5','x5',0.25,['A',2,1.5],5,2,5.3,'AEIOU',('dog','cat','chicken'),[1,2,3],1001,['a',1],'world','01/10/2015',20080633,'2.5',0.123,(1,2,'A','B'),5,'chicken',2016,3.1416]
I have tried to use this but to no success:
for i in range(len(x)):
if x[i].is_integer() == True:
intlist.append(x[i])
elif x[i].isalpha() == True:
strlist.append(x[i])
|
Those are methods, not functions. The `.is_integer()` method is one I haven't seen on any object, and `.isalpha()` is only on strings. You should be checking the type with a different function, say `isinstance()`:
for item in x:
if isinstance(item, int):
intlist.append(item)
elif isinstance(item, str):
strlist.append(item)
Notice that I also use `for item in x:` instead of using the indexes.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "python, string, list, integer, tuples"
}
|
Conditonally convergent series implies convergence of series of absolute values
If $\sum_{i=0}^\infty a_n$ is a convergent sequence and $c > 1$, prove that $\sum_{i=0}^\infty |a_n|^c$ is also convergent.
**My attempt:**
Initially, I was just working with $a_n \rightarrow 0$, but I needed to incorporate the fact that $a_n$ is a convergent sequence. So, I know, there exists some $N_0$ such that for $n \ge N_0$, we have $|a_n| \lt \epsilon < 1$ and for these $a_n(s)$, $|a_n|^c < |a_n|$
But I can't use the comparison test at this stage because I don't have that $a_n$ is absolutely convergent. How do I find a series that is convergent and bigger than $|a_n|^c$?
|
This is not true if $a_n$ is not non-negative.
Take for instance $c=2$ and $a_n=\frac{(-1)^n}{\sqrt{n}}$
If $a_n$ is non-negative then you can use comparison test,thus your proof will be correct.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "real analysis, calculus, sequences and series"
}
|
Continuity of a Function with complex analysis
**Problem:**
Let $f$ be defined $$f(z)=\frac{{{\rm Re}(z^{2})}^2}{\left \| z^2 \right \|}$$ if $z\neq 0$ and $f(0)=0$. Prove that $f$ is continuous at $0$.
Does any one have any idea on how to solve it?
|
Recall that $|\Re z|\leqslant |z|$ so...?
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "complex analysis"
}
|
How to remove 'Cycle Tracking' from my Apple watch?
I find this app 'Cycle Tracking' on my apple watch:
.
2. **Lightly** tap and hold on any app to start the familiar 'wiggle' mode. If you press too firmly you'll trigger the List/Grid view.
3. Icons with an 'X' on the top can be deleted. After tapping the 'X' you'll be asked to verify you want to delete the app. Select 'Delete'.
4. Release the pressure and tap on this button to delete the app.
 button.
Apps like Mail, Maps, Music, and Photos are still permanently installed and you can't delete them.
|
stackexchange-apple
|
{
"answer_score": 4,
"question_score": 1,
"tags": "apple watch"
}
|
Determine angles of triangle given nothing (no scientific calculator) but triangle sides.
The question says it all.
Given a triangle, find its angles without a calculator. Is this even possible without tables or making tables?
Summary:
Is it possible to determine the inverse sin, cos of a triangle with an equation not involving calculators and tables?
|
Use the Law of Cosines. If $C$ is the measure of the angle opposite the side of length $c$, and $a,b$ the other two side lengths, then $$c^2=a^2+b^2-2ab\cos C,$$ so $$\cos C=\frac{a^2+b^2-c^2}{2ab},$$ and so since $C$ is an angle of a triangle, then $$C=\cos^{-1}\left(\frac{a^2+b^2-c^2}{2ab}\right).$$
Similarly, if $A$ and $B$ are the respective measures of the angles opposite the sides of length $a$ and $b$, then $$A=\cos^{-1}\left(\frac{b^2+c^2-a^2}{2bc}\right)$$ and $$B=\cos^{-1}\left(\frac{a^2+c^2-b^2}{2ac}\right).$$
If you want a numerical value, you're probably out of luck, but the above work _does_ give us exact and correct values for $A,B,C$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "trigonometry, triangles"
}
|
How to disable a shell without disabling minimize, maximize and close button in SWT
I'm trying to disable a shell in SWT using
sell.setEnabled(false);
this is working fine, I want to prevent user from doing actions, but in the same time I want to allow him to minimize the shell. The problem is that `setEnabled(false)` will disable the entire shell.
Have you please an idea about that?
|
I guess you want to disable the content of the shell. Then why don't you just add a container (Composite) as the main content in the shell and disable/enable it as desired?. That won't affect the shell and, therefore, the minimize button will keep working.
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Composite composite = new Composite(shell, SWT.NONE);
composite.setEnabled(false);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, eclipse, swt"
}
|
Handling JWT token in multiple services
I'm working on a system where it access few rest APIs and we use JWT toke based authentication. Is it possible to use same token across all services ? If yes, how
|
Token can be used (by "used", I mean consumed) across different services as long as they use the same token provider to validate the token.
In fact, token is supposed to be short-lived for security purpose. So in real, you will just use one-time token to establish the user session. And based on the user session, you will do different service handling accordingly.
Let me know if this makes sense.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "rest, jwt, webapi2"
}
|
Cast List<object> to List<myclass> c#
By this code I got list of selected rows in AspxGrid.
string[] fieldName = new string[] { "UserId", "Name", "Address" };
List<object> SelectedList = Grid.GetSelectedFieldValues(fieldName);
Now I want to perform one of the below operation.
1. Filter this List of object by userid where userid = 1 using linq
2. Cast this `List<object>` into `List<Users>`
I have tried following two methods but Exception occurs.
> Unable to cast object of type 'System.Object[]' to type 'CubeDataObject.Claims'.
List<Users> mylist = (List<Users>)(Object)SelectedList;
List<Users> listd = SelectedList.Select(n => (Users)n).ToList();
I have also tried so many other methods too but tired.
|
It seems that you have list of boxed `object[]`. So, you need to unbox it and get the values of `UserId`, `Name`, `Address` by its corresponding index.
Here is example:
List<Users> mylist = SelectedList
.Where(item => (int)((object[])item)[0] == 1)
.Select(item =>
{
var values = (object[])item;
return new Users()
{
UserId = (int)values[0],
Name = (string)values[1],
Address = (string)values[2]
};
})
.ToList();
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 5,
"tags": "c#, linq, devexpress"
}
|
How to pass the StringBuilder parameter in C# to ctypes in python, which is not the normal ctypes supported datatype
I am working on the project, which there is c# project use the dll like that:
public string GetMachineKey()
{
StringBuilder buff = new StringBuilder();
buff.Length = 128;
ZwCommDll.GetCPUMachineKey(buff, 128);
string mk = buff.ToString();
return mk;
}
and I want do it similily in python use the ctypes.
But i am so comfused by the StringBuilder DataType.
Thanks very much your help.
|
Use `ctypes.create_unicode_buffer()` to generate a writable text string buffer (wchar_t*) for an API. Use `ctypes.create_string_buffer()` for a writable byte string buffer (char*). Something like the following should work if the function takes a `char*`:
>>> import ctypes
>>> buff = ctypes.create_string_buffer(128)
>>> ZwCommDll.GetCPUMachineKey(buff,128)
>>> buff.value
b'<returned string>'
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, python, ctypes, stringbuilder"
}
|
How to Create a DialogBox to prompt the user for Yes/No option in WPF
I know how to do this on Windows Form App, but I couldn't find anyway of doing so on a WPF App. How would I present the user a blocking DialogBox with Yes/No option and get/process the response from the user?
|
Here's an example:
string sMessageBoxText = "Do you want to continue?";
string sCaption = "My Test Application";
MessageBoxButton btnMessageBox = MessageBoxButton.YesNoCancel;
MessageBoxImage icnMessageBox = MessageBoxImage.Warning;
MessageBoxResult rsltMessageBox = MessageBox.Show(sMessageBoxText, sCaption, btnMessageBox, icnMessageBox);
switch (rsltMessageBox)
{
case MessageBoxResult.Yes:
/* ... */
break;
case MessageBoxResult.No:
/* ... */
break;
case MessageBoxResult.Cancel:
/* ... */
break;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 36,
"question_score": 16,
"tags": "wpf, dialog"
}
|
Can a role be granted roles+privileges in oracle all at the same time?
I know that you can grant a role:
* Other roles
* System privileges
* Object privileges
But, can you grant to the same role all at once? I mean, for example you grant a role:
* 2 roles
* 1 system privilege
* 1 object privilege
Is this possible?
If so, what is the priority of the grants? Are roles the top priority, or the privileges?
|
Yes, you can grant as many roles or privileges to a role as you want. The order or priority does not matter because a role or privilege always permit something. Unlike for example Windows file permissions you don't have "allow write" and "forbid write" - where the priority/precedence matters.
Either the role gets a privilege or he does not.
However, you can create ROLES as use the ROLE as marker in PL/SQL at `DBMS_SESSION.IS_ROLE_ENABLED(...)`, there is would be possible to "restrict by granting" and the order and priority could matter. But such design would be quite ugly and is not recommended.
|
stackexchange-dba
|
{
"answer_score": 1,
"question_score": 0,
"tags": "oracle, permissions, oracle 12c, role"
}
|
using an op amp in a battery powered circuit
I'd like to use a simple non-inverting amp circuit in a small project I am working on. The project is battery powered, so naturally the only voltage I have access to is 3.3v. My question is: how should I get the voltage for the -ve rail? Of course I can add a DC-DC converter but I'm sure this is already a solved problem so I figured I'd ask first.
Thanks!
|
It's common in modern battery-powered audio electronics not to reference audio to 'true' ground, with +/- supply rails. Instead, you make an audio reference half way between ground and your voltage rail (often with a pair of resistors and a buffer of some kind). Then you arrange your audio signal to swing either side of this mid-rail reference - one tends to end up with quite a lot of series coupling capacitors to let you shift the DC point of the signal around.
Alternatively, if you don't like that (and there are reasons not to - getting the reference quiet enough and stiff enough can be a pain, as can the series caps, and at 3v3 you're fairly short of headroom once you've cut it in half), then a -ve rail can be produced using a charge-pump device like a MAX660 (there are lots of other sources for basically the same part) - that's a lot simpler than a full-up DC-DC converter.
|
stackexchange-electronics
|
{
"answer_score": 11,
"question_score": 9,
"tags": "batteries, operational amplifier"
}
|
OutputKeys.INDENT doesn't affect nodes, copied from another document
I read XML file into org.w3c.dom.Document, find a node by getElementsByTagName, append child from other document this way:
foundNode.appendChild(document.adoptNode(othersDocumentNode.cloneNode(true)));
After that I save result to a StringWriter:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{ "20");
transformer.transform(
new DOMSource(document),
new StreamResult(out)
);
As a result I get document like this:
<document>
<foundNode>
<nestedContent>
<content/>
</nestedContent>
</foundonde>
</document>
I.e. formatting doesn't affect nested content. I'd like all document to be formatted. How can I achieve this?
Thanx
|
The effect of output indentation is specified to be implementation defined. If you don't like the way one processor handles it, you can always try another (which in this case means, try Saxon).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "java, xml, dom"
}
|
Javascript: run object method on DOM object selected through other property
I am very new to javascript.
Here I am failing to run an object method on a DOM element that I selected through another property of the same object. I suspect there is something wrong with my thinking!
Thanks in advance for any piece of help.
var Arrow = function() {
this.current = $('.arrow');
this.previous = null;
this.bend = function() {
// do bend
};
};
var arrow = new Arrow();
arrow.current.bend();
|
bend() is a method of Arrow, not current. Use arrow.bend() and it will also have access to current using this.current.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, jquery, methods, properties, prototype"
}
|
Как добавить элемент в кортеж на 0 индекс в python
У меня есть кортеж:
pp = 'category', 'key:2', 'title:hr'
И необходимо добавить элемент в кортеж на 0 индекс, чтобы остальные просто сдвинулись дальше. К примеру у меня есть переменная `symbol = '$'`
После вывода кортежа я должен получить:
'$', 'category', 'key:2', 'title:hr'
|
Кортеж является _неизменяемым_ объектом, поэтому Вы _не можете_ добавить в него новый элемент.
Но Вы можете создать новый кортеж на основе имеющегося. Для удобства можно преобразовать его в список, воспользоваться методом `insert` и преобразовать обратно.
_**Пример:**_
pp = 'category', 'key:2', 'title:hr'
symbol = '$'
pp = list(pp)
pp.insert(0, symbol)
pp = tuple(pp)
print(pp)
_**stdout:**_
('$', 'category', 'key:2', 'title:hr')
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "python, python 3.x, строки, tuple"
}
|
регулярное выражение (re) для строки на русском языке: найти три буквенно-цифровых символа с последующей точкой
Python 2.7.6 проблема с применением re к строке на русском.
1. задача - найти три буквенно-цифровых символа с последующей точкой;
2. код:
#!/usr/bin/python
# -*- coding: utf-8 *-*
import re
new = re.findall("\w{3}\.", "gth. Ср. дек. 7 21:22:29 EET 2016" )
print new
3. результат >> `['gth.']`
4. вопрос: почему игнорируется `'дек.'`?
|
Используйте Unicode-строки и флаг re.UNICODE:
#!/usr/bin/env python2
# -*- coding: utf-8 *-*
import re
pattern = re.compile(ur"\w{3}\.", re.UNICODE)
match = pattern.findall(u"gth. Ср. дек. 7 21:22:29 EET 2016")
print(match)
for i in match:
print(i)
Результат:
[u'gth.', u'\u0434\u0435\u043a.']
gth.
дек.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 8,
"question_score": 4,
"tags": "python, регулярные выражения, кодировка, unicode, python 2.7"
}
|
Zend And YouTube Not Deleting Videos
Until yesterday I could delete YouTube videos using Zend framework. Now it seems it is not possible.
I was using this code:
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username, $password, 'youtube',
null, 'MySite', null, null,
'
$yt = new Zend_Gdata_YouTube($httpClient, '', '', $myDevKey);
$vid = $yt->getVideoEntry($myVidID, null, true);
$yt->delete($vid);
Now I am getting this error:
> Expected response code 200, got 410 No longer available
It is the `$yt->delete($vid);` that causes the problem. Perhaps YouTube has changed, but that used to be working. I tried two other dev keys and youtube accounts and still nothing.
The video is in YouTube and the ID is correct.
|
Zend_Gdata uses ClientLogin which was deprecated as of April 20, 2012 and turned off on May 26 2015. This code will not longer work you need to switch to using Oauth2.
You can use the current Google PHP client library to authenticate then use the access token created there to access it.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "zend framework, youtube api, google client login"
}
|
TFS integration - how to set environment variables accessible from test code
I'm writing a TFS / VSTS integration with our server by using extension.
I want to present extra data after the build, specifically I want to show an IFRAME and navigate to our server, to a specific URL, determined in part by a dynamically generated unique string.
I have the function that generates the string, but I need to set it as an environment variable before the tests start to run. This is important because the tests need to create that string on the server.
I searched the documentation, examples and other places, but couldn't find a complete example that sets a dynamically generated environment variable and then runs tests.
How do I do it?
|
You can add/set an environment variable through Logging Commands (e.g. PS: `Write-Host "##vso[task.setvariable variable=testvar;]testvalue"`), then the following tasks can get this variable as general variable.
With Logging Commands, you also can add additional information in build summary. (`##vso[task.uploadsummary]local file path`)
You also can deploy a build result extension to display additional information. vsts-extension-samples
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "tfs, azure devops, azure pipelines build task"
}
|
newline replacement in string using regex
I'am using the following regex to remove newlines from a string:
$description =~ s/\r//;
$description =~ s/\n//;
but afterwards I am getting true for:
$description =~ m/\n/
It seems regex did not replace all newlines from the string, any help with this?
|
Your substitutions are not global substitutions - they replace only the first instance of the pattern in the string. To make a global substitution, add a g after the final slash, like so:
$description =~ s/\r//g;
$description =~ s/\n//g;
You can also combine the two substitutions into a single substitution using a character set:
$description =~ s/[\n\r]//g;
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "regex, perl, newline"
}
|
How to determine if a Carry Look Ahead Adder Overflows
I am implementing a 32 bit CLA Adder like how a 16 bit adder is implemented in Wikipedia
 and XOR with carry out of bit 32(Check difference in MSB)?
**UPDATE**
Is my overflow logic correct

|
I thought about seeing what my brain could regurgitate of long ago explnatins, as opposed to commin sense observations, BUT here's a page which does it all very well indeed.
They explain a "nice" 'trick'.
* Two's compelment overflow detection can be achieved by XORing the carry-in and the carry-out bo=its of the leftmost full adder.
Their diagram. See above ref for detailed comment:
!enter image description here
|
stackexchange-electronics
|
{
"answer_score": 1,
"question_score": 5,
"tags": "digital logic, adder, carry look ahead"
}
|
Close running app when my laptop goes to sleep in Windows 7 (close the lid or sleep button is pressed)
I have a program (program.exe) which I want to be closed when my laptop goes to sleep either if the sleep button was pressed, the lid was closed or some time has passed and entered automatically in sleep mode.
I suspect is something from the Task Scheduler but I don't know how to find event "When laptop goes to sleep" and then to close program.exe
I know that maybe I can do a Python script but I feel Task Scheduler it's the easiest way and maybe someone else, like me, needs to fix the same challenge.
Thanks!
|
After some digging, I found the solution I will post it here maybe it helps someone at some moment.
1. Open Task Scheduler
2. Create Task
3. Give it a name (Close_program_on_sleep)
4. Check Run whether user is logged on or not
5. Select Configure for Windows 7
6. Go on Triggers tab and then select New
7. Select from Begin the task: On an event
8. Select Log = System Source = Kernel-Power Event ID = 42. Click ok
9. On Actions tab click new and then New> Start a program
10. On the Program/Script add taskkill /f /im "your_program_to_be_closed.exe"
11. Ok
12. Enjoy :)!
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "windows 7, task, scheduler, sleep"
}
|
Load Chrome extension before loading all elements of the page
I would like to load my Chrome extension before all the elements of the page load (instead of after). Is this possible? Thanks!
|
If by extension you mean content script then the most you can do is set `"run_at": "document_start"` property in manifest which means
> "[content script] files are injected after any files from css, but before any other DOM is constructed or any other script is run."
(read more).
You won't be able to communicate with your background page before the page starts loading though as there is no synchronous message passing.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "javascript, google chrome, google chrome extension"
}
|
How to parse a string to a React component?
Say I have a string `const s = "I love $FB"`, and I wanna get:
`<p>I love <a href="/symbol/FB">$FB</a></p>` by `<RenderContent content={s}>`
I can use reg to extract the symbol, but how can I turn the string into a React component, without using `dangerouslySetInnerHTML`?
|
An alternative render function for a component to use regex capturing groups, no validation is done on the .exec result however:
render() {
const subs = /(^.*)(\$(.*))/.exec(this.props.content);
return (
<p>
{ subs[1] }
<a href={`/symbol/${subs[3]}`}>{subs[2]}</a>
</p>
);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "reactjs"
}
|
Python string manipulation { _teststr[2:12:-1]) }
I just started learning Python, and I was just getting into strings. So I have 3 commands here
_teststr = "IneedToFocusOnMyFuture"
print('1.',_teststr[::-1])
print('2.',_teststr[2:12:2])
print('3.',_teststr[2:12:-1])
Output:
1. erutuFyMnOsucoFoTdeenI
2. edoou
3.
Why the 3rd output is blank instead of having `'uoode'`? What is going under the hood? Could anyone please explain?
|
if you want to reverse the specific string.
print('3.',_teststr[2:12][::-1])
Lets understand the syntax
str[start:end:step]
start denotes from where to splice and end denotes where to end the splice. The step parameter denotes the number of elements to leave after a successful splicing.By default step is 1.
## Example:
str="naveen"
str[1:3] //av
#with including step
str[1:3:1] //av
str[1:4:2] //ae
step defines the number of elements to leave after a consideration.So it cant be negative.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "python, string"
}
|
Why is name mangling not standardized
I'm just wondering why name mangling was never standardized by the C++ standard. Clearly having different name mangling algorithms hurts interoperability[1] and I don't see any advantage of having it implementation-defined.
That is, contrary to say calling conventions or size of primitives the machine itself doesn't care or even know how the function is called. So why wasn't it standardized and why is it still not standardized? Compilers have changed the rules in the past anyhow between versions.
[1] all those people exporting functions as `extern "C"` speak volumes.
|
The standard does not address implementation details. There are many, many things which depend on the implementation, and which prevent programs from working together: how the classes are laid out, the structure of the `vtable`, etc. In general, compilers will change the name mangling if they change any of these. This is intentional, as it prevents code which would not work from linking.
It is possible for a given platform to define a C++ ABI; all compilers which adhere to it would use compatible implementations, and have a common name mangling. This is an issue for the platform vendors, however; for whatever reasons, very few vendors have defined a C++ ABI.
And the reason `extern "C"` works is because almost all platforms define a C ABI.
|
stackexchange-stackoverflow
|
{
"answer_score": 27,
"question_score": 36,
"tags": "c++, name mangling"
}
|
Git https push with user/password not working in STS4
When I try to push it asks for a username and password. Even when the credentials are correct, I am not able to push.
I have not installed the CLI to config.
I have not enabled 2-factor for git.
I have tried increasing the timeout.
 \rightarrow \Omega Map_C(X,Y) $$
I am confused. How is this deduced?
|
The object $\Sigma X$ is defined as the pushout (in the $\infty$-categorical sense) of $0\leftarrow X\to 0$. By definition, this means that $Map_C(\Sigma X,Y)$ is the pullback of spaces (in the $\infty$-categorical sense) $Map_C(0,Y)\times_{Map_C(X,Y)}Map_C(0,Y)\equiv 0\times_{Map_C(X,Y)}0$, where $0$ is denoting the zero object both in $C$ and in pointed spaces. The latter pullback is $\Omega Map_C(X,Y)$, by definition.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "algebraic topology, homotopy theory, simplicial stuff, higher category theory"
}
|
mysql count(*) from multiple tables
I have a MYSQL database that contains data on my companies customers as they use our services each day.
each table in the database represents one 24 hour period and all customer transactions that took place in that period.
I would like to count the total transactions over a number of days
so far I have a select statement that does the following
select
(
select count(customer) from 2010Dec28
where customer='<customer name>'
) as t1,
(
select count(customer) from 2010Dec29
where customer='<customer name>'
)as t2;`
but this returns the result as two separate counts
| t1 | t2 |
| 1438 | 16282 |
1 row n set (0.00 sec)`
My question is how can I generate the sum of these two results without having to do so in my application code.
|
Tyler is probably right, design is surely wrong!
But it is possible..
select
sum(a.count)
from
(select count(*) as count from table1
union all
select count(*) as count from table2) a
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 7,
"tags": "mysql, select, count"
}
|
Express - get user's ip family
Is there some property on `req` object to get ip's family (IPv4 or IPv6)? Or how can I figure it out? I want to change behavior based on this info. I'm not sure if checking if the string contains a colon is the right way.
|
You can use the built-in net package for this:
* `net.isIPv4(input)`
* `net.isIPv6(input)`
You also have `net.isIP(input)` which will return `6`, `4` or `0` if the parameter is respectively an IPv6, an IPv4, or not an IP.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, node.js, express"
}
|
How to make an RDD from the first n items of another RDD in Spark?
Given an RDD in pyspark, I would like to make a new RDD which only contains (a copy of) its first n items, something like:
`n=100 rdd2 = rdd1.limit(n)`
except RDD does not have a method `limit()`, like DataFrame does.
Note that I do not want to collect the result, the result must still be an RDD, therefore I cannot use `RDD.take()`.
I am using pyspark 2.44.
|
You can convert the RDD to a DF limit and convert it back
rdd1.toDF().limit(n).rdd
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "pyspark"
}
|
Ruby on Rails - What does this symbol mean: <%- ... -%> in erb?
Just generated devise views and found in the generated `erb.html`:
<%- if controller_name != 'sessions' %>
<%= link_to "Sign in", new_session_path(resource_name) %><br />
<% end -%>
What does `<%- %> .. <% -%>`, I know it is a monkey's question, but I don't know which keyword to search..so I came to the help of the invincible Stackoverflow..
|
Eats the whitespace so the rendered HTML looks nicer.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "ruby on rails, ruby"
}
|
Log with % resources used on python script
What is it the best way to create a log that resume the percentage of resources (ram, cpu ...) used in each execution of python script.
|
I think the `resource` library and the `getrusage` function is the solution you're looking for, but it will only inform you of the memory used, not the cpu.
Other option is execute a unix command like perf through a bash script and save the results.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "python, ubuntu"
}
|
How would industry-professionals approach this?
 --- How do I treat consecutive delimiters as one?
For two sample strings in variable temp such as these:
(1) "|RYVG|111|9|"
(2) "|RYVG|111||9|"
I want to do the following:
String splitRating[] = temp.split("\\|",);
But I want the result to be the same, which is:
splitrating[0] = ""
splitrating[1] = "RYVG"
splitrating[2] = "111"
splitrating[3] = "9
This means that I need to treat that double "|" as one delimiter. Is there any way to do this while still using `String.split()`?
|
Add a `+` to match one or more instances of the pipe:
temp.split("\\|+");
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 15,
"tags": "java, string, split, delimiter"
}
|
How to open IntelliJ menu actions search
Blender has a very useful menu invoked by pressing `Spacebar` which allows to find by typing and invoke any function anywhere in any menu of the program.
!The Space-menu
(The Space-menu)
Does IntelliJ have the same feature? Where do I find it?
|
Check out Find Action: `Ctrl` \+ `Shift` \+ `A`
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "intellij idea, ide, keyboard shortcuts"
}
|
Grep: Repeat Line Number for Multiple Matches
Here is a simple example of what I'm trying to do.
echo "1234567" | grep -inoE "12|34|56"
The above command gives the following output:
1:12
34
56
Meaning it found 3 matches on line 1: 12, 34, and 56.
However, I would like the output to show the number on each line:
1:12
1:34
1:56
I'm using grep (BSD grep) 2.5.1-FreeBSD
|
Since you are using `BSD grep` instead of `GNU grep`, this does not work.
I suggest you to pipe the result to a little `awk` that does the remapping:
awk -F: 'NF==2{line=$1} NF==1{$0=line FS $0}1' a
This stores the line number in a `line` variable and prepends it on the output of the "orphan" lines.
If the match itself contains some colons it will need some extra massaging, so let us know if this is the case.
### Test
$ cat a
1:12
34
56
$ awk -F: 'NF==2{line=$1} NF==1{$0=line FS $0}1' a
1:12
1:34
1:56
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "macos, unix, grep"
}
|
How can I import variables to other python file in Python 3.3+?
I have a workspace structure like this:
folder
file1
file2
I want to import the variables of file1 to file 2. I am using python 3.7.6 on Anaconda Environment.
When I write in file 2
import file1
I get
Error: ModuleNotFoundError: No module named 'file1'
I have tried to save an empty file called `__init__.ipynb` in the directory but it does not work.
I have tried:
from file1 import #variables
but I get this. Error
Thanks in advance.
|
This should do the trick:
from file1 import YourClass # or your functions, etc.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python"
}
|
What is the purpose of the watermelon in the ritual at the beach?
In the _Zero no Tsukaima: Princesses no Rondo_ beach vacation OVA, the girls are told to perform an offering ritual to the Spirit of Water, using a watermelon.
](
The "ritual" later turns out to be some sort of game set up by Saito and the other boys. However, why did they choose a watermelon for it? Does it symbolize something specific?
|
This is just a game of watermelon splitting (). In anime and manga, it is common activity portrayed in the beach chapters. Generally, the game is also played at the beach in real life, but it may also be played in nursery/kindergarten/playground or at event venue.
The rules of the game is quite similar to piñata: the watermelon is laid out, and the participants will try to smash it open while blindfolded.
The 2 paragraph above are summarized from Wikipedia page, both English and Japanese version.
There is no significant symbolization here. It is just a game in Japan introduced by Saito to the denizen of Halkeginia. By using the reason "for the sake of the Spirits of Water", the principal (+ Saito) fools the girls to change into bikini from one-piece swimsuit. And since the game is played blindfolded, the boys can ogle at the girls body all they want without triggering the girls self-consciousness.
|
stackexchange-anime
|
{
"answer_score": 7,
"question_score": 5,
"tags": "tropes, the familiar of zero"
}
|
What's different between a single precision and double precision floating values?
What's the difference between a single precision and double precision floating values?
|
In C, `double` has at least as much precision as, and usually more than, `float`, and has at least the exponent range of, and usually more than, `float`.
The C standard only requires that `double` be able to represent all the values of `float`: “The set of values of the type `float` is a subset of the set of values of the type `double`…” (C 3028 6.2.5 10).
In typical common implementations today, `float` is represented with 32 bits in the IEEE-754 _binary32_ format, and `double` is represented with 64 bits in the _binary64_ format.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -8,
"tags": "java, c, types, floating point, programming languages"
}
|
Create a shell with a different PATH
I want to write a script that will create a new shell that has a different path variable _upon instantiation_. That is, I do not want to have to run a configuration script each time I start the new script. I just want the initialization of the shell to have a new PATH). How can I do this?
In terms of specifics, I will be running several tests that require using a modified version of a default package. I want to run these tests from within a new shell, to avoid changing the default `PATH` variable.
Thanks!
|
If you're running on Linux/Mac, you can use it like this:
path='something_new' run_command
where run_command is your test script. Run :
path='something_new' set | grep path
for Mac or :
path='something_new' env | grep path
for Linux
to ensure it works for you.
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 1,
"tags": "bash, shell, environment variables"
}
|
Basic Topology on $\mathbb{R}^{n}$
Given $a \neq b$ at $\mathbb{R}^{n}$ determine $c$ in $[ab]$ such that $c \bot (b-a)$. Conclude that for all $ x \in [ab]$, $x \neq c$ $|c| < |x|$.
Okay, I could find the form of $c$, if $\langle c,b-a\rangle=0$ and $c = a + t(b-a)$ for $t \in[0,1]$ then $t_{0}=\dfrac{\langle a,b-a\rangle}{|b-a|^{2}}$ but how can i prove that for all $x = a + t(b-a)$ we have $|c| < |x|$.
|
Firstly note that $c$ is the unique, i.e., if $c' \in [ab]$ and $\langle c',b-a\rangle= 0$, then $c'=c$.
Now take $x = a + t(b-a)$. If $x \neq c$, then $\langle a+t(b-a), b-a\rangle\neq0$ (Since $c$ is unique).
Finally compute $\langle x,x\rangle^{2}$ and compare to $\langle c,c\rangle^{2}$.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "general topology, analysis"
}
|
Setting current/compatibility version for a dylib using Netbeans (linux/mac)
As per the title, how can I set those? Moreover, how can I set versions themselves?
Thanks to all and best regards.
|
I believe you can add build options to your project. You'd need to add _linker_ options to set the compatible and current versions according to this page on "Mac OS X for for Unix Geeks": library version. (They use a library called "answer" in their examples, with a supposed current version of 1.2.6)
-dynamiclib -install_name libanswer.1.dylib \
-compatibility_version 1.2 -current_version 1.2.6 \
-o libanswer.1.2.6.dylib $(OBJS)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "c++, linux, macos, version, dylib"
}
|
Return value from thread
How do I get a thread to return a tuple or any value of my choice back to the parent in Python?
|
I suggest you instantiate a Queue.Queue before starting the thread, and pass it as one of the thread's args: before the thread finishes, it `.put`s the result on the queue it received as an argument. The parent can `.get` or `.get_nowait` it at will.
Queues are generally the best way to arrange thread synchronization and communication in Python: they're intrinsically thread-safe, message-passing vehicles -- the best way to organize multitasking in general!-)
|
stackexchange-stackoverflow
|
{
"answer_score": 72,
"question_score": 71,
"tags": "python, multithreading, python multithreading, exit code"
}
|
Allow toast to be accessible from another class
I am trying to use a toast from another class.
In class 1 I have the toast method:
public static void textToast(String textToDisplay)
{
Context context = getApplicationContext();
CharSequence text = textToDisplay;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER, 50, 50);
toast.show();
}
I am trying to call this toast from another class but when I make the method static, it says cannot make a static reference to this method `getApplicationContext().`
I access it by using `class2.textToast("");`
Any advice on this would be appreciated. Thanks
|
If you want to provide a method which should be valid for different contexts (e.g. activities), pass this context as parameter.
public static void textToast(String textToDisplay, Context context) { ... }
If you want to call this method from nested inner classes (as is often the case), you can use `this` as context
public void textToast(String textToDisplay) {
...
Toast toast = Toast.makeText(OuterClass.this, text, duration);
...
}
(or implement `textToast` in the outer class and call it via `OuterClass.this.textToast` from the nested inner class)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "java, android"
}
|
How do I modify the HTTP redirect in JMeter?
Here is the current scenario: I'm trying to run a JMeter script on my dev machine - dev.mysite.com and I'm running into an issue.
In production this works fine:
With a correct user / pass -
www.mysite.com/login.html
www.mysite.com/secure.html
With a bad user / pass -
www.mysite.com/login.html
server side redirect to www.mysite.com/login_failed.html
My problem is that the server side redirect has the hostname **hardcoded** So when I do this on my dev box I get:
With a correct user / pass -
dev.mysite.com/login.html
dev.mysite.com/secure.html
With a bad user / pass -
dev.mysite.com/login.html
server side redirect to **www**.mysite.com/login_failed.html (redirects to www)
I know I need to fix my code, but I'm looking for a work-around in JMeter.
Is this possible in JMeter?
|
There is an option within the HTTP Request sampler to control redirects. There are two options. 1. Redirect Automatically (checkbox) and 2. Follow Redirects (checkbox). Uncheck these two check boxes to disable the redirects. You can then include a separate HTTP sampler to perform the redirects if you want by checking the status of the previous request. I face this situation in my projects and this is the technique I use to control redirects.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "http, jmeter"
}
|
Can internal ip addresses of the worker machines be used to connect the worker to rabbitmq queue?
the two machines the "master rabbitmq queue handler" and the "worker machine are servers of same platform (i.e digitalocean)".
Can their internal ips be used to connect them? If yes will it be any faster than the external ip connection?
|
This is more of a network/sysadmin question question than a programming one but anyway:
As long as one machine can access the other thru it's "internal ip" (I assume you mean a local private ip) and there's nothing blocking connections (firewall etc) on those ips, then yes of course it will work. Just note that because two machines belong to the same hosting company doesn't mean they are connected to the same local network (are they physically in the same datacenter ?).
As wether using the internal ip will or not be faster, it depends on the local network, the ethernet cards etc - it's _usually_ faster when both servers are on the same local network indeed, but it's not garanteed either.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "django, server, rabbitmq, celery"
}
|
Use NSViewController with Custom View
I have a main .xib view with parts of it being made up of custom views. At the same time I have also created separate .xib subviews (together with their respective .h and .m files). These custom classes were then connected to the custom views in the main .xib
This setup works fine however I would like to have a number of NSViewController(s) control each of the different custom views. What is the recommended way to do this?
Eg. Main.xib > contains 'custom views' > each using an NSView custom class and designed in it's own .xib
An NSViewController class would respond to events occurring in one of these custom views instead of the NSViewController tied to Main.xib
|
I've ended up creating NSViewControllers with XIB files instead of the custom views I had previously.
I then created NSBox components for every custom view that I had. I connected each of these to the main NSViewController via IBOutlet(s).
Finally, I attached each custom view to the dedicated NSBoxes via the IBOutlets as follows:
- (void) awakeFromNib{
[super awakeFromNib];
//instantiate custom view controller
CustomViewController* customViewController = [[CustomViewController alloc] initWithNibName:@"CustomViewController"
bundle:nil];
[self.customNSBoxView setContentView:[customViewController view]];
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "macos, cocoa, nsview, nsviewcontroller"
}
|
How to include three different tables data in one query
(columns name)
b_Users = id,users_id,ac_num,bills
r_Users = id,users_id,ac_num,bills
f_users = id,users_id,name,address
f_users table:
id ----users_id---- name ---- address
1 12/1 A ad1
2 13/2 B ad2
3 14/1 C ad3
b_Users table:
id ---- users_id ---- ac_num ---- bills
1 12/1 1234 10$
2 14/1 1235 12$
r_Users table:
id ---- users_id ---- ac_num ---- bills
1 13/2 1238 19$
I want to select (users_id,name,address,ac_num,bills)
I used Join but there's showing empty fields. I don't know why.
|
I'd query a `union all` between `b_users` and `r_users` and then join `users` on it:
SELECT f.users_id, name, address, ac_num, bills
FROM (SELECT b.users_id, ac_num, bills
FROM b_users b
UNION ALL
SELECT r.users_id, ac_num, bills
FROM r_users r) t
JOIN f_users f on f.users_id = t.users_id
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mysql, sql, database, select, join"
}
|
Is Html.Encode Needed on User Credentials For Web Resource?
We have a simple utility which accesses a web resource for users via an HttpWebRequest.
This web resource requires login credentials (username / password). The credentials are utilized for access of the resource and are not stored in a database.
Html.Encode is used to help prevent XSS attacks. However, when these credentials are encoded, they can become broken. For instance, if a password is `john&123`, then using Html.Encode will change the password to `john&123`, effectively breaking the password.
How can we safely utilize user-entered username and password strings while preventing XSS?
Or, is this not so much a problem because is XSS mainly a concern when _displaying_ user input on the client browser? If so, is there anything to be aware of (security-wise) when temporarily utilizing user input to access a web resource?
|
You can use HttpUtility.HtmlDecode() or WebUtility.HtmlDecode() to get the original string back.
But, yes, you only need to worry about XSS if the string is being rendered on a page and only SQL injection if the string is used in a query that hits the database. In your case it sounds like the credentials are entered into a form by the user, used by your backend to access an external web service, and then discarded. If that's the case, XSS/SQL injection are the external web service's problem, not yours.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, c#, asp.net, security, xss"
}
|
How to add required .net to InstallShield12
I created a app with VS2012 with version 4.5.
I want to created a setup file, I use InstallSheild12 for this.
In application File step, i add all file of debug folder.
When i Build Installation, Get error
`ISDEV : warning -6245: One or more of the project's components contain .NET properties that require the .NET Framework. It is recommended that the release include the .NET Framework.`
Which step can i add required file?
|
Assuming you mean InstallShield 12, not InstallShield 2012 (yeah it's a bit of a name clash), your best bet is to create or find a prerequisite that installs .NET Framework version 4.5. Unfortunately since it's not built-in, the build won't know that it's .NET, and the warning won't necessarily go away.
(Actually the same advice goes for InstallShield 2012, but that version might include such a prerequisite already; InstallShield 12 is definitely too old for that.)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": ".net, installation, installshield"
}
|
Derivative of two-dimensional Dirac delta function
I have the following equation involving the derivative of a 2-dimensional Dirac delta function
$$\partial_x[\alpha(x,y)\delta(x^2 f(x,y)+g(x,y)+h(y)^2)]=0,$$
where $\alpha$ is a unknown function coming from solving an homogenous equation, $f$ and $g$ are distributions, and $h$ is a scalar function.
Expanding out would suggest $$\delta(x^2 f(x,y)+g(x,y)+h(y)^2)\,\partial_x \alpha(x,y)+\alpha(x,y)\,\partial_x\delta(x^2 f(x,y)+g(x,y)+h(y)^2)=0.$$
Can I here integrate and use the identity $$\int\delta'(x)\phi(x)dx=-\int\delta(x)\phi'(x)dx,$$
which obviously would satisfy the equation. Or does this not hold in my case of a multivariable delta function?
We can also expand the derivative on the delta function using the chain rule, but I don't know if that helps.
I am trying to find some constraints on $\alpha$, so it would be ideal if it didn't satisfy it in this way and I could instead extract some information about $\alpha$.
|
Without additional regularity on $f$ and $g$ the equality is ill defined in the sense of distributions. See this question for more on this. Let's compute the second term in your second equation. Take a test function $\phi \in \mathcal{C}_c^\infty (\mathbb{R}^2)$ and define $k(x,y) = x^2 f(x,y) + g(x,y) +h(y)^2$. Then, allowing an abuse of notation we can write:
$$ \begin{aligned} \langle \alpha \partial_X (\delta \circ k), \phi \rangle &= \int \partial_X (\delta \circ k) \phi \alpha \; dxdy \\\ & = -\int \delta \circ k \; \partial_x (\phi \alpha) \; dx dy \\\ & = -\int \delta \; [\partial_x (\phi \alpha) \circ k^{-1}] |\text{det } D k^{-1}| \; dx dy \end{aligned} $$ where $\delta \circ k$ denotes the composition of the Dirac delta with the function $k$. Note that we require $k$ and its inverse to be smooth for the last equality to hold. As for $\alpha$, it needs to be smooth as well for the problem to be well-defined. The first term in your second equation can be computed similarly.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": -1,
"tags": "functional analysis, derivatives, partial differential equations, dirac delta"
}
|
WordPress Rest API Escapes Returned URLs Forward Slash
I have created an endpoint via `register_rest_route()` that gets serialized data from the DB. When it is returned, all of the URL strings are escaped. `https:\/\/s.w.org\/plugins\/geopattern-icon\/action-scheduler.svg`. It seems this is because returned values are passed through PHPs `json_encode()` function. How would I return the URLs, so they are not escaped `
|
This is no different to when `&` in raw HTML is displayed as `&`, **it's standard JSON encoding** , and is resolved by _decoding_ the JSON. Any application that is unable to handle this has probably forgotten to parse the JSON response.
For example:
const url = JSON.parse( '"https:\/\/s.w.org\/plugins\/geopattern-icon\/action-scheduler.svg"' );
console.log( url );
Will print the URL as you expected. JSON decode then grab that value from the resulting array/object.
|
stackexchange-wordpress
|
{
"answer_score": 2,
"question_score": 0,
"tags": "rest api, json"
}
|
Google Sheet Check if any values in a column match part of a cell
I'm wanting to create a list of strings to search for in Column A. Example "Cafe", "Restaurant", "Shop X"...
Then if a string in another cell (example: "Robert Harris Cafe") **contains** any of the values in column A, I want it to return true.
Similar to `COUNTIF` but but with a `REGEXMATCH`. Count it if it contains any of those values in column A.
|
To get a true/false result:
=0 < counta(
iferror(
filter(
A2:A,
search(A2:A, B2)
)
)
)
To get a count:
=counta(
iferror(
filter(
A2:A,
search(A2:A, B2)
)
)
)
To list the keywords that match:
=filter(
A2:A,
search(A2:A, B2)
)
|
stackexchange-webapps
|
{
"answer_score": 1,
"question_score": 1,
"tags": "google sheets, regex"
}
|
Changing an ApiGateway restapi stage deployment via the cli or sdk
I have a system in place for creating new deployments but I would like to be able to change a stage to use a previous deployment. You can do this via the aws console but it appears it's not an option for v1 API gateways via the SDK or CLI?
|
Can be done via CLI for V1 APIs. You will have to run two commands -> `get-deployments` and `update-stage`. Get the deployment ID from output of first and use it in the second.
$ aws apigateway get-deployments --rest-api-id $API_ID
$ aws apigateway update-stage --rest-api-id $API_ID --stage $STAGE_NAME --patch-operations op=replace,path=/deploymentId,value=$DEPLOYMENT_ID
get-deployments update-stage
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "aws sdk, aws api gateway, aws cli, aws serverless"
}
|
quick javascript function help
I have this function, and I want to pass a variable (z) to the OnClick event of an image.
I have this:
for (z=1; z<img_src.length; z++){
path_th_img= 'ad_images/'+category+'/'+'thumbs/'+img_src[z];
document.getElementById("thumb_pic_div").innerHTML += "<img src='"+path_th_img+"' class='shadow2' style='margin:7px;' onclick='imageShow(z);'>";
}
img_src.lengt is in this case 4... So no matter which of the three images I click, the nr 4 gets passed on... ideas?
Thanks
|
you have to pass the value of z in your string
for (z=1; z<img_src.length; z++) {
path_th_img= 'ad_images/'+category+'/'+'thumbs/'+img_src[z];
document.getElementById("thumb_pic_div").innerHTML +=
"<img src='"+path_th_img+"' class='shadow2' style='margin:7px;' onclick='imageShow("+z+");'>";
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
}
|
PHP - Modify array value by reference inside object
How can I pass a value of an array by reference to modify its value inside an object? I've tried it with the `&` operator at `public function f(&$z) {`.
<?php
class C {
private $a;
public function f($z) {
foreach ($z as $i => $v) {
$v = 8888;
}
}
}
$p = 4;
$obj = new C();
$obj->f(array('key'=>$p));
echo $p;
?>
I would like to set the **8888** value to the `$p` variable.
The fiddle: <
|
You have to use references when you 1) create the array, 2) iterate over it:
<?php
class C {
private $a;
public function f($z) {
foreach ($z as $i => &$v) {
$v = 8888;
}
}
}
$p = 4;
$obj = new C();
$obj->f(array('key'=>&$p));
echo $p;
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php"
}
|
How to download and install imageJLibrary in netbeans
I'm new to java and image processing. I want to develop a java application with functionalities like thresholding and hitorgrams related operations. I have considered about 2 image processing libraries; JAI and imageJ.
I have found that imajeJ is more suitable, but when i searched for it to download i only found a tool instead of a library. Can someone tell me where i can download imageJ api(/library) and install it, so i can use it in netbeans.
|
Download the latest ImageJ jar from here and add it as an external library for your project. You can then program to the API as described in the API documentation. The servlet example provided here may be of use.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "image processing, imagej, java"
}
|
JFace TreeViewer first column
!enter image description hereI have a jface treeviewer with 2 columns. When I hover my mouse over any element in the first column, I see the mouse pointer turning to that of the one we see when we hover an url or a web page link ( I mean a hand pointer ). and also the color of that particular cell turns white irrespective of what background color it had. And for the other columns I see no such effects. Only in the first column, I see this. How do I disable this 'effect' for first column? Thanks. Please see the below pic. you can see the highlighted thing in the first column.
|
I found that the highlighting is due to default single cell selection by the framework on treeviewer. Set SWT.FULL_SELECTION to have full row selection that solves white background as well.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "eclipse, jface, treeviewer"
}
|
How can i match second-last char of a string with RegEx
Angular app!
I need to hide the 2 second-last char of a string and replace them with "XX".
what i got:
+391234567890
what i need
+39123456XX90
How can i match this with a RegEx? I want to use this pattern in _replace()_ method
|
That would look something like this:
let result = source.replace(/^(.*?).{2}(.{2})$/,'$1XX$2');
Where:
* `()` is a "capture group"
* `^` matches beginning of the string
* `.*?` matches as few characters as necessary to fulfill pattern
* `.{2}` matches two characters
* `$` matches the end of the string
And in the replacement string:
* `$#` replaces the content of a capture group, numbered from 1 to #.
|
stackexchange-salesforce
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, string, regular expressions, angular"
}
|
Offsite Backup for SQL Server .bak files (only 5 GB)
I'm looking into possible ideas for off site backup for my SQL Server database backups. I have a ton of space a dream host. I could create a SFTP account and automatically SFTP new backups to that site. And store them in a folder the the public cannot access.
However I was also looking a Mozy and carbonite. I could configure them to watch my backup source folder and they would automatically backup the files every 2 hours. I called Mozy and they said it would be about $9.95 per month if I had 5gb of data.
What does everyone one recommend? Keeping in mind that I'm a just a start-up and I'm not buying another server for this.
|
Go with the mozy or carbonite backups. If they'll watch the folder and sync it automatically whenever you make a change for $10, you'll be in far better shape than buying $5/month shared hosting then needing to worry about scripts, schedules, etc.
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 0,
"tags": "backup"
}
|
Show that these two Eigenvalues are positive
> > In the course of a rather long calculation, I got two Eigenvalues, namely $$ \lambda_{1,2}=\frac{1}{2}(2+x^2+u\pm\sqrt{u^2-2ux^2+x^4+4x^2}). $$ I have to show, that these two Eigenvalues are positive. (Here x is out of a bounded domain $\Omega\subset\mathbb{R}^2$ and $u\in C^2(\Omega)\cap C^1(\overline{\Omega})$ is a non-negative function.)
Could you please help me to show, tha $\lambda_{1,2}$ are positive? I do not have an idea, how to show that.
|
You need to just show that $2+x^2+u > \sqrt{u^2-2ux^2+x^4+4x^2}$ $$\iff (2+x^2+u)^2 > u^2-2ux^2+x^4+4x^2$$ $$\iff 4+4 u+u^2+4 x^2+2 u x^2+x^4 > u^2 - 2 ux^2 + x^4 + 4 x^2$$ $$\iff 4 + 4 u + 4 u x^2 > 0$$
which is true as $u \ge 0$.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "eigenvalues eigenvectors"
}
|
How to attach custom data to elements?
Is there any way to attach custom data to elements? Kind of like the $.data() function in jQuery? I know you can subclass and element and add custom parameters, but it would be an overkill to create custom class just to add a single custom parameter.
|
If I understand your question....
You can create new properties on any given object at runtime using syntax like this:
myObject['newProperty'] = 'somevalue';
I'm not sure I'd recommend it in most situations.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "apache flex, actionscript, flash builder"
}
|
ошибка missing return statement
Метод должен возвращать true если строка(str) начинается с "hi", иначе возвращает false
public boolean startHi(String str) {
String w = str.substring(0,2); // w = первые 2 символа str
if ( str.length() > 2 ) {
if(str.equals("hi")) {
return true;
}
} else {
return false;
}
}
но выдает следующую ошибку
> missing return statement line:10
|
**Причина проблемы:**
В случае входа в `if ( str.length() > 2 )`), но не попадания во вложенный `if(str.equals("hi"))`, окажется, что отсутствует конструкция `return`, которую следует исполнить потоку.
**Как исправить:**
Существует множество способов, к примеру, извлечь конструкцию `return false`; из блока `else`:
public boolean startHi(String str) {
if (str.length() >= 2) {
String w = str.substring(0, 2); // w = первые 2 символа str
if (w.equals("hi")) {
return true;
}
}
return false;
}
Но логичнее сразу написать следующее:
public boolean startHi(String str) {
return str.substring(0, 2).equals("hi");
}
А еще логичнее воспользоваться методом `startsWith`:
public boolean startHi(String str) {
return str.startsWith("hi");
}
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "java"
}
|
What Stack Exchange site should be used for miscellaneous questions, if there is no site for that topic?
If some question is of some rare topic, and no Stack Exchange site has this topic, is there some special Stack Exchange site meant for such rare "Misc" questions, like `misc.stackexchange.com` or `other.stackexchange.com`?
If in the future new Stack Exchange site/community is created that covers this rare question's topic then somehow popular questions can be moved from Misc to that new site.
I just thought that it would be nice to have some Misc site to at least post your question somewhere for history to have a chance for it to be answered, instead of not having such site and losing your question.
It would also be nice for promoting the Stack Exchange platform and tools for those who prefers them, if such questions goes here instead of Quora/Reddit.
|
Not every conceivable question has a home on the Stack Exchange network. The "everything goes" style is more suited for Quora or Yahoo! Answers or Reddit. There are also other Q&A sites like Codidact, various forums and Discord channels, etc.
In principle, sites can be proposed at Area 51, but there has to be existing demand for the site. However, the large number of existing sites is already overwhelming, and I think it's reasonable to speculate that no sites will be created within the next few years.
The idea of a "miscellaneous" site has been rejected in the past, e.g.:
> Our goal is _not_ to create "general sites" for technology or anything else. Instead we create very _specific_ sites for each community's area of expertise.
> Why isn't there a general stack exchange site?, Robert Cartaino
|
stackexchange-meta
|
{
"answer_score": 13,
"question_score": -17,
"tags": "discussion, feature request, stack exchange"
}
|
Unable to retrive the current guest id using public API url of softlayer
unable to retrieve the id of the current node using public softlayer url.
> curl -X GET -u xxxx:xxxxxx < 12345
where as the same request returns errors with public endpoint.
> curl -X GET -u xxxx:xxxxxx <
>
> {"error":"Access Denied. ","code":"SoftLayer_Exception_Public"}
Could anyone tell the reason for this behavior, is this expected?
|
That is the expected behavior. The SoftLayer_Resource_Metadata is only accessible over the private endpoint. This is also the reason that you can call it without a Username or API key
root@wp:~# curl -X GET
35200757
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ibm cloud infrastructure"
}
|
Disable automatic driver update for only one device in Windows 10
Is there a way we can disable automatic driver update for a specific device in Windows 10? The updated driver for that device (Intel Management Engine Interface 11.x in particular) causes problems on some laptops during. The version 9.x works perfect.
I don't want to disable automatic driver installation for all devices.
|
Microsoft published a tool designed to block device driver updates.
Here is the relevant section of that support article:
.
In case the script failed, I'd like to:
* Start up my network interfaces without any iptables rules
* Start up OpenSSH server
* But not any other services like web server, ... (and maybe stop running instances)
Is there a good canonical way to do that? Going into a lower `init` stage? - I haven't done that in a long time, and I think that a lot about init has changed in recent years (?) - which stage should I drop to, and would the OpenSSH server and my network interfaces still run?
Thanks
Chris
(On Debian Lenny)
|
I've never tried this, but another solution that comes to mind is to bind your external services to an internal IP that's not routable at all, even the loopback would probably work. Then, as the last rules in your saved IP Tables configuration, setup a transparent proxy to the local service.
If IP tables fails to come up, you just don't wire up your services. If it does come up, your services just become available.
The only system you leave out of this configuration is SSH, that way you have that out-of-band management.
Of course, your service logs would all have the wrong source IP. I guess this would cover that corner case, though.
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linux, debian, startup, init"
}
|
How to return a list of files uploaded in shiny
I have a shiny app where i want to return a list of files uploaded. I use
ui.R : fileInput("files", "Choose CSV processed files", multiple = "TRUE",
accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv','.cel'))
and
server.R : list <- list.files(path = "input$files[['datapath]]", pattern =".cel")
or
list <- list.files(input$files[['datapath']])
but it returns `character(0)`. May i know Y .
|
Actually `[['datapath']]` give you the temporary data path to upload the files in shiny. You can try `list <- input$files[['name']]` to get the list of files uploaded in shiny.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "r, shiny"
}
|
Under group action, can we define the stabilizer for a set of points?
Let a group $G$ act on a space $S$. If a point $p$ in the space remains invariant under the action of a subgroup of $G$, we call the subgroup the stabilizer of $p$.
$\text{Stab}(p) = \\{g: g \in G, \, p\in S, \, g.p = p\\}$
Can the notion of stabilizer be extended to a set of points (say $P$) in the space rather than a single point? i.e. can we define a subgroup in the following way?
$\\{g: g \in G, \, P\subset S, \, g.p_i = p_j \, \forall \, p_i, p_j \in P\\}$
If so, what is such a group called?
|
For a subset $S'$ of $S$, define $Stab_1(S') = \bigcap_{p\in S'} Stab(p)$ which is the point-wise stabilizer of $S'$. This is a subgroup of $G$ since the intersection of subgroups is itself a subgroup.
Another set to consider is $Stab_2(S') = \\{g\in G\mid g\cdot S'\subseteq S'\\}$ which stabilizes the subset $S'$. Can you check whether this set is a subgroup of $G$?
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "group theory, group actions"
}
|
How can I get the moving sum of streaming events?
I have a source that emits integer events.
For each new integer, I would like to sum it with all the integers that got streamed in the previous hour and emit that value to the next step.
What is the idiomatic way of calculating and then emitting the sum of the current event's integer combined with integers from all the events in the preceding hour? I can think of two options, but feel I am missing something:
* Use a sliding window of size one hour that slides by one millisecond. This would ensure there is always a window that spans from the latest event back one hour exactly.
* Create my own process function that keeps track of the previous integers that are less than or equal to one hour old. Use this state to do my calculations.
|
You can do that with Flink SQL using an over window. Something like this:
SELECT
SUM(*) OVER last_hour AS rolling_sum
FROM Events
WINDOW last_hour AS (
ORDER BY eventTime
RANGE BETWEEN INTERVAL '1' HOUR PRECEDING AND CURRENT ROW
)
See OVER Aggregation from the Flink SQL docs for more info. You could also use the Table API, see Over Windows.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "apache flink, flink streaming"
}
|
Unpack tuples inside a tuple
For the following:
tup = ((element1, element2),(value1, value2))
I have used:
part1, part2 = tup
tup_to_list = [*part1, *part2]
Is there a cleaner way to do so? Is there "double unpacking"?
|
If you're looking to flatten a general tuple of tuples, you could:
1. use a list/generator comprehension
flattened_tup = tuple(j for i in tup for j in i)
2. use itertools
import itertools
flattened_tup = tuple(itertools.chain.from_iterable(tup))
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "python, tuples, unpack"
}
|
javac is able to find the file but not the java command
Example: If there is a file HelloWorld.java in `c:\xyz\javaprograms\HelloWorld.java`
in the command prompt at the following default directory:
`c:\users\username>javac c:\xyz\javaprograms\HelloWorld.java`
it will compile and create a `c:\xyz\javaprograms\HelloWorld.class`
Now if I try to execute the program: `c:\users\username>java c:\xyz\javaprograms\HelloWorld`
it says it did not find that file name.
if I go to the file path and execute the HelloWorld program (bytecode) then it runs fine
`c:\xyz\javaprograms> java HelloWorld`
Why did the java command not recognize the file with complete file path and why did it recognize the file only after going to the actual directory where the file is located?
|
You need to set the class path with -cp :
Java -cp MainFolderPath mainclass
you can find the full documentation here: <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "java"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.