INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Turning off the options() debugging mode in R
In R I can activate debugging mode through `options(error=recover)`. **How can I turn it off?** I tried `options()` and `options(NULL)` and `options(default=NULL)` but none of them seem to turn of the functionality activated by `options(error=recover)`.
|
Try this :
options(error=NULL)
To show that it works:
options(error=recover)
rnorm("k")
# Error in rnorm("k") : invalid arguments
# In addition: Warning message:
# In rnorm("k") : NAs introduced by coercion
#
# Enter a frame number, or 0 to exit
#
# 1: rnorm("k")
#
Selection: 0
options(error=NULL)
rnorm("k")
# Error in rnorm("k") : invalid arguments
# In addition: Warning message:
# In rnorm("k") : NAs introduced by coercion
|
stackexchange-stackoverflow
|
{
"answer_score": 38,
"question_score": 29,
"tags": "r"
}
|
Проблема с редактированием модуля в Joomla
Собственно видео -
Как корректно отредактировать блок?
|
После анализа данных, первая мысль что приходит,по всей вероятности у вас проблемы с редактором, возможно после сохранения, редактор вносит какие то изменения в html коде тем самым вся вёрстка портиться.
1. Можете,до изменения,попробовать скопировать код в редактор там поменять цену и после весь код вставить в редактор.
2. Можете сравнить код - до и после сохранения в редакторе.
3. Можете попробовать сменить редактор, в глобальных настройках Joomla, на другой редактор и снова сохранить изменения в модуле.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "php, joomla"
}
|
How to draw text on picturebox?
I googled for "Drawing text on picturebox C#" ,but I couldnt find anything useful.Then I googled for "Drawing text on form C#" and I found some code,but it doesnt work the way I want it to work.
private void DrawText()
{
Graphics grf = this.CreateGraphics();
try
{
grf.Clear(Color.White);
using (Font myFont = new Font("Arial", 14))
{
grf.DrawString("Hello .NET Guide!", myFont, Brushes.Green, new PointF(2, 2));
}
}
finally
{
grf.Dispose();
}
}
When I call the function,the background color of the form becomes white(it's black by default).
My questions:
1:Will this work on a picturebox?
2:How to fix the problem?
|
You don't want that call to Clear() - that's why it's turning the background white, and it will cover up your picture.
You want to use the Paint event in the PictureBox. You get the graphics reference from e.Graphics, and then use the DrawString() that you have in your sample.
Here's a sample. Just add a picture box to your form, and add an event handler for the Paint event:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
using (Font myFont = new Font("Arial", 14))
{
e.Graphics.DrawString("Hello .NET Guide!", myFont, Brushes.Green, new Point(2, 2));
}
}
(Note that you won't see the text at design time - you'll have to run the program for it to paint).
|
stackexchange-stackoverflow
|
{
"answer_score": 41,
"question_score": 18,
"tags": "c#, graphics, image"
}
|
Twitter Web Intents - Get follower screenname?
I'm using Twitter Web Intents to check if someone follows me. The problem now is; I am only getting my own screenname as callback in the event object.
twttr.events.bind('follow', function(event) {
alert(event.data.user_id);
});
Is there any way to get the followers screenname, so I can store it in the database. I want to use this as kind of "request invite"-function.
Thanks a lot.
|
The user who performed the follow is not revealed through the web intents javascript events -- it would reveal personal information about the user currently on your site without that user explicitly granting your site/application access to that information.
The best way to track recent followers of an account is using the User Streams API to obtain the events in real time as they happen: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "php, javascript, twitter, webintents"
}
|
Whats is Production enviroment in Laravel?
I am curious to know what the `APP_ENV` entry is used for in Laravel environment files. Is it just for my own usage so I can detect it in code? If I create a fresh Laravel app and change `APP_ENV` to production what will it change under the hood? Nothing?
Thanks!
|
Typically you would have a different .env file on each server. It is up to you if you would like different parts of your app to work differently in different environments. The `.env` file is usually used so that your code can just grab values with the env helper function. This way when you change environments like switching from a test API key to a live API key for example, you can just edit the .env file and not touch the rest of your code.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "laravel"
}
|
How to redirect with previously flashed data?
How can I forward the previously flashed data with `Redirect`. I could use `Session::reflash()` or I could take the data from the session and flash it again but I am looking something like:
Redirect::route('index')
->with('message', 'hello')
->withReflash();
Is there something like `withReflash()` ?
|
As you can see in `RedirectResponse` class, there is no any similar method, so you'll still need to reflash session data manually with `->reflash()`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "laravel"
}
|
Create a cell depending on size of a matrix {in MATLAB}
I am trying to create a cell in the following form...
{'x1','x2','x3','x4','x5','x6','x7','x8'}
If the size of my matrix j is 10, I would like,
{'x1','x2','x3','x4','x5','x6','x7','x8','x9','x10'}
if the size of my matrix j is 3 I would like,
{'x1','x2','x3'}
|
You can use `compose`.
>> compose('x%i', 1:10)
ans =
1×10 cell array
{'x1'} {'x2'} {'x3'} {'x4'} {'x5'} {'x6'} {'x7'} {'x8'} {'x9'} {'x10'}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "matlab"
}
|
Suppose $M$ is $n \times p$ of rank r and that $M$ is partitioned as [A, B \\C, D] where $A$ is $r \times r$ of rank r. Show that $D = CA^{-1}B$.
Suppose $M$ is $n \times p$ of rank r and that $M$ is partitioned as \begin{bmatrix} A & B \\\\[0.3em] C & D \end{bmatrix} where $A$ is $r \times r$ of rank r. Show that $D = CA^{-1}B$.
|
Hint: an elementary transformation gives $$\begin{bmatrix} A & B \\\\[0.3em] C & D \end{bmatrix} \to \begin{bmatrix} A & B \\\\[0.3em] O & D-CA^{-1}B \end{bmatrix} $$ while not changing the rank.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "matrices"
}
|
propositional calculus problem, is this right proof?
&A\implies(B\lor C)&\text{premise}\\\ (2)&B\implies D&\text{premise}\\\ (3)&\neg(D\lor C)&\text{assumption}\\\ (4)&\neg D\land \neg C&\text{De Morgan's laws, from (3)}\\\ (5)&\neg D&\text{directly form (4)}\\\ (6)&\neg C&\text{directly form (4)}\\\ (7)&\neg B&\text{modus tollens, from (2) and (5)}\\\ (8)&\neg B \land \neg C&\text{combining (6) and (7)}\\\ (9)&\neg (B \lor C)&\text{De Morgan's laws, from (8)}\\\ (10)&\neg A&\text{modus tollens, from (1) and (9)}\\\ (11)&\neg (D\lor C)\implies\neg A&\text{combining (3) and (10)}\\\ (12)&A\implies D\lor C&\text{modus tollens, from (11)}\\\ \blacksquare \end{array}$$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "propositional calculus"
}
|
CommandLineRunner VS SmartLifecycle
with `@PostConstruct` and autowiring a `MessageChannel` problem, I found a solution SmartLifecycle.start()
can one also use `CommandLineRunner`?
what is the best way to start work with `MessageChannel rabbitMQ` after a full initialization of the context?
|
Spring Boot's `CommandLineRunner` (or `ApplicationRunner`) is fine.
`SmartLifecycle` is available for any Spring application, not just Boot applications.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "spring boot, rabbitmq, spring cloud stream"
}
|
AngularJS: nested array and view update
I'm having problems updating the view after an `Array` inside an `Array` is updated in the `$scope`.
First i check if the Array member already exists:
$scope.myArray = [];
if(typeof $scope.myArray[someIndex] == 'undefined') {
$scope.myArray[someIndex] = {
name: someName,
data: []
};
}
Then push to `$scope.myArray[someIndex].data`:
$scope.myArray[someIndex].data.push(dataContent);
At this point the view does not update.
Of course if i directly push to `$scope.myArray` it does. Any suggestions?
Edit: Fiddle here
|
It was simpler than it looked.
Based on the response here i am setting an associative array which allows set string keys. If you declare your array as `=[]` you simply cannot set strings as keys.
So i just changed my declaration `$scope.myArray=[]` to `$scope.myArray={}` and voilà, it works.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "angularjs, angularjs scope"
}
|
flash as3 - how do I find an object's index in an array
how do you find an object's index / position within an array in flash actionscript 3? I am trying to set a conditional up in a loop where, if an object's id is equal to the current_item variable, I can return its position within the array.
|
Something like this might help you - this example returns the position of the value 7:
private var _testArray:Array = new Array(5, 6, 7, 8, 9, 8, 7, 6);
public function ArrayTest()
{
trace (_testArray.indexOf(7));
//Should output 2
}
so for your needs:
item variableToLookFor = 9 // Your variable here
private var _testArray:Array = new Array(5, 6, 7, 8, 9, 8, 7, 6);
public function ArrayTest()
{
trace (_testArray.indexOf(variableToLookFor));
//Should output 4
}
This will return a -1 if your item doesn't exist, otherwise it will output the position in the array.
If you need more information you can check here for an article on AS3 Arrays.
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 4,
"tags": "arrays, flash, actionscript 3, actionscript, indexing"
}
|
Install wordpress in rails public directory
I'm trying to install wordpress in my rails app. I downloaded and configure wordpress in my rails/public directory. I also configured wp.config file mysql info. However, after apache restart app/blog/index.php I don't see wordpress setup page but I get a prompt to download index.php file. I must be missing some step here? Here is my apache file
...
PassengerEnabled Off
RewriteEngine On
RewriteBase /testme_wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /testme_wordpress/index.php [L]
...
|
For starters, you would need to configure apache to execute .php files in that directory. There are a couple ways to do that.
You might run into more problems after doing that, depending on how you've set up your rails deploy on apache. If it's with passenger... I'm not sure passenger is going to play well with this plan.
But... why the heck would you want to do this? It sounds like not a great idea. What do you have to gain from having a WordPress in a rails app public directory instead of somewhere else not in the middle of a rails app?
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "ruby on rails, apache, passenger"
}
|
Anchor point with ggplot geom_smooth
I'm making a simple plot with `ggplot2` and I'd like to add a smoothed line that is anchored (fixed) at the first point. I used the trick described here, but it looks like I need to readjust the fitted values by adding the difference `y[1] - predict(lm, data.frame(y=5))`. How do I do this? Is there a better way?
library(ggplot2)
set.seed(3)
d = data.frame(x=5:14)
d$y = log(d$x^2) + rnorm(10,0,2)
ggplot(d, aes(x, y)) +
geom_point() +
geom_smooth(method='lm', formula = y ~ poly(x,4), se=F) +
geom_smooth(method='lm', formula = I(y-y[1]) ~ 0 + poly(x-x[1],4), se=F, color='red')
 ~ 0 + poly(x-x[1],4), data=d) # model without intercept
