source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"stackoverflow",
"0026976485.txt"
] | Q:
Translate Excel formula into structured english
I have this formula, with the variables, m,s and e.
IFERROR(IF(m - IF(s*(1/ABS(e))>m;m;s*(1/ABS(e)))>m;m;m-IF(s*(1/ABS(e))>m;m;s*(1/ABS(e))))/100;0)
I want to translate it to structured english, this is what I have, but I doubt its correct:
IF e != 0
IF m > m
return m
ELSE IF s / |e| > m
return m
ELSE IF s / e > m
return m - s / e
ELSE
return s / e
ELSE
return 0
?? forgot this one upss.. s / e / 100;
A:
After analyzing the function, I think this simplified version has the same result:
=IFERROR(IF(MIN(m;s/ABS(e))<0;m;m-MIN(m;s/ABS(e)))/100;0)
And its logic can be explained like this:
if e = 0
0
else if m - (min between s/|e| and m) > m
m
else
m - (min between s/|e| and m)
Even still, I don't understand what that is for. :P
Edit: I added a simplified Javascript version of Sir Ben's code:
function whacko (m,s,e) {
if (e === 0)
return 0;
var value = m - Math.min(s / Math.abs(e), m);
if (value > m)
return m;
return value;
};
|
[
"stackoverflow",
"0005167367.txt"
] | Q:
How can I make git do the "did you mean" suggestion?
I type
git puhs
And git says:
kristian@office:~/myrepo$ git puhs
git: 'puhs' is not a git command. See 'git --help'
Did you mean this?
push
What is the config setting to make git just do the suggested command if it only has one suggestion ?
A:
According to git-config(1), you want to set help.autocorrect appropriately. For example, git config --global help.autocorrect 5 will make it wait half a second before running the command so you can see the message first.
A:
The autocorrect is nice, but my OCD-self needs a little more control over what's going on. So, I wrote a straightforward script that just chooses the first suggestion provided by git. You run the script after the failed command and use the built in bash history substitution "bang bang" syntax. Also, if you are typing something that could possibly have more than one command, this command lets you choose one other than the first option.
It would look something like this,
kristian@office:~/myrepo$ git puhs
git: 'puhs' is not a git command. See 'git --help'
Did you mean this?
push
kristian@office:~/myrepo$ idid !!
Counting objects: 18, done.
Delta compression using up to 32 threads.
Compressing objects: 100% (10/10), done.
Writing objects: 100% (10/10), 1.17 KiB, done.
Total 10 (delta 6), reused 0 (delta 0)
Plus, it's fun to type anything with two exclamation points. So bonus for that.
Here's a gist with my script
A:
As an alternative to help.autocorrect: if you make the same typos all the time, you can create aliases for them in your .gitconfig file
[alias]
puhs = push
(I do this with shell aliases too, where I can never seem to type mkae^H^H^H^Hmake correctly.)
|
[
"stackoverflow",
"0002903416.txt"
] | Q:
Windows shell string operations (changing backslash to slash)
I need to write a script that takes the current path (%~dp0), transforms backslashes into forward slashes and passes it further to some command.
Due to the environment I'm working in the only option that I have is windows shell (not Powershell where the issue would not a problem).
Is it even possible to do that?
A:
The set command has a substitution feature:
set a=C:\test\dir
set a=%a:\=/%
echo %a%
Results in:
C:/test/dir
|
[
"stackoverflow",
"0014861298.txt"
] | Q:
Can anyone convert this VB.NET code to VBScript?
Anybody out there that can help convert this small chunk of VB.NET to VBScript, I didn't realise when I was writing my tester app that the application I was going to use it in is all VBScript =(
The code gets a table from the database, then writes a couple of lines and then the table to a tab delimited file. I understand I may have to rewrite the part with Lambda completely? I may have to start again but if anyone can do this I would be appreciative!
Private dataTable As New DataTable()
Protected Sub Page_Load(sender As Object, e As EventArgs)
PullData()
End Sub
Public Sub PullData()
'Get data from DB into a DataTable
Using conn As New SqlConnection("Server=.\sqlexpress;Database=DB;User Id=User;Password=Password;")
Using cmd As New SqlCommand("SELECT areaID as 'Pond Number', storageDescription + SPACE(1) + areaID as 'Pond Name', " & vbCr & vbLf & "case when fishWeight = 0 then 0 else 1 end as 'Pondis Used', 1 as 'Volume', " & vbCr & vbLf & "FeedDensity AS 'Feed Density',round(cast(FeedDensity * revolution as float(25)),2)/*cast as float for correct rounding*/ AS 'Feed Multiplier'," & vbCr & vbLf & "feedType as 'Feed Type', feedName as 'Feed Name', batchID AS 'FishBatchCode'" & vbCr & vbLf & vbCr & vbLf & "FROM dbo.vwStorageMASTER" & vbCr & vbLf & vbCr & vbLf & "WHERE fkLocationID = 1 AND fkStorageIndicator <> 3 ORDER BY sequenceNumber ASC", conn)
conn.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dataTable)
End Using
End Using
'Output tab-delimited
Dim delim As String = vbTab
Dim sb = New StringBuilder()
sb.AppendLine("Trafalgar Master File" & vbCr & vbLf & vbCr & vbLf)
sb.AppendLine(String.Join(delim, "Number of Ponds: ", dataTable.Rows.Count.ToString() & vbCr & vbLf & vbCr & vbLf))
sb.AppendLine(String.Join(delim, dataTable.Columns.Cast(Of DataColumn)().[Select](Function(arg) arg.ColumnName)))
For Each dataRow As DataRow In dataTable.Rows
sb.AppendLine(String.Join(delim, dataRow.ItemArray.[Select](Function(arg) arg.ToString())))
Next
'Prompt user to download tab-delimited file
Dim FileName As String = "test.xls"
Dim response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
response.ClearContent()
response.Clear()
response.ContentType = "text/plain"
response.AddHeader("Content-Disposition", "attachment; filename=" & FileName & ";")
response.Write(sb.ToString())
response.Flush()
response.[End]()
End Sub
A:
This was how I rewrote it for my application. In the end I basically started again but it's result is pretty much the same;
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<%Response.Buffer = True%>
<!--#include file="Conn/conn.asp" -->
<%
Call DownloadFile()
Private Sub DownloadFile()
Dim Comm
Dim rst
Dim delim
delim = vbTab
response.Clear
set rst = Server.CreateObject("ADODB.Recordset")
rst.ActiveConnection = MM_Conn_STRING
rst.Open "Select COUNT(*) from vwTrafalgarMasterFile"
'Write titles
Response.Write("Trafalgar Master File" & vbcrlf & vbcrlf)
Response.Write("Number of Ponds: " & rst.Fields(0).Value & vbcrlf & vbcrlf)
If rst.State = 1 Then rst.Close 'Used 1 instead of AdStateOpen as this seemed to cause an error
rst.Open "Select * from vwTrafalgarMasterFile"
'Write headers
If Not rst.EOF Then
For Each fld In rst.Fields
Response.Write(fld.Name & delim)
Next
Response.Write vbcrlf
Else
Response.Write("There was a problem retrieving data or no data could be retrieved")
Response.End
Exit sub
End if
'Write rows
With rst
.MoveFirst
Do Until .EOF
For Each fld In rst.Fields
Response.Write(fld.Value & delim)
Next
Response.Write vbcrlf
.Movenext
Loop
End With
Dim FileName
FileName = "TrafalgarMasterFile.xls"
response.ContentType = "text/plain"
response.AddHeader "Content-Disposition", "attachment; filename=" + FileName + ";"
response.Flush
response.End
'Clean up
adoCMD.Close
Set Comm = Nothing
Set rst = Nothing
Set fld = Nothing
End Sub
%>
|
[
"stackoverflow",
"0015793873.txt"
] | Q:
Data Hiding and Objective-C synthesisers
How exactly should attributes be declared if they are needed to be private and the language supports automatic getter/setter method creation?
Is the only way to override the automatically created getter or setter as needed?
A:
In the top of the .m (implementation) file:
// Private category on your class, declared at top of implementation file.
@interface MyClass ()
@property (nonatomic, copy) NSString * privateString;
@end
@implementation
...
@end
These "private properties" are visible only within your implementation.
Please note that ObjC has no facility for runtime access restriction. Other objects can still call your private getters and setters if they want to (although this will generate compiler warnings).
|
[
"stackoverflow",
"0032094443.txt"
] | Q:
How to pass the values from one view controller to previous view controller)
How do I pass a value from one view controller to its previous prant view controller?
Consider this case: I have two view controller. The first screen has one lable and a button and the second view controller has one EditText and a back button.
If I click the first button then it has to move to second view controller and here user has to type something in the text box. If he presses the button from the second screen then the values from the text box should move to the first view controller and that should be displayed in the first view controller.
A:
in secondViewController create protocol - SecondViewController.h
#import <UIKit/UIKit.h>
@protocol MyDelegate
-(void)PassString : (NSString *)str;
@end
@interface SecondViewController : UIViewController
@property (nonatomic)id <MyDelegate> delegate;
-(IBAction)btnBack:(id)sender;
than after in SecondViewController.m file
-(IBAction)btnBack:(id)sender
{
[delegate PassString:txt.text];
[self.navigationController popViewControllerAnimated:YES];
}
than after in FirstViewController set protocol of SecondViewController
in ViewController.h file
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@interface ViewController : UIViewController<MyDelegate>
than after in ViewController.m file
-(void)PassString:(NSString *)str
{
lbl.text=str;
}
|
[
"stackoverflow",
"0036527499.txt"
] | Q:
by install the model of python i have error of exit status 2
I'm using 64-bit python 3.4.3 on my 64-bit win 10 computer.
when i am trying to install the model I met this problem at first.
enter image description here
so i type this code "SET VS100COMNTOOLS=%VS140COMNTOOLS%“(beause I use the Python3 and I've already installed the Visual Studio 2015)
it seems useful but the problem turns into a new one
enter image description here
A:
I think I can noly solve this problem by using Python 2.7. After I install the Python 2.7 and C++ Compiler for 2.7 I can finally install the module.
|
[
"stackoverflow",
"0055945385.txt"
] | Q:
Creating Dyantable with JSON from a remote url
I am trying to create a table using Dynatable to show data which is provided on a remote URL
I am testing out a class management solution called Jackrabbit, which provides an endpoint (here - which has my sample data) containing class lists in JSON.
I've looked at dynatable not creating table from remote JSON & Load remote JSON from Dynatable but I haven't been able to figure out a solution.
I've been working in this JS Fiddle
JS:
$(document).ready(function(){$.getJSON("https://app.jackrabbitclass.com/jr3.0/Openings/OpeningsJSON?orgID=537284", function(data) {
$("#classes").dynatable({
dataset: {
records: data
}
});
});})
The external JSON file contains many different fields, but I am only using some of them for the table. Is anyone able to point me in the right direction?
A:
Your script's dataset records data are not pass properly table structural way. Just replace your script with follows and don't forget to fill blank data array value with from data_value ( I added only name and instructions, please set others data ) -
$(document).ready(function(){$.getJSON("https://app.jackrabbitclass.com/jr3.0/Openings/OpeningsJSON?orgID=537284", function(data) {
var data_arr = [];
$.each(data.rows, function(key, data_value){
data_arr.push({
'name' : data_value.name,
'instructors' : data_value.instructors[0],
'meeting_days' : '',
'min_age' : '',
'openings' : '',
'start_time' : '',
'tuition' : '',
});
});
$("#classes").dynatable({
dataset: {
records: data_arr
}
});});});
|
[
"stackoverflow",
"0009053001.txt"
] | Q:
How I can get a focus message in MFC?
I have a dialog box with some CListCtrl. I want that when I click on one of them, receive killfocus or setfocus message.
How I can get it?
A:
The CListCtrl class wraps the Win32 ListView control. That control communicates with its parent (your dialog) via WM_NOTIFY messages.
So you can process WM_NOTIFY messages from your list control in your dialog class. Use the Properties window to create an OnChildNotify handler function and write a switch statement that handles the notification message(s) of interest.
The possible notification messages are listed here in the Windows SDK documentation.
|
[
"stackoverflow",
"0022243592.txt"
] | Q:
How to reboot CoreBluetooth manager instance at fixed interval in background
I'm developing a iOS application of using CoreBluetooth and i have one problem in application BackGround.
Generally, iOS application can't run long-term in Background. (e.g. pushing HomeButton. switching other application) But my application is set "Uses Bluetooth LE accessories" as BackGroundMode, so i can monitor region in Background. And i implemented startRangingBeaconsInRegion in didEnterRegion. When enter a region, Ranging region will be started and will be stopped after about 10 sec by iOS.
But i want to always use ranging in Background. Because my app use only one UUID for detecting over 20 beacons(20 means limit of startMonitoringForRegion), and i want to know how beacons there are in one region.
(About The reason of using only one UUID, please see this tips. iBeacon / Bluetooth Low Energy (BLE devices) - maximum number of beacons.)
So I'm thinking the way of rebooting CoreBluetooth manager instance at fixed interval in background. if i can do alternately didEnterRegion -> didRangeBeacons-> reboot -> didEnterRegion -> didRangeBeacons -> reboot -> ..., i can check how beacon there are in the region at fixed interval. Maybe i need background fetch... i'll try it later.
If you know about this way is available or not, please tell me that. Or if you have any suggestions, please tell me, i'll try it.
Updated 2014/03/07 17:45
BackGround fetch will fire at UNSTABLE interval. So This way isn't the solution...
A:
You do not need to set that requirement for background modes. You can try on applicationDidEnterBackground: call startBackgroundTask
- (void)startBackgroundTask {
if(bgTask != UIBackgroundTaskInvalid){
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"your time is over");
//you can call start once again to get more time
}];
}
Where the bgTask is UIBackgroundTaskIdentifier bgTask;
My only worry would be that from my observations to get another time for background execution user has to touch the screen to make screen illuminating (screen can be locked). To make sure your code is working in background you can set up a timer and log a message on the console periodically (for example time remaining which system gave you on the background execution [UIApplication sharedApplication].backgroundTimeRemaining or restarting bluetooth). As far as I know it is quite common approach to that kind of problems.
|
[
"stackoverflow",
"0063033157.txt"
] | Q:
Excel - Refer to column/range with Networkdays
=COUNTIFS(NETWORKDAYS(C:C, TODAY(), 1),">=" & 5)
I am trying to use something like the above to count any values in Column C (Date column of my dataset) where the working days from then to todays date is greater than 5. Can this be done without creating a working days column?
A:
It's actually not so obvious but NETWORKDAYS does not work with ranges. Arrays however are completely fine. See this post on SuperUser too.
So in your case you could simply use:
=SUMPRODUCT(--(NETWORKDAYS(C:C+0,TODAY())>=5))
Obviously it's better not to reference the whole of column C. Depending if one has Excel O365, you could also just use =SUM instead of =SUMPRODUCT.
|
[
"stackoverflow",
"0006969197.txt"
] | Q:
F# async stack overflow
I am surprised by a stack overflow in my async-based program. I suspect the main problem is with the following function, which is supposed to compose two async computations to execute in parallel and wait for both to finish:
let ( <|> ) (a: Async<unit>) (b: Async<unit>) =
async {
let! x = Async.StartChild a
let! y = Async.StartChild b
do! x
do! y
}
With this defined, I have the following mapReduce program that attempts to exploit parallelism in both the map and the reduce part. Informally, the idea is to spark N mappers and N-1 reducers using a shared channel, wait for them to finish, and read the result from the channel. I had my own Channel implementation, here replaced by a ConcurrentBag for shorter code (the problem affects both):
let mapReduce (map : 'T1 -> Async<'T2>)
(reduce : 'T2 -> 'T2 -> Async<'T2>)
(input : seq<'T1>) : Async<'T2> =
let bag = System.Collections.Concurrent.ConcurrentBag()
let rec read () =
async {
match bag.TryTake() with
| true, value -> return value
| _ -> do! Async.Sleep 100
return! read ()
}
let write x =
bag.Add x
async.Return ()
let reducer =
async {
let! x = read ()
let! y = read ()
let! r = reduce x y
return bag.Add r
}
let work =
input
|> Seq.map (fun x -> async.Bind(map x, write))
|> Seq.reduce (fun m1 m2 -> m1 <|> m2 <|> reducer)
async {
do! work
return! read ()
}
Now the following basic test starts to throw StackOverflowException on n=10000:
let test n =
let map x = async.Return x
let reduce x y = async.Return (x + y)
mapReduce map reduce [0..n]
|> Async.RunSynchronously
EDIT: An alternative implementation of the <|> combinator makes the test succeed on N=10000:
let ( <|> ) (a: Async<unit>) (b: Async<unit>) =
Async.FromContinuations(fun (ok, _, _) ->
let count = ref 0
let ok () =
lock count (fun () ->
match !count with
| 0 -> incr count
| _ -> ok ())
Async.Start <|
async {
do! a
return ok ()
}
Async.Start <|
async {
do! b
return ok ()
})
This is really surprising to me because this is what I assumed Async.StartChild is doing. Any thoughts on which solution would be optimal?
A:
I think that the stack overflow exception happens when starting the asynchronous workflow created using the <|> operator. The call to Async.StartChild starts the first workflow, which is combined using <|> and so it makes another call to Async.StartChild etc.
An easy way to fix it is to schedule the workflow in a handler of a timer (so that the it isn't added to the current stack). Something like:
let ( <|> ) (a: Async<unit>) (b: Async<unit>) =
async {
do! Async.Sleep 1
let! x = Async.StartChild a
let! y = Async.StartChild b
do! x
do! y }
A better way to fix it would be to create your own Seq.reduce - the current implementation folds it one-by-one so you'll get a tree of depth 10000, that contains just a single work item on the right, and all other work items on the left. If you created a ballanced binary tree of work items, then it shouldn't stackoverflow because the height will be only 15 or so.
EDIT Try replacing Seq.reduce with the following function:
module Seq =
let reduceBallanced f input =
let arr = input |> Array.ofSeq
let rec reduce s t =
if s + 1 >= t then arr.[s]
else
let m = (s + t) / 2
f (reduce s m) (reduce m t)
reduce 0 arr.Length
|
[
"stackoverflow",
"0049915343.txt"
] | Q:
Pass data to php in DropzoneJS
I am a fresher to use DropzoneJS. this is my form
<div class="col-md-12">
<form action="upload.php" enctype="multipart/form-data" class="dropzone" id="myDropzone" method="post"></form>
<select id="category" style="display: none;">
<option value="">Select Category</option>
<option value="cat1">Category 1</option>
<option value="cat2">Category 2</option>
<option value="cat3">Category 3</option>
</select>
<span id="caterr" style="color: red"></span>
<button id="submit-all" style="display: none;">Submit all files</button>
</div>
And here is my dropzone code
Dropzone.options.myDropzone = {
// Prevents Dropzone from uploading dropped files immediately
autoProcessQueue: false,
acceptedFiles: ".png,.jpg,.jpeg",
maxFilesize: 2,
parallelUploads: 20,
addRemoveLinks: true,
init: function() {
myDropzone = this;
$("#submit-all").click(function(){
myDropzone.processQueue();
})
}
};
And Here is php
if (!empty($_FILES))
{
$filename = $_FILES['file']['name'];
$tmpFile = $_FILES['file']['tmp_name'];
move_uploaded_file($tmpFile,$filename);
}
Now the reuirement is i wants to send an <selected> Category to PHP Page. So i can insert php category in database. but how can i send this selected category to php page.
A:
update your init by this codes
init: function() {
myDropzone = this;
$("#submit-all").click(function(){
myDropzone.processQueue();
});
myDropzone.on('sending', function(file, xhr, formData){
formData.append('category',$('#category').val());
});
}
|
[
"stackoverflow",
"0040059510.txt"
] | Q:
Method not calling of RestController of Spring mvc4
I wrote Code for restful api but method is not calling,
getting error "Context Root Not Found".
I am using liberty profile
Here is a my code
Controller
@RestController
public class demoAPIController {
@RequestMapping(value = "/restcall", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> GetParseResume() {
return new ResponseEntity("hello", HttpStatus.OK);
}
}
WebAppInitializer
public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.html");
dispatcher.addMapping("*.pdf");
dispatcher.addMapping("*.json");
}
private AnnotationConfigWebApplicationContext getContext()
{
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(WebConfig.class);
return context;
}
}
here WebConfig.java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.demo")
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver viewResolve = new InternalResourceViewResolver();
viewResolve.setPrefix("/WEB-INF/jsp/");
viewResolve.setSuffix(".jsp");
return viewResolve;
}
}
Error showing in Spring tool suite while start liberty server
[ERROR ] CWWKZ0002E: An exception occurred while starting the application demo1. The exception message was: java.lang.IllegalStateException: com.ibm.wsspi.adaptable.module.UnableToAdaptException: java.util.zip.ZipException: invalid LOC header (bad signature)
A:
It seems some backend side file was corrupted.
I did right click on pom.xml -> maven -> clean and install again.
Error resolved.
|
[
"stackoverflow",
"0042864003.txt"
] | Q:
UML class diagram - what do I put the output type for a function that can return different output types?
I have a function that returns a different output based on the converter function the user passes in. Basically the output of the function will be the same as the output of the converter function. I know it's not really a proper function since the output type isn't constant but python allows it and so I want to take advantage of it. How will label the output for my function when I don't know its type?
Thanks
A:
I've dealt with this as instructor a couple of times. First, I have the student explain why it's a good idea to return different types from a function. This usually solves the problem: that unit needs a cleaner design.
In two cases, the team did have a valid reason for the return variety. In that case, I had them use any practical, readable notation, such as
{ int | exception }
The formal UML notation we used didn't suggest that this was acceptable in "pure" UML, but there was also no authority to enforce the standards that was higher than me (the person assigning grades).
|
[
"stackoverflow",
"0008884482.txt"
] | Q:
Using named arguments in Javascript with regular expressions as names of arguments
Is it possible to use named arguments in Java or Javascript with regular expressions as the names of arguments? I want to make it possible to call a function like this:
f("function name:", "drawCircle", "radius:" 1, "xPos:" 0, "yPos:", 0, "color:", "red");
Or like this, with exactly the same effect:
f("name of function:", "draw a circle", "y position:", 0, "color:", "red", "rad:" 1, "x location:" 0);
Both of these should be equivalent to foo(1, 0, 0, red).
In both cases, the arguments that are given should match a list of regular expressions. It should be possible to list the arguments and the function name in any order with the same result.
Is there any way to implement something like this?
A:
f({
"name": "drawCircle",
"radius": 1,
"xPos": 0,
"yPos": 0,
"color": "red"
});
This is why you use objects in javascript.
Although you probably want
drawCircle({
radius: 0,
x: 0,
y: 0,
color: "red"
});
|
[
"stackoverflow",
"0009545566.txt"
] | Q:
Cant resolve nested Resource
I got following Source
<UserControl.Resources>
<DataTemplate x:Key="ItemTemplate">
<ListBox ItemsSource="{Binding Inventory}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
ItemTemplate="{StaticResource ItemChildTemplate}"
ItemContainerStyle="{StaticResource ListBoxChildItemStyle}"
BorderThickness="0">
</ListBox>
</DataTemplate>
<DataTemplate x:Key="ItemChildTemplate"> ... </DataTemplate>
<Style x:Key="ListBoxChildItemStyle" TargetType="{x:Type ListBoxItem}">...</Style>
</UserControl.Resources>
I get:
The resource ListBoxChildItemStyle could not be resolved.
The resource ItemChildTemplate could not be resolved.
I don't see the problem at all. Expression Blend also has no suggestions.
A:
Resources need to be declared before being referenced statically. Swap the order of your resources so that you never reference one that appears later in your file.
|
[
"math.stackexchange",
"0002122469.txt"
] | Q:
If $ \tan \left( x \right) +\tan \left( x+\frac{\pi}{3} \right) +\tan \left( x+\frac{2\pi}{3} \right) =3 $ prove that ..
If
$$
\tan \left( x \right) +\tan \left( x+\frac{\pi}{3} \right) +\tan \left( x+\frac{2\pi}{3} \right) =3
$$
prove that $$\frac{3\tan x-\tan^3x}{1-3\tan^2x}=1$$
hints will be appreciated
thanks.
A:
We try to simplify $\tan \left( x+\frac{\pi}{3} \right) +\tan \left( x+\frac{2\pi}{3} \right) $. We have
$$\begin{align}
&\tan \left( x+\frac{\pi}{3} \right) +\tan \left( x+\frac{2\pi}{3} \right) \\
=& \frac {\tan x +\sqrt {3}}{1-\sqrt {3}\tan x} + \frac {\tan x -\sqrt {3}}{1+\sqrt {3}\tan x}\\
=& \frac {\tan x +\sqrt {3} + \sqrt {3}\tan^2 x + 3\tan x +\tan x- \sqrt {3} -\sqrt {3}\tan^2 x +3\tan x}{1-3\tan^2 x} \\
=&\frac {8\tan x}{1-3\tan^2 x}\end{align}$$
Now add this to $\tan x $ and the result follows. Hope it helps.
|
[
"tex.stackexchange",
"0000399210.txt"
] | Q:
How to cite theorems within a series of equations?
I want to know if it's possible to cite theorems within series of equations, without interleaving text like "From Theorem 1.3, it follows that:". Here's an idea of the kind of formatting I'm looking for:
x = 1 (Theorem 1.1)
x^2 = 1 (Theorem 1.2)
x^2 - 1 = 0 (Theorem 1.3)
(x + 1)(x - 1) = 0 (Theorem 1.4)
x + 1 = 0 (Theorem 1.5)
1 + 1 = 0 (Theorem 1.6)
2 = 0 (Theorem 1.7)
I also want to be able to do this in a single long, chained equation. e.g. Intermixing it with the align* environment from amsmath:
expr1 = expr2 (Theorem 2.1)
= expr3 (Theorem 2.2)
= expr4 (Theorem 2.3)
= expr5 (Theorem 2.4)
= ...
Is it possible to achieve this?
A:
Here are 3 possible layouts for references. alignat gives you full control on the spacing between the equations and the reference, whereas flalign puts references at the right margin:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fourier}
\usepackage{mathtools}
\usepackage[standard, amsmath, thmmarks]{ntheorem}
\usepackage{cleveref}
\begin{document}
\begin{theorem}\label{th:P}
A powerful theorem.
\end{theorem}
\begin{theorem}\label{th:PP}
Another powerful theorem.
\end{theorem}
\begin{flalign}
& & a + b & = c + d + e& & \text{(by \cref{th:P})}\\
& & a' + b' + e'& = c'+ d' & & \text{(by \cref{th:PP})}
\end{flalign}
\begin{align}
a' + b' + e' & = c' + d' & & \text{(by \cref{th:PP})} \\
a + b & = c + d + e & & \text{(by \cref{th:P})}
\end{align}
\begin{alignat}{2}
a' + b' + e' & = c' + d' & \qquad & \text{(by \cref{th:PP})} \\
a + b & = c + d + e & & \text{(by \cref{th:P})}
\end{alignat}
\end{document}
|
[
"stackoverflow",
"0012452305.txt"
] | Q:
Scale image proportionally to fit current document dimensions
I have an image with some dimension alfa x beta pixels.
Then onDocumentReady and onWindowResize I calculate current document dimensions.
Task is to scale image proportionally until one of dimensions is reached.
A:
$(document).ready(function() {
scaleStart();
});
$(window).resize(function() {
scaleStart();
});
function scaleStart() {
$("#myImage").css("min-width", 0);
$("#myImage").css("min-height", 0);
var originalWidth = 1762;
var originalHeight = 1041;
var safeWidth = $(document).width() - 100;
var safeHeight = $(document).height() - 100;
var scaleWidth = originalWidth / safeWidth;
var scaleHeight = originalHeight / safeHeight;
if (scaleWidth > scaleHeight)
{
$("#myImage").css("min-width", originalWidth / scaleWidth);
$("#myImage").css("min-height", originalHeight / scaleWidth);
}
else
{
$("#myImage").css("min-width", originalWidth / scaleHeight);
$("#myImage").css("min-height", originalHeight / scaleHeight);
}
}
|
[
"stackoverflow",
"0010082189.txt"
] | Q:
Android: How do you send data to a website securely
I was just wondering how you could send data to a website securely so then the website can display the information upon log in of the user (of the website). I am not that familiar with MySQL or anything like those. The data is only text but it would be great if anyone can include examples of the code.
Cheers
Nick
A:
It is common for people to create a RESTful API to allow your client to access the data. This API should be over HTTPS. It is important that you do not trust the device. You should assume that this is like any other web application backend and that an attacker can access it directly.
|
[
"stackoverflow",
"0025642052.txt"
] | Q:
Android - programmatically change the state of a switch without triggering OnCheckChanged listener
I'm looking for a method of programmatically changing the state of an Android Switch widget using switch.setChecked(true); without triggering OnCheckedChangedlistener. My first thought was to swap it out for an OnClickListener but as this only registers clicks and you are able to not only click but also slide a Switch then it's not really fit for purpose as if the user was to slide the Switch from off to on then the Switch would actually do nothing as the user is not clicking...If anyone's got a solution or a smart work around for this, that would be awesome
A:
Set the listener to null before calling setCheck() function, and enable it after that, such as the following:
switch.setOnCheckedChangeListener (null);
switch.setChecked(true);
switch.setOnCheckedChangeListener (this);
Reference: Change Checkbox value without triggering onCheckChanged
A:
Well, just before doing things in code with the switch you could just unregister the Listener, then do whatever you need to, and again register the listener.
A:
Every CompoundButton (two states button - on/off) has a pressed state which is true only when a user is pressing the view.
Just add a check in your listener before starting the actual logic:
if(compoundButton.isPressed()) {
// continue with your listener
}
That way, changing the checked value programmatically won't trigger the unwanted code.
From @krisDrOid answer.
|
[
"stackoverflow",
"0024831954.txt"
] | Q:
input data and run a php script from jquery event
I am having a problem getting data from jquery into a php script. I am trying to load a php script (i.e. send an email) with a variable (email address) from jquery event without leaving the original page and going to a confirmation page. Please help!
Here is my jquery code:
<script>
$("#test").click(function() {
var id = 1;
$("#target").load("javascript_test2.php", id);
});
</script>
<div id="target">hmmm did it work?</div>
</body>
This is the php I would like to receive and process the code:
<div id="S1">
<?php
$id = htmlspecialchars($_POST['id']);
for ($i=1; $i<=2; $i++) {
echo $id . 'Hello world ' . $i . '<br>';
}
require_once('lawyeralertemail.php');
?>
</div>
Thanks!
A:
You can use jQuery ajax to post data into your PHP.
Here is a link:
http://api.jquery.com/jquery.post/
This will allow you to post data without reloading the page and give your user a better experience.
You can then use $_POST to capture the data inside your PHP.
|
[
"stackoverflow",
"0039485575.txt"
] | Q:
How do i wrap a string following a search result?
I've got a javascript file with over 1000 object properties that I want to replace with a function.
Example:
myObject.ARANDOMPROPERTY
myObject.THISISAPROPERTY
...
myObject.ANOTHERPROPERTY
I want to replace these with functions that wrap the property in a string value. i.e.:
myFunction('ARANDOMPROPERTY')
myFunction('THISISAPROPERTY')
...
myFunction('ANOTHERPROPERTY')
The property is always alphabetical and always in all caps. The string can be followed by multiple characters, sometimes a +, sometimes a , sometimes a linebreak, but never by an alphabetic character.
I'm currently using SublimeText3 which supports regular expressions, but I'm open to suggestions with other resources.
How do would I go about doing this?
A:
You may use a \bmyObject\.([A-Z]+) pattern and replace with myFunction('$1').
Details:
\b - word boundary (we only match the next word as a whole word)
myObject - the myObject word
\. - a dot
([A-Z]+) - Group 1 capturing one or more uppercase letters.
In the replacement, $1 references the value inside Group 1.
V
|
[
"stackoverflow",
"0004604223.txt"
] | Q:
How to detect file or folder changes in Android?
Is it possible to detect folder changes in Android? I mean detect when files are deleted or changed and know wich application are doing these? In Windows you have system events for this, it's not necesary to permanently watch the files to detect changes. It's very important to know which application is doing the changes.
A:
Is possible to detect folder changes in android?
You can use FileObserver to find out when files are modified.
Is very important to know wich application is doing the changes.
That information is not available.
|
[
"stackoverflow",
"0001784647.txt"
] | Q:
StringBuilder string format
scriptValues.AppendFormat("something = {1};", SessionID.ToString());
in the above, I get a R# warning or something that says I need to add a 3rd param. When I look with intellisense it shows string formatter. Do I need one here?
A:
It should be scriptValues.AppendFormat(@"something = {0}";", SessionID.ToString());
|
[
"gis.stackexchange",
"0000097995.txt"
] | Q:
generate massive shapefiles
I have a shapefile with 1475 records, and I want to generate a shapefile for each record.
What can I do to generate them avoiding selecting and exporting each record to do that?
A:
Let's assume you have access to Excel and this is a one-off and you don't want to (or are unwilling to) write a program.
Open the .dbf file in excel - yes, it's an Excel type just don't save it. What you want is just the FID field, but that's not there is it! You will notice that the records are arranged sequentially and consecutively (1-n with no breaks). Start a new worksheet and close the dbf, insert a series for the number of records (1-1475).
Insert a column before the series in the worksheet and copy this into it:
ogr2ogr -where FID=
Which is the OGR2OGR command. In this example I'm using a query filter which can adapt to any unique attribute or group of features. The other option is -fid .
in the column after the FID put your output shapefile and use your imagination for the output shape file, in this example I have used ="d:\OutPath\Out" & B1 & ".shp". The input shape file goes last.
fill the table by selecting the cells A, C & D for all the rows and use Ctrl + D to fill down. The fomula will change each output file:
Now save as CSV, ignore the warnings, open with Notepad and you will get:
ogr2ogr -where FID=,1,d:\OutPath\Out1.shp,d:\some_path\InShape.shp
ogr2ogr -where FID=,2,d:\OutPath\Out2.shp,d:\some_path\InShape.shp
ogr2ogr -where FID=,3,d:\OutPath\Out3.shp,d:\some_path\InShape.shp
ogr2ogr -where FID=,4,d:\OutPath\Out4.shp,d:\some_path\InShape.shp
ogr2ogr -where FID=,5,d:\OutPath\Out5.shp,d:\some_path\InShape.shp
ogr2ogr -where FID=,6,d:\OutPath\Out6.shp,d:\some_path\InShape.shp
ogr2ogr -where FID=,7,d:\OutPath\Out7.shp,d:\some_path\InShape.shp
ogr2ogr -where FID=,8,d:\OutPath\Out8.shp,d:\some_path\InShape.shp
ogr2ogr -where FID=,9,d:\OutPath\Out9.shp,d:\some_path\InShape.shp
Do a find & replace FID=, with FID=, then , with space and you will get this:
ogr2ogr -where FID=1 d:\OutPath\Out1.shp d:\some_path\InShape.shp
ogr2ogr -where FID=2 d:\OutPath\Out2.shp d:\some_path\InShape.shp
ogr2ogr -where FID=3 d:\OutPath\Out3.shp d:\some_path\InShape.shp
ogr2ogr -where FID=4 d:\OutPath\Out4.shp d:\some_path\InShape.shp
ogr2ogr -where FID=5 d:\OutPath\Out5.shp d:\some_path\InShape.shp
ogr2ogr -where FID=6 d:\OutPath\Out6.shp d:\some_path\InShape.shp
ogr2ogr -where FID=7 d:\OutPath\Out7.shp d:\some_path\InShape.shp
ogr2ogr -where FID=8 d:\OutPath\Out8.shp d:\some_path\InShape.shp
ogr2ogr -where FID=9 d:\OutPath\Out9.shp d:\some_path\InShape.shp
Which is batch commands! Save the file with the extension .bat and then double click to run.
The other way of exporting using -FID looks like this:
ogr2ogr -FID 1 d:\OutPath\Out1.shp d:\some_path\InShape.shp
ogr2ogr -FID 2 d:\OutPath\Out2.shp d:\some_path\InShape.shp
ogr2ogr -FID 3 d:\OutPath\Out3.shp d:\some_path\InShape.shp
ogr2ogr -FID 4 d:\OutPath\Out4.shp d:\some_path\InShape.shp
ogr2ogr -FID 5 d:\OutPath\Out5.shp d:\some_path\InShape.shp
ogr2ogr -FID 6 d:\OutPath\Out6.shp d:\some_path\InShape.shp
ogr2ogr -FID 7 d:\OutPath\Out7.shp d:\some_path\InShape.shp
ogr2ogr -FID 8 d:\OutPath\Out8.shp d:\some_path\InShape.shp
ogr2ogr -FID 9 d:\OutPath\Out9.shp d:\some_path\InShape.shp
traps Paths with spaces must be enclosed in "", so D:\project data\FromShape.shp becomes "d:\project data\FromShape.shp".
OGR2OGR comes with QGIS but you might need to do some changes to get it to work. If the computer can't find the program insert the line set path=C:\Program Files\QGIS Dufour\bin;%path% in the top of the batch file... obviously substitute your own path to QGIS\bin folder, this one is for Dufour.
|
[
"serverfault",
"0000852344.txt"
] | Q:
How to keep log of a whole day, for complete AWS s3 bucket, in single file?
I have s3 buckets say xfile, and say xlog.
xfile to keep the files, and xlog to keep files.
I have one folder as xlog/data, and i have also enabled logging for xfile with prefix data
I have done no extra configuration, everything going on defaults.
So after some time i see logs like this in data folder of xlog
It seems like that for every request a separate log file is created.
Is that the expected behaviour?
What i am expecting to have one file for 0000 hrs to 2359 hrs, that contains the complete logs of one single day. For another day, separate file should be created.
What am i missing? or how should i configure this?
A:
S3 is a distributed system, and this is at least one factor in the large numbers of log files it generates.
Objects in S3 are immutable -- it isn't possible to directly append data to an S3 object, and doing so requires an emulation operation: the bytes of the object must be copied into a new object, followed by the additional data. This would make logging into a single "growing" daily log file nearly impossible to do at any scale. The log files are standard S3 objects, so this is likely another reason why the individual files are written as they are.
It isn't one file per request, although it can certainly seem like that on a bucket with low traffic. Essentially, each log file contains records created prior to its timestamp, but not necessarily records since the last log was written -- a log file can occasionally contain records from hours, days, or weeks ago that have been stranded somewhere inside S3 and have finally been released. This is rare, but a documented possibility.
Logs for troubleshooting are often needed quickly after the events occur, so it often desirable to receive them as soon as practical, and that is what S3 tends to do.
This is not configurable.
http://docs.aws.amazon.com/AmazonS3/latest/dev/ServerLogs.html
My solution for easy access to logs is an S3 event notification on my log-collecting buckets, which sends a message into an SQS queue. The queue consumer runs on an EC2 instance with an EBS Cold Storage (sc1) volume. When each log file is written to the bucket, the queue consumer fetches the file, and derives the date from the filename. It then parses the log events to determine their HTTP status class, e.g. 2XX, 3XX, 4XX, 5XX, or other/unmatched, and appends each record to a master daily file. The records with 4xx, 5xx, or unmatched/unexpected are appended to smaller daily files with errors only. Searching these local files with a tool like grep then becomes a trivial task.
|
[
"stackoverflow",
"0046235478.txt"
] | Q:
Mysql php insert multiple rows
I have a code that works that inserts records in a MySQL database
if (isset($_POST['horaseguinte'])){
$horaseguinte = $_POST['horaseguinte'];
$sql="INSERT INTO reservas (cod, data, hora, user, reservas, pc, colunas, outros, sala) VALUES (NULL, '$mydate', '$hora1', '$userid', '$proj', '$pc', '$col', '$outros', '$sala'),(NULL, '$mydate', '$horaseguinte', '$userid', '$proj', '$pc', '$col', '$outros', '$sala')";
}else{
$horaseguinte="";
$sql="INSERT INTO reservas (cod, data, hora, user, reservas, pc, colunas, outros, sala) VALUES (NULL, '$mydate', '$hora1', '$userid', '$proj', '$pc', '$col', '$outros', '$sala')";
}
if (!mysqli_query($con,$sql))
{
$erro = true;
$erromessage = "Error: " . mysqli_error($con);
}
$id = mysqli_insert_id($con);
mysqli_close($con);
}
However now, the $mydate variable can have several values that come in an array. For example: Array ( [0] => 2017-09-20 [1] => 2017-09-27 [2] => 2017-10-04 [3] => 2017-10-11 )
So considering that the array is stored in $a, I changed the code to this:
if (isset($_POST['horaseguinte'])){
$horaseguinte = $_POST['horaseguinte'];
for($i = 0; $i < count($a); $i++) {
$sql.="INSERT INTO reservas (cod, data, hora, user, reservas, pc, colunas, outros, sala) VALUES (NULL, '$a[$i]', '$hora1', '$userid', '$proj', '$pc', '$col', '$outros', '$sala'),(NULL, '$a[$i]', '$horaseguinte', '$userid', '$proj', '$pc', '$col', '$outros', '$sala')";
}
}else{
$horaseguinte="";
for($i = 0; $i < count($a); $i++) {
$sql. = "INSERT INTO reservas (cod, data, hora, user, reservas, pc, colunas, outros, sala) VALUES (NULL, '$a[$i]', '$hora1', '$userid', '$proj', '$pc', '$col', '$outros', '$sala')";
}
}
if (!mysqli_multi_query($con,$sql))
{
$erro = true;
$erromessage = "Error: " . mysqli_error($con);
}
$id = mysqli_insert_id($con);
mysqli_close($con);
}
But if returns the following error:
Catchable fatal error: Object of class mysqli_result could not be
converted to string in
/home/louros/public_html/material/add_reserva_savemef.php on line 115
If someone can help I would appreciate!
A:
You have to end your queries by a semicolon. From the description of the mysqli_multi_query function:
Executes one or multiple queries which are concatenated by a semicolon.
So for example, your 4th line would become:
$sql.="INSERT INTO reservas (cod, data, hora, user, reservas, pc, colunas, outros, sala) VALUES (NULL, '$a[$i]', '$hora1', '$userid', '$proj', '$pc', '$col', '$outros', '$sala'),(NULL, '$a[$i]', '$horaseguinte', '$userid', '$proj', '$pc', '$col', '$outros', '$sala');";
Moreover, as Barmar pointed out, consider using a single call of mysqli_query for every query. This way you can verify the success of each of them.
Not strictly related but relevant: don't directly insert $_POST values into your queries. Ever. This is the simplest example of an SQL injection vulnerability. There are several ways to handle this, but real_escape_string is a good way to start.
|
[
"stackoverflow",
"0061977591.txt"
] | Q:
Azure Service Bus Queues: How To Read Individual Messages From A Queue
I have an application where I am able to write a message to an Azure Service Bus Queue in a JSON format in one part of my process. I have a downstream process that I'd like to then pop that message off the queue, translate the json to an object and then process that object.
I have no problem pushing messages onto the queue but I have not been able to find any examples of popping a message off of the queue one at a time or in a loop. EVERY example that I've seen from Microsoft or on Github is a console application (useless in a web application) that sets up some kind of listener that grabs all the messages in a queue and writes a console message. There are no examples I've found where the message is popped and then some processing is done with the data. Does anyone have examples on how to pop a message off of the queue and then process it or call another method to do something with the data in the message?
Update:
I used the WindowsAzure.ServiceBus example below supplied by Guru Pasupathy and ended using the following snippet from Azure Service Bus Queues: How To Read Individual Messages From A Queue to get the text of the message from the BrokeredMessage object:
Stream stream = message.GetBody<Stream>();
StreamReader reader = new StreamReader(stream);
string messageBody = reader.ReadToEnd();
I could then take messageBody and deserialize the embedded JSON into a POCO object and I was on my way! Now I can use queues more effectively in my application for a variety of tasks.
A:
You can use the Peek Lock receive mode to get message from queue, process it and then you have choice to either Abandon it or Complete it based on your business logic.
If you are using WindowsAzure.ServiceBus nuget package to send / receive the messages the below method can be used to consume the message from queue one by one based on a loop or single call without having to use a listener.
public void Receive()
{
QueueClient myQueueClient = QueueClient.CreateFromConnectionString("<connectionString>;<queueName>", ReceiveMode.PeekLock);
int someCount = 2; //some random value for testing
try
{
for (int i = 0; i < someCount; i++)
{
BrokeredMessage message = myQueueClient.Receive();
Console.WriteLine("The message is " + message);
message.Complete();
}
}
catch(Exception e)
{
//Handle your expection
}
}
If you are using Microsoft.Azure.Service nuget package then I could not find a direct way to read only a single message without using a listener. I see that the listener will keep polling and processing the queue till there are no more message.
If your ask is to stop the polling and continue fetching all the available messages, then as a workaround you may close the QueueClient instance after reading one single message and open qc and register handler when your process is ready to take the next one.
public async Task ProcessMessagesAsync(Message message, CancellationToken token)
{
Console.WriteLine($"Received message: {Encoding.UTF8.GetString(message.Body)}");
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(message.Body))
{
Payload payload = (Payload) bf.Deserialize(ms);
//Based on your needs you may have a condition here based on which you could Abandon or Complete the mesage
await qc.CompleteAsync(message.SystemProperties.LockToken);
Console.WriteLine("Completed the message --> " + payload.Message + " -- Id --> " + payload.Id);
//await qc.AbandonAsync(message.SystemProperties.LockToken);
//Console.WriteLine("Abandon the message --> " + payload.Message + " -- Id --> " + payload.Id);
qc.CloseAsync(); //If you close the QueueClient instance here, no more messages will be picked up from queue.
}
}
The above example is based on https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues#receive-messages-from-the-queue , I just added the qc.CloseAsync() call at the end. Without this line, the listener will continue processing till there are no more message left in the queue. I am not sure if there are better ways to achieve this, but thought of sharing.
Hope this helps
EDIT -
When sending the message, if you are using a custom type you can use the below
BrokeredMessage message = new BrokeredMessage(new Payload() { Id = 4332, Message = "WindowsAzure package" });
myQueueClient.Send(message);
and while receiving you should use the GetBody as shown below
BrokeredMessage message = myQueueClient.Receive();
var incoming = message.GetBody<Payload>();
Console.WriteLine("The message is " + incoming.Id + " and " + incoming.Message);
message.Complete();
Below is the custom object for your reference
[Serializable]
public class Payload
{
public int Id { get; set; }
public string Message { get; set; }
}
Same applies to string also
While receiving you can use
var incoming = message.GetBody<string>();
While sending you can send as
BrokeredMessage message = new BrokeredMessage("WindowsAzure package" );
You get more details on different content formatting on the below link
https://abhishekrlal.com/2012/03/30/formatting-the-content-for-service-bus-messages/
|
[
"math.stackexchange",
"0000538088.txt"
] | Q:
Isomorphism of Tensor Product over a Group Ring.
Let $\mathbb{Q}$ be the rationals and $\mathbb{Z}$ integers. Let further $p$ be prime and $t\in \mathbb{Z}$ such that $p \mid t$. Then $\mathbb{Z}_{(p)}$ is the local ring. Let $G < H$ be groups, then $\mathbb{Z}_{(p)}[G] < \mathbb{Q}[H]$ are grouprings.
Now I am looking for an isomorphic $\mathbb{Z}_{(p)}[G]$-module to the following tensor product
\begin{align}
\mathbb Q[H] \otimes_{\mathbb{Z}_{(p)}[G]} \mathbb{Z}/t\mathbb{Z}
\end{align}
knowing that $t$ ist invertible in $\mathbb{Q}$.
A:
Take $q \in {\mathbb Q}[H]$ and $a \in {\mathbb Z}_{(p)}$. Then
$q \otimes a = (t \frac{1}{t} q) \otimes a = (\frac{1}{t} q) \otimes ta = \frac{1}{t} q \otimes 0 = 0.$ Therefore ${\mathbb Q}[H] \otimes_{{\mathbb Z}_{(p)}[G]} \mathbb Z/t\mathbb Z = 0$.
Note neither the groups $G$ and $H$, nor the localization at $(p)$ play a role in this argument.
|
[
"stackoverflow",
"0008588498.txt"
] | Q:
How can I get xslt to indent xml (from Ant)?
From what I understand having looked around for an answer to this the following should work:
<xslt basedir="..." destdir="..." style="xslt-stylesheet.xsd" extension=".xml"/>
Where xslt-stylesheet.xsd contains the following:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
Unfortunately while most formatting is applied (spaces are stripped, newlines entered, etc.), indentation is not and every element is along the left side in the file. Is this an issue with the xslt processor Ant uses, or am I doing something wrong? (Using Ant 1.8.2).
A:
It might help to set some processor-specific output options, though you should note that these may vary depending on the XSLT processor that you're using.
For example, if you're using Xalan, it defines an indent-amount property, which seems to default to 0.
To override this property at runtime, you can declare xalan namespace in your stylesheet and override using the processor-specific attribute indent-amount in your output element as follows:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xalan="http://xml.apache.org/xalan">
<xsl:output method="xml"
encoding="UTF-8"
indent="yes"
xalan:indent-amount="2"/>
This example is from the Xalan usage patterns documentation at http://xml.apache.org/xalan-j/usagepatterns.html
If you do happen to be using Xalan, the documentation also says you can change all of the output preferences globally by setting changing the file org/apache/serializer/output_xml.properties in the serializer jar.
In the interest of completeness, the complete set of Xalan-specific xml output properties defined in that file (Xalan 2.7.1) are:
{http://xml.apache.org/xalan}indent-amount=0
{http://xml.apache.org/xalan}content-handler=org.apache.xml.serializer.ToXMLStream
{http://xml.apache.org/xalan}entities=org/apache/xml/serializer/XMLEntities
If you're not using Xalan, you might have some luck looking for some processor-specific output properties in the documentation for your XSLT processor
|
[
"math.meta.stackexchange",
"0000013389.txt"
] | Q:
Can not log in my account using google chrome
Whenever I am trying to log in my stack exchange account through google chrome, it says the following:
The problem was not there few days ago. But I can open my account using Mozilla Firefox. Why is that happening ? How can I fix this problem? Can someone help? I want to use google chrome as it works much faster (in my case).
After Pressing Ctrl-Shift-J to open the JavaScript console, It shows the following:
UPDATE: I reinstalled google chrome and the problem still remains. Now after Pressing Ctrl-Shift-J to open the JavaScript console, It shows the following:
A:
Apparently, you have installed Website Logon Chrome extension. As far as I know, it is a legitimate extension, but it appears to either have a temporary malfunction, or to be incompatible with Stack Exchange logging in process. Suggestion: either disable the extension for this one site (if possible), or remove it altogether.
Update, taken from comments: So, the problem is that your Chrome is so incredibly old that it can't properly interact with Google's site anymore. The current version of Chrome is 34. It's not surprising that the problem appeared suddenly; Google could have tweaked things on their end without bothering to maintain compatibility with Chrome 16. Solution: either upgrade Chrome or use another browser. Using very old browsers is not a good idea anyway.
|
[
"stackoverflow",
"0040265798.txt"
] | Q:
Pointer to member type incompatible with object type when calling a pointer to a member of a derived class
I have defined a class template such as this one:
template <const category_id_t category, class Base>
class Node : public Base
{
...
template <typename Derived, class T>
void on_message( const frame_t& frame, void (Derived::*call)(const T*) )
{
if ( frame.length == sizeof(T) )
(this->*(call))((T*)frame.data);
}
}
The argument category serves as a token to implement several similar classes and provide proper specialization according to specific categories. The above class is then derived like this:
template <class Base>
class Sys : public Node<CID_SYS, Base>
{
Sys() : Node<CID_SYS, Base>() { /* ... */ }
....
};
Class Sys is only a class that provides an base interface to objects of category CID_SYS (enum, value = 5) and serves as a base class to the actual implementation of the interface:
class SysImpl : public Sys<CAN>
{
...
/* Parse remote notifications */
void on_notify( const state_info_t* ) { /* ... */ }
};
SysImpl sys;
Finally I have a function that calls the base class Node<CID_SYS, Base> member function on_message() like this:
void foo(const frame_t& frame)
{ sys.on_message(frame, &SysImpl::on_notify ); }
The compiler throws an error around the line (this->*(call))((T*)frame.data) saying
error: pointer to member type 'void (SysImpl::)(const state_info_t*)' is incompatible with object type 'Node<(category_id_t)5u, CAN>'
The compiler has successfully guessed what template function to call, it's just that it doesn't seem to "recognize" that this is from a derived class.
What I'd like is to call any member function of a class derived from Node<CID_SYS, CAN>, not only stand-alone functions (which works perfectly well so far, not shown in the excerpt above).
What am I missing?
A:
In the on_message function the variable this is not a pointer to SysImpl, it's type is Node<CID_SYS, CAN>*. The Node template class have no member on_notify so you can't call it on an instance of Node. It must be called on an instance of Derived (which should be SysImpl).
That's why you get the error and need to cast this to Derived*:
(static_cast<Derived*>(this)->*(call))(...);
Of course, this only works if Derived actually is derived from the Node class.
|
[
"stackoverflow",
"0041617562.txt"
] | Q:
LocalContainerEntityManagerFactoryBean cannot be converted to EntityManagerFactory
I don't understand, what is happening at all!
Suddenly, simple things stopped to work!
Now ehen I am trying to define something like here http://docs.spring.io/spring-data/jpa/docs/1.10.6.RELEASE/reference/html/#jpa.java-config
I get the following compile error
incompatible types: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean cannot be converted to javax.persistence.EntityManagerFactory
And this is correct, since LocalContainerEntityManagerFactoryBean does not implement EntityManagerFactory, which is required by JpaTransactionManager#setEntityManagerFactory() method.
How it cn be, that official example contains absolutely incorrect snippet? How it can be, that this snippet was compiling for me for some time?
What I broke?
UPDATE
I was able to rewrite
txManager.setEntityManagerFactory(entityManagerFactory());
to
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
So it is an error in the doc?
A:
Yes, the documentation is wrong
Use this code to inject entity manager factory into txManager
@Bean @Autowired public PlatformTransactionManager transactionManager(EntityManagerFactory factory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(factory);
return txManager;
}
|
[
"stackoverflow",
"0023177579.txt"
] | Q:
How to enable logging done by netty code?
I have written an HTTP server using netty framework. I have done logging for the HTTP server ().
I also want to enable the logging done inside the netty code.What steps do I need to follow to print the log statements of the netty code?
A:
Just configure the InternalLoggerFactory of needed and set the right delegation. By default it will first try to use slf4j, log4j and then JUL.
|
[
"stackoverflow",
"0012432209.txt"
] | Q:
command AutoCloseWindow not valid in Section
Section userSoftware
MessageBox MB_YESNO|MB_ICONQUESTION "Insert user software DVD in to drive and click Yes to install User Software or click No to Proceed" /SD IDNO IDYES yes IDNO no
yes:
AutoCloseWindow true
SetRebootFlag false
Call installUserSoftware
no:
;do nothing
SectionEnd
Section: "userSoftware"
Error: command AutoCloseWindow not valid in Section
This is the error I am getting with AutoCloseWindow. All I am trying to do is after installing the server software if user selects to install Client software, installation of server software should disappear without asking user to hit finish button.
Code I gave I am just testing how AutoCloseWindow or SetAutoClose works, nut all I have is an error!!
A:
AutoCloseWindow is a property like Name and Installdir and must be placed outside functions and sections. If you want to set the autoclose flag at runtime you must use the SetAutoClose command...
|
[
"stackoverflow",
"0007925015.txt"
] | Q:
Build a JAR file that can only be executed?
My project isn't complete, but I'd like to distribute some demo versions.
Is there a way to make a executable JAR file that won't give users access to its classes (e.g. when imported into Eclipse)?
A:
No, a jar file is a zip file and there's no way to stop your users from looking inside it - because the JVM needs to look inside it to run it.
You can however:
Try converting it into a native executable (there are a few tools to do that)
Run an obfuscator over it (there's even more tools for that)
My experience with obfuscators are that they don't do a good enough job to acutally stop someone who's really keen. I've tried running decompilers over a variety of obfuscated classes and they're still easy enough to understand.
If you're interested in the native exe path, then this article might help.
Generally speaking, I don't think it's worth pursuing. If what you're distributing it valuable enough to the people you're giving it to, then they'll find a way to dig inside if they want to. Or if they're trustworthy then they won't. But technological solutions probably won't change that.
|
[
"stackoverflow",
"0056959669.txt"
] | Q:
Tracking if phrase exists within a list of terms
I am having difficulty finding a formula to do exactly what I am looking for.
I have two lists, one containing search phrases like ("Sound bars for tv") and another list that contains individual terms like ("TV", "Sound", "bars").
My goal is to see if any of the search phrases match for each keyword within the individual term list.
So for "Sound bars for TV", I would need each of those words to be in the term list for it to come back as a TRUE. Also, and more complicated, if I have the search phrase "Soundbar" and "Sound Bar" these should both pass if both terms are in the list.
Any idea what is the best way to approach this.
I have tried the following unsuccessfully:
Individual terms = the list of terms like "TV", "Sound", "Bars"
Phrase = search phrases like "Sound bars for TV"
The goal would be to create a formula that says "Yes" every word in "Sound bars for TV" is within the Individual terms list.
=SUMPRODUCT(--ISNUMBER(SEARCH(individual terms,phrase)))=COUNTA(individual terms)
=IF(ISNUMBER(SEARCH(phrase,individual terms)), "Yes", "No")
=SUMPRODUCT(--ISNUMBER(SEARCH(individual terms,phrase)))>0
A:
Let's pretend you have a data setup like this:
Column D was made into an Excel table (with Insert -> Table) and named tblTerms. This lets you add and remove terms from the list dynamically.
Now in cell B2 and copied down is this formula:
=SUMPRODUCT(--(COUNTIF(tblTerms[Search Terms],TRIM(MID(SUBSTITUTE(A2," ",REPT(" ",LEN(A2))),LEN(A2)*(ROW(A$1:INDEX(A:A,LEN(A2)-LEN(SUBSTITUTE(A2," ",""))+1))-1)+1,LEN(A2))))=0))=0
Note that you'll have to add "Soundbars" separately to the search terms list. There's not really any way for Excel to recognize individual words in a compound word, and attempting to do that would be extremely unwieldy, even with VBA.
|
[
"math.stackexchange",
"0001577679.txt"
] | Q:
How to find the probability of getting queens using combination or premutations?
Two cards are drawn at random from a standard deck of 52 cards, without replacement. What is the probability that both cards are drawn are queens?
Its a permutation cause the order matter, I mean its a pack of cards and cards have order so its going to be different if you choose anything else right? I'm just guessing not sure.
So the $$ P(Queens) = ? / 52P2 $$
Whats going to be the numerator? I mean i said the denominator was 52P2 because its the total number of outcomes and you pick 2 out of it?
A:
If you want to use "combinations," note that there are $\binom{52}{2}$ ways to draw a two-card hand. All these hands are equally likely.
Now we count the "favourables," the number of two-queen hands. There are $\binom{4}{2}$ such hands. It follows that the probability of a two queen hand is $\dfrac{\binom{4}{2}}{\binom{52}{2}}$.
Alternately, imagine drawing the cards one at a time. Record the result as an ordered pair $(a,b)$, where $a$ is the first card drawn, and $b$ is the second card drawn. Then there are $(52)(51)$ possible outcomes, and they are all equally likely.
Now count the number of ordered pairs consisting of two queens. There are $(4)(3)$ of these. So the probability of two queens is $\dfrac{(4)(3)}{(52)(51)}$.
A:
When order is important it is in the selection not what is selected from. The question only wants you to draw two queens. It did not say you had to draw the queen of clubs and then the queen of hearts, just any two queens.
What is the probability of drawing the first queen? Well there are 4 queens in the shuffled deck off 52 cards so the probability is $\frac{4}{52}$
What is the probability of drawing the second queen? This time there are 3 queens left and only 51 cards left in the deck: $\frac{3}{51}$
The probability of these events occurring is therefore:
$$\frac{4}{52}\times\frac{3}{51}=\frac{1}{221}$$
|
[
"stackoverflow",
"0019695829.txt"
] | Q:
OkHttp binding library for Xamarin Android throwing error
I'm attempting to use the OkHttp-Xamarin library in a Xamarin Android application. Whenever I try to create a new OkHttpNetworkHandler I get the exception below.
Line:
var handler = new OkHttpNetworkHandler();
Throws:
[] Missing method Android.Runtime.JNIEnv::AllocObject(Type) in assembly Mono.Android.dll, referenced in assembly /data/data/com.my.app/files/.__override__/OkHttp.dll
[MonoDroid] UNHANDLED EXCEPTION: System.MissingMethodException: Method not found: 'Android.Runtime.JNIEnv.AllocObject'.
[MonoDroid] at ModernHttpClient.OkHttpNetworkHandler..ctor () <IL 0x00001, 0x00057>
I am using prebuilt binaries from ModernHttpClient version 0.9. My minimum Android version is set to 2.3 and target is set to 4.2. I'm using Xamarin Studio 4.0.13 and Mono 3.2.3.
A:
Not really an answer to why the Exception is being thrown but at the suggestion of Paul Betts I switched to the Alpha channel and things are working now.
|
[
"stackoverflow",
"0057737673.txt"
] | Q:
Errors in tutorial project from Unreal's documentation
I'm trying to learn C++/UE4 for the first time, and the code provided in the tutorial (in their own documentation) throws errors. How can I fix this and/or find a tutorial that works?
I'm attempting to work through the tutorial at https://docs.unrealengine.com/en-US/Programming/Tutorials/PlayerInput/index.html, but the code provided in Step 1 throws errors.
I have tried the 'potential fixes' and looked around online but haven't found anything to fix the error.
AMyPawn::AMyPawn()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Set this pawn to be controlled by the lowest-numbered player
AutoPossessPlayer = EAutoReceiveInput::Player0;
// Create a dummy root component we can attach things to.
RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
// Create a camera and a visible object
UCameraComponent* OurCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("OurCamera"));
OurVisibleComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("OurVisibleComponent"));
// Attach our camera and visible object to our root component. Offset and rotate the camera.
OurCamera->SetupAttachment(RootComponent);
OurCamera->SetRelativeLocation(FVector(-250.0f, 0.0f, 250.0f));
OurCamera->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f));
OurVisibleComponent->SetupAttachment(RootComponent);
}
Error C2065 'UCameraComponent': undeclared identifier
Error C2065 'OurCamera': undeclared identifier
Error C2672 'UObject::CreateDefaultSubobject': no matching overloaded function found
Error C2974 'UObject::CreateDefaultSubobject': invalid template argument for 'TReturnType', type expected
Error MSB3075 The command ""C:\Program Files\Epic Games\UE_4.22\Engine\Build\BatchFiles\Build.bat" SecondUnrealProjectEditor Win64 Development -Project="C:\Users...\SecondUnrealProject\SecondUnrealProject.uproject" -WaitMutex -FromMsBuild" exited with code 5. Please verify that you have sufficient rights to run this command.
I expected the code to run without errors as I am following the tutorial exactly (and have in fact copy-pasted the 'working' code to check that I didn't change anything by accident)
A:
The first error means that the compiler can't find the declaration for UCameraComponent, the other errors are simply follow-up errors.
You need to add the following include to your MyPawn.cpp:
#include "Camera/CameraComponent.h"
After fixing that you'll get another error, this time because the declaration for UStaticMeshComponent is missing. For that you need the following include:
#include "Components/StaticMeshComponent.h"
The error messages are different, because in the first case the compiler wants to instantiate an object of an unknown type, which is not possible, while in the latter case the compiler wants to assign a pointer of the unknown type UStaticMeshComponent to another pointer of the known type USceneComponent, and it doesn't know that UStaticMeshComponent can be cast to USceneComponent.
I agree that it's bad that the tutorial missed this, however finding a missing include is fairly easy with the right tool. In Visual Studio you can simply click on any type (e.g. UCameraComponent) while holding Ctrl and it will either directly go to the declaration, or it will show you a list of files with potential declarations.
In Unreal it's also generally the case that for every component the include file has that component's name, so for UCameraComponent that's CameraComponent.h, which resides in the subfolder Camera.
|
[
"stackoverflow",
"0035834329.txt"
] | Q:
Why is GIT not replacing CRLF with LF on writing to the working directory, although core.autocrlf is set to input?
Recently I fiddled around with gits option core.autocrlf und set it to input. I tested if the configuration parameter is set correctly:
$ git config --global core.autocrlf
input
$ git config core.autocrlf
input
Then to test gits behavior I deleted all contents of the project folder (except of course the folder .git) and made a
git reset --hard HEAD
But my editor tells me, the line endings ares still CRLF.
Why?
(I am on Ubuntu and use Atom as editor. The editors statement seems to be valid, as when I tell it to change all line endings to LF, git tells me that every line of the file was changed.)
To understand more about the whole topic i read this enlighting article:
Mind the End of Your Line
A:
core.autocrlf=input will only adopt file endings when adding them to the index (and commiting them).
It will not modify the files on the way to the workspace. You would need to use true for that - and mostly for older Mac and Windows where the native line ending is not LF.
But most likely .gitattributes is the better system for you, as discussed in the article you mentioned.
|
[
"stackoverflow",
"0009152508.txt"
] | Q:
path of view is incorrect in extjs 4 mvc application
I'm trying to deploy my mvc app into my large web application. I have defined the app folder and can see in fire bug that it is calling the correct files with the exception of the initial view. So
"App.view.Jobs" is calling
https://www.estore.localhost/Jobs/Edit/ext/jobs/App/view/Jobs.js?_dc=1328471746967
when i would like it to call
https://www.estore.localhost/ext/jobs/App/view/Jobs.js?_dc=1328471746967
Ext.Loader.setConfig({ enabled: true });
Ext.application({
name: 'MyApp',
appFolder: '/ext/jobs/app',
models: ['Part', 'Material', 'Job', 'Process'],
stores: ['SalesContact', 'Parts', 'Materials', 'Jobs', 'AccountHandlers', 'JobTypes', 'Processs', 'Artwork', 'Varnish', 'VarnishType', 'PrintType', 'ProofRequired', 'InvoiceDetails', 'PurchaseOrders'],
controllers: ['Part', 'Material', 'Job', 'Process', 'Invoice'],
launch: function () {
Ext.QuickTips.init();
var cmp1 = Ext.create('App.view.Jobs', {
renderTo: "form-job"
});
cmp1.show();
}
});
A:
to answer my own question. You can use setPath to assign the path.
like so...
Ext.Loader.setConfig({ enabled: true });
Ext.Loader.setPath('App', '/ext/jobs/app');
Ext.application({
name: 'Pandora',
appFolder: '/ext/jobs/app',
models: ['Part', 'Material', 'Job', 'Process'],
stores: ['SalesContact', 'Parts', 'Materials', 'Jobs', 'AccountHandlers', 'JobTypes', 'Processs', 'Artwork', 'Varnish', 'VarnishType', 'PrintType', 'ProofRequired', 'InvoiceDetails', 'PurchaseOrders'],
controllers: ['Part', 'Material', 'Job', 'Process', 'Invoice'],
launch: function () {
Ext.QuickTips.init();
var cmp1 = Ext.create('App.view.Jobs', {
renderTo: "form-job"
});
cmp1.show();
}
});
|
[
"stackoverflow",
"0001800817.txt"
] | Q:
How can I get part of regex match as a variable in python?
In Perl it is possible to do something like this (I hope the syntax is right...):
$string =~ m/lalala(I want this part)lalala/;
$whatIWant = $1;
I want to do the same in Python and get the text inside the parenthesis in a string like $1.
A:
If you want to get parts by name you can also do this:
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds")
>>> m.groupdict()
{'first_name': 'Malcom', 'last_name': 'Reynolds'}
The example was taken from the re docs
A:
See: Python regex match objects
>>> import re
>>> p = re.compile("lalala(I want this part)lalala")
>>> p.match("lalalaI want this partlalala").group(1)
'I want this part'
A:
import re
astr = 'lalalabeeplalala'
match = re.search('lalala(.*)lalala', astr)
whatIWant = match.group(1) if match else None
print(whatIWant)
A small note: in Perl, when you write
$string =~ m/lalala(.*)lalala/;
the regexp can match anywhere in the string. The equivalent is accomplished with the re.search() function, not the re.match() function, which requires that the pattern match starting at the beginning of the string.
|
[
"stackoverflow",
"0042013272.txt"
] | Q:
How to check element with multiple classes for a number in class
Is it posible to get the class name in this element if its a number?
Can you check if this element has a number as a class and get it out ?
<button id="12" class="btn btn-default 1000 tBtn">
A:
You could use the attribute selector, [class], to select all elements with class attributes. From there you can filter the selected elements based on whether the the array of classes contain a number as a value by using the $.isNumeric jQuery method:
var $elements = $('[class]').filter(function () {
var classes = this.className.split(' ');
var classesWithNumbers = classes.filter(function (value) {
return $.isNumeric(value);
});
return classesWithNumbers.length;
});
Here is a shorter, less verbose version:
var $elements = $('[class]').filter(function () {
return this.className.split(' ').filter($.isNumeric).length;
});
It's worth mentioning that as of HTML4 classes and ids cannot start with numbers. However, that is no longer the case with HTML5. For reference, see: What are valid values for the id attribute in HTML?
|
[
"stackoverflow",
"0009380105.txt"
] | Q:
DataObject.GetDatapresent with subclass
When I call this method DataObject.GetData(typeof(ItemType)) from an instance of a subclass of ItemType the method returns null... How can i get the data from the subtype?
Thank you
A:
The DataObject handling doesn't deal with class hierarchies - it's a straight string 'type' derived from the full name of the data type given, so it has no context to provide it the knowledge of subclasses. I've just hit up against exactly the same problem implementing drag and drop in a treeview.
I had two options (these are possibly drag and drop-specific - if that's not your problem, it may not be a whole lot of use) - both rely on changing the source of the data object (again, if you don't have access to that, it may not be much use).
Create a wrapper class which takes an ItemType instance, and when calling DoDragDrop, pass that wrapper instead of the actual instance. On the other side, test for DataObject.GetData(typeof(WrapperClass)) instead.
Again, where the data object is being set, set a DataObject instance yourself - eg. call
ctl.DoDragDrop(new DataObject(typeof(ItemType).FullName, itemTypeInstance),
DragDropEffects.Move|DragDropEffects.Copy)
then you can just use DataObject.GetData(typeof(ItemType)) on the other side.
|
[
"stackoverflow",
"0042817383.txt"
] | Q:
Resize UITableViewCell to fit label or image and rounded corners
I am attaching a sample project to allow you to test and see what I can do to fix this.
I am trying to resize the height's image dynamically and at the same time round two corners on every other cell. Doing so results in a mask that is cut off.
Basically here is what I am trying to achieve:
UITableView's row height is set to automatic.
_nTableView.rowHeight = UITableViewAutomaticDimension;
_nTableView.estimatedRowHeight = 150;
Download images using SDWebImage library using a CustomTableViewCell
[self.nImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){}];
Configure a cell to round the corners depending on its row
UIBezierPath *maskPath = [UIBezierPath
bezierPathWithRoundedRect:self.bubbleView.bounds
byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerTopLeft)
cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.bubbleView.bounds;
maskLayer.path = maskPath.CGPath;
self.bubbleView.layer.mask = maskLayer;
Doing the above results in a mask being cut off but the height is calculated correctly. See below:
Based on this stack overflow's question, we need to remove the mask if there is one. I have tried to set the mask to nil in awakeFromNib method but that has no affect.
self.nImageView.layer.mask = nil;
self.nImageView.layer.masksToBounds = NO;
I also tried following the answers from this question but it results in the app crashing.
Thank you in advance.
A:
Here is one possible solution - may not be the best, may not do exactly what you need, but might get you on your way...
Instead of trying to manipulate the layers / masks from within your custom UITableViewCell class, use a UIView subclass as the image holder. The code of that class can handle the rounded corners and layer/mask size updating.
See example here: https://github.com/DonMag/dhImage
|
[
"stackoverflow",
"0013325353.txt"
] | Q:
Access names of other apps -windows phone
I know one can't access internal storage of another app,but can we make an app that just gets the names of all other apps installed?
A:
No you do not have access to the other apps installed that are not "Microsoft" apps. The best you can do is have access to "launchers." Read this article by Jeff Blankenburg: http://www.jeffblankenburg.com/2010/10/07/31-days-of-windows-phone-day-7-launchers/
Per Jeff's article (source code is available via the url above):
For a quick look at the list of Launchers, here’s what you’ve got so far:
using Microsoft.Phone.Tasks;
BingMapsDirectionsTask – allows you to provide turn by turn directions from either a start AND end point, or from the user’s current location to an end point.
BingMapsTask – you can use this task to launch a map with a specific point labeled.
ConnectionSettingsTask – a task that allows you to direct your users to their wi-fi, bluetooth, and other settings of their device.
EmailComposeTask – allows the user to send an email using their email accounts.
MarketplaceDetailTask – launches the Windows Phone Marketplace, and takes the user to a specific product offering.
MarketplaceHubTask – launched the Windows Phone Marketplace, and allows you to specify a category of applications to show by default.
MarketplaceReviewTask – takes the user to the Windows Phone Marketplace to review the current application.
MarketplaceSearchTask – launches search results for the Windows Phone Marketplace, based on a search term your user enters (or that you specify.)
MediaPlayerLauncher – launches the internal Media Player application, and plays the media file that you specify.
PhoneCallTask – launches the Phone application and displays the provided phone number and name. The phone call isn’t dialed until the user presses “Call.”
SearchTask – think of this as a way to provide a Bing search from your application.
SMSComposeTask – launches the Messaging application, and presents the user with the ability to send a text message. You can specify recipients and message body, but the user has to send it.
WebBrowserTask – launches the Web Browser, and navigates to the specified URL.
Also, Windows Phone 8 has released some new features to add to this list. Check out the new items via MSDN.
|
[
"physics.stackexchange",
"0000039015.txt"
] | Q:
Mathematical probabilistic interepretation of probability amplitude
As a warning, I come from an "applied math" background with next to no knowledge of physics. That said, here's my question:
I'm looking at the possibility of using probability amplitude functions to represent probability distributions on surfaces. From my perspective, a probability amplitude function is a function $\psi:\Sigma\rightarrow\mathbb{C}$ satisfying $\int_\Sigma |\psi|^2=1$ for some domain $\Sigma$ (e.g. a surface or part of $\mathbb{R}^n$)-- obviously these are some of the main objects manipulated in quantum physics! In other words, $\psi$ is a complex function such that $|\psi|^2$ is a probability density function on $\Sigma$.
From this purely probabilistic standpoint, is it possible to understand why multiple $\psi$'s can represent the same probability density $|\psi|^2$? What is the most generic physical interpretation?
That is, if I write down any function $\gamma:\Sigma\rightarrow\mathbb{C}$ with $|\gamma(x)|=1\ \forall x\in\Sigma$, then $|\psi\gamma|^2=|\psi|^2|\gamma|^2=|\psi|^2$, and thus $\psi$ and $\psi\gamma$ represent the same probability distribution on $\Sigma$. So why is this redundancy useful mathematically?
A:
The redundancy is useful because, apparently, the phases have a physical meaning, and relative phases do actually make a difference to the probabilities in some situations. For example, consider a simplified two-slit experiment. We have a photon emitter, which fires a photon toward two slits. Behind the two slits is a detector, which will either fire or not fire. (If it doesn't fire, we think of the photon as having "missed" the detector and been absorbed by something else.) We also have the option to try and detect which of the slits the photon passed through, or not to try and do this.
Let $E$ stand for "a photon is emitted", $D$ stand for "the detector fires" $S_i$ stand for "the photon was detected passing through slit $i$." If we do try to detect which slit the photon passed through, the probability of the detector firing is
$$ p(D|E) = p(S_1|E)p(D|S_1) + p(S_2|E)p(D|S_2),$$
as you would expect from elementary probability theory. If we want, we can formally define a complex number $a(X|Y)$ for each pair of events, such that $p(X|Y) = |a(X|Y)|^2.$ There is some redundancy in this definition because any choice of phase gives the same probability. Now we have
$$ p(D|E) = |a(S_1|E)a(D|S_1)|^2 + |a(S_2|E)a(D|S_2)|^2.$$
Note that this is completely non-standard notation that you won't find anywhere, but it's a perfectly reasonable way to express the path integral formalism for this type of simplified system.
If we don't try to detect which slit the photon passed through, so that it remains isolated throughout its journey, then it's a bit different. Now it turns out that instead of the above expression we have $$ p(D|E) = |a(S_1|E)a(D|S_1) + a(S_2|E)a(D|S_2)|^2,$$
for some particular choice of the numbers $a(S_i|E)$ and $a(D|S_i)$ defined above. Note that this can be greater or less than the "classical" $p(D|E)$, depending on the relative phases of $a(S_1|E)a(D|S_1)$ and $a(S_2|E)a(D|S_2)$. Therefore the different phases lead to different physical predictions, and part of the power of quantum theory is that it does actually tell you these relative phases.
This argument shows that there must be some physical interpretation of the phases, but it doesn't tell you what that physical interpretation actually is. I'm afraid I don't know the answer to that question.
A:
Different wave functions with the same $|\psi(x)|^2$ represent different physical states (unless they are proportional). Different states means that one gets different measurable results on at least one kind of measurements.
The same $|\psi(x)|^2$ gives the same probability density for position measurements (only), but generally not for measurements of other observables such as momentum.
For the momentum probability density, the absolute squares of the Fourier transform counts, and this is usually different if only the $|\psi(x)|^2$ are the same.
The mathematical content of the wave function is the following (from which the above follows): The inner product of $\psi$ with $A\psi$ gives the expectation value of the operator $A$ for a system in state $\psi$. For example, if you take $A$ to be multiplication by the characteristic function of a region in $R^3$ you get the probability for being in that region. The position operator is simply multiplication by $x$, while the momentum operator is a multiple of differentiation.
For going deeper, try my online book http://lanl.arxiv.org/abs/0810.1019,
written for mathematicians without any background knowledge in physics.
|
[
"serverfault",
"0000126708.txt"
] | Q:
Linux SVN not communicating with apache
I have SVN setup on the server, but when I try to do a checkout remotely via SSH it throws a 200 OK response, rather than processing my checkout. I think I've missed a step with the SVN and how it communicates with apache.... any thoughts?
A:
Do yourself a favor and bookmark the official SVN book. It's got many handy references, like this table. Let me call your attention to this table There are three common ways to connect to SVN:
SVN procotol. SVN server listening on port 3690. URIs start with svn://
SVN+SSH. SSH listening (port 22 by default) with a local SVN daemon launched for the duration of the transaction. URIs start with svn+ssh://
HTTP. Apache listening on port 80/443 for HTTP requests, and directing them to mod_dav_svn. This is what you claim to be using. URIs start with https://
If you have only set up Apache then you need to use something like https://example.com/repo/path
|
[
"stackoverflow",
"0007568621.txt"
] | Q:
TextBox Column In DataGridView
I have added TextBox control inside the grid: I want my DataGridView TextBox column to hold numbers without any decimal values. How can I do it?
A:
From: http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/919b059c-dba9-40d2-bac7-608a9b120336
You can handle the DataGridView.EditingControlShowing event to cast
the editing control to TextBox when editing in the column you want to
restrict input on, and attach KeyPress event to the TextBox, in the
KeyPress event handler function, we can call the char.IsNumber()
method to restrict the key board input, something like this:
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("c1", typeof(int));
dt.Columns.Add("c2");
for (int j = 0; j < 10; j++)
{
dt.Rows.Add(j, "aaa" + j.ToString());
}
this.dataGridView1.DataSource = dt;
this.dataGridView1.EditingControlShowing +=
new DataGridViewEditingControlShowingEventHandler(
dataGridView1_EditingControlShowing);
}
private bool IsHandleAdded;
void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (!IsHandleAdded &&
this.dataGridView1.CurrentCell.ColumnIndex == 0)
{
TextBox tx = e.Control as TextBox;
if (tx != null)
{
tx.KeyPress += new KeyPressEventHandler(tx_KeyPress);
this.IsHandleAdded = true;
}
}
}
void tx_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsNumber(e.KeyChar) || e.KeyChar == '\b'))
{
e.Handled = true;
}
}
|
[
"stackoverflow",
"0005842993.txt"
] | Q:
How to design a location data app integrated with own RoR web site for iPhone
Simple concept: Map users current location with specific points of interest around their vicinity.
Details:
I have my own map mash-up web site, that provides a service for people to search for as well as contribute GPS location data of toboggan hills.
Now I need to build a companion iPhone app for the site.
My Challenge: I'm kindly asking for input as to which API tools/design best suit this task?
I'm aware of the Core Location Framework. But am ignorant of how best to go about getting my list of location data points from my own Rails web site. (I didn't code the web site, it was outsourced)
I'll need to explain this to the rails team for any site changes. As well as figure out for myself the iPhone portion.
Ideally, I'm imagining a protocol where I ask the server to only give me the list of location points within a certain GPS radius that the iPhone is in.
Is that possible? Will that tax the server too much?
Downloading the entire world-wide list of hills and then filtering on the iPhone for just the ones 'in view' seems inefficient.
How do other apps do it?
Thank you.
A:
You are going down the correct path. In a nutshell you want to:
Have the iPhone provide an updated location when the user moves more than X meters
Take the new GPS location and make a request to the server. (Preferrably SSL with some posted key info to prevent open access)
The server searches for POIs within a radius of that location and returns JSON or XML of POI GPS information
Use that information to draw the POIs
The question you have, is if you want to store the POI info on the device or if you want to get it fresh every time.
|
[
"stackoverflow",
"0035970010.txt"
] | Q:
GO : how to Assign all elements in 2 by 2 array of variable size?
I'm having problems filling a 2D array with a matrix from a text file using GO.
The main problem I have is to create a 2D array because I have to calculate the dimension of the array and GO does not seem to accept VAR in array dimension :
nb_lines = number of line of the array
nb_col = number of columns of the array
// read matrix from file
whole_file,_ := ioutil.ReadFile("test2.txt")
// get each line of the file in tab_whole_file
tab_whole_file := strings.Split(string(whole_file), "\n")
// first line of the table
tab_first_line := strings.Split(tab_whole_file[0], "\t")
nb_col := len(tab_first_line)
nb_lines := len(tab_whole_file) - 1
// at this point I tried to build a array to contain the matrix values from the texte file
var columns [nb_lines][nb_col]float64 // does not work
columns := make([][]float64, nb_lines, nb_col) // does not work
columns := make([nb_lines][nb_col]float64) // does not work
columns := [nb_lines][nb_col]float64{} // does not work
columns := [][]float64{} // panic: runtime error: index out of range
for i := 0; i < nb_lines ; i++ { // for each line of the table from text file
line := strings.Split(tab_whole_file[0], "\t") // split one line to get each table values
for j := 1; j < len(line) ; j++ {
columns[i][j], _ = strconv.ParseFloat(line[j], 64) // assign each value to the table columns[i][j]
}
}
A:
For example,
package main
import (
"bytes"
"fmt"
"io/ioutil"
"strconv"
)
func loadMatrix(filename string) ([][]float64, error) {
var m [][]float64
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
rows := bytes.Split(data, []byte{'\n'})
for r := len(rows) - 1; r >= 0; r-- {
if len(rows[r]) != 0 {
break
}
rows = rows[:len(rows)-1]
}
m = make([][]float64, len(rows))
nCols := 0
for r, row := range rows {
cols := bytes.Split(row, []byte{'\t'})
if r == 0 {
nCols = len(cols)
}
m[r] = make([]float64, nCols)
for c, col := range cols {
if c < nCols && len(col) > 0 {
e, err := strconv.ParseFloat(string(col), 64)
if err != nil {
return nil, err
}
m[r][c] = e
}
}
}
return m, nil
}
func main() {
filename := "matrix.tsv"
m, err := loadMatrix(filename)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Matrix:")
fmt.Println(m)
fmt.Println("\nBy [row,column]:")
for r := range m {
for c := range m[0] {
fmt.Printf("[%d,%d] %5v ", r, c, m[r][c])
}
fmt.Println()
}
fmt.Println("\nBy [column,row]:")
for c := range m[0] {
for r := range m {
fmt.Printf("[%d,%d] %5v ", c, r, m[r][c])
}
fmt.Println()
}
}
Output:
$ cat matrix.tsv
3.14 1.59 2.7 1.8
42
$ go run matrix.go
Matrix:
[[3.14 1.59 2.7 1.8] [42 0 0 0]]
By [row,column]:
[0,0] 3.14 [0,1] 1.59 [0,2] 2.7 [0,3] 1.8
[1,0] 42 [1,1] 0 [1,2] 0 [1,3] 0
By [column,row]:
[0,0] 3.14 [0,1] 42
[1,0] 1.59 [1,1] 0
[2,0] 2.7 [2,1] 0
[3,0] 1.8 [3,1] 0
$
|
[
"stackoverflow",
"0048571577.txt"
] | Q:
Concurrency inside embedded Jetty of Spark java
We have a simple Java REST API that is supported by Spark framework.
We have initialized the threads as is indicated in http://sparkjava.com/documentation#embedded-web-server by the following chunk that is being called from the Java main method of our application:
int maxThreads = 8;
int minThreads = 2;
int timeOutMillis = 30000;
threadPool(maxThreads, minThreads, timeOutMillis);
However, we have made some simulations for simultaneous requests and it results that the threads get created but are queued to make HTTP requests sequentially, although we thought that the requests were going to be concurrent.
Is that normal? Is Spark framework usual behavior to avoid the server to handle a configured number of threads but make them to wait in queue to effectively perform the HTTP requests?
A:
I have been investigating this and what I know now is that this is the usual way to proceed specially for tiny web frameworks like Spark Java.
The reason behind is to regulate the traffic in the server an avoid throttling.
|
[
"stackoverflow",
"0059436814.txt"
] | Q:
Program responsible for displaying of ETA while loading InceptionV3 from Keras
I was loading the InceptionV3 model from Keras for the first time and it took a long time due to my low processing power and it had me thinking about which program is responsible for the calculation of ETA displaying the bar?
InceptionV3_base_model = InceptionV3(weights='imagenet', include_top=False)
>>
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.5/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5
37036032/87910968 [===========>..................] - ETA: 37s
Which program is calculating and displaying these? is it Keras, Jupyter or the Linux itself calculating?
A:
Take keras.datasets.mnist as an example. (Because it's also showing a progress bar.)
Source code:
"""MNIST handwritten digits dataset.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ..utils.data_utils import get_file
import numpy as np
def load_data(path='mnist.npz'):
"""Loads the MNIST dataset.
# Arguments
path: path where to cache the dataset locally
(relative to ~/.keras/datasets).
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path,
origin='https://s3.amazonaws.com/img-datasets/mnist.npz',
file_hash='8a61469f7ea1b51cbae51d4f78837e45')
with np.load(path, allow_pickle=True) as f:
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
return (x_train, y_train), (x_test, y_test)
And we know the bar comes from ..utils.data_utils.get_file
keras.utils.__init__.py looks like this:
from __future__ import absolute_import
from . import np_utils
from . import generic_utils
from . import data_utils
from . import io_utils
from . import conv_utils
from . import losses_utils
from . import metrics_utils
# Globally-importable utils.
from .io_utils import HDF5Matrix
from .io_utils import H5Dict
from .data_utils import get_file
from .data_utils import Sequence
from .data_utils import GeneratorEnqueuer
from .data_utils import OrderedEnqueuer
from .generic_utils import CustomObjectScope
from .generic_utils import custom_object_scope
from .generic_utils import get_custom_objects
from .generic_utils import serialize_keras_object
from .generic_utils import deserialize_keras_object
from .generic_utils import Progbar
from .layer_utils import convert_all_kernels_in_model
from .layer_utils import get_source_inputs
from .layer_utils import print_summary
from .vis_utils import model_to_dot
from .vis_utils import plot_model
from .np_utils import to_categorical
from .np_utils import normalize
from .multi_gpu_utils import multi_gpu_model
get_file comes from keras.data_utils
keras.data_utils.py:
"""Utilities for file download and caching."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import hashlib
import multiprocessing as mp
import os
import random
import shutil
import sys
import tarfile
import threading
import time
import warnings
import zipfile
from abc import abstractmethod
from contextlib import closing
from multiprocessing.pool import ThreadPool
import numpy as np
import six
from six.moves.urllib.error import HTTPError
from six.moves.urllib.error import URLError
from six.moves.urllib.request import urlopen
try:
import queue
except ImportError:
import Queue as queue
from ..utils.generic_utils import Progbar
if sys.version_info[0] == 2:
def urlretrieve(url, filename, reporthook=None, data=None):
"""Replacement for `urlretrieve` for Python 2.
Under Python 2, `urlretrieve` relies on `FancyURLopener` from legacy
`urllib` module, known to have issues with proxy management.
# Arguments
url: url to retrieve.
filename: where to store the retrieved data locally.
reporthook: a hook function that will be called once
on establishment of the network connection and once
after each block read thereafter.
The hook will be passed three arguments;
a count of blocks transferred so far,
a block size in bytes, and the total size of the file.
data: `data` argument passed to `urlopen`.
"""
def chunk_read(response, chunk_size=8192, reporthook=None):
content_type = response.info().get('Content-Length')
total_size = -1
if content_type is not None:
total_size = int(content_type.strip())
count = 0
while True:
chunk = response.read(chunk_size)
count += 1
if reporthook is not None:
reporthook(count, chunk_size, total_size)
if chunk:
yield chunk
else:
break
with closing(urlopen(url, data)) as response, open(filename, 'wb') as fd:
for chunk in chunk_read(response, reporthook=reporthook):
fd.write(chunk)
else:
from six.moves.urllib.request import urlretrieve
def _extract_archive(file_path, path='.', archive_format='auto'):
"""Extracts an archive if it matches tar, tar.gz, tar.bz, or zip formats.
# Arguments
file_path: path to the archive file
path: path to extract the archive file
archive_format: Archive format to try for extracting the file.
Options are 'auto', 'tar', 'zip', and None.
'tar' includes tar, tar.gz, and tar.bz files.
The default 'auto' is ['tar', 'zip'].
None or an empty list will return no matches found.
# Returns
True if a match was found and an archive extraction was completed,
False otherwise.
"""
if archive_format is None:
return False
if archive_format == 'auto':
archive_format = ['tar', 'zip']
if isinstance(archive_format, six.string_types):
archive_format = [archive_format]
for archive_type in archive_format:
if archive_type == 'tar':
open_fn = tarfile.open
is_match_fn = tarfile.is_tarfile
if archive_type == 'zip':
open_fn = zipfile.ZipFile
is_match_fn = zipfile.is_zipfile
if is_match_fn(file_path):
with open_fn(file_path) as archive:
try:
archive.extractall(path)
except (tarfile.TarError, RuntimeError,
KeyboardInterrupt):
if os.path.exists(path):
if os.path.isfile(path):
os.remove(path)
else:
shutil.rmtree(path)
raise
return True
return False
def get_file(fname,
origin,
untar=False,
md5_hash=None,
file_hash=None,
cache_subdir='datasets',
hash_algorithm='auto',
extract=False,
archive_format='auto',
cache_dir=None):
"""Downloads a file from a URL if it not already in the cache.
By default the file at the url `origin` is downloaded to the
cache_dir `~/.keras`, placed in the cache_subdir `datasets`,
and given the filename `fname`. The final location of a file
`example.txt` would therefore be `~/.keras/datasets/example.txt`.
Files in tar, tar.gz, tar.bz, and zip formats can also be extracted.
Passing a hash will verify the file after download. The command line
programs `shasum` and `sha256sum` can compute the hash.
# Arguments
fname: Name of the file. If an absolute path `/path/to/file.txt` is
specified the file will be saved at that location.
origin: Original URL of the file.
untar: Deprecated in favor of 'extract'.
boolean, whether the file should be decompressed
md5_hash: Deprecated in favor of 'file_hash'.
md5 hash of the file for verification
file_hash: The expected hash string of the file after download.
The sha256 and md5 hash algorithms are both supported.
cache_subdir: Subdirectory under the Keras cache dir where the file is
saved. If an absolute path `/path/to/folder` is
specified the file will be saved at that location.
hash_algorithm: Select the hash algorithm to verify the file.
options are 'md5', 'sha256', and 'auto'.
The default 'auto' detects the hash algorithm in use.
extract: True tries extracting the file as an Archive, like tar or zip.
archive_format: Archive format to try for extracting the file.
Options are 'auto', 'tar', 'zip', and None.
'tar' includes tar, tar.gz, and tar.bz files.
The default 'auto' is ['tar', 'zip'].
None or an empty list will return no matches found.
cache_dir: Location to store cached files, when None it
defaults to the [Keras Directory](/faq/#where-is-the-keras-configuration-filed-stored).
# Returns
Path to the downloaded file
""" # noqa
if cache_dir is None:
if 'KERAS_HOME' in os.environ:
cache_dir = os.environ.get('KERAS_HOME')
else:
cache_dir = os.path.join(os.path.expanduser('~'), '.keras')
if md5_hash is not None and file_hash is None:
file_hash = md5_hash
hash_algorithm = 'md5'
datadir_base = os.path.expanduser(cache_dir)
if not os.access(datadir_base, os.W_OK):
datadir_base = os.path.join('/tmp', '.keras')
datadir = os.path.join(datadir_base, cache_subdir)
if not os.path.exists(datadir):
os.makedirs(datadir)
if untar:
untar_fpath = os.path.join(datadir, fname)
fpath = untar_fpath + '.tar.gz'
else:
fpath = os.path.join(datadir, fname)
download = False
if os.path.exists(fpath):
# File found; verify integrity if a hash was provided.
if file_hash is not None:
if not validate_file(fpath, file_hash, algorithm=hash_algorithm):
print('A local file was found, but it seems to be '
'incomplete or outdated because the ' + hash_algorithm +
' file hash does not match the original value of ' +
file_hash + ' so we will re-download the data.')
download = True
else:
download = True
if download:
print('Downloading data from', origin)
class ProgressTracker(object):
# Maintain progbar for the lifetime of download.
# This design was chosen for Python 2.7 compatibility.
progbar = None
def dl_progress(count, block_size, total_size):
if ProgressTracker.progbar is None:
if total_size == -1:
total_size = None
ProgressTracker.progbar = Progbar(total_size)
else:
ProgressTracker.progbar.update(count * block_size)
error_msg = 'URL fetch failure on {} : {} -- {}'
try:
try:
urlretrieve(origin, fpath, dl_progress)
except HTTPError as e:
raise Exception(error_msg.format(origin, e.code, e.msg))
except URLError as e:
raise Exception(error_msg.format(origin, e.errno, e.reason))
except (Exception, KeyboardInterrupt):
if os.path.exists(fpath):
os.remove(fpath)
raise
ProgressTracker.progbar = None
if untar:
if not os.path.exists(untar_fpath):
_extract_archive(fpath, datadir, archive_format='tar')
return untar_fpath
if extract:
_extract_archive(fpath, datadir, archive_format)
return fpath
def _hash_file(fpath, algorithm='sha256', chunk_size=65535):
"""Calculates a file sha256 or md5 hash.
# Example
```python
>>> from keras.utils.data_utils import _hash_file
>>> _hash_file('/path/to/file.zip')
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
```
# Arguments
fpath: path to the file being validated
algorithm: hash algorithm, one of 'auto', 'sha256', or 'md5'.
The default 'auto' detects the hash algorithm in use.
chunk_size: Bytes to read at a time, important for large files.
# Returns
The file hash
"""
if (algorithm == 'sha256') or (algorithm == 'auto' and len(hash) == 64):
hasher = hashlib.sha256()
else:
hasher = hashlib.md5()
with open(fpath, 'rb') as fpath_file:
for chunk in iter(lambda: fpath_file.read(chunk_size), b''):
hasher.update(chunk)
return hasher.hexdigest()
def validate_file(fpath, file_hash, algorithm='auto', chunk_size=65535):
"""Validates a file against a sha256 or md5 hash.
# Arguments
fpath: path to the file being validated
file_hash: The expected hash string of the file.
The sha256 and md5 hash algorithms are both supported.
algorithm: Hash algorithm, one of 'auto', 'sha256', or 'md5'.
The default 'auto' detects the hash algorithm in use.
chunk_size: Bytes to read at a time, important for large files.
# Returns
Whether the file is valid
"""
if ((algorithm == 'sha256') or
(algorithm == 'auto' and len(file_hash) == 64)):
hasher = 'sha256'
else:
hasher = 'md5'
if str(_hash_file(fpath, hasher, chunk_size)) == str(file_hash):
return True
else:
return False
class Sequence(object):
"""Base object for fitting to a sequence of data, such as a dataset.
Every `Sequence` must implement the `__getitem__` and the `__len__` methods.
If you want to modify your dataset between epochs you may implement
`on_epoch_end`. The method `__getitem__` should return a complete batch.
# Notes
`Sequence` are a safer way to do multiprocessing. This structure guarantees
that the network will only train once on each sample per epoch which is not
the case with generators.
# Examples
```python
from skimage.io import imread
from skimage.transform import resize
import numpy as np
# Here, `x_set` is list of path to the images
# and `y_set` are the associated classes.
class CIFAR10Sequence(Sequence):
def __init__(self, x_set, y_set, batch_size):
self.x, self.y = x_set, y_set
self.batch_size = batch_size
def __len__(self):
return int(np.ceil(len(self.x) / float(self.batch_size)))
def __getitem__(self, idx):
batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]
batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]
return np.array([
resize(imread(file_name), (200, 200))
for file_name in batch_x]), np.array(batch_y)
```
"""
use_sequence_api = True
@abstractmethod
def __getitem__(self, index):
"""Gets batch at position `index`.
# Arguments
index: position of the batch in the Sequence.
# Returns
A batch
"""
raise NotImplementedError
@abstractmethod
def __len__(self):
"""Number of batch in the Sequence.
# Returns
The number of batches in the Sequence.
"""
raise NotImplementedError
def on_epoch_end(self):
"""Method called at the end of every epoch.
"""
pass
def __iter__(self):
"""Create a generator that iterate over the Sequence."""
for item in (self[i] for i in range(len(self))):
yield item
# Global variables to be shared across processes
_SHARED_SEQUENCES = {}
# We use a Value to provide unique id to different processes.
_SEQUENCE_COUNTER = None
def init_pool(seqs):
global _SHARED_SEQUENCES
_SHARED_SEQUENCES = seqs
def get_index(uid, i):
"""Get the value from the Sequence `uid` at index `i`.
To allow multiple Sequences to be used at the same time, we use `uid` to
get a specific one. A single Sequence would cause the validation to
overwrite the training Sequence.
# Arguments
uid: int, Sequence identifier
i: index
# Returns
The value at index `i`.
"""
return _SHARED_SEQUENCES[uid][i]
class SequenceEnqueuer(object):
"""Base class to enqueue inputs.
The task of an Enqueuer is to use parallelism to speed up preprocessing.
This is done with processes or threads.
# Examples
```python
enqueuer = SequenceEnqueuer(...)
enqueuer.start()
datas = enqueuer.get()
for data in datas:
# Use the inputs; training, evaluating, predicting.
# ... stop sometime.
enqueuer.close()
```
The `enqueuer.get()` should be an infinite stream of datas.
"""
def __init__(self, sequence,
use_multiprocessing=False):
self.sequence = sequence
self.use_multiprocessing = use_multiprocessing
global _SEQUENCE_COUNTER
if _SEQUENCE_COUNTER is None:
try:
_SEQUENCE_COUNTER = mp.Value('i', 0)
except OSError:
# In this case the OS does not allow us to use
# multiprocessing. We resort to an int
# for enqueuer indexing.
_SEQUENCE_COUNTER = 0
if isinstance(_SEQUENCE_COUNTER, int):
self.uid = _SEQUENCE_COUNTER
_SEQUENCE_COUNTER += 1
else:
# Doing Multiprocessing.Value += x is not process-safe.
with _SEQUENCE_COUNTER.get_lock():
self.uid = _SEQUENCE_COUNTER.value
_SEQUENCE_COUNTER.value += 1
self.workers = 0
self.executor_fn = None
self.queue = None
self.run_thread = None
self.stop_signal = None
def is_running(self):
return self.stop_signal is not None and not self.stop_signal.is_set()
def start(self, workers=1, max_queue_size=10):
"""Start the handler's workers.
# Arguments
workers: number of worker threads
max_queue_size: queue size
(when full, workers could block on `put()`)
"""
if self.use_multiprocessing:
self.executor_fn = self._get_executor_init(workers)
else:
# We do not need the init since it's threads.
self.executor_fn = lambda _: ThreadPool(workers)
self.workers = workers
self.queue = queue.Queue(max_queue_size)
self.stop_signal = threading.Event()
self.run_thread = threading.Thread(target=self._run)
self.run_thread.daemon = True
self.run_thread.start()
def _send_sequence(self):
"""Send current Iterable to all workers."""
# For new processes that may spawn
_SHARED_SEQUENCES[self.uid] = self.sequence
def stop(self, timeout=None):
"""Stops running threads and wait for them to exit, if necessary.
Should be called by the same thread which called `start()`.
# Arguments
timeout: maximum time to wait on `thread.join()`
"""
self.stop_signal.set()
with self.queue.mutex:
self.queue.queue.clear()
self.queue.unfinished_tasks = 0
self.queue.not_full.notify()
self.run_thread.join(timeout)
_SHARED_SEQUENCES[self.uid] = None
@abstractmethod
def _run(self):
"""Submits request to the executor and queue the `Future` objects."""
raise NotImplementedError
@abstractmethod
def _get_executor_init(self, workers):
"""Get the Pool initializer for multiprocessing.
# Returns
Function, a Function to initialize the pool
"""
raise NotImplementedError
@abstractmethod
def get(self):
"""Creates a generator to extract data from the queue.
Skip the data if it is `None`.
# Returns
Generator yielding tuples `(inputs, targets)`
or `(inputs, targets, sample_weights)`.
"""
raise NotImplementedError
class OrderedEnqueuer(SequenceEnqueuer):
"""Builds a Enqueuer from a Sequence.
Used in `fit_generator`, `evaluate_generator`, `predict_generator`.
# Arguments
sequence: A `keras.utils.data_utils.Sequence` object.
use_multiprocessing: use multiprocessing if True, otherwise threading
shuffle: whether to shuffle the data at the beginning of each epoch
"""
def __init__(self, sequence, use_multiprocessing=False, shuffle=False):
super(OrderedEnqueuer, self).__init__(sequence, use_multiprocessing)
self.shuffle = shuffle
self.end_of_epoch_signal = threading.Event()
def _get_executor_init(self, workers):
"""Get the Pool initializer for multiprocessing.
# Returns
Function, a Function to initialize the pool
"""
return lambda seqs: mp.Pool(workers,
initializer=init_pool,
initargs=(seqs,))
def _wait_queue(self):
"""Wait for the queue to be empty."""
while True:
time.sleep(0.1)
if self.queue.unfinished_tasks == 0 or self.stop_signal.is_set():
return
def _run(self):
"""Submits request to the executor and queue the `Future` objects."""
while True:
sequence = list(range(len(self.sequence)))
self._send_sequence() # Share the initial sequence
if self.shuffle:
random.shuffle(sequence)
with closing(self.executor_fn(_SHARED_SEQUENCES)) as executor:
for i in sequence:
if self.stop_signal.is_set():
return
future = executor.apply_async(get_index, (self.uid, i))
future.idx = i
self.queue.put(future, block=True)
# Done with the current epoch, waiting for the final batches
self._wait_queue()
if self.stop_signal.is_set():
# We're done
return
# Call the internal on epoch end.
self.sequence.on_epoch_end()
# communicate on_epoch_end to the main thread
self.end_of_epoch_signal.set()
def join_end_of_epoch(self):
self.end_of_epoch_signal.wait(timeout=30)
self.end_of_epoch_signal.clear()
def get(self):
"""Creates a generator to extract data from the queue.
Skip the data if it is `None`.
# Yields
The next element in the queue, i.e. a tuple
`(inputs, targets)` or
`(inputs, targets, sample_weights)`.
"""
try:
while self.is_running():
try:
future = self.queue.get(block=True)
inputs = future.get(timeout=30)
except mp.TimeoutError:
idx = future.idx
warnings.warn(
'The input {} could not be retrieved.'
' It could be because a worker has died.'.format(idx),
UserWarning)
inputs = self.sequence[idx]
finally:
self.queue.task_done()
if inputs is not None:
yield inputs
except Exception:
self.stop()
six.reraise(*sys.exc_info())
def init_pool_generator(gens, random_seed=None):
global _SHARED_SEQUENCES
_SHARED_SEQUENCES = gens
if random_seed is not None:
ident = mp.current_process().ident
np.random.seed(random_seed + ident)
def next_sample(uid):
"""Get the next value from the generator `uid`.
To allow multiple generators to be used at the same time, we use `uid` to
get a specific one. A single generator would cause the validation to
overwrite the training generator.
# Arguments
uid: int, generator identifier
# Returns
The next value of generator `uid`.
"""
return six.next(_SHARED_SEQUENCES[uid])
class GeneratorEnqueuer(SequenceEnqueuer):
"""Builds a queue out of a data generator.
The provided generator can be finite in which case the class will throw
a `StopIteration` exception.
Used in `fit_generator`, `evaluate_generator`, `predict_generator`.
# Arguments
sequence: a sequence function which yields data
use_multiprocessing: use multiprocessing if True, otherwise threading
wait_time: time to sleep in-between calls to `put()`
random_seed: Initial seed for workers,
will be incremented by one for each worker.
"""
def __init__(self, sequence, use_multiprocessing=False, wait_time=None,
random_seed=None):
super(GeneratorEnqueuer, self).__init__(sequence, use_multiprocessing)
self.random_seed = random_seed
if wait_time is not None:
warnings.warn('`wait_time` is not used anymore.',
DeprecationWarning)
def _get_executor_init(self, workers):
"""Get the Pool initializer for multiprocessing.
# Returns
Function, a Function to initialize the pool
"""
return lambda seqs: mp.Pool(workers,
initializer=init_pool_generator,
initargs=(seqs, self.random_seed))
def _run(self):
"""Submits request to the executor and queue the `Future` objects."""
self._send_sequence() # Share the initial generator
with closing(self.executor_fn(_SHARED_SEQUENCES)) as executor:
while True:
if self.stop_signal.is_set():
return
self.queue.put(
executor.apply_async(next_sample, (self.uid,)), block=True)
def get(self):
"""Creates a generator to extract data from the queue.
Skip the data if it is `None`.
# Yields
The next element in the queue, i.e. a tuple
`(inputs, targets)` or
`(inputs, targets, sample_weights)`.
"""
try:
while self.is_running():
try:
future = self.queue.get(block=True)
inputs = future.get(timeout=30)
self.queue.task_done()
except mp.TimeoutError:
warnings.warn(
'An input could not be retrieved.'
' It could be because a worker has died.'
'We do not have any information on the lost sample.',
UserWarning)
continue
if inputs is not None:
yield inputs
except StopIteration:
# Special case for finite generators
last_ones = []
while self.queue.qsize() > 0:
last_ones.append(self.queue.get(block=True))
# Wait for them to complete
list(map(lambda f: f.wait(), last_ones))
# Keep the good ones
last_ones = [future.get() for future in last_ones if future.successful()]
for inputs in last_ones:
if inputs is not None:
yield inputs
except Exception as e:
self.stop()
if 'generator already executing' in str(e):
raise RuntimeError(
"Your generator is NOT thread-safe."
"Keras requires a thread-safe generator when"
"`use_multiprocessing=False, workers > 1`."
"For more information see issue #1638.")
six.reraise(*sys.exc_info())
That's where it comes from.
So progress bar in get_file is rendered by ..utils.generic_utils.Progbar, which is keras itself.
|
[
"stackoverflow",
"0050063080.txt"
] | Q:
User defined function can only have select statements
One of the main differences between UDF and SP is that UDF can only have select statements inside it and not insert/update/delete statements. Can someone please explain the reason behind this?The below function:
create function test(..)
...
BEGIN
insert into EMPLOYEE('22',12000,'john');
return 0;
END
is not valid. But why is this so?
A:
The insert statement inside your function is missing the values keyword;
insert into EMPLOYEE('22',12000,'john');
should be
insert into EMPLOYEE values ('22',12000,'john');
though it's better to include the list of column names too. From the small part of the code you showed that is the only thing that is invalid. There could be other errors in the bits you have omitted. (If the first column in your table is numeric then you shouldn't be passing a string - it works but does implicit conversion and is best avoided. And if the column is a string, should it be really?)
UDF can only have select statements inside it and not insert/update/delete statements
That is not correct. You can have DML (insert/update/delete) in a function, but you can only call it from a PL/SQL context (though even in PL/SQL, it's often said that functions should query data with no side effects and only procedures should modify data; but that is not restricted by the language itself):
create table employee (id varchar2(3), salary number, name varchar2(10));
Table EMPLOYEE created.
create function test(unused number)
return number as
BEGIN
insert into EMPLOYEE (id, salary, name)
values ('22',12000,'john');
return 0;
END;
/
Function TEST compiled
declare
rc number;
begin
rc := test(42);
end;
/
PL/SQL procedure successfully completed.
select * from employee;
ID SALARY NAME
--- ---------- ----------
22 12000 john
But you cannot call it from a SQL context:
select test(42) from dual;
ORA-14551: cannot perform a DML operation inside a query
ORA-06512: at "MYSCHEMA.TEST", line 4
The documentation lists restrictions on functions called from SQL, and goes into more detail in this warning:
Because SQL is a declarative language, rather than an imperative (or procedural) one, you cannot know how many times a function invoked by a SQL statement will run—even if the function is written in PL/SQL, an imperative language.
If the function was allowed to do DML then you would have no control over how many times that DML was performed. If it was doing an insert, for instance, it might try to insert the same row twice and either duplicate data or get a constraint violation.
|
[
"stackoverflow",
"0038200398.txt"
] | Q:
SSIS: Why won't my Text Delimiter work?
Originally I had wrote the following:
Environment:
- SSIS 2012, Microsoft Visual Studio
Files Involved: Destination Manager: OLEDB SQL Server Table
Source Manager: FLATFILE - CSV File
FORMAT: Delimited
HeadRowDelimiter: {CR}{LF}
Column Delimiter: Comma {,}
Text qualifier: " (manually set)
Header rows to skip: 0
Column Width: 100
Column Type: DT_STR
My File has the following columns:
Year, Lg..., Div Finish, Playoffs, PF, PA...OSRS, DSRS
I wish to only retrieve:
Year, Lg..., Div Finish, Playoffs
But instead of:
|2015,'NFL',...,'2nd of 4',NULL,...,-4,0.3
|2014,'NFL',...,'3rd of 4',NULL,...,0.6,-4.4
The SSIS package would fail with a message similar to this:
[NFL_Team_List [52]] Error: Data conversion failed. The data conversion for column "Playoffs" returned status value 4 and status
text "Text was truncated or one or more characters had no match in the
target code page.".
However, looking at the data that did go through a couple of times, I
notice the following:
|2015,'NFL',...,'2nd of 4','339,345,-6,Quinn,Jones,Ryan...'
|2014,'NFL',...,'3rd of 4','299,422,-123,Reeves Phillips,Brooking...'
So the problem was on my delimiters are not acting like delimiters! Even though I set the Text Qualifier setting, it seems that SSIS is unable to actually enforce this rule in the dynamic FOREACHLOOP, leading to the issue.
QUESTIONS:
Why is this the case?
How can I get the Text Qualifier to work as designed?
A:
You've set your text qualifier to " but it is actually '
|
[
"stackoverflow",
"0028397473.txt"
] | Q:
Stop Sublime Text from executing infinite loop
When I do something like
while True:
print('loop')
and execute that code in sublime I am not able to stop it. I have to manually kill the process and restart sublime.
Is there a way of setting some kind of 'max_execution_time' or any other workaround which allow us to stop this nicely?
A:
You want to use Ctrl+Break. For your own information, just go check under Tools in Sublime Text and you'll see Cancel Build and the above hotkey. It'll work just fine for infinite loops. Suffice to say, I've had the same happen! ;)
For Windows users, there is no Break key, so go into Preferences>Key Bindings and change the line
{ "keys": ["ctrl+break"], "command": "cancel_build" }
to a different shortcut, such as Ctrl+Alt+B
A:
For me (on Linux), there is no break key on the keyboard and this shortcut was somehow bound to a different combination: ctrl+alt+c.
You can find where it is bound in the Tools menu:
After interrupting your script you should see the text [Cancelled] printed to the sublimetext console.
|
[
"stackoverflow",
"0045232591.txt"
] | Q:
Update column with part of the data from column of another table in another database with intermediate tables
I have a table Tab1 in database DB1:
col1 | col2
--------------
'abc-1' | 11
'abc-2' | 22
'abc-3' | 33
null | 44
null | 55
I want to update col1 column from this table with data from column col3 from another table (Tab2) in another database (DB2):
col3 | col4 | col5
---------------------
'abc-1' | 1 | 10
'abc-1' | 2 | 10
'abc-2' | 1 | 20
'abc-3' | 1 | 30
'abc-3' | 2 | 30
'abc-3' | 3 | 30
'abc-4' | 1 | 40
'abc-5' | 2 | 60
(Data in col1 always comes from col3 only.)
The tables are connected through two intermediate tables: DB1.Tab3:
col6 | col7
----------------
'abc-001' | 11
'abc-002' | 22
'abc-003' | 33
'abc-004' | 44
and DB2.Tab4:
col8 | col9
----------------
10 | 'abc-001'
20 | 'abc-002'
30 | 'abc-003'
40 | 'abc-004'
50 | 'abc-005'
Now, col3 values may repeat (while being identified by id value) and this is the tricky part. Assuming that all values that are missing in col1 do not repeat in col3, this is how I update the column:
update DB1.Tab1 as T1
inner join
DB1.Tab3 as T3 ON T3.col7 = T1.col2
inner join
DB2.Tab4 as T4 ON T4.col9 = T3.col6
inner join
DB2.Tab2 as T2 ON T2.col5 = T4.col8
set
T1.col1 = T2.col3
where
T1.col1 is null;
This also works for repeated values in general - but I only want to update col1 when col3 values do not repeat, that is, in this case with values abc-2, abc-4, abc-5. This is how I select single col3 values (relevant for update):
select
col3
from
DB2.Tab2 as T2
inner join
DB2.Tab4 as T4 ON T2.col5 = T4.col8
inner join
DB1.Tab3 as T3 ON T4.col9 = T3.col6
inner join
DB1.Tab1 as T1 ON T3.col7 = T1.col2
where
T1.col1 is null
and T1.col2 is not null
group by col3
having count(*) = 1;
The question is: how do I update col1 with col3 only with col3 values that does not repeat?
EDIT. This almost works:
update DB1.Tab1 as T1,
(select
col3
from
DB2.Tab2 as T2
inner join DB2.Tab4 as T4 ON T2.col5 = T4.col8
inner join DB1.Tab3 as T3 ON T4.col9 = T3.col6
inner join DB1.Tab1 as T1 ON T3.col7 = T1.col2
where
T1.col1 is null
and T1.col2 is not null
group by col3
having count(*) = 1) as T2d
set
T1.col1 = T2d.col3
where
T1.col1 is null;
but it updates all empty col1 values with only one col3 value - the first one resulting from the select query. I think there is something missing in the where clause but I cannot formulate an appropriate condition.
A:
I have found the solution. The problem was quite complex but the answer turned out to be simple after thinking it through.
My update statement that almost worked was lacking an additional condition in select statement and where clause.
update DB1.Tab1 as T1,
(select
col3, T1.col2 as T1c2
from
DB2.Tab2 as T2
inner join DB2.Tab4 as T4 ON T2.col5 = T4.col8
inner join DB1.Tab3 as T3 ON T4.col9 = T3.col6
inner join DB1.Tab1 as T1 ON T3.col7 = T1.col2
where
T1.col1 is null
and T1.col2 is not null
group by col3
having count(*) = 1) as T2d
set
T1.col1 = T2d.col3
where
T1.col1 is null
and T1.col2 = T1c2;
The solution comes down to selecting yet another column from the table to be updated (T1.col2), and specifically the values for which T1.col1 should be updated, then compare each T1.col2 with the previously selected ones.
However the mechanism behind it isn't clear to me, specifically why update statement without this edit would update all fields with only one value, so comments are still appreciated.
|
[
"mathematica.stackexchange",
"0000190691.txt"
] | Q:
Complex partial fraction expansion
I would like to have a tool for partial fraction expansion of polynomial quotient
$$\frac{P(z)}{Q(z)},$$
where the order of the polynomial $P(z)$ is less than that of $Q(z)$.
The output of the function is expected to be the coefficients $c_{ij}$ of the expansion:
$$
\sum_i\sum_{j=1}^{m_i}\frac{c_{ij}}{(z-\zeta_i)^j},
$$
where the sum runs over all distinct roots $\zeta_i$ (with multiplicity $m_i$) of the polynomial $Q(z)$.
Is there a built-in function in Mathematica which is suitable for performing the task? For a symbolic computation the list of roots of the polynomial $Q(z)$ can be supplied.
A:
We can factor the denominator completely and feed the result into Apart:
FullApart[expr_, x_] :=
Block[{num, den, coeff, roots},
{num, den} = Through[{Numerator, Denominator}[Together[expr]]];
(
coeff = Coefficient[den, x, Exponent[den, x]];
roots = x /. Solve[den == 0, x];
Apart[num/(coeff Times @@ (x - roots)), x]
) /; PolynomialQ[num, x] && PolynomialQ[den, x]
]
Some examples:
FullApart[(x^2 + 3 x + 1)/(x^2 + 3 x - 5)^2, x]
$\displaystyle \scriptsize -\frac{34}{29 \sqrt{29} \left(2 x+\sqrt{29}+3\right)}+\frac{24}{29 \left(2
x+\sqrt{29}+3\right)^2}-\frac{34}{29 \sqrt{29} \left(-2
x+\sqrt{29}-3\right)}+\frac{24}{29 \left(-2 x+\sqrt{29}-3\right)^2}$
FullApart[(x^2 + 3 x + 1)/(x^5 + 3 x - 5), x] // N // Chop
$\scriptsize {\displaystyle -\frac{0.329077\, -0.0459113 i}{x-0.639573\, -1.20691 i}}-{\displaystyle \frac{0.329077\, +0.0459113i}{x-0.639573\, +1.20691 i}}+{\displaystyle \frac{0.0658591\, -0.0529159 i}{x+1.19386\, -0.996095i}}+{\displaystyle \frac{0.0658591\, +0.0529159 i}{x+1.19386\, +0.996095i}}+{\displaystyle \frac{0.526436}{x-1.10858}}$
|
[
"stackoverflow",
"0050717257.txt"
] | Q:
Ajax call to insert to database not working
I'm trying to do an Ajax call on button click to insert to a database through a PHP file. I want to use AJAX to achieve this, but it does not show the alert dialog on success nor does it insert the data to the database. Here is the code I have:
AjaxTest.html:
<button type="button" onclick="create()">Click me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
function create () {
$.ajax({
url: "AjaxTestRegistration.php",
type: "POST",
data: {
'bid': 10,
'kid': 20
},
success: function (msg) {
alert("!");
}
});
}
</script>
AjaxTestRegistration.php:
<?php
include "connection.php";
include "Coupon.php";
$bid = $_GET['bid'];
$kid = $_GET['kid'];
Coupon::insertCoupon($bid, $kid);
?>
If I try to enter AjaxTestRegistration.php manually in the browser like this: ajaxtestregistration.php?kid=10&bid=5, the row gets inserted into the database.
wWhat could be the problem with this code? How to rectify that?
A:
Your PHP handles GET requests.
$bid = $_GET['bid'];
But your ajax function tries to POST
type: "POST",
The easiest here is to get your data by $_POST in php.
|
[
"stackoverflow",
"0044823599.txt"
] | Q:
Finding the difference between two time values iOS objective c
I am trying to subtract two different time values
**Aim:-**i want to subtract the value get the difference between two time which I get from server
below is my method
self.start=[jsonDict valueForKey:@"start_time"];
self.end=[jsonDict valueForKey:@"end_time"];
self.datefj=[jsonDict valueForKey:@"date"];
NSLog(@"%@",self.start);
NSLog(@"%@",self.end);
NSLog(@"%@",self.datefj);
self.date1fj=[NSString stringWithFormat:@"%@ %@",self.datefj,self.start];
self.date2fj=[NSString stringWithFormat:@"%@ %@",self.datefj,self.end];
//NSTimeInterval secondsBetween = [_end timeIntervalSinceDate:_start];
//NSArray *hoursMins = [_end componentsSeparatedByString:@":"];
//NSInteger timeInMins = [hoursMins[0] intValue] * 60 + [hoursMins[1] intValue];
NSDateFormatter *df=[[NSDateFormatter alloc] init];
// Set the date format according to your needs
[df setDateFormat:@"dd/MM/YYYY hh:mm"]; //for 12 hour format
//[df setDateFormat:@"MM/dd/YYYY HH:mm "] // for 24 hour format
NSDate *date1 = [df dateFromString:_date1fj];
NSDate *date2 = [df dateFromString:_date2fj];
NSLog(@"%@",date1);
NSLog(@"%@",date2);
NSLog(@"%f is the time difference",[date2 timeIntervalSinceDate:date1]);
}
and this is the data that I get from server and I want the difference between start time and end time
2017-06-29 16:37:50.543 Barebones[4204:233648] requestReply cust category: {
date = "29-6-2017";
"end_time" = "17:45";
"market_crash" = true;
"start_time" = "14:28";
}
below is my nslog details
2017-06-29 16:37:50.543 Barebones[4204:233648] true
2017-06-29 16:37:53.482 Barebones[4204:233648] 14:28
2017-06-29 16:37:53.483 Barebones[4204:233648] 17:45
2017-06-29 16:37:53.483 Barebones[4204:233648] 29-6-2017
2017-06-29 16:37:58.493 Barebones[4204:233648] (null)
2017-06-29 16:37:58.494 Barebones[4204:233648] (null)
2017-06-29 16:45:47.514 Barebones[4204:233648] 0.000000 is the time difference
thanks in advance!!:)
A:
Try below code
[date1 timeIntervalSinceReferenceDate] - [date2 timeIntervalSinceReferenceDate];
This will work :)
A:
The problem is in Your Date Formatter. I tried your code like this and it worked fine for me.
NSString * start = @"14:28";
NSString * end = @"17:45";
NSString * datefj = @"29-6-2017";
NSString *date1fj =[NSString stringWithFormat:@"%@ %@",datefj,start];
NSString *date2fj =[NSString stringWithFormat:@"%@ %@",datefj,end];
NSDateFormatter *df=[[NSDateFormatter alloc] init];
// Set the date format according to your needs
//[df setDateFormat:@"dd-mm-yyyy hh:mm"]; //for 12 hour format
[df setDateFormat:@"dd-MM-YYYY HH:mm "]; // for 24 hour format
NSDate *date1 = [df dateFromString:date1fj];
NSDate *date2 = [df dateFromString:date2fj];
NSLog(@"%@",date1);
NSLog(@"%@",date2);
NSLog(@"%f is the time difference",[date2 timeIntervalSinceDate:date1]/60);
// Edit For Getting The time in Proper format
NSString *formattedTime = [self timeFormatted:[date2 timeIntervalSinceDate:date1]/60];
// Create a new function
- (NSString *)timeFormatted:(int)totalSeconds
{
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
}
|
[
"rpg.stackexchange",
"0000004945.txt"
] | Q:
Skill Checks in 4e -- specific help
For the purposes of this question, please assume that I have four characters in play. They all have "Acrobatics" skill. They are 1st, 5th, 10th, and 15th levels respectively.
They are in a bar and they want to swing on exactly the same chandelier to impress a fair maiden on the other side of the room.
What is the difficulty class for the swing? Why?
What if all the characters were the same level?
What is the difficulty class for the swing? Why?
[EDITS]
I'm trying to ascertain, in 4e, whether the DCs change with the character or with the situation. In other words, does the difficulty of the swing depend on the chandelier -- its the same for everyone; or does it depend on the character -- there's a sliding scale?
A:
It depends on the chandelier, the maiden, and the level of a typical character who would do such a thing. If impressing this fair maiden by swinging on this chandelier should be hard for a 1st level character, its DC is 19. If it should be medium difficulty for a 5th level character (since she's the governor's daughter and a bit out of a f1st level character's league), the DC is 15.
level easy med hard
1 8 12 19
5 10 15 22
10 13 18 26
15 15 22 30
Numbers (and a very good description) from here. Thanks @Brian for the link!
Once the DC is chosen, anyone can attempt it, though. If the PCs are trying to be diplomatic, but are in over their heads (i.e. 3rd level characters vs 8th level diplomats), pick the DC as easy for an 8th level character (DC 12) just for them to keep up with the negotiations.
Someone who is trained and has a good attribute score (16) will succeed automatically on Easy tasks for their level. (i.e. Easy DC = 1/2 level + trained(5) + bonus(3)) That same character will succeed on medium difficulty more than 2/3 of the time and succeed on hard difficulty around half of the time. (Note that medium and hard scales assumes that the relevant attributes are going up with the level increases at 4th, 8th, etc. since that's what the character is good at.)
For your example, let's describe the challenge for each of the 4 levels you reference:
a young woman with 1 level of Fair Maiden
the governor's daughter (a level 5 encounter)
a 10th level socialite (and it must be a high class tavern!)
the duchess (at level 15)
NOTE: I'm using the levels in the description to describe the level for which the interaction is normed. I am NOT saying that all NPCs that the characters interact with need to be of the their level!
To interpret the results:
Easy: you didn't make a fool of yourself
Med: you did well and she'd probably talk to you
Hard: Wow. She's impressed!
So a Fighter, a Wizard, a Monk, and Vin Diesel walk into a bar.
The 1st level Fighter rolls a 2. She has an Acrobatics bonus of +8 (0+5+3), so she can't make a fool of herself in front of her peers. In front of the socialite or the Duchess, though, she'd be completely embarrassed and lose face.
The wizard rolls a 16 to jump to the chandelier. At 5th level he's got a +3 bonus (2+0+1) since he has a 13 dexterity. The governor's daughter would talk to him, but even with that great roll, he didn't wow her. The young woman would be wowed, and luckily he even wouldn't have made a fool of himself in front of the Duchess.
The 10th level Monk makes an Acrobatics check to swing across the room. She rolls an 11 and adds her bonus of 15(5+5+5) for a 26. Even though it's about average for her, she could be in the circus and the socialite invites her to all her fancy parties. Everybody is wowed, except for the Duchess who sees that kind of stuff all them time.
Vin Diesel enters and he doesn't need to roll. The bartender just gives him a drink and everyone swoons. Since he's got a modifier of +29(10+5+6+racial and inherent bonuses!) it's an automatic success, even against the Duchess. He's that good. She'd definitely want to talk to him, but he'd just want to drink his drink in silence.
A:
Your question is unanswerable, as we don't know the nature of the bar. The DC of interactions is a function of the environment, not the characters. The characters, however, usally inform the environment by adventuring in level specific areas.
In a bar like this, it is up to the DM to determine who is the "appropriate" level for the bar, and then based on the intrinsic difficulty of the task relative to intended level, assign a DC, as discussed here. The players will not experience different DCs for the same activity, though they can be presented with different DCs to demonstrate their level of skill
For simple DCs by level, look here. And for another discussion of the scaling nature of difficulties, here.
|
[
"stackoverflow",
"0019239096.txt"
] | Q:
C++ (CAS-like) synchronization on getter and setter of user defined types
Suppose there is a user defined class MyClass that has a setter and a getter function.
class MyClass {
int m_value;
public:
void set(int value)
{ m_value = value; }
int get() const
{ return m_value;}
};
And there is a function increment() that can increase the value of the object by 1, which may be invoked in multiple threads.
void increment(MyClass& myClass)
{
myClass.set(myClass.get() + 1);
}
What is the best way to make this function thread-safe? By just using a lock? Is there any way to achieve it by using some CAS-like operations?
A:
If you're using C++11, you could just use std::atomic<int> which provides atomic load, store and increment which seems to be everything you need.
I suspect you don't need atomics though as in most cases they will be slower than your basic mutex.
See this other question before you make your decision.
|
[
"stats.stackexchange",
"0000105602.txt"
] | Q:
Example of how the log-sum-exp trick works in Naive Bayes
I have read about the log-sum-exp trick in many places (e.g. here, and here) but have never seen an example of how it is applied specifically to the Naive Bayes classifier (e.g. with discrete features and two classes)
How exactly would one avoid the problem of numerical underflow using this trick?
A:
In
$$
p(Y=C|\mathbf{x}) = \frac{p(\mathbf{x}|Y=C)p(Y=C)}{~\sum_{k=1}^{|C|}{}p(\mathbf{x}|Y=C_k)p(Y=C_k)}
$$
both the denominator and the numerator can become very small, typically because the $p(x_i \vert C_k)$ can be close to 0 and we multiply many of them with each other. To prevent underflows, one can simply take the log of the numerator, but one needs to use the log-sum-exp trick for the denominator.
More specifically, in order to prevent underflows:
If we only care about knowing which class $(\hat{y})$ the input $(\mathbf{x}=x_1, \dots, x_n)$ most likely belongs to with the maximum a posteriori (MAP) decision rule, we don't have to apply the log-sum-exp trick, since we don't have to compute the denominator in that case. For the numerator one can simply take the log to prevent underflows: $log \left( p(\mathbf{x}|Y=C)p(Y=C) \right) $. More specifically:
$$\hat{y} = \underset{k \in \{1, \dots, |C|\}}{\operatorname{argmax}}p(C_k \vert x_1, \dots, x_n)
= \underset{k \in \{1, \dots, |C|\}}{\operatorname{argmax}} \ p(C_k) \displaystyle\prod_{i=1}^n p(x_i \vert C_k)$$
which becomes after taking the log:
$$
\begin{align}
\hat{y} &= \underset{k \in \{1, \dots, |C|\}}{\operatorname{argmax}} \log \left( p(C_k \vert x_1, \dots, x_n) \right)\\
&= \underset{k \in \{1, \dots, |C|\}}{\operatorname{argmax}} \log \left( \ p(C_k) \displaystyle\prod_{i=1}^n p(x_i \vert C_k) \right) \\
&= \underset{k \in \{1, \dots, |C|\}}{\operatorname{argmax}} \left( \log \left( p(C_k) \right) + \ \displaystyle\sum_{i=1}^n \log \left(p(x_i \vert C_k) \right) \right)
\end{align}$$
If we want to compute the class probability $p(Y=C|\mathbf{x})$, we will need to compute the denominator:
$$ \begin{align}
\log \left( p(Y=C|\mathbf{x}) \right)
&= \log \left( \frac{p(\mathbf{x}|Y=C)p(Y=C)}{~\sum_{k=1}^{|C|}{}p(\mathbf{x}|Y=C_k)p(Y=C_k)} \right)\\
&= \log \left( \underbrace{p(\mathbf{x}|Y=C)p(Y=C)}_{\text{numerator}} \right) - \log \left( \underbrace{~\sum_{k=1}^{|C|}{}p(\mathbf{x}|Y=C_k)p(Y=C_k)}_{\text{denominator}} \right)\\
\end{align}
$$
The element $\log \left( ~\sum_{k=1}^{|C|}{}p(\mathbf{x}|Y=C_k)p(Y=C_k) \right)\\ $ may underflow because $p(x_i \vert C_k)$ can be very small: it is the same issue as in the numerator, but this time we have a summation inside the logarithm, which prevents us from transforming the $p(x_i \vert C_k)$ (can be close to 0) into $\log \left(p(x_i \vert C_k) \right)$ (negative and not close to 0 anymore, since $0 \leq p(x_i \vert C_k) \leq 1$). To circumvent this issue, we can use the fact that $p(x_i \vert C_k) = \exp \left( {\log \left(p(x_i \vert C_k) \right)} \right)$ to obtain:
$$\log \left( ~\sum_{k=1}^{|C|}{}p(\mathbf{x}|Y=C_k)p(Y=C_k) \right) =\log \left( ~\sum_{k=1}^{|C|}{} \exp \left( \log \left( p(\mathbf{x}|Y=C_k)p(Y=C_k) \right) \right) \right)$$
At that point, a new issue arises: $\log \left( p(\mathbf{x}|Y=C_k)p(Y=C_k) \right)$ may be quite negative, which implies that $ \exp \left( \log \left( p(\mathbf{x}|Y=C_k)p(Y=C_k) \right) \right) $ may become very close to 0, i.e. underflow. This is where we use the log-sum-exp trick:
$$\log \sum_k e^{a_k} = \log \sum_k e^{a_k}e^{A-A} = A+ \log\sum_k e^{a_k -A}$$
with:
$a_k=\log \left( p(\mathbf{x}|Y=C_k)p(Y=C_k) \right)$,
$A = \underset{k \in \{1, \dots, |C|\}} \max a_k.$
We can see that introducing the variable $A$ avoids underflows. E.g. with $k=2, a_1 = - 245, a_2 = - 255$, we have:
$\exp \left(a_1\right) = \exp \left(- 245\right) =3.96143\times 10^{- 107}$
$\exp \left(a_2\right) = \exp \left(- 255\right) =1.798486 \times 10^{-111}$
Using the log-sum-exp trick we avoid the underflow, with $A=\max ( -245, -255 )=-245$:
$\begin{align}\log \sum_k e^{a_k} &= \log \sum_k e^{a_k}e^{A-A} \\&= A+ \log\sum_k e^{a_k -A}\\ &= -245+ \log\sum_k e^{a_k +245}\\&= -245+ \log \left(e^{-245 +245}+e^{-255 +245}\right) \\&=-245+ \log \left(e^{0}+e^{-10}\right) \end{align}$
We avoided the underflow since $e^{-10}$ is much farther away from 0 than $3.96143\times 10^{- 107}$ or $1.798486 \times 10^{-111}$.
|
[
"stackoverflow",
"0001734808.txt"
] | Q:
How to adjust speaker volume from Java program?
I'm running Win Vista, at the lower right side of the window there is a speaker icon next to the clock, I can click on it and adjust the volume, I wonder if there is a way in my Java program to do this automatically?
For instance, when my Java program starts, it turns the volume to 80, and when the program exits, it changes the volume back to the original level. I don't mind using Runtime.getRuntime().exec() if there is a way to achieve this effect.
A:
I used the following code to simulate a volume adjustment :
Robot robot; // Set speaker volume to 80
try
{
robot=new Robot();
robot.mouseMove(1828,1178);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.delay(90);
robot.mouseMove(1828,906);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.delay(260);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
catch (AWTException ex)
{
System.err.println("Can't start Robot: " + ex);
System.exit(0);
}
And it worked !
|
[
"stackoverflow",
"0054804047.txt"
] | Q:
Blank space bottom of text when using font family
I face an issue when I apply font family for my Text component as the image below
As you can see, my text cannot align center itself (red area is my default Text component, without any margin or padding).
I think this issue comes from my font (TradeGothicLTStd-BdCn2) because when I change the font, I don't see this issue anymore.
Here is my style for this component
dropdownCurrentText: {
fontFamily: Fonts.type.TradeGothicLTStdBold,
fontSize: 14,
justifyContent: 'center',
textAlign: 'center',
color: Colors.black,
letterSpacing: 0.2
},
Does any suggestion to resolve this within keeping above font? any response would be appreciated.
P.S It's not happening on Android platform, only iOS
A:
Finally, I find out the solution for my issue, thank for another answer.
That is using Font Tool for XCode, you guys can read this article for more detail https://medium.com/@martin_adamko/consistent-font-line-height-rendering-42068cc2957d
|
[
"stackoverflow",
"0011759628.txt"
] | Q:
deleting variables by specifying id value with OFFSET
I want to delete specific variables based on 'id' value. but the code below is displaying syntax error near: OFFSET 1. I use a similar code where I use SELECT instead of DELETE and it works fine, What am doing wrong here? Thanks
DELETE FROM users WHERE name = '$name' ORDER BY id ASC LIMIT 1 OFFSET 1
A:
The offset component in LIMIT is not available in MySQL DELETE statements but it is allowed in SELECT statements.
So what you can do to get around this fact, is you can actually join a subselect in a DELETE operation, which will then give you your desired results:
DELETE a FROM users a
INNER JOIN
(
SELECT id
FROM users
WHERE name = '$name'
ORDER BY id
LIMIT 1,1
) b ON a.id = b.id
|
[
"stackoverflow",
"0009967790.txt"
] | Q:
Enum instance for tuples in Haskell
I'd like to define a tuple (x, y) as an instance of Enum class, knowing that both x and y are instances of Enum. A following try:
instance (Enum x, Enum y) => Enum (x, y) where
toEnum = y
enumFrom x = (x, x)
only results in error (y not in scope). I'm new to Haskell, could somebody explain how to declare such an instance?
A:
instance (Enum x, Enum y) => Enum (x, y) where
In the above line, x and y are both types (type variables).
toEnum = y
enumFrom x = (x, x)
In the above two lines, x and y are both values ((value) variables). y-as-a-value has not been defined anywhere, that's what it not being in scope means.
As to how to declare such an instance, I'm not sure how you'd want fromEnum and toEnum to behave, for example.
|
[
"stackoverflow",
"0056296732.txt"
] | Q:
How to position a popup based on the cursor click (without using jQuery)?
I am trying to create a Firefox extension, where I want a popup to appear next to some text which is double clicked. As I am placing this code as my extension's content script which will be loaded on ANY website, I have tried to not use jQuery for this task.
I have seen and implemented the answers given in the links: How to position popover over a highlighted portion of text?
How to position a popup div based on the position of where the cursor clicks
Using mouse/cursor coordinates to position popup
Unfortunately most of these answers were in jQuery. I have tried replacing them to a pure DOM implementation and have come up with the following code:
function doSomethingWithSelectedText(obj) {
var textObj = getSelectedTextObj();
if (textObj.toString() && textObj.toString().trim().split(" ").length <= 2) {
var NewPara = document.createElement("div");
NewPara.setAttribute("id", "infoDiv");
NewPara.setAttribute("class", "tooltipDiv");
NewPara.appendChild(document.createTextNode(textObj.toString().trim()));
if (document.getElementsByClassName("tooltipDiv").length) {
var OldPara = document.getElementById("infoDiv");
document.body.replaceChild(NewPara, OldPara);
}
else {
document.body.appendChild(NewPara);
}
document.getElementById("infoDiv").style.display = "block";
document.getElementById("infoDiv").style.width = "250px";
document.getElementById("infoDiv").style.zIndex = "101";
document.getElementById("infoDiv").style.backgroundColor = "#F5DEB3";
document.getElementById("infoDiv").style.border = "3px solid #666";
document.getElementById("infoDiv").style.padding = "12px 12px 12px 12px";
document.getElementById("infoDiv").style.borderRadius = "0px 0px 25px 0px";
document.getElementById("infoDiv").style.position = "absolute";
var oRect = textObj.getRangeAt(0).getBoundingClientRect();
var leftOffset, topOffset;
var pageWidth, pageHeight;
var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0],
pageWidth = w.innerWidth || e.clientWidth || g.clientWidth,
pageHeight = w.innerHeight|| e.clientHeight|| g.clientHeight;
leftOffset = oRect.left + oRect.width + 1 + 12;
if (300 + leftOffset > pageWidth - 12) {
leftOffset = pageWidth - 350 - 12;
}
topOffset = oRect.top;
if (topOffset + 12 > pageHeight) {
topOffset -= 12;
}
leftOffset += window.scrollX;
topOffset += window.scrollY;
document.getElementById("infoDiv").style.left = leftOffset;
document.getElementById("infoDiv").style.top = topOffset;
}
else {
document.getElementById("infoDiv").style.display = "none";
};
};
The issue with the above code is that the popup is not displayed next to the text which is double clicked, instead it sometimes appears below and sometimes above the screen. I have tried positioning div at various places and replacing clientX, clientY with pageX, pageY but nothing seems to work. I strongly believe that the problem is with the node NewPara and it's position, but I am unable to determine it.
UPDATE: Modified the code but initial problem still persists.
A:
There are two major issues which will fix the popup's display position.
First is the document.body should be replaced with document.documentElement as to put the scope outside the body tag and into the html tag.
The next and major issue is with the leftOffset and topOffset. Both of them are never converted to px, hence they are never rendered by the browser.
To prevent that use String(leftOffset) + "px" and String(topOffset) + "px".
Here is the modified code:
function doSomethingWithSelectedText(obj) {
var textObj = getSelectedTextObj();
if (textObj.toString() && textObj.toString().trim().split(" ").length <= 2) {
var NewPara = document.createElement("div");
NewPara.setAttribute("id", "infoDiv");
NewPara.setAttribute("class", "tooltipDiv");
NewPara.appendChild(document.createTextNode(textObj.toString().trim()));
if (document.getElementsByClassName("tooltipDiv").length) {
var OldPara = document.getElementById("infoDiv");
document.documentElement.replaceChild(NewPara, OldPara);
}
else {
document.documentElement.appendChild(NewPara);
}
var oRect = textObj.getRangeAt(0).getBoundingClientRect();
var leftOffset, topOffset;
var pageWidth, pageHeight;
var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0],
pageWidth = w.innerWidth || e.clientWidth || g.clientWidth,
pageHeight = w.innerHeight|| e.clientHeight|| g.clientHeight;
leftOffset = oRect.left + oRect.width + 1 + 12;
if (300 + leftOffset > pageWidth - 12) {
leftOffset = pageWidth - 350 - 12;
}
topOffset = oRect.top;
if (topOffset + 12 > pageHeight) {
topOffset -= 12;
}
leftOffset += window.scrollX;
topOffset += window.scrollY;
document.getElementById("infoDiv").style.display = "block";
document.getElementById("infoDiv").style.width = "250px";
document.getElementById("infoDiv").style.zIndex = "101";
document.getElementById("infoDiv").style.backgroundColor = "#F5DEB3";
document.getElementById("infoDiv").style.border = "3px solid #666";
document.getElementById("infoDiv").style.padding = "12px 12px 12px 12px";
document.getElementById("infoDiv").style.borderRadius = "0px 0px 25px 0px";
document.getElementById("infoDiv").style.position = "absolute";
document.getElementById("infoDiv").style.left = String(leftOffset) + "px";
document.getElementById("infoDiv").style.top = String(topOffset) + "px";
}
else {
document.getElementById("infoDiv").style.display = "none";
};
};
This fixes the position issue.
|
[
"stackoverflow",
"0044750318.txt"
] | Q:
How to stop spacebar from triggering click effect on a button?
I have created a jframe and i have added a button which, after it get clicked, it asks u to press any button, which also displays on the button.
(its displays should go like this -> "Click Me" -> "Press Any Button" -> "Space Bar")
My problem no.1 is that, i dont want to go from "Click Me" to "Press Any Button" by pressing the spacebar.
And my problem no.2 is that, when i am at "Press Any Button" and i press spacebar, on release, it goes back to "Press Any Button" instead of staying at "Space Bar".
Here is my code.
public class Test {
/**
* @param args the command line arguments
*/
static class starton implements ActionListener {
private JButton button;
private JFrame frame;
public starton(JButton button, JFrame frame) {
this.button = button;
this.frame = frame;
}
public void actionPerformed(ActionEvent e) {
button.setText("Press A Button");
button.setSize(button.getPreferredSize());
button.addKeyListener(
new KeyListener() {
@Override
public void keyPressed(KeyEvent e){
String text = null;
char a = e.getKeyChar();
text = ""+a+"";
if (a == ' '){
text = "Space Bar";
}
button.setText(""+text+"");
button.setSize(button.getPreferredSize());
button.removeKeyListener(this);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent ke) {
}
});
}
}
public static void main(String[] args) throws IOException {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
int frame1w = 600;
int frame1h = 400;
JFrame frame1 = new JFrame("Foo");
frame1.setSize(frame1w, frame1h);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
frame1.setContentPane(contentPane);
JButton button1 = new JButton("Click Me");
button1.setSize(button1.getPreferredSize());
button1.addActionListener(new starton(button1, frame1));
// add more code here
contentPane.add(button1);
frame1.setVisible(true);
}
}
A:
The JButton installs a series of key bindings to control user input
You can inspect what these are using something like...
JButton btn = new JButton("Test");
InputMap im = btn.getInputMap();
for (KeyStroke ik : im.allKeys()) {
System.out.println(ik + " = " + im.get(ik));
}
On my system, it prints
pressed SPACE = pressed
released SPACE = released
This tells me that the Space key is bound to the action keys pressed and released
In order to disable these keys, you need to provide your own binding...
Action blankAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
}
};
ActionMap am = btn.getActionMap();
am.put("pressed", blankAction);
am.put("released", blankAction);
This just replaces the pressed and released bindings with a empty Action which does nothing.
Now, a word of warning - key bindings can be different on different platforms/look and feels; You should also beware that users often have a pre-defined expectation of what certain controls can and can't do, changing them will affect how they react to you program
As to your second problem, the button is still using the same ActionListener you originally registered, so whenever you press Space, it's triggering the ActionListener again, and adding a new KeyListener which is going to compound your problems
You either want to use a separate ActionListener for both buttons or you want to remove the ActionListener from the button when it's first triggered - I'd go for the second, it's easier to understand the code
no, i mean, if i disable the "press" for spacebar, would i be able to press it when i am at "Press Any Button"?
The simplest solution would be to use two different buttons, one with an ActionListener which set up the other button, which had a KeyListener attached to it.
If, for some reason you "really" don't want to do that, then you need to remove the ActionListener from the button when it's first triggered
static class starton implements ActionListener {
//...
public void actionPerformed(ActionEvent e) {
button.setText("Press A Button");
button.setSize(button.getPreferredSize());
button.addKeyListener(...);
button.removeActionListener(this);
}
}
|
[
"stackoverflow",
"0030103673.txt"
] | Q:
How can i create a cascading md-select with angularjs?
I have JSON like this,
$scope.analytics = {
'Twitter': [
'Following',
'Followers',
'Tweets'
],
'Facebook': [
'People engaged',
'Likes',
'Clicks',
'Views'
],
'LinkedIn': [
'Overview'
]
};
From the above, I need to create a cascading md-select , First md-select should have Twitter,Facebook and Linkedin.
OnChanging Twitter, it should display the Following,Followers,Tweets in the next md-select.
HTML:
<md-select ng-model="type" >
<md-option ng-value="t" data-ng-repeat="t in analytics">{{ t }}</md-option>
</md-select>
<md-select ng-model="metrics" >
<md-option ng-value="t" data-ng-repeat="t in analytics">{{ t }}</md-option>
</md-select>
App.JS:
app.controller('MainCtrl', function($scope) {
$scope.analytics = {
'Twitter': [
'Following',
'Followers',
'Tweets'
],
'Facebook': [
'People engaged',
'Likes',
'Clicks',
'Views'
],
'LinkedIn': [
'Overview'
]
};
});
Here is my code in Cascading md-select
A:
The key to solving this is to place a watch on the value of the first select and control the options of the second. Also remember to clear the dependent selection, when the master selection changes!
A sample implementation:
Add a level2 variable in the scope. It will hold the options of the dependent select.
Place the watch on the first model:
$scope.$watch('type', function(newval, oldval) {
if( newval ) {
$scope.level2 = $scope.analytics[newval];
}
else {
$scope.level2 = [];
}
// delete the dependent selection, if the master changes
if( newval !== oldval ) {
$scope.metrics = null;
}
});
Finally the markup needs a little tweaking to display correctly:
<md-select ng-model="type" >
<md-option ng-value="k" data-ng-repeat="(k,v) in analytics">{{ k }}</md-option>
</md-select>
<md-select ng-model="metrics" >
<md-option ng-value="t" data-ng-repeat="t in level2">{{ t }}</md-option>
</md-select>
See a forked plunk: http://plnkr.co/edit/rI3AsC2plZ3w82WRBjAo?p=preview
|
[
"aviation.stackexchange",
"0000019270.txt"
] | Q:
How does CDI work when flying to VOR without DME?
Let's show what I mean on an example.
Flying towards a VOR (not knowing the distance), HSI course pointer pointing
towards the VOR. Let's say the plane is really far from the VOR and we turn
the course pointer 5 degrees (no matter what way) CDI will move to one side
(far because of the distance). If the plane was close to the VOR and we turned
the course pointer 5 degrees CDI would not move as much (or should not because the
deviation is really small).
based on this example CDI needs to know distance from VOR to work properly, yet it works without knowing the distance. How?
(If I'm wrong about something, quickly correct me)
A:
The VOR and ILS CDI indicates difference, in degrees, between the radial selected and the radial sensed.
If the plane was far from the VOR and we turn the course pointer 5 degrees, the CDI will move to one side. If the plane was close to the VOR and we turned the course pointer 5 degrees, the CDI would move exactly as much, because it indicates the angular difference in degrees.
This is in contrast to a CDI slaved to GPS, which indeed indicates lateral distance from the selected track in miles (en-route; GPS approach has to simulate ILS).
VOR does nothing with DME. DME is completely independent piece of equipment that was introduced later than VOR. The only relation is that there is a standard correspondence between VOR and DME channels and the DME receiver automatically tunes to the DME frequency corresponding to the VOR or ILS frequency tuned on your VOR/ILS receiver.
A:
The change in "sensitivity" of the CDI needle as you approach a VOR has nothing to do with the DME distance - it depends on your lateral distance from the VOR.
You could be 5 miles straight up from the VOR (showing 5 miles on the DME), but the VOR receiver's sensitivity will depend on your lateral distance from the VOR.
This is because the VOR is displaying a difference in angular position: how many degrees of arc you are away from the desired course. The OBS knob on your CDI is selecting a roughly one-degree wide corridor that you want to be within, which is a pie-shaped wedge around the radial you've selected.
That wedge extends out from the VOR, getting wider as you get further from the station.
To illustrate, look at the 50-degree wide corridor highlighted in yellow below:
This has two practical sets of effects on VOR navigation:
The CDI needle sensitivity varies inversely with distance from the station
Far from the VOR station the CDI needle has low sensitivity: A large variation in position (miles) is a small number of degrees of arc away, so you could be a mile off the centerline of your selected course with the needle still nearly centered.
Close to the VOR station the CDI needle is extremely sensitive and "twitchy" - a tenth of a mile left or right could be full-scale deflection, because it represents being several degrees of arc off course.
VERY Close to the VOR station the CDI needle twitches erratically to the point of being nearly unusable because the VOR decoder in your aircraft can't determine which radial you're actually on. (Shortly after this you will usually fly past the station, and eventually the needle will calm down again.)
The OBS knob sensitivity appears to vary directly with distance from the station
As Jan noted an ideal VOR (transmitter and receiver) would vary the same number of dots of deflection for the same number of degrees dialed on the OBS, whether you're 10 miles from the station or 10 feet. With real world hardware though the OBS knob's sensitivity is also affected by distance from the VOR, but in the opposite way from the CDI needle.
Very Close to the VOR station the distance between each radial gets small enough that they are practically overlapping, and your radio may wind up decoding the VOR signal as indicating any one of those overlapping radials. Spinning the OBS knob appears to have less of an effect here, particularly with mechanical meter-movement CDIs, because the needle is twitching enough that what you're seeing is an average of what's being decoded.
Far from the station - far enough that the VOR receiver can definitively decode which radial it thinks you're on - the CDI appears to be more sensitive: The signal is definitely 065 degrees, and when you change the OBS value to 070 the needle will move to reflect the difference between the selected and detected value, with no erroneous decodings to mess it up. At these distances the VOR behaves more-or-less ideally, as Jan described.
|
[
"superuser",
"0000341729.txt"
] | Q:
Can I safely email a bank account statement?
The receiver will need to access the statement in a cyber cafe from a gmail account and print the statement as well. Would it make sense to encrypt the file or something in this scenario? Should I drop the idea of emailing the bank statement?
A:
You should avoid doing this if possible, unless you are comfortable with unknown third parties seeing your bank statement.
If you have to do it, use encryption, but know that it is quite possible that someone else in that cyber cafe may see it and from there it could be sent anywhere.
In general, never put anything in an e-mail that you are not comfortable with the whole world knowing.
|
[
"math.stackexchange",
"0001088739.txt"
] | Q:
The constraint subset of $H_0^1(\Omega)$ is a $C^1$-submanifold.
This problem comes from the constraint problem in CoV. (the lagrange-multiplier case)
Let $\Omega\subset \mathbb R^N$ be open bounded, smooth boundary. We define the sub-manifold
$$ M:=\{u\in H_0^1(\Omega),\,\,\int_\Omega g(x,u,\nabla u)dx\equiv 0\} $$
where $g(x,u,\xi)$, from $\Omega\times\mathbb R\times\mathbb R^N\to \mathbb R$, is $C^2$.
We denote
$$ g_u(x,u,\xi):=\frac{d}{du}g(x,u,\xi) $$
and
$$ g_\xi(x,u,\xi):=\nabla_\xi g(x,u,\xi) $$
I want to conclude that the set $M$ is of $C^1$-submanifold so that I could apply Lagrange multiplier rule on it. The book, by Struwe, page 15 has a quick but not clear prove for a very specific example but I want to prove a general version.
Here is what I tried and where I got stuck.
First of all, if both $g_u(x,u,\nabla u)$ and $g_\xi(x,u,\nabla u)$ are a.e. $0$ on $\Omega$, then we have set $M$ is entire $H_0^1(\Omega)$ and it is not interesting.
Now, assume one of $g_u(x,u,\nabla u)$ or $g_\xi(x,u,\nabla u)$ is not a.e. $0$ on $\Omega$, then I want to conclude that for every $u\in M$, I have
$$\int_\Omega g_u(x,u,\nabla u)\cdot u\,dx+\int_\Omega g_\xi(x,u,\nabla u)\cdot\nabla u \,dx\neq 0 \tag 1$$
I got stuck on proving $(1)$... I tried the contradiction but it does not work... please help me about this.
Lastly, book states that if $(1)$ hold, then the set $M$ is a $C^1$-submanifold of $H_0^1(\Omega)$ by implicit function theorem. I know what is implicit function theorem but I don't quit see how we applied it here... Please provided me some details. Thank you!
A:
Let $H$ be a Hilbert space and define $M$ by $$M=\{u\in H:\ F(u)=0\},$$
where $F:H\to\mathbb{R}$ is a $C^1(H)$ function.
Theorem: Suppose that for all $u\in M$, $F'(u)\neq 0$. Then, $M$ is a $C^1$ Hilbert Manifold of $H$.
To prove it, fix $u\in H$. Remember that $F':H\to H^\star$, so $F'(u)\neq 0$ means that the linear function $F'(u)$ has non trivial kernel, which we will call $K$. Let $e\in H$ be such that $$\{e\}\oplus K =H.$$
Define $G:\{e\}\oplus K\to\mathbb{R}$ by $G(t,k)= F(te+k)$. Write $u=t'e+k'$ and note that $$\frac{\partial G}{\partial t}(t',k')=F'(u)e\neq 0,$$
and $$G(t',k')=F(u),$$
hence, from the Implicit Function Theorem, there is a $C^1$ function $\varphi: U_{k'}\to (-\delta+t',\delta+t')$, where $(-\delta+t',\delta+t')$ is an open neighborhood of $t'$ and $U_{k'}$ is an open neighborhood of $k'$, such that $$G(\varphi(k),k)=F(\varphi(k)e+k)=0,\ \forall\ k\in U_{k'}.$$
Therefore, there is an open neighborhood $V_{F(u)}$ such that $$V_{F(u)}=\{\varphi(k)e+k:\ k\in U_{k'}\}.$$
Can you conclude from here?
Remark: If $X$ is a Banach space then, a similar procedure shows that $M$ is a Banach Manifold of class $C^1$.
|
[
"math.stackexchange",
"0001825765.txt"
] | Q:
$A^A$ in category of graphs
(reference is Lawvere/Schanuel, Session 31, Ex. 1)
I'm trying to calculate the exponential object $A^A$ and its evalution map $e \colon A \times A^A \to A$ in the category of graphs, where $A$ is the "arrow graph" (ie. one arrow and two dots).
In the following, $D$ is the graph with one dot and no arrows, $1$ is the terminal object in this category (graph with one dot and one arrow, the loop).
So far I have:
The points of $\mathbf{1}\to A^A$ correspond to the maps $A\to A$ (via two standard isomorphisms), and since $\mathbf{1}$ is the loop, and there is one map of graphs $A \to A$, there is one loop in $A^A$.
The dots $D\to A^A$ correspond to the maps $A \times D \to A$, of which there are four, hence four dots in $A^A$.
The arrows $A \to A^A$ correspond to the maps $A \times A \to A$, of which there are four, hence four arrows in $A^A$.
But I'm stuck on how to put these together to constitute $A^A$ and its evaluation map.
A:
You're looking good so far. The only information you're missing is which arrows go with which dots. So let's introduce some notation.
Write $A=0\to 1$, so that $A\times D=\{0,1\}$ and $A\times A$ has vertices $\{(0,0),(0,1),(1,0),(1,1)\}$ and sole edge $\{((0,0),(1,1))\}$. Denote the four maps $D\times A\to A$ by $00,01,10,11$, where for instance $10(0)=1$ and $10(1)=0$. Write $p_x,p_y,m_1,m_0$ for the four maps $A\times A\to A$, sending respectively $(0,1)\mapsto 0$ and $(1,0)\mapsto 1$; $(0,1)\mapsto 1$ and $(1,0)\mapsto 0$; $(0,1),(1,0)\mapsto 1$; $(0,1),(1,0)\mapsto 0$. To determine their associated vertices we should precompose $p_x,p_y,m_1,m_0$ with the two inclusions $0,1:D\to A$. Under transposition, these become the two maps $a,b:D\times A\to A\times A$ with $a(0)=(0,0),a(1)=(0,1),b(0)=(1,0),b(1)=(1,1)$. (If you have unusual conventions for your Cartesian product, you could end up with the two "horizontal" maps, rather than the vertical ones, here.)
So we want to compose each of $p_x,...,m_0$ with each of $a,b$. This is now a straightforward computation: $p_xa=00,p_xb=11 , p_ya=01,p_yb=01,m_0a=00,m_0b=01,m_1a=01,m_1b=11$. Thus $A^A=(\{00,01,10,11\},\{(01,01),(00,11),(00,01),(01,11)\})$.
|
[
"stackoverflow",
"0038065069.txt"
] | Q:
Selenium - unable to determine error java.lang.IndexOutOfBoundsException: Index: 92, Size: 92
I understand this question has been asked couple of times but I have tried most of solutions and finally posting... if missed any please direct me thanks.
I am trying to go a page and grab all the links in a tag ('a') and click on each displayed link, for some reason I am getting
java.lang.IndexOutOfBoundsException: Index: 92, Size: 92
public static void clickOnEachLinkOnAPage(String tagName, String homePageTitle) {
int numberOfElementsFound = getNumberOfElementsFound(By.tagName(tagName));
System.out.println(numberOfElementsFound);
for (int pos = 0; pos < numberOfElementsFound; pos++) {
if (getElementWithIndex(By.tagName(tagName), pos).isDisplayed()) {
String linkText = getElementWithIndex(By.tagName(tagName), pos).getText().trim();
String url = getElementWithIndex(By.tagName(tagName), pos).getAttribute("href");
if (linkText.length()!=0) {
getElementWithIndex(By.tagName(tagName), pos).click();
String newWindow = driver.getWindowHandle();
Generic.handleMultipleWindows(newWindow);
String pageTitle = driver.getTitle();
linkText = StringUtils.abbreviate(linkText, 10);
System.out.println(pos +","+linkText+","+url+","+pageTitle);
// System.out.println(linkText+","+url+","+pageTitle);
closeAllOtherWindows(newWindow );
System.out.println("number of elements"+numberOfElementsFound);
if(!pageTitle.equals(homePageTitle)) {
driver.navigate().back();
}
}
}
}
}
public static int getNumberOfElementsFound(By by) {
return driver.findElements(by).size();
}
public static WebElement getElementWithIndex(By by, int pos) {
return driver.findElements(by).get(pos);
}
public static boolean closeAllOtherWindows(String openWindowHandle) {
Set<String> allWindowHandles = driver.getWindowHandles();
for (String currentWindowHandle : allWindowHandles) {
if (!currentWindowHandle.equals(openWindowHandle)) {
driver.switchTo().window(currentWindowHandle);
driver.close();
}
}
driver.switchTo().window(openWindowHandle);
if (driver.getWindowHandles().size() == 1)
return true;
else
return false;
}
public static void handleMultipleWindows(String windowTitle) {
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
driver.switchTo().window(window);
if (driver.getTitle().contains(windowTitle)) {
return;
}
}
}
Error I am getting
java.lang.IndexOutOfBoundsException: Index: 92, Size: 92
A:
I have fixed my code as below and works fine... Thank you all. I have changed a little bit to make it work.
public static void clickOnEachLinkOnAPage(String tagName, String homePageTitle) {
int numberOfElementsFound = getNumberOfElementsFound(By.tagName(tagName));
// System.out.println(numberOfElementsFound);
String currentWindow = driver.getWindowHandle();
for (int pos = 0; pos < numberOfElementsFound; pos++) {
String linkText = getElementWithIndex(By.tagName(tagName), pos).getText().trim();
if (linkText.length() != 0) {
String url = getElementWithIndex(By.tagName(tagName), pos).getAttribute("href");
getElementWithIndex(By.tagName(tagName), pos).click();
String newWindow = driver.getWindowHandle();
Generic.handleMultipleWindows(newWindow);
String pageTitle = driver.getTitle();
linkText = StringUtils.abbreviate(linkText, 10);
// System.out.println(pos +","+linkText+","+url+","+pageTitle);
System.out.println(linkText + "," + url + "," + pageTitle);
closeAllOtherWindows(newWindow);
Generic.handleMultipleWindows(currentWindow);
String pageTitleCurrent = driver.getTitle();
if (!pageTitleCurrent.equals(homePageTitle)) {
driver.navigate().back();
}
}
}
}
|
[
"stackoverflow",
"0042660037.txt"
] | Q:
Mule:SFDC<->Oracle Integration API Specification Process
Wanted to ask this general question where I am working on implementing SFDC Oracle integration. From the implementation point of view it is easy to visualize using Polling/Batching/Bulk exports etc.
But is SFDC<->Oracle integration amenable to RAML specification process given that we are not following REST conventions as in specifying GET/POST and RAML is based on REST Invocation(atleast based on my experience). The invocation style used here BATCH processing. So is RAML API specification process relevant here at all? Is there any value in establishing RAML specs for SFDC & Oracle?
A:
If you're not actually routing inbound HTTP requests using the APIkit Router, I wouldn't add unnecessary code bloat. While RAML + the APIKit router is pretty powerful for routing requests, enforcing policies, generating variables from URI params, etc.... it's probably overkill.
|
[
"stackoverflow",
"0009236434.txt"
] | Q:
M2Eclipse (M2E) build errors
I have installed the m2e plugin for Eclipse and used it to create a simple archetype. I wrote a small test driver and am trying to build the project (via Maven) and compile my Java sources into class files.
I go toRun >> Run Configurations and create a New Maven Build. I name it and set its base directory to be my project root.
When I try to select Goals it doesn't see any and so I can't add/specify any. I click the Run button. Here is my console output:
[INFO] Scanning for projects...
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR] The project org.me:myproject:0.0.1-SNAPSHOT (C:\Users\me\workbench\eclipse\workspace\MyProject\pom.xml) has 3 errors
[ERROR] 'build.plugins.plugin.artifactId' is missing. @ line 145, column 17
[ERROR] 'build.plugins.plugin.groupId' is missing. @ line 144, column 14
[ERROR] 'build.plugins.plugin.version' for : must be a valid version but is ''. @ line 146, column 14
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
The <build> tag in my pom.xml is:
<build>
<plugins>
<plugin>
<groupId></groupId>
<artifactId></artifactId>
<version></version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>compiler:compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
A few things:
What should my artifactId, groupId and version be if this is the (standard) Maven compile phase?
Is this the correct way to launch a Maven build (through Run Configurations)? In Ant there is a plugin that lets you see all of the targets defined in your build.xml; I see no such analog in Maven/m2e.
Why does something as simple as compile require plugins? One would think this would be a standard part of any build tool.
A:
You don't need to put anything as you are using all the defaults settings of the maven compiler. If you really want to specify it you can do it this way:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
</plugin>
|
[
"stackoverflow",
"0061550885.txt"
] | Q:
Can't Emit an Empty Value with yaml-cpp
I would like to emit an empty value but when I assign an empty string to be emitted the output is not technically empty.
Code Snippet:
YAML::Emitter out;
std::string name;
out << YAML::Key << "name";
out << YAML::Value << name;
Expected yaml Output:
name:
Actual yaml Output:
name: ""
As you can see I have an empty string defined and I expect the yaml output to effectively be empty.
Is this intended behavior? If so is there a way to work around this? I'm aiming to have my entire yaml output be quote free.
A:
The YAML
name:
doesn't have a string value for the key name; it's actually a null value. See, e.g., an online parser here; the canonical YAML representation is:
!!map {
? !!str "name"
: !!null "null",
}
yaml-cpp is trying to ensure that what you told it ("write this empty string") is how the resulting YAML will be parsed, so it's writing the empty string as "".
If you want to write a null value, then either don't write a value, or write YAML::Null. The latter (I believe) will produce
name: ~
which is the canonical form of null.
|
[
"stackoverflow",
"0019238568.txt"
] | Q:
How can I tell what shell is running my init file?
I have an init file (/etc/profile.d/which2.sh) that aliases the which command whenever any shell starts. In bash or sh that is fine but in zsh I don't want that as which is a built-in that is already aware of aliases and functions. How can I have the script 'know' when it is under zsh and not execute the alias?
$0 does not help.
I have fixed the problem by simply unsetting the alias in zsh-specific ~/.zshrc, but I would like to know another way.
A:
How about
[ "$(which which)" = /usr/bin/which ] && alias which "whichever"
This doesn't verify the name of the shell; rather it verifies the shell's behaviour. That's an instance of a generally-applicable programming paradigm: test behaviour directly whenever possible. (See, for example, browser detection.)
In this case, if you just checked the shell's name as a proxy for a behaviour check, you might luck out now, but things could break in the future. The name is actually arbitrary, and new names might easily be introduced. For example, in some distros ksh is a hard-link to zsh; zsh will adapt its behaviour in an attempt to emulate ksh. As another example, I have two different zsh versions, one of which is invoked as zsh5.
Ideally, the test wouldn't depend on the precise location of the which utility, either.
|
[
"stackoverflow",
"0056269829.txt"
] | Q:
AWS Lambda finish before sending message to SQS
I'm running a "Node.JS" lambda on AWS that sends a message to SQS.
For some reason the SQS callback function get execute only once every couple of calls. It's looks like that the thread that running the lambda finish the run (because it's not a synchronous call to SQS and also can't return a Future) and therefore the lambda doesn't "stay alive" for the callback to get executed.
How can I solve this issue and have the lambda wait for the SQS callback to get execute?
Here is my lambda code:
exports.handler = async (event, context) => {
// Set the region
AWS.config.update({region: 'us-east-1'});
// Create an SQS service object
var sqs = new AWS.SQS({apiVersion: '2012-11-05'});
const SQS_QUEUE_URL = process.env.SQS_QUEUE_URL;
var params = {
MessageGroupId: "cv",
MessageDeduplicationId: key,
MessageBody: "My Message",
QueueUrl: SQS_QUEUE_URL
};
console.log(`Sending notification via SQS: ${SQS_QUEUE_URL}.`);
sqs.sendMessage(params, function(err, data) { //<-- This function get called about one time every 4 lambda calls
if (err) {
console.log("Error", err);
context.done('error', "ERROR Put SQS");
} else {
console.log("Success", data.MessageId);
context.done(null,'');
}
});
};
A:
You should either stick to callback based approach, or to promise based one. I recommend you to use the latter:
exports.handler = async (event, context) => {
// Set the region
AWS.config.update({region: 'us-east-1'});
// Create an SQS service object
var sqs = new AWS.SQS({apiVersion: '2012-11-05'});
const SQS_QUEUE_URL = process.env.SQS_QUEUE_URL;
var params = {
MessageGroupId: "cv",
MessageDeduplicationId: key,
MessageBody: "My Message",
QueueUrl: SQS_QUEUE_URL
};
console.log(`Sending notification via SQS: ${SQS_QUEUE_URL}.`);
try {
await sqs.sendMessage(params).promise(); // since your handler returns a promise, lambda will only resolve after sqs responded with either failure or success
} catch (err) {
// do something here
}
};
P.S. Instantiating aws classes in the handler is not a good idea in lambda environment, since it increases the cold start time. It's better to move new AWS.SQS(...) action out of handler and AWS.config.update() too, since these actions will be executed on each call of the handler, but you really need them to be executed only once.
|
[
"stackoverflow",
"0023588921.txt"
] | Q:
Writing to Google Cloud Storage - Testing Locally
I'm testing my Google App Engine app locally in Windows. I want to be able to save my data to Google Cloud Storage like so:
file_put_contents('gs://my_folder/filename.json', $jsonFile);
It works great while running live on Google App Engine. But when I test it locally, it appears to run fine (no errors) but I don't know where it's saving the file. I thought I'd find it in the local admin console in my browser, but no luck.
Any suggestions?
A:
Go to the Admin console and then to the "Datastore Viewer".
Then select the Entity Kind "_GsFileInfo_" and your gs files will be displayed.
http://localhost:8000/datastore?kind=__BlobInfo__
Stack won't let me make a link to localhost, but it's something like the above.
|
[
"photo.stackexchange",
"0000077442.txt"
] | Q:
Maximum distance between the camera and a specified object when the object is still visible on the picture?
Theoretically, what is the minimum distance between the camera and an object, where the object begins to not be visible ? Suppose that a camera has f as focal distance and the sensor size 2/3" and the object is a square of 2m x 2m and we are filming in the daylight.
A:
This is not a practical answer (it is not a practical question), but it is a precise answer.
Let's define "not visible". If in an image, I will offer a description of "not visible" that the object is not more than one pixel size in the image, which certainly will not be considered visible (probably 5 or 10 pixels works as well ...), but "it depends", on the overall image size (pixels) and the enlargement at which it will be viewed, and of course, the size of the object, and what we mean by "can be seen".
Then the calculator at http://www.scantips.com/lights/subjectdistance.html can be used to fill in the other details, such as sensor size and image size and focal length. All of the details there will affect it.
Then if you specify "size of object in image" to be 1 pixel (or 5 or 10 pixels), then it will compute the necessary distance to the object (in the same units as was specified for the "real size of the object, perhaps feet?) A one pixel dot cannot be recognizable as anything.
A:
I will just give you a glimpse of what are you asking, so you can do your own math.
We need to take in account:
The object
1) What is the color. Diferent colours have diferent wavelengths, so this affects on the sensor reception, difraction, atmospheric absortion, etc.
2) The contrast with the background. This is pretty obvious, a white board on a white surroundings is less visible than a bright softbox flash on a dark surrounding.
The atmospheric conditions
This is obvious too, haze day, desert, refraction of the hot-cold air, water droplets.
The sensor
Sensor size, resolution, capacity, quantum characteristics...
Exposure time
Probably this has less effect on a daytime shoot than on astronomy, but this affects too.
Lens
Lens absorption, sharpness, aberration, difraction.
Focal length
Are you using your Iphone or did you rented Hubble to take a shoot of a daytime of the moon?
The main factors, on ideal conditions are focal length versus sensor resolution.
Study this: https://en.wikipedia.org/wiki/Angular_resolution
and this: https://en.wikipedia.org/wiki/Angle_of_view
After that we need to take into account the resolution of the sensor.
|
[
"stackoverflow",
"0005490883.txt"
] | Q:
NHibernate: Mapping One-toOne Relationship having Composite IDs
We have a situation wherein there is a Parent table and many Child tables. The Parent Table contains all transactions while the child tables are made to segregate specific type of transactions. The key structure is as follows:
Parent Table - Contains all Transactions
Composite Primary Key
TranId
TranMonth
Children Tables - Contains Transactions of specific type
Composite Primary Key (and also the Foreign Key from Parent table)
TranId
TranMonth
Request someone to help me out on how to map a one-to-one relationship between these tables in NHibernate.
A:
you need to use the composite id element in the mapping - see this post for an example
|
[
"stackoverflow",
"0024586105.txt"
] | Q:
Python : Division of unicode by unicode
I have to run the below part of a code, where Unicode is divided by a Unicode.
def updateUI(self):
p = unicode(self.SpinB1.value())
r = unicode(self.SpinB2.value())
t = unicode(self.Combo1.currentText())
t = t.split()
q = t[0]
amount = p * ((1 + (r / unicode(100)))**q)
self.label5.setText(amount)
I am getting the below error : 'TypeError: unsupported operand type(s) for /: 'unicode' and 'unicode''
What can I do to get this to work?
A:
You can't divide unicode types. Convert to ints or floats and then divide:
amount = int(p) * ((1 + (int(r) / 100))**int(q))
|
[
"german.stackexchange",
"0000048905.txt"
] | Q:
Verb placement with the definition of "Ordinalzahlen"
I was reading about Ordinalzahlen and the following sentence appeared:
Wenn wir über das Datum sprechen, etwas aufzählen oder über Reihenfolgen sprechen, nutzen wir Ordinalzahlen.
This is a relatively simple sentence to translate:
When we talk about the date, list something or talk about orders, we use Ordinal numbers.
However, the sentence structure confuses me.
I assume that the part
Wenn wir über das Datum sprechen, etwas aufzählen oder über Reihenfolgen sprechen
is a subordinate clause as it cannot make sense on its own (unless I'm otherwise wrong)
but why is the verb placed after this clause immediately:
nutzen wir Ordinalzahlen
and not
wir nutzen Ordinalzahlen
My interpretation was that the verb came second so the first element was the subordinate clause, followed by the verb and then the rest of the sentence, but I haven't found any information regarding this on the internet. I would like to be sure about it before I move on and advance my German further.
Why is nutzen placed before the pronoun "wir"?
A:
This is a pretty unexceptional case. The matrix clause with "nutzen" is in verb-second position like most main clauses. Whether the first position is filled by a short adverb as in "Heute gehen wir in den Zoo" or by a long subclause makes no difference.
The point to remember is that English subjects go in front of their verbs unless special circumstances arise; German subject's don't. Instead, German main clauses put the verb second, and everything else follows from that.
|
[
"stackoverflow",
"0010734215.txt"
] | Q:
Set Text for Custom UIBarButtonItem
I need to set title for Custom UIBarButtonItem.
I've the following code:
UIButton* backToRecent = [UIButton buttonWithType:UIButtonTypeCustom];
[backToRecent setImage:[UIImage imageNamed:@"back.png"]forState:UIControlStateNormal];
[backToRecent addTarget:self action:@selector(backToRecent) forControlEvents:UIControlEventTouchUpInside];
[backToRecent setFrame:CGRectMake(0, 0, 60, 30)];
UIBarButtonItem* backButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backToRecent];
[backButtonItem setTitle:@"Recent"];
partViewController.navigationItem.leftBarButtonItem = backButtonItem;
[backButtonItem release];
But the button appears without the "Recent" text.
A:
Muhammad, I suspect you have resolved this already, but here is an easy way. Hope this helps someone who is struggling with the same issue:
UIBarButtonItem * backButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Recent" style:UIBarButtonItemStyleBordered target:self action:@selector(backToRecent)];
self.navigationItem.leftBarButtonItem = backButtonItem;
A:
you should set title on the UIButton , not the UIBarButtonItem
[backToRecent setTitle:@"Recent" forState:UIControlStateNormal];
and it's not good to make the same name of variable and method
[backToRecent addTarget:self action:@selector(backToRecent) forControlEvents:UIControlEventTouchUpInside];
it's not work , because you use
[backToRecent setImage:[UIImage imageNamed:@"back.png"]forState:UIControlStateNormal];
try use
[backToRecent setBackgroundImage:[UIImage imageNamed:@"back.png"]forState:UIControlStateNormal];
|
[
"stackoverflow",
"0046764057.txt"
] | Q:
Vespa Tutorial – Pig Failing to connect to local Vespa endpoint: URISyntaxException
When following Vespa's tutorial about blog recommendation I ran into an issue connecting to the local Vespa endpoint when calling Pig from the command line with ENDPOINT=$(hostname):8080:
ERROR org.apache.pig.PigServer - exception during parsing: Error during parsing. Pig script failed to parse:
<file tutorial_feed_content_and_tensor_vespa.pig, line 131, column 0> pig script failed to validate:
java.lang.IllegalArgumentException:
java.net.URISyntaxException: Relative path in absolute URI: localhost:8080
This is a bit frustrating for people unfamiliar with Pig following the tutorial step-by-step.
The accepted answer works to get the correct port set. Problem with Handshake flying-otter.local:8080 is still an issue but is probably unrelated.
edited to add, if it's of any use: The Problem with Handshake seemed to occur when the application was not activated (i.e., deployed but forgot to do the next step).
A:
Correct usage is
-param ENDPOINT=$(hostname) -D vespa.feed.defaultport=8080
I see you have gotten around it by rewire the port but using -Dvespa.feed.defaultport will be better for production use cases.
https://github.com/vespa-engine/vespa/pull/3576
|
[
"stackoverflow",
"0041925351.txt"
] | Q:
Transition time ignored unless a DOM style property is queried before it's set
I'm creating a div using JavaScript and inserting it into a page. I'm doing this by changing the parent div's transform: translateY to shift it up by the div's height, inserting the div, then sliding it back down.
Here's the basic code:
attachTo.style.transform = 'translateY(-' + divHeight + 'px)';
attachTo.insertBefore(div, attachTo.firstElementChild);
attachTo.style.transition = 'transform 2s';
attachTo.style.transform = 'translateY(0)';
With that code the transform time is ignored and the added div pops in as normal. If I change it to something like this, however:
attachTo.style.transform = 'translateY(-' + divHeight + 'px)';
attachTo.insertBefore(div, attachTo.firstElementChild);
// Either of these can be used, as can any statement or expression that queries an element's CSS styles.
console.log(document.body.clientHeight);
var foo = pageWrap.offsetParent;
attachTo.style.transition = 'transform 2s';
attachTo.style.transform = 'translateY(0)';
The div will animate properly. Less surprisingly to me, I can also wrap the final transition and transform changes in a zero-length timeout.
The behaviour's the same in Firefox and Chromium.
My question is why this happens, and why the code isn't executed synchronously? I'm thinking it's related to the browser's execution queue, as covered in this question about zero-length timeouts, but not only would I like to know for certain that's the case, I'd also like an explanation on why using a DOM element's style property achieves the same effect (my guess is it creates a slight pause in execution).
A:
When javascript runs a series of commands, the browser does not redraw the elements until it is done, or if one tell it to, and since the last command resets everything, nothing happens.
This is also the case with many other programming languages.
So one either have to put it in a function, in this case using a setTimeout, or call for example window.scrollHeight in between, to make the browser redraw.
Why a property is used is because javascript does not have a method, like for example Application.DoEvents(); in Dot.Net.
Src: What forces layout / reflow in a browser
|
[
"stackoverflow",
"0043213617.txt"
] | Q:
After Gremlin 3.2.5-SNAPSHOT I can't pass an array of vertex labels in function hasLabel()
It used to be that both those statements would work in Java:
GraphTraversalSource g =...;
String[] labels = new String[]{"label1","label2","label3"};
g.V().hasLabel(labels);
g.V().hasLabel("label1", "label2", "label3");
After upgrading to 3.2.5-SNAPSHOT only the later one is supported and I am getting "Cannot resolve method hasLabel(java.lang.String[])".
Apparently hasLabel(String label, String... otherLabels) collides with hasLabel(P<String> predicate). Is there a work around for that so I can still build a list of labels incrementally?
Thanks!
A:
You could force it to use hasLabel(String label, String... otherLabels)
g.V().hasLabel(labels[0], labels);
|
[
"stackoverflow",
"0023901384.txt"
] | Q:
HTML / PHP Link via button in one line
I am quite certain this is an easy thing for someone to answer but since I am still pretty new to webpage design I figured I would ask it anyway. All I am trying to do is create a button to which when clicked will load another page (either .html or .php). I am doing all of this within an existing PHP page so of course it needs to be echoed.
Currently what I have tried is this:
echo '<input type="button" onclick="save_playlist.php" value="Save Playlist">';
Am I missing something very simple? I am not passing any data, simply trying to load the save_playlist.php.
Thanks in advance.
A:
Thanks to aldanux above. Here is how I solved my problem:
echo '<input type="button" value="Save Playlist" onClick="window.location.href=\'http://example.com/save_playlist.php\'">';
|
[
"stackoverflow",
"0028986491.txt"
] | Q:
ListView always has the same intent
I have a ListView that is updated from a ASyncTask, The adapter updates the list properly, however my setOnItemClickListener always has the same data in the intent.
This is the code for the loop that populates the ListView
if (JsonStr != null) {
//Get list of courses
JSONObject json = new JSONObject(JsonStr);
JSONObject Username = json.getJSONObject(InputUsername);
JSONObject Courses = Username.getJSONObject("Courses");
JSONObject CoursesItems = Courses.getJSONObject("items");
//Iterate around all courses
Iterator<String> i = CoursesItems.keys();
while (i.hasNext()) {
final String key = i.next();
JSONObject Course = (JSONObject) CoursesItems.get(key);
//Create a course entry
Map<String, String> ListEntry = new HashMap<>(2);
ListEntry.put("code", key);
if (Course.has("m_name")) {
String CourseName = (String) Course.get("m_name");
ListEntry.put("title", CourseName);
}
if (Course.has("original_source")) {
String Source = (String) Course.get("original_source");
ListEntry.put("source", Source);
}
JSONObject Units = null;
if (Course.has("Units")) {
Units = Course.getJSONObject("Units");
ListEntry.put("Units", Units.toString());
}
ListEntries.add(ListEntry);
final JSONObject finalUnits = Units;
runOnUiThread(new Runnable() {
public void run() {
SimpleAdapter adapter = new SimpleAdapter(
getApplicationContext(), //Activity
ListEntries, //List of pairs
R.layout.mymodules__list_item, //Target Parent Layout
new String[]{"title", "code", "source"}, //Key for pairs
new int[]{R.id.list_item_alert_textview,
R.id.list_item_date_textview,
R.id.list_item_source_textview}); //target items
ListView lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), CourseActivity.class);
intent.putExtra("Data", finalUnits.toString());
startActivity(intent);
}
});
}
});
}
}
A:
'finalUnits' is final value .
move listener and data(List Units) to inside adapter.
and set listener in bindview method.
{
Intent i = new Intent(context,CourseActivity.class);
i.putExtra("Data",list.get(position).toString());
startActivity(i);
}
|
[
"stackoverflow",
"0033832448.txt"
] | Q:
Handlebars.net disable escaping with noEscape option in
I just found this link to escape html in string with Handlebars.js:
Handlebars.js disable escaping with noEscape option?
i.e var template = Handlebars.compile(source, {noEscape: true});
I am using Handlebars.Net in my project and I want to use the same configuration to escape html. Unfortunately I was not able to find any overload there to escape html.
It is just:
Handlebars.Compile(template)
Can you help me escaping html tags in that library?
A:
I expect you have figured this out by now, but Handlebars.net respects the Handlebars.js "triple 'stache" syntax, as in the following snippet. So change your {{}} to {{{}}} for the affected property and you should be golden.
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{{body}}}
</div>
</div>
|
[
"stackoverflow",
"0057375971.txt"
] | Q:
How to get the value of data-id-proofinglevel in option
I have an dropdown that lists people available for a job. In each option there is a value and a data-id-proofinglevel. I would like to get the value of the data-id-proofinglevel for the selected person, but it's returning null.
Using MooTools and JavaScript, this is what I have:
$(document.body).addEvent("change:relay(.connectedassignments)", function (e, el) {
let rowid = el.get('data-row-id');
let proofingLevel = document.getElementById('connected[' + rowid + ']').getAttribute('data-id-proofinglevel');
console.log('Proofing Level: ' + proofingLevel);
});
The HTML is:
<select id="connected[1]" name="assignment[1][connected][]" class="connectedassignments" data-row-id="1">
<option value="">Please select...</option>
<option value="627" data-id-proofinglevel="4">Abby</option>
<option value="375" data-id-proofinglevel="2">Jennifer</option>
<option value="308" data-id-proofinglevel="0">Aimee</option>
</select>
I should be getting the numbers, like 4, 2, and 0.
I tried getting the childNodes and looping through them, but can't access that specific property value. Any help would be much appreciated.
A:
I think you've got a mistake at this line:
let proofingLevel = document.getElementById('connected[' + rowid + ']').getAttribute('data-id-proofinglevel');
Try to change the JS code in your event callback to this one:
var rowId = 1
var list = document.getElementById('connected[' + rowId + ']')
var proofingLevel = list.options[list.selectedIndex].getAttribute('data-id-proofinglevel')
console.log('Proofing level: ' + proofingLevel || 'Not selected')
<select id="connected[1]" name="assignment[1][connected][]" class="connectedassignments" data-row-id="1">
<option value="">Please select...</option>
<option value="627" data-id-proofinglevel="4">Abby</option>
<option value="375" data-id-proofinglevel="2" selected>Jennifer</option>
<option value="308" data-id-proofinglevel="0">Aimee</option>
</select>
That should work :)
|
[
"stackoverflow",
"0036881958.txt"
] | Q:
C++ program cannot find boost
I am trying to compile the MultiNEAT project (https://github.com/peter-ch/MultiNEAT). I have installed boost and boost-python, and it is located in /usr/local/Cellar/boost. I also edited ~/.bash_profile to add /usr/local/Cellar/boost/1.60.0_1/include to PATH. However, when I try to compile and install MultiNEAT by
sudo python setup.py install
I get the problem:
running install
running build
running build_py
running build_ext
building '_MultiNEAT' extension
cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c src/Genome.cpp -o build/temp.macosx-10.11-intel-2.7/src/Genome.o -march=native -DUSE_BOOST_PYTHON -DUSE_BOOST_RANDOM -std=gnu++11 -g -Wall
src/Genome.cpp:37:10: fatal error: 'boost/unordered_map.hpp' file not found
#include <boost/unordered_map.hpp>
^
1 error generated.
error: command 'cc' failed with exit status 1
So my question is: how can I make the program found the boost library and successfully comiple MultiNEAT? My system is OS X Yosemite. Thanks!
A:
You have to change your compilation definitions to include the boost header files. You may, possibly, need to add the boost libraries (and their directories) to the linkage settings. I could have said more if you have published the way you build your application.
|
[
"stackoverflow",
"0027818573.txt"
] | Q:
How to deactivate button while loading
I have the following Angular and HTML to display and reload a list of images:
<script type="text/javascript">
var application = angular.module('Application', []);
application.service('ImageService', function ($http) {
return {
GetList: function (page) {
return $http.get('api/images', { params: { page: page } });
},
}
});
application.controller('ImageController', function ImageController($scope, ImageService) {
var page = 0;
$scope.images = [];
var load = function () {
ImageService.GetList(page)
.success(function (data, status, headers, config) {
$scope.images = $scope.images.concat(data);
})
.error(function (data, status, headers, config) { });
}
$scope.reload = function () {
page++;
load();
}
load();
});
</script>
<div data-ng-app="Application" data-ng-controller="ImageController" class="gallery">
<div data-ng-repeat='image in images' class="image">
<img src="{{image.Url}}" alt="" />
</div>
<a href="" class="reload" data-ng-click="reload()">load more</a>
</div>
How can I change the text of "load more" do "loading ..." and deactivate the button while is loading?
A:
You could create a 'loading' directive that disables a button/link when there are pending $http requests:
Directive
app.directive('loading', function($http) {
return {
restrict: 'A',
scope: true,
link: function(scope, element) {
scope.pending = $http.pendingRequests;
scope.$watch('pending.length', function (length) {
if (length > 0)
{
element.attr('disabled', 'disabled');
}
else {
element.removeAttr('disabled');
}
});
}
}
});
Controller
app.controller('ctrl', function($scope, $http) {
$scope.load = function() {
$http({url: 'api/get', method:'GET'}).success(function(data) {
$scope.data = data;
});
}
});
HTML
<div ng-controller="ctrl">
<button ng-click="load()" loading>Click Me</button>
</div>
A:
You could bind it to the scope:
<script type="text/javascript">
var application = angular.module('Application', []);
application.service('ImageService', function ($http) {
return {
GetList: function (page) {
return $http.get('api/images', { params: { page: page } });
},
}
});
application.controller('ImageController', function ImageController($scope, ImageService) {
var page = 0;
$scope.images = [];
$scope.loading = false;
$scope.loadingText = function() {
if ($scope.loading) {
return 'loading';
}
return 'load more';
}
var load = function () {
$scope.loading = true;
ImageService.GetList(page)
.success(function (data, status, headers, config) {
$scope.images = $scope.images.concat(data);
})
.error(function (data, status, headers, config) { })
.finally(function() {$scope.loading = false});
}
$scope.reload = function () {
page++;
load();
}
load();
});
</script>
<div data-ng-app="Application" data-ng-controller="ImageController" class="gallery">
<div data-ng-repeat='image in images' class="image">
<img src="{{image.Url}}" alt="" />
</div>
<a ng-disabled="{{loading}}" href="" class="reload" data-ng-click="reload()">{{loadingText()}}</a>
</div>
|
[
"travel.stackexchange",
"0000088875.txt"
] | Q:
UK visa refused because the immigration officer suspects I'm trying to live in the UK through successive visits. What are my options?
I am in a relationship with a UK citizen. We just started dating and in Oct of 2016 I went to visit the UK to spend time with them. I stayed from Oct 11th to Nov 4th. I flew home to attend my older sister's wedding and to return to work. I flew back to revisit my significant other on Nov 30th and was denied entry. The reason(s) I was denied entry is because I mistakenly bought a one way ticket, thinking that it wasn't going to be a big deal to just purchase the return when I got there (stupid mistake number 1), and also, I brought some hair styling shears with me to cut my significant other's hair and her Mom's for fun (no monetary gain at all) just as a nice gesture (stupid mistake number 2). The border official thought I was seeking employment because of me carrying that & having a one way ticket. They stamped an X on my passport and I was able to stay one day with my partner then flown back home on a return flight.
I tried to enter UK again in early December this time with supporting documents to prove that I just wanted to visit. I brought proof of work, financial stability, ties to my home, return ticket, etc.. And I was let into the UK. I stayed until the end of January and then went home to attend another wedding and to return to work. When I got back, I decided this time, I would do the right thing and apply for a visitors visa for 6 months. I just got word back that they refused my visa. I am beyond heartbroken because I think if I were to try and fly back to see my significant other again, I would be refused again
Will I be refused again?
Is there a way to check notes or restrictions associated with my passport?
Is there a way to clear any such restrictions associated with me?
Can I write a formal letter to the UK Home Office to have a chance to clarify things?
A:
The pattern you described is fairly common. You as the US (or Canadian) national developed a romantic long distance relationship (LDR) with a Brit, and sought to maintain the relationship by using your status as a non-visa national to visit without a visa. Last year you were served removal papers and got a temporary admission of 1 day. We don't have the IO's transcript of your landing interview, but typically those situations involve some cat-and-mouse type of interaction that gets them more upset than normal.
Then you applied for entry clearance (a good strategy), but were refused.
They got you on V 4.2 (a+b+c), which is symptomatic of a person whose history indicates they are not a genuine visitor and should be using one of the other inward routes (a fiance visa for example). LDR's are fine, but the person needs to be leading a properly integrated lifestyle in their home country. They expect that during one of your visits you will likely go underground and engage in further abuse of the rules.
Some of your questions...
Will I be refused again?
We're not prophets, but it can be difficult to maintain an LDR after they have introduced V 4.2 (b) as a grounds. It means you have worn out your welcome and your visits suggest a further agenda (one characterised by abuse).
Is there a way to check notes or restrictions associated with my
passport?
Yes, in general the UK has a procedure called Subject Access Request where they will release your records in a very limited form. It will not, for example, contain the transcript behind your earlier removal, and it will not include any information that might help you evade immigration controls.
Is there a way to clear any such restrictions associated with me?
Yes, the absolute golden solution is to get an entry clearance. This has the effect of wiping the slate to the extent that you have successfully established yourself as a genuine visitor who is using the rules lawfully. I recognise that just having been refused, this solution seems like a cruel tautological recursion. But as the Brits say, that's just "hard cheese".
Can I write a formal letter to the UK Home Office to have a chance to
clarify things?
Of course. You can even petition HM (she is contactable at Buckingham Palace, via an assistant) or write to the Home Secretary. In either case you will get back a standard letter informing you that you are free to make a fresh application for entry clearance. In other words, do not expect very much. Entry Clearance Officers have a mandate from the government to make decisions on behalf of the Home Secretary and that's that. Visitor applications do not have appeal rights.
The most frustrating part about all of this, is I am not, nor have I
ever had any intention of trying to cheat the system or do anything
illegal.
There is a lengthy history of abuse with people in LDR's. They lie to the IO's, they waste time playing cat-and-mouse, they overstay, they tie up the courts, they evade fees and other requirements. So much so that they have been trying to contain it with rule changes for a long time (more than 20 years). So while your personal intentions are an unknown factor, you clearly fit the pattern and that's what they work from.
I am beyond heartbroken because I think if I were to try and fly back
to see my significant other again, I would be refused again. I don't
know what to do. We both don't know what to do. All I want to do is
spend time with the person I love. I'm not trying to do anything
illegal. I just want to be with them.
"Significant other", "partner", "the person I love", this is language that describes a serious commitment. As I mentioned above one of the settlement routes is more appropriate. They may be adjusting the financial hurdles following a court decision last week. In addition to fiance or spouse, you can also try the student route.
Any help, options or advice would be greatly appreciated. More than
you know.
There are several immigration solicitors of national stature who specialise in entry clearance for LDR's. I took a law course in it a while back (and know the instructor personally for about 23 years) and it was very well attended. Use the search pages at ILPA.
NOTES:
Comparisons. The OP has asked her questions on two internet resources. It's interesting to see how the same case was handled...
For comparative purposes, the interested reader is invited to view
the OP's thread at UKY. It's a forum dedicated to American women
trying to marry Brits and lots of their advice has sound
practicality. They are not legal professionals, their very
impressive experience derives from tens-of-thousands of threads, so
always double check their stuff to make sure.
Also for comparison purposes, the OP published her thread on
Immigration Boards.
Citations
Citation from the study that I linked to above...
...the indication is that many of these persons had intended to marry
all along but had not obtained leave to enter on this basis and had
therefore lied about their intentions to the entry clearance officer...
And from the seminal Home Office Online Report ...
Some IOs were surprised, and suspicious, when people travel to spend
time with someone they hardly know or have never met. If people are
going to visit someone in another country, IOs assume they will have
had recent or regular contact and will know something about the other
person. Internet relationships attract particular attention.
A:
Thanks for posting the refusal, it clarified a lot that wasn't as visible in your question.
Let's start from the bottom. You were refused under paragraph 4.2 sections a, b and c, so let's bring them up for reference.
V 4.2 The applicant must satisfy the decision maker that they are a
genuine visitor. This means that the applicant:
(a) will leave the UK at the end of their visit; and
(b) will not live in the UK for extended periods through frequent or
successive visits, or make the UK their main home; and
(c) is genuinely seeking entry for a purpose that is permitted by the
visitor routes (these are listed in Appendices 3, 4 and 5);
ECO not only thinks that there is a secondary motive to your visits, but that this motive is to eventually settle in the UK. And that is something not to take lightly, as anyone suspected of seeking to settle in the UK illegally will struggle with future applications.
To understand why ECO arrived at this conclusion, try to look at the situation from his perspective. You have started dating a person in October, and since you've spent most of your time (2.5 out of 3 months period) in the UK across multiple visits. Given how short is your relationship, this type of absence is unlikely to be planned, and most people who have ties to local community would struggle to be suddenly absent for most of 3 months and then seek additional month. Just from work perspective, who can take almost three months of vacation without pre-arranging that with your employer well ahead of time? Not to mention missing your friends, family, and out of work commitments, you may have which usually tie you back to local community.
When you put it together with your reason for a visit, it makes it very likely that you will continue that pattern of spending more time in the UK than you do back home. It also brings up the possibility that you may decide to not leave after one of your visits and instead go underground.
All this means that you will very likely be refused on any subsequent visas as a visitor in the near future, as you will need to show unyielding ties back home and only time can fix this.
But not all is lost. Since you are happy to spend most of your time in the UK, why not take it step further and try to apply for Tier 2 (General) visa? If you are a skilled employee, obtaining a sponsorship should not be outside of your reach, and then you could reside in the UK, with visits back to your home country. You may be interested in reading more about the process on the gov.uk website.
In the meanwhile, your special someone could visit you in your home country, although you will be best to make sure not to repeat the mistakes you've done with UK immigration and keep the visits longer, better planned, but less frequent. You could also fly together to neutral countries for short vacations.
Regarding the note in your passport, that is what they call a coded landing, which is, in essence, a note to future immigration officers. It is almost always nothing to worry about. If you want to find out what it means, you would have to fill in SAR to receive its content.
A:
One of the notes in your refusal letter is that the ECO has not got a clear picture of your situation back at home. That includes financial situation.
I think that if you apply for a visitor visa again (for 6 months) you could successfully obtain the visitor visa if accompanied by the following:
Show the ECO through a bank statement of yours containing the financial history of that account of at least the last three months that you can fund yourself for the next 6 months through your own income;
The new application for entry clearance should be accompanied by a letter where you justify paragraph by paragraph the parts that looked suspicious to the ECO that made the refusal decision. The justification should be done by FACTS. For example, it does not help if you say that your father will help you buy the ticket, but it does help if you provide a signed letter by your father together with the copy of his id as well as his financial history (of at least one of his bank accounts with sufficient funds) of the last three months.
A letter from your current employer stating that they agree to you taking days off, or your contract of employment stating your employment terms and conditions showing that even if you make long absences, you would still be welcome to work there.
Show any ties with your home country. For example you can provide bills or statements showing that you still live with your family or some statement that has got your address in there and some statements of your parents with the same address and a certificate of birth to show the connection you have with them.
The visitor rules are in Appendix V. It is helpful to thoroughly review them prior to making your application.
|
[
"stackoverflow",
"0039901985.txt"
] | Q:
php post file using file_get_contents does not work for some file types
The following code works fine, however if I change the files to use myFile.pdf or myFile.xlsx the file gets created with 0 bytes. only thing that changes for the working version and the non working version is the file type. Why am I getting 0 bytes with excel files and pdfs?
$file = file_get_contents('myFile.xml');
$url = 'destination.php';
$post_data = array(
"file" => $file,
"fileName" => "myFile.xml"
);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($post_data),
),
);
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
echo $response;
then my destination file saves the file like this:
file_put_contents($_POST["fileName"], $_POST["file"]);
?>
A:
In My instance the problem was actually with file size restrictions on the server and the file types were just coincidental. check post_max_size and upload_max_filesize.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.