text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Symfony not respecting overriding class argument for test environment
I have a bundle with a services.yml where the service definition uses a parameter contained within the same file for the class parameter, like so:
parameters:
application.servicename.class: Application\Service\ServiceName
services:
application.servicename:
class: %application.servicename.class%
Now I want to override the service class for my test environment. However, overriding the parameter in config_test.yml does not result in an object of the overriding class being instantiated.
Adding the following to config_test.yml:
parameters:
application.servicename.class: Application\Mock\Service\ServiceName
...still causes the service to be instantieted from Application\Service\ServiceName. If I try passing application.servicename.class as an argument to the service and dump it in the constructor, the overriden value of Application\Mock\Service\ServiceName is displayed.
Why is Symfony not respecting the overridden value for the service class when preparing the service?
A:
As it turns out, this problem was not related to Symfony loading configuration but rather an assumption that the incorrect class was loaded. This assumption was caused by the fact that the method calls of both the original service (and the mock extending it) was marked as private.
Had this not been a problem, I belive what I was attempting to do should be possible, ref http://symfony.com/doc/2.8/cookbook/bundles/override.html#services-configuration
Sorry to waste your time.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"Fulfill online orders from this location" option status through Location API
I have 3 locations in my shopify store, but in one of them the option "Fulfill online orders from this location" is disabled. When I retrieve locations list though Inventory API https://help.shopify.com/en/api/reference/inventory/location#index it doesn't return any information about the "Fulfill online orders from this location" option status.
Is there a different API where I can fetch this info? Or could you please add an appropriate field in locations for Inventory API responses?
A:
The reason is that you probably have not assigned inventory to that location? Items in inventory dictate fulfillments, based on levels. If you read up on InventoryLevels, you can see how fulfillments from locations for items is setup.
Note: the explanation from Shopify may seem excellent to them, but to me it is a tough slog to understand how their system actually works. Experiment will tell you all the problems.
My two cents to you is that you should not focus at all on the Location endpoint of the API, and instead, spend your time figuring out your InventoryItem and InventoryLevel setup issues.
https://help.shopify.com/en/api/reference/inventory/inventorylevel
https://help.shopify.com/en/api/reference/inventory/inventoryitem
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sum pairwise rows with R?
My input is
df1 <- data.frame(Row=c("row1", "row2", "row3", "row4", "row5"),
A=c(1,2,3,5.5,5),
B=c(2,2,2,2,0.5),
C= c(1.5,0,0,2.1,3))
It look like this:
# Row1 1 2 1.5
# Row2 2 2 0
# Row3 3 2 0
# Row4 5.5 2 2.1
# Row5 5 0.5 3
I want to get the sum of all these pairs of rows, with the following equation. Let's said for Row1 and Row2 pairs: I want to multiply each column's entry and sum them into one final answer, for example-
Row1-Row2 answer is (1*2) + (2*2)+ (1.5 *0) = 6
Row1-Row3 answer is (1*3) + (2*2) + (1.5*0) = 7
I want to do all analysis for each pairs of row and get a result data frame like this:
row1 row2 6
row1 row3 7
row1 row4 12.65
row1 row5 10.5
row2 row3 10
row2 row4 15
row2 row5 11
row3 row4 20.5
row3 row5 16
row4 row5 34.8
How can I do this with R? Thanks a lot for comments.
A:
Create all the combinations you need with combn. t is used to transpose the matrix as you expect it to be formatted.
Use apply to iterate over the indices created in step 1. Note that we use negative indexing so we don't try to sum the Row column.
Bind the two results together.
`
ind <- t(combn(nrow(df1),2))
out <- apply(ind, 1, function(x) sum(df1[x[1], -1] * df1[x[2], -1]))
cbind(ind, out)
out
[1,] 1 2 6.00
[2,] 1 3 7.00
[3,] 1 4 12.65
.....
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Example of an algebra finite over a commutative subalgebra with infinite dimensional simple modules
Let $A$ be an algebra over an algebraically closed field $k.$ Recall that if $A$ is
a finitely generated module over its center, and if its center is a finitely generated
algebra over $k,$ then by the Schur's lemma all simple $A$-modules are finite dimensional
over $k.$
Motivated by the above, I would like an example of a $k$-algebra $A,$ such that:
1) $A$
has a simple module of infinitie dimension over $k,$
2) $A$ contains
a commutative finitely generated subalgebra over which $A$ is a finitely generated
left and right module.
Thanks in advance.
A:
Doc, this is a stinker. Your condition (2) forces your algebra to be finitely generated PI, and every little hare knows that simple modules over such algebras are finite-dimensional. See 13.4.9 and 13.10.3 of McConnell-Robson...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Custom Font in View Pager in android
I am developing demo application in which I am using view pager. Now I want to know that can we change the text style of Title displayed in view pager.
Please give your suggestions on it.
Thanking you in advance.
A:
Working demo
TextView txt = (TextView) v.findViewById(R.id.custom_font);
and then change your font
Something like this:
switch (position) {
case 0:
v = (LinearLayout) LayoutInflater.from(cxt).inflate(R.layout.lcmeter, null);
TextView txt = (TextView) v.findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "Chantelli_Antiqua.ttf");
txt.setTypeface(font);
break;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
AngularJS Hide selected items in the drop-down options
I am trying to allocate two crews based on the same data from the server. In the drop-down options, when I select an item in one box. I would like the selected option to disappear in the next drop-down
A:
You could use a filter in the ngOptions expression:
Define your two select box like this , one with a filter
<select ng-model="crew1" ng-options="crew.text for crew in crews1></select>
<select ng-model="crew2" ng-options="crew.text for crew in crews2 | filter:shouldShow"></select>
and define the shouldShow() function to $scope in the controller:
$scope.shouldShow = function (crew) {
// put your authorization logic here
return $scope.crew1 != 'selectedOption';
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
error CS1061: 'List' does not contain a definition for when trying to use ModelView
I'm running into a problem. I'm following a tutorial on Pluralsight:
Consolidating MVC Views Using Single Page Techniques
I'm not able to access the properties in the modelview class from the index.cshtml page
Compiler Error Message: CS1061: 'List<TrainingProductViewModel>' does not contain a definition for 'Products' and no accessible extension method 'Products' accepting a first argument of type 'List<TrainingProductViewModel>' could be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 38: </thead>
Line 39: <tbody>
Line 40: @foreach (var item in Model.Products)
Line 41: {
Line 42: <tr>
The ModelView class
namespace PTCData
{
public class TrainingProductViewModel
{
public TrainingProductViewModel()
{
Products = new List<TrainingProduct>();
EventCommand = "List";
}
public string EventCommand { get; set; }
public List<TrainingProduct> Products { get; set; }
public void HandleRequest()
{
switch (EventCommand.ToLower()){
case "list":
Get();
break;
default:
break;
}
}
private void Get()
{
TrainingProductManager mgr = new TrainingProductManager();
Products = mgr.Get();
}
}
}
The index.cshtml page - not able to access Model.Products and the properties
@model List<PTCData.TrainingProductViewModel>
@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm())
{
<!-- Begin Search Area-->
<p> </p>
<div class="panel panel-primary">
<div class="panel-heading">
<h1 class="panel-title">Search</h1>
</div>
<div class="panel-body">
<div class="form-group">
@Html.Label("Product Name");
@Html.TextBox("SearchProductName", "", new { @class = "form-control" })
</div>
</div>
<div class="panel-footer">
<button id="btnSearch" class="btn btn-sm btn-primary">Search</button>
<button id="btnReset" class="btn btn-sm btn-primary">Reset</button>
</div>
</div>
<!-- End Search Area-->
<!-- Begin List Area-->
<div class="table-responsive">
<table class="table table-condensed table-bordered table-striped table-hover">
<thead>
<tr>
<th>Product Name</th>
<th>Introduction Date</th>
<th>Url</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Products)
{
<tr>
<td>@item.ProductName</td>
<td>@item.IntroductionDate</td>
<td>@item.Url</td>
<td>@item.Price.ToString("c")</td>
</tr>
}
</tbody>
</table>
</div>
<!-- End List Area-->
}
@section scripts{
<script></script>
}
A:
Your model inside the view should be @model PTCData.TrainingProductViewModel and not a list.
A list is a collection of a type, hence a List<TrainingProductViewModel> will not contain the Products property but the individual elements inside the list will.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
python - beautifulsoup - TypeError: sequence item 0: expected string, Tag found
I'm using beautifulsoup to extract images and links from a html string. It all works perfectly fine, however with some links that have a tag in the link contents it is throwing an error.
Example Link:
<a href="http://www.example.com"><strong>Link Text</strong></a>
Python Code:
soup = BeautifulSoup(contents)
links = soup.findAll('a')
for link in links:
print link.contents # generates error
print str(link.contents) # outputs [Link Text]
Error Message:
TypeError: sequence item 0: expected string, Tag found
I don't really want to have to loop through any child tags in the link text, I simply want to return the raw contents, is this possible with BS?
A:
To grab just the text content of a tag, the element.get_text() method lets you grab (stripped) text from the current element including tags:
print link.get_text(' ', strip=True)
The first argument is used to join all text elements, and sitting strip to True means all text elements are first stripped of leading and trailing whitespace. This gives you neat processed text in most cases.
You can also use the .stripped_strings iterable:
print u' '.join(link.stripped_strings)
which is essentially the same effect, but you could choose to process or filter the stripped strings first.
To get the contents, use str() or unicode() on each child item:
print u''.join(unicode(item) for item in link)
which will work for both Element and NavigableString items contained.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Node.js: Memory usage keeps going up
We are writing a script that reads a large set of JPG files on our server (infinite, since we have another process that keeps writing JPG files to the same directory) and send them to users' browsers as an MJPEG stream at fixed time interval (variable "frameDelay" in code below). This is similar to what an IP camera would do.
We found out the memory usage of this script keeps going up and always ends up being killed by the system (Ubuntu);
We have inspected this seemingly simple script many many times. Therefore I'm posting the code below. Any comments / suggestions are greatly appreciated!
app.get('/stream', function (req, res) {
res.writeHead(200, {
'Content-Type':'multipart/x-mixed-replace;boundary="' + boundary + '"',
'Transfer-Encoding':'none',
'Connection':'keep-alive',
'Expires':'Fri, 01 Jan 1990 00:00:00 GMT',
'Cache-Control':'no-cache, no-store, max-age=0, must-revalidate',
'Pragma':'no-cache'
});
res.write(CRLF + "--" + boundary + CRLF);
setInterval(function () {
if(fileList.length<=1){
fileList = fs.readdirSync(location).sort();
}else{
var fname = fileList.shift();
if(fs.existsSync(location+fname)){
var data = fs.readFileSync(location+fname);
res.write('Content-Type:image/jpeg' + CRLF + 'Content-Length: ' + data.length + CRLF + CRLF);
res.write(data);
res.write(CRLF + '--' + boundary + CRLF);
fs.unlinkSync(location+fname);
}else{
console.log("File doesn't find")
}
}
console.log("new response:" + fname);
}, frameDelay);
});
app.listen(port);
console.log("Server running at port " + port);
To facilitate the troubleshooting process, below is a stand-alone (no 3rd-party lib) test case.
It has exactly the same memory issue (memory usage keeps going up and finally got killed by the OS).
We believe the problem is in the setInterval () loop - maybe those images didn't get deleted from memory after being sent or something (maybe still stored in variable "res"?).
Any feedback / suggestions are greatly appreciated!
var http = require('http');
var fs = require('fs');
var framedelay = 40;
var port = 3200;
var boundary = 'myboundary';
var CR = '\r';
var LF = '\n';
var CRLF = CR + LF;
function writeHttpHeader(res)
{
res.writeHead(200,
{
'Content-Type': 'multipart/x-mixed-replace;boundary="' + boundary + '"',
'Transfer-Encoding': 'none',
'Connection': 'keep-alive',
'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT',
'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
'Pragma': 'no-cache',
});
res.write(CRLF + '--' + boundary + CRLF);
}
function writeJpegFrame(res, filename)
{
fs.readFile('./videos-8081/frames/' + filename, function(err, data)
{
if (err)
{
console.log(err);
}
else
{
res.write('Content-Type:image/jpeg' + CRLF);
res.write('Content-Length:' + data.length + CRLF + CRLF);
res.write(data);
res.write(CRLF + '--' + boundary + CRLF);
console.log('Sent ' + filename);
}
});
}
http.createServer(function(req, res)
{
writeHttpHeader(res)
fs.readdir('./videos-8081/frames', function(err, files)
{
var i = -1;
var sorted_files = files.sort();
setInterval(function()
{
if (++i >= sorted_files.length)
{
i = 0;
}
writeJpegFrame(res, sorted_files[i]);
}, framedelay);
});
}).listen(port);
console.log('Server running at port ' + port);
A:
Of course it leaks memory. You do
setInterval(...)
on each request, but you never clean these intervals. Meaning that after ( for example ) 20 requests you have 20 intervals running in the background, which will run forever, even if clients/connections are long dead. One of the solutions is the following:
var my_interval = setInterval(function() {
try {
// all your code goes here
} catch(e) {
// res.write should throw an exception once the connection is dead
// do the cleaning now
clearInterval( my_interval );
}
}, frameDelay);
req.on( "close", function() {
// just in case
clearInterval( my_interval );
});
which ensures that my_interval ( and all corresponding data ) will be cleaned once the connection is closed.
P.S. I advice using setTimeout instead of setInterval, because loading file may take more time then frameDelay which will cause problems.
P.S.2. Use asynchronous versions of fs functions. Entire power of Node.JS is in nonblocking operations and you are loosing the main advantage ( performance ) here.
A:
There are a few things caused this
MJPEG is not designed to send high resolution motion pictures in a high frequency (25fps, in your case, may be ok for 320x240 frames, but not for 720p.) Just consider the output throughput of the payload 25fps*70KB = 1750KBps = 14Mbps which is higher than full HD video.
Node.js will cache the output in a buffer when the client is incapable to receive. Because you are sending to much data to client, so node saved them for you. That's why your memory usage never go down, and it's NOT memory leak. To detect if the output buffer is bulked up, check the return value of res.write().
setInterval() is OK to use, and will not cause any problem as long as the client keep the connection. But when the client is disconnected, you need to stop it. To do so, you need to monitor 'close' event.
You cannot maintain a stable fps by using MJPEG as it's not designed for this purpose, so no matter how hard you try, you cannot control the fps at client. But with carefully designed code, you can make the average fps stable by using setTimeout().
Here is the fixed code.
var http = require('http');
var fs = require('fs');
var framedelay = 40;
var port = 3200;
var boundary = 'myboundary';
var CR = '\r';
var LF = '\n';
var CRLF = CR + LF;
http.createServer(function(req, res) {
var files = fs.readdirSync('./imgs');
var i = -1;
var timer;
var sorted_files = files.sort();
res.writeHead(200, {
'Content-Type': 'multipart/x-mixed-replace;boundary="' + boundary + '"',
'Transfer-Encoding': 'none',
'Connection': 'keep-alive',
'Expires': 'Fri, 01 Jan 1990 00:00:00 GMT',
'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
'Pragma': 'no-cache',
});
res.write(CRLF + '--' + boundary + CRLF);
var writePic = function() {
if (++i >= sorted_files.length)
i = 0;
var data = fs.readFileSync('./imgs/' + sorted_files[i]);
res.write('Content-Type:image/jpeg' + CRLF);
res.write('Content-Length:' + data.length + CRLF + CRLF);
res.write(data);
var ok = res.write(CRLF + '--' + boundary + CRLF);
console.log('Sent ' + sorted_files[i], ok);
if (ok)
timer = setTimeout(writePic, framedelay);
};
res.on('close', function() {
console.log('client closed');
clearTimeout(timer);
});
res.on('drain', function() {
console.log('drain');
timer = setTimeout(writePic, framedelay);
});
}).listen(port);
console.log('Server running at port ' + port);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# Try-Catch & Exception handling
In various parts of code in a current project, there is constant usage of
try
{
//code
}
catch(Exception e)
{
//display nicely formatted error message
}
My question is, under the assumption that the code handles all known/assumed errors (such as checking if objects are null etc), should a try-catch be placed around the code that displays errors in a application-global format?
Or is it better practice to let the error throw an exception and have the application crash naturally?
Thanks
A:
Catching all exceptions like this is not a good practice, except at the top level of your application, where you display a nice error message. Done right, it could preserve end user's perception of your program as slightly buggy, but reasonable overall. In contrast, letting your application crash is the easiest way to convince your end users that your application is bad beyond repair.
As far as exception prevention goes, there are two major kinds of exceptions - programming errors (null pointer, class cast, out of range, etc.) and environment errors (file not found, network path is unavailable, user entry error, etc.) You can and should avoid the first kind, and be prepared to handle the second kind.
A:
class PerformTask
{
public void ConnectToDB(requiredParams)
{
}
}
class PerformTaskConsumer
{
public void SomeMethod()
{
try
{
PerformTask obj = new PerformTask();
}
catch(RelaventExceptions)
{
}
}
}
Just avoid the exception if you can. If Exception occurs, leave it to the caller what he wants to do with the Exception. The caller may decide to show a well formatted message about the exception or decide to crash or what ever.
Eric Lippert has a good article regarding exceptions. here
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Jhipster : Proper architecture to authenticate using an existing database
I'm currently working on a Jhipster prototype application. The application is a simple gateway with a microservice to access data.
Right now, I would like to use an existing database from my company to authenticate users, but Jhispter doesn't seems to supports multiple datasources (and I don't want my whole gateway to switch to another database)
My first idea was to use a microservices to authenticate user. This microservice would run on the other database, but this creates another problem : to call this service from the gateway, I need a JWT token... and this starts to look like I need to be authenticated to authenticate a user.
The other solution, as said before, would be to have two datasources on my gateway : one for user authentication (pointing to the existing database), and the other for Jhipster-related data (audits, etc..)
Do you know what would be the best practice in this case?
And can you point me in the right direction for this choice ?
A:
First solution: you can easily unprotect authenticate endpoint in SecurityConfioguration on your micro service so that you don't require a token for it then you will have to create a Zuul route on gateway for /api/authenticate.
Second solution is a well known question about using multiple datasources in Spring Boot which has many well docuemnted answers.
There could be another solution consisting in using an existing third party identity server like uaa or KeyCloak if you can configure them to your existing user database.
So for a prototype, I'd go with the second solution.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Efficiently compute proportions of one data frame from another
I have this data.frame:
set.seed(1)
df <- cbind(matrix(rnorm(26,100),26,100),data.frame(id=LETTERS,parent.id=sample(letters[1:5],26,replace = T),stringsAsFactors = F))
Each row is 100 measurements from a certain subject (designated by id), which is associated with a parent ID (designated by parent.id). The relationship between parent.id and id is one-to-many.
I'm looking for a fast way to get the fraction of each df$id (for each of its 100 measurements) out the measurements of its parent.id. Meaning that for each id in df$id I want to divide each of its 100 measurements by the sum of its measurements across all df$id's which correspond to its df$parent.id.
What I'm trying is:
sum.df <- dplyr::select(df,-id) %>% dplyr::group_by(parent.id) %>% dplyr::summarise_all(sum)
fraction.df <- do.call(rbind,lapply(df$id,function(i){
pid <- dplyr::filter(df,id == i)$parent.id
(dplyr::filter(df,id == i) %>% dplyr::select(-id,-parent.id))/
(dplyr::filter(sum.df,parent.id == pid) %>% dplyr::select(-parent.id))
}))
But for the real dimensions of my data: length(df$id) = 10,000 with 1,024 measurements, this is not fast enough.
Any idea how to improve this, ideally using dplyr functions?
A:
The problem with your data is all rows are duplicate of each other, so I changed it slightly to reflect different values in the dataset.
Data:
set.seed(1L)
df <- cbind(matrix(rnorm(2600), nrow = 26, ncol = 100),data.frame(id=LETTERS,parent.id=sample(letters[1:5],26,replace = T),stringsAsFactors = F))
Code:
library('data.table')
setDT(df) # assign data.table class by reference
# compute sum for each `parent.id` for each column (100 columns)
sum_df <- df[, .SD, .SDcols = which(colnames(df) != 'id' )][, lapply(.SD, sum ), by = .(parent.id ) ]
# get column names for sum_df and df which are sorted for consistency
no_pid_id_df <- gtools::mixedsort( colnames(df)[ ! ( colnames(df) %in% c( 'id', 'parent.id' ) ) ] )
no_pid_sum_df <- gtools::mixedsort( colnames(sum_df)[ colnames(sum_df) != 'parent.id' ] )
# match the `parent.id` for each `id` and then divide its value by the value of `sum_df`.
df[, .( props = {
pid <- parent.id
unlist( .SD[, .SD, .SDcols = no_pid_id_df ] ) /
unlist( sum_df[ parent.id == pid, ][, .SD, .SDcols = no_pid_sum_df ] )
}, parent.id ), by = .(id)]
Output:
# id props parent.id
# 1: A -0.95157186 e
# 2: A 0.06105359 e
# 3: A -0.42267771 e
# 4: A -0.03376174 e
# 5: A -0.16639600 e
# ---
# 2596: Z 2.34696158 e
# 2597: Z 0.23762369 e
# 2598: Z 0.60068440 e
# 2599: Z 0.14192337 e
# 2600: Z 0.01292592 e
Benchmark:
library('microbenchmark')
microbenchmark( sathish(), frank(), dan())
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# sathish() 404.450219 413.456675 433.656279 420.46044 429.876085 593.44202 100 c
# frank() 2.035302 2.304547 2.707019 2.47257 2.622025 18.31409 100 a
# dan() 17.396981 18.230982 19.316653 18.59737 19.700394 27.13146 100 b
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I databind to a ViewModel in Expression Blend?
In WPF and Silverlight you can make a view model object and set it into the DataContext of a control when the control is constructed at runtime. You can then bind properties of the visual object to properties in your DataContext.
One way to set the binding is to type the binding directly into the tag:
<TextBox Text="{Binding Path=Description}"/>
And this will bind the textbox to the Description property in the view model.
The problem with typing in the binding is that you may make a typing mistake. (And you will almost certainly make a mistake if you have hundreds of bindings to make.)
In Expression Blend there is a little white dot beside the Text property in the Properties window. This brings up a menu from which you can Create Data Binding.
How can I get my view model properties to show in the Create Data Binding dialog so that I can select them.
Will the configuration of data binding in Blend interfere with setting my view model into the DataContext at runtime?
A:
One technique is to include the VM as a resource in your view:
<UserControl>
<UserControl.Resources>
<local:YourViewModel x:Key="ViewModel"/>
</UserControl.Resources>
</UserControl>
You can then reference that as DataContext="{StaticResource ViewModel}" elsewhere.
Can't say I like it, but I can't say I like any of the view-first idiosynchrasies that Blend imposes on your design.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can we continuously integrate new features when the PO only determines whether a feature is "done" at the end of each Sprint?
My team is having an issue with integrating software product features. Specifically, when do features get pull requested into our integration branch of code?
Currently our understanding is:
The Product Owner is the only person who can say that a feature or User Story is "done".
The Product Owner makes his decision on whether a User Story is "done" at the end of sprint, during the Sprint Review Meeting.
With the points above, it appears that pull requests for our "done" features or User Stories should occur at the end of our sprints. But how can this be the case?
If we merge several features together after we get the Product Owner's approval, it may be the case that the features conflict or break each other. Now the features are no longer "done", additional work to resolve conflicts must be done, etc.
How can we continuously integrate our new features (allowing us to do realistic integration testing) while retaining the fact that the Product Owner is the final say of whether or not a feature is "done"?
A:
The team says the story is done. Think of this on a storyboard where the team marks the story as ready to pull (done or completed) into accepted status.
The Product Owner accepts the story, (by pulling it into accepted) but their acceptance only indicates the story is done in terms of business functionality.
So acceptance from a product owner, is only partial to saying the story is done. Done goes beyond PO acceptance because it encompasses the non-functional portions of finishing a story as well. QA, tech debt, etc.
One model for handling integration and done stories is to land these stories into a staging environment. Staging is a clone or close replica of your production environment. Its also where integrating teams would go to consume any code. Your Product Owner uses this environment to validate that the functional requirements of the story are met and accept the story. This doesn't need to happen during the review ceremony. It can happen anytime throughout the iteration, but ideally is completed soon after the iteration finishes (otherwise you hold your stage environment hostage and can't check in new features).
In order to get to staging, all your done criteria (functional and non-functional) must already be completed.
I'm simplifying a bit with this model as there are done criteria that can happen in production in some situations. But the majority of done criteria must be met by the time code goes to stage.
A:
From Scrum.Org:
The DoD is usually a clear and concise list of requirements that a
software Increment must adhere to for the team to call it complete.
Until this list is satisfied, a product Increment is not done. During
the Sprint Planning meeting, the Scrum Team develops or reconfirms its
DoD, which enables the Development Team to know how much work to
select for a given Sprint.
The key sentence there for me is that the Scrum Team (especially the Product Owner) develops and confirms the DoD. It is an agreed standard prior to the Sprint work commencing.
If the Product Owner does not consider the Definition of Done to have been met then technically the Scrum Team have not accomplished the Definition of Done and the PO reserves the right to reject the User Story(s) as not done.
Edit to Add
The Scrum Alliance have a handy chart for ensuring that the Definition of Done is simple, transparent and consistent. Please note the two boxes stating
Product Owner Approval
Acceptance Testing
I know some in the community will respond with anger at my strict siding with the Product Owner but in my opinion it is absurd to think that the Developers are allowed to decide when to take work, what constitutes completion of that work and then force that work into the done column regardless of the Product Owner expectations.
The Product Owner manages the stakeholders, the business requirements and assumes the risk on behalf of the business entity. Of course, they absolutely must own the Definition of Done.
As a balancing act the Scrum Team own the Definition of Ready which allows them to reject User Stories from the Product Owner due to unclear specifications, technical problems, dependency work or any other valid concern.
Ultimately, if we allow Scrum Teams to mark their own homework and push products to a business without Product Owner due diligence the results could be terrible.
In addition, that does not scale to Scrum of Scrums otherwise each Scrum team would simply proclaim their dependency was 'Done' without a Product Owner to consider that they whole product was progressing.
Personal Approaches
As an aside I thought it would be helpful to illustrate how I control this issue as the Scrum Master.
When a Back End Developer user story has been Tested it goes into "Being Verified" where we discuss it with the PO.
If the PO disagrees then I ask for the Business Specifications or Requirements that demonstrate that it is not 'done'
95% of the time I side with the Developer and reason the Product Owner to either produce a new card for the Product Backlog or accept the current completion.
Business Intelligence Front End Development in our environment is trickier since much more testing is required including UX and data reconciliation between old and new outputs
At this point the PO represents the End User and acts a customer
We give the Product Owner much more capability to reject reports at this stage
Like all things Scrum (and Agile) a balance must be struck to ensure team harmony, trust and a high functioning team. I take the parts of Scrum I need to achieve that and adapt the rest.
Some might say I am not doing Scrum anymore but the truth is, I don't need the label, what I need is a highly productive Business Intelligence Centre.
To the OP, I say this -
Does it suit your needs to have the Product Owner reject User Stories? Be honest. If he/she is truly skilled and good at their role, their rejection of User Stories may be the best thing that happens to your delivery saving the team a higher amount of rework in the long run.
A:
The main source of your conundrum is the Product Owner waiting until end of sprint to accept stories. The function of the Sprint Review is not for the Product Owner to review and accept the work of the Team. It is for the Team to review itself and present what was done to other stakeholders. Time for Product Owner review, feedback and iteration should be built into your sprint schedule.
With that in mind, let's answer your main question "when do features get pull requested into our integration branch of code?"
When to integrate can be a tricky decision. It's common to have a staging environment that serves as the environment both for integration and acceptance testing. But merging a feature can be hard to turn back from. If the Product Owner finds significant issues, now you have a potential blocker to pushing to production, and an untrustworthy branch for other features to branch from.
If possible, the Product Owner should review and approve each feature in isolation before it is merged with other features. Acceptance of the feature at this stage means that it has been realized as envisioned, although more work may be needed to make it shippable. Product Owner approval at this point should be the green light to proceed with completing the work of integrating and deploying the feature.
Here's one way integration and merge conflicts can be handled:
Let's say two features, A and B, are being developed simultaneously. Feature A becomes reviewable first and is accepted by the Product Owner. It can now be merged into the integration branch. All other features, as they approach reviewability, should be paying attention to the progress of the integration branch and updating themselves from the integration branch. This is the point where merge conflicts can arise and be resolved. Now the onus is on Feature B's developer to resolve any conflicts. This may even require modifications to Feature A. Once this is done, Feature B, along with the modifications to Feature A, can now be reviewed by the Product Owner. Once accepted, it too can be merged to the integration branch.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Morse Code to English
My problem right now is getting the "morse code to english" to work. the first part which converts english to morse is working perfectly. i know this has been asked before but i can't figure out what i am doing wrong. i know i need a split somewhere, but I'm just not sure where to put it in the code. right now the morse to english part won't even convert one symbol. any help will be much appreciated.
import java.util.Scanner;
public class MorseCode2 {
public static void main ( String [] args )
{
Scanner input = new Scanner( System.in );
System.out.print( "Would you like to convert English to Morse (yes or no)? " );
String answer = input.nextLine();
if( answer.equals( "yes" ) )
{
System.out.println( "Please enter the text you want to translate into Morse code: " );
String english = input.nextLine();
System.out.println( stringToMorse( english ) );
}
if (answer.equalsIgnoreCase( "no" ) )
{
System.out.print( "Morse to English? " );
String answer2 = input.nextLine();
if (answer2.equalsIgnoreCase( "yes" ) )
{
System.out.println( "Please enter the Morse code you want to translate into English: " );
String code = input.nextLine();
System.out.println( stringToEnglish( code ) );
}
}
}
public static String encode (String toEncode)
{
String morse = toEncode;
if (toEncode.equalsIgnoreCase("a"))
morse = ".-";
if (toEncode.equalsIgnoreCase("b"))
morse = "-...";
if (toEncode.equalsIgnoreCase("c"))
morse = "-.-.";
if (toEncode.equalsIgnoreCase("d"))
morse = "-..";
if (toEncode.equalsIgnoreCase("e"))
morse = ".";
if (toEncode.equalsIgnoreCase("f"))
morse = "..-.";
if (toEncode.equalsIgnoreCase("g"))
morse = "--.";
if (toEncode.equalsIgnoreCase("h"))
morse = "....";
if (toEncode.equalsIgnoreCase("i"))
morse = "..";
if (toEncode.equalsIgnoreCase("j"))
morse = ".---";
if (toEncode.equalsIgnoreCase("k"))
morse = "-.-";
if (toEncode.equalsIgnoreCase("l"))
morse = ".-..";
if (toEncode.equalsIgnoreCase("m"))
morse = "--";
if (toEncode.equalsIgnoreCase("n"))
morse = "-.";
if (toEncode.equalsIgnoreCase("o"))
morse = "---";
if (toEncode.equalsIgnoreCase("p"))
morse = ".--.";
if (toEncode.equalsIgnoreCase("q"))
morse = "--.-";
if (toEncode.equalsIgnoreCase("r"))
morse = ".-.";
if (toEncode.equalsIgnoreCase("s"))
morse = "...";
if (toEncode.equalsIgnoreCase("t"))
morse = "-";
if (toEncode.equalsIgnoreCase("u"))
morse = "..-";
if (toEncode.equalsIgnoreCase("v"))
morse = "...-";
if (toEncode.equalsIgnoreCase("w"))
morse = ".--";
if (toEncode.equalsIgnoreCase("x"))
morse = "-..-";
if (toEncode.equalsIgnoreCase("y"))
morse = "-.--";
if (toEncode.equalsIgnoreCase("z"))
morse = "--..";
if (toEncode.equalsIgnoreCase("0"))
morse = "-----";
if (toEncode.equalsIgnoreCase("1"))
morse = ".----";
if (toEncode.equalsIgnoreCase("2"))
morse = "..---";
if (toEncode.equalsIgnoreCase("3"))
morse = "...--";
if (toEncode.equalsIgnoreCase("4"))
morse = "....-";
if (toEncode.equalsIgnoreCase("5"))
morse = ".....";
if (toEncode.equalsIgnoreCase("6"))
morse = "-....";
if (toEncode.equalsIgnoreCase("7"))
morse = "--...";
if (toEncode.equalsIgnoreCase("8"))
morse = "---..";
if (toEncode.equalsIgnoreCase("9"))
morse = "----.";
if (toEncode.equalsIgnoreCase("."))
morse = ".-.-";
if (toEncode.equalsIgnoreCase(","))
morse = "--..--";
if (toEncode.equalsIgnoreCase("?"))
morse = "..--..";
return morse;
}
public static String decode (String toEncode) {
String morse = toEncode;
if (toEncode.equalsIgnoreCase(".-"))
morse = "a";
if (toEncode.equalsIgnoreCase("-..."))
morse = "b";
if (toEncode.equalsIgnoreCase("-.-."))
morse = "c";
if (toEncode.equalsIgnoreCase("-.."))
morse = "d";
if (toEncode.equalsIgnoreCase("."))
morse = "e";
if (toEncode.equalsIgnoreCase("..-."))
morse = "f";
if (toEncode.equalsIgnoreCase("--."))
morse = "g";
if (toEncode.equalsIgnoreCase("...."))
morse = "h";
if (toEncode.equalsIgnoreCase(".."))
morse = "i";
if (toEncode.equalsIgnoreCase(".---"))
morse = "j";
if (toEncode.equalsIgnoreCase("-.-"))
morse = "k";
if (toEncode.equalsIgnoreCase(".-.."))
morse = "l";
if (toEncode.equalsIgnoreCase("--"))
morse = "m";
if (toEncode.equalsIgnoreCase("-."))
morse = "n";
if (toEncode.equalsIgnoreCase("---"))
morse = "o";
if (toEncode.equalsIgnoreCase(".--."))
morse = "p";
if (toEncode.equalsIgnoreCase("--.-"))
morse = "q";
if (toEncode.equalsIgnoreCase(".-."))
morse = "r";
if (toEncode.equalsIgnoreCase("..."))
morse = "s";
if (toEncode.equalsIgnoreCase("-"))
morse = "t";
if (toEncode.equalsIgnoreCase("..-"))
morse = "u";
if (toEncode.equalsIgnoreCase("...-"))
morse = "v";
if (toEncode.equalsIgnoreCase(".--"))
morse = "w";
if (toEncode.equalsIgnoreCase("-..-"))
morse = "x";
if (toEncode.equalsIgnoreCase("-.--"))
morse = "y";
if (toEncode.equalsIgnoreCase("--.."))
morse = "z";
if (toEncode.equalsIgnoreCase("-----"))
morse = "0";
if (toEncode.equalsIgnoreCase(".----"))
morse = "1";
if (toEncode.equalsIgnoreCase("..---"))
morse = "2";
if (toEncode.equalsIgnoreCase("...--"))
morse = "3";
if (toEncode.equalsIgnoreCase("....-"))
morse = "4";
if (toEncode.equalsIgnoreCase("....."))
morse = "5";
if (toEncode.equalsIgnoreCase("-...."))
morse = "6";
if (toEncode.equalsIgnoreCase("--..."))
morse = "7";
if (toEncode.equalsIgnoreCase("---.."))
morse = "8";
if (toEncode.equalsIgnoreCase("----."))
morse = "9";
if (toEncode.equalsIgnoreCase("|"))
morse = "";
return morse;
}
public static String stringToMorse( String text )
{
String newText = "";
String selectedChar;
String convertedChar;
for (int i = 0; i < text.length(); i++)
{
//Select the next character
selectedChar = text.charAt(i) + "";
// Convert the character
convertedChar = encode(selectedChar);
if (convertedChar.equals(" ")) // " " separates each word represented in english code
{
newText = newText + "| ";
}
// Add the converted text, and add a space
else
{
newText = newText + convertedChar;
if (!convertedChar.equals(" "))
{
newText = newText + " ";
}
}
}
return newText;
}
public static String stringToEnglish( String text )
{
String newMorse = ""; //sets string for newMorse
String selectedMorse; //sets string for selectedMorse
String convertedMorse; //sets string for convertedMorse
for (int i = 0; i < text.length(); i++)
{
//Select the next character
selectedMorse = text.charAt(i) + "";
// Convert the character
convertedMorse = encode(selectedMorse);
if (convertedMorse.equals("| ")) // "|" separates each word represented in morse code
{
newMorse = newMorse + " ";
}
// Add the converted text, and add a space
else
{
newMorse = newMorse + convertedMorse;
if (!convertedMorse.equals(" "))
{
newMorse = newMorse + " ";
}
}
}
return newMorse;
}
}
A:
You probably want something like this:
public static String stringToEnglish( String text )
{
String newEnglish = ""; //sets string for newEnglish
String selectedEnglish; //sets string for selectedEnglish
String convertedEnglish; //sets string for convertedEnglish
String[] morseChars = text.split(" ");
for (int i = 0; i < morseChars.length; i++)
{
//Select the next Morse character
selectedEnglish = morseChars[i];
boolean endsWithWordSeparator = selectedEnglish.endsWith("|");
if(endsWithWordSeparator) selectedEnglish = selectedEnglish.substring(0, selectedEnglish.length() - 1);
// Convert the string
convertedEnglish = decode(selectedEnglish);
newEnglish = newEnglish + convertedEnglish;
if (endsWithWordSeparator)
{
newEnglish = newEnglish + " ";
}
}
return newEnglish;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can two matrices with the same characteristic polynomial have different eigenvalues?
The polynomial is $-\lambda^3+3\lambda -2$
which factorizes into ($\lambda-1$)($\lambda +1$)($\lambda -2$)
A matrix A has the above characteristic polynomial, and so its eigenvalues are 1, -1, and 2.
However, another matrix B, already in diagonal form, has the same characteristic polynomial, but with eigenvalues 1,1,-2, i.e., diagonal entries 1,1,-2.
Is this possible? Or have I gone wrong in my computations?
The problem statement does ask to show that the characteristic polynomials are the same but that the matrices A and B are not similar. So, perhaps I have found exactly what I needed, but it just seems weird...
Thanks,
A:
$-\lambda^3+3\lambda - 2 = -(\lambda-1)^2(\lambda+2) \neq -(\lambda-1)(\lambda+1)(\lambda-2)$.
A:
Two matrices with the same characteristic polynomial necessarily have the same eigenvalues (the roots of the polynomial).
If an $n$-dimensional matrix has $n$ distinct eigenvalues, then it is diagonalizable. Consequently, all $n$-dimensional matrices with this set of $n$ distinct eigenvalues are similar.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Flow of current in the circuit
I'm very new to electronics and raspberry pi and trying to follow this tutorial.
When I check the circuit the resistor is connected between the ground and the LED to limit the amount of current that is passed to the LED.
Is it safe to assume the flow of current is from negative to positive in the raspberry pi?
A:
Current ALWAYS flows in a circuit.
In this simple example the current flows from the Power Supply -> Pi -> GPIO pin -> LED -> resistor -> Ground (and thus back to the Power Supply).
In a series circuit it makes no difference which order the components are connected (although with polarised components, such as the LED, they need to be connected the right way round).
I should point out that while the article you linked is a good beginners description, it contains a number of factual errors, in particular the resistor colour code.
From an purist engineering point of view the best connection would be +3.3V -> resistor -> LED -> GPIO pin (just to be clear the GPIO pin then needs to be LOW to light the LED).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can't close NavigationDrawer with right-to-left swipe
I have been trying to fix the problem I've got, which is that I'm unable to close the NavigationDrawer by swiping from right-to-left, without success. Opening it by swiping from the left edge of the screen to the right is working as it should. I'm currently just trying to merge the NavigationDrawer sample and the ViewPager sample from the developer.android.com website, and everything is working, but not the closing of the navigation drawer. I hope somebody of you wants to help me.
Here's my code:
package com.example.android.effectivenavigation;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity /*implements ActionBar.TabListener*/ {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* three primary sections of the app. We use a {@link android.support.v4.app.FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
/**
* The {@link ViewPager} that will display the three primary sections of the app, one at a
* time.
*/
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
Log.v("MainActivity", "Closed!");
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
Log.v("MainActivity", "Opened!");
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
//actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
/*for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}*/
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public CharSequence getPageTitle (int position) {
return "Hello";
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
/*@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new LaunchpadSectionFragment();
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
return "Section " + (position + 1);
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class LaunchpadSectionFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.demo_collection_button)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CollectionDemoActivity.class);
startActivity(intent);
}
});
// Demonstration of navigating to external activities.
rootView.findViewById(R.id.demo_external_activity)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Create an intent that asks the user to pick a photo, but using
// FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching
// the application from the device home screen does not return
// to the external activity.
Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
externalActivityIntent.setType("image/*");
externalActivityIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(externalActivityIntent);
}
});
return rootView;
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
And my XML:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTitleStrip
android:id="@+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</android.support.v4.view.ViewPager>
EDIT: Turns out I can close the NavigationDrawer, but not how it should be. To close it, I have to swipe from left to right, and then swipe from right to left without taking my finger off the screen. So I have to make the same gesture as opening the drawer and then instantly make the closing gesture, but thats not how it should be.
A:
I think the XML causes your problem. The ListView (left_drawer) should be the last element in your XML so it can overlay your content and catch your swipe gesture.
If you put your ViewPager within the FrameLayout (that's why it's called content_frame), it should work as expected.
A:
Yeah peitek is right to be more clarify this is my xml file.
<fragment
android:id="@+id/single_map_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
<include
layout="@layout/app_bar_map_view_tt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/single_map_appbar"/>
<!--This should be the last element to maintain right to left closing gesture.-->
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_map_view_tt"
app:menu="@menu/activity_map_view_tt_drawer" />
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mixed Effects, Doctors & Operations: predicting on new data containing previously unobserved levels, and updating our confidence accordingly
Here's a quick sketch of a hypothetical situation. There are Doctors $\{1, \ldots, J\}$ who perform different types of operations $\{1, \ldots, K\}$. Our response variable is whether the operation was a success ($Y_{i,j,k} = 1$ implying that for the $i$th patient for doctor $j$ for which he performed operation $k$ was a success).
Doctors have some inherent level of skill $\alpha_j$, and operations have some inherent level of difficulty $\beta_k$. We might think that there are some fixed known number of operations, but that Doctor skill is normally distributed, drawn from a population of doctors. So we assume that Doctor skill is distributed as $\alpha_j \sim N(0, \sigma_\alpha^2)$.
A crude model might look something like the following, where the Logit of the probability of success is a sum of some base intercept, the skill of the doctor, and the difficulty of the operation.
$$
\text{Logit}(\text{Pr}(Y_{i,j,k} = 1)) = \mu_0 + \alpha_j + \beta_k.
$$
This naive model seems to be a straightforward mixed effects model. Doctors are levels we observe from some larger population, and their skills are random intercepts. The Operations can be categorical fixed effects (determining difficulty). In reality we would certainly expect there to be an interaction between Doctor and Operation (they specialize!), but I'll ignore that for now as I'm just trying to understand a theoretical example.
Here's the crux of the issue. I want an approximate model (this need not be perfectly rigorous) which can look at a new batch of data and guess "About how many failed operations do we expect?". This is some function of the skill of the doctors involved, how many operations they do, and what those operations are. However, in practice, my new batch of data will contain a mix of doctors which I know a great deal about, as well as new recruits fresh out of med school! (Who lack previous data to indicate their skill).
Does a mixed effects model still work in this case? Basically, I want a model which defaults to some sort of baseline assumption of skill when we haven't observed this doctor in practice, and then updates it as we observe more (until we are very confident if we have a large sample for them). This is clearly a Bayesian framework: we have some prior belief about their skill, and we update it to reflect new information.
As a concrete example, our new data contains operations from Doctors A, B, and C. Doctor A is a veteran who has performed 5,000 operations, and we can confidently estimate that they are much more skilled than average as they rarely fail. Doctor B just moved from a different hospital, so we assume they are exactly as skilled as the average doctor. Doctor C has performed 100 operations with a higher failure rate than usual, so we think they are less skilled but recognize that it's a small sample so we hedge our bets a bit. Again, this is an obviously bayesian set-up, but I'm not sure if it can be accomplished using a mixed effects model, or how to actually build a reasonable bayesian model to reflect this.
So, in total,
Can a mixed effects model work here? (That is, update its confidence on doctor skill based on how much past data we've seen for this specific random intercept).
Should I instead move to a more directly Bayesian framework? (I'm sure the mixed effects model has a Bayesian interpretation, but again I'm not sure if it specifically does what I need here).
Do you have any ideas for models which might do what I need here? This is meant to be a rough benchmark, not an elite predictive model, so simple and intuitive is fine even if it doesn't exactly fit the scenario (the Doctors and Operations is just an example anyways).
Thank you all for any advice you can provide!
A:
What you describe is the concept of dynamic predictions from mixed models.
Initially, when you have no information for a doctor you only use the fixed effects in the prediction, i.e., you put his/her ability level equal to the average ($\alpha_j = 0$).
But, as extra information is recorded you can update your predictions by calculating the random effect of the doctor. You get this from the posterior/conditional distribution of the random effects $\alpha_j$ given the observed data $y_j$.
You can find more information on these predictions in the Dynamic Predictions vignette of the GLMMadaptive package.
A:
I think a Bayesian approach might be beneficial. When predicting for an unobserved category in a Bayesian mixed model, you generate posterior predictions by sampling the $\alpha_j$ from the fitted $N(0, \sigma^2_\alpha)$ (aside from sampling the fixed effects from the fitted posterior). This way, you will see high uncertainty for the new doctor - which is IMHO a good thing. The amount of uncertainty will be related to the fitted $\sigma^2_\alpha$, so when most doctors are similar, you will get lower uncertainty. After you have more data, you would refit the model and the uncertainty for the (now observed) doctor will gradually shrink.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why don't we get to indicate the appropriate site for off-topic questions?
When voting to close a question as off-topic in the main site, we have the option to check as reason,
"This question belongs on another site in the Stack Exchange network"
Then a new window opens... and the only option we get is that the question belongs to the meta of economics.se.
I don't know if this is a bug or deliberate, but if it is deliberate, it renders the option totally useless -the point is to be able to select among the SE sites.
I understand that migration itself (decision and execution) is and should be the responsibility of moderators, but we should be able to indicate to them what site we think is the appropriate one, to avoid duplication of effort.
I checked the same feature in Cross Validated, and there, one gets the option, apart from migration to meta, to indicate math.se and stackoverflow.
Then I guess someone, either a moderator or an SE-associate could (and should) add to our choices in the main for off-topic/migration suggestions, the following four sites
https://money.stackexchange.com/
https://quant.stackexchange.com/
https://stats.stackexchange.com/
https://math.stackexchange.com/
A:
UPDATE:
Based on When should we consider adding a default migration path? and https://meta.stackexchange.com/a/276084/274708
it seems like (1) migration paths are not likely to be added while this site is still in beta, and (2) a migration path is not likely to be deemed appropriate until we are sending "tens or hundreds" of migrations to a site within each 90 day period (we are currently well short of that level).
For now, please continue to handle migration requests using the flag feature.
Original post
It seems we can have a maximum of four external sites listed, but I couldn't find an option to add them myself. I have asked on Meta.SE to find out how to get this done.
For the record, we don't actually migrate that much. Here is a complete list of every question that has ever been migrated from econ.SE.
My understanding is that sites will be added to the migration target list only on the basis of evidence that there are a significant number of migration candidates for that site. Based on the above list, only Money.SE seems to generate a significant number of questions for migration right now so I think it unlikely that sites other than Money.SE will be added to the list.
In the event of a question that belongs on a site other than Money.SE, the relevant response will probably continue to be flagging the question for moderator attention. The mods can migrate to any site and other migration targets can be added to the list if and when we build up a substantial stream of questions that have been migrated to them.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Which function (s) is(are) the k-th derivative of itself?
As I attempted to solve for a function that is the $k$-th derivative of itself where $k$ is some natural number, and generalise the result, I realised it gets very hard to prove anything. For $k= 1$, apart from trivial corner cases, it's the exponential function with any constant multiplied.
For $k=2$, along with the exponential function and it's reciprocal, it works for their sum along with any mixture by constants multiplied...
For any $k$, I guessed it should be of the form $e^{x w}$ where w is the $k$-th root of unity. And we can add all these $k$ terms for each root with constants multiplied.
While it is easy to verify it's satisfying the condition, it is beyond my scope to prove this is the only family of functions that satisfy it.
I am hoping for some interesting math at work here, and want to know if this is an already established fact. Also, how do I prove anything here?
A:
So, your unknown function satisfies $y^{(k)}(t) \equiv y(t)$. This is called a linear differential equation of $k$-th order. There is an established method for solving such equations. It is based on observation that you can pick any function $y_j (t) = \exp{\omega_j t}$, where $\omega_j = \exp(\frac{2\pi i}{k}j)$ and it would be a solution. Moreover, any solution of this equation can be expressed as some linear combination $\sum\limits_{p=1}^{k} \alpha_p y_p(t)$, $\alpha_p \in \mathbb{C}$. The resulting solution is a complex valued function (i.e., a mapping $\mathbb{R} \mapsto \mathbb{C}$), and if you want to get only real-valued functions, you can do this by appropriate choice of $\alpha_p$. Namely, if $\omega_j \not \in \mathbb{R}$ you put $\alpha_{k-j} = \overline{\alpha_j}$, then a pair of terms $\alpha_j y_j(t) + \alpha_{k-j} y_{k-j}(t)$ transforms to $\alpha_j y_j(t) + \overline{(\alpha_j y_j(t))}$ and basically to $$2 \mathrm{Re}\,(\alpha_j y_j(t)) = 2(\mathrm{Re}\,\alpha_j \cos{\omega_j t} + \mathrm{Im}\,\alpha_j \sin{\omega_j t}).$$ Thus, you can also get any linear combination of $\cos \omega_j t$ and $\sin \omega_j t$ as a solution of such equation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the correct way of getting the value of a selected drop down item using JavaScript?
I thought i knew this, and now I'm quite embarassed becuase I don't :-/
This JSFiddle demonstrates two ways of getting the value of a selected drop down item in JavaScript. Code reproduced here:
var obj = document.getElementById("test");
alert(obj.options[obj.selectedIndex].value); //like this
alert(obj.value); //or like this
Quirksmode suggests that some older broswers don't support the latter (http://www.quirksmode.org/js/forms.html), and value isn't a supported attribute in the HTML 4.01 spec.
So I wondered, which is the correct standarised way of doing this?
Anyone?
A:
David is correct. If you want full compatibility you might want to use something like:
var options = document.getElementById('securityWalkInTime').children;
var value = [];
for (var i=0;i<options.length;i++) {
var option = options[i];
if (option.selected === true) {
value.push(option.value ? option.value : option.text);
}
}
This will definitely work, however, for all practical cases I would use the latter of your example.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Finding the maximum value in a binary tree
I have to find the maximum value in a binary tree. This is how I did it iteratively:
int maxValue(Node* node)
{
if (node == nullptr)
throw "BT is empty";
int max = node->data;
for (Node* left = node; left != nullptr; left = left->left)
{
if (left->data > max)
max = left->data;
}
for (Node* right = node; right != nullptr; right = right->right)
{
if (right->data > max)
max = right->data;
}
return max;
}
I don't know if this is the best way to do it. How can this be improved? Is there a recursive solution?
A:
Trees are often most useful when they're sorted. If the tree is sorted, you can just descend into the right side of the tree.
Since we're assuming an unsorted tree, we have to search the whole thing. Let's build this up by cases. First assume that the current node has the largest value:
int maxValue(Node *node)
{
if (node == nullptr)
throw "BT is empty";
max = node->data;
return max;
}
Nice, but not likely. We can do better. What if the largest value is in the left side of the tree?
int maxValue(Node *node)
{
if (node == nullptr)
throw "BT is empty";
max = node->data;
if(node->left != nullptr) {
int leftMax = maxValue(node->left);
if(max < leftMax)
max = leftMax;
}
return max;
}
Great! Now we have a function that will check its left side for larger values, all the way down the left side. But what if the largest value is on the right of some node? We'd better cover that case too:
int maxValue(Node *node)
{
if (node == nullptr)
throw "BT is empty";
int max = node->data;
if(node->left != nullptr) {
int leftMax = maxValue(node->left);
if(max < leftMax)
max = leftMax;
}
if(node->right != nullptr) {
int rightMax = maxValue(node->right);
if(max < rightMax)
max = rightMax;
}
return max;
}
Now since we only have to check for NULL that will throw on the first node we can optimize slightly:
int maxValue(Node *node)
{
if (node == nullptr)
throw "BT is empty";
return maxValueNonNull(node, node->data);
}
int maxValueNonNull(Node* node, int currentMax)
{
if (node == NULL)
{ return currentMax;
}
currentMax = currentMax > node->data ? currentMax : node->data;
int leftMax = maxValueNonNull(node->left, currentMax);
int rightMax = maxValueNonNull(node->right, currentMax);
return leftMax > rightMax ? leftMax : rightMax;
}
That should do it.
A:
With most issues already mentioned, here is a simpler version of the code mentioned by GargantuChet. A recursive call to return the maximum value in a binary tree.
int getMax(Node* root){
if(root==NULL){
return Integer.MIN_VALUE; // the minimum value so that it does not affect the calculation
}
// return the maximum of the data of the current node ,its left child and its right child.
return Math.max(root->data, Math.max(getMax(root->left), getMax(root->right)));
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Two-step watermark applying using imagemagick
I am trying to apply watermark to an image of any size using two steps in one command line:
Tile small png image and overlay it over the target image.
Overlay a logo at top left corner without tiling.
I don't understand the imagemagick command line principles and can't create a command line to make these operations without creatig temporary file between steps 1 and 2. But I am sure this is possible :)
Please help me to do that.
Thanks.
A:
There are many ways to achieve this, but the simplest would be to leverage ImageMagick's Stack notation "()".
Simply group the first step into a command wrapped in parentheses, and omit the output filename.
convert \( \
wizard: \
-size 480x640 \
-background transparent \
tile:label.png -composite \
\) \
-gravity NorthEast rose: \
-composite output.png
The above will compose the label.png as a repeating image over the wizard: image. Note, in this example I provided the -size and -background attributes. The result of the Image Stack will be accepted as the input image for the second -composite operation; which, places the rose: image in the top right.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make a actionbar drop-down-menu that shows items horizontally?
I want to make a action-bar drop-down-menu that shows items (icons) horizontally. Like this:
This is suppose to be a action-bar withe drop-down menu, where you can choose a color.
So it should show the icons (colors) horizontally and the icons should be clickable. Until now I have only managed to make a vertical list.
If possible I would like to do this in XML.
A:
The ActionBar is not designed for such a use-case. The ActionBar buttons are meant to replace the old options menu that could be triggered with a separate hardware button on older devices (pre HC/ICS). The overflow button (the one with the 3 dots) that you've drawn in your sketch is used when there isn't enough room to show all buttons (the Android framework takes care of this automatically), so those will be grouped in the overflow menu. Overriding this behavior is a bad idea (if even possible).
Instead you should consider another approach: Add one ActionButton to the ActionBar that is meant to handle the color chooser. When this button is clicked the best solution is to show an AlertDialog (you can easily insert your on Views here that show the colors you want) because this will work best even if the button is hidden in the overflow menu.
Alternatively you could trigger a PopupMenu or implement some QuickAction to handle the color chooser (this will probably suck if your button is hidden in the overflow menu and will also lead to a very confusing UI).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I find the biggest string of numbers?
There are array elements e.g.: 2 3 4 7 8. I need to write to console what is the biggest string of numbers, so the solution will be 2-4, because 2 3 4 --> 4-2=2 is bigger than 7 8 -> 8-7=1
I need to find the longest growing row, which increases by 1. 2 3 4 (2+1=3, 3+1=4 and 4+1= 7 it's wrong. And in 2 3 4 row has 2 element and it's the longest not 7 8 where it is just 1
int first=0;
int last=0;
for(int i=0; i < n; i++)
{
if(t[i]-t[i-1]==1)
{
first=t[i];
}
else
{
last=t[i];
}
}
With this code the solution is 7 8, so the code will the last pair (7 8).
A:
The following function takes an int array and size as input, as in your example code. And return the maximum increasing size. It may not be what you are looking for exactly, but your question is not very clear.
int func(int[] arr, int size) {
// trivial case
if (size == 0)
return 1;
int max = 1; // At least 1 when there is an element
int cur = 1; // At least 1 when there is an element
int first;
int second;
int cur_first;
cur_first = arr[0];
for (int i = 0; i < size-1; i++) {
if (arr[i] == arr[i+1] -1) {
cur ++;
}
else {
if (cur > max) {
max = cur;
first = cur_first;
second = arr[i];
}
cur = 1;
cur_first = arr[i+1];
}
}
if (cur > max) {
cur = max;
first = cur_first;
second = arr[size-1];
}
return max
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to change the return value in a finally clause in C#?
Assume that you have a C# method with a return statement inside a try block. Is it possible to modify the return value in the finally block?
The obvious approach, using return in the finally block, won't work:
String Foo()
{
try
{
return "A";
}
finally
{
// Does not compile: "Control cannot leave the body of a finally clause"
return "B";
}
}
Interestingly, this can be done in VB: Return inside Finally is forbidden, but we can abuse the fact that (probably for reasons of backwards compatibility) VB still allows the return value to be modified by assigning it to the method name:
Function Foo() As String ' Returns "B", really!
Try
Return "A"
Finally
Foo = "B"
End Try
End Function
Notes:
Note that I ask this question purely out of scientific curiosity; obviously, code like that is highly error-prone and confusing and should never be written.
Note that I am not asking about try { var x = "A"; return x; } finally { x = "B"; }. I am aware that this doesn't change the return value and I understand why this happens. I'd like to know if there are ways to change the return value set inside the try block by means of a finally block.
A:
Assume that you have a C# method with a return statement inside a try block. Is it possible to modify the return value in the finally block?
No.
You can however modify the return value outside the finally block:
static int M()
{
try
{
try
{
return 123;
}
finally
{
throw new Exception();
}
}
catch
{
return 456;
}
}
Just because there was originally a "return 123" does not mean that the method will return 123, if that's what your question is actually getting at. This method returns 456.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Hyper-V replication - avhdx files and checkpoints on replica target, but none on source
I am replicating from one Hyper-V server to another, on the source there are no checkpoints shown in Hyper-V manager, and a single vhdx file.
On the target, there is a checkpoint from months ago along with avhdx files, and this checkpoint cannot be deleted.
Any ideas please? Is it possible to delete these or just resync from scratch again?
A:
Hyper-V Replica doesn't attempt to replicate checkpoints. It's a disaster recovery strategy for VMs, and it only replicates the currently running instance of the VM (and not the frozen moments in the past that those checkpoints represent.)
What Replica does do, however, is create checkpoints periodically while it does this replication. Each checkpoint that you see on the recovery server represents an application-consistent moment that you might recover if you do fail over. These don't exist on the primary server because you can't "recover" a lost VM on the machine that hasn't lost it yet.
You should be able to delete the checkpoint on the recovery server. I'm not sure why that's failing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Este/Esta/Esto when referring to an idea
I was taught that "esto" can be used when referring to an idea but I have seen cases where "este" or "esta" is used.
In this sentence:
Aunque el proyecto de ley fue rechazado, esta ha sido la primera vez que la iniciativa de aprobar el aborto llega tan lejos.
The "esta" is referring to an idea but it is saying that it is "la primera vez" which is feminine. Is this why "esta" is used instead of "esto"?
A:
In these kind of sentences, este/esta acts as a pronoun. If you want to know which noun it is replacing, just convert it into an adjective by moving the corresponding noun in the sentence:
Esta ha sido la primera vez que la iniciativa de aprobar el aborto llega tan lejos.
Esta vez ha sido la primera que la iniciativa de aprobar el aborto llega tan lejos.
You can do this with any sentence of this kind. The resulting senteces will only make sense if you move the right noun:
Este es el último arroz que cocino, me salen fatal.
Este arroz es el último que cocino, me salen fatal.
Este es el mejor día de mi vida.
Este día es el mejor de mi vida.
Esta será la primera visita que hago a mi padre en años.
Esta visita será la primera que hago a mi padre en años.
De todos los cuadros que he visto, este es el que más me gusta.
De todos los que he visto, este cuadro es el que más me gusta.
You also mention esto, but this word can act only as a pronoun, you cannot turn it into an adjective.
Esto es lo mejor que me ha pasado en la vida.
In this case esto replaces something that is not present in the sentence, something that has probably been mentioned before in the conversation.
A:
Yes, the sentence is
Esta ha sido la primera vez
"La primera vez" is the subject, and it's feminine, so "esta" must be feminine too. You're right: it's referring to "primera vez", not to the "idea".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Enter parameter value but I've already included one in the query
I've got a SQL query in my VB6 project that is performing a three-way INNER JOIN in an Ms-Access database.
The VB6 query is:
SQL = "SELECT popsLines.stockCode, popsLines.orderNumber, popsOrders.dateOrdered, popsReceipts.dateReceived, popsReceipts.reference" & _
" FROM (popsOrders INNER JOIN popsLines ON popsOrders.orderNumber = popsLines.orderNumber)" & _
" INNER JOIN popsReceipts ON popsOrders.orderNumber = popsReceipts.orderNumber" & _
" WHERE (([WHERE popsLines].[stockCode]=" & sqlString(m_sStockCode) & "));"
This wasn't working, it returned an error saying
No value given for one or more required parameters
So then next thing I did was copy the value in the SQL variable and paste it into an Access query, with the value of the m_sStockCode parameter.
SELECT popsLines.stockCode, popsLines.orderNumber, popsOrders.dateOrdered, popsReceipts.dateReceived, popsReceipts.reference
FROM (popsOrders INNER JOIN popsLines ON popsOrders.orderNumber = popsLines.orderNumber)
INNER JOIN popsReceipts ON popsOrders.orderNumber = popsReceipts.orderNumber WHERE (([WHERE popsLines].[stockCode]="010010003"));
When executing this, it said
Enter Parameter Value: WHERE popsLines.StockCode
Why isn't it accepting the query as it is?
I've also tried changing there WHEREclause to
(( WHERE [popsLines].[stockCode]="010010003"));
but got
Syntax error (missing operator) in query expression '((WHERE [popsLines].[stockCode]="010010003"))'
A:
The last part - your WHERE clause - is garbled. It should read:
.. WHERE ([popsLines].[stockCode]='010010003');
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to write log inside my rubygem that will be used in a rails app?
I'm developing a rubygem that will be used in a rails app. In this rubygem i need to log some information (warnings, errors...).
I saw some gems to do this, like logging, but apparently i need no configure the log output (stdout, some file).
My rails app log the messages in a file. So, my question: Is there a way to my gem use the same log configuration that my rails app uses? or my gem will send the log according to his own configuration?
A:
You may use Rails.logger directly, which is valid if your gem will always only be used within a Rails application. You may alternatively define a logger for your gem namespace and default to Rails.logger if defined, or Logger.new(STDOUT) if it's not, along with a writer, so it's overridable:
module MyGem
def self.logger
@@logger ||= defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
end
def self.logger=(logger)
@@logger = logger
end
end
Whatever the case, you will use it like this:
MyGem.logger.debug "it works"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using Regex to parse a chat transcript
I need to classify each line as "announce, whisper or chat" once I have that sorted out I need to extract certain values to be processed.
Right now my regex is as follow:
var regex = new Regex(@"^\[(\d{2}:\d{2}:\d{2})\]\s*(?:(\[System Message\])?\s*<([^>]*)>|((.+) Whisper You :))\s*(.*)$");
Group 0 is the entire message.
Group 1 is the hour time of when the message was sent.
Group 2 is wether it was an announce or chat.
Group 3 is who sent the announce.
Group 4 is if it was a whisper or not.
Group 5 is who sent the whisper.
Group 6 is the sent message by the user or system.
Classify each line:
if 4 matches
means it is a whisper
else if 2 matches
means it is an announce
else
normal chat
Should I change anything to my regex to make it more precise/accurate on the matches ?
Sample data:
[02:33:03] John Whisper You : Heya
[02:33:03] John Whisper You : How is it going
[02:33:12] <John> [02:33:16] [System Message] bla bla
[02:33:39] <John> heya
[02:33:40] <John> hello :S
[02:33:57] <John> hi
[02:33:57] [System Message] <John> has left the room
[02:33:57] [System Message] <John> has entered the room
A:
You can always break it down in multiple lines to make it more readable. You can also use named groups which take the "magic" out of the group numbers (4 == whisper, 3 == normal, etc).
var regex = new Regex(@"^\[(?<TimeStamp>\d{2}:\d{2}:\d{2})\]\s*" +
@"(?:" +
@"(?<SysMessage>\[System Message\])?\s*" +
@"<(?<NormalWho>[^>]*)>|" +
@"(?<Whisper>(?<WhisperWho>.+) Whisper You :))\s*" +
@"(?<Message>.*)$");
string data = @"[02:33:03] John Whisper You : Heya
[02:33:03] John Whisper You : How is it going
[02:33:12] <John> [02:33:16] [System Message] bla bla
[02:33:39] <John> heya
[02:33:40] <John> hello :S
[02:33:57] <John> hi
[02:33:57] [System Message] <John> has left the room
[02:33:57] [System Message] <John> has entered the room";
foreach (var msg in data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
Match match = regex.Match(msg);
if (match.Success)
{
if (match.Groups["Whisper"].Success)
{
Console.WriteLine("[whis from {0}]: {1}", match.Groups["WhisperWho"].Value, msg);
}
else if (match.Groups["SysMessage"].Success)
{
Console.WriteLine("[sys msg]: {0}", msg);
}
else
{
Console.WriteLine("[normal from {0}]: {1}", match.Groups["NormalWho"].Value, msg);
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
System.IO.FileNotFoundExecption, even when file is present
I am uploading files using GUID for their names and then I am trying to download them but I am getting a file not found error even when file is there on the server,I think, I am doing something wrong with command arguement but I am not sure what. Please tell me where I am wrong, any help is appreciated.
Database schema:
I have 2 columns : ReceiptFileName - Stores filename without GUID for UI.
filename - Stores filename with GUID.
Aspx code:
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='<%# Bind("filename") %>' Text='<%# Bind("ReceiptFileName") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Code for Upload:
{
if (FileUpload1.HasFile)
{
//check file Extension & Size
string filename = FileUpload1.PostedFile.FileName;
{
filename = filename + Guid.NewGuid();
}
int filesize = FileUpload1.PostedFile.ContentLength;
if (filesize > (20 * 1024))
{
Label1.Text = "Please upload a zip or a pdf file";
}
string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileextention.ToLower() != ".zip" && fileextention.ToLower() != ".pdf")
{
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "Please upload a zip or a pdf file";
}
else
{
//string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string ReceiptFileName = Path.GetFileName(filename);
//save file to disk
FileUpload1.SaveAs(Server.MapPath("Reciepts/" + ReceiptFileName));
}
Code For Downlaod:
protected void gridExpenditures_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AppendHeader("content-disposition", "FileName=" + e.CommandArgument);
Response.TransmitFile(Server.MapPath("~/Reimbursement/Reciepts/") + e.CommandArgument);
Response.End();
}
}
A:
It might be just silly but I can only read the file paths are different:
FileUpload1.SaveAs(Server.MapPath("Reciepts/" + ReceiptFileName));
Vs:
Response.TransmitFile(Server.MapPath("~/Reimbursement/Reciepts/")
The last path has Reimbursement in it. The first doesn't.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to reorder data.table columns (without copying)
I'd like to reorder columns in my data.table x, given a character vector of column names, neworder:
library(data.table)
x <- data.table(a = 1:3, b = 3:1, c = runif(3))
neworder <- c("c", "b", "a")
Obviously I could do:
x[ , neworder, with = FALSE]
# or
x[ , ..neworder]
# c b a
# 1: 0.8476623 3 1
# 2: 0.4787768 2 2
# 3: 0.3570803 1 3
but that would require copying the entire dataset again. Is there another way to do this?
A:
Use setcolorder():
library(data.table)
x <- data.table(a = 1:3, b = 3:1, c = runif(3))
x
# a b c
# [1,] 1 3 0.2880365
# [2,] 2 2 0.7785115
# [3,] 3 1 0.3297416
setcolorder(x, c("c", "b", "a"))
x
# c b a
# [1,] 0.2880365 3 1
# [2,] 0.7785115 2 2
# [3,] 0.3297416 1 3
From ?setcolorder:
In data.table parlance, all set* functions change their input by reference. That is, no copy is made at all, other than temporary working memory, which is as large as one column.
so should be pretty efficient. See ?setcolorder for details.
A:
One may find it easier to use the above solution, but instead sort by column number. For example:
library(data.table)
> x <- data.table(a = 1:3, b = 3:1, c = runif(3))
> x
a b c
[1,] 1 3 0.2880365
[2,] 2 2 0.7785115
[3,] 3 1 0.3297416
> setcolorder(x, c(3,2,1))
> x
c b a
[1,] 0.2880365 3 1
[2,] 0.7785115 2 2
[3,] 0.3297416 1 3
|
{
"pile_set_name": "StackExchange"
}
|
Q:
calc formula interpretation?
Reading this twitter and applying Pemdas I believe that the answer should be 9, but applying this formula in emacs-calc yields 1:
'6/2(1+2) ==>
alg' 6 / 2 * (2 + 1)
1
Hard to believe I'm wrong, but even harder to believe emacs-calc is wrong.
A:
(calc) Basic Arithmetic:
When combining multiplication and division in an algebraic formula,
it is good style to use parentheses to distinguish between possible
interpretations; the expression a/b*c should be written (a/b)*c or
a/(b*c), as appropriate. Without the parentheses, Calc will
interpret a/b*c as a/(b*c), since in algebraic entry Calc gives
division a lower precedence than multiplication. (This is not
standard across all computer languages, and Calc may change the
precedence depending on the language mode being used. See (calc) Language Modes.) This default ordering can be changed by setting the
customizable variable calc-multiplication-has-precedence to nil
(see (calc) Customizing Calc); this will give multiplication and division
equal precedences. Note that Calc’s default choice of precedence
allows a b / c d to be used as a shortcut for
a b
---.
c d
|
{
"pile_set_name": "StackExchange"
}
|
Q:
using make_tuple for comparison
Possible Duplicate:
Implementing comparision operators via 'tuple' and 'tie', a good idea?
sometimes I need to write some ugly functors
e.g.
lhs.date_ < rhs.date_ ||
lhs.date_ == rhs.date_ && lhs.time_ < rhs.time_ ||
lhs.date_ == rhs.date_ && lhs.time_ == rhs.time_ && lhs.id_ < rhs.id_ .....
it really annoyed me.
So I started avoiding that writing following:
std::make_tuple( lhs.date_, lhs.time_, lhs.id_ ) <
std::make_tuple(rhs.date_, rhs.time_, rhs.id_ );
and I am almost happy, but mind that I'm probably using tuples not by their purpose makes me worry.
Could you criticize this solution?Or it's a good practice?How do you avoid such comparisons?
UPDATE:
Thanks for pointing on std::tie to avoid copying objects.
And thanks for pointing on duplicate question
A:
The declaration of std::tuple comparison operators states that:
Compares lhs and rhs lexicographically, that is, compares the first elements, if they are equivalent, compares the second elements, if those are equivalent, compares the third elements, and so on.
So what you are doing, other than having the possibility of creating unneeded temporaries (probably optimized away), seems ok to me.
Note that equivalent means !( lhs < rhs ) && !( rhs < lhs ) and not lhs == rhs, that's equality. Assuming equivalent and equality mean the same for your class, this would be ok. Note that this is no different than, for instance, accessing a set/map by key.
In order to avoid the temporaries, you can use std::tie which makes a tuple of lvalue references to its arguments:
std::tie( lhs.date_, lhs.time_, lhs.id_ ) <
std::tie( rhs.date_, rhs.time_, rhs.id_ );
In a similar fashion, std::forward_as_tuple makes a tuple of rvalue references.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
asp.net: Read data from uploaded Excel document
I would like to know the best way to read data from an uploaded excel document. Im currently using http://exceldatareader.codeplex.com/, which works good. The problem is that it cant read the values from checkboxes or radiobuttons. Im using asp.net framework 3.5. Any help is appreciated. Thanks
A:
IF you have Excel installed on your system, you could include Microsoft.Office.Interop.Excel assembly and use that to do everything you need.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Calculating a Covered Call Strike with N% Probability that Shares Won't be Called Away
I'm starting to experiment with covered call strategies, and I'm trying to find the right strike price to sell for my covered calls such that I can maximize premium while being generally "confident" that the strike price won't hit and I can just bank the premium. "Confidence" would hopefully be an adjustable parameter in my calculations; I.e., maybe this week I'm willing to sell with 70% confidence whereas next week I'm more conservative and willing to sell calls with 95% confidence that shares won't be called away. My plan is to write weekly covered calls against steady/boring unsexy stocks.
I downloaded weekly adjusted close data and calculated the weekly absolute price move and the percentage move from one week to the next for the last 2 years. That became my sample set.
Here are some things I considered:
I started by trying to calculate the normal distribution (sigma) for
all of the absolute price changes over my sample. I was thinking that if I could settle on a price that's 2-sigma higher than the current price, then I'd have 95% confidence that my shares wouldn't be called away. But this is a pretty rudimentary approach, and potentially skews more to the positive side than negative (or vice-versa) depending on recent stock movement. I don't think this is a good approach.
So then I tried separating the positive moves and negative moves, and doing a normal distribution over those samples. I was thinking If I set my strike price at current price + average positive move + sigma then I'd get a 68% confidence that my underlying would stay below the strike price. I think that method skews artificially high though, just based on where the majority of the distribution occurs if graphed on a number line.
I also considered using a percentile of price moves over that sample and basing strategy on that, i.e., just choose the positive move that occurs at the 85th percentile and set the strike at current price + 85th percentile price, but... I don't think that's a statistically sound approach either.
So I've done some homework, but I'm pretty sure I'm not on the right track. And statistics are not my strong suit.
Is there a well-defined way to choose strike prices that meet a statistical confidence threshold like what I'm describing?
A:
Using an option's delta could be a quick and easy way to back into the probability that you are seeking. For example, if you are looking for an option that has a 70% chance of expiring worthless, you would look for an option with a delta of 1 - .70 or .30.
There are lots of resources regarding this technique and the potential inaccuracies of it. I don't know of any statistical technique that will be any better or worse for this purpose so please check the links below and look around for more information before using something like this to make a decision.
From Wikipedia: As a proxy for probability
Main article: Moneyness
The (absolute value of) Delta is close to, but not identical with, the
percent moneyness of an option, i.e., the implied probability that the
option will expire in-the-money (if the market moves under Brownian
motion in the risk-neutral measure).[5] For this reason some option
traders use the absolute value of delta as an approximation for
percent moneyness. For example, if an out-of-the-money call option has
a delta of 0.15, the trader might estimate that the option has
approximately a 15% chance of expiring in-the-money. Similarly, if a
put contract has a delta of −0.25, the trader might expect the option
to have a 25% probability of expiring in-the-money. At-the-money calls
and puts have a delta of approximately 0.5 and −0.5 respectively with
a slight bias towards higher deltas for ATM calls. The actual
probability of an option finishing in the money is its dual delta,
which is the first derivative of option price with respect to
strike.[6]
A note of caution from volcube.com regarding this in practice:
This probability is highly theoretical. It is not a FACT about the
options that will always be true. All it means is that if every
assumption in the pricing model that has been used to formulate the
delta turns out to be true, then the delta can be interpreted as the
probability of expiring in-the-money, in some cases. This is very
unlikely to be the case consistently or even frequently. Volatility
can be higher or lower than expected. Interest rates can move. Indeed,
for some options where cost of carry or dividends are relevant, this
interpretation of delta is even more precarious. Nevertheless, as a
rule of thumb, option delta as the probability of expiring
in-the-money is undoubtedly useful to know.
More info on interpreting delta in this way can be found here:
Macroption
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is the ciphertext given by encrypting a file with CipherInputStream the same length then the file itself
I'm trying to encrypt files using CipherInputStream. I want to add a progress bar during the encryption.
The problem is that the ciphertext doesn't seem to be the same length as the file. It means I cannot know when cipherInputStream.read(bytes) is going to return -1.
How to know that in advance?
A:
It depends on the mode of operation, so the stream itself won't tell you this. Generally however, when using a symmetric cipher, the size of the ciphertext should only be one block more at the maximum. So in general for long ciphertext, only displaying the full 100% may be an issue (but then you're done, right?).
For CTR mode, there is no overhead.
For ECB or CBC mode with PKCS#7 padding ("PKCS5Padding" in Java) the overhead is maximum one full block and at minimal one byte. You can calculate the amount of padding by using:
int n = cipher.getBlockSize();
int pad = n - plaintextSize % n;
For GCM mode the authentication tag is included, which defaults to 16 bytes.
For all modes except ECB, the IV may be prefixed to the ciphertext.
Great, that's my direct answer. Let's invalidate it.
Don't use CipherInputStream to encrypt. Use CipherOutputStream to encrypt instead. That way you know exactly when everything ends: when the last block of the original input stream has been encrypted. After all, you don't need encrypted ciphertext in your application, right? See this related answer about encoding / decoding.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I don't know what my L1 is and want to find out
I've been doing personal research in Second Language Acquisition by reading a book on the subject (Understanding Second Language Acquisition -- by Lourdes Ortega) and I've become convinced that the L1 has a huge effect on the way an individual thinks and communicates.
However, as a very young child I first spoke Russian at a low level, and then spoke Hebrew from the age of about 5 until 10, where I soon after lost Hebrew and English became my native language.
I now speak English at a native level with no apparent accent and am maintaining an intermediate level of Russian and am re-learning my Hebrew from ground up.
Two questions arise in my mind:
Is it possible that my thinking in general and communication in English is suffering because my L1 is still Hebrew, yet I lack the vocabulary to communicate?
Has my L1 become English at an age as late as 10-11?
Now a question that can potentially be answered:
If I were to re-learn Hebrew, how would I be able to determine whether my L1 is indeed English or in fact Hebrew, or perhaps even a mix of the two (three if you include Russian)? Is there some sort of analysis I could perform on myself?
A:
You have to first determine how you are going to define "L1", which isn't a scientific term in linguistics. It sort of stands for "first language", in which case Russian is your L1. Though perhaps Hebrew is the first language you became fluent in, suggesting another definition. A third possibility is "dominant" ("number one", not first), so from what you say it it would be English. It can't be a mix, since "Hebrew and English" isn't a language, it's two languages. But again, since L1 isn't a defined technical term, you can define it however you want and maybe "Hebrew and English" could be an answer. If you want, you could adopt the definition promulgated by Wikipedia (for "first language"), but please bear in mind that that article is mostly unsubstantiated opinions, not backed up by studies of usage in technical articles.
On LLSE they might have an informed opinion of how the term "L1" is used in language learning journals.
A:
How is "L1" used in these texts you're reading? Is it
a) about the influence of the L1 on the syntax and pronunciation of the L2?
b) is it just about the L2 label for a new adult learned language?
c) is it about cognitive development in children?
For a and c it is complex and you are a very special case. For b, it's just about difficulties in learning an additional language as an adult.
Yes, you may very well have more than one L1.
You state that you have no accent in English (most likely no accent because of when you started immersion, but have others confirmed that?). Do you have an no accent in Hebrew or Russian? Do you make grammar mistakes like natives in those? Then those are probably both L1's also. Whether you're labeled L1 for Hebrew or Russian or English just says what kind troubles you will have learning more of the language. If you're L1 then there's no accent, basic grammar is no problem, elementary vocab too, and you will learn more complicated grammar quickly. L2 you may never get a perfect accent, and native-like grammar (with mistakes like a native) will require lots of practice (but can be achieved).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to put an time interval on random image change
i want to put an interval ,so that it will generate each time a random link from this function:
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="/documents/templates/bilgiteknolojileri/standalone.swf"
myimages[2]="/documents/templates/bilgiteknolojileri/mobil.swf"
myimages[3]="/documents/templates/bilgiteknolojileri/3b2.swf"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1
document.write('<embed wmode="transparent" src="'+myimages[ry]+'" height="253" width="440"></embed>')
}
random_imglink()
but the problem is that after i integrate the timeout to a func like this
random_imglink()
setInterval( "random_imglink()", 2000 );
after 2 sec it shows just the embed object, i mean the only thing that displayed on the page is the embed object, thats all.. and after another 2 sec it doesn't change the object... all i want is to change just the link inside the embed object, so that it wont brake the page vision, please help me!
A:
You should not write the embed object in timeout but overwrite it there.
Add the embed object directly into your HTML:
<embed id="randomEmbed" ...other parameters...></embed>
Then in your timer function change the writing to something like this:
document.getElementById("randomEmbed").src = myimages[ry];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Subtleties of exec in TSQL
This stored procedure
CREATE PROC GetPage(@blockNumber int, @blockSize int = 40, @query varchar(1000))
AS
DECLARE @a int = @blockNumber * @blockSize;
DECLARE @b int = @a + @blockSize - 1;
DECLARE @fromPos int = PATINDEX('% FROM %', @query);
DECLARE @from varchar(1000) = SUBSTRING(@query, @fromPos, 1000);
DECLARE @select varchar(1000) = SUBSTRING(@query, 1, @fromPos);
DECLARE @SQL varchar(1000) =
'select *, ROW_NUMBER() over (order by ONE) R INTO #FOO FROM ('
+@SELECT+',1 ONE'+@from+') T';
EXEC @SQL;
SELECT * FROM FOO WHERE RN BETWEEN @a AND @b;
DECLARE @C INT = (SELECT COUNT(*) FROM #FOO);
DROP TABLE #FOO
RETURN @C;
when passed SELECT * FROM ASSET generates this SQL
select *, ROW_NUMBER() over (order by ONE) R INTO #FOO
FROM (select * ,1 ONE from asset) T
When I execute this from SQL Server Management Studio, like this:
exec('select *, ROW_NUMBER() over (order by ONE) R INTO #FOO FROM (select * ,1 ONE from asset) T')
it creates the table #FOO as expected.
However, when the stored procedure is executed:
exec getpage 5,10,'select * from asset'
I get this error
Msg 2812, Level 16, State 62, Procedure GetPage, Line 12
Could not find stored procedure 'select *, ROW_NUMBER() over (order by ONE) R INTO FOO FROM (select * ,1 ONE from asset) T'.
Msg 208, Level 16, State 1, Procedure GetPage, Line 14
Invalid object name '#FOO'.
I think the second message is merely a consequence of the first error. Does anyone know why the exec statement is behaving differently inside a stored procedure?
A:
Use parenthesis in your exec
EXEC (@SQL);
EXECUTE (Transact-SQL)
Without the parenthesis you are using this:
Execute a stored procedure or function
[ { EXEC | EXECUTE } ]
{
[ @return_status = ]
{ module_name [ ;number ] | @module_name_var }
[ [ @parameter = ] { value
| @variable [ OUTPUT ]
| [ DEFAULT ]
}
]
[ ,...n ]
[ WITH [ ,...n ] ]
}
[;]
You want this where the parenthesis is required.
Execute a character string
{ EXEC | EXECUTE }
( { @string_variable | [ N ]'tsql_string' } [ + ...n ] )
[ AS { LOGIN | USER } = ' name ' ]
[;]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Keras: How to concatenate two CNN?
I'm trying to implement the CNN model in this article (https://arxiv.org/abs/1605.07333)
Here, they have two different contexts as inputs which are processed by two independent conv and max-pooling layers. After pooling they concat the results.
Assuming each CNN is modelled as such, how do I achieve the model above?
def baseline_cnn(activation='relu'):
model = Sequential()
model.add(Embedding(SAMPLE_SIZE, EMBEDDING_DIMS, input_length=MAX_SMI_LEN))
model.add(Dropout(0.2))
model.add(Conv1D(NUM_FILTERS, FILTER_LENGTH, padding='valid', activation=activation, strides=1))
model.add(GlobalMaxPooling1D())
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
Thanks in advance!
Final Code: I simply used @FernandoOrtega's solution:
def build_combined(FLAGS, NUM_FILTERS, FILTER_LENGTH1, FILTER_LENGTH2):
Dinput = Input(shape=(FLAGS.max_dlen, FLAGS.dset_size))
Tinput = Input(shape=(FLAGS.max_tlen, FLAGS.tset_size))
encode_d= Conv1D(filters=NUM_FILTERS, kernel_size=FILTER_LENGTH1, activation='relu', padding='valid', strides=1)(Dinput)
encode_d = Conv1D(filters=NUM_FILTERS*2, kernel_size=FILTER_LENGTH1, activation='relu', padding='valid', strides=1)(encode_d)
encode_d = GlobalMaxPooling1D()(encode_d)
encode_tt = Conv1D(filters=NUM_FILTERS, kernel_size=FILTER_LENGTH2, activation='relu', padding='valid', strides=1)(Tinput)
encode_tt = Conv1D(filters=NUM_FILTERS*2, kernel_size=FILTER_LENGTH1, activation='relu', padding='valid', strides=1)(encode_tt)
encode_tt = GlobalMaxPooling1D()(encode_tt)
encode_combined = keras.layers.concatenate([encode_d, encode_tt])
# Fully connected
FC1 = Dense(1024, activation='relu')(encode_combined)
FC2 = Dropout(0.1)(FC1)
FC2 = Dense(512, activation='relu')(FC2)
predictions = Dense(1, kernel_initializer='normal')(FC2)
combinedModel = Model(inputs=[Dinput, Tinput], outputs=[predictions])
combinedModel.compile(optimizer='adam', loss='mean_squared_error', metrics=[accuracy])
print(combinedModel.summary())
return combinedModel
A:
If you want to concatenate two sub-networks you should use keras.layer.concatenate function.
Furthermore, I recommend you shoud use Functional API as long as it easiest to devise complex networks like yours. For instance:
def baseline_cnn(activation='relu')
# Defining input 1
input1 = Embedding(SAMPLE_SIZE, EMBEDDING_DIMS, input_length=MAX_SMI_LEN)
x1 = Dropout(0.2)(input)
x1 = Conv1D(NUM_FILTERS, FILTER_LENGTH, padding='valid', activation=activation, strides=1)(x1)
x1 = GlobalMaxPooling1D()(x1)
# Defining input 2
input2 = Embedding(SAMPLE_SIZE, EMBEDDING_DIMS, input_length=MAX_SMI_LEN)
x2 = Dropout(0.2)(input)
x2 = Conv1D(NUM_FILTERS, FILTER_LENGTH, padding='valid', activation=activation, strides=1)(x2)
x2 = GlobalMaxPooling1D()(x2)
# Merging subnetworks
x = concatenate([input1, input2])
# Final Dense layer and compilation
x = Dense(1, activation='sigmoid')
model = Model(inputs=[input1, input2], x)
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
After compile this model, you can fit/evaluate it by means of model.fit([data_split1, data_split2]) in which data_split1 and data_split2 are your different contexts as input.
More info about multi input in Keras documentation: Multi-input and multi-output models.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Array value from variable
Could somebody explaind me ***why array count is not 2
$value = '"305", "112", ';
//remove last comma and space
echo $value = rtrim($value, ', ');
echo '<br>';
$value = array($value);
echo $array_length = count($value); //***
A:
you can use explode() to get it.
$value = '"305", "112", ';
//remove last comma and space
echo $value = rtrim($value, ', ');
echo '<br>';
$value = explode(',',$value);
echo $array_length = count($value);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Connect Gear 2 to Tizen SDK and get Data From Sensor
i'm searching a way to develop an application that can collect data from sensor embedded in Samsung Gear 2 lite, to do this i thinked to use the Android API but after some searching i found that gear 2 not supporting Android, so it support only tizen API, so i installed the Tizen SDK and i try to run the application directly in Gear 2 via a us cable, but when i try it the emulator say that i must certificate the device before running apps, but do what written in help, i got the necessaries files but in the last it say that the certification is failed cause of failure to find the path the some key...
so firstly is there anyone who know how to solve this problem?
in other side, i searched for a way to run the android apps in gear 2 directly from emulator or phone (S4) , hope that you can tell me a solution to do this without changing the device or developing with javascript.
A:
the problem was in certification, i succeed to install certification, the problem was related to the steps to follow, i tried the right sequence of steps, and i got the perfect result, i can for now install Tizen application in gear directly or from sumsung galaxy with the application Samsung Gear application, i embedded the gwt file in the android project and when the android apps is installed, the gear application will be installed directly in Gear watch, so i havn't to use usb cable to install the gear application.
Thank for your suggestions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Решить задачу без простого перебора в массиве, сохраняя только состояние между запросами
Задан массив, состоящий из n целых чисел: a[1], a[2], ..., a[n], по умолчанию заполнены нулями. Более того, заданы m запросов, каждый из которых характеризуется тремя числами li, ri, ki. Запрос li, ri, ki обозначает, что нужно добавить к каждому элементу a[j], где li ≤ j ≤ ri, число Ckij - li + ki.
Запись Cxy обозначает биномиальный коэффициент, или количество сочетаний из y элементов по x элементов.
Вам нужно выполнить последовательно все запросы и вывести, чему будут равны элементы массива в итоге, после всех запросов.
Входные данные
В первой строке заданы целые числа n, m (1 ≤ n, m ≤ 105).
Во второй строке задано n целых чисел a[1], a[2], ..., a[n] (0 ≤ ai ≤ 109) — изначальное состояние массива.
В следующих m строках заданы запросы в формате li, ri, ki — прибавить всем элементам отрезка li...ri число Ckij - li + ki (1 ≤ li ≤ ri ≤ n; 0 ≤ k ≤ 100).
Выходные данные
Максимальное число из полученного массива
Можно ли как то решить эту задачу кроме как простого перебора в массиве, сохраняя только состояние между запросами? цель задачи не используя массив arr, так как изначально в массиве arr только нули, найти максимальное значение.
public static void main(String[] args) throws FileNotFoundException {
int[] first = new int[3];
first[0] = 1;
first[1] = 2;
first[2] = 3;
int[] last = new int[3];
last[0] = 2;
last[1] = 4;
last[2] = 5;
int[] value = new int[3];
value[0] = 45;
value[1] = 55;
value[2] = 41;
int[] arr = new int[6];
System.out.println(maxValue(arr, first, last, value));
}
private static int maxValue(int[] arr, int first[], int last[], int[] value) {
for (int i = 0; i < first.length; i++) {
for (int j = first[i] - 1; i < last[i]; i++) {
arr[j] += value[j];
}
}
Arrays.sort(arr);
return arr[0];
}
}
A:
Если отрезки [li, ri] полностью покрывают отрезок [1, n] и значения элементов массива arr могут только увеличиваться (что вроде как соответствует условию задачи), то всё просто:
private static int maxValue(int[] arr, int first[], int last[], int[] value) {
int max = arr[0]; // предполагаемый максимум в первом элементе
for (int i = 0; i < first.length; i++) {
for (int j = first[i] - 1; i < last[i]; i++) {
arr[j] += value[j];
if (max < arr[j]) max = arr[j]; // каждый раз обновляем максимум при необходимости
}
}
return max;
}
Хотя не уверен в правильном понимании условия задачи, но раз без массива, так без массива. При условии, что отрезки [l, r] не пересекаются, всё сводится к поиску максимального значения в массиве value + 0. А больше ничего на фиг не нужно:
private static int maxValue(int[] value) {
int max = 0;
for (int i = 0; i < value.length; i++) {
if (max < value[i]) max = value[i];
}
return max;
}
Но сдаётся мне, что не может быть такого бредового задания. Либо лыжи не едут, либо одно из двух...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Custom Exception Controller in Symfony 4
I am building a custom exception controller in Symfony 4 to overwrite the ExceptionController class included in the Twig bundle.
I am doing this as per the Symfony documentation for customizing error pages.
# config/packages/twig.yaml
twig:
exception_controller: App\Controller\Error::handleException
The reason I am using a custom exception controller is because I need to pass some additional variable to the template that are given by a custom BaseController class.
The Symfony docs mention the following about using a custom controller:
The ExceptionListener class used by the TwigBundle as a listener of the kernel.exception event creates the request that will be dispatched to your controller. In addition, your controller will be passed two parameters:
exception
A FlattenException instance created from the exception being handled.
logger
A DebugLoggerInterface instance which may be null in some circumstances.
I need the FlattenException service to determine the error code but its not clear from the docs how these parameters are passed to the custom exception controller.
Here is my custom exception controller code:
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Debug\Exception\FlattenException;
class Error extends BaseController {
protected $debug, // this is passed as a parameter from services.yaml
$code; // 404, 500, etc.
public function __construct(BaseController $Base, bool $debug) {
$this->debug = $debug;
$this->data = $Base->data;
// I'm instantiating this class explicitly here, but have tried autowiring and other variations that all give an error.
$exception = new FlattenException();
$this->code = $exception->getStatusCode(); // empty
}
public function handleException(){
$template = 'error' . $this->code . '.html.twig';
return new Response($this->renderView($template, $this->data));
}
}
A:
From the documentation page you are linking, at the very beginning of the chapter Overriding the default template the documentation actually cross link you to the class \Symfony\Bundle\TwigBundle\Controller\ExceptionController, and this shows you how to use it.
So as per Symfony's own ExceptionController, the FlattenException is actually an argument of the action showAction:
<?php
namespace App\Controller;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
class Error extends BaseController {
protected $debug; // this is passed as a parameter from services.yaml
protected $code; // 404, 500, etc.
protected $data;
public function __construct(BaseController $base, bool $debug) {
$this->debug = $debug;
$this->data = $base->data;
}
public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null) {
// dd($exception); // uncomment me to see the exception
$template = 'error' . $exception-> getStatusCode() . '.html.twig';
return new Response($this->renderView($template, $this->data));
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can an amCharts3 serial chart have a specific x-axis set?
I am creating an amCharts3 serial chart to show production hourly, forecast and target levels over a 24 hour period (midnight to midnight). The hourly and forecast data are logged every 30 minutes and this will then be displayed as bullet points on the chart. The target data is static value which is represented by a line across the chart
My code for the chart is,
"type": "serial",
"backgroundAlpha": 1,
"plotAreaFillAlphas": 1,
"autoMargin": true,
"autoMarginOffset": 30,
"autoDisplay": true,
"marginRight": 50,
"color": "#000000",
"plotAreaFillColors": scope.config.plotAreaFillColor,
"creditsPosition": "bottom-right",
"titles": createArrayOfChartTitles(),
"fontSize": 11,
"pathToImages": "Scripts/app/editor/symbols/ext/images/",
"categoryAxis": {
"parseDates": true,
"minPeriod": "ss",
"axisAlpha": 1,
"axisColor": "black",
"gridAlpha": 0.1,
"autoWrap": true,
"gridThickness": 2,
"title": "Time, hrs"
},
"chartScrollbar": {
"enabled": false
},
"legend": {
"enabled": true,
"useGraphSettings": true,
"color": "#000000",
"labelText": "[[title]]",
},
"valueAxes": [
{
"title": "Temperature",
"inside": false,
"axisAlpha": 1,
"axisColor": "black",
"fillAlpha": 0.05,
"gridAlpha": 0.1,
"gridThickness": 2
}
],
"graphs": [
{
"id": "g1",
"title": graph1Label,
"type": "line",
"bullet": "square",
"lineThickness": 0,
"bulletColor": "#0094FF",
"balloonColor": "#0094FF",
"balloonText": "[[timestamp]]<br />[[value1]]",
"valueField": "value1"
},
{
"id": "g2",
"title": graph2Label,
"type": "line",
"bullet": "round",
"lineThickness": 0,
"bulletColor": "#FF8000",
"balloonColor": "#FF8000",
"balloonText": "[[timestamp]]<br />[[value2]]",
"valueField": "value2"
},
{
"id": "g3",
"title": graph3Label,
"type": "line",
"lineThickness": 1,
"lineColor": "#FF0000",
"balloonColor": "#FF0000",
"balloonText": "[[timestamp]]<br />[[value3]]",
"valueField": "value3"
}
],
"dataProvider": dataArray,
"categoryField": "timestamp",
"chartCursor": {
"cursorColor": "gray",
"valueLineBalloonEnabled": true,
"valueLineEnabled": true,
"valueZoomable": true,
"categoryBalloonDateFormat": "D/MM/YYYY L:NN:SS A"
},
"zoomOutButtonImage": ""
}
The data displays correctly but I am trying to set the x-axis range to a specific start and end point.
I want the chart to show with the x-axis to be set from midnight to midnight. Even if it is 10am I would like the chart to show the entire 24 hour time range.
Currently the chart shows data from midnight up to the current time it is being viewed. For example midnight to 10am.
I have added images for what the display looks like currently and also what the desired outcome is.
Current Display
Desired Display
A:
I was able to solve this by using the date padding plugin provided by amCharts.
Date padding plugin
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CSS filter: make color image with transparency white
I have a colored png image with transparency. I would like to use css filter to make the whole image white but leave the transparency as it is.
Is that possible in CSS?
A:
You can use
filter: brightness(0) invert(1);
html {
background: red;
}
p {
float: left;
max-width: 50%;
text-align: center;
}
img {
display: block;
max-width: 100%;
}
.filter {
-webkit-filter: brightness(0) invert(1);
filter: brightness(0) invert(1);
}
<p>
Original:
<img src="http://i.stack.imgur.com/jO8jP.gif" />
</p>
<p>
Filter:
<img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />
</p>
First, brightness(0) makes all image black, except transparent parts, which remain transparent.
Then, invert(1) makes the black parts white.
A:
To my knowledge, there is sadly no CSS filter to colorise an element (perhaps with the use of some SVG filter magic, but I'm somewhat unfamiliar with that) and even if that wasn't the case, filters are basically only supported by webkit browsers.
With that said, you could still work around this and use a canvas to modify your image. Basically, you can draw an image element onto a canvas and then loop through the pixels, modifying the respective RGBA values to the colour you want.
However, canvases do come with some restrictions. Most importantly, you have to make sure that the image src comes from the same domain as the page. Otherwise the browser won't allow you to read or modify the pixel data of the canvas.
Here's a JSFiddle changing the colour of the JSFiddle logo.
//Base64 source, but any local source will work
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJDQDtKymxT1iWZLFDUy0/kkfDUxzYVzV0hvHZLs946Gph+uBLCRmRDQdjTVwmw9DZCNMPi4KzqWbPX/sxwIu71vlrKq10HnZizwTSFZngj5f1NOx5s7bdB2LHWDEusBOD487LrX9qyd8qpnvJL3zGjqAh+pR4W4RVhu715Vv2U8PTWeQLn5YHvms4qsR4TpH/ImLfhfARvbPaGGrrjTtwjH5hFFfHcgkv5SOZ9mbvxIgwGaZl+8ULGcJ8zOsJa9R1r9B2d8v2eGb1KNieqBhLNz8ekyAoV3VAX985+FvSXEenF8lf9lA7DUUxa0HUl/RTG1EfOUQmUwwCtggDewiHmc1R+Ir/MfKJz/f9tTwn31Nf7qVxlHLR6qXwg7cHXqU/p4hPdUB6Lp55TiXwDYTsrpG12dbdY5t0WLrCSRSVjIItG0dqIAG2jHwlPTmvQdsL3Ajjg3nAq3zIgdS98ZiGV0MJZeWVJs2WNWIJK5hcLh0osuqVTxIAdi6X3w/0LFGoa+AtFMzo5kflix0gQLBiLOZmAYro84RcfSc3NKpFAcliM9eYDdjZ7QO/1mRc+CTapqFX+4lO9TQEPoUpz//anQ5FQphXdizB1QXXk/moOl/JUC7aLMDpQSHj02PdxbG9xybM60u47UjZ4bq290Zm451ky3HSi6kxTKJ9fXHQVvZJm1XTjutYsozw53T1L+2ufBGPMTe/c30M/mD3uChW+c+6tQttthuBnbqMBLKGbydI54/eFQ3b5CWa/dGMl8xFJ0D/rvg1Pjdxil+2XK5b6ZWD15lyfnvYOxTBYs9TrY5NbuUENRUo5EGtGyVUNtBwBfDjA/IDtTkiNRsdYD8O+NcVN2KUfXo3UnukvA6Z3I+mWeY++NpNoAwDvAv1Uiss7oiNBmYD+XraoO0NvnPVnvrbUsA4CcYusPgajzY2/cvN+KtOFl/6w/IWrvdTV/Ktla92KhkNcOxpwPCqm/IgLbEvteW1m4E2/d8iY9AZOXQ/7WxKq6nxq9YNT5OLF6DmAfTHT13EL3XjTk2csXk4bqX2OXWiQ73Jz49tS4N5d/oxoHLr14EzPfAf1IIlS/2oznIx1omLURhL5Qa1oxFuC8EeHb8U6I88bXCwGbuZ61jb2Jgz1XYUHb0b0vEHNWmHE9lNsjWrcmnMhNhYDNnCkmNJSFHFdzte82M1b04HgC6HrYbAPw1pFdNOc4GE334wz9qkihRAdK/0HBub/E1MkhJBiq6V8gq7Htm05OjN2C/z/jCP1xbAlCwcnsAsbdkGHF/trPIcoNrtbjFRNmoama6EgZ42SimRG5FjLHWakNwWjmirLyZpLpKH7TysghZ00OUHNTxFmK2yDNQSKlx7u0Q0GQeLtQdy4rY5zMzqVb/ccoJ/OQMEmoPWW3988to4NY8DxYf6WMDCW6ktuRvFqxmqewgguhdLCcwsic0DMA8lE7kvrYyFhBw446X2B/nRNo739/YnX9azKUXYCg9CtlvdAUyywuEB1p4gh9AzbPZc0mF8Z+sINgn0MIwiVgKcAG6rGlT86AMdqw2n8ppR63o+mveQXCFAxzX2BWD0P6pcT+g3uNlmEDV3JX4iOh1xICdWU2gGXOMXN5HfRhK4IoPxlfXQfmKf+Ajh1I+MEeHMcKzqvoxoZsHsoOXgP+fEkxbw1e2JhB0h2q9tc4OL/fAVdsdd3jnyhklmRo8qGBQXchIvMMKPW7Pt85/SM66CNmDw1mh75cHu6JWZFZxNLNSJTPIM5PuJquKEt3o6zmqyJZH4LTC7CIfTonO5Jr/B2jxIq6jW3OZVYVX4edDSD6e1BAXqwgl/I2miKp+ZayOkT0CjaJww21/2bhznio7uoiL2dQB8HdhoV++ri4AdUdtgfw789mRHspzulXzyCcI1BMVQXgL5LodnP7zFfE+N9/9yOUyedxTn/SFHWWj0ifAY1ANHUleOJRlPqdCUmbO85J1jjxUfkUkgVCsg1/uGw0n/fvFm67LT2NLTLfi98Cke8dpMGl3r9QxVRnPuPrWzaIUmsAtgas0okd6ETh7AYt5d7+BeCbhfKVcQ6CtwgJjjoiP3fdgVbcbY57/otBnxidfndvo6/67BtxUf4kztJsbMg0CJaU9QxN2FskhePQBWr7La6wvzRFarTtyoBgB4hm5M//aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";
var canvas = document.getElementById("theCanvas");
var ctx = canvas.getContext("2d");
var img = new Image;
//wait for the image to load
img.onload = function() {
//Draw the original image so that you can fetch the colour data
ctx.drawImage(img,0,0);
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
/*
imgData.data is a one-dimensional array which contains
the respective RGBA values for every pixel
in the selected region of the context
(note i+=4 in the loop)
*/
for (var i = 0; i < imgData.data.length; i+=4) {
imgData.data[i] = 255; //Red, 0-255
imgData.data[i+1] = 255; //Green, 0-255
imgData.data[i+2] = 255; //Blue, 0-255
/*
imgData.data[i+3] contains the alpha value
which we are going to ignore and leave
alone with its original value
*/
}
ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image
ctx.putImageData(imgData, 0, 0); //paint the new colorised image
}
//Load the image!
img.src = src;
body {
background: green;
}
<canvas id="theCanvas"></canvas>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
onbeforeunload not working in Windows Chrome
I have seen this issue posted before but onbeforeunload does not work for me in Windows Chrome. I am using version 49.0.2623.112 m. Here is my code:
<body onbeforeunload="handleBrowserCloseButton();">
function handleBrowserCloseButton() {
//Call method by Ajax call
alert('Browser close button clicked');
}
When I navigate away from the page or close the browser window, nothing happens. Any help would be greatly appreciated.
A:
You need to return a non-void value from the callback function, otherwise you won't see a message dialog.
So you would need to change two things:
<body onbeforeunload="return handleBrowserCloseButton();">
and
function handleBrowserCloseButton() {
return 'Browser close button clicked';
}
Beside that you should use window.addEventListener('beforeunload', ... ) instead.
MDN: WindowEventHandlers.onbeforeunload: Notes:
When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog. In Firefox 4 and later the returned string is not displayed to the user. Instead, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved." See bug 588292.
Because the functionality should net be misused to prevent the user form leaving the page, functions like alert or confirm won't work in the onbeforeunload callback.
MDN: WindowEventHandlers.onbeforeunload: Notes:
Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Blackberry : how to play *.swf/*.flv file?
I want to play flash file in my BB application.
is it possible ? if yes then pls help me out to implement this in my application
waiting for your suggession...
thanking you in advance...
A:
Flash is not currently supported by BlackBerry devices, however Adobe and RIM have announced upcoming support for Flash 10.1 -- if I had to guess it will be part of OS 6.0.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
app icon did not refresh
I change the icon image in my new version app, and I have installed and old version app in the device , then i install the new version, it works well in iOS 5 , but in iOS 6, the icon did not refresh, it still showing the old version icon/logo. If did no install the old version app, the deice works well both in iOS 5 and iOS 6.
Why? Can any body help me ?
A:
This has been a bug in iOS for years, but in iOS 6 it seems to happen every time now.
You can delete your app before running from Xcode (if you don't mind losing all your documents and caches).
You can reboot the device (if you don't mind waiting a few minutes).
You can open the Settings app and go to General -> Reset -> Reset Home Screen Layout (if you don't mind your icons all rearranging).
You can file a bug report (if you don't mind a lengthy timewasting exercise in futility).
(My personal favourite is #3 for development-only devices).
EDIT: See Craig Watkinson's answer for a much better method, i.e. dragging the icon into and out of a folder. Thanks Craig!
A:
You can also drag the old icon into a folder (i.e. drag it over another icon) and then before it even finishes wibbling, drag it back out again. Hey presto, the icon updates.
The issue is to do with the icon file being cached by springboard, and for some reason this action refreshes the cache.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to bind elements of a list to labels
I am looking for a nice code solution for the following problem.
I have a List which I want to bind to a couple of labels. The MyObject class only contains a few fields (strings and ints). This list contains of 3 elements. In my view I would like to have the following layout
Element 1
Element 2
Element 3
Where "Element 1", "Element 2" and "Element 3" is a property of the MyObject class.
Note that the view is already defined in Blend as follows (I prefer not to change the view-code, but if I have no choice ... ;) ):
<Label Content="1." RenderTransformOrigin="0,0.404" Foreground="Black" FontSize="16" VerticalContentAlignment="Bottom" HorizontalContentAlignment="Right" FontFamily="Segoe UI Semibold"/>
<Label Content="2." RenderTransformOrigin="0,0.404" Foreground="Black" FontSize="16" VerticalContentAlignment="Bottom" HorizontalContentAlignment="Right" Grid.Row="1" FontFamily="Segoe UI Semibold"/>
<Label Content="3." Margin="0,0,0,1.077" RenderTransformOrigin="0,0.404" Foreground="Black" FontSize="16" VerticalContentAlignment="Bottom" HorizontalContentAlignment="Right" Grid.Row="2" FontFamily="Segoe UI Semibold"/>
<Label Content="Login bug startup (6 days)" Foreground="Black" FontSize="14.667" VerticalContentAlignment="Bottom" Grid.Column="1"/>
<Label Content="Setup screen exception (4 days)" Foreground="Black" FontSize="14.667" VerticalContentAlignment="Bottom" Grid.Column="1" Grid.Row="1"/>
<Label Content="No users available bug (1 day)" Foreground="Black" FontSize="14.667" VerticalContentAlignment="Bottom" Grid.Column="1" Grid.Row="2"/>
What is the best way to do this ? I am sure I can do this with some loose code, but I prefer a neat solution.
Thank you very much !!
A:
<ListView ItemsSource={Binding MyObjectsList}>
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Number}" />
<Label Content="{Binding Element}" />
</StackPanel>
</DataTempalte>
</ListView.ItemTemplate>
</ListView>
Number and Element are properties of your MyObject.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using XSL to output KML information in an HTML table
It's been a few years since I've done any coding so I hope you will bear with me...
I have an app that outputs the (non-standard) kml file below.
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<Style id="icon-503-BCA920">
<IconStyle>
<color>FFBCA920</color>
<Icon><href>http://www.gstatic.com/mapspro/images/stock/503-wht-blank_maps.png</href></Icon>
</IconStyle>
</Style>
<Placemark>
<name><![CDATA[Deficiency 2]]></name>
<styleUrl>#icon-503-BCA920</styleUrl>
<ExtendedData>
<Data name="rating"><value>0</value></Data>
<Data name="images"><value>file:///storage/emulated/0/mapin/1411660694536.jpg||</value></Data>
</ExtendedData>
<description><![CDATA[<p dir="ltr">4001; Vegetation Control; Mowing; + 60 < 2m</p>
<br/><img src="images/image_1.jpg"/>
<br/><img src="images/image_1.jpg"/>
]]></description>
<Point>
<coordinates>-89.59504411, 48.0247752, 0</coordinates>
</Point>
</Placemark>
I am trying to use xsl to convert/output it as an html page/table. What I have gleaned so far is my code should like something like this:
<html>
<body>
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
<xsl:template match="/">
<h2>Audit Results</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th style="text-align:center">Name</th>
<th style="text-align:center">Description</th>
<th style="text-align:center">Coordinates</th>
</tr>
<xsl:for-each select="kml:kml/dml:Document/kml:Placemark">
<tr>
<td><xsl:value-of disable-output-escaping="yes" select="kml:name"/></td>
<td><xsl:value-of disable-output-escaping="yes" select="kml:description"/></td>
<td><xsl:value-of select="kml:Point/kml:coordinates"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
</body>
</html>
Having read everything i can lay my hands on about xsl the last day or two I am at my ropes end. What I'm hoping someone can tell me is:
1)do I have to call the kml file i would like to display?? it is a local file.
2)am I going about this wrong? is there any articles you know of which could help me?
What I am attempting to do is use the xsl code to output a html file that I can print every time I finish another "audit.kml" file. Is there a better/easier way you would recommend doing this?
I am honestly looking to learn how to do this myself, not here asking for a block of code... all advice is greatly appreciated!
Thanks Phil.
So now that I have a valid xsl file I am trying to apply it to my kml file locally using the browser. Some reading points me in the direction of Javascript being the best way to do this. When I use the script below I come up with a blank document... any advice?
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(filename)
{
if (window.ActiveXObject)
{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
else
{
xhttp = new XMLHttpRequest();
}
xhttp.open("GET", filename, false);
try {xhttp.responseType = "msxml-document"} catch(err) {} // Helping IE11
xhttp.send("");
return xhttp.responseXML;
}
function displayResult()
{
xml = loadXMLDoc("doc.kml");
xsl = loadXMLDoc("reportGen.xsl");
// code for IE
if (window.ActiveXObject || xhttp.responseType == "msxml-document")
{
ex = xml.transformNode(xsl);
document.getElementById("example").innerHTML = ex;
}
// code for Chrome, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("example").appendChild(resultDocument);
}
}
</script>
</head>
<body onload="displayResult()">
<div id="example" />
</body>
</html>
A:
You are close. You should have the xsl:stylesheet as your root. Also you have a typo in your name space
<xsl:for-each select="kml:kml/dml:Document/kml:Placemark">
should be
<xsl:for-each select="kml:kml/kml:Document/kml:Placemark">
You want something like this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
<xsl:template match="/">
<html>
<head>
<title/>
</head>
<body>
<h2>Audit Results</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th style="text-align:center">Name</th>
<th style="text-align:center">Description</th>
<th style="text-align:center">Coordinates</th>
</tr>
<xsl:for-each select="kml:kml/kml:Document/kml:Placemark">
<tr>
<td>
<xsl:value-of disable-output-escaping="yes" select="kml:name"/>
</td>
<td>
<xsl:value-of disable-output-escaping="yes" select="kml:description"/>
</td>
<td>
<xsl:value-of select="kml:Point/kml:coordinates"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jqgrid: multiselect and disable check (conditional)
I love jqGrid but sometimes things seem more complicated than they should be.
What I would like to achieve is to have a checkbox on each row so that a user can choose which rows are going to be submitted/processed.
I need, though, to block some checkboxes cause the user has no authorization on that particular row, maybe.
I've tried to set multiselect: true and then I've tried to hide the checkbox:
loadComplete: function (data) {
if (data.rows.length > 0) {
for (var i = 0; i < data.rows.length; i++) {
if (data.rows[i].cell[7] == 'false') {
$("#jqg_OrdersGrid_" + data.rows[i].id).css("visibility", "hidden");
}
}
}
},
and it works well but, still, .jqGrid('getGridParam', 'selarrrow') give me the selected rows, even if they haven't been checked.
Is there any other way to have checkboxes which are enabled/disabled and a way to know which ones have been checked?
thanks
A:
I would suggest you to disable some checkboxed from the be selectable with respect of "disabled" attribute. To make full implementation you will need
set "disabled" inside of loadComplete event handle
additionally prevent selection of disabled rows inside beforeSelectRow event handle
to have support of "select all" checkbox in the header of the multiselect column implement onSelectAll event handle which fix selection of disabled rows.
The corresponding demo can you see here. The most important part of the code is here:
var grid = $("#list10"), i;
grid.jqGrid({
//...
loadComplete: function() {
// we make all even rows "protected", so that will be not selectable
var cbs = $("tr.jqgrow > td > input.cbox:even", grid[0]);
cbs.attr("disabled", "disabled");
},
beforeSelectRow: function(rowid, e) {
var cbsdis = $("tr#"+rowid+".jqgrow > td > input.cbox:disabled", grid[0]);
if (cbsdis.length === 0) {
return true; // allow select the row
} else {
return false; // not allow select the row
}
},
onSelectAll: function(aRowids,status) {
if (status) {
// uncheck "protected" rows
var cbs = $("tr.jqgrow > td > input.cbox:disabled", grid[0]);
cbs.removeAttr("checked");
//modify the selarrrow parameter
grid[0].p.selarrrow = grid.find("tr.jqgrow:has(td > input.cbox:checked)")
.map(function() { return this.id; }) // convert to set of ids
.get(); // convert to instance of Array
}
}
);
UPDATED: Free jqGrid supports hasMultiselectCheckBox callback, which can be used to create multiselect checkboxes not for all rows of jqGrid. One can use rowattr to disable some rows additionally. As the result one will get the described above functionality in more simple way. It's recommended to use multiPageSelection: true option additionally for free jqGrid with local data (datatype: "local" or loadonce: true). The option multiPageSelection: true will hold the array selarrrow on paging. It allows "pre-select" some rows by filling the corresponding ids inselarrrow. See UPDATED part of the answer and the answer with the demo for additional information.
A:
Great answer from Oleg, I would also add code to deselect disabled rows, complete onSelectAll function below.
onSelectAll: function(aRowids,status) {
if (status) {
// uncheck "protected" rows
var cbs = $("tr.jqgrow > td > input.cbox:disabled", grid[0]);
cbs.removeAttr("checked");
//modify the selarrrow parameter
grid[0].p.selarrrow = grid.find("tr.jqgrow:has(td > input.cbox:checked)")
.map(function() { return this.id; }) // convert to set of ids
.get(); // convert to instance of Array
//deselect disabled rows
grid.find("tr.jqgrow:has(td > input.cbox:disabled)")
.attr('aria-selected', 'false')
.removeClass('ui-state-highlight');
}
}
A:
I've found a work-around.
During the loadComplete event I disable the SelectAll checkbox: I don't need it.
I also hide the checkbox and disable it.
loadComplete: function (data) {
$("#cb_OrdersGrid").css("visibility", "hidden");
if (data.rows.length > 0) {
for (var i = 0; i < data.rows.length; i++) {
if (data.rows[i].cell[7] == 'false') {
$("#jqg_OrdersGrid_" + data.rows[i].id).css("visibility", "hidden");
$("#jqg_OrdersGrid_" + data.rows[i].id).attr("disabled", true);
}
}
}
}
Now, when I want to submit my data I loop through the selected rows and check if they've been disabled and put those which are enabled in a new array.
var selectedRows = myGrid.jqGrid('getGridParam', 'selarrrow');
var checkedRows = [];
var selectionLoop = 0;
for (var x = 0; x < selectedRows.length; x++) {
var isDisabled = $('#jqg_OrdersGrid_' + selectedRows[x]).is(':disabled');
if (!isDisabled) {
checkedRows[selectionLoop] = selectedRows[x];
selectionLoop++;
}
}
What I've achieved now is to be able to select a row conditionally being able to check it or not.
I know the code is not optimized (forgive me Oleg) but I'll do it later.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Texture tile bleeding from neighbour cell (image atlas)
I have an image atlas with elements arranged in boxes packed beside each other. When I position/scale these so that they are pixel-for-pixel rendered everything works fine. However then moment I start doing sub-pixel positioning I can get bleed from the neigbouring image in the atlas.
If I understand correctly this is caused by the fragment shader, or rather the texture position interpolation. A pixel near the border of the texture position will end up getting some of the value from the neighbouring pixel.
Though I'm uncertain since if I do some searching this problem usually only shows up in relation to using layers in a mip-map. Is my understanding correct, or am I doing something wrong? I know how to fix it (for both tiling and not-tiling textures) but I'd like to make sure I've got the basics correct first.
A:
It depends on what rendering engine you use and the platform.
The simple solution is add a 1 pixel transparent border between each box in the texture atlas, that should solve the artifacts problem in most cases.
In plain OpenGL, vertex positions are floats so subpixel precision is easy to achieve. anti-aliasing occurs naturally by the opengl implementation when you position sprites on a non integer boundaries. The quality depends on the OpenGL implementation, you can also use glHint() to make sure you're on the safe side.
glHint() Documentation
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to update a QStringListModel?
I have the following code:
QStringListModel* m=new QStringListModel(gc.get_lista_file());
ui->lista_immagini_listView->setModel(m);
where gc.get_lista_file() returns a QStringList object and lista_immagini_listView is a QListView.
I need to update my lista_immagini_listView adding a string when I press a button, but if I add my new string to my QStringList object it doesn't update my model (I read the QStringList is passed by copy, so it isn't connected to the model). So, I have to update my QStringListModel but in this way I have to update 2 object (QStringList and QStringListModel) and doesn't seem a good practice.
What is the best way (if exists) to resolve it?
A:
QStringListModel does not allow you to simply add a string (sadly). Simply updating the QStringList does not work because the model stores a copy of the list.
There are basically two ways to get the desired behavior:
1. Reset:
This is the simple way. You just take the list from the model, add the string and reassign it:
QStringList list = m->stringList();
list.append("someString");
m->setStringList(list);
This method does work, but has one big disadvantage: The view will be reset. Any selections the user may have, sorting or the scroll-position will be lost, because the model gets reset.
2. Using the Model:
The second approach is the proper way of doing, but requires some more work. In this you use the functions of QAbstractItemModel to first add a row, and then changing it's data:
if(m->insertRow(m->rowCount())) {
QModelIndex index = m->index(m->rowCount() - 1, 0);
m->setData(index, "someString");
}
This one does properly update the view and keeps it's state. However, this one gets more complicated if you want to insert multiple rows, or remove/move them.
My recommendation: Use the 2. Method, because the user experience is much better. Even if you use the list in multiple places, you can get the list after inserting the row using m->stringList().
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Django filter exclude with in and case senstive
Doe anyone know how to both exclude using the __in and also make this case senstive (__iexact)
Event.objects.values_list('total',flat=True).exclude(total__in=self.summaries)
A:
You could use Q objects to constuct a query like this:
Event.objects.values_list('total',flat=True).exclude(reduce(lambda x, y: x | y, [Q(total__iexact=word) for word in self.summaries])))
This Will work for you
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Multiple APK signing - signature protectionLevel behavior
Suppose the following situation:
I have 2 apps: A1 & A2.
A1 defines a signature level permission, lets say "com.example.myapp.PERMISSION".
A2 claims the permission defined by A1.
I have 2 signing keys: K1 & K2.
A1 is signed with both K1 & K2.
A2 is signed with only K1.
If A1 exposes a service that is protected by the "com.example.myapp.PERMISSION" permission, can A2 access that service? Do all signatures have to be present for both apps, or will it work as long as there is a match between any two?
A:
Android treats all the signatures as Set - 2 applications must have the same Set of signatures to be considered equivalent. So in your example A2 would not be granted the permission since it's signature set does not equals A1's.
Here is the code from the source code
ArraySet<Signature> set1 = new ArraySet<Signature>();
for (Signature sig : s1) {
set1.add(sig);
}
ArraySet<Signature> set2 = new ArraySet<Signature>();
for (Signature sig : s2) {
set2.add(sig);
}
// Make sure s2 contains all signatures in s1.
if (set1.equals(set2)) {
return PackageManager.SIGNATURE_MATCH;
}
return PackageManager.SIGNATURE_NO_MATCH;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to deploy staging in Google Cloud Platform with Kubernetes and Gitlab CI/CD?
I am playing with Docker, Kubernetes, Google Cloud Platform(GCP) and Gitlab recently to achieve CI/CD from commit to staging.
So far I have succeeded testing, building and pushing the image to Container registry of Gitlab.
I have a small node and docker application which output 'Hello world'. Also, I have built my docker image in Container registry of Gitlab. At this moment the process is docker-in-docker. I want to push my image from Gitlab container registry to Kubernetes engine in GCP. I have installed both kubectl and gcloud sdk. The Auto DevOps seems to be promising but I want to implement my own .gitlab-ci.yml file.
Here is my .gitlab-ci.yml below:
stages:
- testing
- build
- staging
variables:
CONTAINER_TEST_IMAGE: registry.gitlab.com/surajneupane55/node-app-
testing
CONTAINER_RELEASE_IMAGE: registry.gitlab.com/surajneupane55/node-
app-testing:latest
test:
stage: testing
image: node:boron
script:
- npm install
- npm test
build_image:
stage: build
only: [master]
image: docker:git
services:
- docker:dind
script:
- docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN
registry.gitlab.com/surajneupane55
- docker build -t $CONTAINER_TEST_IMAGE .
- docker push $CONTAINER_TEST_IMAGE
staging_site:
//I need help here!!!
//For staging my project in Kubernetes cluster in GCP
//Already created node-app Kubernetes cluster
Please, let me know if my approach is wrong since this is my first learning project with CI/CD.
A:
A simple gitlab-ci.yml file to build and deploy in GKE with Google Container Registry(GCR). First, we build image and push it to GCR. With valid credentials, we can easily connect the GKE with GCR and deploy.
stages:
- build
- deploy
variables:
CONTAINER_TEST_IMAGE: gcr.io/node-testing-189614/node-testing:latest
build_image:
stage: build
only: [master]
image: google/cloud-sdk
services:
- docker:dind
script:
- echo "$GOOGLE_KEY_SECRET" > key.json # Google Cloud service accounts
- gcloud auth activate-service-account --key-file key.json
- gcloud config set project node-testing-189614
- gcloud container builds submit -t $CONTAINER_TEST_IMAGE .
deploy_staging:
image: google/cloud-sdk
stage: deploy
script:
- echo "$GOOGLE_KEY_SECRET" > key.json # Google Cloud service accounts
- gcloud auth activate-service-account --key-file key.json
- gcloud config set project node-testing-189614
- gcloud config set compute/zone europe-west1-b
- gcloud config set container/use_client_certificate True
- gcloud container clusters get-credentials node-testing
- kubectl delete pods --all
- kubectl apply -f staging.yml
environment:
name: staging
url: http://***.***.**.***:****/ //External IP from Kubernetes
only:
- master
Above we delete pods in GKE because we always want to update the image with the latest tag. The best possible solution available so far is to delete the pods and let the staging.yml file creates new one if not available.
Finally staging.yml looks like this:
apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: node-testing
spec:
replicas: 2
template:
metadata:
labels:
app: node-testing
spec:
containers:
- name: node-testing
image: gcr.io/node-testing-189614/node-testing:latest
imagePullPolicy: Always
ports:
- containerPort: 8080
imagePullSecrets:
- name: gcr.io/node-testing-189614/node-testing
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Input Dialogs in C#
i am new to c# , and i am trying to write a piece of code that is equivalent to code written in java below.
i need an input dialogue that asksthe user to enter his choice, sadly my attempts ended in both run time and compile time errors:)
i would apperciate your help
this is the code in java , which i am trying to implement in c#
do{
String name = JOptionPane.showInputDialog(null, "PLEASE ENTER YOUR CHOICE OF SQUARE NUMBER");
choice = Integer.parseInt(name);
choice --;
}while(TicTac[choice]!=' ');
Thank You:)
A:
Add a reference to Microsoft.VisualBasic.dll.
Call Microsoft.VisualBasic.Interaction.InputBox(...).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Optimize Spring-Data JPA queries
I am looking for possible optimizations for framework-generated queries.
As far as I understand, the process is the following:
you could declare your domain objects as POJOs and adding several annotations like @Entity, @Table, @ManyToOneetc.
you declare your repositories e.g. per interfaces
With (2) you have several options to describe your query: e.g. per Methodnames or @Query
If I write a query like:
@Query("select t from Order t LEFT join fetch t.orderPositions where t.id = ?1")
Page<Order> findById(Pageable pageable, String id);
a SQL-query is autogenerated, where every column of the order is resolved and subsequentially for orderpositions and depending obejcts/tables.
As if I wrote:
select * from order
So in case, that I need some Information from several joined objects, a query could be quite expensive: and more interesting quite ineffective. I stumbled upon a slow query and MySQL-explain told me, that in the generated query the optimizer could not make use of indices, which is bad.
Of course (I am aware) I have to deal with a tradeoff, that generated SQL isn't as optimal as manually written and have the advantage of writing less boilerplate code.
My question is: what are good strategies to improve queries, queryexecution?
I have thought for some options by myself:
1) Is it possible to define several "Entities" for different purposes, like Order for access to the full characteristics of an order and something like FilteredOrder with fewer columns and no resolution of Join-columns? Both would reference the same tables, but one would use all of the columns and the other only some.
2) Use @Query(... native="true") with a selection of all columns, which I want to use. The advantage of that would be, that I would not double my domain-objects and litter my codebase with hundreds of Filtered-Objects.
What about paging? Is using pageable in combination with @Query( ...native="true") still possible (I am afraid not).
3) Last but in my eyes "worst"/boilerplate solution: Use JDBCTemplates and do stuff at a lower level.
Are there other options, of which I haven't thought?
Thank you for any inspiration on that topic :]
Update:
Our current strategy is the following
1) Where possible, I work with select new
As I have seen, this works for every Object (be it an Entity or POJO)
2) In combination with database views it is possible to take the best of SQL and ORM. For some usecases it might be of interest to have an aggregated resultset at hand. Defining this resultset as a view makes it easy from the db-perspective to watch the result with a simple select-statement.
For the ORM-side this means, you could easily define an entity matching this view and you get the whole ORM-goodness on top: Paging incl.
A:
One solution is to use DTO's:
@Query("select new FilteredOrder(o.name, o.size, o.cost) from Order o where o.id = ?1")
Page<FilteredOrder> findFilteredOrderById(Pageable pageable, String id);
If you want to have entities for some reports generation maybe you should think about using nosql datastore?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iOS TableView with paging?
I am working on an iOS app with a nice UI for viewing users’ friends which is currently in a vertical ScrollView with paging enabled and 100×100pt pictures. However, with 500+ friends, this is insanely inefficient and slow, loading all of those pictures in memory at once. What I’d like to do is use a TableView and load the images when I load the cells, but I really like the snapping effect of having a ScrollView with paging enabled.
How would you recommend I add this functionality to a TableView?
A:
Setting the pagingEnabled property of your UITableView to YES is always an option… However, default UIScrollView paging will automatically page in multiples of your UITableView's frame height (unlikely the same height of your UITableViewCells), so you'll probably need to implement scrollViewWillEndDragging:withVelocity:targetContentOffset. This method is called when a UIScrollView (or UITableView) begins to decelerate, and it allows us to specify where the UIScrollView should finish movement.
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView
withVelocity:(CGPoint)velocity
targetContentOffset:(inout CGPoint*)targetContentOffset
{
//Intercept and recalculate the desired content offset
CGPoint targetOffset = [self recalculateUsingTargetContentOffset:targetContentOffset];
//Reset the targetContentOffset with your recalculated value
targetContentOffset->y = targetOffset.y;
}
You may want to check out this post (UITableView w/ paging & momentum) in order to get a feel for how you'll need to tailor the target content offset recalculation method to fit your needs.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Filtering PDF files that contain given keyword
I am trying to make a listBox that will display PDF files that contain given keyword in textBox.
I am using iTextSharp 7. All files are loaded into listBox as full path strings.
This is what I've done so far:
Function for finding the given keyword:
private int ReadPdfFile(string fileName, String searthText)
{
int indicator = 0;
if (File.Exists(fileName))
{
PdfReader pdfReader = new PdfReader(fileName);
PdfDocument pdfDocument = new PdfDocument(pdfReader);
{
for (int page = 1; page <= pdfDocument.GetNumberOfPages(); page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentPageText = PdfTextExtractor.GetTextFromPage(pdfDocument.GetPage(page), strategy);
if (currentPageText.Contains(searthText))
{
indicator++;
}
}
}
}
return indicator;
}
And the textBox code:
private void textBox1_TextChanged(object sender, EventArgs e)
{
listBox2.Items.Clear();
for (int i = 0; i < items.Count; i++)
{
if (ReadPdfFile(items[i].ToString(), textBox1.Text)>0)
{
listBox2.Items.Add(items[i]);
}
}
}
But when I try to type anything in textbox I get the following exception at PdfDocument pdfDocument = new PdfDocument(pdfReader);
System.IO.FileNotFoundException: 'Could not load file or assembly
'Common.Logging, Version=3.4.1.0, Culture=neutral,
PublicKeyToken=af08829b84f0328e' or one of its dependencies. The
system cannot find the file specified.'
Any suggestions?
Am I even going in the right direction?
A:
You need to check if the file Common.Logging.dll is in the bin directory of your project.If not
Try this in visual studio in package manager console type this.
PM> Install-Package Common.Logging
|
{
"pile_set_name": "StackExchange"
}
|
Q:
change line in php file
for example I have this php file:
{
$data= 'anydata';
$age = '33';
$site ='mysite';
$name = 'anyname'
}
Question: How I can change the strings with php ?
A:
fgets, read a single line, from the Manual page here
fwrite, from Manual page here
unlink, from Manual page here
rename, from Manual page here
chmod, from Manual page here
1. Open file1 (in file), file2 (outfile)
2. use fgets reading single lines (the next line) from file1
3. need to modify that string? do so.
4. use fwrite to write string to file2 (just that line)
5. loop back to 2 when not end-of-file (eof) of file1
6. close file1 and file2
7. unlink (delete) file1
8. rename file2 to file1 name
9. chmod accordingly
|
{
"pile_set_name": "StackExchange"
}
|
Q:
eclipse - is there a "duplicate file to other view" option like notepad++
Notepad++ has a feature to allow two simultaneous views of the same file in the same instance.
This is useful if you want to view two different regions of a file side-by-side.
Does Eclipse have this feature?
A:
Use 'Window > Editor > Toggle Split Editor (Horizontal)' or 'Toggle Split Editor (Vertical)'.
The keys Ctrl+_ and Ctrl+{ are shortcuts for these actions. On macOS the keys are ⇧+⌘+- and ⇧+⌘+[
|
{
"pile_set_name": "StackExchange"
}
|
Q:
egrep from Java fails while in shell succeed
I run egrep using Java Runtime.exec()
String command = "egrep \'(Success|Loading\\.\\.\\.|Loaded : READY|Found a running instance)\' "+ instance.getPath() + "/log";
Runtime.getRuntime().exec(command);
The stdout is always null and stderr shows "egrep: Unmatched ( or (". but when I copy the command to shell and run, it returns the correct value.
A:
The solution is pretty simple: (Success|Loading\\.\\.\\.|Loaded is not a valid regex.
You can't protect white space with quotes when using Process.exec(String). Always use the versions of exec() that take an array or, even better, use ProcessBuilder.
That way, you can pass each argument as a single Java String and spaces and other special characters won't create any problems.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Updating Tkinter Label with an Image
Well I got a "small" problem with updating a label using Tkinter and PIL.
As soon as I press the cheese Button it should display foo2, but it just displays a white screen. Any suggestions?
Here is my code:
from PIL import Image as Im
from Tkinter import *
class MyWindow():
def __init__(self):
self.root = Tk()
self.maskPng = Im.open("foo.png")
self.maskPng.convert("RGBA")
self.maskPng.save("bar.gif", "GIF")
self.mask = PhotoImage(file = "bar.gif")
self.show = Label(self.root, image = self.mask).pack(side = "left")
self.speedBTN = Button(self.root, text = "cheese", command = self.speed).pack(side = "right")
self.changed = False
def speed(self):
self.speedImg = Im.open('foo2')
self.speedImg = self.speedImg.convert("RGBA")
# overlaying foo and foo2 -- it works I tested it
self.maskPng.paste(self.speedImg, (0,0), self.speedImg)
self.render()
def render(self):
self.mask = PhotoImage(self.speedImg)
self.show.configure(image = self.mask)
self.show.image = self.mask
def draw(self):
self.root.mainloop()
main = MyWindow()
main.root.mainloop()
A:
Well, I think that the reason is self.show which is None when you press the button. This is because this line:
self.show = Label(self.root, image = self.mask).pack(side = "left")
should be:
self.show = Label(self.root, image = self.mask)
self.show.pack(side = "left")
This happens, because pack, grid etc. return None.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ValueError: invalid literal for int() with base 10; Trying to extract an integer from a float
Im trying to make the program to identify a number in a NETCDF file name, I altered the code, but is still giving me the same error and I can't identify why.
The section of the code creating the error is:
Band = int((listofallthefiles[number][listofallthefiles[number].find("M3C" or "M4C" or "M6C")+3:listofallthefiles[number].find("_G16")]))
The path and name of the NETCDF file is:
/Volumes/Anthonys_backup/Hurricane_Dorian/August_28/Channel_13/OR_ABI-L2-CMIPF-M6C13_G16_s20192400000200_e20192400009520_c20192400010004.nc
Im trying to extract the "13" between "M6C" and "_G16" to save the value, but its giving me the error message:
ValueError: invalid literal for int() with base 10: 'olumes/Anthonys_backup/Hurricane_Dorian/August_28/Channel_13/OR_ABI-L2-CMIPF-M6C13'
A:
First extract the number of your string, so that int can properly convert it, see here.
It might be easier to use regex to do so, e.g.:
import re
...
str = listofallthefiles[number]
num = re.findall('.*M6C(.*)_G16', str)[0]
Now you can convert that to an integer:
val = int(num)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
XML caracteres especiales ( como ñ ) en el nombre de un atributo
Sucede la ley de mi país requiere un nuevo atributo en el XML de uno de sus tramites ( CFDI ) http://www.sat.gob.mx/informacion_fiscal/factura_electronica/Documents/Complementoscfdi/nomina12.pdf pag.37
<xs:attribute name="NumAñosServicio" use="required">
<xs:annotation>
<xs:documentation>Atributo requerido para expresar el número de años de servicio del trabajador. Se redondea al entero
superior si la cifra contiene años y meses y hay más de 6 meses.</xs:documentation>
El fragmento de xml por lo tanto queda así:
<nomina12 NumAñosServicio="12"/>
Personalmente nunca me había encontrado un nombre de atributo que tuviera un carácter especial ñ en su nombre. Incluso dudo que sea valido hacerlo ni mucho menos que sea una practica recomendable.
El documento se define con UTF-8 : <?xml version=“1.0” encoding=“utf-8”?>
El sistema responsable de emitir este documento actualmente utiliza SAXParser con jdk 1.7 y falla al intentar parsearlo truncándose en "NumA" aunque todo el encoding y el charset sea con UTF-8.
Estoy tratando de encontrar un approach para solucionar este problema y ya que es un requerimiento que entra en vigor en año nuevo creo que muchos están pasando por esta situación. Cualquier ayuda o información al respecto estaré muy agradecido.
A:
Solucionado:
Es importante en el parsing asegurarse de especificar también el uso de UTF-8:
Reader reader = new InputStreamReader(inputStream,"UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
saxParser.parse(is);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Specifying a request body doing a Gatling POST
I'm a fresh newbie to Gatling. I'm trying to send a POST message to an HTTP API using Gatling. I tried the following:
package app.basic
import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._
class basicPost extends Simulation {
val headers_10 = Map("Content-Type" -> """application/json""")
object Post {
// repeat is a loop resolved at RUNTIME
val post = repeat(50) {
exec(http("Post Data")
.post("/data")
.queryParam("""size""", "10"))
.headers(headers_10)
.body("""{"id1":"0000000000"}""")
.pause(1)
}
}
val httpConf = http.baseURL("http://amazonperf-env.elasticbeanstalk.com")
val users = scenario("Users").exec(Post.post)
setUp(
users.inject(rampUsers(1000) over (10 seconds))
).protocols(httpConf)
}
However, I get this error when compiling: value body is not a member of io.gatling.core.structure.ChainBuilder
possible cause: maybe a semicolon is missing before `value body'?
How do I specify the body of the message that I want to send?
A:
This is old Gatling 1 syntax (Gatling 1 is deprecated and no longer maintained).
Please read the documentation.
In you case, you'd get something like:
.body(StringBody("""{"id1":"0000000000"}"""))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Command with argument within a command within a command
Yes, that title is a complete mess. I didn't really know how else to describe it.
I'm setting up my RPi to run Homebridge in a screen on startup. I've edited my rc.local file to include this line:
su - pi -c "screen -dm -S hbscreen homebridge"
It creates a screen called "hbscreen" which executes the command "homebridge". Now the problem is that I'd like to add an argument so the command reads "homebridge -I".
Seeing as I like to just try things I simply added -I to the line and got this:
su - pi -c "screen -dm -S hbscreen homebridge -I"
But suddenly my RPi wouldn't boot anymore. So, I guess that wasn't the right way to go about it.
I've been googling for half an hour now and I can't seem to figure it out. What would be the correct notation? I'm guessing I need to let it know "homebridge -I" is one piece, but I'm assuming I can't use quotation marks within quotation marks like this:
su - pi -c "screen -dm -S hbscreen "homebridge -I""
A:
Thanks to someone on Reddit I managed to fix it by not putting everything in rc.local but instead making an .sh file in my home directory called hbboot.sh and running that instead.
rc.local:
su - pi -c "screen -dm -S hbscreen ~/hbboot.sh"
hbboot.sh:
#!/bin/sh
homebridge -I "$@"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make Python to be Client-Side?
I know that Python can be a server-side language but is there a way to make python act like a client side language (like javascript) i just want to try it out if its possible thank you
A:
You can compile your python to javascript with Pyjs.
Note that if you use Skulpt, Skulpt will NOT let you create full websites or actual javascript code that can run inside browsers. For this, you must use Pyjs. Pyjs essentially transforms your Python code into actual Javascript, so you can run the resulting Javascript in any browser, or host it as a website.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
push to array vb.net 2008
the message was variable j is used before it have been assigned value.If in php language, it's not a problem at all.
Dim j() As String
Dim i As Integer
If (i = 1) Then
j(0) = "x"
Else
j(0) = "d"
End If
A:
in php language,it's not a problem at all.
php doesn't use real arrays. A real array is a contiguous block of memory. Php uses a collection type with array-like semantics. They call it an array, but it's not really. Collections seldom make the same kind of guarantees about continuity because of performance problems caused when the collection grows at runtime.
If you want php-style "arrays" in .Net, you need to do the same thing php does and use a collection. The System.Collections.Generics.List<T> type works pretty well. Then you can append to the List by using its .Add() method or using the collection initializer syntax demonstrated below (requires Visual Studio 2010):
Dim i As Integer = 1
Dim j As New List(Of String) From { If(i = 1, "x","d") }
We can forgive php it's naming lapse, though, as real arrays should be used sparingly. A collection is almost always more appropriate.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Show the error instead of ruby default?
When using this I am getting the default design for Ruby on Rails . How can i just print it as regular text in my current design like <%= error.text %>?
Model:
class Users < ActiveRecord::Base
validates_presence_of :username, :message => "Du skal udfylde brugernavn"
attr_accessible :email, :password, :username
end
Controller:
class HomeController < ApplicationController
def index
if params[:username]
l = Users.new(:username => params[:username], :password => params[:password], :email => params[:email]).save!
if Users.save?
z = Users.where(:username => params[:username]).limit(1).last
@debugging="Yay"
else
@debugging = user.errors.full_messages.join("<br/>")
end
end
end
end
A:
In model:
validates_presence_of :username, :message => "Du skal udfylde brugernavn"
In controller:
if user.save
flash[:success] = 'User saved successfully'
else
flash[:error] = user.errors.full_messages.join('<br />')
end
Edit
Not if Users.save? it should be l.save. (I suggest you to use User as model)
if params[:username]
l = Users.new(:username => params[:username], :password => params[:password], :email => params[:email])
if l.save
z = Users.where(:username => params[:username]).limit(1).last
@debugging="Yay"
else
@debugging = l.errors.full_messages.join("<br/>")
end
end
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Difference in acid strength of oxalic acid and malonic acid
Despite very similar skeletal structures, the difference in acid strength between oxalic acid (ethanedioic acid) and malonic acid (propanedioic acid) is quite significant. What is the reason for that?
It seems that the inductive effect plays a role, but what is the explanation for the inductive effect in oxalic acid as there is same group on opposite sides?
How does the inductive effect plays different roles in both acids?
A:
** UNDER DEVELOPMENT **
Linear saturated dicarboxylic acids
$n$ = number of $\ce{-CH_2}-$ groups in chain
n pKa1 pKa2 Ka1/Ka2
0 Oxalic acid 1.25 4.14 776
1 Malonic acid 2.83 5.69 724
2 Succinic acid 4.21 5.41 15.8
3 Glutaric acid 4.34 5.41 11.7
4 Adipic acid 4.41 5.41 10.0
5 Pimelic acid 4.50 5.43 8.51
6 Suberic acid 4.526 5.498 9.4
12 Dodecanedioic acid 4.45 5.05 4.0
Dodecanedioic acid
Aromatic carboxylic acids
pka1 pka2 pka3
benzoic acid 4.202 ---- ----
ortho-phthalic acid 2.89 5.51 ----
meta-phthalic acid 3.46 4.46 ----
para-phthalic acid 3.51 4.82 ----
o,o'-bibenzoic acid
p,p'-bibenzoic acid
benzene-1,3,5-tricarboxylic acid 3.12 3.89 4.70
Linear unsaturated dicarboxylic acids
$n$ = number of $\ce{-CH=CH}-$ trans groups in chain
n pka1 pka2
0 Oxalic acid 1.25 4.14
1 Fumaric acid 3.02 4.38
2 trans,trans-Muconic acid 3.87
3
Straight-chain, saturated carboxylic acids
$n =$ total number of carbon atoms in molecule ($n \geqslant 2$ has terminal methyl group).
n pKa
1 Formic acid 3.77
2 Acetic acid 4.76
3 Propionic acid 4.88
4 Butyric acid 4.82
5 Valeric acid 4.82
6 Caproic acid 4.88
15 Pentadecanoic acid 4.8
most $\mathrm{p}K_\mathrm{a}$ data from Wikipedia.
How does the inductive effect plays different roles in both acids?
First think of what happens when the carboxylic acid group of a straight-chain, saturated carboxylic acids ionizes to form the carboxylate ion. The $\ce{C=O}$ and $\ce{-C-O^{-}}$ bonds of course hybridize. This hybridization occurs faster than hydrogen bonds to the solvent form. The net result is effectively two oxygen atoms with 1/2 a charge each. This increases the ability of the carboxylate ion to solvate, which increases its acidity.
In malonic acid the $\ce{C-C}$ bond "shares" some of that hybridization. This is the "inductive effect." The additional delocalization of the electrons from the carbon atoms makes the carboxylate ions more electronegative than they would be in a long linear saturated dicarboxylic acid. So the first ionization , the second ionization
A:
First, notice that a carboxylic carbon ($\ce{COOH}$) has an oxidation state of $\mathrm{+III}$ (except in formic acid where it is $\mathrm{+II}$). This means, that the carbon is very electron deficient and wishes to draw electrons towards it from sources that are not the two oxygen atoms (because they are stronger). We term this an inductive effect, as we cannot easily draw mesomeric structures to explain it.
Since the inductive effect is mainly based on electrostatic interactions, it gets exponentially weaker with increasing distance. In oxalic acid, there is one one bond separating the two carboxylic groups, so they can exert a strong inductive effect. In malonic acid the effect is weaker due to the separating $\ce{CH2}$ group. And in succinic and subsequent diacids it is almost unmeasurable due to the distance between the groups.
But how do we rationalise each group exerting a $+I$ effect on the corresponding other group? Well — we cannot deprotonate twice immediately (I am introducing this as an axiom, but it does have reasoning that I feel too lazy to explain right now). So we have to pretend one side is going to be inert while the other is deprotonated. And if we do that, we see that the inductive effect of one side is strong in drawing away electron density from the $\ce{COOH}$ group we are deprotonating. Since this means there is a lower effective negative charge, deprotonation happens more easily, i.e. at lower $\ce{pH}$.
We can use this simple picture since the groups are isotopic, i.e. they can be transformed into each other by a $C_2$ rotation of the molecule’s inherent symmetry.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How much sturdier are through mix pavers vs face mix?
I’m adding pavers to a section in the backyard ~320 sqft worth around concrete surrounding a pool.
I found face mix pavers but am hearing that I should use through mix pavers.
I’m not seeing much online on the benefits of one over the other. Any specs or knowledge would be appreciated.
A:
A quick search reveals that face-mix pavers have a concentrated wear/color/texture layer on top. I don't see any indication that this substantially affects strength. If you install a proper base, strength probably isn't a concern anyway.
Prior to Face-mix technology, pavers were a blend of aggregate, pigment color, and concrete pressed together. When the thru-mix wear with age, the coloring fades and the coarse aggregates in the pavers (which are used to increase the strength of the paver) starts to show through the top of paver, which can ruin the look of the paver.
Face-mix technology adds concentrated color and fine wear-resistant aggregates on the top of the paver, in addition to the coarse aggregates at the base of the paver. So not only is the paver structurally strong, but the color and finish of the paver lasts for generations. The Face-mix process eliminates the risk of the coarse (and ugly) aggregate from appearing through the top of the paver.
https://unilock.com/paver-technology/thru-mix-vs-face-mix/
Of course, through-mix sellers have their own arguments:
If the concrete paver is brand new someone may not notice the difference, over time however it becomes obvious. If a face mix paver should become chipped the gray core will be exposed to the surface. The core of a through mix paver is the same color as the surface so this is not an issue. Since the color for a face mix paver is not mixed throughout the entire paver it tends to fade at a faster rate than a through mix paver. We manufacture all of our pavers using a through mix allowing for more intense longer lasting color.
https://castleliteblock.wordpress.com/2015/09/16/what-is-through-mix-and-why-we-use-it-exclusively-for-our-pavers/
It's really a matter of your priorities. If you don't expect rough treatment, face-mix might give better results over time. If you expect chips and scratches from hard objects, through-mix is probably the best choice.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is a speeding ticket invalid if the listed speed is not what it was?
I recall reading about speeding ticket defenses in some jurisdiction in the United States or Canada that the fact that the officer "reduced" the alleged speed that he obtained through his radar and such, invalidates the whole ticket. (Which is probably one of the reasons that the officers never negotiate what number they put on the ticket.)
E.g., if the traffic citation says you were going 80 in a 70 zone on an interstate, but, it turns out, the officer does have evidence from his laser that you were going 85 instead, then the ticket is invalid and should be dismissed by the judge as improper. (Would it matter if, for example, the officer did have another reading at exactly 80? Or if he has also followed you bumper-to-bumper for a couple of seconds at the speed of, say, 75, or 78?)
Could anyone possibly find any reference or confirmation of this? Would something like this be applicable in Texas?
A:
Here is a link to the relevant Texas Statute: Title 7, Subtitle C, Chapter 545, Subchapter A:
Sec. 545.351. MAXIMUM SPEED REQUIREMENT. (a) An operator may not drive at a speed greater than is reasonable and prudent under the circumstances then existing.
Combine that with:
Sec. 545.352. PRIMA FACIE SPEED LIMITS. (a) A speed in excess of the limits established by Subsection (b) or under another provision of this subchapter is prima facie evidence that the speed is not reasonable and prudent and that the speed is unlawful.
This section mentions, as an example, among other points:
(2) except as provided by Subdivision (4), 70 miles per hour on a highway numbered by this state or the United States outside an urban district, including a farm-to-market or ranch-to-market road;
What this means is that if you are driving over 70 miles per hour on a type of highway mentioned in (2) above then you are, by legal definition, driving at a speed that is greater than is reasonable and prudent.
When you are cited for speeding you are not charged for driving at a specific speed in an area posted at another speed. You are cited for violating a broader law, such as in Texas, driving in an unreasonable or imprudent manner. The mention of the speed is merely a recordation of the facts that support the state's case against you.
Let's take the proposal to demonstrate the speed is too low to its logical conclusion. You plead not guilty and it comes out during testimony that you weren't driving 80 but really 85. The judge will still find you guilty of the underlying charge as the facts in the case still support that finding.
I have personally witnessed mistakes in tickets result in dismissal. Those mistakes have, however, been related to other facts about the case though: time of day, date of offense, etc.
I've also witnessed people attempt to claim a lower but still illegal speed. For example, "I wasn't going 85 I was only going 80." These resulted in findings of guilt.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
mod_rewrite replace '_' with '-'
I'm almost there with a mod_rewrite rule, but I've caved in :)
I need to rewrite
country/[countryname].php
to
country/[countryname]/
however, [countryname] may have an underscore like this: 'south_africa.php' and if it does I want to replace it with a hypen: 'south-africa/'
I also want to match if the country has numbers following it: 'france03.php' to 'france/'
Heres my rule, its almost there but its still adding a hyphen even if there is no second part after the underscore.
RewriteRule ^country/(.*)_(.*?)[0-9]*\.php$ country/$1-$2 [R=301,L]
so currently 'country/south_.php' becomes 'country/south-/'
Can someone please help me find the missing piece of the puzzle? Thanks.
A:
Try this:
RewriteRule ^country/([^_]*)_([^_]*?)\d*\.php$ country/$1-$2 [R=301,L]
This rule will match urls with a single underscore - you'll need a different rule for more underscores or none.
If you want to make sure $2 contains only letter and isn't empty, change ([^_]*?) it to ([a-zA-Z]+).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I catch and rethrow an error in Perl?
Let's say I have a module Bar that is a subclass wrapper for module Foo. I want calls to Bar's methods to mimic Foo's exactly -- even down to fatal errors. So far, easy enough; I just call the SUPER method.
sub stuff {
# Do stuff here
SUPER::stuff(@_);
# Do more stuff here
}
But, let's say that I want to catch, log, and rethrow any fatal errors SUPER::stuff() produces. First two steps are easy:
sub stuff {
# Do stuff here
eval {
SUPER::stuff(@_);
};
$@ and log("Naughty, naughty: $@");
# Do more stuff here
}
... but I don't know how to do the last part. How do I re-throw the error in such a way that the caller will be unable to distinguish between a call to Foo->stuff() and a call to Bar->stuff()? Can I just insert die $@ after the log statement and expect it to do what I want, or are there nuances here that would likely get me into trouble?
A:
The full code to safely eval/catch/log/rethrow in Perl can be a bit verbose.
sub stuff {
# Do stuff here
local $@; # don't reset $@ for our caller.
my $eval_ok = eval { # get the return from eval, it will be undef if the eval catches an error.
SUPER::stuff(@_);
1; # return 1 (true) if there are no errors caught.
};
if (!$eval_ok) { # don't trust $@ it might have been reset as the eval unrolled.
my $error = $@ || 'unknown error'; # copy $@ incase write_log resets $@, or is later changed to cause it to reset $@.
write_log("Naughty, naughty: $error");
die $error; # after all that we can rethrow our error.
}
# Do more stuff here
}
You can use Try::Tiny sugested by mob to simplify:
sub stuff {
# Do stuff here
try {
SUPER::stuff(@_);
} catch {
my $error = $_;
write_log("Naughty, naughty: $error");
die $error;
}
# Do more stuff here
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is a bit pattern?
I'm reading a book at it cites the following:
With primitive variables, an assignment of one variable to another means the contents (bit pattern) of one variable are copied into another...The contents of a reference variable are a bit pattern...
Please help me understand what 'bit pattern' means here. Is that another way of saying the memory address of a variable?
For example, what could the bit patterns look like for the following two variables
int x;
TimeClass time;
Integer y;
So, for example if "int x = 4" and that 4 resides at memory address X77348 then what gets copied to the other reference? 00000100 (which is 4 in binary)? or the X77348
A:
Not the memory address of the primitive variables. The contents of the memory address of the primitive variable.
Likewise, with a reference it's the contents of the memory address of the reference variable. (Remember that behind the scenes a Java reference is essentially a pointer. So the "bit pattern" with respect to a reference is that pointer (which points to wherever on the heap the object lives)).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ubuntu rename command regex not working
I'm trying to use the rename command to rename a bunch of images in a folder.
I have this list of images,
image.php?x=10
image.php?x=25
image.php?x=50
image.php?x=75
I'm trying to rename them to 10.png, 25.png etc. using this regex:
$ rename "s/image\.php\?x\=(.*)/$1\.png/g" *
This regex works fine in for example Sublime Text, all the matches are replaced correctly...
But when I run the rename command like this, with $0 it says bash.png already exists and with $1 it says .png already exists, so nothing was saved!
wat do?
A:
Most probably, your shell is expanding $1 (likely to an empty string) before passing it to the rename command. Try single quotes instead of double quotes around the regex:
rename -- 's/image\.php\?x\=(.*)/$1.png/g' *
(also, it should not be necessary to escape the dot in the replacement expression i.e. you can use $1.png in place of $1\.png)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why do plain-text technical articles often enclose terms within backticks and single quotes?
I like to save local copies of useful text-heavy pages from the web so I can practice improving their appearance by modifying the markup to include CSS.
I've noticed that some text on the pages is often delimited by ` and '.
Is there a good reason for this? I'd like to do my modifications automatically with a script if I thought these quotes were there for a good reason. Is it, for example, a byproduct of a particular authoring tool?
I have tried to search for this, but search engines treat it like empty or incomplete strings and don't give meaningful results.
A single quote example (` ') can be found in Eric Raymond's Cathedral and the Bazaar:
The problem was this: suppose someone named `joe' on locke sent me mail. If I fetched the mail to snark and then tried to reply to it, my mailer would cheerfully try to ship it to a nonexistent `joe' on snark. Hand-editing reply addresses to tack on `@ccil.org' quickly got to be a serious pain.
A:
The example of Eric Raymond’s essay is a typical example of people from pre-Unicode eras trying to “improve” the typograph of their text by using conventions that no longer hold. The quoting style `' is typical of that. It’s also used in LaTeX (which automatically converts it to correct typographical single quotes ‘’).
You can see other ASCII artifacts in Eric’s essay, too: for example, he uses “--” instead of a “correct” dash “–” (an awful lot of people do this, since the dash doesn’t exist on default Windows keyboards).
As such, it’s an anachronism from a time where support for Unicode fonts (or generally: fonts lacking these typographical features) wasn’t widespread.
A:
HTML doesn't. Only ' and " characters may be used to delimit attribute values (which are the only strings that can be delimited in HTML).
People writing text (which happens to be marked up with HTML) may use “,”,‘ and ’, but that is just writing using quote marks.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Initialization Vector in encryption
I've never done any encryption before, but I've been all over MSDN and google. I finally got something working.
I've seen this a ton of times:
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}.
My question is this - do the hex digits inside the array have any significance? I just find it terribly odd that these particular numbers would be used SO often otherwise.
A:
It doesn't matter. Anything can be in the initialization vector (as long as both sides use the same values in the vector). These values are used in examples because they are simple...
Read more about the initialization vector here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change height on TelerikMVC Grid Control
Does anybody know a way for changing the height of a Telerik Extensions for MVC Grid? Other than overriding the style manually using
div#MyGrid .t-grid-content {
height: 100px !important;
}
I'd like to controll that on the grid itself, not on the stylesheet. Telerik samples and documentation say nothing about it and it seems it's not supported
Have anybody faced (and solved) the same issue?
A:
You can control the height of the grid using the Scrollable method.
Using an int32 representing pixels:
.Scrollable(scrolling => scrolling.Height(500))
Using a string:
.Scrolling(scrolling => scrolling.Height("20em"))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
reCAPTCHA v2 with HTML5 Dialog .showModal() method
Google's reCAPTCHA v2 displays layering problems when included in a HTML5 dialog triggered with .showModal(). The challenge element with the question and the images is layered underneath the dialog instead of on top.
Try this demo in a browser which natively supports the HTML5 dialog, such as Chrome:
Demo
The offending code is the document.body.appendChild(a.P) in the reCAPTCHA JavaScript, which appends the challenge div to the document body. I've thought about monkey-patching this to append to the dialog instead, but this is also not an ideal solution.
One workaround is to use the .show() method instead of the .showModal() method:
Workaround
Is there a better solution to this? @google Can this be fixed in reCAPTCHA itself?
A:
Invoking the dialog using .show() and mimicking the styling of the .showModal() method seems to be the best solution for now:
http://jsfiddle.net/karlhorky/b3hjdqeL/9/
Unless Google updates reCAPTCHA for use inside <dialog>s, this is the cleanest solution I've come up with.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add slightly similar content with regular expressions (regex)?
I'm using Dreamweaver on a file that has about 30 instances the following:
'portfolio_bg' =>'#555555',
'portfolio_font'=>'#ffffff',
But, for each instance the hex codes are different. I want to add the following two lines underneath the above:
'product_bg' =>'#555555',
'product_font'=>'#ffffff',
where the hex codes in my two product lines will match the hex codes of the portfolio lines above it.
How do I accomplish his using regular expressions in Dreamweaver's Find and Replace?
Thanks in advance.
A:
This works for me in EditPad Pro; it should work in Dreamweaver too.
Find:
'portfolio_bg'\s*=>\s*'(#[0-9A-Fa-f]+)',(\s+)'portfolio_font'\s*=>\s*'(#[0-9A-Fa-f]+)',\s*
Replace:
$&$2'product_bg' =>'$1',$2'product_font'=>'$3',$2
EDIT: corrected replacement string to use $& instead of $0.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NAA flag has been sitting in the VLQ queue for 2 weeks (even though earlier and later flags have been reviewed)
I recently flagged this link-only answer as NAA. While the OP is, in fact, looking for a library recommendation (which the links technically provided), the links are now dead. Obviously, this renders the answer completely useless (hence my NAA flag).
However, at this point, the post has been sitting in the VLQ queue for 2 weeks without being reviewed (even though some of my other earlier - and later - VLQ and NAA flags have been reviewed).
Any idea why this might be?
A:
"not an answer" flags can be handled at varying rates, depending on a number of factors that aren't obvious to the flagger. Flagged posts in the moderator queue are sorted first by number of flags on the post and then by the age of the flags. Posts that accumulate multiple flags jump to the top of the queue.
I checked, and the flags you had handled earlier than this one largely had multiple flags on them from other users. They also tended to be "have you solved this?" or "I like turtles" kinds of non-answers, which are easy to judge and delete in seconds from the queue.
Also, sometimes obvious flags can get buried between bad ones (people love flagging answers they simply don't like or think are wrong as "not an answer"), which can block us from seeing your flag until we work through those.
Community review can handle some of these, which further complicates when they might be processed.
And yes, there's an election going on right now to add more people to help.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a view controller for image crop and rotate works like iOS 8 photo.app?
I need a view controller for user to crop and rotate image.
And I think the UI which iOS8 photo app did is very awesome
But I found only these two :
https://github.com/heitorfr/ios-image-editor
https://github.com/kishikawakatsumi/PEPhotoCropEditor
These are useful, but when making image smaller than the crop area, to move or rotate the image is very difficult, and the respond is very weird.
After using these, I think the iOS8 photo app's crop and rotate function is much better
So is there a view controller performs image crop and rotate like iOS 8 photo app?
A:
Try The following:
https://github.com/itouch2/PhotoTweaks
https://github.com/yackle/CLImageEditor
They enables similar functionality as the native Photos app in iOS8.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Making a persistent SSO with OAuth2 Client and ADFS 3.0
I have a hybrid(Ionic) mobile app is registered as an OAuth2 client with ADFS3.0.
Now, i am doing Authorization Code Grant Method of OAuth2 as it is the only method supported by ADFS3.0. I am successfully getting the access token, and staying in the session.
But, after 1 hour, when the access token expires, and ADFS asks me to enter my credentials again. How to make this a persistent SSO.
I am using Cordova Inappbrowser to call the ADFS Url.
A:
When you got the original tokens, you should have received a refresh token as well.
Then use something like:
POST xxx/token
grant_type=refresh_token
client_id=xxx
client_secret=yyy
refresh_token=token
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++ Program reading '*' as 'a'
I am working on a short little calculator program that takes command line arguments and performs the relevant operations. It all works fine except with multiplication.
When I type "./calc 3 * 3" in the command line, the program spits out an error, and when I "cout" the char it stored as operator it says "a". All the other operators work fine.
Can you guys figure out why it's not accepting '*' as a char?
Here is the code and some sample output:
#include <iostream>
#include <cstdlib>
using namespace std;
const int MINIMUM_ARGUMENTS = 4; //must have at least 4 arguments: execution command, a first number, the operator, and a second number;
double Add(double x, double y);
double Subtract(double x, double y);
double Multiply(double x, double y);
double Divide(double x, double y);
int main(int argc, char* argv[])
{
if (argc < MINIMUM_ARGUMENTS) //"less than" because counting execution command as first argument
{
cout << "\nMust have at least " << MINIMUM_ARGUMENTS << " arguments (including execution command)." << endl;
}
else
{
double num1 = atof(argv[1]); //stores first argument as double
char operation = *argv[2]; //stores second argument (operator) as char
double num2 = atof(argv[3]); //stores third argument - second number
double result = 0; //will store result of arithmetic
cout << '\n';
switch (operation) //determines which function to call based on the char (operator) argument
{
case '+':
result = Add(num1, num2);
cout << result << endl;
break;
case '-':
result = Subtract(num1, num2);
cout << result << endl;
break;
case '*':
result = Multiply(num1, num2);
cout << result << endl;
break;
case '/':
result = Divide(num1, num2);
cout << result << endl;
break;
default:
cout << "Error." << endl;
}
}
cin.clear();
cout << "\nPress enter to quit." << endl;
cin.ignore();
return 0;
}
double Add(double x, double y)
{
return x + y;
}
double Subtract(double x, double y)
{
return x - y;
}
double Multiply(double x, double y)
{
return x * y;
}
double Divide(double x, double y)
{
return x / y;
}
Sample Output:
-bash-4.1$ ./calc 10 - 5
5
Press enter to quit.
-bash-4.1$ ./calc 4 + 9
13
Press enter to quit.
-bash-4.1$ ./calc 10 / 2
5
Press enter to quit.
-bash-4.1$ ./calc 5 * 5
Error.
Press enter to quit.
A:
The * sign is used by OS (bash here) to select all files from current dir. so change your sign.
I suggest 'x'
A:
While sending * use single quotes '*' or escape it using \*.
Simply * will not work because on command line * means "everything in the current directory".
A:
* is a wildcard that is used to select all . Generally used in selecting all files in a directory .
For example :
delete *.exe: This command would delete all the files with extension ".exe " from the folder .
If used in bash, * would be treated as a Wildcard, so you should consider some other sign to perform the required operation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to swipe right on ViewPager
I'm using a ViewPager on android.
When I start the ViewPager from a certain position other than 0, I cannot swipe right to go back to previous positions but I can swipe left to go to next positions.
Is it a default ViewPager property ? What do I need to do to be able to swipe right ?
Inside OnCreate
viewPager = (ViewPager) findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
Outside OnCreate
private class ImagePagerAdapter extends PagerAdapter{
@Override
public int getCount() {
return imageFull.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((SubsamplingScaleImageView) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = ImageGallery.this;
SubsamplingScaleImageView fullImage =
new SubsamplingScaleImageView(ImageGallery.this);
// starting the view pager from position 4
viewPager.setCurrentItem(4);
fullImage.setImage(ImageSource.uri(imageFull.get(position_value)));
return fullImage;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((SubsamplingScaleImageView) object);
}
}
A:
You should setCurrentItem after setting the adapter for the viewpager not in the viewpager instantiateItem() method. You should try this:
Inside OnCreate
viewPager = (ViewPager) findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(4);
A:
viewPager = (ViewPager) findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(4);
private class ImagePagerAdapter extends PagerAdapter{
@Override
public int getCount() {
return imageFull.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((SubsamplingScaleImageView) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = ImageGallery.this;
SubsamplingScaleImageView fullImage =
new SubsamplingScaleImageView(ImageGallery.this);
fullImage.setImage(ImageSource.uri(imageFull.get(position_value)));
return fullImage;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((SubsamplingScaleImageView) object);
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Reading USB Relay Specifications
Good morning,
I am trying to work on some home improvement DIY projects and trying to control light from an RPi / Arduino using USB connection. I've found two possible products, that I think might suit me:
http://www.sainsmart.com/8-channel-dc-5v-relay-module-for-arduino-pic-arm-dsp-avr-msp430-ttl-logic.html
or
http://www.amazon.com/gp/product/B0093Y89DE/ref=pd_lpo_sbs_dp_ss_1?pf_rd_p=1944687622&pf_rd_s=lpo-top-stripe-1&pf_rd_t=201&pf_rd_i=B004JWW1GQ&pf_rd_m=ATVPDKIKX0DER&pf_rd_r=1QWFW0X2KN49TCBWJW0K#product-description-iframe.
However, I was not really sure how to exactly read the specs for the relays that are given on each website. The light that I am trying to control are going to operating at 12V drawing around 5A (60W bulbs). The specs that are given are:
Relay specification: 10A 250VAC/10A 125VAC/10A 30VDC /10A 28VDC
Power Supply: 12 VDC
Current consumption: 300 mA
Thus I wanted to ask if somebody could enlighten me what the first line "Relay specification" means? Would it be able to handle 5A / 12V bulbs that I would want to connect to it?
Thank you very much to everybody.
A:
The "DC30V 10A" means that it can switch DC voltages up to 30V, at currents up to 10A.
Switching DC is more difficult than switching AC, which is why you might see "250VAC 10A" on the same device.
So the basic answer to your question is 'Yes'.
Incandescent light bulbs do draw much more than their rated current when you first turn them on (because they're cold), so your 5A lamp might be quite hard work for the relays. However switches usually struggle more with turning off than turning on, so you'll probably be OK, at least within the margin of confidence you can have in the rating of cheapo relays.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Generate all ways of selection of n items
Possible Duplicate:
How to find all possible subsets of a given array?
How can all ways of selection of items be generated efficiently using C++?
For example, if there are there items A, B and C.
[A,B,C] => [A], [B], [C], [A,B], [B,C], [A,C], [A, B, C]
A:
For that input set:
#include <iostream>
void print(int b, char *a, int n)
{
for(int i = 0 ; i < n ; i++)
{
if( b & 0x1) std::cout << a[i];
b = b >> 1;
}
std::cout << std::endl;
}
int main() {
char a[] = {'A','B','C'};
for(int i = 1 ; i < 8 ; i++ )
print(i,a,3);
return 0;
}
Output:
A
B
AB
C
AC
BC
ABC
Demo : http://ideone.com/2Wxbi
Now it's your turn to improve and generalize this approach, and find it's limitations.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
setting MySQL field uid as auto_increment
For some reason i keep getting the following error when i try to set my uid as auto_increment. I am using phpMyAdmin.
Error
SQL query:
ALTER TABLE `ITEMS` ADD `uid` INT( 2 ) NOT NULL AUTO_INCREMENT FIRST ,
ADD `name` VARCHAR( 100 ) NOT NULL AFTER `uid` ,
ADD `status` VARCHAR( 100 ) NOT NULL AFTER `name`
MySQL said: Documentation
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
I had a few other tables in my database that originally had index as auto_increment but I changed all those columns to uid varchar. But now I am adding a table named ITEMS and I want uid to be the "master" key that I can use as a reference point to all my other tables.
A:
You need to add the PRIMARY KEY constraint to your new column. BTW, this may mean removing that constraint from any old column that was originally AUTO_INCREMENT.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Angular2 Query Parameter from index URL
I am trying to get the query params from a url in a component in Angular2
Version: "angular2": "npm:[email protected]",
I am trying to extract id query param in the component and display it
Here is the request.
localhost:8080/index.html?id=1
boot.ts
import 'reflect-metadata';
import 'angular2/bundles/angular2-polyfills';
import { bootstrap } from 'angular2/platform/browser';
import { provide} from 'angular2/core';
import { AppComponent } from './app.component';
import {ROUTER_PROVIDERS, Location, LocationStrategy, HashLocationStrategy} from "angular2/router";
import {HTTP_PROVIDERS} from "angular2/http";
bootstrap(AppComponent , [ROUTER_PROVIDERS, HTTP_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy})]);
Here is app.component.ts
import { Component } from 'angular2/core';
import {Router, Location, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig, RouteParams} from 'angular2/router';
@Component({
selector: 'my-app',
template: '{{welcome}} {{queryParam}}',
directives: [ROUTER_DIRECTIVES]
})
export class AppComponent {
welcome: string = 'Query Param test!'
queryParam : string;
constructor(private _location: Location, private _routeParams: RouteParams){
console.log(_routeParams.get('id'));
this.queryParam = _routeParams.get('id');
}
}
I keep getting this error:
error message
I got this solution from another post. Not sure how to fix the error
A
A:
RouteParams it's not available in the root component. It's only available to the routable components.
See RouterOutlet soure code, in its activate function, you can see the following
var providers = Injector.resolve([
provide(RouteData, {useValue: nextInstruction.routeData}),
provide(RouteParams, {useValue: new RouteParams(nextInstruction.params)}),
provide(routerMod.Router, {useValue: childRouter})
]);
Basically RouteParams is being injected through RouterOutlet to the routable components, you can't access it in non-routable components (sorry for repeating myself).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Prove that :$\tan 70 - \tan 20 = 2\tan 40 + 4\tan 10$
Prove that :$\tan 70 - \tan 20 = 2\tan 40 + 4\tan 10$
My Attempt,
$$70-20=40+10$$
$$\tan (70-20)=\tan (40+10)$$
$$\dfrac {\tan 70 - \tan 20}{1+\tan 70. \tan 20 }=\dfrac
{\tan 40 + \tan 10 }{1-\tan 40. \tan 10 }$$
How should I move on? Please help
Thanks
A:
Hint:
Repeatedly use the identity $$\tan x - \cot x = \tan x - \frac{1}{\tan x} = \frac{\tan^2 x-1}{\tan x} = \frac{-2(1-\tan^2 x)}{2\tan x} = \frac{-2}{\frac{2\tan x}{1-\tan^2 x}} = \frac{-2}{\tan 2x}$$ $$ = -2\cot 2x$$ to get, $$\tan 20 - \cot 20 = -2\cot 40 \tag{1}$$ $$2(\tan 40 - \cot 40) = -4\cot 80 \tag{2}$$ Adding $(1)$ and $(2)$ gives us, $$\tan 20 + 2\tan 40 - \cot 20 = -4\cot 80 = -4\tan 10$$ $$\Rightarrow \cot 20 = \tan 70 = \tan 20 + 2\tan 40 + 4\tan 10$$ Hope it helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OpenCV: black image captured from usb camera
I am trying to capture an image frame from a USB camera using opencv. However I am always getting a black frame. I have read many posts with this issue and tried all the suggestions but nothing worked for me.
I started using the code discussed here:
http://opencv-users.1802565.n2.nabble.com/Using-USB-Camera-td6786148.html
I have tried including the method cvWaitKey(1000) after many 'critical' sentences. As you can see the waiting value is very high (1000).
I have also tried to save the image frame and, equally, it is a black image.
I am using the following system:
OpenCV 2.2.0
Windows 7, 32 bits
Visual Studio 2010 (C++)
a board usb camera (which I do not know the manufacturer)
The usb camera works well with AMCAP.EXE 1.00.
Could it be because of the camera drivers being used by Windows? Could I change to other drivers that work better for OpenCV 2.2.0?
Thanks
A:
Ok. As I promised to your request in the comments, and sorry to keep you waiting, really been busy. Barely had time to post this answer too. But here it is:
This is me simulating that opencv is capturing black image. On the output window, which I had asked you in the comments about what it says, shows that there is an error.
After investigating, I realised that it is due to the camera's available format:
Of cuz, this is a lousier camera. If you have a better camera like the logitech one, you can see that the format available is so much more.
There are lots of methods, you can try some thing like
capture.set(CV_CAP_PROP_FRAME_WIDTH , 640);
capture.set(CV_CAP_PROP_FRAME_HEIGHT , 480);
capture.set (CV_CAP_PROP_FOURCC, CV_FOURCC('B', 'G', 'R', '3'));//diff from mine, using as example
then the webcam will be able to snap. This webcam is bit faulty, hence the image snapped is not that beautiful.
Hope this is your problem. but it may not be the case too. I like debugging problems, but I can't put down all the possible causes that this happen for you as I am really busy, as you asked for an example, this is one of them. Cheers. If you could tell me what you output window error says, I probably can help more.
EDIT(to answer more in your comments):
Ok, I want you to try a few things:
1)First, instead of using cvQueryFrame, or similar capturing methods, I want you to try use that webcam to capture a video instead. Wait up to maybe say 10 secs to see if it's successful. Reason being, some cameras(lower quality ones) take quite a while to warm up and the first few frames they capture may be an empty one.
2) If the step one doesn't work, try typing
cout << cv::getBuildInformation() << endl;
and paste the results for media I/O and Video I/O? I want to see the results. I would suspect your library dependencies too, but since you said it works with a logitech camera, I doubt that's the case. Of course, there's always a chance it's due to that the camera is not compatible to OpenCV. Does the camera have any brands by the way?
3) Alternatively, just search for usb drivers online and install it, I had a friend who did this for a similar problem, but not sure the process of that.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are the advantages and disadvantages of becoming a werewolf?
Before I decide whether or not I would like to become a werewolf, I'd like to know what I'll have to deal with. Whether this means being stronger, or having an appetite for human flesh, what are the advantages and disadvantages associated with becoming a werewolf?
I'm particularly interested in if there are any difference between the different races when they become werewolves. For instance, is there any difference between if an orc becomes a werewolf, to if a Khajiit becomes a werewolf?
A:
While in regular form, there isn't a whole lot of difference between werewolves and non-werewolves, but when you transform, you get a ton of benefits and drawbacks:
Benefits
Increased max health by 100 (non-regenerating)
Increased max stamina by 100
Faster sprint speed
Wolves no longer attack you
Committing crimes in beast form don't count against your normal form
Immunity to all diseases, including vampirism (also cures vampirism if you have it)
Special, werewolf-only abilities like howls
Drawbacks
No looting (when a werewolf)
No inventory or equipment access (when a werewolf)
No talking (when a werewolf)
People either run away from you, cower, or attack you (no friendly humanoid NPCs) (when a werewolf)
If someone sees you transform, it's automatically a crime
No rested bonus
If caught transforming in public it's 1,000 gold bounty to pay
A:
You can become a werewolf once per day for a couple of real-time minutes. It's excellent for serial killing of low-to-medium-level humanoids (like the Markarth prison), or for the fun of causing a major crime if caught transforming in sight.
When you have the beast blood, you cannot get diseases. The only disadvantages are that you can never get the "restful sleep" bonuses, and you are doubly vulnerable to silver weapon attacks. So I recommend that you get the beast blood through the Champions quest chain in Whiterun unless you're going straight through the main quest.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ASP.net Session Destroy if he closes the browser
I have an website. When the user is logged the session details will loaded.
When the user logged out the session details will abandoned. (Log out by clicking the logout menu)
when the user simply closes the browser then how to destroy the session.
In the next time its get logging with the same session data. I need to avoid this.
A:
As part of your handling of the logout, call Session.Clear() to clear the key/value pairs:
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.clear.aspx
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.