INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to input 5D tensor to keras model.fit
I am utilizing tensorflow ver 2, tensorflow.keras.
A model I made is in a sequence of `tf.keras.Conv2D` ( which requires 4D input tensor (samples, rows, cols, channels)
then `tf.keras.convLSTM2D` (which requires 5D input tensor (samples, time, rows, cols, channels).
Because of this reason, I made an input with 5D tensor (samples, time, rows, cols, channels) but it can't be fed into tf.keras.Conv2D at the beginning when I implement `model.fit(train_data, train_data... )`
Is there any way to make model.fit to take 5D tensor?
|
You need to implement `TimeDistributed` conv2D as in :
x_conv = tf.keras.layers.TimeDistributed(tf.keras.layers.Conv2D(filters=filters,
kernel_size=kernel_size,
strides=strides,
padding='same',
kernel_initializer='he_normal'))(x)
This way the layers understand that you're giving 4D input over `timestep`
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "tensorflow, keras, tensorflow2.0"
}
|
FirePower Malware Notification - Track Destination
Good Morning,
I received a notification from FirePower that there was a MALWARE-CNC Win.Trojan.Gh0st variant outbound connection to our exchange server. I'm guessing there was an email sent to one of our staff that has a malicious attachment. I'd like to track who this was sent to though. Do you know if thats possible. I have the source IP, but the only thing the FirePower notification tells me is that it was directed to our load balancer for exchange. Doesn't exactly tell me what mailbox it was being sent too. Is it possible to find this info?
Thanks, Ryan
|
Upon further investigation it appears this was generated by < hitting out our Outlook Web Access Site.
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 0,
"tags": "cisco asa, exchange 2013"
}
|
MyClass.class.getClassLoader().getResource("").getPath() throws NullPointerException
I have code that is running correctly on a development machine but throws a NullPointerException when installed in a production environment. The line that throws the exception is the following:
MyClass.class.getClassLoader().getResource("").getPath();
So I split this into multiple lines of code to see exactly which call was returning null, like this:
ClassLoader cl = MyClass.class.getClassLoader();
URL url = cl.getResource("");
String path = url.getPath();
Now the url.getPath() call is throwing the NullPointerException, meaning that cl.getResource("") is returning null.
Can anyone tell me how this call can ever return null?
|
The implementation of `getResource` is different for different `ClassLoader` implementations.
While this might reliably work on your local machine, it is not guaranteed to be successful on other ClassLoader implementations.
So expect other ClassLoaders to behave differently (especially if you execute that code inside a Application Server, WebStart Launcher or any environment that has some security restrictions).
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "java, classloader"
}
|
Create True VLAN over RAS
I was wondering if it's possible.
I want to create a virtual network over RAS using Windows Server 2003.
The Client should be able to connect to the server using L2TP and should get an IP Adress from a private Range (lets say 192.168.1.100 - 192.168.1.200 and a subnetmask of 255.255.255.0). Now each client connected to the server should be able to ping another connected client.
e.g. 192.168.1.123 <-> 192.168.1.145 via RAS via the server.
Is this possible? And ... how ?
best regards, andre
|
Yes its possible. You just have to add a static address pool on the IPV4 address assignment. Will your clients be able to access the server network segment or just this DMZ ? If so, you need to route the clients to the servers segment cause they will be put on a different network segment. Regards.
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 0,
"tags": "windows server 2003, vpn, vlan"
}
|
Paperclip dimension for images without cropping the image
Can any one give the dimension for the image without cropping that are used in paperclip. Any other symbols avaliable rather # and >.Thanks.
|
Paperclip uses the ImageMagick library to process images so you can use any option that ImageMagick provides. The full listing is here: <
So you can do things like:
has_attached_file :photo,
:styles => {
:thumb => "100x100!",
:small => "150x150^",
:medium => "50%" }
etc.
You should spend some time reading through the commands to find the right one for your case.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, ruby on rails 3"
}
|
Google map for reviewed places
Is there a way to visualize on a Google map all places I've given a review on Google? Something similar to My Maps, but with places I reviewed automatically added.
|
It appears that since a few weeks it's possible.
Click on any place you've ever reviewed, then click on "Reviews", find your review and click on your profile icon. You'll be brought to a map containing your reviewed places, marked with this icon:
}{2}}$ where $d(n)$ gives the number of divisors
I tried reading the answers on Product of Divisors of some $n$ proof and unfortunately couldn't understand them. The accepted answer mentions that
${\displaystyle\prod_\limits{d|n}{d^2}=\prod_\limits{d|n}{d\frac{n}{d}} = \prod_\limits{d|n}{n}=n^{d(n)} }$ where $d(n)$ gives the number of divisors of a number $n$ over $\mathbb N$,
which I assume proves something about the product of (every divisor of $n$ squared) being equal to $n^{d(n)}$. But I still don't get how this is related to the conclusion.
|
Bearer of the curse, first $d$ is a divisor of $n\iff$ $\frac{n}{d}$ is a divisor of $n$. This is because $d\cdot\frac{n}{d}=n$, and $\frac{n}{d}$ is an integer. This would mean that $$\prod_{d\mid n} d=\prod_{d\mid n} \frac{n}{d}\tag{1}$$ because both products run over the same divisors just in opposite order. Multiplying both sides of $(1)$ by $\prod_{d\mid n} d$ gives $$\prod_{d\mid n} d^2=\prod_{d\mid n} d\prod_{d\mid n} \frac{n}{d}=\prod_{d\mid n} n\tag{2}$$
For the last equality you get an $n$ for each divisor $d$. There are $d(n)$ divisors, we get
$$\prod_{d\mid n} d^2=n^{d(n)}\tag{3}$$
Now, $\prod_{d\mid n} d^2=\left(\prod_{d\mid n} d\right)^2$ so taking the square-root of both sides of $(3)$ yields $$\prod_{d\mid n} d=n^{\frac{d(n)}{2}}$$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "elementary number theory, divisor counting function"
}
|
How to turn off site suggestions in Firefox address bar
How do I prevent the dropdown in Firefox that shows social media sites?
I don't have these sites bookmarked (except YouTube) and I hate seeing the icons of the companies that are invading peoples privacy and selling their personal data every time I try to visit a website.
.mousemove(function() {
if (timer) {
clearTimeout(timer);
timer = 0;
}
$('.navi a, a.left, a.right').animate({top:'0px'},'fast');
timer = setTimeout(function() {
$('.navi a, a.left, a.right').animate({top:'50px'},'fast');
}, 1000)
});
|
problem is, you're starting the animation to move up over and over again on each mousemove event. due to jquery's animation queuing, every call to `animate()` on the same object will get queued, so your your final `animate()` call in the delayed function (moving the element down again) has to wait until all 'up' animations are done.
see this fiddle for a quick fix
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "jquery"
}
|
Remove query string and make clean url using htaccess
I have url's like following with query string. I want to remove query string from url and want to make clean url.
www.demo.com/following.php?user=hardik
www.demo.com/fans.php?user=john
This url's should be like
www.demo.com/hardik/following
www.demo.com/john/fans
OR should be like
www.demo.com/following/hardik
www.demo.com/fans/john
Is this possible with htaccess? I tried to find a loot in google but still no luck. Need help.
Update:
I need something like this
www.demo.com/user/hardik/following/
www.demo.com/user/john/fans/
I tried like this
RewriteRule ^user/([^?]*) following.php?user=$2/ [L,QSA]
|
You can use this code in your `DOCUMENT_ROOT/.htaccess` file:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/(\w+)/(\w+)/?$ $2.php?user=$1 [L,QSA,NC]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "regex, apache, .htaccess, mod rewrite"
}
|
MongoDB - grantRolesToUser is rolled back?
Replicaset - Mongo version 3.2.4, I use bash script to update mongo permission in some situations, something like :
mongo <<EOF
db"grantRolesToUser";
print(JSON.stringify(db.getUsers()));
EOF
Basically, adding readWriteAnyDatabase role to "someone".
It works, and the print shows the user with the new role. However, 2-3 seconds later. it's gone !!
Any thoughts on what could be causing this?
|
The issue is related to MMS/OpsManager automatic sync of users across the replicaset.
From the OpsManager Manual:
If you want Ops Manager to ensure that all deployments in a group have the same database users, use only the Ops Manager interface to manage users.
If you want certain deployments in a group to possess users not set at the group level, you can add them through direct connection to the MongoDB instances.
So you can either control users in the OpsManager or from mongo shell itself, but not both.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "mongodb, roles, database"
}
|
Why this matche not working just for css file
> **Possible Duplicate:**
> My CSS is not getting injected through my content script
**manifest.json**
{
"name": "TESTE",
"version": "0.0.0.1",
"manifest_version": 2,
"description": "Description",
"content_scripts": [
{
"matches": [" <<---------
"css": ["style.css"],
"js":["alert.js"]
}
],
"permissions": ["tabs", "<all_urls>","
}
The js file is working perfectly, but the css just load if i put generic match like
"matches":["
Why?
|
This is a known bug that exists for over an year now.
Temporary solution for this is to inject CSS from content script javascript:
var link=document.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", chrome.extension.getURL("main.css"));
document.getElementsByTagName("head")[0].appendChild(link);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "google chrome extension"
}
|
Proving continuity of a $\mathbb{R^2}\rightarrow \mathbb{R}$ function at a point.
Let $f(x,y): \mathbb{R^2}\rightarrow \mathbb{R}$ with $f(x_0,y_0)=a$. To prove that $f$ is continuous at $(x_0,y_0)$ when approaching the point in the domain along a straight path, we define $g(t)=\begin{bmatrix}x_0\\\y_0\end{bmatrix} + t\cdot \begin{bmatrix}r_x\\\r_y\end{bmatrix}$, $(r_x,r_y)\neq(0,0)$ and $h(t) = f(g(t))$. Then if $\lim_{t\rightarrow 0}{h(t)}=a$, the statement is proven.
Question: is it possible for $f$ to still not be continuous at $(x_0,y_0)$? For example, if approaching the point along $t\cdot \sin{\frac{1}{t}}$ or other path that has no defined direction at $(x_0,y_0)$, or for other reasons.
|
Yes, $f$ may not be continuous. For example, consider the following $f$ given in polar coordinates where $0\leq\theta<2\pi$: $f(r,\theta) = \frac{1}{2\pi-\theta}r$. This is continuous on every straight path through the origin, but is not continuous in $\mathbb{R}^2$ at the origin because $\frac{1}{2\pi-\theta}r$ gets arbitrarily large as $\theta \to 2\pi$ for any $r$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "real analysis, multivariable calculus, continuity"
}
|
What happens when you select a country in Azure AD B2C
I am a bit confused about the meaning of country/region when creating a new tenant. This is not the region I am used to from other services (like West US, West Europe, ...).
So: what exactly is the meaning when I select 'Germany' here? What happens?
|
Depending on the country you choose, Azure AD B2C selects the closest data center/region that will hold your Azure AD B2C directory. Currently, Azure AD B2C only uses the European and North American regions. If you select Germany, your Azure AD B2C directory will be created in a data center in the European region.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "azure ad b2c"
}
|
How to use more than one button in one field in Kendo Treelist?
I want to use 2 or more buttons in one field like Kendo Grid by using custom command in TreeList but I could not do that. Does anyone have a solution?
|
You just add an array of buttons to the column command property:
$("#treeList").kendoTreeList({
columns: [
{ field: "name" },
{
command: [
{
name: "Cust1",
text: "Custom1",
click: function(e) {
alert("Custom1");
}
},
{
name: "Cust2",
text: "Custom2",
click: function(e) {
alert("Custom2");
}
},
]
}
],
editable: true,
dataSource: dataSource
});
# **DEMO**
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "kendo ui, treelist"
}
|
How to use Windows Authentication in WPF?
I'm not finding much documentation on how to use Windows Authentication in a WPF app. I wouldn't have thought that it would be any different than in any non-WPF app, but it seems that it is. I want to go into my project Properties -> Application and ensure that Windows Authentication is on, but that option is not available in a WPF app (as the following document confirms).
<
If I ignore all that and just look at `My.User.Name` (VB), it is empty. This tells me that somehow Windows Authentication is not enabled.
Seems like there is a concept I am missing; could someone point me in the right direction?
My plan is to use `PrincipalPermissionAttribute` to restrict access to certain parts of my app (or perhaps the entire app, by applying it to `Application_Startup()`).
|
Itowlson's answer is correct, but also, in order to use the PrincipalPermissionAttribute on any method, you have to first make the windows principal the current principal by calling:
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 7,
"tags": "wpf, vb.net, windows authentication"
}
|
settings.py file not loaded when using CrawlerRunner in Scrapy in Python
I try to debug run on the following code and have a breakpoint in settings.py file, it finished without stepping into that line of code:
configure_logging()
runner = CrawlerRunner()
@defer.inlineCallbacks
def crawl():
# yield runner.crawl(a_spider)
yield runner.crawl(b_spider)
reactor.stop()
crawl()
reactor.run() # the script will block here until the last crawl call is finished
Whereas if i run with the following code, it will be hit.
cmdline.execute(("scrapy crawl a_spider -o %s -t csv -L INFO" % (file_path,)).split())
What I'm trying to do is running multiple spiders in one single run, could anyone help me out with the latter solution? Thanks.
|
As `scrapy.crawler.CrawlerRunner` doesn't load the settings automatically for you, you'll need to get the setting object yourself and pass it to the runner.
E.g. you may replace this line of your code:
runner = CrawlerRunner()
with these:
from scrapy.utils.project import get_project_settings
runner = CrawlerRunner(get_project_settings())
See also: Run Scrapy from a script (Scrapy doc)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "python, scrapy"
}
|
More than one exception when using the match operator
I have this part of my code:
$exception = "VM"
ForEach($item in $list) {
IF ($item -match $exception) { $invalidlist += $item }
ELSE { $validlist += $item }
}
Which works as intendet when only assigned 1 item to the variable `$exception`. The Problem is, i need the variable to contain more then one item, like:`$exception = "VM","TM","TMP"`
How is it possible to search for a match to any item in `$exception`?
Thanks in advance.
EDIT: The `$list` is created by using:
`$list = Search-ADAccount -AccountInactive -ComputersOnly -TimeSpan 548.00:00:00`
|
Regarding your updated comment, your `$list` is array of AD Objects: Assuming you care of the computer name, You should add the Name property to `$item` -> `$item.name` like in the following example:
*If you care to return only the Computer name and not the full object, add the $item.name to the invalid variable as well, e.g. `$invalidlist += $item.name`
$invalidlist = @()
$validlist = @()
$exception = "VM","TM","TMP"
$list = Search-ADAccount -AccountInactive -ComputersOnly -TimeSpan 548.00:00:00
ForEach($item in $list) {
## if the item in $exception are equal to the $item name you can use the contains operator
## otherwise you can use -match
IF ($exception -contains $item.name) { $invalidlist += $item }
ELSE { $validlist += $item }
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "powershell, match, powershell 2.0"
}
|
Trying to get a list of Facebook IDs for those who have checked into a place
I am trying to determine if it is possible to get a list of Facebook users and IDs (via JSON I assume) that have checked in to a place/page.
Is this even possible? Do you need an access token from each user account to access this information? I found Facebook's documentation to be less than helpful...any help will be much appreciated!
|
You can query the FQL `checkin` table but at most (based on the permissions granted) you'll get the user's & her friends' checkins.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "facebook, json, facebook graph api"
}
|
Set APPLICATION_ENV in Zend framework 3
I've enabled development mode using `composer development-enable` . How can I check in my module's `config/module.config.php` that development is enabled or not?
I've also added `SetEnv APPLICATION_ENV development` in public/.htaccess and tried to use it in `module.config.php` using `echo APPLICATION_ENV;exit;` but it doesn't give me environment.
How I can set and get application environment in zend framework 3?
|
use the correct function ;)
$environment = getenv('APPLICATION_ENV');
Usage for config in ZF2/3:
$env = getenv('APPLICATION_ENV'); // Expect null or "development"
$modules = [];
if ($env === 'development') {
//Array of modules used only for development
$modules = array_merge_recursive($modules, [
'Zf2Whoops',
]);
}
In just Zend Framework nothing special happens with the usage of `composer development-enable`. However, if you use Apigility at some point, it will create a `development.config.php` file for you which disables application caches.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "zend framework, zend framework3"
}
|
Set img src at runtime
Here is how I do it:
var src = '<%=Url.Content(Server.MapPath("~/AppData/images/myImages/1.jpg"))%>';
$('#imgLocation').attr('src', src);
I have a solution with MVC project in it. The code above is in index.aspx, which is in:
C:\Users\John\Documents\Visual Studio 2010\Projects\MyApp\MyApp\Views\index.aspx
Here is the image path:
C:\Users\John\Documents\Visual Studio 2010\Projects\MyApp\MyApp\App_Data\myImages\locations\1.jpg
When I run my project, the image has src whose value is:
src="C:UsersJohndocumentsisual studio 2010ProjectsMyAppMyAppAppDataimagesmyimages.jpg"
What is the problem?
|
using Server.MapPath renders the physical location of the image instead of the relative location from the web server
You should drop it entirely:
var src = '<%=Url.Content("~/AppData/images/myImages/1.jpg")%>';
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery"
}
|
Change default keyboard language in mobile app
I am developing a html5 based hybrid application and it is for a german client. Everything is completed and stumbled into one problem.
The web app is in german, but while accessing the application, the keyboard is english one and i need to change it to german.
Specifying
<html lang="de">
dint work really.
Ive found some questions related to android/iOs application and found in iOS you cannot do this. But in android, someone was able to solve this.
how to change keyboard language programmatically
Is there a way in html5 apps?
I am using backbone.js + phonegap
Any help is appreciated.
|
This is not really that possible. You can change the users locale.
Number of solutions present on stackoverflow already:
Here for example, or Here another one.
However, this will only change the locale. The problem you will encounter is that the keyboard is itself an application. Therefore, you cannot change it directly from your application, nor can you guarantee that your user will have the "German" charset or addon or whatever, for they keyboard app that they employ.
Your only real and reliable solution if you wish to accomplish what you need would be to create your own keyboard input. Otherwise, it will be in the user's hands to change their keyboard to German.
That means you have to change input language yourself.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "html, hybrid mobile app"
}
|
IONIC -3 calendar language issue
Im created my university project for using `IONIC -3` , I'm installed this calendar
npm install ionic3-calendar
< calendar is working but i had some issue for calendar display `unknown language` how to removed this language
look image
 currentMember;