ggplot(d, aes(x, y)) +
geom_point() +
geom_smooth(method='lm', formula = y ~ poly(x,4), se=F) +
geom_line(data=data.frame(x=d$x,
# the intercept is y[1] - poly(x)[1,]*coeff (it's not computed by lm)
# y = prediction by the model + the intercept
y = poly(d$x,4)%*%m$coefficients + d$y[1]-as.numeric(poly(d$x,4)[1,]%*%m$coefficients)),
aes(x,y), color='red')

{
List<lkpMarketCode> mcodesList = new List<lkpMarketCode>();
LINQOmniDataContext db = new LINQOmniDataContext();
var mcodes = from p in db.lkpMarketCodes
orderby 0
select p;
mcodesList = mcodes.ToList<lkpMarketCode>();
//bind to Country COde droplist
dd2.DataSource = mcodesList;
dd2.DataTextField = mcodesList[0].marketName;
dd2.DataValueField = mcodesList[0].marketCodeID.ToString();
}
|
See revised code below
protected void BindMarketCodes()
{
using (var dataContext = new LINQOmniDataContext()) {
//bind to Country COde droplist
dd2.DataSource = from p in dataContext.lkpMarketCodes
orderby p.marketName
select new {p.marketCodeID, p.marketName};
dd2.DataTextField = "marketName";
dd2.DataValueField = "marketCodeID";
dd2.DataBind();
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 29,
"question_score": 19,
"tags": "c#, asp.net, linq, ado.net"
}
|
What are these symbols next to "merge mode by recursive" in git merge?
When I use `git pull [project name] master` to update my core files, I get a bunch of green plus and red minus signals under "merge made by recursive." What are these symbols and what do they mean?
Here's a screenshot:
!git pull
Thank you for your help.
|
That is an approximation of how many lines have changed. Pluses are for new content and minuses are for what was taken out. Modifications end up with equal amount of both. Deletions are only minuses and new files are all pluses.
Hope this helps!
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 15,
"tags": "git, version control, git merge, git pull"
}
|
Cannot create a Elasticache cluster in sa-east-1 region using boto
I'm trying to create a Redis Elasticache cluster using boto in the sa-east-1 region, and boto is giving me this error message:
{"Error":{"Code":"InvalidParameterValue","Message":"sa-east-1 is not a valid availability zone.","Type":"Sender"},"RequestId":"2q34hj192-6902-11e4-8b4a-afafaefasefsadfsadf"}
with this code:
from boto.elasticache.layer1 import ElastiCacheConnection
self.elasticache = ElastiCacheConnection()
boto.elasticache.connect_to_region(
'sa-east-1a',
aws_access_key_id=settings.AWS_ACCESS_KEY,
aws_secret_access_key=settings.AWS_SECRET_KEY
)
elasticache.create_cache_cluster(
cache_cluster_id='test1',
engine='redis',
cache_node_type='cache.m3.medium',
num_cache_nodes=1,
preferred_availability_zone='sa-east-1',
)
Thanks
|
After searching in boto code, I found that
elasticache = boto.elasticache.connect_to_region(
'sa-east-1',
aws_access_key_id=settings.AWS_ACCESS_KEY,
aws_secret_access_key=settings.AWS_SECRET_KEY
)
elasticache.create_cache_cluster(
cache_cluster_id=cache_cluster_id,
engine=engine,
cache_node_type=cache_node_type,
num_cache_nodes=num_cache_nodes,
preferred_availability_zone='sa-east-1a',
preferred_maintenance_window=preferred_maintenance_window,
)
works.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, amazon web services, boto"
}
|
How to call method of other object in Python?
I am new in python, and I have small problem, I have two classes, and it wrotes this : set_gyro_angle() takes exactly 1 argument (2 given) how can I call **set_gyro_angle()** method from Machine method?
class Gyro(object):
"""gyroskop senzor"""
def __init__(self,gyro_start_angle = 0):
self.gyro_angle = 0
def get_gyro_angle():
return self.gyro_angle
def set_gyro_angle(angle):
self.gyro_angle = angle
return 0
class Maschine(object):
def __init__(self, state = "normal",length = 10,width = 15):
self.length = length
self.width = width
self.gyro = Gyro()
def setPoint(self,alpha):
self.gyro.set_gyro_angle(alpha)
return 0
Main:
maschine = Maschine()
maschine.setPoint()
|
If you want to create an instance method, you need to add an extra argument that will be a pointer to your instance. Usually it's `self`:
class Gyro(object):
"""gyroskop senzor"""
def __init__(self,gyro_start_angle = 0):
self.gyro_angle = 0
def get_gyro_angle(self):
return self.gyro_angle
def set_gyro_angle(self, angle):
self.gyro_angle = angle
return 0
And i think you want `setPoint` to be like this:
def setPoint(self, alpha):
self.gyro.set_gyro_angle(alpha)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, python 2.7"
}
|
How to get thread id of a pthread in linux c program?
In a Linux C program, how do I print the thread id of a thread created by the pthread library? For example like how we can get pid of a process by `getpid()`.
|
`pthread_self()` function will give the thread id of current thread.
pthread_t pthread_self(void);
The `pthread_self()` function returns the Pthread handle of the calling thread. The pthread_self() function does NOT return the integral thread of the calling thread. You must use `pthread_getthreadid_np()` to return an integral identifier for the thread.
NOTE:
pthread_id_np_t tid;
tid = pthread_getthreadid_np();
is significantly faster than these calls, but provides the same behavior.
pthread_id_np_t tid;
pthread_t self;
self = pthread_self();
pthread_getunique_np(&self, &tid);
|
stackexchange-stackoverflow
|
{
"answer_score": 106,
"question_score": 124,
"tags": "c, linux, pthreads"
}
|
How to clear screen on python 3.6 IDLE?
All I wanted to ask that if i want to clear screen in IDLE what method I can use to clear it without closing it. For e.g. I print this statement using:-
print("Prabal Tiwari")
after getting output of this I want to clear the console without closing it. Just like we use "clear" on ubuntu terminal.
|
The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window). From your screenshot, you are using the shell within IDLE, which won't be affected by such things. Unfortunately, I don't think there is a way to clear the screen in IDLE. The best you could do is to scroll the screen down lots of lines, eg:
print "\n" * 100
Though you could put this in a function:
def cls(): print "\n" * 100
And then call it when needed as `cls()`
source: Any way to clear python's IDLE window?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, python idle"
}
|
Angular @ViewChild Error 'Cannot read property nativeElement of undefined"
I am new to Angular and facing this issue.
I want to check value for variable `elementRef` if its empty before data shown because I want to display a chart. This is my code:
**component.ts**
@ViewChild('normalDeviasiDaily', {read: ElementRef}) normalDeviasiDaily: ElementRef;
**component.html**
<div *ngIf="normalDeviasiDaily">
<div #normalDeviasiDaily id="normalDeviasiDaily">
<canvas style="width:100%; height:400px;"></canvas>
</div>
</div>
<div *ngIf="!normalDeviasiDaily">
<skeleton-item height="400px"></skeleton-item>
</div>
My issue is `cannot read property nativeElement of undefined`, has anyone else experienced this, please help me.
Thanks.
|
You are facing this issue because of the `*ngIf` directive won't create a DOM element until the condition becomes `true`.
So instead of using the `*ngIf` use `hidden` property of HTML which will create DOM element but it won't show to the user until condition `false`
<div [hidden]="!normalDeviasiDaily">
<div #normalDeviasiDaily id="normalDeviasiDaily">
<canvas style="width:100%; height:400px;"></canvas>
</div>
</div>
<div [hidden]="normalDeviasiDaily">
<skeleton-item height="400px"></skeleton-item>
</div>
Hope this will help!
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 3,
"tags": "angular, ionic framework, angular5"
}
|
Find number of paths in a 2d binary array (C)
I have been asked this question during an interview, and have been struggling to find an elegant solution (in C), Problem statement:
* You are given a two-dimensional array with M rows and N columns.
* You are initially positioned at (0,0) which is the top-left cell in the array.
* You are allowed to move either right or downwards.
* The array is filled with 1′s and 0′s. A 1 indicates that you can move through that cell, a 0 indicates that you cannot move through the cell.
Write a function in C ‘numberOfPaths’ which takes in the above two dimensional array, return the number of valid paths from the top-left cell to the bottom-right cell (i.e. [0,0] to [M-1,N-1]).
Edit: forgot to mention that the requirement is for a recursive solution
help would be greatly appreciated! Thanks
|
If you are looking for a recursive solution you can use DFS.
DFS (array, x, y)
{
if (array [x][y]==0 || x>M || y>N){
return;
}
if (x==M && y==N){
count++;
return;
}
DFS (array, x, y+1);
DFS (array, x+1, y);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c, arrays"
}
|
Subtract hours from date object in bash
I need to find a time X hours before the previous midnight, thus I would like to subtract X hours from a date object.
**Example**
# Finding the previous midnight
date -d "yesterday 23:59:59"
Mon Jul 11 00:00:00 CEST 2022
**What I want** I would like to find the date X hours before this midnight
x=4
Mon Jul 10 20:00:00 CEST 2022
|
It seems one can just write the following:
date --date 'yesterday 23:59:59 CEST -4 hours'
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "bash, date"
}
|
create tasks in Airflow by looping over a list and pass arguments
edit: **This will work, I defined ex_func_airflow(var_1 = i) which was causing the issue**
I would like to create tasks in airflow by looping on a list.
tabs = [1,2,3,4,5]
for i in tabs:
task = PythonOperator(
task_id = name,
provide_context=False,
op_args = [i],
python_callable=ex_func_airflow,
dag=dag)
task_0 >> task >> task_1
When this is run in airflow the argument that is passed is always the last element in that list.
So i'm essentially running:
ex_func_airflow(6)
five times instead of running
ex_func_airflow(1)
ex_func_airflow(2)
ex_func_airflow(3)
..etc.
How would can I pass the correct arguments for each task?
|
The following codes work for me.
def print_context(ds, **kwargs):
print("hello")
def ex_func_airflow(i):
print(i)
dag = DAG(
dag_id="loop_dag",
schedule_interval=None,
start_date=datetime(2018, 12, 31),
)
task_0 = PythonOperator(
task_id='task_0',
provide_context=True,
python_callable=print_context,
dag=dag)
task_1 = PythonOperator(
task_id='task_1',
provide_context=True,
python_callable=print_context,
dag=dag)
tabs = [1, 2, 3, 4, 5]
for i in tabs:
task_id = f'task_tab_{i}'
task = PythonOperator(
task_id=task_id,
provide_context=False,
op_args=[i],
python_callable=ex_func_airflow,
dag=dag)
task_0 >> task >> task_1
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "airflow, airflow scheduler"
}
|
Authentication Required for jqueryrotate.googlecode.com
I have a web page that uses this link below, now every time I access the page a dialog box shows up asking for authentication with user name and password. I never had that hapenning before. Is this a bug or something new, has anyone seeing this before, is there a way to fix this?
<
Thank you!
|
I believe this behaviour occurs when the script has been deleted or no longer located at that address or permissions deny public access.
I would use a locally hosted copy, if you have one, or a similar script such as `
Edit: Found the author of the script your using on Github
`
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "jquery"
}
|
How to check the compactness of these sets:
How to check the compactness of these sets:
a.the unit sphere in $l_2$ the space of all square summable real sequences with its usual metric i.e.$d({x_i,y_i}) =(\sum_1^\infty|x_i-y_i|^2)^{1/2}$
b.the closure of the unit ball.
I find many equivalent conditions on compact sets but dont know which to use
|
The closed unit ball is not compact in any infinite dimensional Banach space. Thus the closure of unit ball is not compact. If the unit sphere in $\ell_2 $ were compact then the sequence $\\{e_n\\}$ of vectors of orthogonal basis of $\ell_2$ should has a convergent subsequence but this is impossible since $||e_i -e_j| =\sqrt{2}.$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "metric spaces"
}
|
Downloading And Displaying Image From URL
I am trying to essentially create a proxy image loader that can download and return an image. My code is very close, it is displaying an image however I believe some of the bytes just aren't coming out right:
Dim myRequest As WebRequest = WebRequest.Create(URL)
Dim myResponse As WebResponse = myRequest.GetResponse()
Response.ContentType = "image/jpeg"
Response.Clear()
Response.BufferOutput = True
Dim strm As Stream = myResponse.GetResponseStream()
Dim buffer As Byte() = New Byte(4095) {}
Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)
Do While byteSeq > 0
Response.OutputStream.Write(buffer, 0, 4096)
byteSeq = strm.Read(buffer, 0, 4096)
Response.Flush()
Loop
Any help is greatly appreciated.
|
Try this:
Dim theRequest As WebRequest = WebRequest.Create(URL)
Dim theResponse As WebResponse = theRequest.GetResponse()
Dim theStream As Stream = theResponse.GetResponseStream()
Dim theImage As System.Drawing.Image = System.Drawing.Image.FromStream(theStream)
Using theMemoryStream As New MemoryStream()
theImage.Save(theMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg)
theMemoryStream.WriteTo(Response.OutputStream)
End Using
Note: You can also just point an ASP.NET Image server control to the URL of the image you want downloaded, like this:
<asp:Image id="img1" runat="server" ImageUrl="URL" />
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "asp.net, vb.net"
}
|
Failure of syndrome decoding
I am currently decoding a $[8,4,4]$ binary code using syndrome decoding, and I have two words I'd like to decode. Here is the parity-check matrix I am working with:
$H = \begin{pmatrix} 0 & 1 & 1 & 1 & 1 & 0 & 0 & 0 \\\ 1 & 0 & 1 & 1 & 0 & 1 & 0 & 0 \\\ 1 & 1 & 1 & 0 & 0 & 0 & 1 & 0 \\\ 1 & 1 & 0 & 1 & 0 & 0 & 0 & 1 \end{pmatrix} $
For the first word $y_1=(11010011)$, the decoding algorithm didn't work because I didn't find the right syndrome. Indeed, $Hy_1^T=(0110)$ which is not in the syndrome table of $H$. For the second word $y_2=(01010001)$, the decoding worked and gave me a code element $c=(11010001)$. After looking at $c$, I realized that the first word I received was simply $c-(00000010)$, in other words there was a simple error of weight $1$. Is it normal that the algorithm couldn't decode it? Did I make an error computing the syndromes?
|
I get $Hy_1^T = (0010)$, I think you miscomputed.. Note that this is the 7th column of $H$ so the most likely error is $(00000010)$, which it indeed was.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "coding theory"
}
|
At least 2 letters in regex pattern
How can I enforce a minimum of 2 letters in the following regex?
`/^[a-zA-Z0-9\_\-\.\+]+$/`
For the moment I'm stripping out everything that is not a letter and counting the result with `strlen` to achieve what I need.
|
This works:
`^[a-zA-Z0-9_.+-]*(?:[a-zA-Z][a-zA-Z0-9_.+-]*){2,}$`
Expanded:
^
[a-zA-Z0-9_.+-]*
(?:
[a-zA-Z] [a-zA-Z0-9_.+-]*
){2,}
$
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 5,
"tags": "php, regex"
}
|
at which points the function is differentiable
Could anyone help me how to find those points in which $f(x,y)={x^3y\over x^4+y^2}; (x,y)\ne (0,0)$ is differentiable? is there any general formuale for calculationg directional derivative of $f$?
thanks for helping!
|
I would say it's differentiable everywhere where $(x,y)\ne(0,0)$. To see that one simply calculate partial derivates and realize that these are continuous everywhere except at $(0,0)$ - because the partial derivate is a polynomial divided by the denominator squared (as per the formula for derivate of a ratio).
The formula for directional derivate is $f'_v = \nabla f\cdot v$ where $\nabla f$ is the gradient (and $v$ is a vector of unit length). The gradient in turn is $\nabla f = (f'_x, f'_y)$ **if** $f$ is differentiable. If on the other hand $f$ is not differentiable there's no such general formula.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "multivariable calculus"
}
|
Using a bookmarklet to modify the current page, and accessing iFrames
I have been working on making a bookmarklet to make a tiny change to a webpage, for my own personal use as I am browsing the site. I have the bookmarklet dynamically loading jquery (if needed) and can access and modify the page without any issues.
This page has several nested iFrames, the html, I want to modify is within an iFrame which has a different domain then the original page. So I get the:
`Unsafe JavaScript attempt to access frame with URL`
The browser is using the topmost page as the point of origin for my script, which is interesting since it's origin is a bookmark. Is it possible to get around this limitation?
|
There is no way to get around this limitation using only a bookmarklet. When you execute a bookmarklet it executes within the context of the current (top) page. Even though the restriction is called "same origin policy", origin means the context within which the code was executed, not the origin of where the code came from. When you execute a bookmarklet, the code comes from the bookmark, but it executes inside the current page.
To achieve your goal you'll have to create a user script or create an addon/extension. User scripts are supported in Firefox if you install Greasemonkey and natively in Chrome.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, bookmarklet"
}
|
Ruby on rails tutorial $mate Gemfile problem
I'm doing the Ruby on Rails Tutorial and am at 1.2.4 Bundler, where I have to do mate Gemfile but I have Windows and am using vim.
So what do I type instead of mate?
|
`mate` is a command to open TextMate, a Mac editor. Just open Gemfile in your text editor of preference (it's in the root of your Rails project)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, windows"
}
|
Rice's Theorem for Turing machine with fixed output
So I was supposed to prove with the help of Rice's Theorem whether the language: $L_{5} = \\{w \in \\{0,1\\}^{*}|\forall x \in \\{0,1\\}^{*}, M_{w}(w) =x\\}$ is decidable.
First of all: I don't understand, why we can use Rice's Theorem in the first place: If I would chose two Turingmachines $M_{w}$ and $M_{w'}$ with $w \neq w'$ then I would get $M_{w}(w) = M_{w'}(w) = x$. But this would lead to $w'$ not being in $L_{5}$ and $w \in L_{5}$. Or am I misunderstanding something?
Second: The solution says, that the Language $L_{5}$ is decidable as $L_{5} = \emptyset$ because the output is clearly determined with a fixed input. But why is that so? I thought that $L_{5}$ is not empty because there are TM which output x on their own input and there are some which do not.
|
A word $w$ belongs to $L_5$ if for all $x \in \\{0,1\\}^*$ it is the case that $M_w(w) = x$. In particular, if $w \in L_5$ then $M_w(w) = 0$ and $M_w(w) = 1$, which can't both be true. So no word belongs to $L_5$.
|
stackexchange-cs
|
{
"answer_score": 1,
"question_score": 1,
"tags": "turing machines, decision problem, rice theorem"
}
|
Save ggtern plots in R Shiny
What to add in server in order to save the plot as either png or svg?
Does ggsave work with ggtern? (which is an extension to ggplot for ternary plots)
Here is a minimal reproducible example of what I'm trying to do in Shiny:
library(shiny)
library(ggtern)
library(tidyverse)
ui <- fluidPage(
downloadButton("dwnld", label = "Save plot"),
plotOutput("ternary")
)
server <- function(input, output) {
# ternary plot via ggtern
output$ternary <- renderPlot({
data <- tibble(x = 0.2, y = 0.3, z = 0.5)
plot <- ggtern(data, aes(x = x, y = y, z = z)) + geom_point(size = 8)
print(plot)
})
# download the plot
#????????
}
shinyApp(ui = ui, server = server)
|
You can proceed as follows:
myPlot <- reactive({
data <- tibble(x = 0.2, y = 0.3, z = 0.5)
ggtern(data, aes(x = x, y = y, z = z)) + geom_point(size = 8)
})
output[["ternary"]] <- renderPlot({
myPlot()
})
output[["dwnld"]] <- downloadHandler(
filename = "myPlot.png",
content = function(file){
ggsave(file, myPlot())
}
)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "r, plot, shiny, save, ggtern"
}
|
How to modify the header <ul> in superfish menu?
I am trying to convert a html theme into drupal theme using superfish module. I can't figure out what to edit so that my menu has a different ID. So, instead of
< ul id="supermenu-1">I'd like to have < ul id ="jMenu">. Which files do I have to edit? Here is the code
<ul id="superfish-1" class="menu sf-menu sf-main-menu sf-horizontal sf-style-none superfish-processed sf-js-enabled"><li class="active-trail sf-depth-1 sf-no-children" id="menu-218-1"><a class="fNiv sf-depth-1 active" href="/">Home</a></li><li class="sf-depth-1 menuparent" id="menu-443-1"><a class="fNiv sf-depth-1 menuparent" href="/?q=who-we-are">Who we are</a><ul style="float: none; width: 12em;" class="sf-hidden"><li class="sf-depth-2 sf-no-children" id="menu-444-1" style="white-space: normal; float: left; width: 100%;"><a class="fNiv sf-depth-2" href="/?q=project" style="float: none; width: auto;">Project</a></li></ul></li></ul>
|
I'm not sure that this is a good idea because changing that ID may break the scripted functionality of a Superfish menu but that said, here goes...
* I'm assuming you're on Drupal 7.
It's not a template that you'll be doing anything with. It is a theme function. When the Superfish menu is generated by drupal it is in response to a call to the theme_superfish() function. You can find detailed info info on it here: <
So with that in mind, you would want to override that funtion in your template.php file in your theme folder by copying the function to your template.php file, renaming it to YOUR_THEME_theme_superfish($variables) and changing the part at the end where it builds the menu.
If you have several Superfish menus and only want to affect one of them (ie: superfish-1), you can add a conditional to the function so that it only changes the ID of the menu when the conditions match.
Hope that works for you.
|
stackexchange-drupal
|
{
"answer_score": 1,
"question_score": 0,
"tags": "7, navigation"
}
|
if and else statement just not working
Here is my if statement. I'm trying to have two differnt options. One is if the user is logged in and the other of course if they're not. For the life of me I can not get these to work. This is a Word Press site.. Any help here would be awesome. Here is what I have.
<div class="btn btn-success">
<?php if( ! is_user_logged_in()): ?>
<a href="<?php echo $submit_question_link ?>"<?php _e('Ask a question','dwqa') ?></a>
} else {
<?php add_modal_login_button( $login_text = 'Login to Ask a Question', $logout_text = 'Logout', $logout_url = '', $show_admin = false ); ?><?php endif; } ?>
</div>
|
<div class="btn btn-success">
<?php if( ! is_user_logged_in()): ?>
<a href="<?php echo $submit_question_link ?>"<?php _e('Ask a question','dwqa') ?></a>
<? else: ?>
<?php add_modal_login_button( $login_text = 'Login to Ask a Question', $logout_text = 'Logout', $logout_url = '', $show_admin = false ); ?><?php endif; ?>
</div>
You have completely wrong syntax. Your `} else {` isn't even in PHP tags and the alternative syntax that you are using doesn't require braces.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -3,
"tags": "php, html, wordpress, if statement"
}
|
Python list to string loop
If I want to disassemble a string into a list, do some manipulation with the original decimal values, and then assemble the string from the list, what is the best way?
str = 'abc'
lst = list(str.encode('utf-8'))
for i in lst:
print (i, chr(int(i+2)))
gives me a table.
But I would like to create instead a presentation like 'abc', 'cde', etc.
|
Hope this helps
str_ini = 'abc'
lst = list(str_ini.encode('utf-8'))
str_fin = [chr(v+2) for v in lst]
print(''.join(str_fin))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, list, for loop"
}
|
Raphael.JS, prevent event bubbling
In the following fiddle, how can I prevent the click event from bubbling up and calling "AddVertex" when I am dragging and dropping?
To replicate:
1. Click on document (will add a vertex)
2. Click on vertex and drag, upon releasing the mouse addVertex is called which creates another vertex.
I have tried all sorts of combinations of event.stopPropogation, return false etc. in the up function to no joy.
<
|
I was able to make it work by changing it to this:
function addVertex(e)
{
if(e.target.nodeName !== 'circle'){
paper.vertex(e.clientX, e.clientY);
}
console.log("Added vertex.");
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, raphael"
}
|
How can I pass in rendered HTML to a vue property?
I'm using `vue-material` and I have:
<md-dialog-confirm
:md-active="true"
md-title="Make an Outboud Call"
md-confirm-text="Agree"
md-cancel-text="Disagree"
md-content="some <p>HTML</p> here"
@md-cancel="$emit('closeModal')"
@md-confirm="$emit('accept')"
>
For `md-content`, I can pass HTML but want it to be rendered via the Vue.js template engine so I can use my `{{template interpolation }}` as needed.
Can someone please help?
|
You could pass a dynamically generated HTML. If it is just a simple case, you could even do it inline with a template string:
<md-dialog-confirm
:md-active="true"
md-title="Make an Outboud Call"
md-confirm-text="Agree"
md-cancel-text="Disagree"
:md-content="`some text with the value <b>${yourVariable}</b> here`"
@md-cancel="$emit('closeModal')"
@md-confirm="$emit('accept')"
>
Note the `:` in front of `md-content` which is the shorthand for `v-bind`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "javascript, vue.js, vue material"
}
|
What kind of values we can add to List<B> type?
Class A{
public static void main(String args[])
List<B> list=new ArrayList<B>();
list.add("what type of value should we add here");
}
Class B{
int a;
boolean b;
String c;
}
|
You can add:
* references of type `B`
* references of any class which is a subclass of `B`
* `null`
However, if you get a reference out of the list, its compile-time type will always be of type `B` \-- even if the runtime type is actually a subclass, or `null`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -5,
"tags": "java, generics"
}
|
What is A B::* func() defining?
A now deleted question had something similar to this:
struct A { };
struct B {
A read();
};
A B::* read()
{
return A{};
}
This code will give the error:
error: cannot convert ‘A’ to ‘A B::*’ in return
return A{};
As we can see, this is not an out-of-class definition of `read()` but defining a non-member function which returns an `A B::*`. What exactly is an `A B::*` in this case?
|
`A B::*` means "pointer to data member of `B` with type `A`. For example:
struct B {
A x;
};
...
B b;
A B::*ptr = &B::x; // ptr is the variable declared here.
b.*ptr = foo; // same as b.x = foo;
In your code's context, it would mean a function (not a member function) returning a pointer to member. You could have
A B::*foo() {
return &B::x;
}
...
A B::*ptr = foo();
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "c++"
}
|
What is this output "VSs5Range" when iterating through an array in Swift?
In .playground I am just exploring Swift and I was attempting to create an array in an odd way, well, just because.
So this doesn't create an array of items 0, 1, 2,... 50, like I was naively hoping:
let numberArray = [0...50]
and trying to iterate through it:
for num in numberArray {
println("The number is \(num)")
}
gives this console output:
The number is VSs5Range (has 2 children)
What does that mean? Running this in a .swift file, the build fails so the console output doesn't give me anything.
|
What's happening is that you _are_ creating an array with `[0...50]`, but the array has one element: the object `0...50`, which is a new construct in Swift denoting a _range_ (and apparently of the type `VSs5Range`.
So your loop over the initial array is displaying the single array element, which writes itself as the type name and the number of end points it has.
The range is _not_ an array, it's something between a generator (iterators in C#) and a testing unit. You can use it in `switch` statements for example (`case 0..3:`) as well as generate numbers from it (`for i in 0..3 {}`). Personally I find it pretty cool!
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "swift"
}
|
How to kill/Terminate all running process on Sql Server 2008
After executing this query on master db ,it is giving me all running process on all databases, is there any query which will kill all process running on a database .
USE
Master
GO
SELECT
SPID,DBID FROM SYSPROCESSES
WHERE
DBID NOT IN (1,2,3,4) AND SPID >50 AND SPID<> @@spid
|
If you want to force every other connection to disconnect, and you have suitable permissions, you can bounce the database in and out of single user mode:
alter database current set single_user with rollback immediate;
go
alter database current set multi_user;
go
Any other connection to the same database will be terminated.
|
stackexchange-stackoverflow
|
{
"answer_score": 23,
"question_score": 10,
"tags": "sql server 2008, database deadlocks"
}
|
How to replace the first folder name in a URL using the Ionic Rewrite Filter (IIRF)
I'm using the latest version of IIRF to handle URL redirections (301s) for SEO. I'm having problems figuring out the syntax for this rule though.
I'm trying to redirect URLs which match this pattern...
<
to
<
Where the * is the part of the URL I'm trying to preserve.
The closest I've got is...
RedirectRule ^/folder1/$ /folder2/ [I,R=301]
...however that doesn't append the rest of the URL.
Any help would be appreciated.
|
Try this:
`RewriteRule ^/folder1/(.*[^/])$ /folder2/$1 [I,R=301]`
It should pick up everything after folder1/* till next / and append it after /folder2/
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 0,
"tags": "windows, iis, web server"
}
|
interface & integer comparison in golang
I don't understand why the first result is false while second is true.
Any help will be appreciated.
func main() {
var i interface{}
i = uint64(0)
fmt.Println("[1] ", reflect.TypeOf(i), i == 0)
i = 0
fmt.Println("[2] ", reflect.TypeOf(i), i == 0)
var n uint64 = 32
fmt.Println("[3] ", reflect.TypeOf(n), n == 32)
}
// result
// [1] uint64 false
// [2] int true
// [3] uint64 true
Try it here Go playground
|
Because `0` is an untyped constant whose default type is `int`, not `uint64`, and when doing comparison with an interface, the thing you are comparing to must be both the same type and the same value for them to be considered equal.
<
> The equality operators == and != apply to operands that are comparable. The ordering operators <, <=, >, and >= apply to operands that are ordered. These terms and the result of the comparisons are defined as follows:
>
> A value x of non-interface type X and a value t of interface type T are comparable when values of type X are comparable and X implements T. They are equal if t's dynamic type is identical to X and t's dynamic value is equal to x.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 9,
"tags": "go"
}
|
Tensorflow reducing learning rates of saved model
I am working on cnn model which has 4 conv layers and 3 dense layers. dataset have around 28000 images and 7000 test images. The model has saved checkpoints and I have trained it several times and achieved 60 % accuracy so far, and while training learning rate is reduced to 2.6214403e-07 (as i used ReduceLROnPlateau factor 0.4). I have question if I increased the learning rate say 1e-4. and resumed the training how will it effect my model? Is It a good idea?
accuracy vs epoch
|
If your learning curve plateaus immediately and doesn't change much beyond the initial few epochs (as in your case), then your learning rate is too low. While you can resume training with higher learning rates, it would likely render any progress of the initial epochs meaningless. Since you typically only _decrease_ the learning rate between epochs, and given the slow initial progress of your network, you should simply retrain with an _increased_ initial learning rate until you see larger changes in the first few epochs. You can then identify the point of convergence by whenever overfitting happens (test accuracy goes down while train accuracy goes up) and stop there. If this point is still "unnecessarily late", you can additionally reduce the amount that the learning rate decays to make faster progress between epochs.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "tensorflow, neural network, tensorflow2.0"
}
|
Can I use Bootstrap Tooltips inside table cell?
I'm trying to use Twitter Bootstrap Tooltips in table cell. Either this way:
<td><span rel="tooltip" title="Tooltip" data-delay="500">A<sub>p</sub></span></td>
or without a span:
<td rel="tooltip" title="Tooltip" data-delay="500">A<sub>p</sub></td>
Works just fine in both versions, but in each situation Netbeans warns me: " _Attribute`rel` not allowed on element `span`/`td` at this point._".
What am I missing or doing wrong? Is it allowed to have tooltips in table cells?
|
The `rel` attribute is to identify the relationship between current document and the target link. So `rel` can be used in:
* tags link anchor,
* link tag which has stylesheet URL,
In your case, you have used for tooltip which is not a standard defined by W3C. Hence, NetBeans objects and throws a warning.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html table, css tables"
}
|
How to access values from list of dictionaries in a dataframe?
I have a dataframe that has a column with a list of dictionaries and for each dictionary I want to be able to extract the values and put them in another column as list. Please see the picture below for example which shows only 1 row of the dataframe. so for each title shown on the picture I want to extract the values and put them in a list for all the rows in a dataframe
])
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "python, pandas, dictionary, nested lists"
}
|
How to combine wildcards and spaces (quotes) in an Windows command?
I want to remove directories of the following format:
C:\Program Files\FogBugz\Plugins\cache\[email protected]_NN
`NN` is a number, so I want to use a wildcard (this is part of a post-build step in Visual Studio). The problem is that I need to combine quotes around the path name (for the space in `Program Files`) with a wildcard to match the end of the path. I already found out that `rd` is the remove command that accepts wildcards, but where do I put the quotes? I have tried no ending quote (works for `dir`), `...example.com*"`, `...example.com"*`, `...example.com_??"`, `...cache\"[email protected]*`, `...cache"\[email protected]*`, but none of them work.
(How many commands to remove a file/directory are there in Windows anyway? And why do they all differ in capabilities?)
|
`rmdir` _does not support_ wildcards. It only accepts complete filenames.
You can try this alternative:
for /d %f in ("C:\Program Files\FogBugz\Plugins\cache\[email protected]_*") do rmdir /s/q "%~f"
(The `/s/q` arguments to `rmdir` do the same thing as `rm -rf` on Unix. The `for /d` argument makes `for` match directory names instead of file names.)
* * *
_Remember that the`cmd.exe` shell does not do wildcard expansion (unlike Unix `sh`) -- this is handled by the command itself._
|
stackexchange-superuser
|
{
"answer_score": 3,
"question_score": 2,
"tags": "windows, command line, wildcards"
}
|
Twilio - Fetching list of user's incoming phone numbers
we have implemented a connect app, and we are trying to show a list of users' incoming phone numbers, but we are not able to fetch this list and we always get empty list, I have understood the following about the API -
when a user connects his account with a twilio button, then a new sub-account is created for this client app, and the sid for this new sub account is sent in the callback url. for exmaple - lets say the account SID is "111111", and when this account authorizes a connect app, then a new sub account is created with new SID, lets say it is "2222222", this new SID (2222222) is then sent in the callback url of the connect app
the issue I am facing is that this new SID always retuns an empty list of user's phone numbers, so I need some way to authorize the connect app with the actual user SID (111111), can anyone please tell me how can I achieve this.?
thanks.
|
you will need to port your numbers to the sub accounts for them to be used as you have requested. To port the numbers, you need to login to the sub account and then go to porting page.
Once a number is ported, it can be completely used in the sub Account.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "connect, twilio"
}
|
timestamp from Incoming SMS android
How can I get time stamp of incoming sms. Here is my code.
public void onReceive(Context context, Intent intent) {
Log.i("SMS Reciever", "smsReceiver: SMS Received");
Bundle bundle = intent.getExtras();
if (bundle != null) {
Log.i("SMS Reciever", "smsReceiver : Reading Bundle");
Object[] pdus = (Object[])bundle.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage sms = SmsMessage.createFromPdu((byte[])pdus[i]);
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "Send From: "+ senderNum + "; message: " + message);
|
Soon as you receive an SMS on your device, Broadcast receiver handles it, as you've codded it. so to get time at which SMS is received, you may use:
long smsReceiveTime = System.currentTimeMillis();
after your
String message = currentMessage.getDisplayMessageBody();
and same way, for date:
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "android"
}
|
Show that $\int_0^\infty\frac{\arctan(\mathrm{πx})-\arctan(\mathrm x)}xdx=\;\frac{\mathrm\pi}2\ln(\pi)$ using 12th grade calculus.
I have to show that $\int_0^\infty\frac{\arctan(\mathrm{πx})-\arctan(\mathrm x)}xdx=\;\frac{\mathrm\pi}2\ln(\pi)$ using 12th grade calculus wich means single variable calculus.
What I've tried:
First I tried to make a single arctan from those 2: $\arctan(\mathrm{πx})-\arctan(\mathrm x)=\arctan(\frac{(\mathrm\pi-1)\mathrm x}{1+\mathrm{πx}^2})$ as you can see it's still not very pleasant... and it looks like I don't get anywhere with this..
|
Let $I(a) = \int_0^\infty \frac{\arctan(a x)-\arctan(x)}{x}dx$. Then $I'(a) = \int_0^\infty \frac{1}{x}\frac{x}{1+(ax)^2}dx = \frac{1}{a}\frac{\pi}{2}$. So, $I(a) = \frac{\pi}{2}\ln(a)+C$. Letting $a=1$, we see that $0=I(1)=\frac{\pi}{2}\ln(1)+C \implies C=0$. So, $I(a) = \frac{\pi}{2}\ln(a)$.
|
stackexchange-math
|
{
"answer_score": 13,
"question_score": 5,
"tags": "calculus, integration, definite integrals"
}
|
PhpStorm not recognizes a PHP class
this morning I faced with this issue and I don't know really how to solve this.
Here's an image and a video: <
P.S. When I refactor the file to "filename.PHP" PhpStorm detects it but if I change it back to "filename.php" PhpStorm won't detect it as a PHP file.
|
1. `Settings/Preferences | Editor | File Types`
2. Locate `Text Files` entry there
3. Remove unwanted pattern from the bottom list (most likely will be `LoginListener` or `LoginListener.php`
|
stackexchange-stackoverflow
|
{
"answer_score": 22,
"question_score": 8,
"tags": "php, phpstorm"
}
|
Does Firefox v42+ support CSS Grid?
I'm doing some programming with CSS Grid and was tasked with making sure it's compatible with Firefox v42+ and IE 11+. According to caniuse.com it isn't supported by IE 11 fully nor v42 of Firefox. I have no clue how correct this information is and just wanna double check and make sure it is correct. I also can't find the documentation to check this info. Anything helps!
Edit: The duplicate answered my question.
|
Neither of the browsers you mention fully support Grid. IE uses an old syntax, while Firefox 42 requires a flag to be turned on. The Caniuse data matches what's on MDN: <
If you need to support these browsers, you should probably use a different layout method.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "css, internet explorer, firefox, css grid"
}
|
error: "va_start" used in Win64 ABI funtion getting thi seero in clang help me to solve this?
I have compiled but while compiling with CLANG in ubuntu im getting error like this error: "va_start" used in Win64 ABI funtion. can anyone help me?
|
Since your function is `static` _and_ I doubt you're passing it anywhere as an argument, I believe you can just remove `EFIABI` here (and in the declaration). `EFIABI` is a 4-register calling convention for which GCC seemingly does not support variable arguments.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "c++, c, clang, covariance"
}
|
OpenSSL for making iOS certs on a windows machine - do I need a server?
I'm running Windows 7 Pro, not a server, and am wondering if I need a server to run openssl for the purpose of setting up my iOS certs for PhoneGap?
I've installed opensll, and am following instructions for making the cert here: <
But when I enter openssl genrsa -des3 -out ios.key 2048 it tells me 'opensll is an invalid command', displays a list of standard commands, and I cannot find the file ios.key on my machine.
I'm running the command window by shift-right-clicking on the bin folder in OpenSSL-Win64
Am I on the right track?
Thanks for your time and help.
|
Never mind - for anyone else looking, I found a great guide to the whole process here:
<
I was running the Shining Light installation of openssl from my own command window instead of running openssl.exe, which is why I was getting the 'opensll is an invalid command' error. But even so, errors about missing equal signs from the openssl.cnf (which I hadn't touched) kept displaying when running openssl.exe. I instead used a different openssl installation, found in the above link, which worked fine.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "windows, cordova, openssl"
}
|
Keeping the context of a function
I'd like to know whether it was possible to do this with Matlab or not.
I have a script that create and initialize a lot of variable. In my main program I call this script to do all the initialization then I go on manipulating the data.
I want to improve that script and make it function-like : I'd like to have different version of my program that will use the slightly different initialized values.
However I can't do that because I can't call a script with arguments and if I create a function with that script I won't recover the context of the function (and I don't want to modify the script that much so I can return things).
So I'm kinda stuck here. Does anyone know what I should do?
|
I can suggest a few options:
1. Save the desired variable to a mat file with `save`. In the script file, you can then `load,` and if desired delete the file.
2. Try to save same of the variables as global (to do that, declare `global` in front of the desired variables in both the function call, and the scripts):
To do the last option:
global Vari
Vari = sum (....);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "matlab, function"
}
|
How can I create the following Android bash script?
When I type:
adb devices
My output is (this can be variable, it can list 10 or 20 etc):
List of devices attached
0280414640c133d7 device
TA054085R1 device
Afterwards I'd like to run:
adb install MyApp 0280414640c133d7
adb install MyApp TA054085R1
How can I get this going in a bash script?
|
I'm not sure how robust you need your solution to be, but something like this will work with the case you describe above:
#!/bin/bash
echo "Deploying SONR to devices..."
#install SONR
for foo in `adb devices | egrep 'device$' | cut -d ' ' -f1`
do
adb -s $foo install SONR.apk
done
It is no doubt possible to replace the ugly `egrep` piped through `cut` with a single call to `sed` or `awk` or even a `perl` one-liner.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, bash, shell, scripting, adb"
}
|
Is $L^1(\Omega)$ isomorphic to $l¹$?
I'm trying to understand a statement in the Brezis book, that $L^1(\Omega, \mu)$ is not reflexive. He divides the problem into two parts: one in which $\mu$ is a non atomic measure and another in which $\mu$ is purely atomic, i.e, $\Omega$ consists of a infinite countable number of distinct atoms.
**My question:** In the second case in which $\Omega$ consists of a infinite countable number of distinct atoms, how to show that $L^1(\Omega)$ isomorphic to $l¹$?
|
Suppose that $\mu$ is purely atomic and there are countably many atoms, call them $x_1, x_2, \ldots$. Let $f\in L_1(\Omega)$. Then
$$\int\limits_{\Omega} f(x)\,\mu({\rm d}x) = \sum_{n=1}^\infty \int\limits_{\\{x_n\\}} f(x)\,\mu({\rm d}x) = \sum_{n=1}^\infty f(x_n).$$
This shows that the map $f\mapsto (f(x_n))_{n=1}^\infty\in \ell_1$ is an isomorphism. As point out by Daniel Fisher, it need not be isometric. To make it such, just define
$$f\mapsto \left(\frac{f(x_n)}{\mu(\\{x_n\\})}\right)_{n=1}^\infty.$$
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 2,
"tags": "real analysis, functional analysis, reference request"
}
|
How to use NSTableView's selectedRowIndexes?
I'm just learning some basic programming in Objective C and Cocoa. I'm trying to get some data from NSTableView. Based on what I read in one tutorial, I wrote this:
NSArray * items = [[itemsTableView selectedRowEnumerator] allObjects];
But then I learned that `selectedRowEnumerator` was deprecated already in 10.3 Panther and that I should use `selectedRowIndexes`.
The problem is, I didn't find how to actually use the returned `NSIndexSet` to achieve the same result as with code written above.
So, If anyone could give me a tip, I would be very grateful. Thanks.
|
You can loop through the indexes of an `NSIndexSet` like this:
- (void) goThroughIndexSet:(NSIndexSet *) anIndexSet
{
NSUInteger idx = [anIndexSet firstIndex];
while (idx != NSNotFound)
{
// do work with "idx"
NSLog (@"The current index is %u", idx);
// get the next index in the set
idx = [anIndexSet indexGreaterThanIndex:idx];
}
// all done
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "objective c, cocoa, macos, nstableview"
}
|
Intersection on circle of vector originating inside circle
I have a circle. Inside the circle is a point. I have a vector originating at this point. I'd like to know what point on the circle this vector intersects. Here is a drawing:
The red dot is the point I am trying to determine.
I know these things: the center of the circle, the origin of the vector, and the direction of the vector.
I know this is basic stuff, but I'm still having trouble. Most of the Googlings bring me to line-circle collision, which is related but not quite the same. Thanks for any help you can provide!
|
Elementary vector algebra.
O — center of circle (vector)
r — its radius (scalar)
A — origin of ray (vector)
k — direction of ray (vector)
Solve `(A + kt - O)² = r²` for scalar `t`, choose positive root, and `A + kt` is your point.
**Further explanation:**
`.` is dot product, ² for a vector is dot product of the vector with itself. Expand LHS
(A + kt - O)² = (A - O)² + 2(k.(A - O))t + k²t².
The quadratic is `k²t² + 2(k.(A - O))t + (A - O)² - r² = 0`. In terms of your variables, this becomes `(rayVX² + rayVY²)t² + 2(rayVX(rayX - circleX) + rayVY(rayY - circleY))t + (rayX - circleX)² + (rayY - circleY)² - r² = 0`.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 4,
"tags": "math, geometry"
}
|
Delete a line with a pattern ONLY when the previous line has another specific pattern
I am trying to delete all lines with a specific pattern ( **PATTERN 2** ) only when the previous line has another specific pattern ( **PATTERN 1** ).
The code looks like this:
PATTERN 1
PATTERN 2 <- This line should be deleted
NNN
PATTERN 2
PATTERN 1
PATTERN 2 <- This line should be deleted
blabla
PATTERN 1
blabla
PATTERN 2
PATTERN 1
PATTERN 2 <- This line should be deleted
**PATTERN 2** should be deleted ONLY when the previous line is **PATTERN 1**
* I know how to delete all lines with **PATTERN 2** : sed '/PATTERN 2/d'
* and I can delete all lines that follow **PATTERN 1** : sed '/PATTERN 1/{n;N;d}'
However, I don't know to apply both requirements to a single AWK or SED.
How can this be done with AWK? Thank you in advance,
|
Assuming by "PATTERN" you mean "partial regexp match" since that's what you use in the sed scripts in your question:
$ awk '!(/PATTERN 2/ && prev~/PATTERN 1/); {prev=$0}' file
PATTERN 1
NNN
PATTERN 2
PATTERN 1
blabla
PATTERN 1
blabla
PATTERN 2
PATTERN 1
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "awk"
}
|
Python comtypes read Outlook file
I'm using comptypes python 3.6 and trying read office documents as i need to extract the text from these files.
I understand that for word and ppt this is how to open files using comtype
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(filename)
ppt = comtypes.client.CreateObject('PowerPoint.Application')
prs = ppt.Presentations.Open(filename)
How about for Outlook files (.msg)? I tried the following code but doesn't work
ol = comtypes.client.CreateObject('Outlook.Application')
msg = ol.MailItem.Open(filename)
|
I've resorted in using the approach done in this thread instead of what I was testing out on my question.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, comtypes"
}
|
Managing multiple dependency versions with OSGI/Maven
I've got a Maven build for an OSGI project I'm working on. I'd like to use some functionality from Google's guava-osgi library, version 11.0.1.
One of the projects I'm depending on has a dependency on guava-osgi, version 10.0.0. I know that having multiple versions for a particular dependency is feasible, but I'm having a little trouble with it.
Specifying the dependency on 11.0.1 in my project's pom compiles just fine, but when I run my unit tests, Java's pulling in version 10.0.0, which results in a runtime error. Specifically, one of the classes in 11.0.1 has the same name as an interface in 10.0.0, so Java barfs when I try to instantiate it.
Is there a way to do this elegantly?
|
1. Check dependency tree with maven-dependency-plugin: `mvn dependency:tree`
2. Find all dependencies that are active in test scope with `guava-osgi:10.0.0` version
3. Exclude `guava-osgi:10.0.0` from test scope
...
<dependency>
<groupId>dep1-groupid</groupId>
<artifactId>dep1-artifactid</artifactId>
<version>dep1-version</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.googlecode.guava-osgi</groupId>
<artifactId>guava-osgi</artifactId>
</exclusion>
</exclusions>
</dependency>
...
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "java, maven, osgi, dependency management"
}
|
Is there any app to show sun position and possibly also angle for particular times?
I was invited to shoot an particular event outdoors. Is there any tool which could help me to avoid backlight?
I searched the web and found apps like Photoephemeris, Suncalc etc. but none of them shows me sun movement during time.
I does not have to implement map - something like compass rose with time, sunset and sunrise would be enough.
Something to tell me not to put tripod with camera towards southwest from 5 to 6pm etc.
is there such a tool?
thanks
|
Maybe try the free "sunshine compass" Android app, it simply activates the phone camera showing the camera feed overlayed with a curve of the sun's path, annotated with time points, using GPS, so you can point your phone in different directions and visually determine the where and when of the sun's location.
|
stackexchange-photo
|
{
"answer_score": 1,
"question_score": 4,
"tags": "outdoor, sunlight, backlight"
}
|
How do I make a UITableView concurrent?
The `UITableView`'s data source is from an external server. Anyone could update / delete / add data to it at any time.
The problem is that `UITableView` likes to complain whenever data is not consistent:
`The number of rows contained in an existing section after the update (X) must be equal to the number of rows contained in that section before the update (Y), plus or minus the number of rows inserted or deleted from that section and plus or minus the number`
How do I create a `UITableView` that lets me delete, add, update and refresh without having to be consistent?
I use Swift 3.
|
"How do I create a `UITableView` that lets me delete, add, update, and refresh without having to be consistent?"
You don't. The model data presented in the table view must match the table view itself. If you delete cells from the table view, you have to delete those entries in your model so that when the table view asks the data source for info on your rows/sections, they match.
You should cache your server data locally and use it to populate the table view. If the user makes a change to the local copy, you should batch-update the server with your changes.
Likewise, if the server updates the data, you should batch-update the local copy and then tell the table view to reload it's contents.
It's hard to give a specific answer without a more specific description of what you're trying to do.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, swift, uitableview, concurrency"
}
|
Hibernate: No type name
Hello I am using Hibernate 3.6 with XML mapping (no annotations).
I tried to create instance of Configuration, but it failed. The only message Hibernate told me was this:
org.hibernate.MappingException: No type name
**Yep, that's it**. No mapping file name, no entity name, nothing. I am pretty much desperate here, I really have no idea what to do. Maybe there are more options to put in `hibernate.cfg.xml`, maybe some advanced logging.
Do you have an idea how to deal with this? Getting more info about this exception or making Hibernate to be more chatty would be great. Thanks
|
There's this unresolved bug against hibernate-core that looks like what you're experiencing. You can check the link there to see the source code where the exception is being thrown. If you put a breakpoint at the line where the exception is thrown, you can probably gather enough information from the debugger to see where the problem is. Otherwise, if you can localize the problem and post some mappings, someone might be able to spot the problem for you.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "hibernate"
}
|
SE login OpenID redirect blocked in Chrome Canary
It is not possible for me to logon to SE using Chrome Canary. I have to use Canary, because a recent bug prevents flash from loading at all in Chrome for some sites.
Canary seems to adopt security BCPs that are incompatible with what SE does. The following errors are displayed after clicking "StackExchange Account" on the login page:
 for a file programmatically
This is what I want to get:
!enter image description here
I know it's possible to get because Total Commander shows exactly the same info, although in a differently styled window. Which makes me think that there must be a way of querying this text for any given file.
|
The `IQueryInfo` interface is what you want. Briefly (psuedo-code only, sorry):
PCUITEMID_CHILD pidl = <PIDL of item in question>
IShellFolder* psf = <IShellFolder parent folder of item in question>
IQueryInfo* pqi;
if (SUCCEEDED(psf->GetUIObjectOf(hWnd, 1, &pidl, 0, &pqi)))
{
LPWSTR lpszTip;
if (SUCCEEDED(pqi->GetInfoTip(0, &lpszTip)) && lpszTip)
{
// do something with the tip, and then free it
CoTaskMemFree(lpszTip);
}
}
Once you have the text you can, of course, display it any way you like.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "windows, winapi, windows shell"
}
|
How to change brightness of image in JLabel?
I have an image imported in JLabel. Is there any built in function in Java that i can use to change brightness and contrast of that image with a Slider?
|
You may try RescaleOp class (pixel-by-pixel rescaling) methods.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 6,
"tags": "java, swing"
}
|
Interpreting pinout and the transfer function for this sensor from its datasheet
I have this pressure sensor with the following details from the datasheet:
** What is V1, V2 and Vex?
**2-)** And how can I obtain the transfer function equation? Is it Vout = Vs* (.009*P-.095) ± Error ?
|
The fact that the pins are listed by name in the package spec, but not further defined, indicates to me that they're either ports for automated end-of-line testing or for diagnostic purposes. Less likely, but quite possible, is that they're special purpose functions such as fine adjustments or reference voltages that are used only internally or by a few select customers. In any case, the only advice given is on page 4, where they're listed as no connects. I'd take that to the bank, as it's possible that some connected conditions could damage the sensor.
The transfer function you listed agreed with the one on page 5, and matches the graph as well as the specs table. Since it's directly proportional to Vs, if you want good accuracy you should regulate Vs pretty tightly, or alternatively use Vs as a reference to your ADC if you're digitizing the output.
|
stackexchange-electronics
|
{
"answer_score": 2,
"question_score": 2,
"tags": "sensor, datasheet"
}
|
Choosing a source control system: logical next steps after VSS
I've been using Git for the past few months and love it.
I looked into how to host it in a corporate environment. Considering a 10 person team who use Visual SourceSafe, programming in Coldfusion, Powerbuilder, PHP and a bit of .NET, I found, to my surprise, that the Git 'server' tooling is still fairly rudimentary.
Git in a company - hosting own server
**Question** Apart from SVN, what other source control options would be a logical next step after VSS? Paid options are fine.
Something with nice tooling, that isn't scary would be great :-)
|
Perforce (non-free) offers a lot of features and tools. I heard Google uses it. Perforce offers more advanced branching and merging capabilities than SVN.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "svn, git, version control, visual sourcesafe"
}
|
what is the best way to bind ListView (WPF) with same icon for each item
I have a list view that is binded to some object I've created. The binding is working perfect, but I want to add icon to each item in my list. All the items should have the SAME icon (should be defined prior as "file.ico"). What is the best to implement this? Thanks.
|
Use an ItemTemplate, e.g:
<ListBox ItemsSource="{Binding MyItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="/Images/.." Width=".." Height=".." />
<TextBlock Grid.Column="1" Text="{Binding Name}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You should use a `ListBox` unless you have a specific reason to use a `ListView`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, wpf controls"
}
|
How to view the app directory from iphone app
I try to find out how I can look into app directory from my iphone app. Is there a way see the folder structure of my app within xcode?
Thanks for any hints.
|
Just gonna try answering. How about logging it, like this:
//App Directory & Directory Contents
NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSLog(@"App Directory is: %@", appFolderPath);
NSLog(@"Directory Contents:\n%@", [fileManager directoryContentsAtPath: appFolderPath]);
or
Inside Xcode:
* Window > Organizer > Projects
* Select Project
* "Derived Data" has a small arrow, it will reveal the location in Finder
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "iphone, xcode"
}
|
Change textbox highlight color
,0 0 8px rgba(102,175,233,.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);
}
The colors (both the hex #66afe9 and the rgba(102,175,233,.6)) in there are what make it blue, so you would need to change those values (though I don't know enough about bootstrap to know if you're probably preprocessing the CSS and would therefore change some variable value somewhere instead of plain CSS).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "html, css, twitter bootstrap 3"
}
|
M1 docker preview and keycloak 'image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8)' Issue
I just downloaded Docker Preview v3.1 < and tried running keycloak.
Anyone else running into this issue?
docker run -p 8080:8080 -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin quay.io/keycloak/keycloak:12.0.4
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
|
Just found this post: <
Using this image, I am now able to startup keycloak. <
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 136,
"tags": "macos, docker, keycloak, apple m1"
}
|
Inversed logarithmic scale in gnuplot
When plotting data which are very dense in small ranges of y, the logarithmic scale of gnuplot is the right scale to use.
But what scale to use when the opposite is the case? let's say most y values of different curves are between 90 and 100. In this case I want to use something like a inversed logarithmic scale. I tried a log scale between 0 and 1 but gnuplot wants me to choose a scale greater than 1
How can I achieve this?
|
You are right, you can use the inverse of the logarithmic function, which is the exponential. But gnuplot only supports logarithmic scales, so you have to do the conversion on your own:
plot "myData" using 1:(exp($2))
You will also have to handle the axis tics on your own. Either you just set them via a list like
set ytics ("0" 1.00, "1" 2.72, "2" 7.39, "3" 20.09, "4" 54.60, "5" 148.41)
or you use the `link` feature for axes of gnuplot 5. The following code uses the y2axis (right y-axis) to plot the data and calculates the tics on the left y-axis from the right one.
set link y via log(x) inverse exp(x)
plot "myData" using 1:(exp($2)) axes x1y2
_Side note: Always remember that a non-linear axis is hard to understand. Logarithmic scales are common, but everything else not. So, be careful when presenting the data_
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "gnuplot, scale"
}
|
How can I deserialize the incoming AWS Lambda request into a lombok @Value or @Data class?
If I have a
import lombok.Value;
@Value
public class IncomingRequest {
String data;
}
and try to have a `RequestHandler` like
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaHandler implements RequestHandler<IncomingRequest, String> {
@Override
public String handleRequest(IncomingRequest request, Context context) {
...
}
}
I only ever get empty `request` objects or with some other configuration I get deserialization exceptions.
What do I need to do to enable AWS Lambda to properly deserialize into my custom class?
|
AWS Lambda uses Jackson to deserialize the data and as such needs a no-arg constructor and setters for the properties. You could make those setters public but at that point you have a mutable class and you generally do not want that for pure data classes. "Luckily" Jackson uses reflection anyway and therefore can (and does) access private methods. Instead of `@Value` you can therefore use
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter(AccessLevel.PRIVATE)
public class IncomingRequest {
String data;
}
That way Jackson can properly parse the incoming JSON and your class remains sort-of immutable. Obviously you can add more constructors via annotation to that class if you want to as long as you make sure a no-args constructor is also still present. Add you can safely add `@ToString @EqualsAndHashCode` as well if you want to.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, amazon web services, aws lambda, jackson, lombok"
}
|
How does market work when there are few buyers and few sellers at the same market?
If I understand it right, correct term for such situation is bilateral oligopoly.
|
Hendricks and McAfee (2007) offer a theory of **bilateral oligopoly**. They consider the example of the wholesale gasoline market on the west coast of the United States, which is composed of a small number of large sellers and large buyers who compete against each other in the downstream retail market. They are specifically interested in the effect of a merger of vertically integrated firms on the whole sale and retail markets. They discuss price and cost formation. They also offer a review of the literature.
The extreme case is **bilateral monopoly** with one buyer and one seller. Tirole's Industrial Organization textbook (pp. 21-25) offers a nice discussion of how this market works and in particular price behavior under bargaining and contracting.
|
stackexchange-economics
|
{
"answer_score": 2,
"question_score": 2,
"tags": "microeconomics, oligopoly"
}
|
Distinct column with primary key column
Distinct column count differs when adding the primary key column in the Select query
The count distinct for supplier_payment_terms is 110, but when adding the PK column, the count changes to thousands.
select distinct supplier, unique_id from indirect_spend;
I expect the same record count of 110 when including the PK column in the select. The Select must only include the unique_id of the supplier.
|
You can use aggregation to get _example_ primary keys:
select supplier, min(unique_id), max(unique_id)
from indirect_spend
group by supplier;
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "sql, distinct"
}
|
Probability of random walk returning to 0
Given a symmetric 1-dimensional random walk starting at 0 -- what is the probability of the walk returning $k$ times to 0 after $2N$ steps?
I know that the total number of paths it can take is $2^{2N}$. My problem is finding the total number of paths returning to 0. Also, since you can only return at even $k$'s, the no. of possible hitting points is $ {{N}\choose{k}}. $
|
Let $T$ denote the first return time to $0$. The generating function $E_0(s^T)$ of $T$ for the random walk starting at $0$ is such that $$E_0(s^T)=sE_1(s^T),$$ where $E_1(s^T)$ is the generating function of $T$ for the random walk starting at $1$. By the same first-step argument, $$E_1(s^T)=\frac12s(1+E_2(s^T)),$$ where $E_2(s^T)$ is the generating function of $T$ for the random walk starting at $2$. By the Markov property, $$E_2(s^T)=E_1(s^T)^2.$$ Solving this system in $E_0(s^T)$, $E_1(s^T)$ and $E_2(s^T)$ yields $$E_0(s^T)=1-\sqrt{1-s^2}.$$ Thus, the generating function of the $k$th return to $0$ starting from $0$ is $$E_0(s^T)^k=\left(1-\sqrt{1-s^2}\right)^k.$$ These functions have series expansions in powers of $s^2$. The probability that the $k$th return to $0$ occurs after exactly $2N$ steps is the coefficient of $s^{2N}$ in $E_0(s^T)^k$, that is, $$ (-1)^N\sum_{i=1}^k(-1)^i{k\choose i}{i/2\choose N}. $$
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 5,
"tags": "probability, random walk"
}
|
How to send an object in postman
I was trying to make a post request to the api route I just created.

console.log(req.body)
const { firstName, lastName, email, phoneNumber } = req.body
console.log(`Variable Values`, firstName, lastName, email, phoneNumber)
Here I am getting typeof as `String` and body as this
{
firstName: "Varun",
lastName: "Bindal",
email: "[email protected]",
phoneNumber: "+91-8888"
}
What I want is that the typeof to be object so I can de-structure it, How can I make a request from postman in this case (I don't want use JSON.parse)
|
You should change the type of body from raw text to JSON (application/json) by clicking on the text button right next to your GraphQL option.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, node.js, postman"
}
|
How to get url path info into a form variable
I am creating a module for Drupal 7 that has form that will appear in a block. What I would like to do is get the url for the page that the block appears on (when displayed to the user) and store it in a hidden variable so that it can be processed later. Is this possible and how would you go about doing it?
Thanks
|
How to store the data depends on what you want to achieve with that data or how you want to process it afterwards. The easiest solution for that is probably using watchdog() after form submission:
watchdog('myblock', $url);
To get the current path there is current_path():
$url=current_path();
Please beware that you must disable caching for that block to have the code in your block processed all the time. Here is an answer on how to create a block programmatically in Drupal.
|
stackexchange-drupal
|
{
"answer_score": 0,
"question_score": 0,
"tags": "7, forms, blocks, uri"
}
|
iOS 10 - uploaded build showing success in xcode but its not available in the app store content?
**Xcode** upload showing success while upload but not showing error message in the app store content page
Note: already requested more information to apple team
|
With the reference of the video, I resolved: <
I missed NSCameraUsageDescription field in the info.plist
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "xcode, app store connect"
}
|
How to set the value of a symbol in a package
I am writing a package like this:
BeginPackage["HNotation2`"];
Begin["`Private`"];
HTransR=3;
End[];
EndPackage[];
When I load the package, it seems that the symbol `HTransR` is not defined. Is there something wrong with the way that I'm assigning a value to the symbol in the package?
|
With respect, I believe `Begin["`Private`"]` is acceptable, and perhaps preferable. `Begin["Private`"]` establishes a context `"Private`"`. This is fine, but if two packages do that they will share that context. `Begin["`Private`"]` establishes context `HNotation2`Private``. This will be private to this package only.
The reason `HTransR` appears to be undefined is that it is defined within context `HNotation2`Private``, which is not on the `$ContextPath` \-- it can be accessed by its full name as `HNotation2`Private`HTranR`.
If you wish it to be accessible by its short nme, you could place a usage statement for it before `Begin["`Private`"]`, or just define it there. Then it will be in the package context, which is placed on the context path when the package is loaded.
|
stackexchange-mathematica
|
{
"answer_score": 4,
"question_score": 4,
"tags": "packages"
}
|
invisible border around input field not working
this is the code to my search bar and button. i am using images as background and would like the input field border to dissappear, however it does not seem to be working
.masthead-search input[type=search] {
background: url( no-repeat;
float: left;
border: 1px solid #fff;
font-size: 11px;
padding: 0 10px;
width: 130px;
height: 28px;
line-height: 28px;
border: none;
-webkit-appearance: none;
border-radius: 10px;}
this is my code in the php file for wordpress:
<input type="search" class="field" name="s" style="border: 1px #fff;"value="<?php echo esc_attr( get_search_query() ); ?>" id="s" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder', 'wpex' ); ?>"/>
|
You have two border definitions in your CSS:
.masthead-search input[type=search] {
....
border: 1px solid #fff;
...
....
border: none;
-webkit-appearance: none;
border-radius: 10px;}
and a style applied to your field (which is missing one parameter):
<input type="search" class="field" name="s" style="border: 1px #fff;"
What shall the browser do? He goes with the last one, probably, which is 1px border.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html, css, input"
}
|
Проблема прокрутки overflow на мобильном устройстве
Всем привет. Столкнулся с одной проблемкой. У меня прокрутка реализована через overflow:hidden; , на пк все работает отлично, но когда пытаешься прокручивать на телефоне, то сначала надо тыкнуть на div(ленту новостей) и только потом заработает прокрутка, до этого если пытаться прокручивать ленту новостей, то прокручивается вся страница.
Много чего пробовал и ничего не повезло. Пробовал фиксировать элементы, пробовать webkit-skrollbar и т.д...
|
Стоит попробовать поставить overflow:auto; Скорей всего скрипт строит под мобильное отображение свои теги. Надо посмотреть код, чтобы знать что там происходит.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html, css"
}
|
Making calls to an ASP.NET 5 Web API from a C# class library
I have a Web API that was created with ASP.NET 5. I have a repository class library (package) that needs to make calls to this web api using some kind of http client.
What would be the correct package to reference if I want to keep everything within ASP.NET 5? I tried referencing: "Microsoft.AspNet.WebApi.Client": "5.2.3" but it doesn't work with Platform 5.4
|
<
You should use the modern HttpClient class from System.Net.Http on NuGet, which supports DNXCore.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, asp.net, .net, asp.net web api, httpclient"
}
|
How to maintain an application for an old Linux kernel
I'm tasked with maintaining some software for an old i486 device running Linux 2.6.18.
I managed to compile the source code on an up to date Linux system but when I run it on the device it crashes. Running strace shows that the futex operation FUTEX_WAIT_PRIVATE is not implemented. Makes sense since it was added in Linux 2.6.22.
What would be the reasonable way of maintaining this software? Sure I can find an old image of a Linux distro but that would lock me into an environment that has no support and hard to find the packages I need.
|
I ended up installing Debian 4.0 in a VM. I edit the code on the host OS and ssh into the Debian 4.0 VM to compile.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "linux, legacy, i386"
}
|
How to remove Children from an AbsoluteLayout in Xamarin.Forms?
In my app I use a `Xamarin.Forms` `AbsoluteLayout`. I have a custom menu bar. When I clicked on a menu button, the main content (a `View`) of my `AbsoluteLayout` is supposed to be replaced.
So far I can only achieve that by adding a new child and setting its layout bounds using `Children.Add()` and `SetLayBounds()`. But this way I'm adding more and more children and never remove them.
What is the proper way to remove a child from an `AbsoluteLayout`?
|
`.Children` implements `IList<View>` (and `ICollection<View>`, `IEnumerable<View>`, `Ienumerable`) so you can use at your best convenience:
* `layout.Children.RemoveAt (position)`,
* `layout.Children.Remove (view)`,
* `layout.Children.Clear ()`
provide you know the index of your view in `.Children`, you can also replace the element in place:
layout.Children[position] = new MyView ();
but that gives you less options than the `Children.Add (...)` overrides and you'll have to use `SetLayoutBounds` and `SetLayoutFlags`.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 5,
"tags": "children, removechild, xamarin.forms, absolutelayout"
}
|
How to subtract two times of different dates in java
How do i subtract two times which are in two different dates, say 23:20:45 of 2019/07/24 and 00:10:32 of 2019/07/25. It should return me the difference between those two hours:minutes:seconds.
I have to note the duration of people which log into the system at night, but as the date changes it's a bit difficult to do so I need some code in java which will return me the exact time in hours:minutes:seconds.
|
LocalDateTime from = LocalDateTime.parse("2019/07/24 23:20:45", formatter);
LocalDateTime to = LocalDateTime.parse("2019/07/25 00:10:32", formatter);
System.out.println(Duration.between(to.toLocalTime(),from.toLocalTime()).getSeconds());
So, since the requrements recently changed and it is now about the total duration between to moments in time, and not the duration between the time-part only, omitting the date-part, the whole thing gets simpler, then it it's just
`System.out.println(Duration.between(to,from).getSeconds());`
... and a duplicate question ...
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "java"
}
|
MongoDB connector for PHP: count documents for pagination
I'm using the `MongoDB\Driver\Manager` to connect to MongoDB using PHP. The driver version is 1.6.14 and I can connect and make a query.
But I need the total number of documents for my query to make the pagination:
$reg_pag = 20;
$pag = $_GET["pag"];
$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter = [];
$filter["brand"] = $_GET["brand"];
$options = ["skip" => ($pag-1)*$reg_pag , "limit" => $reg_pag];
$query = new MongoDB\Driver\Query($filter, $options);
$rows = $mng->executeQuery("carsdb.cars", $query);
I try with `$rows->count()` and with `count($rows)`. The first command doesn't work and the last command returns the filtered data (return 20).
|
Use `executeCommand` method. Try something like the following code:
$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// search params
$query = ["brand" => $_GET["brand"]];
// define a command - not only a regular query
$command = new MongoDB\Driver\Command(["count" => "cars", "query" => $query]);
try {
// execute the command here on your database
$result = $mongo->executeCommand("carsdb", $command);
$res = current($result->toArray());
$count = $res->n;
echo $count;
} catch (MongoDB\Driver\Exception\Exception $e) {
echo $e->getMessage(), "\n";
}
Taken from here, with an adaptation to your case.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "php, mongodb"
}
|
How do eliminate/remove a gem that is throwing errors
When I run the rails console command, I'm getting the following error messages:
Invalid gemspec in [/Users/MI1/torquebox-2.0.0.beta1/jruby/lib/ruby/gems/1.8/specifications/ZenTest-4.9.0.gemspec]: Illformed requirement ["< 2.1, >= 1.8"]
When I ran gem uninstall zentest, the system said zentest was not installed.
Does anyone know how can remove this gem and annoying error message.
|
Try this to make sure you don't have multiple versions of the gem
gem cleanup
then
sudo gem uninstall zentest
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, torquebox"
}
|
Analog to $.map that loops over an object's properties
Does jQuery offer an analog to `$.map` that loops over an object's properties?
|
As of jQuery 1.6, `$.map` not only iterates over arrays but also over the properties of an object. <
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "javascript, jquery"
}
|
Angular Date pipe showing Invalid date
Angular Date pipe not showing Date properly
I am using an angular date pipe on my page list.
{{ row.createdDate }} // 2019-11-04T06:32:24.352856
{{ row.createdDate | date: 'mm-dd-yyyy' }} // 32-04-2019
|
`mm` is minute, you should use `MM`
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 0,
"tags": "angular, angular8, date pipe"
}
|
¿Cómo obtener el dia del año a partir de una fecha seleccionada en un DatePickerDialog 1 - 365?
Tengo el siguiente código
Calendar c = Calendar.getInstance();
c.set(año, mes, dia);
num_dia = Calendar.DAY_OF_YEAR;
String d = Integer.valueOf(num_dia).toString();
tvdias.setText(d);
Deseo obtener el día del año.
|
Solo hay que hacer un pequeño cambio a tu código, para que se obtenga el valor
Calendar calendar = Calendar.getInstance();
c.set(año,mes,dia);
int num_dia = calendar.get(Calendar.DAY_OF_YEAR);// Aquí obtengo el dia del año
String d = Integer.valueOf(num_dia).toString();
tvdias.setText(d);
|
stackexchange-es_stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "java, android"
}
|
unix : how does a "./process | sort" work?
To debug some map/reduce jobs I often test them using a simple unix command that basically reads
cat data/* | mapper | sort | reduce > out
Now everything works just fine, but I'm wondering what _really_ happens with the `map | sort` command.
More precisely :
* does someone knows how the ram/cpu is loaded by `sort` ?
* Is the `sort` command sorting data _on the fly_ , or does it wait for the map job to be finished ( note that the mapper uses STDOUT and does not wait for the end of the computation to output data) ?
* Using quite a large amount of input data does not seem to load the ram as I would expect ( I rather observe peaks of cpu, but I'm not really measuring this very precisely). Is it possible for the process to use less ram as the amount of output information ?
Thanks for your answers :)
|
In Linux, `sort` uses merge sort algorithm (from < ). A merge sort can store some parts in temporary files on disk (and it does in case of `sort`). So the process uses a reasonable amount of RAM (you can specify how much RAM is used via `--buffer-size` option).
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "linux, unix, sorting, mapreduce, pipe"
}
|
Exclude elements from ArrayList
I'd like to iterate over an ArrayList of Strings:
List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
Instead of Iterating over all Items:
for(String a : list) {
System.out.println(a);
}
I'd like to exclude the last elements of the List. Currently I use:
for(int i = 0; i < list.size()-1; i++) {
System.out.println(list.get(i));
}
But I was wondering, if there is a shorter form. For example in R you could simply generate a list without the last element:
a = c("A", "B", "C")
a[-length(a)]
|
You could use `list.subList(0,list.size()-1)` to get a view of the List without the last element.
> **`List<E>` java.util.List.subList(int fromIndex, int toIndex)**
>
> Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 3,
"tags": "java, arraylist, iterator"
}
|
Assign to a variable in the condition of a while loop - scala
I Java I can write this:
Matcher m;
while ((m = pattern.matcher(string)).matches()) {...}
How would I do this in Scala? This doesn't work :
var m: Matcher = null
while ((m = pattern.matcher(s)).matches()) {}
|
Assignments return `Unit` in Scala, but it's ok to use code blocks like this:
while ({
val m = pattern.matcher(s)
m.matches
}) { ... }
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 5,
"tags": "scala, while loop"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.