however, g++ gives me this error:
error: expected initializer before '.' token
I figure that I'm misusing typedef, since `clients.members.at(selectedTab)` is a function call and not a type. Is there a way to do what I'm trying to do here?
|
If this is used function-local and neither `clients.members` nor `selectedTab` change between its uses, just use references. E.g.:
Member& currentMember = clients.members.at(selectedTab);
currentMember.foo();
currentMember.bar();
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "c++, typedef"
}
|
C Programming - Role of spaces in scanf()
I wrote the following code:
#include <stdio.h>
int main()
{
int a, b;
printf("Enter values of a and b\n");
scanf(" %d%d ", &a, &b); // Note the two spaces before and after %d
// ^This^
printf("a = %d b = %d\n", a, b);
return 0;
}
The program run something like this:
aps120797@XENON-PC:/mnt/d/Codes/LetUsC$ ./a.out
Enter values of a and b
1
2
3
a = 1 b = 2
My question is that why is it taking three inputs instead of two (two %d is in scanf() ) and even if it is taking three, why is it skipping the last one?
|
Space in a format string means to skip over any sequence of whitespace (spaces, newlines, tabs) in the input, and stops scanning when it gets to the first non-white character or the end of the input. That next character is left in the input buffer, so it can be read by the next format operator (if there is one) or the next input operation (if you were to call `getc()` after your `scanf()`, it would read the `'3'` character.
When you put a space at the end of the format string, it skips over the newline after `2`, and keeps scanning until it gets to the next non-white character. So it has to get to the `3` before it stops.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c, scanf"
}
|
Как в таблице динамически создать <tbody>
`<thead>` создаётся `createTHead()`;
`<tfoot>` создаётся `createTFoot()`;
Вопрос: как динамически создать тэг `<tbody>`?
|
В спецификации `HTML4` метод для создания `TBody` отсутствует. Проясняться это может тем, что `THead` и `TFoot` у таблицы должны быть в единственном экземпляре, и при повторном вызове функций _createTHead_ , _createTFoot_ , будет возвращен существующий экземпляр. В то время как `TBody` может быть несколько. Поэтому для него не нужен особый метод и можно было использовать обычный createElement
table.appendChild(document.createElement('tbody'));
Но в HTML5, судя по всему, решили передумать и добавили соответствующий метод
createTBody()
Который создает элемент и добавляет его в конец таблицы.
Судя по MDN данный метод поддерживается всеми основными браузерами.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, html"
}
|
Reading wordpress RSS with C# - Content different
I'm trying to read a RSS generated by wordpress with full text activated. On firefox and IE9 an item data contains the element `content:encoded`:
<content:encoded><![CDATA[bla bla bla]]></content:encoded>
but when in a C# program I request the same rss url this node is not present. I do my C# request like this:
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
client.Headers.Add("Accept", "application/xml");
var xml = client.DownloadString(url)
Does I have to add an header to the request to have this specific field?
|
You don't need WebClient to download rss.
XDocument wp = XDocument.Load("
XNamespace ns = XNamespace.Get("
foreach (var content in wp.Descendants(ns + "encoded"))
{
Console.WriteLine(System.Net.WebUtility.HtmlDecode(content.Value)+"\n\n");
}
**EDIT**
The problem is related with compression. If the client doesn't support compression, then server doesn't send contents.
WebClient web = new WebClient();
web.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
var zip = new System.IO.Compression.GZipStream(
web.OpenRead("
System.IO.Compression.CompressionMode.Decompress);
string rss = new StreamReader(zip, Encoding.UTF8).ReadToEnd();
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 1,
"tags": "c#, wordpress, rss"
}
|
Java / IntelliJ doesn't recognize "java" imports or 'String' type
I think I messed around with my Java configurations, but now IntelliJ won't recognize the keyword 'String' in my code (it gets displayed in red and says 'Cannot resolve symbol 'String' ' - suggests to 'import class'). Also, any imports I'm trying to add, like `java.sql` and stuff like that, it colors the word 'java' in red and says it doesn't recognize it. This wasn't a problem before!
I tried reinstalling IntelliJ and Java and it didn't fix the problem. Please help! I gotta do my homework! :(
P.S. I'm running latest Java, latest IntelliJ Ultimate with a license, on 64-bit Linux Mint
|
Open the Project Structure, and select a Project SDK. IntelliJ wouldn't know what to do with Java if it didn't know that was the SDK.

I have the following file testf.h:
#ifndef TESTF_H_
#define TESTF_H_
int test(int what){
return what;
}
#endif
I included/imported it in TestAppDelegate.h (which is used for other .m files in my xcode project). I get a duplicate symbol error. If I included/imported testf.h in a .m file that is never included/imported in other files then it works fine. So it seems like the `#ifndef/#define/#endif` has no effect. Is there anyway to go around this?
Thanks
|
This is a function definition, it belongs in a c, cpp or m file.
This popular trick with #defines will protect you from compiler errors (typically to survive circular #include dependencies. ) It will not protect against a linker error. This is exactly why people put declarations in h files and definitions in c (or m) files.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "iphone, objective c, c, xcode, ios4"
}
|
Or between groups when one group has to be preceeded by a character
I have the following data:
$200 – $4,500
Points – $2,500
I would like to capture the ranges in dollars, or capture the `Points` string if that is the lower range.
For example, if I ran my regex on each of the entries above I would expect:
Group 1: 200
Group 2: 4,500
and
Group 1: Points
Group 2: 2,500
For the first group, I can't figure out how to capture only the integer value (without the `$` sign) while allowing for capturing `Points`.
Here is what I tried:
(?:\$([0-9,]+)|Points) – \$([0-9,]+)
<
|
Just use an alternation here:
^(?:(Points)|\$(\d{1,3}(?:,\d{3})*)) - \$(\d{1,3}(?:,\d{3})*)$
## Demo
The salient points of the above regex pattern are that we use an alternation to match either `Points` or a dollar amount on the lower end of the range, and we use the following regex for matching a dollar amount with commas:
\$\d{1,3}(?:,\d{3})*
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "regex"
}
|
Compare two XMLNodes in C (libxml library)
I'm parsing some xml files in C using libxml library. I want to compare two xmlnodes to see whether they contain the same data or not. Is there any function available to do so?
|
The libxml API docs seem reasonable and suggest that xmlBufGetNodeContent and xmlBufContent might do what you want.
xmlNode node1, node2;
......
xmlBuf buf;
xmlChar* content1 = NULL;
xmlChar* content2 = NULL;
if (xmlBufGetNodeContent(&buf, &node1) == 0) {
content1 = xmlBufContent(&buf);
}
if (xmlBufGetNodeContent(&buf, &node2) == 0) {
content2 = xmlBufContent(&buf);
}
if (strcmp(content1, content2) == 0) {
/* nodes match */
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "c, xml, xmlnode, nsxmlnode"
}
|
Prove $u_n$ = $n$ $*$ $2^n$ with mathematical induction
I need to prove that
$u_n$ = $n \times 2^n$
using mathematical induction with the below information.
$u_1\;=\;2\;\text{ and }\;\;u_{n+1}=2\left(u_n+\frac{u_n}n\right)\;\text{ for }\;n\geq1$
I have expanded the first few terms such that
$u_1\;=\;2$
$u_2\;=\;8$
$u_3\;=\;24$
$u_4\;=\;64$
$u_5\;=\;160$
I have also proved that $P(1)$ is true such that $u_n$ = $2$.
Therefore, $u_k$ = $k \times 2^k$ .
How do i prove the case for $k+1$ ?
|
We need to prove $ \forall n \geq 1,P(n) \implies P(n+1)$
Base case: $$u_2=2\cdot2^2=8=2(u_1+\frac{u_1}{1})=2(2+2)=2*4=8$$
Assume that it is true for $n=k$
thus $$u_k=k\cdot2^k$$
Now you have to prove it for $n=k+1$
use $$\;\;u_{n+1}=2\left(u_n+\frac{u_n}n\right)\;for\;n\geq1$$ $$u_{k+1}=2\left(u_k+\frac{u_k}k\right)$$
but we have $$u_k=k\cdot2^k$$ put back into the equation above we get
$$u_{k+1}=2\left(k\cdot2^k+2^k\right)=(k+1)\cdot2^{k+1}$$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "induction"
}
|
How to make a presence lookup with UCMA
I'm having a LocalOwnerPresence object, which I want to get the PresenceState object of, to compute against another PresenceState to check if they are equals. Does anyone knows where the PresenceState of a LocalOwnerPresence is located?
|
The LocalOwnerPresence is part of the endpoint (either Application or User).
To retrieve presence for the local endpoint, you can use
_endpoint.LocalOwnerPresence.BeginSubscribe()
Before doing this though, you should make sure you subscribe to the PresenceNotificationReceived event handler so that you can receive events.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, lync, ucma"
}
|
Convert 2 columns dataframe to a 2 dimensional matrix in R
Hi I am trying to convert an R dataframe with 2 character columns to a matrix. Here is an example of what I am trying to do:
suppose I have this dataframe:
name work
one test1
one test2
two test1
two test3
three test3
And I would like to turn it into this matrix
name test1 test2 test3
one 1 1 0
two 1 0 1
three 0 0 1
Any idea how I can accomplish this in R please?
|
DF <- read.table(text="name work
one test1
one test2
two test1
two test3
three test3", header=TRUE)
table(DF)
work
name test1 test2 test3
one 1 1 0
three 0 0 1
two 1 0 1
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "r, matrix, dataframe"
}
|
How to filter a filed when it is Null or null character string?
How to filter a filed when it is Null or null character string?
I can only to check when it is null:
DataDictionary.objects.filter(parentlevel__isnull=True)
How about Null or null character string?
|
To answer the literal question, you may add empty strings into the filter query by using `Q` objects:
from django.db.models import Q
q = Q(parentlevel__isnull=True)
q |= Q(parentlevel='')
DataDictionary.objects.filter(q)
But, to answer the question behind the question, the docs recommend to avoid this awkward situation in the first place by initializing the field differently:
> Avoid using null on string-based fields such as `CharField` and `TextField`. If a string-based field has `null=True`, that means it has two possible values for "no data": NULL, and the empty string. In most cases, it’s redundant to have two possible values for "no data;" the Django convention is to use the empty string, not NULL.
So, I recommend you make this change on the `DataDictionary` model and add the corresponding data migration to convert nulls into empty strings.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, django"
}
|
Install "dev" build of Android app along side market version
I just released my first Android Application through the market. I'm currently working on some new features for the next release and would like to install this "dev build" on my phone, without uninstalling the "production" version (among other things, this will stop future updates from the Market).
I'm especially interested in this because I'd like to give the APK to friends / "beta-testers" to try, but I don't want them to uninstall the released application first.
Is there anyway to have on one device two applications: "App (via market)" and "App (DEV)"
Would this involve using a different signing key or modifying the manifest in someway?
Thanks!
|
You can simply rename the package, so both apps are installed.
You need to change the package name in the manifest as well as in the source folder. Use Eclipse's refactoring for it and it will be done in a minute.
They don't need to be signed with the same key.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 9,
"tags": "android"
}
|
Concatenate and minify css with Gulp still necessary?
I'm using Gulp as part of my theming workflow and was wondering if it was necessary to add the concatenate and minify tasks into Gulp if Drupal already does that when I check the option under Performance.
|
No, it's not necessary, unless you decide there's an appreciable performance benefit by using the gulp method as well (possible but unlikely).
You'll just be minifying twice otherwise, wasted CPU cycles.
|
stackexchange-drupal
|
{
"answer_score": 1,
"question_score": 0,
"tags": "workflows"
}
|
Issue with having both slow fall and levitation
I'm trying to make Blaze armor: I have a command block giving me levitation 253, essentially slow falling while wearing. However, I would like to change the amplifier to 1 (so the player floats up) temporarily as long as the player is holding a blaze rod. But the two commands do not seem to mix; the amplifier of 1 won't overwrite the 255.
Here's what I have now:
If wearing the Blaze armor: `/effect @p 25 3600 253 true`
If holding the Blaze rod: `/effect @p 25 3600 1 true`
What am I doing wrong?
|
I was trying to make Blaze armor but no one helped so I figured it out myself. While wearing the gear, I had one command block giving me levitation 253, (essentially slow falling while wearing) then while holding a blaze rod, I had to remove the amplifier and add and new amplifier of 1 (so the player floats up). The amplifier of 1 won't overwrite the 255, so you have to remove the 255 and add a completely new effect.
If wearing the Blaze armor: `/effect @p 25 3600 253 true`
If holding the Blaze rod: `/effect @p 25 3600 1 true`
|
stackexchange-gaming
|
{
"answer_score": 1,
"question_score": 1,
"tags": "minecraft java edition, minecraft commands"
}
|
Using rad notification as confirm meessage
Can I Use RadNotification as confirm message with submit and cancel button, Is that scenario is available with this telerik control
|
RadNotification is only for notifications, a beautiful one. You must use RadWindow instead. You can see the documentation here.
Hope it helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "asp.net, telerik"
}
|
Code Contract understanding of error
I am just getting started with Code Contracts, and need a little help in correcting an error:
Given this code:
class MyClass
{
private bool _isUsed = false;
public void SomeMethod()
{
Contract.Requires(!_isUsed);
}
}
I get the following error:
error CC1038: Member 'MyClass._isUsed' has less visibility than the enclosing method 'MyClass.SomeMethod'
which seems to makes alot of the standard checks unavailable. What am I missing in this example?
|
You have a public method SomeMethod. However, you're requiring that a private member variable is set to false. You provide no way of setting _isUsed, and so you're putting a check on a variable that a caller has no control over.
You could make _isUsed into a property i.e.
public bool IsUsed {get; set;}
And then in your SomeMethod() have
Contract.Requires(!IsUsed);
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 8,
"tags": ".net 4.0, code contracts"
}
|
How to align an ascii character and text side by side?
In the example below, how can you make the text "Menu" be vertically aligned (middle) along side of the burger menu?
#burger { font-size:2em; }
<div>
<span id="burger">≡</span> Menu
</div>
|
You can use `vertical-align` with the value that suits you the best:
<
> The vertical-align property affects the vertical positioning inside a line box of the boxes generated by an inline-level element.
example
#burger { font-size:2em; vertical-align:-0.15em;}
<div>
<span id="burger">≡</span> Menu
</div>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html, css"
}
|
How to round the decimal value which we store in the admin panel?
Is it possible to round the decimal value we store in the admin panel . Can anyone Explain me with an example
|
Twig offers various filters. So to round the decimal value, we can use a round filter.
The round filter rounds a number to a given precision:
{{ 42.55|round }}
{# outputs 43 #}
{{ 42.55|round(1, 'floor') }}
{# outputs 42.5 #}
The round filter takes two optional arguments; the first one specifies the precision (default is 0) and the second the rounding method (default is common)
* common rounds either up or down (rounds the value up to precision decimal places away from zero, when it is half way there – making 1.5 into 2 and -1.5 into -2).
* ceil always rounds up.
* floor always rounds down.
For more filter in Craft CMS. You can check below link. <
|
stackexchange-craftcms
|
{
"answer_score": 1,
"question_score": 1,
"tags": "craft3"
}
|
Asp.net MVC eCommerce app - Add To Cart implementation
Let say I am rendering list of products with _Add To Cart_ link / button next to each.
I also have a **CartController** with **AddToCart** Action that accept a parameter of **Product** type.
After product is added to cart user should stay on the same page (Product list) - not to be redirected to Cart or something.
I am rendering Cart summary partial view that should update itself.
So my question is about implementation of the _Add To Cart_ link / button.
Should I use: **Html.ActionLink(...)**
or **Html.BeginForm()** and Submit button.
Maybe there is other ways...
How do I send Product info in each case?
Thanks
|
The way I do it is to have a form for each add button (with maybe the quantity also), since you want your AddToCart action only receive POST actions anyway, that way you process all the add to cart logic and then redirect to your main catalog view (or something like that :)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "asp.net mvc, e commerce"
}
|
How can I narrow down my soup.find search to one line in the HTML
I'm trying to scrape one line of html from this:
<strong class="listingPrice">
£75- £85
<abbr title="">pw</abbr>
</strong>
The line I'm trying to scrape is "`£75- £85`"
My current code to scrape the page is:
html_text = requests.get("web address").text
soup = BeautifulSoup(html_text, 'lxml')
prices = soup.find_all('strong', class_='listingPrice')
Any advice?
|
You can use `.contents[0]`:
from bs4 import BeautifulSoup
doc = """<strong class="listingPrice">
£75- £85
<abbr title="">pw</abbr>
</strong>"""
soup = BeautifulSoup(doc, "lxml")
price = soup.select_one(".listingPrice").contents[0].strip()
print(price)
Prints:
£75- £85
* * *
Or `.find_next()` with `text=True`:
price = soup.select_one(".listingPrice").find_next(text=True).strip()
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "python, html, web scraping"
}
|
External hard drive frequently ejects itself when using Aperture
I have a brand new external hard drive which frequently ejects itself on a regular basis (every ~20 minutes or so), seemingly _only_ when I have Aperture open (my Aperture library is located on the external hard drive). The disk works perfectly fine for long periods of time when I am not using Aperture.
I have read many places online that this could be related to disk inactivity sleep, disk journaling, Spotlight indexing, faulty Firewire cables, faulty Firewire ports, hard drives which are about to die, etc. However, the disk seems to work perfectly fine when I am not using it for Aperture and none of the many forum threads I have found have pointed me in the right direction.
Does anyone have any ideas on how to identify and fix this issue?
Thanks in advance.
|
After long conversations with Apple tech support and also LaCie tech support, we managed to figure out what the issue was. I figured I would add it here, for completeness sake, in case anyone else is experiencing the same issue.
Basically, the external hard drive was powered through the Firewire port; it didn't have an external power source. The problem was that I was trying to import _a lot_ of pictures (around 20 thousand `.raw` format images) into an Aperture library on the external hard drive, _from_ the external hard drive itself (the pictures were also located on the same drive). This would cause the device to not have enough power, which would force it to "eject" itself.
After moving the pictures onto a different hard drive and then importing them from there, I no longer experienced this problem. Just make sure the pictures you are trying to import and the Aperture library live on different hard drives, basically.
|
stackexchange-apple
|
{
"answer_score": 1,
"question_score": 1,
"tags": "hard drive, external disk, aperture"
}
|
Javascript If Condition with multiple OR and AND
please have a look on my if condition. I am just refreshing my javascript and I am wondering, how I could check, if the inserted variables, are the ones I want to be used.
Obviously the "game" should only take rock, paper or scissors.
Now the if condition says, if (choice 1 and choice 2 equal rock or scissors or paper) { do this; } else {do something else}
But apparently it is not working the way I want.
var choice1 = prompt("Player 1: Rock, scissors or paper?");
var choice2 = prompt("Player 2: Rock, scissors or paper?");
compare(choice1, choice2);
function compare(choice1, choice2) {
if(choice1 && choice2 === "rock" || "paper" || scissors) {
alert("You pass");
} else {
alert("Something went wrong");
}
Could anyone give me a short explanation, why the if condition passes every value it gets? It never shows the mssage "Something went wrong".
|
I believe it shoud look like:
if ((choice1=="rock" || choice1=="paper" || choice1=="scissors") &&
(choice2=="rock" || choice2=="paper" || choice2=="scissors")){...
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, html"
}
|
Converting Array to object without any key or single key
I just want to create an object which contains all the values of an array on a sigle key .
arr1 = [{ x: 12, y:13},{ x1: 14, y2:15}];
arr2 = [{ xx: 18, yy:18},{ xx1: 17, yy2:16}];
// result = { finalObj :[{ x: 12, y:13},{ x1: 14, y2:15}],[{ xx: 18, yy:18},{ xx1: 17, yy2:16}]}
Although i can get final array by :
const finalArr = arr1.concat(arr2);
But how to get the end result . Thanks in advance .
|
Concat two arrays
{ finalObj: [...arr1, ...arr2] }
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "javascript, arrays, ecmascript 6"
}
|
Using EventStream doesn't work because MimeType from Controller Action is always text/html
I'm trying to listen to SSE events from a controller action.
I am setting the headers in the controller action with:
Craft::$app->response->headers
->set('Content-Type: text/event-stream')
->set('Cache-Control: no-cache');
The EventSource listener always gives me:
EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection.
Checking the URL (controller action URL) manually, you can see indeed that the headers are "text/html" and I cannot change them.
What is a good way to send SSE events from CraftCMS?
|
I have finally found out that you need to set the RAW on the Response.
$this->response->format = Response::FORMAT_RAW;
So you can overwrite the response format with your own headers.
|
stackexchange-craftcms
|
{
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, controller, craft4"
}
|
Is it advisable to have a web browser remember login credentials?
I have a really long random password for my cellphone account and have it written down in a safe place. I only use it once a month and am considering having my browser remember it. Would there be any disadvantages to this? My computer is password protected so I don't see the threat.
Something I want to point out: the longer a password is the more likely a person is to make a mistake typing it in.
|
Make sure you use a strong Master Password, and don't forget it or lose it (Because resetting your master password will remove all of your saved usernames and passwords).
Essentially doing this means you're using Firefox as a password manager. The question now is "Is Firefox a good password manager?". Here are some answers to consider.
Alternatives: Lastpass (as mentioned) is a standalone password manager. A free and open source one I use is Keepass.
|
stackexchange-security
|
{
"answer_score": 5,
"question_score": 6,
"tags": "passwords, web browser, access control"
}
|
What angle does minute hand and hour hand clock inclined to each other at $2:25$
What angle does minute hand and hour hand clock inclined to each other at $2:25$
My Attempt:
The hour hand of a clock rotate throufh an angle of $30°$ in $1$ hour,
So,
At $2$o'clock, $2$ hrs$\equiv 60°$
Again,
The minute hand of a clock rotate through an angle of $6°$ in $1$ minute.
So, At $2:25$, i.e, $25$min$\equiv 150°$
What should I do further?
|
Time 2 hrs 25 minutes. Converting into hours $2\frac{25}{60} = 2 \frac5{12} = \frac {29}{12}$
Angle made by hour hand in $\frac {29}{12}$ hrs $= \frac{360}{12} \times \frac{29}{12} = \frac {145}{2} = 72.5°$
Angle made by minute hand in 25 min $= \frac{360}{60} \times 25 = 150°$
Difference in angle $= 150° - 72.5° = 77.5°$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "algebra precalculus, trigonometry"
}
|
How dangerous are cracked teeth?
Common accidents can lead to tooth injuries. A tooth that has fallen out obviously needs a dentist, but cracked teeth are on a line between important and ignorable. How does this type of injury affect the patients' health? What are the potential consequences of leaving a cracked tooth untreated?

|
stackexchange-health
|
{
"answer_score": 5,
"question_score": 5,
"tags": "dentistry, cracked broken tooth"
}
|
How create a table AS SELECT with a serial field
This query already work.
CREATE TABLE source.road_nodes (
node_id serial,
node TEXT
);
-- SAVE UNIQUE NODES AND ASIGN ID
INSERT INTO source.road_nodes (node)
SELECT DISTINCT node
FROM
(
(SELECT DISTINCT node_begin AS node
FROM map.rto)
UNION
(SELECT DISTINCT node_end AS node
FROM map.rto)
) as node_pool;
Im wondering if there is a way to create the table using
CREATE TABLE source.road_nodes AS SELECT ( ... )
Instead of having to create the table and then execute insert.
The thing is how create the serial column.
|
You can create the table as select:
create table source.road_nodes as
select (row_number() over())::int node_id, node::text
from (
select node_begin node from map.rto
union
select node_end node from map.rto
) sub;
and the data in the table will be as expected, but the column `node_id` will have no default.
You can, however, manually add the appropriate `default` post factum:
create sequence road_nodes_node_id_seq;
select setval('road_nodes_node_id_seq',
(select node_id from source.road_nodes order by 1 desc limit 1));
alter table source.road_nodes alter node_id set not null; -- not necessary
alter table source.road_nodes alter node_id set default
nextval('road_nodes_node_id_seq'::regclass);
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "postgresql, create table"
}
|
Can i mock static method whith juni5 and mockito or easymock?
I need to mock a static method with junit5 **(that's is very important)** and mockito or easymock. I saw that powermock works only with junit 4. there exists any form to do it with junit5?
|
Mocking of static methods is not possible without PowerMock. And when you need PowerMock, it means that the code is not developed correctly, in the way it is testable. I am working on a project with Java 11, JUnit 5 and Mockito. PowerMock does not support this at all. And I doubt it will ever support it.
That being said: the only way to make it testable is to have the class-with-static-method injected into the class you need to test and then replace the implementation of the bean in the test-scope with a mock. When you inject it, you have a live object, so no need for a static method anymore.
It has benefits to change the code and use an injection framework (like Spring). I know there are situations you can't just do this. If you really can't change the implementation, just leave this for what it is and make a lot of unit tests to test the static method by itself with all kind of parameters. Just to make sure this class works as expected.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 5,
"tags": "mocking, mockito, easymock"
}
|
Develop with SQL Server and change to PostgreSQL later
I need to build an application with ASP.Net Core 2.2 MVC, EF Core and use SQL Server Local db during development.
However, when ready to deploy the app, I'd like to include the dependencies of PostgreSQL 11 into the project and point the project to use PostgreSQL rather than SQL Server .
Is this approach a viable approach that I can easily swap one database to another using EF Core or should I start with PostgreSQL from start?
Thank you in advance.
..Ben
|
It is a viable approach, but you can't use any SQL Server or PostgreSQL-specific features.
If you intend your program to continue to support both databases, then keep developing in either, but be aware of not using SQL Server specific features.
If you only indent to use PostgreSQL in the future, then you should develop using it. It is free, so you can easily install a local version for development.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "sql server, entity framework core, asp.net core 2.2, postgresql 11"
}
|
Derivate of finite sum?
I'm having trouble finding the derivative of the following finite sum:
$$\frac{\mathrm{d}}{\mathrm{d}n} \sum\limits_{k=1}^{n-1} \ln\frac{n-k}{n}$$
I get the following:
$$\frac{1}{n-1}+\frac{1}{n-2}+\ldots+\frac{-1}{n}+\frac{-1}{n}$$
I know the closed form is:
$$\frac{\mathrm{d}}{\mathrm{d}n} \sum\limits_{k=1}^{n-1} \ln\frac{n-k}{n} = \frac{\mathrm{d}}{\mathrm{d}n} \ln\frac{n!}{n^n} = \mathrm{polygamma}(n+1) - \ln(n) - 1$$
But I can't seem to figure out why it cannot be evaluated by taking the derivative of each term. Thanks in advance!
|
You can not differentiate the terms individually and then sum them, since the number of terms in the sum depends on the variable we are differentiating with.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "calculus"
}
|
Create dynamic array from each in jquery?
Is it possible to create a dynamic array using something like this and store X elements, then get the average? How would that be possible?
$(xml).find('student').each(function(){
var name = $(this).find("name").text();
var myArray = DYNAMIC ELEMENTS
student_list.append("<tr><td>"+name+"</td><td>"+cid+"</td><td>"+grade+"</td></tr>");
});
I want to store a set of grades for each class, then get the average of ALL the elements in the array. I would need to get a count of all the elements for it has increasing "key:value" Correct?
Along these lines: `myArray[1] = "54" = myArray[i] = g <- dynamic`
|
Key/value is used with dictionary types, not arrays. To get the average you simply add up all of the elements in the array, then divide by the length of the array. You can get each element by `for` looping through it.
var allGrades = [];
$.each( ... // whatever you had over here ... function() {
var grade = $(this).find("course").text();
allGrades[allGrades.length] = Number(grade);
});
// Average grades
var gradesTotal = 0;
for (var i = 0; i < allGrades.length; i++) {
gradesTotal += allGrades[i];
}
var gradesAverage = gradesTotal / allGrades.length;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery, xml, arrays, dynamic"
}
|
In GIMP, how can I change one solid colors to multiple color variations?
I'm not really sure how to ask this in words, but I used to use a program along time ago that would change one solid color into multiple variations. Say I have a solid red square, but I want it to be more textured, by varying the colors inside the square.
See this picture.
!enter image description here
So what I am asking is, is there a method or brush to do this automatically, or possibly a gimp plugin? Google says no.
|
The following seems to work:
1. Create a blank 3 x 3 image (make bigger if you need more tones).
2. Put your color as foreground and paint the new image with **Bucket Fill.**
3. **Filters > Noise > RGB Noise** or **Filters > Noise > HSV Noise.**
If you find this size to be unmanageable, create something large, say 90 x 90 pixels, repeat the procedure increasing the noise levels, and then **Filters > Blur > Pixelise** with size 30 x 30. If you don't make the noise values quite large, the averaging of the pixelisation will give you little variation.
|
stackexchange-graphicdesign
|
{
"answer_score": 5,
"question_score": 5,
"tags": "color, gimp, texture, plugin"
}
|
Set Background image in CSS
I have the following code in my JavaScript&CSS to create a div & set a bg image :
var incrementEnabled = document.createElement('div');
incrementEnabled.className = "SchedMainCtrlIncrementBtn_En";
this.divElt.appendChild(incrementEnabled);
.SchedMainCtrlIncrementBtn_En {
background-color: white;
float:left;
position: fixed;
width:230px;
height:65px;
top:125px;
left:360px;
background:url("../images/icons/IcnListAddRecipient_En.png") no-repeat center;
path of url is also proper but image is not getting set.
Thanks
Sneha
|
Did you check with firebug (or any other developer tools in your favorite browser) what happens?
* does your div show up at all?
* is the class correctly set?
* what happens to the background attribute?
And why are you using float AND position:fixed? The float:left doesn't do anything.
And btw, I always use single quotes, it's just fine using them :)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, css"
}
|
React useRef with Array for dynamic
I am trying to make the component that the focus moves to the next input when each letter inputted.
I think I need multiple `ref` like an array but I don't know about it.
It's a sample code for the question.
function PIN({length, onChange, value}){
const inputEl = React.useRef(null);
function handleChange(e){
onChange(e);
inputEl.current.focus();
}
return (
<div>
{
new Array(length).fill(0).map((i)=>(
<input type="text" ref={inputEl} onChange={handleChange} />
))
}
</div>
)
}
|
You can create multiple refs
function PIN({length, onChange, value}){
const inputRefs = useMemo(() => Array(length).fill(0).map(i=> React.createRef()), []);
const handleChange = index => (e) => {
//onChange(e); // don't know about the logic of this onChange if you have multiple inputs
if (inputRefs[index + 1]) inputRefs[index + 1].current.focus();
}
return (
<div>
{
new Array(length).fill(0).map((inp, index)=>(
<input type="text" ref={inputRefs[index]} onChange={handleChange(index)} />
))
}
</div>
)
}
|
stackexchange-stackoverflow
|
{
"answer_score": 16,
"question_score": 7,
"tags": "reactjs, react hooks"
}
|
grouped regresion in R
I am trying to run a multiple linear regression but i am getting the same coefficients for all my grouped variables
names<- rep(LETTERS[1:25], each = 20)
daysp<- runif(1:500,1,500)
startdate <-sample(seq(as.Date('1999/01/01'), as.Date('2020/01/01'), by="day"), 500)
enddate<- sample(seq(as.Date('2010/01/01'), as.Date('2020/01/01'), by="day"), 500)
class <- rep(LETTERS[1:4], each = 125)
amt<- runif(1:500,10000,500000)
2ndclass <- rep(LETTERS[5:8], each = 125)
df<-data.frame(names,daysp,startdate,enddate,class,amt,2ndclass)
Changed to factor class and 2ndclass
fitted_models = df %>% group_by(names) %>% do(model = lm(daysp ~ startdate + enddate
+ class + 2ndclass + amt, data=df))
fitted_models$models
How can i run the regressions and get different coefficients for each group?
|
`data = df` explicitly uses the entire data frame `df`, ignoring any grouping. Use `.` to refer to the data that is piped in, which will let `do` use the groups. See the example at the bottom of `?do` for reference:
## From ?do
by_cyl <- mtcars %>% group_by(cyl)
models <- by_cyl %>% do(mod = lm(mpg ~ disp, data = .))
Though, versions of `dplyr` > 1.0 will prefer using `nest_by` (also demonstrated on the `?do` help page):
models <- mtcars %>%
nest_by(cyl) %>%
mutate(mod = list(lm(mpg ~ disp, data = data)))
models %>% summarise(broom::tidy(mod))
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "r, regression"
}
|
Доступ к элементу массива
Как изменить (получить доступ к элементу) элемент массива через указатель на него?
var
q: array of integer;
Pq: pointer;
begin
pq:=addr(q);
end;
|
Ну, наверное, так. Может быть, есть способ лучше, но мне подобное приходилось делать пару раз. В Си и Си++ с указателями на массивы (и на элементы) всё намного проще и интереснее. На мой взгляд, лучше не использовать указатели, если можно обойтись без них.
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;
Var
Mas: Array[0..99] Of Integer;
PMas: ^Integer;
i, n: Byte;
begin
Write(' n = ');
ReadLn(n);
Randomize;
For i:=0 To N-1 Do
Begin
// PMas:=Addr(Mas[i]); можно написать так
PMas:=@Mas[i];
PMas^:=Random(100)-Random(100);
WriteLn(' ', PMas^);
End;
ReadLn;
end.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "delphi"
}
|
Magento 2 how to unserialize backend config
I've created Magento 2 module that saves a particular configuration. Screenshot: array that I can use on the frontend.
I've used the PHP function `unserialize()` but this didn't work. Also i've searched the Magento 2 JSON decode library, but I didn't find an answer there.
Any help would be appreciated.
|
Use `\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig`, In your constructor argument and set the class property: `$this->scopeConfig = $scopeConfig;`
Now to Get the configuration value just use
$fields = $this->scopeConfig->getValue('yourSystemConfigPath', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
$fields = unserialize($fields);
|
stackexchange-magento
|
{
"answer_score": -3,
"question_score": 2,
"tags": "magento2, json, data, unserialize"
}
|
Stop ssh service at specific port
I've started multiple ssh services at a range of port for a particular testing using
/usr/sbin/sshd -p portnumber
How do i stop service at a specific port where i've started ? I've seen this command (But dats general, i have to stop at a specific port)
/etc/init.d/ssh stop
|
To stop all instances you can use:
killall sshd
If you want a specific one you need to use `ps aux | grep sshd -p <port>`. There you get the pid (process id) which you can simply kill by `kill <pid>`.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "linux, bash, ssh"
}
|
abstracting Promises, how to pass arguments to functions
I'm new to JS and practicing with Promises.
I have the following structure, which works:
Database.load('menus')
.then((value) => {return JSON.parse(value)})
.then((parsed) => {return parsed['Menu'].map(Menu.create)})
.then(console.log)
.catch((err) => console.log(err))
I would like to make it a reusable function and abstract away the literals, I've tried:
parse = (value) => {return JSON.parse(value)}
createObject = (parsed) => {return parsed[key].map(`${key}`.create)}
convert = (name, key) => {
Database.load(name)
.then(parse)
.then(createObject)
.then(console.log)
}
convert('menus', 'Menu')
But this is returning:
(node:51848) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: key is not defined
|
`key` is not visible in the required context.
parse = (value) => {
return JSON.parse(value)
}
createObject = (key) => { (parsed) => {
return parsed[key].map(`${key}`.create)
}};
convert = (name, key) => {
Database.load(name)
.then(parse)
.then(createObject(key))
.then(console.log)
}
convert('menus', 'Menu')
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, node.js, promise"
}
|
Set a fixed velocity for keyboard MIDI input while recording on Reason Propellerhead
I have a low-quality MIDI keyboard that doesn't allow changes in its velocity output. So, since I do all my recording with Reason, I want to set the velocity specs there.
Actually, with setting a max for the velocity is enough. But, of course, it has to be done in real time, since I need to listen what I am playing.
Is this feature possible in Reason somehow?
|
I have found another way, the one I am using right now.
The sampled sound I have for the piano in Reason has 4 sounds per key (it is 5 meter gran piano), the sounds are like soft-medium-hard-veryHard. Each one is assigned to a velocity period (very hard for example is assigned to velocity 100-127, and hard to 80-99).
Using Reason, I have deleted the sounds of soft, hard and very hard, and have expanded the velocity range of "medium" to cover the whole spectrum (1-127).
The sound sounds kind of correct. Works for me.
|
stackexchange-music
|
{
"answer_score": 1,
"question_score": 3,
"tags": "midi controller keyboard, reason"
}
|
epsilon delta proofs notation question
If I want to say let $\delta$ be less than $\epsilon/6$ or $1$, whichever is smaller do I denote it as
$\delta< \min\\{\epsilon/6,1\\}$ or $\delta< \min(\epsilon/6,1)$??
|
You normally write $\delta < \min \\{ \epsilon/6 , 1 \\}$ which makes it immediately clear what you mean.
I've never seen anyone using $\delta < \min(\epsilon /6 ,1 )$ for expressing this, because $\\{ \\}$ normally denotes a set and $()$ denotes a touple (ordered). In the case of $\min$ it does not make sence to use an ordered structure as argument anyways.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "real analysis, notation"
}
|
Compilers and negative numbers representations
Recently I was confused by this question. Maybe because I didn't read language specifications (it's my fault, I know).
C99 standard doesn't say which negative numbers representation should be used by compiler. I always thought that the only right way to store negative numbers is two's complement (in most cases).
So here's my question: do you know any present-day compiler that implements by default one's complement or sign-magnitude representation? Can we change default representation with some compiler flag?
What is the simplest way to determine which representation is used?
And what about C++ standard?
|
I think it's not so much a question of what representation the compiler uses, but rather what representation the underlying machine uses. The compiler would be very stupid to pick a representation not supported by the target machine, since that would introduce loads of overhead for no benefit.
Some checksum fields in the IP protocol suite use one's complement, so perhaps dedicated "network accelerator"-type CPU:s implement it.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "c++, c, compiler construction, representation, negative number"
}
|
Can i pass a reference from one function to another
Here i have three functions; passing a reference from function 1 to function 2.So in function 2, `a` is a reference. Then why it is not allowed to pass this same reference to function 3? without using the keyword `ref`
**Function 1:**
public void funReadA()
{
double a=10;
//read value for a
funReadB(ref a);
}
**Function 2 :**
public void funReadB(ref double a)
{
double b = 25;
a = 11;
// sum(a, b);this method call is not allowed
sum(ref a, b);// why ref a is required? a is already a reference na?
}
**Function 3:**
public double sum(ref double a,double b)
{
return a += b;
}
|
The `ref` keyword on the call site is required mostly to make sure the person who wrote the calling code is aware that he is passing a reference, and so that the value could change.
It's not strictly necessary from a _programming language_ point of view, but it's a good idea from a _programmer_ point of view.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "c#, .net, reference, pass by reference"
}
|
Is it possible to calculate a bar based on song BPM and time position in the song?
I'm using a spreadsheet to analyze song arrangements. I know the BPM of the song.
I'd like to just listen to the song, and then input the time where I'd like to make a note (say 1:50 or 90 seconds) and have a formula determine what bar this happened at (vs. what time).
What might the formula be to determine the bar from time and BPM?
EDIT: I'm almost every case, I'm listening to music in 4/4!
|
> What might the formula be to determine the bar from time and BPM?
If you multiply beats per unit time by the time, you get the number of beats. To find the number of bars, divide by the number of beats per bar. If your time is expressed in seconds, you also need to convert minutes to seconds. You also need to add one bar, because the beginning of bar 1 is at t=0.
For example, 1:50 is 110 seconds, so, if there are 108 beats per minute and 3 beats in each bar, you have
(108 beats / min) * 110 seconds / (60 seconds / min) / (3 beats / bar) + 1 = bar 67
Another example, 90 seconds is 1.5 minutes, so, assuming 72 bpm and 5 beats per bar, you have
(72 beats / minute) * 1.5 minutes / (5 beats / bar) + 1 = bar 22.6
That is, it's the third beat of the five in bar 22.
|
stackexchange-music
|
{
"answer_score": 3,
"question_score": 2,
"tags": "time signatures"
}
|
Update de multiples filas con distintos valores
Estoy intentando actualizar distintas filas con distintos valores, en mi tabla sql, lo mas cerca que he llegado es:
UPDATE cursos
SET posicion = 11
where Id in (1,2)
Pero me actualiza con el mismo valor (11) logicamente las dos filas, yo necesito darle un valor distinto a cada fila. Alguien me podria ayudar con este dilema je?. Gracias!!!
|
Puedes usar un condicional, como CASE ... END, el cual va a asignar un valor a posicion según el id:
UPDATE cursos
SET posicion = CASE Id
WHEN 1 THEN 11
WHEN 2 THEN 15
END
WHERE Id IN (1,2)
De esta forma, el curso con id=1 tendrá posicion=11 y el curso con id=2 tendrá posicion=15.
|
stackexchange-es_stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, mysql, sql, phpmyadmin"
}
|
Убрать из строки определенное количество символов
Есть строка
241,284,234,248
Тут через запятую указаны id постов. Нужно убрать несколько первых id. Сколько именно не известно - будем считать n количество нужно убрать. Как это сделать?
|
$string = '241,284,234,248';
$arr = explode(",",$string);
$n = 2;
$new_arr = array_slice($arr,$n);
$new_arr = implode(",",$new_arr);
print_r($new_arr);
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, html, css"
}
|
SQL Server : set variables with an if statement
I get two values passed from variables:
@F_START_DATE_DT VARCHAR(50)
@F_END_DATE_DT VARCHAR(50)
And I have other parameter declarated:
DECLARE @sSQL NVARCHAR(4000)
I would like to **check if the first two variables are null** and do something like this but correctly:
SELECT CASE WHEN @F_START_DATE_DT OR @F_END_DATE_DT IS NULL THEN
SET @sSQL = 'select * from test_sql1'
ELSE
SET @sSQL = 'select * from test_sql2'
END
|
Something like that would suffice.
IF @F_START_DATE_DT IS NULL OR @F_END_DATE_DT IS NULL
BEGIN
SET @sSQL = 'SELECT * FROM test_sql1'
END
ELSE
BEGIN
SET @sSQL = 'SELECT * FROM test_sql2'
END
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -1,
"tags": "sql, sql server, if statement, case"
}
|
On asymptotics for the number of ways to write $2n$ as the sum of two primes
Let $g(n)$ be the number of ways to write $2n$ as the sum of two primes. Define $G(n) = g(2) + \cdot \cdot \cdot + g(n)$. Are there any conjectured or known asymptotics or bounds for $G(n)$? Especifically, is it known or conjectured that $G(n) \sim \frac{n^2}{\log(n)^2}$?
|
> Unconditionally we have that $$G(N)\sim\frac{2N^2}{\log^2(2N)}.$$
To see why, let $1_{\mathcal{P}}(n)$ denote the indicator function for the odd primes. Then $$G(N)=\sum_{n=1}^{2N} \sum_{a+b=n} 1_{\mathcal{P}}(a)1_{\mathcal{P}}(b).$$ Since $1_{\mathcal{P}}(m)=0$ when $m<0$, we may extending the inner sum to obtain
$$G(N)=\sum_{n=1}^{2N} \sum_{a=1}^{2N} 1_{\mathcal{P}}(a)1_{\mathcal{P}}(n-a),$$ and then by switching the order of summation
$$G(N)=\sum_{a=1}^{2N} 1_{\mathcal{P}}(a)\sum_{n=1}^{2N} 1_{\mathcal{P}}(n-a)$$
$$=\sum_{a=1}^{2N} 1_{\mathcal{P}}(a)\sum_{n=1}^{2N-a} 1_{\mathcal{P}}(n)$$
$$=\sum_{a=1}^{2N} 1_{\mathcal{P}}(a)(\pi(2N-a)-1),$$ and by using the prime number theorem, this is asymptotic to $$\frac{2N^2}{\log^2(2N)}.$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 4,
"tags": "number theory, prime numbers, analytic number theory"
}
|
How can I filter data with Dataview when column name include "-" type of character
My table has three columns(`NIGHTS`,`CRUISE-ID`,`DEP-DATE`).I found a way to filter data table like this.(this link help a lot :Helpful).
DataView dv = new DataView(table);
dv.RowFilter = "NIGHTS=7";//query
this works fine and filtered data correctly.but when I use to filter like below
DataView dv = new DataView(table);
dv.RowFilter = "CRUISE-ID=2K2KFJDKF"; //query
It only reads `CRUISE` string from the `query` and gives an error.How can I filtered for `CRUISE-ID`.hope your help.
|
From <
> Column names
>
> If a column name contains any of these special characters ~ ( ) # \ / = > < \+ **-** * % & | ^ ' " [ ], you must enclose the column name within square brackets [ ]. If a column name contains right bracket ] or backslash \, escape it with backslash (] or \\).
Thus the code would be:
dv.RowFilter = "[CRUISE-ID]='2K2KFJDKF'"; //query
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "c#, model view controller, datatable, dataview"
}
|
Error downloading url file
I get this error when I attempt to download a file from a link I get this error no matter what I try and look up and to do Im using
urllib.error.HTTPError: HTTP Error 403: Forbidden
My code is
elif message.content.startswith('``'):
countn = (count+1)
print(countn)
print('ADD')
meme = (message.content)
memen = meme.replace("``", "")
print(memen)
print('Converted')
urllib.request.urlretrieve(memen, meme)
await client.send_message (message.channel, "Added!")
|
403: FORBIDDEN means that the server is denying you access to the resources, either because you have failed to supply sufficient authentication or because it blocks the default python user agent (`Python.urllib/3.X`).
urlretrieve is actually a legacy interface as it was ported from Python 2. You should consider using `urlopen` instead.
Anyway, one solution to this is to add a (spoofed) user-agent to your request, which can't be done using urlretrieve...
headers = {"User-Agent": "Mozilla/5.0"}
request = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(request)
with open(filename, "w") as file:
file.write(resp.read())
This wont fix issues for sites that require a login, but it will fix a lot of sites that don't.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "python 3.x, discord.py"
}
|
How Remember Me for email id Works
I have created one Login Screen where user enter their mail id.
But i want to insert one functionality where it should list the mail id automatically when user type first character of mail id
|
There is one way. I don't know how much feasible it is. So the Idea is : You can store somewhere all the email id after log in success. For example in sqlite database. Now, Implement Notification center for "UITextFieldTextDidChangeNotification" and search for the character in database when user start typing in TextField and show UITableview underneath UITextField with match results (which start from entered character).
When user tap on any cell of Tablview hide tableview and take that cell label value in UITextField. That's it. Hope this logic work.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "iphone, objective c, ipad, xib"
}
|
Pulling individual words from manual input of unknown length
Re-post as I didn't include enough info in the last one.
I tried my best google fu and can't seem to find the right answer (doesn't mean it's not a stupid mistake, as I'm still new)
int main()
{
vector<string> clauses;
string test;
cout << "Please enter your choice or choices\n\ ";
while (cin >> test) {
clauses.push_back(test);
}
return 0;
}
I don't know how many options they will enter so I'm throwing them in a vector.
Currently when it runs it won't take any user input and just let the person keep typing even when hitting enter. c
Thanks in advance. Paul
|
The following code should work for what you want to do :
#include <vector>
#include <string>
#include <iostream>
int main()
{
std::vector<std::string> clauses;
std::string test;
std::cout << "Please enter your choice or choices\n";
do
{
getline(std::cin, test);
if(!test.empty())
clauses.push_back(test);
}while (!test.empty());
return 0;
}
The getline function will read any text on the keyboard and push it in your vector until the user only use the Enter key, which will end the loop.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c++, vector, user input"
}
|
Null reference on MVC 2 Server
I'm writing a MVC 2.0 app with VS2010. On my Windows 7 Ultimate 64bit machine it runs fine. On my laptop (Windows 7 Home Premium, 32bit) it is getting a null reference on Server when I call MapPath.
public ActionResult Index()
{
ContentModel content = new ContentModel();
content.Content = ContentInterface.GetHtmlContent(Server.MapPath("~"), "Home");
content.Ads = ContentInterface.GetPartialAds(Server.MapPath("~"), AdCount);
content.Testimonials = ContentInterface.GetTestimonials();
return View(content);
}
I have installed MVC 2 via Webinstaller, I reregistered .Net 4 with IIS. I've confirmed IIS 6 WMI compatibility mode.
Any ideas?
|
Figured it out: permissions. I granted Full Control to IUSR and it works now.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "asp.net mvc, visual studio 2010, asp.net mvc 2"
}
|
Proof of Expected number of renewals in finite time (Non measure theoretic)
I am reading renewal theory from Stochastic Process by Sheldon Ross.
Proposition 3.2.2 states $E[N(t)] < \infty$ for all $0 \leq t< \infty$, where $N(t)$ is number of renewals in time t.
I understand the approach given, creating another renewal process having higher number of arrivals in t time and proving that the expected number of arrivals in time t for newly created renewal process is less than infinity.
My doubt is: In the previous page author proves that an infinite number of renewals cannot happen in finite time i.e N(t) is finite in finite time. In proposition we are given that $t< \infty$, which implies all the realizations of N(t) are finite. Doesn't that implies $E[N(t)] < \infty$?
I am unable to understand the need for a longer approach taken by the author. What am I missing?
Thanks.
|
A nonnegative random variable $X$ that is finite WP1, does not imply $E[X] \lt \infty$... that is why extra work is required.
_Example_ : consider discrete $X$ that has pmf for natural numbers $\geq 2$, given by $\frac{1}{n(n-1)}$
That said, $E[X] \lt \infty$ does imply $X$ is finite WP1 (eg by Markov Inequality).
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "stochastic processes, renewal processes"
}
|
Get Group from GroupDescription
Say I have a bunch of Books stored in BooksList. Each Book has a genre, for example: adventure, mystery, or sci-fi.
I can group the Books by genre by adding a GroupDescription for the "genre" property.
Given BooksList and the GroupDescription "genre", how can I retrieve the list of all genres? (adventure, mystery, sci-fi).
My use-case is wanting to create a dropdown for my view that can filter by genre. I'm planning to bind the dropdown items to the list of genres.
EDIT: Also, in my use-case, the descriptor "genre" is only known at runtime. So the answer to my problem cannot rely on hardcoding "genre".
|
You could use `DistinctBy` method in MoreLinq library:
`var query = booksList.DistinctBy(p => p.GroupDescription);`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "c#, wpf, list"
}
|
How do I update an individual package without breaking future updates?
I'm on a LTS release and want it to remain LTS. However, I have an individual package called libmlx4-1 that I need to update to version 1.04 (i.e. libmlx4-1) . This is in the Ubuntu 12.10 (quantal) release but not 12.04 (precise) yet and I need that.
How can I obtain this individual package from 12.04 (which already has it's dependencies met on 12.04) and install it without breaking future updates?
|
From the link you added to your question:
* Click on the package you want to download `libxml4-1`.
!image
* Then choose your architecture.
!enter image description here
Then choose a mirror and download it.
And just as that the site advises you:
> If you are running Ubuntu, it is strongly suggested to use a package manager like aptitude or synaptic to download and install packages, instead of doing so manually via this website.
You can install them and if the dependencies in your version are enough to satisfy the package it will install but you won't get automatic updates.
|
stackexchange-askubuntu
|
{
"answer_score": 1,
"question_score": 1,
"tags": "12.04, dpkg, libraries"
}
|
¿Hay alguna forma de averiguar cuantos y cuales callbaks hay en una collección de delegados del tipo Action?
La cuetion es la siguiente. Si yo tengo un action.
Action action:
Y A este Action le añado unos cuantos manejadores tal que asi:
public class Duda
{
Action action;
void handler1(){}
void handler2(){}
void handler3(){}
void handler4(){}
void Init()
{
action+=handler1;
action+=handler3;
}
}
Hay alguna fora de saber cuantos y cuales son los elementtos que se han agregado al action en runtime? Muchas Gracias!!
|
Tienes el método `GetInvocationList()`. Este es un ejemplo muy simple que puedes compilar y ejecutar:
using System;
public class Program
{
public static void Main()
{
Action a = ()=>Console.WriteLine("First");
a+=()=>Console.WriteLine("Second");
foreach (Action aa in a.GetInvocationList())
aa.Invoke();
}
}
El resultado es:
> First
> Second
|
stackexchange-es_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, delegados"
}
|
Lining up the boxes with negative entries in a Young tableau
Given the partition (5,2), I would like the boxes in the following Young tableau to line up:
\documentclass{article}
\usepackage[enableskew]{youngtab}
\begin{document}
$\young({-3}{-2}{-1}01,:23)$
\end{document}
. I have found that quickbitcoin is _very_ fast, and usually takes 10-15 minutes from sending you money to receiving your coins.
|
stackexchange-bitcoin
|
{
"answer_score": 2,
"question_score": 4,
"tags": "buy bitcoins, uk"
}
|
How to select rows where items of two columns match with items of two lists (same index), using Pandas?
The question is the same as the one answered here but extended to two conditionals. This may be tricky because the Pandas method 'isin' cannot be used as that would result in looking at combinations of items in my two lists, while what I want is to compare (and select) the dataframe items corresponding to list items of identical index (e.g. pairs of xn,yn from lists of X=[x1,x2,...xn], Y=[y1,y2,..yn]). The lists can be converted to a dataframe if needed.
Is there a way to generalize this to multiple (more than two) conditionals in Pandas?
|
You could do:
df[df['col1'].isin(list1) & df['col2'].isin(list2)]
This will return the rows of `df` where the value of `col1` exists in `list1` and the value of `col2` exists in `list2`.
`&` is the bitwise AND operator, and will return True on the indices where both the operands are True.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "python, pandas, select"
}
|
altering values for List (text) error: Allowed values list: some values are being removed while currently in use
I have a drupal 7 site with content type that has a field of type List (text) and widget is Select list, I wanted to alter the allowed values but unable to because I keep getting an error: Allowed values list: some values are being removed while currently in use.
What do you suggest? maybe change it through PHPmyadmin for existing nodes?
|
If data is not much delete the field values entered earlier and then alter the allowed values. After that you can reenter the the field values added.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "drupal 7, content type"
}
|
How to download my custom theme?
I'm taking over a website that was previously managed by another person, which had installed a **self-made custom theme** (uploaded through .zip file). In other words, the theme is not available online. It was made for the website.
The person does not have the original files and I need to update it. Is it possible to reconstruct/download the theme so I can modify it offline and then re-upload it? I do not find anywhere a download option for the theme.
Alternatively, is it possible to bulk download the website and somehow reconstruct the theme? In principle, all should be there.
I know there are some related posts here but can't find the proper answer to my question.
|
You can download installed themes and plugins from the WordPress dashboard with a plugin like this: <
|
stackexchange-wordpress
|
{
"answer_score": 0,
"question_score": 0,
"tags": "themes"
}
|
Creating a function from string which inherits the parent scope
In Javascript, is there a way to create a function from a string (such as through the new Function() constructor) and have it inherit the parent scope? For example:
(function(){
function yay(){
}
var blah = "super yay"
yay.prototype.testy = new Function("alert(blah)")
yay.prototype.hello = function(){alert(blah)}
whee = new yay();
whee.hello()
whee.testy()
})()
Is there any way to make whee.testy() also alert "super yay"?
|
(function(){
function yay(){
}
var blah = "super yay"
yay.prototype.testy = eval("(function(){alert(blah)})")//new Function("alert(blah)")
yay.prototype.hello = function(){alert(blah)}
whee = new yay();
whee.hello()
whee.testy()
})()
This seems to work for me, and none of the eval'd data is from any untrusted source. It's just to be used for minifying code.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 5,
"tags": "javascript, function, scope"
}
|
SQL SERVER SSAS: How do I handle a NULL date value in my fact table, so I can process my time dimension without errors?
I have a fact table that has a column with dates loaded from an MS Access source. The thing is, some of the values are NULL and the SSAS won't let me refer my DATE dimension to it.
Is it better to solve it at the SSIS stage or is there some solution at the SSAS?
Thank you very much for you help.
|
Best practice is not to have any NULL key (i.e. Dimension key) values in a Fact table.
Instead, create a MAX date in the Date dimension table (or an 'UnknownValue', -1 for instance) and key to that.
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 5,
"tags": "sql, sql server, ssis, null, ssas"
}
|
Can run a jar file without knowing the jar file name
Can any one tell how to run a jar file using java -jar command without knowing the Jar's full name, I know the prefix but the version of the jar file is dynamic,so I don't want to update my sh for every deplolyment
#!/bin/bash
PROJECT_HOME=/opt/services/testing-batchp
PROJECT_JAR=batch-1.0.8-SNAPSHOT.jar
[ -f /etc/environment ] && . /etc/environment
nohup java -jar -Dspring.config.location=${PROJECT_HOME}/config/ ${PROJECT_HOME}/${PROJECT_JAR} $1 $2 >/dev/null 2>&1 &
I just modified the variable PROJECT_JAR="batch*.*-SNAPSHOT.jar" but its not working. Here the version of the jar will change in each deployment. Please help
|
Try the below approach for executing script without mentioning the jar's release version.
#!/bin/bash
PROJECT_HOME=/opt/services/testing-batchp
PROJECT_JAR=batch-*.*.jar
[ -f /etc/environment ] && . /etc/environment
nohup java -jar -Dspring.config.location=${PROJECT_HOME}/config/ ${PROJECT_HOME}/${PROJECT_JAR} $1 $2 >/dev/null 2>&1 &
Make sure that only one valid jar is there in the deployment folder.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "java, spring, sh"
}
|
How is the use of this 何? 「何ユッキーに変なこと吹き込んでるのよ」
This sentence is from "Mirai Nikki" episode 4". I've seen this use in various animes but I don't get it quite right. It doesn't seem to be the object of the sentence since the object of is . It sounds more like a "why", but that's not the meaning of , right? It also doesn't seem to be an interjection since it's not alone in the sentence.
What is the grammatical function of this ?
|
This is meaning "why" or "how dare you". This always sounds accusatory or dubious.
* Using with intransitive verbs (eg ?)
* Use of with seemingly intransitive verbs describing emotions
This type of accusatory can be used with an intransitive verb. When it's used with a transitive verb, the verb can take two (one as part of and one for the actual object). Both can be omitted in colloquial sentences.
>
> = **** ****
> = Why are you inculcating strange things into Yuckie?
|
stackexchange-japanese
|
{
"answer_score": 3,
"question_score": 2,
"tags": "anime, casual"
}
|
How to colspan in kivy with python
How can I make this layout in kivy without .kv file?
:
def build(self):
root = FloatLayout()
layout = BoxLayout(orientation='vertical')
button1 = TextInput(size_hint=(1,.7))
button2 = TextInput(size_hint=(1,.2))
button3 = Button(text='Send',size_hint=(1, .1))
layout.add_widget(button1)
layout.add_widget(button2)
layout.add_widget(button3)
root.add_widget(layout)
return root
TestApp().run()
|
Add Button2 and Button3 to a different BoxLayout and then add this BoxLayout as a child of `layout`. So something like this inside your `build` method:
root = FloatLayout()
layout = BoxLayout(orientation='vertical')
layout1 = BoxLayout()
button1 = TextInput()
button2 = TextInput()
button3 = Button()
layout.add_widget(button1)
layout1.add_widget(button2)
layout1.add_widget(button3)
layout.add_widget(layout1)
root.add_widget(layout)
I'm assuming this is the behaviour you expect to get:
?
|
If $X$ is nonempty and $\kappa$ is an arbitrary cardinal, then you do not need $AC$ to prove that $X^{\kappa}$ (the cartesian power of $X$) is nonempty: since $X$ is nonempty, there exists $x_0\in X$. Then define $f\colon\kappa\to X$ by $f(i) = x_0$ for all $i\in\kappa$. This is an element of $X^{\kappa}$, so the latter is not empty. No choice needed.
(If $\kappa=0$, you get the empty function, which is the unique element of $X^{\varnothing}$)
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "set theory, axiom of choice, axioms"
}
|
Vagrant - Docker provider vs. docker provisioner
Can anybody explain to me the difference?
Provisioner - is something doing provision - in docker installing, running, pulling containers.
Provider - is something that runs the VM. I.e. VBox runs the ubuntu OS image.
How can be Docker a provider? It runs directly some docker image? If I'm on windows there must some hidden usage of boot2docker right? When will I use each one?
|
Docker provisioner help to prepare environment: build and pull images, run containers if you need multiple containers running for your vagrant machine. Docker provider is running vagrant machine in docker container (instead of VM/cloud as other providers do).
On Linux vagrant is using docker from the host OS. On Windows and MacOS X boot2docker is used for both docker provisioner and provider. By default all vagrant docker machines are using the same boot2docker instance - but you could configure which VM to use (It does not need to be boot2docker - any Linux with docker is ok).
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 17,
"tags": "docker, vagrant, virtualization"
}
|
Cannot invoke initializer for type CGFloat with an argument list of type 'String'
I am making a bar chart from JBChart. I would like to change the chartData to String. please help me do it.
here's the chartData code: var chartData = [1, 2, 3]
Then I want to change it to a String from a UILabel from other view controller.
var chartData = [score1, score2, score3]
But I always get this error (Cannot invoke initializer for type CGFloat with an argument list of type 'String')in this code:
public func barChartView(_ barChartView: JBBarChartView!, heightForBarViewAt index: UInt) -> CGFloat {
return CGFloat(chartData[Int(index)])
}
|
The error is clearly saying that `CGFloat` doesn't have initializer that accept `String` as argument. You can use wrapped around like first convert `String` to `Float` and then convert `Float` to `CGFloat`.
public func barChartView(_ barChartView: JBBarChartView!, heightForBarViewAt index: UInt) -> CGFloat {
if let value = Float(chartData[Int(index)]) {
return CGFloat(value)
}
return 0
}
**Note:** Be sure that this `String` have number as value otherwise it will return `0` for `height`.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "swift, bar chart, jawbone"
}
|
solve linear congruence
Solve $6x \equiv 4 \pmod{10}$. I've tried the following:
Note that $\gcd(6,10) = 2$. Since $2 \mid 4$, a solution exists. We can rewrite the problem as $6x \equiv 24 \pmod{10}$, by adding $10$ to the right side twice. So, $x \equiv 4 \pmod{10}$.
Is this a correct approach? I'm going through the book for examples but it's minimal. The class lectures didn't cover it either.
|
When you render $6x\equiv24\bmod10$, that is correct; but dividing by $6$ must be accompanied by dividing the _modulus_ by the gcd of the modulus itself ($10$) and the divisor ($6$). Thus the modulus is divided by $10/(gcd(10,6))=2$ and so is reduced from $10$ to $5$.
$6x\equiv24\bmod10\implies x\equiv4\color{blue}{\bmod 5}.$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": -1,
"tags": "elementary number theory, modular arithmetic"
}
|
Passing properties to this in cleaner way
Is there another clean way to write this code so that the properties from data array are passed directly to this object.
this.Email = data[0].Email;
this.RealName = data[0].RealName;
this.JobTitle = data[0].JobTitle;
this.UserDID = data[0].UserDID;
this.CreatedDateTime = data[0].CreatedDateTime;
this.ApplicationCount = data[0].ApplicationCount;
this.CountApply = data[0].CountApply;
this.CountResume = data[0].CountResume;
this.LastEmailAction = data[0].LastEmailAction;
this.CountEmailActions = data[0].CountEmailActions;
this.LastResume = data[0].LastResume;
this.LastApply = data[0].LastApply;
|
If you want all the properties from `data[0]` assigned to the object pointed to by `this`, you can use `Object.assign()` which will copy all enumerable properties from the source object to the target object:
Object.assign(this, data[0]);
If you want only select properties, then you can make a list of those properties and loop through them:
['Email', 'RealName', ...].forEach(prop => {this[prop] = data[0][prop]});
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, node.js"
}
|
flutter- !_debugLocked is not true
I have this problem , when I try to use navigator this error will show up
[+1368632 ms] Error: Assertion failed: file:///home/saeedszz/snap/flutter/common/flutter/packages/flutter/lib/src/widgets/navigator.dart:4564:12
!_debugLocked
is not true
I tried everything inside relevant topics in StackOverflow and non of them seemed to work thank you in advanced
|
add this line of code before using Navigator Solved my problem
await Future.delayed(Duration(seconds: 1));
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, flutter, android studio, debugging"
}
|
How can I add a load spinner to my React components, if I'm rendering them on node.js backend?
app.get('/', function (req, res) {
res.render("todo",{}); // todo is my main component
})
I would like to send the client a loader until all components are ready to be shown on the client side. How would you guys implement this?
|
The loader would have to be on the client side because the page can't be reloaded by the server. In your client side code, render a top level component that wraps your other components and displays them instead of the spinner when they're ready.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "node.js, reactjs, express"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.