This is 2013. C++11 and C++14 is on us. But why still no dedicated IDE for
C++?
I'm 26 years old. C++ is nearly 35 years old.
I'm really baffled at seeing the evolution of C++ in my 15 years of
programming. I started with Turbo C blue screen in late 90's to vim in
early 2000's. From there, I have moved on to Java, Python and Ruby. All
beautiful languages having extensive set of IDE's which makes programming
in these languages easy and fun.
But As for C++. With it's latest iteration in C++11 and coming iteration
C++14, There's still no full fledged, dedicated Editor which full support
for latest standard and documentation of libraries and intellisense. This
is really ironic, since today, almost every language have extensive
toolsets.
C++ is not as easy to learn. An IDE will surely go a long way getting new
programmers on-boarding process easy to a great extent.
If anyone knows any reason behind it, please edify us.
Saturday, 31 August 2013
Button click with jquery cancel form and redirect page
Button click with jquery cancel form and redirect page
http://jsfiddle.net/nqCFL/
I'm trying to check the value of an input and if it's empty, redirect the
page, if not empty, redirect to another page. It has no value as is and
does not represent what I'm actually trying to do, it';s just an
experiment. This experiment is supposed to help me with the goal is to
check the input and if it's empty, submit the form. If it's not empty,
cancel the form and redirect to another page. I'm experimenting with
Botcha and this is similar in idea. The problem is the page just
continually refreshes on button click and never redirects according to the
test I have above.
The experiment I have is:
<form action="" method="post">
<input type="text" placeholder="issue" class="issue-input" />
<button class="submit button" type="submit">Send</button>
</form>
$(".submit").click(function(){
if($(".issue-input").val().length == 0){
window.location.href = "http://www.google.com";
} else {
window.location.href = "http://www.yahoo.com";
};
});
http://jsfiddle.net/nqCFL/
I'm trying to check the value of an input and if it's empty, redirect the
page, if not empty, redirect to another page. It has no value as is and
does not represent what I'm actually trying to do, it';s just an
experiment. This experiment is supposed to help me with the goal is to
check the input and if it's empty, submit the form. If it's not empty,
cancel the form and redirect to another page. I'm experimenting with
Botcha and this is similar in idea. The problem is the page just
continually refreshes on button click and never redirects according to the
test I have above.
The experiment I have is:
<form action="" method="post">
<input type="text" placeholder="issue" class="issue-input" />
<button class="submit button" type="submit">Send</button>
</form>
$(".submit").click(function(){
if($(".issue-input").val().length == 0){
window.location.href = "http://www.google.com";
} else {
window.location.href = "http://www.yahoo.com";
};
});
How to send not declared selector without performSelector:?
How to send not declared selector without performSelector:?
Background: I have an object (let's call it BackendClient) that represents
connection with server. Its methods are generated to single @protocol and
they are all synchronous, so I want to create proxy object that will call
them in background. The main problem is return value, which I obviously
can't return from async method, so I need to pass a callback. The "easy"
way will be copy all BackendClient's methods and add callback argument.
But that's not very dynamic way of solving that problem, while ObjectiveC
nature is dynamic. That's where performSelector: appears. It solves
problem entirely, but it almost kills proxy object transparency.
Problem: I want to be able to send not declared selector to proxy
(subclass of NSProxy) object as if it was already declared. For example, I
have method:
-(AuthResponse)authByRequest:(AuthRequest*)request
in BackendClient protocol. And I want proxy call look like this:
[proxyClient authByRequest:myRequest withCallback:myCallback];
But this wouldn't compile because
No visible @interface for 'BackendClientProxy' declares the selector
'authByRequest:withCallBack:'
OK. Let's calm down compiler a bit:
[(id)proxyClient authByRequest:myRequest withCallback:myCallback];
Awww. Another error:
No known instance method for selector 'authByRequest:withCallBack:'
The only thing that comes to my mind and this point is somehow construct
new @protocol with needed methods at runtime, but I have no idea how to do
that.
Conclusion: I need to suppress this compilation error. Any idea how to do
that?
Background: I have an object (let's call it BackendClient) that represents
connection with server. Its methods are generated to single @protocol and
they are all synchronous, so I want to create proxy object that will call
them in background. The main problem is return value, which I obviously
can't return from async method, so I need to pass a callback. The "easy"
way will be copy all BackendClient's methods and add callback argument.
But that's not very dynamic way of solving that problem, while ObjectiveC
nature is dynamic. That's where performSelector: appears. It solves
problem entirely, but it almost kills proxy object transparency.
Problem: I want to be able to send not declared selector to proxy
(subclass of NSProxy) object as if it was already declared. For example, I
have method:
-(AuthResponse)authByRequest:(AuthRequest*)request
in BackendClient protocol. And I want proxy call look like this:
[proxyClient authByRequest:myRequest withCallback:myCallback];
But this wouldn't compile because
No visible @interface for 'BackendClientProxy' declares the selector
'authByRequest:withCallBack:'
OK. Let's calm down compiler a bit:
[(id)proxyClient authByRequest:myRequest withCallback:myCallback];
Awww. Another error:
No known instance method for selector 'authByRequest:withCallBack:'
The only thing that comes to my mind and this point is somehow construct
new @protocol with needed methods at runtime, but I have no idea how to do
that.
Conclusion: I need to suppress this compilation error. Any idea how to do
that?
Difference between (3) and 3 in Clojure
Difference between ​(​3​) and 3 in Clojure
​I'm new to clo​j​ure. What is the difference between
​(​3​) and 3​? If I do ​(3) ​I get
this exception:
java.lang.ClassCastException: java.lang.Long cannot be cast to
clojure.lang.IFn​​.
​I'm new to clo​j​ure. What is the difference between
​(​3​) and 3​? If I do ​(3) ​I get
this exception:
java.lang.ClassCastException: java.lang.Long cannot be cast to
clojure.lang.IFn​​.
java xml validation with relative path to glasshfish config folder
java xml validation with relative path to glasshfish config folder
I searched a lot but couldn't find anything. I want to validate a selected
xml file with an schema file. My problem is working relative path is
config folder of the Glassfish server. I tried to get url of the schema
file which I copied into same package of the class I run this code but
still I can't find the file. I only able to make it work is by copying the
file into server config file.
URL url = ClassLoader.getSystemResource("/schema.xsd");
File file = new File(url.getPath());
But url returns null. How can I find this file and even if I find I
believe file object can not be created because my relative path is
/home/user/glassfish3/glassfish/domains/domain1/config. Any ideas how to
solve this problem? Thnx for any help in advance.
I searched a lot but couldn't find anything. I want to validate a selected
xml file with an schema file. My problem is working relative path is
config folder of the Glassfish server. I tried to get url of the schema
file which I copied into same package of the class I run this code but
still I can't find the file. I only able to make it work is by copying the
file into server config file.
URL url = ClassLoader.getSystemResource("/schema.xsd");
File file = new File(url.getPath());
But url returns null. How can I find this file and even if I find I
believe file object can not be created because my relative path is
/home/user/glassfish3/glassfish/domains/domain1/config. Any ideas how to
solve this problem? Thnx for any help in advance.
displaying time recorded while recording video
displaying time recorded while recording video
i'm working on an app that enables the user to capture video. however i'm
customising the user interface of the UIImagePickerController thus the
timer wouldn't be showing since i'm hiding the default controls. so i want
to display the time recorded live while the user is recording. how can i
do that? i tried this
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self
selector:@selector(updateLabel)
userInfo:nil repeats:YES];
but since the user will be able to pause. i should stop the counting or
pause it. how can i do that? besides i want to be able to present the time
in this format 00:00 [mm:ss]
Edit: figured out how to kill the timer by [timer invalidate]; i just
wanna represent it the right way. of if there is any alternative to using
NSTimer it will be highly appreciated.
i'm working on an app that enables the user to capture video. however i'm
customising the user interface of the UIImagePickerController thus the
timer wouldn't be showing since i'm hiding the default controls. so i want
to display the time recorded live while the user is recording. how can i
do that? i tried this
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self
selector:@selector(updateLabel)
userInfo:nil repeats:YES];
but since the user will be able to pause. i should stop the counting or
pause it. how can i do that? besides i want to be able to present the time
in this format 00:00 [mm:ss]
Edit: figured out how to kill the timer by [timer invalidate]; i just
wanna represent it the right way. of if there is any alternative to using
NSTimer it will be highly appreciated.
Friday, 30 August 2013
Rails 3 in action book - Chapter 7.3.1
Rails 3 in action book - Chapter 7.3.1
I did as the steps in the book but cucumber test is not passing this time !
➜ ticketee git:(master) ✗ rake cucumber:ok
/home/dexter/.rvm/rubies/ruby-1.9.3-p194/bin/ruby -S bundle exec
cucumber --profile default
Rack::File headers parameter replaces cache_control after Rack 1.5.
Using the default profile...
Feature: Creating projects
In order to have projects to assign tickets to
As a user
I want to create them easily
Background: #
features/creating_projects.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password | admin |
| admin@ticketee.com | password | true |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Given I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "New Project" #
features/step_definitions/web_steps.rb:56
Scenario: Creating a project #
features/creating_projects.feature:14
And I fill in "Name" with "TextMate 2" #
features/step_definitions/web_steps.rb:60
Unable to find field "Name" (Capybara::ElementNotFound)
./features/step_definitions/web_steps.rb:61:in `/^(?:|I )fill in
"([^"]*)" with "([^"]*)"$/'
features/creating_projects.feature:15:in `And I fill in "Name"
with "TextMate 2"'
And I press "Create Project" #
features/step_definitions/web_steps.rb:52
Then I should see "Project has been created." #
features/step_definitions/web_steps.rb:105
And I should be on the project page for "TextMate 2" #
features/step_definitions/web_steps.rb:230
And I should see "TextMate 2" #
features/step_definitions/web_steps.rb:105
Scenario: Creating a project without a name #
features/creating_projects.feature:21
And I press "Create Project" #
features/step_definitions/web_steps.rb:52
Unable to find button "Create Project" (Capybara::ElementNotFound)
./features/step_definitions/web_steps.rb:53:in `/^(?:|I )press
"([^"]*)"$/'
features/creating_projects.feature:22:in `And I press "Create
Project"'
Then I should see "Project has not been created." #
features/step_definitions/web_steps.rb:105
And I should see "Name can't be blank" #
features/step_definitions/web_steps.rb:105
Feature: Creating Tickets
In order to create tickets for projects
As a user
I want to be able to select a project and do that
Background:
# features/creating_tickets.feature:6
Given there is a project called "Internet Explorer"
# features/step_definitions/project_steps.rb:1
And there are the following users:
# features/step_definitions/user_steps.rb:1
| email | password |
| user@ticketee.com | password |
And I am on the homepage
# features/step_definitions/web_steps.rb:44
When I follow "Internet Explorer"
# features/step_definitions/web_steps.rb:56
And I follow "New Ticket"
# features/step_definitions/web_steps.rb:56
Then I should see "You need to sign in or sign up before
continuing." # features/step_definitions/web_steps.rb:105
When I fill in "Email" with "user@ticketee.com"
# features/step_definitions/web_steps.rb:60
And I fill in "Password" with "password"
# features/step_definitions/web_steps.rb:60
And I press "Sign in"
# features/step_definitions/web_steps.rb:52
Then I should see "New Ticket"
# features/step_definitions/web_steps.rb:105
Scenario: Creating a ticket
# features/creating_tickets.feature:20
When I fill in "Title" with "Non-standards compliance"
# features/step_definitions/web_steps.rb:60
And I fill in "Description" with "My pages are ugly!"
# features/step_definitions/web_steps.rb:60
And I press "Create Ticket"
# features/step_definitions/web_steps.rb:52
Then I should see "Ticket has been created."
# features/step_definitions/web_steps.rb:105
Then I should see "Created by user@ticketee.com"
# features/step_definitions/web_steps.rb:105
Scenario: Creating a ticket without valid attributes fails
# features/creating_tickets.feature:27
When I press "Create Ticket"
# features/step_definitions/web_steps.rb:52
Then I should see "Ticket has not been created."
# features/step_definitions/web_steps.rb:105
And I should see "Title can't be blank"
# features/step_definitions/web_steps.rb:105
And I should see "Description can't be blank"
# features/step_definitions/web_steps.rb:105
Scenario: Description must be longer than 10 characters
# features/creating_tickets.feature:33
When I fill in "Title" with "Non-standards compliance"
# features/step_definitions/web_steps.rb:60
And I fill in "Description" with "it sucks"
# features/step_definitions/web_steps.rb:60
And I press "Create Ticket"
# features/step_definitions/web_steps.rb:52
Then I should see "Ticket has not been created."
# features/step_definitions/web_steps.rb:105
And I should see "Description is too short"
# features/step_definitions/web_steps.rb:105
Feature: Deleting projects
In order to remove needless projects
As a project manager
I want to make them disappear
Background: #
features/deleting_projects.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password | admin |
| admin@ticketee.com | password | true |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Scenario: Deleting a project #
features/deleting_projects.feature:12
Given there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
And I follow "Delete Project" #
features/step_definitions/web_steps.rb:56
Then I should see "Project has been deleted." #
features/step_definitions/web_steps.rb:105
expected to find text "Project has been deleted." in "You must
be an admin to do that. Ticketee Signed in as admin@ticketee.com
New Project Projects TextMate 2"
(RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/web_steps.rb:107:in `/^(?:|I )should
see "([^"]*)"$/'
features/deleting_projects.feature:17:in `Then I should see
"Project has been deleted."'
Then I should not see "TextMate 2" #
features/step_definitions/web_steps.rb:123
Feature: Deleting tickets
In order to remove tickets
As a user
I want to press a button and make them disappear
Background: #
features/deleting_tickets.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password |
| user@ticketee.com | password |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Given there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And "user@ticketee.com" has created a ticket for this project: #
features/step_definitions/ticket_steps.rb:1
| title | description |
| Make it shiny! | Gradients! Starbursts! Oh my! |
Given I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
And I follow "Make it shiny!" #
features/step_definitions/web_steps.rb:56
Scenario: Deleting a ticket #
features/deleting_tickets.feature:19
When I follow "Delete Ticket" #
features/step_definitions/web_steps.rb:56
Then I should see "Ticket has been deleted." #
features/step_definitions/web_steps.rb:105
And I should be on the project page for "TextMate 2" #
features/step_definitions/web_steps.rb:230
Feature: Editing Projects
In order to update project information
As a user
I want to be able to do that through an interface
Background: #
features/editing_projects.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password | admin |
| admin@ticketee.com | password | true |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Given there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
And I follow "Edit Project" #
features/step_definitions/web_steps.rb:56
Scenario: Updating a project #
features/editing_projects.feature:16
And I fill in "Name" with "TextMate 2 beta" #
features/step_definitions/web_steps.rb:60
Unable to find field "Name" (Capybara::ElementNotFound)
./features/step_definitions/web_steps.rb:61:in `/^(?:|I )fill in
"([^"]*)" with "([^"]*)"$/'
features/editing_projects.feature:17:in `And I fill in "Name"
with "TextMate 2 beta"'
And I press "Update Project" #
features/step_definitions/web_steps.rb:52
Then I should see "Project has been updated." #
features/step_definitions/web_steps.rb:105
Then I should be on the project page for "TextMate 2 beta" #
features/step_definitions/web_steps.rb:230
Scenario: Updating a project with invalid attributes is bad #
features/editing_projects.feature:22
And I fill in "Name" with "" #
features/step_definitions/web_steps.rb:60
Unable to find field "Name" (Capybara::ElementNotFound)
./features/step_definitions/web_steps.rb:61:in `/^(?:|I )fill in
"([^"]*)" with "([^"]*)"$/'
features/editing_projects.feature:23:in `And I fill in "Name"
with ""'
And I press "Update Project" #
features/step_definitions/web_steps.rb:52
Then I should see "Project has not been updated." #
features/step_definitions/web_steps.rb:105
Feature: Editing tickets
In order to alter ticket information
As a user
I want a form to edit the tickets
Background: #
features/editing_tickets.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password |
| user@ticketee.com | password |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Given there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And "user@ticketee.com" has created a ticket for this project: #
features/step_definitions/ticket_steps.rb:1
| title | description |
| Make it shiny! | Gradients! Starbursts! Oh my! |
Given I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
And I follow "Make it shiny!" #
features/step_definitions/web_steps.rb:56
When I follow "Edit Ticket" #
features/step_definitions/web_steps.rb:56
Scenario: Updating a ticket #
features/editing_tickets.feature:20
When I fill in "Title" with "Make it really shiny!" #
features/step_definitions/web_steps.rb:60
And I press "Update Ticket" #
features/step_definitions/web_steps.rb:52
Then I should see "Ticket has been updated." #
features/step_definitions/web_steps.rb:105
And I should see "Make it really shiny!" within "#ticket h2" #
features/step_definitions/web_steps.rb:35
But I should not see "Make it shiny!" #
features/step_definitions/web_steps.rb:123
Scenario: Updating a ticket with invalid information #
features/editing_tickets.feature:27
When I fill in "Title" with "" #
features/step_definitions/web_steps.rb:60
And I press "Update Ticket" #
features/step_definitions/web_steps.rb:52
Then I should see "Ticket has not been updated." #
features/step_definitions/web_steps.rb:105
Feature: Signing in
In order to use the site
As a user
I want to be able to sign in
Scenario: Siging in via confirmation
# features/signing_in.feature:6
Given there are the following users:
# features/step_definitions/user_steps.rb:1
| email | password | unconfirmed |
| user@ticketee.com | password | true |
And "user@ticketee.com" opens the email with subject "Confirmation
instructions" # features/step_definitions/email_steps.rb:80
And they click the first link in the email
# features/step_definitions/email_steps.rb:182
Then I should see "Your account was successfully confirmed"
# features/step_definitions/web_steps.rb:105
And I should see "Signed in as user@ticketee.com"
# features/step_definitions/web_steps.rb:105
Scenario: Signing in via form # features/signing_in.feature:15
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password |
| user@ticketee.com | password |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Feature: Signing up
In order to be attributed for my work
As a user
I want to be able to sign up
Scenario: Signing up #
features/signing_up.feature:6
Given I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "Sign up" #
features/step_definitions/web_steps.rb:56
And I fill in "Email" with "user@ticketee.com" #
features/step_definitions/web_steps.rb:60
And I fill in "Password" with "password" #
features/step_definitions/web_steps.rb:60
And I fill in "Password confirmation" with "password" #
features/step_definitions/web_steps.rb:60
And I press "Sign up" #
features/step_definitions/web_steps.rb:52
Then I should see "You have signed up successfully." #
features/step_definitions/web_steps.rb:105
Feature: Viewing projects
In order to assign tickets to a project
As a user
I want to be able to see a list of available projects
Scenario: Listing all projects #
features/viewing_projects.feature:6
Given there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
Then I should be on the project page for "TextMate 2" #
features/step_definitions/web_steps.rb:230
Feature: Viewing tickets
In order ro view the tickets for a project
As a user
I want to see them on that project's page
Background: #
features/viewing_tickets.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password |
| user@ticketee.com | password |
And there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And "user@ticketee.com" has created a ticket for this project: #
features/step_definitions/ticket_steps.rb:1
| title | description |
| Make it shiny! | Gradients! Starbursts! Oh my! |
And there is a project called "Internet Explorer" #
features/step_definitions/project_steps.rb:1
And "user@ticketee.com" has created a ticket for this project: #
features/step_definitions/ticket_steps.rb:1
| title | description |
| Standards compliance | Isn't a joke. |
And I am on the homepage #
features/step_definitions/web_steps.rb:44
Scenario: Viewing tickets for a given project #
features/viewing_tickets.feature:20
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
Then I should see "Make it shiny!" #
features/step_definitions/web_steps.rb:105
And I should not see "Standards compliance" #
features/step_definitions/web_steps.rb:123
When I follow "Make it shiny!" #
features/step_definitions/web_steps.rb:56
Then I should see "Make it shiny" within "#ticket h2" #
features/step_definitions/web_steps.rb:35
And I should see "Gradients! Starbursts! Oh my!" #
features/step_definitions/web_steps.rb:105
When I follow "Ticketee" #
features/step_definitions/web_steps.rb:56
And I follow "Internet Explorer" #
features/step_definitions/web_steps.rb:56
Then I should see "Standards compliance" #
features/step_definitions/web_steps.rb:105
And I should not see "Make it shiny!" #
features/step_definitions/web_steps.rb:123
When I follow "Standards compliance" #
features/step_definitions/web_steps.rb:56
Then I should see "Standards compliance" within "#ticket h2" #
features/step_definitions/web_steps.rb:35
And I should see "Isn't a joke." #
features/step_definitions/web_steps.rb:105
Failing Scenarios:
cucumber features/creating_projects.feature:14 # Scenario: Creating a
project
cucumber features/creating_projects.feature:21 # Scenario: Creating a
project without a name
cucumber features/deleting_projects.feature:12 # Scenario: Deleting a
project
cucumber features/editing_projects.feature:16 # Scenario: Updating a
project
cucumber features/editing_projects.feature:22 # Scenario: Updating a
project with invalid attributes is bad
16 scenarios (5 failed, 11 passed)
158 steps (5 failed, 12 skipped, 141 passed)
0m2.705s
I did as the steps in the book but cucumber test is not passing this time !
➜ ticketee git:(master) ✗ rake cucumber:ok
/home/dexter/.rvm/rubies/ruby-1.9.3-p194/bin/ruby -S bundle exec
cucumber --profile default
Rack::File headers parameter replaces cache_control after Rack 1.5.
Using the default profile...
Feature: Creating projects
In order to have projects to assign tickets to
As a user
I want to create them easily
Background: #
features/creating_projects.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password | admin |
| admin@ticketee.com | password | true |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Given I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "New Project" #
features/step_definitions/web_steps.rb:56
Scenario: Creating a project #
features/creating_projects.feature:14
And I fill in "Name" with "TextMate 2" #
features/step_definitions/web_steps.rb:60
Unable to find field "Name" (Capybara::ElementNotFound)
./features/step_definitions/web_steps.rb:61:in `/^(?:|I )fill in
"([^"]*)" with "([^"]*)"$/'
features/creating_projects.feature:15:in `And I fill in "Name"
with "TextMate 2"'
And I press "Create Project" #
features/step_definitions/web_steps.rb:52
Then I should see "Project has been created." #
features/step_definitions/web_steps.rb:105
And I should be on the project page for "TextMate 2" #
features/step_definitions/web_steps.rb:230
And I should see "TextMate 2" #
features/step_definitions/web_steps.rb:105
Scenario: Creating a project without a name #
features/creating_projects.feature:21
And I press "Create Project" #
features/step_definitions/web_steps.rb:52
Unable to find button "Create Project" (Capybara::ElementNotFound)
./features/step_definitions/web_steps.rb:53:in `/^(?:|I )press
"([^"]*)"$/'
features/creating_projects.feature:22:in `And I press "Create
Project"'
Then I should see "Project has not been created." #
features/step_definitions/web_steps.rb:105
And I should see "Name can't be blank" #
features/step_definitions/web_steps.rb:105
Feature: Creating Tickets
In order to create tickets for projects
As a user
I want to be able to select a project and do that
Background:
# features/creating_tickets.feature:6
Given there is a project called "Internet Explorer"
# features/step_definitions/project_steps.rb:1
And there are the following users:
# features/step_definitions/user_steps.rb:1
| email | password |
| user@ticketee.com | password |
And I am on the homepage
# features/step_definitions/web_steps.rb:44
When I follow "Internet Explorer"
# features/step_definitions/web_steps.rb:56
And I follow "New Ticket"
# features/step_definitions/web_steps.rb:56
Then I should see "You need to sign in or sign up before
continuing." # features/step_definitions/web_steps.rb:105
When I fill in "Email" with "user@ticketee.com"
# features/step_definitions/web_steps.rb:60
And I fill in "Password" with "password"
# features/step_definitions/web_steps.rb:60
And I press "Sign in"
# features/step_definitions/web_steps.rb:52
Then I should see "New Ticket"
# features/step_definitions/web_steps.rb:105
Scenario: Creating a ticket
# features/creating_tickets.feature:20
When I fill in "Title" with "Non-standards compliance"
# features/step_definitions/web_steps.rb:60
And I fill in "Description" with "My pages are ugly!"
# features/step_definitions/web_steps.rb:60
And I press "Create Ticket"
# features/step_definitions/web_steps.rb:52
Then I should see "Ticket has been created."
# features/step_definitions/web_steps.rb:105
Then I should see "Created by user@ticketee.com"
# features/step_definitions/web_steps.rb:105
Scenario: Creating a ticket without valid attributes fails
# features/creating_tickets.feature:27
When I press "Create Ticket"
# features/step_definitions/web_steps.rb:52
Then I should see "Ticket has not been created."
# features/step_definitions/web_steps.rb:105
And I should see "Title can't be blank"
# features/step_definitions/web_steps.rb:105
And I should see "Description can't be blank"
# features/step_definitions/web_steps.rb:105
Scenario: Description must be longer than 10 characters
# features/creating_tickets.feature:33
When I fill in "Title" with "Non-standards compliance"
# features/step_definitions/web_steps.rb:60
And I fill in "Description" with "it sucks"
# features/step_definitions/web_steps.rb:60
And I press "Create Ticket"
# features/step_definitions/web_steps.rb:52
Then I should see "Ticket has not been created."
# features/step_definitions/web_steps.rb:105
And I should see "Description is too short"
# features/step_definitions/web_steps.rb:105
Feature: Deleting projects
In order to remove needless projects
As a project manager
I want to make them disappear
Background: #
features/deleting_projects.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password | admin |
| admin@ticketee.com | password | true |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Scenario: Deleting a project #
features/deleting_projects.feature:12
Given there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
And I follow "Delete Project" #
features/step_definitions/web_steps.rb:56
Then I should see "Project has been deleted." #
features/step_definitions/web_steps.rb:105
expected to find text "Project has been deleted." in "You must
be an admin to do that. Ticketee Signed in as admin@ticketee.com
New Project Projects TextMate 2"
(RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/web_steps.rb:107:in `/^(?:|I )should
see "([^"]*)"$/'
features/deleting_projects.feature:17:in `Then I should see
"Project has been deleted."'
Then I should not see "TextMate 2" #
features/step_definitions/web_steps.rb:123
Feature: Deleting tickets
In order to remove tickets
As a user
I want to press a button and make them disappear
Background: #
features/deleting_tickets.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password |
| user@ticketee.com | password |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Given there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And "user@ticketee.com" has created a ticket for this project: #
features/step_definitions/ticket_steps.rb:1
| title | description |
| Make it shiny! | Gradients! Starbursts! Oh my! |
Given I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
And I follow "Make it shiny!" #
features/step_definitions/web_steps.rb:56
Scenario: Deleting a ticket #
features/deleting_tickets.feature:19
When I follow "Delete Ticket" #
features/step_definitions/web_steps.rb:56
Then I should see "Ticket has been deleted." #
features/step_definitions/web_steps.rb:105
And I should be on the project page for "TextMate 2" #
features/step_definitions/web_steps.rb:230
Feature: Editing Projects
In order to update project information
As a user
I want to be able to do that through an interface
Background: #
features/editing_projects.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password | admin |
| admin@ticketee.com | password | true |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Given there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
And I follow "Edit Project" #
features/step_definitions/web_steps.rb:56
Scenario: Updating a project #
features/editing_projects.feature:16
And I fill in "Name" with "TextMate 2 beta" #
features/step_definitions/web_steps.rb:60
Unable to find field "Name" (Capybara::ElementNotFound)
./features/step_definitions/web_steps.rb:61:in `/^(?:|I )fill in
"([^"]*)" with "([^"]*)"$/'
features/editing_projects.feature:17:in `And I fill in "Name"
with "TextMate 2 beta"'
And I press "Update Project" #
features/step_definitions/web_steps.rb:52
Then I should see "Project has been updated." #
features/step_definitions/web_steps.rb:105
Then I should be on the project page for "TextMate 2 beta" #
features/step_definitions/web_steps.rb:230
Scenario: Updating a project with invalid attributes is bad #
features/editing_projects.feature:22
And I fill in "Name" with "" #
features/step_definitions/web_steps.rb:60
Unable to find field "Name" (Capybara::ElementNotFound)
./features/step_definitions/web_steps.rb:61:in `/^(?:|I )fill in
"([^"]*)" with "([^"]*)"$/'
features/editing_projects.feature:23:in `And I fill in "Name"
with ""'
And I press "Update Project" #
features/step_definitions/web_steps.rb:52
Then I should see "Project has not been updated." #
features/step_definitions/web_steps.rb:105
Feature: Editing tickets
In order to alter ticket information
As a user
I want a form to edit the tickets
Background: #
features/editing_tickets.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password |
| user@ticketee.com | password |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Given there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And "user@ticketee.com" has created a ticket for this project: #
features/step_definitions/ticket_steps.rb:1
| title | description |
| Make it shiny! | Gradients! Starbursts! Oh my! |
Given I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
And I follow "Make it shiny!" #
features/step_definitions/web_steps.rb:56
When I follow "Edit Ticket" #
features/step_definitions/web_steps.rb:56
Scenario: Updating a ticket #
features/editing_tickets.feature:20
When I fill in "Title" with "Make it really shiny!" #
features/step_definitions/web_steps.rb:60
And I press "Update Ticket" #
features/step_definitions/web_steps.rb:52
Then I should see "Ticket has been updated." #
features/step_definitions/web_steps.rb:105
And I should see "Make it really shiny!" within "#ticket h2" #
features/step_definitions/web_steps.rb:35
But I should not see "Make it shiny!" #
features/step_definitions/web_steps.rb:123
Scenario: Updating a ticket with invalid information #
features/editing_tickets.feature:27
When I fill in "Title" with "" #
features/step_definitions/web_steps.rb:60
And I press "Update Ticket" #
features/step_definitions/web_steps.rb:52
Then I should see "Ticket has not been updated." #
features/step_definitions/web_steps.rb:105
Feature: Signing in
In order to use the site
As a user
I want to be able to sign in
Scenario: Siging in via confirmation
# features/signing_in.feature:6
Given there are the following users:
# features/step_definitions/user_steps.rb:1
| email | password | unconfirmed |
| user@ticketee.com | password | true |
And "user@ticketee.com" opens the email with subject "Confirmation
instructions" # features/step_definitions/email_steps.rb:80
And they click the first link in the email
# features/step_definitions/email_steps.rb:182
Then I should see "Your account was successfully confirmed"
# features/step_definitions/web_steps.rb:105
And I should see "Signed in as user@ticketee.com"
# features/step_definitions/web_steps.rb:105
Scenario: Signing in via form # features/signing_in.feature:15
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password |
| user@ticketee.com | password |
And I am signed in as them #
features/step_definitions/user_steps.rb:11
Feature: Signing up
In order to be attributed for my work
As a user
I want to be able to sign up
Scenario: Signing up #
features/signing_up.feature:6
Given I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "Sign up" #
features/step_definitions/web_steps.rb:56
And I fill in "Email" with "user@ticketee.com" #
features/step_definitions/web_steps.rb:60
And I fill in "Password" with "password" #
features/step_definitions/web_steps.rb:60
And I fill in "Password confirmation" with "password" #
features/step_definitions/web_steps.rb:60
And I press "Sign up" #
features/step_definitions/web_steps.rb:52
Then I should see "You have signed up successfully." #
features/step_definitions/web_steps.rb:105
Feature: Viewing projects
In order to assign tickets to a project
As a user
I want to be able to see a list of available projects
Scenario: Listing all projects #
features/viewing_projects.feature:6
Given there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And I am on the homepage #
features/step_definitions/web_steps.rb:44
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
Then I should be on the project page for "TextMate 2" #
features/step_definitions/web_steps.rb:230
Feature: Viewing tickets
In order ro view the tickets for a project
As a user
I want to see them on that project's page
Background: #
features/viewing_tickets.feature:6
Given there are the following users: #
features/step_definitions/user_steps.rb:1
| email | password |
| user@ticketee.com | password |
And there is a project called "TextMate 2" #
features/step_definitions/project_steps.rb:1
And "user@ticketee.com" has created a ticket for this project: #
features/step_definitions/ticket_steps.rb:1
| title | description |
| Make it shiny! | Gradients! Starbursts! Oh my! |
And there is a project called "Internet Explorer" #
features/step_definitions/project_steps.rb:1
And "user@ticketee.com" has created a ticket for this project: #
features/step_definitions/ticket_steps.rb:1
| title | description |
| Standards compliance | Isn't a joke. |
And I am on the homepage #
features/step_definitions/web_steps.rb:44
Scenario: Viewing tickets for a given project #
features/viewing_tickets.feature:20
When I follow "TextMate 2" #
features/step_definitions/web_steps.rb:56
Then I should see "Make it shiny!" #
features/step_definitions/web_steps.rb:105
And I should not see "Standards compliance" #
features/step_definitions/web_steps.rb:123
When I follow "Make it shiny!" #
features/step_definitions/web_steps.rb:56
Then I should see "Make it shiny" within "#ticket h2" #
features/step_definitions/web_steps.rb:35
And I should see "Gradients! Starbursts! Oh my!" #
features/step_definitions/web_steps.rb:105
When I follow "Ticketee" #
features/step_definitions/web_steps.rb:56
And I follow "Internet Explorer" #
features/step_definitions/web_steps.rb:56
Then I should see "Standards compliance" #
features/step_definitions/web_steps.rb:105
And I should not see "Make it shiny!" #
features/step_definitions/web_steps.rb:123
When I follow "Standards compliance" #
features/step_definitions/web_steps.rb:56
Then I should see "Standards compliance" within "#ticket h2" #
features/step_definitions/web_steps.rb:35
And I should see "Isn't a joke." #
features/step_definitions/web_steps.rb:105
Failing Scenarios:
cucumber features/creating_projects.feature:14 # Scenario: Creating a
project
cucumber features/creating_projects.feature:21 # Scenario: Creating a
project without a name
cucumber features/deleting_projects.feature:12 # Scenario: Deleting a
project
cucumber features/editing_projects.feature:16 # Scenario: Updating a
project
cucumber features/editing_projects.feature:22 # Scenario: Updating a
project with invalid attributes is bad
16 scenarios (5 failed, 11 passed)
158 steps (5 failed, 12 skipped, 141 passed)
0m2.705s
Thursday, 29 August 2013
How to add a character in xml from the internet
How to add a character in xml from the internet
I'm creating a rss feed using Sax. The xml is from the internet. The
problem is that the date looks like "1407"
Example:
<example name="DAvid" id="1" test1="1407" test2="0811">
What I need is to insert the simbol "-" between the 14 and the 07. How
could I do that?
The parse here:
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xReader = saxP.getXMLReader();
itemHoroscopeXMLHandler = new ItemHoroscopeXMLHandler();
xr.setContentHandler(itemHoroscopeXMLHandler);
Reader reader = new InputStreamReader(new
URL("http://example.xml").openStream(),
Charset.forName("ISO-8859-1"));
InputSource is = new InputSource (reader);
xReader.parse(is);
I'm creating a rss feed using Sax. The xml is from the internet. The
problem is that the date looks like "1407"
Example:
<example name="DAvid" id="1" test1="1407" test2="0811">
What I need is to insert the simbol "-" between the 14 and the 07. How
could I do that?
The parse here:
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xReader = saxP.getXMLReader();
itemHoroscopeXMLHandler = new ItemHoroscopeXMLHandler();
xr.setContentHandler(itemHoroscopeXMLHandler);
Reader reader = new InputStreamReader(new
URL("http://example.xml").openStream(),
Charset.forName("ISO-8859-1"));
InputSource is = new InputSource (reader);
xReader.parse(is);
Wednesday, 28 August 2013
understanding recursion vs loops
understanding recursion vs loops
I have the following recursion method. I get an error stack overflow. it
stops at -9352. My questions, is stack overflow the same as an infinite
loop? Because this will keep calling itself.
But if I do a infinite loop with while, until, do, etc it doesn't give me
the same stack overflow error. It just keeps going until my system runs
out of memory.
def recursion(n)
print n
recursion(n-1)
end
recursion(3)
I have the following recursion method. I get an error stack overflow. it
stops at -9352. My questions, is stack overflow the same as an infinite
loop? Because this will keep calling itself.
But if I do a infinite loop with while, until, do, etc it doesn't give me
the same stack overflow error. It just keeps going until my system runs
out of memory.
def recursion(n)
print n
recursion(n-1)
end
recursion(3)
I don't plan to use a clustered index on my table, will I regret it?
I don't plan to use a clustered index on my table, will I regret it?
pFor simplicity, let's say I have a table 'Car' in Sql Server. It has 2
columns. 'Id' is a uniqueidentifier/Guid and is the primary key. 'Name' is
a nvarchar/string. The database will be for a lightly used app that peaks
at maybe 10 concurrent users. 'Car' could have thousands of rows. It will
be queried, inserted, and updated regularly./p pI know it's bad in general
to have a clustered index on a Guid column, so my plan is to leave the
table as a heap and have no clustered indexes. I'd have a non-clustered
index on Id./p pIn this very simple scenario, is there any reason I would
regret not having a clustered index? If you say yes, please explain the
reasoning behind your answer. I've seen posts where people say things like
I'd add an int column just to add a clustered index. I can't figure out
why anyone would do that if you don't plan on querying against the int
column anyways, what value does it add?/p pAlso for this example, please
assume newsequentialid() isn't an option. I'm using Entity Framework model
first and it's a pain to use (unless someone can point to an easy way to
do this I missed). Also assume a Guid PK is a requirement (it's an
existing system)./p
pFor simplicity, let's say I have a table 'Car' in Sql Server. It has 2
columns. 'Id' is a uniqueidentifier/Guid and is the primary key. 'Name' is
a nvarchar/string. The database will be for a lightly used app that peaks
at maybe 10 concurrent users. 'Car' could have thousands of rows. It will
be queried, inserted, and updated regularly./p pI know it's bad in general
to have a clustered index on a Guid column, so my plan is to leave the
table as a heap and have no clustered indexes. I'd have a non-clustered
index on Id./p pIn this very simple scenario, is there any reason I would
regret not having a clustered index? If you say yes, please explain the
reasoning behind your answer. I've seen posts where people say things like
I'd add an int column just to add a clustered index. I can't figure out
why anyone would do that if you don't plan on querying against the int
column anyways, what value does it add?/p pAlso for this example, please
assume newsequentialid() isn't an option. I'm using Entity Framework model
first and it's a pain to use (unless someone can point to an easy way to
do this I missed). Also assume a Guid PK is a requirement (it's an
existing system)./p
SSRS rounds to whole numbers, but includes 2 decimal places
SSRS rounds to whole numbers, but includes 2 decimal places
I have some SQL, of which the part in question is:
sum(Minutes)/60.0 Hrs
In SQL Server Management Studio, my database returns:
14.500000
In SSRS, my report displays:
14.00
My RDL's cell that displays this value has this definition:
=Fields!Hrs.Value
The cell's textbox properties have been defined as a Number, no checkboxes
selected, 2 decimal points.
So, the question is, why is my report only outputting 14.00 rather than
14.50 and how can I fix it?
I have some SQL, of which the part in question is:
sum(Minutes)/60.0 Hrs
In SQL Server Management Studio, my database returns:
14.500000
In SSRS, my report displays:
14.00
My RDL's cell that displays this value has this definition:
=Fields!Hrs.Value
The cell's textbox properties have been defined as a Number, no checkboxes
selected, 2 decimal points.
So, the question is, why is my report only outputting 14.00 rather than
14.50 and how can I fix it?
Multiple applications sharing a single system-wide socket
Multiple applications sharing a single system-wide socket
I'm trying to develop a network library in my free time. I read a lot
about how to do it and I was impressed by an idea from UDT were any number
of applications can use a single port on a machine.
I got the basic socket interaction working already. What I plan to do now
is to create a class that is in charge for routing incoming messages to
the application that had previously registered its protocol number with
it. If there is no application for the received package, it is dropped.
What I want to achieve is that a chat program may run next to an MMOG
client may run next to a data transfer pipeline, all sharing the same port
and application base. They just have to retrieve a reference to the
"Connection Manager" (I'm using UDP as transportation, so "connections" is
not the correct term), register the protocol ID with it and are informed
about incoming messages and may send messages this way.
Since I'm working on this in C# for .NET/Mono 4.0+, how would I implement
a similar approach? Is COM a way or is the CLI implementing such a thing
in a platform independent manner?
For anyone interested in sources: I develop this on GitHub and could use
some extra pair of eyes ;)
I'm trying to develop a network library in my free time. I read a lot
about how to do it and I was impressed by an idea from UDT were any number
of applications can use a single port on a machine.
I got the basic socket interaction working already. What I plan to do now
is to create a class that is in charge for routing incoming messages to
the application that had previously registered its protocol number with
it. If there is no application for the received package, it is dropped.
What I want to achieve is that a chat program may run next to an MMOG
client may run next to a data transfer pipeline, all sharing the same port
and application base. They just have to retrieve a reference to the
"Connection Manager" (I'm using UDP as transportation, so "connections" is
not the correct term), register the protocol ID with it and are informed
about incoming messages and may send messages this way.
Since I'm working on this in C# for .NET/Mono 4.0+, how would I implement
a similar approach? Is COM a way or is the CLI implementing such a thing
in a platform independent manner?
For anyone interested in sources: I develop this on GitHub and could use
some extra pair of eyes ;)
Loading a URL when dropdown option Changes in YUI
Loading a URL when dropdown option Changes in YUI
I am trying to load a URL when a drop down menu changes via YUI Change
event. I just want to navigate to that URL.
I made a long search. But didn't got any way.
Thanks :)
I am trying to load a URL when a drop down menu changes via YUI Change
event. I just want to navigate to that URL.
I made a long search. But didn't got any way.
Thanks :)
Reading UTF8 encoded CSV and converting to Unicode
Reading UTF8 encoded CSV and converting to Unicode
I'm reading in a CSV file that has UTF8 encoding:
ifile = open(fname, "r")
for row in csv.reader(ifile):
name = row[0]
print repr(row[0])
This works fine, and prints out what I expect it to print out; a UTF8
encoded str:
> '\xc3\x81lvaro Salazar'
> '\xc3\x89lodie Yung'
...
Furthermore when I simply print the str (as opposed to repr()) the output
displays ok (which I don't understand eitherway - shouldn't this cause an
error?):
> Álvaro Salazar
> Élodie Yung
but when I try to convert my UTF8 encoded strs to unicode:
ifile = open(fname, "r")
for row in csv.reader(ifile):
name = row[0]
print unicode(name, 'utf-8') # or name.decode('utf-8')
I get the infamous:
Traceback (most recent call last):
File "scripts/script.py", line 33, in <module>
print unicode(fullname, 'utf-8')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xc1' in
position 0: ordinal not in range(128)
So I looked at the unicode strings that are created:
ifile = open(fname, "r")
for row in csv.reader(ifile):
name = row[0]
unicode_name = unicode(name, 'utf-8')
print repr(unicode_name)
and the output is
> u'\xc1lvaro Salazar'
> u'\xc9lodie Yung'
So now I'm totally confused as these seem to be mangled hex values. I've
read this question:
Reading a UTF8 CSV file with Python
and it appears I am doing everything correctly, leading me to believe that
my file is not actually UTF8, but when I initially print out the repr
values of the cells, they appear to to correct UTF8 hex values. Can anyone
either point out my problem or indicate where my understanding is breaking
down (as I'm starting to get lost in the jungle of encodings)
As an aside, I believe I could use codecs to open the file and read it
directly into unicode objects, but the csv module doesn't support unicode
natively so I can use this approach.
I'm reading in a CSV file that has UTF8 encoding:
ifile = open(fname, "r")
for row in csv.reader(ifile):
name = row[0]
print repr(row[0])
This works fine, and prints out what I expect it to print out; a UTF8
encoded str:
> '\xc3\x81lvaro Salazar'
> '\xc3\x89lodie Yung'
...
Furthermore when I simply print the str (as opposed to repr()) the output
displays ok (which I don't understand eitherway - shouldn't this cause an
error?):
> Álvaro Salazar
> Élodie Yung
but when I try to convert my UTF8 encoded strs to unicode:
ifile = open(fname, "r")
for row in csv.reader(ifile):
name = row[0]
print unicode(name, 'utf-8') # or name.decode('utf-8')
I get the infamous:
Traceback (most recent call last):
File "scripts/script.py", line 33, in <module>
print unicode(fullname, 'utf-8')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xc1' in
position 0: ordinal not in range(128)
So I looked at the unicode strings that are created:
ifile = open(fname, "r")
for row in csv.reader(ifile):
name = row[0]
unicode_name = unicode(name, 'utf-8')
print repr(unicode_name)
and the output is
> u'\xc1lvaro Salazar'
> u'\xc9lodie Yung'
So now I'm totally confused as these seem to be mangled hex values. I've
read this question:
Reading a UTF8 CSV file with Python
and it appears I am doing everything correctly, leading me to believe that
my file is not actually UTF8, but when I initially print out the repr
values of the cells, they appear to to correct UTF8 hex values. Can anyone
either point out my problem or indicate where my understanding is breaking
down (as I'm starting to get lost in the jungle of encodings)
As an aside, I believe I could use codecs to open the file and read it
directly into unicode objects, but the csv module doesn't support unicode
natively so I can use this approach.
STAthread doesn't let me print reports in c#
STAthread doesn't let me print reports in c#
I have problem with my application. The application starts with login form
then I'm using the following thread to run my application.
Thread t = new Thread(Program.RunApplication);
t.Start();
Thread.Sleep(2000);
but I have problem now when trying to save any of my reports as excel or
pdf it gives me error current thread must be sit to single thread which I
made by adding
[STAThread]
before my Main[] but now I don't really know what is the problem.
Can anybody help please?
I have problem with my application. The application starts with login form
then I'm using the following thread to run my application.
Thread t = new Thread(Program.RunApplication);
t.Start();
Thread.Sleep(2000);
but I have problem now when trying to save any of my reports as excel or
pdf it gives me error current thread must be sit to single thread which I
made by adding
[STAThread]
before my Main[] but now I don't really know what is the problem.
Can anybody help please?
Tuesday, 27 August 2013
Operation could destabilize the runtime Enterprise Library 6
Operation could destabilize the runtime Enterprise Library 6
I created a .NET 4.5 Console app to try out the Semantic Logging bits in
the new Ent Lib v6. Using the sample code from the PDF:
var listener2 = new ObservableEventListener();
listener2.EnableEvents( EventSourceCore.Log , EventLevel.LogAlways ,
Keywords.All );
SinkSubscription<SqlDatabaseSink> subscription =
listener2.LogToSqlDatabase( "Demo Semantic Logging Instance" ,
ConfigurationManager.AppSettings["mdbconn"] );
Running the code immediately gives the error "Operation could destabilize
the runtime". Looking at the stack trace within the Exception helper from
VS2012, I see
at
Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling.RetryPolicy`1..ctor(Int32
retryCount, TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan
deltaBackoff)
at
Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Sinks.SqlDatabaseSink..ctor(String
instanceName, String connectionString, String tableName, TimeSpan
bufferingInterval, Int32 bufferingCount, Int32 maxBufferSize, TimeSpan
onCompletedTimeout)
at
Microsoft.Practices.EnterpriseLibrary.SemanticLogging.SqlDatabaseLog.LogToSqlDatabase(IObservable`1
eventStream, String instanceName, String connectionString, String
tableName, Nullable`1 bufferingInterval, Int32 bufferingCount,
Nullable`1 onCompletedTimeout, Int32 maxBufferSize)
at svc2.Program.LogPrep() in c:\cos\Program.cs:line 66
at svc2.Program.Main(String[] args) in c:\cos\Program.cs:line 23
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,
String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence
assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Looking at the Entlib source code, line 32 in SqlDatabaseSink.cs shows
private readonly RetryPolicy retryPolicy = new
RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(5,
TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(1),
TimeSpan.FromSeconds(5));
Going to line 59 in RetryPolicyGeneric.cs that shows
public RetryPolicy(int retryCount, TimeSpan minBackoff, TimeSpan
maxBackoff, TimeSpan deltaBackoff)
: base(new T(), retryCount, minBackoff, maxBackoff, deltaBackoff)
But I don't see anything like an implicit cast that could be causing the
problem, that was found in other SO posts.
What did I miss? Has anyone actually seen the logging block work "out of
the box"?
Thanks,
I created a .NET 4.5 Console app to try out the Semantic Logging bits in
the new Ent Lib v6. Using the sample code from the PDF:
var listener2 = new ObservableEventListener();
listener2.EnableEvents( EventSourceCore.Log , EventLevel.LogAlways ,
Keywords.All );
SinkSubscription<SqlDatabaseSink> subscription =
listener2.LogToSqlDatabase( "Demo Semantic Logging Instance" ,
ConfigurationManager.AppSettings["mdbconn"] );
Running the code immediately gives the error "Operation could destabilize
the runtime". Looking at the stack trace within the Exception helper from
VS2012, I see
at
Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling.RetryPolicy`1..ctor(Int32
retryCount, TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan
deltaBackoff)
at
Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Sinks.SqlDatabaseSink..ctor(String
instanceName, String connectionString, String tableName, TimeSpan
bufferingInterval, Int32 bufferingCount, Int32 maxBufferSize, TimeSpan
onCompletedTimeout)
at
Microsoft.Practices.EnterpriseLibrary.SemanticLogging.SqlDatabaseLog.LogToSqlDatabase(IObservable`1
eventStream, String instanceName, String connectionString, String
tableName, Nullable`1 bufferingInterval, Int32 bufferingCount,
Nullable`1 onCompletedTimeout, Int32 maxBufferSize)
at svc2.Program.LogPrep() in c:\cos\Program.cs:line 66
at svc2.Program.Main(String[] args) in c:\cos\Program.cs:line 23
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,
String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence
assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Looking at the Entlib source code, line 32 in SqlDatabaseSink.cs shows
private readonly RetryPolicy retryPolicy = new
RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(5,
TimeSpan.FromSeconds(1), TimeSpan.FromMinutes(1),
TimeSpan.FromSeconds(5));
Going to line 59 in RetryPolicyGeneric.cs that shows
public RetryPolicy(int retryCount, TimeSpan minBackoff, TimeSpan
maxBackoff, TimeSpan deltaBackoff)
: base(new T(), retryCount, minBackoff, maxBackoff, deltaBackoff)
But I don't see anything like an implicit cast that could be causing the
problem, that was found in other SO posts.
What did I miss? Has anyone actually seen the logging block work "out of
the box"?
Thanks,
writting a case statement in Ms SQL
writting a case statement in Ms SQL
After i run my select statement i get the following values "see image"
want i would like to di is have case statement to check if
"BloodPressureSystolic == 0 and if BloodPressureDiastolic == 0" then pull
the values from "BPSRSit and BPSRSit" and add then add the values to the
temp table like this "115/65" can someone show me how to write a case like
that.
here is my select statement that i would like to add a case statement to
select ad.ApptDate ,
ISNULL(v.Temperature, 0) as Temperature,
ISNULL(v.PS, 0) as PerfStatus,
v.*
from vitals v,AppointmentData ad
Where v.PatientId = 11
And ad.ApptId = v.ScheduleId
and ad.ApptDate < GETDATE()
and ad.StatusId not in (3,8)
After i run my select statement i get the following values "see image"
want i would like to di is have case statement to check if
"BloodPressureSystolic == 0 and if BloodPressureDiastolic == 0" then pull
the values from "BPSRSit and BPSRSit" and add then add the values to the
temp table like this "115/65" can someone show me how to write a case like
that.
here is my select statement that i would like to add a case statement to
select ad.ApptDate ,
ISNULL(v.Temperature, 0) as Temperature,
ISNULL(v.PS, 0) as PerfStatus,
v.*
from vitals v,AppointmentData ad
Where v.PatientId = 11
And ad.ApptId = v.ScheduleId
and ad.ApptDate < GETDATE()
and ad.StatusId not in (3,8)
jQuery replace text when clicking over different input text objects
jQuery replace text when clicking over different input text objects
I'm new to JS/jQuery. WHat I try to achieve is that every time I press
over "Title" or "Description", only the current's text area message should
appear.
I tried to clone the original div, but I really didn't know where or how
to use it, so this idea of replacing the text seemed easier to implement.
As I said, I'm new to web programming and I really hit the rock. I don't
understand why the following code doesn't work:
http://jsfiddle.net/MceE9/
<div class="content">
<form method="POST" id="anunt">
<table id="anunt">
<tr id="title">
<td> Title: </td>
<td> <input type='text' name='title' id='titleClick'> </td>
</tr>
<tr id="description">
<td> Description: </td>
<td> <textarea rows="5" cols="40" id="descriptionClick"
name="description"></textarea> </td>
</tr>
<tr>
<td> <input type="submit" name="send" value="Send"> </td>
</tr>
</table>
</form>
var title;
var description;
$('#titleClick').one('click', function(){
title = '<span id="text" style="font-weight: bold; font-size:
18px; color: red;">Title text</span>';
$("#title").append(title);
$('#description').html($('#description').html().replace(description,
''));
});
$('#descriptionClick').one('click', function(){
description = '<span id="text" style="float:left; font-weight:
bold; font-size: 18px; color: red;"> Description text</span>';
$("#description").append(description);
$('#title').html($('#title').html().replace(title, ''));
});
I'm new to JS/jQuery. WHat I try to achieve is that every time I press
over "Title" or "Description", only the current's text area message should
appear.
I tried to clone the original div, but I really didn't know where or how
to use it, so this idea of replacing the text seemed easier to implement.
As I said, I'm new to web programming and I really hit the rock. I don't
understand why the following code doesn't work:
http://jsfiddle.net/MceE9/
<div class="content">
<form method="POST" id="anunt">
<table id="anunt">
<tr id="title">
<td> Title: </td>
<td> <input type='text' name='title' id='titleClick'> </td>
</tr>
<tr id="description">
<td> Description: </td>
<td> <textarea rows="5" cols="40" id="descriptionClick"
name="description"></textarea> </td>
</tr>
<tr>
<td> <input type="submit" name="send" value="Send"> </td>
</tr>
</table>
</form>
var title;
var description;
$('#titleClick').one('click', function(){
title = '<span id="text" style="font-weight: bold; font-size:
18px; color: red;">Title text</span>';
$("#title").append(title);
$('#description').html($('#description').html().replace(description,
''));
});
$('#descriptionClick').one('click', function(){
description = '<span id="text" style="float:left; font-weight:
bold; font-size: 18px; color: red;"> Description text</span>';
$("#description").append(description);
$('#title').html($('#title').html().replace(title, ''));
});
XSLT Data Merge
XSLT Data Merge
I have a very basic knowledge of XSLT and I am currently trying to achieve
something which I am still trying to figure out if its possible.
Can be XSLT 1.0 or 2.0
Basically this is the structure of my XML
<?xml version="1.0" encoding="windows-1252"?>
<Root>
<DataPage>
<Record>
<TEMP>xxx</TEMP>
<DEBITNO>6250281</DEBITNO>
<DOSSIERNUMMERINT>2012365</DOSSIERNUMMERINT>
<ID>0123456789Z60</ID>
<DATE>31/01/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 1</DESC>
<AMOUNT> 38170.0000000</AMOUNT>
<HEAD>123</HEAD>
</Record>
</DataPage>
<DataPage>
<Record>
<TEMP>xxx</TEMP>
<DEBITNO>6250281</DEBITNO>
<DOSSIERNUMMERINT>2012365</DOSSIERNUMMERINT>
<ID>0123456789Z70</ID>
<DATE>22/02/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 2</DESC>
<AMOUNT> 14410.0000000</AMOUNT>
<HEAD>123</HEAD>
</Record>
</DataPage>
<DataPage>
<Record>
<TEMP>xxx</TEMP>
<DEBITNO>3849322</DEBITNO>
<DOSSIERNUMMERINT>20132394</DOSSIERNUMMERINT>
<ID>34958701223Z20</ID>
<DATE>06/01/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 1</DESC>
<AMOUNT> 33811.0000000</AMOUNT>
<HEAD>567</HEAD>
</Record>
</DataPage>
</Root>
I would like this the output the following
<?xml version="1.0" encoding="windows-1252"?>
<Root>
<DataPage>
<Record>
<TEMP>xxx</TEMP>
<DEBITNO>6250281</DEBITNO>
<DOSSIERNUMMERINT>2012365</DOSSIERNUMMERINT>
<Line>
<ID>0123456789Z60</ID>
<DATE>31/01/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 1</DESC>
<AMOUNT> 38170.0000000</AMOUNT>
</Line>
<Line>
<ID>0123456789Z70</ID>
<DATE>22/02/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 2</DESC>
<AMOUNT> 14410.0000000</AMOUNT>
</Line>
<HEAD>123</HEAD>
</Record>
</DataPage>
<DataPage>
<Record>
<TEMP>xxx</TEMP>
<DEBITNO>3849322</DEBITNO>
<DOSSIERNUMMERINT>20132394</DOSSIERNUMMERINT>
<Line>
<ID>34958701223Z20</ID>
<DATE>06/01/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 1</DESC>
<AMOUNT> 33811.0000000</AMOUNT>
</Line>
<HEAD>567</HEAD>
</Record>
</DataPage>
</Root>
So the logic would be to merge all records with the same DEBITNO.
The rules for the merge is everything other than ID, Date, Year, DESC and
AMOUNT can be taken from the 1st appearance
ID, Date, Year, DESC and AMOUNT needs to be placed into a tag, so if there
are 2 records with the same DEBITNO there will be 2 line items, if there
are 5 records with the same DEBITNO the resulting record will have 5 line
items.
I hope that makes sense.
Is something like this possible?
Regards,
I have a very basic knowledge of XSLT and I am currently trying to achieve
something which I am still trying to figure out if its possible.
Can be XSLT 1.0 or 2.0
Basically this is the structure of my XML
<?xml version="1.0" encoding="windows-1252"?>
<Root>
<DataPage>
<Record>
<TEMP>xxx</TEMP>
<DEBITNO>6250281</DEBITNO>
<DOSSIERNUMMERINT>2012365</DOSSIERNUMMERINT>
<ID>0123456789Z60</ID>
<DATE>31/01/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 1</DESC>
<AMOUNT> 38170.0000000</AMOUNT>
<HEAD>123</HEAD>
</Record>
</DataPage>
<DataPage>
<Record>
<TEMP>xxx</TEMP>
<DEBITNO>6250281</DEBITNO>
<DOSSIERNUMMERINT>2012365</DOSSIERNUMMERINT>
<ID>0123456789Z70</ID>
<DATE>22/02/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 2</DESC>
<AMOUNT> 14410.0000000</AMOUNT>
<HEAD>123</HEAD>
</Record>
</DataPage>
<DataPage>
<Record>
<TEMP>xxx</TEMP>
<DEBITNO>3849322</DEBITNO>
<DOSSIERNUMMERINT>20132394</DOSSIERNUMMERINT>
<ID>34958701223Z20</ID>
<DATE>06/01/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 1</DESC>
<AMOUNT> 33811.0000000</AMOUNT>
<HEAD>567</HEAD>
</Record>
</DataPage>
</Root>
I would like this the output the following
<?xml version="1.0" encoding="windows-1252"?>
<Root>
<DataPage>
<Record>
<TEMP>xxx</TEMP>
<DEBITNO>6250281</DEBITNO>
<DOSSIERNUMMERINT>2012365</DOSSIERNUMMERINT>
<Line>
<ID>0123456789Z60</ID>
<DATE>31/01/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 1</DESC>
<AMOUNT> 38170.0000000</AMOUNT>
</Line>
<Line>
<ID>0123456789Z70</ID>
<DATE>22/02/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 2</DESC>
<AMOUNT> 14410.0000000</AMOUNT>
</Line>
<HEAD>123</HEAD>
</Record>
</DataPage>
<DataPage>
<Record>
<TEMP>xxx</TEMP>
<DEBITNO>3849322</DEBITNO>
<DOSSIERNUMMERINT>20132394</DOSSIERNUMMERINT>
<Line>
<ID>34958701223Z20</ID>
<DATE>06/01/2013</DATE>
<YEAR>2006</YEAR>
<DESC>Test Item 1</DESC>
<AMOUNT> 33811.0000000</AMOUNT>
</Line>
<HEAD>567</HEAD>
</Record>
</DataPage>
</Root>
So the logic would be to merge all records with the same DEBITNO.
The rules for the merge is everything other than ID, Date, Year, DESC and
AMOUNT can be taken from the 1st appearance
ID, Date, Year, DESC and AMOUNT needs to be placed into a tag, so if there
are 2 records with the same DEBITNO there will be 2 line items, if there
are 5 records with the same DEBITNO the resulting record will have 5 line
items.
I hope that makes sense.
Is something like this possible?
Regards,
Dell Vostro 1510, Unable to connect to WIFI
Dell Vostro 1510, Unable to connect to WIFI
I have Dell Vostro 1510. I have installed Blackbuntu 12.04 and wireless
does not detect. Tried:
rfkill unblock all
Still; same issue, restarted aswell.
rfkill list all
0: hci0: Bluetooth Soft blocked:0 Hard Blocked:0
Have also Tried rfkill unblock all sudo /etc/init.d/networking restart
Wifi Adapter also doesnt seem to get detected
Still same issue Please help
I have Dell Vostro 1510. I have installed Blackbuntu 12.04 and wireless
does not detect. Tried:
rfkill unblock all
Still; same issue, restarted aswell.
rfkill list all
0: hci0: Bluetooth Soft blocked:0 Hard Blocked:0
Have also Tried rfkill unblock all sudo /etc/init.d/networking restart
Wifi Adapter also doesnt seem to get detected
Still same issue Please help
Monday, 26 August 2013
LaTeX3: l3keys Multiple-Choices Keys and Startup Value for Predefined Choice Integer Variable
LaTeX3: l3keys Multiple-Choices Keys and Startup Value for Predefined
Choice Integer Variable
In the interface3 documentation it can be read (what follows is not a
literal quotation) that the variable \l_keys_choice_int is available to be
used as an index register for a multiple-choices key with its values
starting up from 0. Nonetheless, according to my experience with the code
below, it is as though the starting value is actually 1.
This is my class, in a file insightfully called myclass.cls:
\RequirePackage{l3keys2e,xparse}
\ProvidesExplClass
{myclass}
{2013/08/25}
{1.0}
{myclass}
\bool_new:N \g_myclass_enum_bool
\bool_new:N \g_myclass_enumalt_bool
\NewDocumentCommand \SetTBool { m }
{
\bool_gset_true:c
{ g_myclass_\tl_trim_spaces:n {#1} _bool}
}
\NewDocumentCommand \TypeBool { m }
{ \bool_if:cTF { g_myclass_#1_bool } { T } { F } }
\keys_define:nn { myclass }
{
alter .choice_code:n =
{
\AtBeginDocument{Option ~ Index: ~ \int_use:N \l_keys_choice_int\par}
\int_compare:nNnTF { \l_keys_choice_int } = { 1 }
{ \SetTBool { enum } }
{ \SetTBool { enumalt } }
},
alter .generate_choices:n = { enum, enumalt }
}
\ProcessKeysOptions { myclass }
\LoadClass{memoir}
Then I have a document file by the original name mydoc.tex reading thus:
\documentclass[alter = enum]{myclass}
\begin{document}
\TypeBool{enum}\par
\TypeBool{enumalt}
\end{document}
What I get in my typeset document is 1 T F, whereas according to the
documentation I should get 0 T F. Moreover, if I set the class option
alter = enumalt, I get 2 F T. Am I getting something wrong?
Choice Integer Variable
In the interface3 documentation it can be read (what follows is not a
literal quotation) that the variable \l_keys_choice_int is available to be
used as an index register for a multiple-choices key with its values
starting up from 0. Nonetheless, according to my experience with the code
below, it is as though the starting value is actually 1.
This is my class, in a file insightfully called myclass.cls:
\RequirePackage{l3keys2e,xparse}
\ProvidesExplClass
{myclass}
{2013/08/25}
{1.0}
{myclass}
\bool_new:N \g_myclass_enum_bool
\bool_new:N \g_myclass_enumalt_bool
\NewDocumentCommand \SetTBool { m }
{
\bool_gset_true:c
{ g_myclass_\tl_trim_spaces:n {#1} _bool}
}
\NewDocumentCommand \TypeBool { m }
{ \bool_if:cTF { g_myclass_#1_bool } { T } { F } }
\keys_define:nn { myclass }
{
alter .choice_code:n =
{
\AtBeginDocument{Option ~ Index: ~ \int_use:N \l_keys_choice_int\par}
\int_compare:nNnTF { \l_keys_choice_int } = { 1 }
{ \SetTBool { enum } }
{ \SetTBool { enumalt } }
},
alter .generate_choices:n = { enum, enumalt }
}
\ProcessKeysOptions { myclass }
\LoadClass{memoir}
Then I have a document file by the original name mydoc.tex reading thus:
\documentclass[alter = enum]{myclass}
\begin{document}
\TypeBool{enum}\par
\TypeBool{enumalt}
\end{document}
What I get in my typeset document is 1 T F, whereas according to the
documentation I should get 0 T F. Moreover, if I set the class option
alter = enumalt, I get 2 F T. Am I getting something wrong?
Running Topcoder arena applet behind University firewall
Running Topcoder arena applet behind University firewall
I am posting this question here after redirection from stackoverflow. I
don't know if it's appropriate or not but I'm dying to get a solution. In
our University, connections to external IP through the non standard port
is blocked as a result of which I can't run Top Coder arena applet by
filling in the proxy details (We connect through proxy). I then have to
use Tor to route the traffic through the socks for the applet. Here is
what I do :
Run tor and establish a network.
Fill in socks and proxy details in Java Control Panel
Run topcoder arena with values of socks proxy.
However, this thing doesn't work out all the time. It may connect today
and may not for next week. I can see in Tor's view network area where it
makes connection to TopCoder servers, but the connection closes. I have
tried like thousands of times. Please help me. Am I doing something wrong?
Do you have any alternatives on Ubuntu?
I am posting this question here after redirection from stackoverflow. I
don't know if it's appropriate or not but I'm dying to get a solution. In
our University, connections to external IP through the non standard port
is blocked as a result of which I can't run Top Coder arena applet by
filling in the proxy details (We connect through proxy). I then have to
use Tor to route the traffic through the socks for the applet. Here is
what I do :
Run tor and establish a network.
Fill in socks and proxy details in Java Control Panel
Run topcoder arena with values of socks proxy.
However, this thing doesn't work out all the time. It may connect today
and may not for next week. I can see in Tor's view network area where it
makes connection to TopCoder servers, but the connection closes. I have
tried like thousands of times. Please help me. Am I doing something wrong?
Do you have any alternatives on Ubuntu?
program exits when shellexcute was called
program exits when shellexcute was called
win7 OS, vs2008. My program disappears when shellexcute was called,
It's a WTL project and the code like these: *.h
COMMAND_HANDLER(IDC_BTN_LOGIN, BN_CLICKED, DoLogin)
*.cpp
LRESULT XLoginView::DoLogin(WORD, WORD, HWND, BOOL&)
{
::ShellExecute(NULL, _T("open"), _T("http://mysite.com/login.php"),
NULL,NULL, SW_SHOW);
return 0;
}
when the login button was clicked, then my program was disappeard and the
visual studio exit too.
even the code is such simple as these:
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
ShellExecute(NULL, L"open", L"http://stackoverflow.com", NULL,
NULL, SW_SHOW);
}
return nRetCode;
}
the site(etc:http://stackoverflow.com) was openned only the first running
or debugging, then the second time and over, the visual studio disappears
at the same time.
win7 OS, vs2008. My program disappears when shellexcute was called,
It's a WTL project and the code like these: *.h
COMMAND_HANDLER(IDC_BTN_LOGIN, BN_CLICKED, DoLogin)
*.cpp
LRESULT XLoginView::DoLogin(WORD, WORD, HWND, BOOL&)
{
::ShellExecute(NULL, _T("open"), _T("http://mysite.com/login.php"),
NULL,NULL, SW_SHOW);
return 0;
}
when the login button was clicked, then my program was disappeard and the
visual studio exit too.
even the code is such simple as these:
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
ShellExecute(NULL, L"open", L"http://stackoverflow.com", NULL,
NULL, SW_SHOW);
}
return nRetCode;
}
the site(etc:http://stackoverflow.com) was openned only the first running
or debugging, then the second time and over, the visual studio disappears
at the same time.
Sunday, 25 August 2013
Sending custom headers through RSpec
Sending custom headers through RSpec
Given my API consumers are required to send a customer HTTP header like this:
# curl -H 'X-SomeHeader: 123' http://127.0.0.1:3000/api/api_call.json
Then I can read this header in a before_filter method like this:
class ApiController < ApplicationController
before_filter :log_request
private
def log_request
logger.debug "Header: #{request.env['HTTP_X_SOMEHEADER']}"
...
end
end
So far great. Now I would like to test this using RSpec as there is a
change in behavior:
describe ApiController do
it "should process the header" do
@request.env['HTTP_X_SOMEHEADER'] = '123'
get :api_call
...
end
end
However, the request received in ApiController will not be able to find
the header variable.
When trying the same code with the HTTP_ACCEPT_LANGUAGE header, it will
work. Are custom headers filtered somewhere?
Given my API consumers are required to send a customer HTTP header like this:
# curl -H 'X-SomeHeader: 123' http://127.0.0.1:3000/api/api_call.json
Then I can read this header in a before_filter method like this:
class ApiController < ApplicationController
before_filter :log_request
private
def log_request
logger.debug "Header: #{request.env['HTTP_X_SOMEHEADER']}"
...
end
end
So far great. Now I would like to test this using RSpec as there is a
change in behavior:
describe ApiController do
it "should process the header" do
@request.env['HTTP_X_SOMEHEADER'] = '123'
get :api_call
...
end
end
However, the request received in ApiController will not be able to find
the header variable.
When trying the same code with the HTTP_ACCEPT_LANGUAGE header, it will
work. Are custom headers filtered somewhere?
Can't overwrite file on windows in Python 2.7
Can't overwrite file on windows in Python 2.7
Whenever I try to overwrite a file in Python 2.7 this is what happens, code:
a = open('hello.txt')
a.write('my name is mark')
And my error is:
Traceback (most recent call last):
File "C:\Users\Mark Malkin\Desktop\New folder\opener.py", line 2, in
<module>
a.write('my name is mark')
IOError: File not open for writing
Whenever I try to overwrite a file in Python 2.7 this is what happens, code:
a = open('hello.txt')
a.write('my name is mark')
And my error is:
Traceback (most recent call last):
File "C:\Users\Mark Malkin\Desktop\New folder\opener.py", line 2, in
<module>
a.write('my name is mark')
IOError: File not open for writing
[ Polls & Surveys ] Open Question : would someone talk to me?
[ Polls & Surveys ] Open Question : would someone talk to me?
I just feel beyond hopeless, I don't even remember a time when I was
happy. I dread getting up every day and going on with life. I don't know
what I want to do in life anymore and just feel like I am a burden to
others. I have tried for a long time to find a girlfriend but none like
me. I don't have many people to talk to either, you can message me if you
like.
I just feel beyond hopeless, I don't even remember a time when I was
happy. I dread getting up every day and going on with life. I don't know
what I want to do in life anymore and just feel like I am a burden to
others. I have tried for a long time to find a girlfriend but none like
me. I don't have many people to talk to either, you can message me if you
like.
Decide the entity type of entity framework query dinamically
Decide the entity type of entity framework query dinamically
Let's say I have a DbContext sub class that looks like
public partial class DBEntities : DbContext
{ ...//More to come }
and in this class I have 2 DataSets
public DbSet<Config> Config { get; set; }
public DbSet<Parameters> Parameters { get; set; }
that look like:
public partial class Config
{
public string Name { get; set; }
public string Value { get; set; }
public string Override { get; set; }
public string Description { get; set; }
}
AND
public partial class Parameters
{
public string Id { get; set; }
public System.DateTime UpdateTime { get; set; }
public float AzValue_rad { get; set; }
public float E_rad { get; set; }
public float N_rad { get; set; }
}
Now let's say I want to have a configuration xml that will encode saved
queries. How can I do that and keep my type strength?
e.g. How can I encode the query
using (var db = new DBEntities())
{
var query = from floatTag in db.Config
select floatTag;
where floatTag.Name = "SOME_VALUE"
}
Let's say I have a DbContext sub class that looks like
public partial class DBEntities : DbContext
{ ...//More to come }
and in this class I have 2 DataSets
public DbSet<Config> Config { get; set; }
public DbSet<Parameters> Parameters { get; set; }
that look like:
public partial class Config
{
public string Name { get; set; }
public string Value { get; set; }
public string Override { get; set; }
public string Description { get; set; }
}
AND
public partial class Parameters
{
public string Id { get; set; }
public System.DateTime UpdateTime { get; set; }
public float AzValue_rad { get; set; }
public float E_rad { get; set; }
public float N_rad { get; set; }
}
Now let's say I want to have a configuration xml that will encode saved
queries. How can I do that and keep my type strength?
e.g. How can I encode the query
using (var db = new DBEntities())
{
var query = from floatTag in db.Config
select floatTag;
where floatTag.Name = "SOME_VALUE"
}
Is it possible to convert android application in eclipse to ios Rim windows using codename one?
Is it possible to convert android application in eclipse to ios Rim
windows using codename one?
I have written an application in eclipse for android and its working fine !!
I would like to send ios Rim and windows build using code name one Is it
possible ? or do i have to write the whole code from scratch as a New
Codename one project?
I tried directly sending my application using code name send android build
but i got error.
Error log [javac] C:\Documents and Settings\0mkar\My
Documents\Downloads\Compressed\android\android\src\com\securedcloudspace\android\Log_SC.java:3:
error: cannot find symbol [javac] import java.io.BufferedWriter; [javac] ^
[javac] symbol: class BufferedWriter
Full Error log http://www.mediafire.com/?evb4ex8lg8054ja
windows using codename one?
I have written an application in eclipse for android and its working fine !!
I would like to send ios Rim and windows build using code name one Is it
possible ? or do i have to write the whole code from scratch as a New
Codename one project?
I tried directly sending my application using code name send android build
but i got error.
Error log [javac] C:\Documents and Settings\0mkar\My
Documents\Downloads\Compressed\android\android\src\com\securedcloudspace\android\Log_SC.java:3:
error: cannot find symbol [javac] import java.io.BufferedWriter; [javac] ^
[javac] symbol: class BufferedWriter
Full Error log http://www.mediafire.com/?evb4ex8lg8054ja
Saturday, 24 August 2013
Secure updates of chrome app
Secure updates of chrome app
I have a chrome app that will be distributed as a normal file and not use
the app store. I would like a way of updating it, preferably using the
auto-update facility. However, I do not want to use an unsecured URL for
the updates.
Is it possible to use any kind of authentication for updates? What
approaches could I use to secure updates that would not be accessible to
unauthorized users?
I have a chrome app that will be distributed as a normal file and not use
the app store. I would like a way of updating it, preferably using the
auto-update facility. However, I do not want to use an unsecured URL for
the updates.
Is it possible to use any kind of authentication for updates? What
approaches could I use to secure updates that would not be accessible to
unauthorized users?
batch file filename / record cont
batch file filename / record cont
I am trying to create a batch file (displayed below) to get a count
records along with the file name in a group .csv files The batch file
below will output the record count of the first .csv file. Is there a way
to list all the record counts along with file name. Thanks
@echo off
for /F "tokens=3" %%f in ('find /V /C "-------------" *.csv') do ( echo
%%f ) >output.txt
I am trying to create a batch file (displayed below) to get a count
records along with the file name in a group .csv files The batch file
below will output the record count of the first .csv file. Is there a way
to list all the record counts along with file name. Thanks
@echo off
for /F "tokens=3" %%f in ('find /V /C "-------------" *.csv') do ( echo
%%f ) >output.txt
Find the general solution of the differential equation: $(1+e^x)yy' = e^x$
Find the general solution of the differential equation: $(1+e^x)yy' = e^x$
someone could help me with this question?
Find the general solution of $(1+e^x)yy' = e^x$
I tried to divide both sides by $(1+e^x)y$, but i found nothing.
someone could help me with this question?
Find the general solution of $(1+e^x)yy' = e^x$
I tried to divide both sides by $(1+e^x)y$, but i found nothing.
C# send/recieve using serial port
C# send/recieve using serial port
I made serice aplication. I have data in lists. I communicate with more
device using COM1, COM2, etc.
I first list is COM port configuration and device id. In second is device
id and AT commands (more then one)
I need to go thrue first list and open ports one by one and send commands
from seconds list. When I send command I have to wait for recive some
second (depeng of command).
When I go to end i must repeat all process.
I try to make some code but without success.
Any idea, I will be grateful.
Thank you in advance.
I made serice aplication. I have data in lists. I communicate with more
device using COM1, COM2, etc.
I first list is COM port configuration and device id. In second is device
id and AT commands (more then one)
I need to go thrue first list and open ports one by one and send commands
from seconds list. When I send command I have to wait for recive some
second (depeng of command).
When I go to end i must repeat all process.
I try to make some code but without success.
Any idea, I will be grateful.
Thank you in advance.
Compilation issues with method overloading
Compilation issues with method overloading
I was working on a personal project and overloaded some methods in Java so
as to make things easier to call and read. And then I started thinking
about how the compiler does the correct assignment of the called method.
Could anyone explain to me in more detail what issues the compiler might
face when we overload methods?
Aside from having to type and signature check each and every single one of
the existing methods with that name, is there something else at stake? Or
how does it know exactly which method will be called?
I was working on a personal project and overloaded some methods in Java so
as to make things easier to call and read. And then I started thinking
about how the compiler does the correct assignment of the called method.
Could anyone explain to me in more detail what issues the compiler might
face when we overload methods?
Aside from having to type and signature check each and every single one of
the existing methods with that name, is there something else at stake? Or
how does it know exactly which method will be called?
How important is my pet and the fish I feed him?
How important is my pet and the fish I feed him?
Ok, so I have this cute pet that I picked. It attacks things and I can use
fish to make it uber. The problem I have is that I don't seem to care very
much about him, except that his trips to town are very convenient. What I
want to know, in hopes that I will find new appreciation for my pet, is
how important he really is to my survival and progress.
Here's the question: Assuming I give him the best collar and tags I can
find, how much of a difference can fish really make?
I have searched for questions regarding the effects of various fish and
therefore understand their various effects, but they don't seem
significant. As a result, I seldom bother to feed fish to my pet. I've
even assigned a hotkey to fish feeding, but still seldom bother. The
problem is probably that I do not know what percentage of my DPS is
generated by my pet, and therefore do not account for him whatsoever. (He
is useful but unaccountable.)
Ok, so I have this cute pet that I picked. It attacks things and I can use
fish to make it uber. The problem I have is that I don't seem to care very
much about him, except that his trips to town are very convenient. What I
want to know, in hopes that I will find new appreciation for my pet, is
how important he really is to my survival and progress.
Here's the question: Assuming I give him the best collar and tags I can
find, how much of a difference can fish really make?
I have searched for questions regarding the effects of various fish and
therefore understand their various effects, but they don't seem
significant. As a result, I seldom bother to feed fish to my pet. I've
even assigned a hotkey to fish feeding, but still seldom bother. The
problem is probably that I do not know what percentage of my DPS is
generated by my pet, and therefore do not account for him whatsoever. (He
is useful but unaccountable.)
Autorised Twitter application only once
Autorised Twitter application only once
I am developing one application. where I need to provide the feature to
post a message on twitter after login. users need to authorize using their
twitter account only once. some authentication code / token will be store
in DB for future action
To do this which API do I need to be used ??
I have used https://dev.twitter.com/docs/api/1/get/oauth/authorize
(https://api.twitter.com/oauth/authorize) API to authorize the user for
the first time. it will return oauth_token and oauth_verifier
How can I use these two parameters to post the message on Twitter for any
authorized user (authorized previously) ??
Please let me know
I am developing one application. where I need to provide the feature to
post a message on twitter after login. users need to authorize using their
twitter account only once. some authentication code / token will be store
in DB for future action
To do this which API do I need to be used ??
I have used https://dev.twitter.com/docs/api/1/get/oauth/authorize
(https://api.twitter.com/oauth/authorize) API to authorize the user for
the first time. it will return oauth_token and oauth_verifier
How can I use these two parameters to post the message on Twitter for any
authorized user (authorized previously) ??
Please let me know
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in - p
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean
given in - p
Im getting an error: Warning: mysql_fetch_array() expects parameter 1 to
be resource, boolean given in
I tryed everything I cant seem to figure out where the problem is, would
somebody help
if ($number == 1) {
$row = mysql_fetch_array($r);
if ($return == "array") $res = $row;
else if ($return == "object") {
if ($obj == "Gallery") $res = new $obj($row["id"]);
else {
$obj = str_replace("_", "", $obj);
$res = new $obj($row);
}
}
} else {
$res = Array();
while ($row = mysql_fetch_array($r)) {
if ($return == "array") $res[] = $row;
else if ($return == "object") {
if ($obj == "Gallery") $res[] = new $obj($row["id"]);
else {
$obj = str_replace("_", "", str_replace("MM_", "",
$obj));
$res[] = new $obj($row);
}
}
}
}
return $res;
given in - p
Im getting an error: Warning: mysql_fetch_array() expects parameter 1 to
be resource, boolean given in
I tryed everything I cant seem to figure out where the problem is, would
somebody help
if ($number == 1) {
$row = mysql_fetch_array($r);
if ($return == "array") $res = $row;
else if ($return == "object") {
if ($obj == "Gallery") $res = new $obj($row["id"]);
else {
$obj = str_replace("_", "", $obj);
$res = new $obj($row);
}
}
} else {
$res = Array();
while ($row = mysql_fetch_array($r)) {
if ($return == "array") $res[] = $row;
else if ($return == "object") {
if ($obj == "Gallery") $res[] = new $obj($row["id"]);
else {
$obj = str_replace("_", "", str_replace("MM_", "",
$obj));
$res[] = new $obj($row);
}
}
}
}
return $res;
Friday, 23 August 2013
Can you make a clock as a placeable block?
Can you make a clock as a placeable block?
In Minecraft can you make a clock and then place it? I want to have it as
an "Alarm clock" for my mansion.
In Minecraft can you make a clock and then place it? I want to have it as
an "Alarm clock" for my mansion.
Convert mysqli pagination to prepared statement pagination
Convert mysqli pagination to prepared statement pagination
Sorry to trouble you guys as I am really desperate. I am going to try to
paginate using prepared statement. I tried this Paginate result set having
written the query with prepared statements, but no luck with Fatal error:
Call to undefined method mysqli_stmt::get_result() my PHP is =5.3 what i
did is convert
$sql2 = "SELECT COUNT(id) FROM products ";
$query2 = mysqli_query($myConnection, $sql2);
$row = mysqli_fetch_row($query2);
// Here we have the total row count
$rows = $row[0];
to this code :
$stmt=$myConnection->prepare('SELECT id FROM products');
// Don't use bind_result()...
// execute your statement
$stmt->execute();
// Get result set into a MySQLi result resource
$result = $stmt->get_result();
// array to hold all results
$rowset = array();
// And fetch with a while loop
while ($rows = $result->fetch_assoc()) {
$row[] = $rows;
}
also I do aware that this is just the first stage as there is still :
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
// This is your query again, it is for grabbing just one page worth of
rows by applying $limit
$sql = "SELECT id,product_name, price FROM products ORDER BY product_name
DESC $limit";
$query = mysqli_query($myConnection, $sql);
to convert to prepared statement which i will try to do after the first
part succeeded.
and also the last bit to convert
$dynamicList = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$dynamicList .= "
<li><div class='product'>
<a href='product.php?id=$id' class='info'>
<span class='holder'>
<img src='inventory_images/$id.jpg' alt='$product_name' />
<span class='book-name'>$product_name</span>
</a>
<a href='product.php?id=$id' class='buy-btn'>RM<span
class='price'>$price</span></a>
</div>
</li>
";
}
the current working code with mysqli is as below.
<?php
// Script and tutorial written by Adam Khoury @ developphp.com
// Line by line explanation : youtube.com/watch?v=T2QFNu_mivw
include_once("storescripts/connect_to_mysqli.php");
// This first query is just to get the total count of rows
$sql2 = "SELECT COUNT(id) FROM products ";
$query2 = mysqli_query($myConnection, $sql2);
$row = mysqli_fetch_row($query2);
// Here we have the total row count
$rows = $row[0];
// This is the number of results we want displayed per page
$page_rows = 10;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
// This is your query again, it is for grabbing just one page worth of
rows by applying $limit
$sql = "SELECT id,product_name, price FROM products ORDER BY product_name
DESC $limit";
$query = mysqli_query($myConnection, $sql);
// This shows the user what page they are on, and the total number of pages
$textline1 = "Products (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
/* First we check if we are on page one. If we are then we don't need
a link to
the previous page or the first page so we do nothing. If we aren't
then we
generate links to the first page, and to the previous page. */
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= '<a
href="'.$_SERVER['PHP_SELF'].'?pn='.$previous.'">Previous</a>
';
// Render clickable number links that should appear on the left of
the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= '<a
href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a>
';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= ''.$pagenum.' ';
// Render clickable number links that should appear on the right of
the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= '<a
href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a> ';
if($i >= $pagenum+4){
break;
}
}
// This does the same as above, only checking if we are on the last
page, and then generating the "Next"
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' <a
href="'.$_SERVER['PHP_SELF'].'?pn='.$next.'">Next</a> ';
}
}
$dynamicList = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$dynamicList .= "
<li><div class='product'>
<a href='product.php?id=$id' class='info'>
<span class='holder'>
<img src='inventory_images/$id.jpg' alt='$product_name' />
<span class='book-name'>$product_name</span>
</a>
<a href='product.php?id=$id' class='buy-btn'>RM<span
class='price'>$price</span></a>
</div>
</li>
";
}
// Close your database connection
mysqli_close($myConnection);
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{ font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
div#pagination_controls{font-size:21px;}
div#pagination_controls > a{ color:#06F; }
div#pagination_controls > a:visited{ color:#06F; }
</style>
</head>
<body>
<div>
<h2><?php echo $textline1; ?> Paged</h2>
<p><?php echo $textline2; ?></p>
<p><?php echo $dynamicList; ?></p>
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</body>
</html>
thanks in advance for any assistance
Sorry to trouble you guys as I am really desperate. I am going to try to
paginate using prepared statement. I tried this Paginate result set having
written the query with prepared statements, but no luck with Fatal error:
Call to undefined method mysqli_stmt::get_result() my PHP is =5.3 what i
did is convert
$sql2 = "SELECT COUNT(id) FROM products ";
$query2 = mysqli_query($myConnection, $sql2);
$row = mysqli_fetch_row($query2);
// Here we have the total row count
$rows = $row[0];
to this code :
$stmt=$myConnection->prepare('SELECT id FROM products');
// Don't use bind_result()...
// execute your statement
$stmt->execute();
// Get result set into a MySQLi result resource
$result = $stmt->get_result();
// array to hold all results
$rowset = array();
// And fetch with a while loop
while ($rows = $result->fetch_assoc()) {
$row[] = $rows;
}
also I do aware that this is just the first stage as there is still :
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
// This is your query again, it is for grabbing just one page worth of
rows by applying $limit
$sql = "SELECT id,product_name, price FROM products ORDER BY product_name
DESC $limit";
$query = mysqli_query($myConnection, $sql);
to convert to prepared statement which i will try to do after the first
part succeeded.
and also the last bit to convert
$dynamicList = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$dynamicList .= "
<li><div class='product'>
<a href='product.php?id=$id' class='info'>
<span class='holder'>
<img src='inventory_images/$id.jpg' alt='$product_name' />
<span class='book-name'>$product_name</span>
</a>
<a href='product.php?id=$id' class='buy-btn'>RM<span
class='price'>$price</span></a>
</div>
</li>
";
}
the current working code with mysqli is as below.
<?php
// Script and tutorial written by Adam Khoury @ developphp.com
// Line by line explanation : youtube.com/watch?v=T2QFNu_mivw
include_once("storescripts/connect_to_mysqli.php");
// This first query is just to get the total count of rows
$sql2 = "SELECT COUNT(id) FROM products ";
$query2 = mysqli_query($myConnection, $sql2);
$row = mysqli_fetch_row($query2);
// Here we have the total row count
$rows = $row[0];
// This is the number of results we want displayed per page
$page_rows = 10;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
// This sets the range of rows to query for the chosen $pagenum
$limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;
// This is your query again, it is for grabbing just one page worth of
rows by applying $limit
$sql = "SELECT id,product_name, price FROM products ORDER BY product_name
DESC $limit";
$query = mysqli_query($myConnection, $sql);
// This shows the user what page they are on, and the total number of pages
$textline1 = "Products (<b>$rows</b>)";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
/* First we check if we are on page one. If we are then we don't need
a link to
the previous page or the first page so we do nothing. If we aren't
then we
generate links to the first page, and to the previous page. */
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= '<a
href="'.$_SERVER['PHP_SELF'].'?pn='.$previous.'">Previous</a>
';
// Render clickable number links that should appear on the left of
the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= '<a
href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a>
';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= ''.$pagenum.' ';
// Render clickable number links that should appear on the right of
the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= '<a
href="'.$_SERVER['PHP_SELF'].'?pn='.$i.'">'.$i.'</a> ';
if($i >= $pagenum+4){
break;
}
}
// This does the same as above, only checking if we are on the last
page, and then generating the "Next"
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' <a
href="'.$_SERVER['PHP_SELF'].'?pn='.$next.'">Next</a> ';
}
}
$dynamicList = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$dynamicList .= "
<li><div class='product'>
<a href='product.php?id=$id' class='info'>
<span class='holder'>
<img src='inventory_images/$id.jpg' alt='$product_name' />
<span class='book-name'>$product_name</span>
</a>
<a href='product.php?id=$id' class='buy-btn'>RM<span
class='price'>$price</span></a>
</div>
</li>
";
}
// Close your database connection
mysqli_close($myConnection);
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body{ font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
div#pagination_controls{font-size:21px;}
div#pagination_controls > a{ color:#06F; }
div#pagination_controls > a:visited{ color:#06F; }
</style>
</head>
<body>
<div>
<h2><?php echo $textline1; ?> Paged</h2>
<p><?php echo $textline2; ?></p>
<p><?php echo $dynamicList; ?></p>
<div id="pagination_controls"><?php echo $paginationCtrls; ?></div>
</div>
</body>
</html>
thanks in advance for any assistance
How can I improve this code to call Google API less times
How can I improve this code to call Google API less times
I have to sync google contacts with spreadsheet, for this I have to call
API so may time to set values in Google spreadsheet, how can I overcome
this problem to call google API less times or only once ?
var preContacts = group.getContacts();
var rowNo = 2;
for(var y = 0; y < preContacts.length; y++) {
var FNameContact = preContacts[y].getGivenName();
var PhoneNoArray = preContacts[y].getPhones();
var PhoneNoContact = getPhoneNumbers(PhoneNoArray);
var emailArray = preContacts[y].getEmails();
var emailAdressContact = getEmailAddresses(emailArray);
//var customFieldsArray = preContacts.getCustomFields();
sheettab_bulk_cdb.getRange("J"+rowNo).setValue(emailAdressContact);
sheettab_bulk_cdb.getRange("G"+rowNo).setValue(emailAdressContact);
sheettab_bulk_cdb.getRange("F"+rowNo).setValue(emailAdressContact);
sheettab_bulk_cdb.getRange("A"+rowNo).setValue(emailAdressContact);
rowNo++;
}
I have to sync google contacts with spreadsheet, for this I have to call
API so may time to set values in Google spreadsheet, how can I overcome
this problem to call google API less times or only once ?
var preContacts = group.getContacts();
var rowNo = 2;
for(var y = 0; y < preContacts.length; y++) {
var FNameContact = preContacts[y].getGivenName();
var PhoneNoArray = preContacts[y].getPhones();
var PhoneNoContact = getPhoneNumbers(PhoneNoArray);
var emailArray = preContacts[y].getEmails();
var emailAdressContact = getEmailAddresses(emailArray);
//var customFieldsArray = preContacts.getCustomFields();
sheettab_bulk_cdb.getRange("J"+rowNo).setValue(emailAdressContact);
sheettab_bulk_cdb.getRange("G"+rowNo).setValue(emailAdressContact);
sheettab_bulk_cdb.getRange("F"+rowNo).setValue(emailAdressContact);
sheettab_bulk_cdb.getRange("A"+rowNo).setValue(emailAdressContact);
rowNo++;
}
Trouble getting jquery mobile panels to work
Trouble getting jquery mobile panels to work
So I'm clearly making a stupid mistake here...but I've been stuck on it
for a while. I'm trying to test out the panel widget in jquery mobile but
I cannot get it to work. Here's my code. Anybody know what's wrong?
<!DOCTYPE html>
<html>
<head>
<title class="identifying" id="TOC-proof-of-concept.html">Table of
Contents</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css"
/>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script
src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="../Support/js/jStorage.js"></script>
<script src="../Support/js/bookmark.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="panel" id="mypanel">
<p>panel content</p>
</div><!-- /panel -->
<div data-role="header">
<p>sample text blah blah</p>
</div>
<div data-role="content">
<a href="#mypanel">Open panel</a>
</div>
<div date-role="footer">
here is some footer text
</div>
</div><!-- page -->
</body>
</html>
So I'm clearly making a stupid mistake here...but I've been stuck on it
for a while. I'm trying to test out the panel widget in jquery mobile but
I cannot get it to work. Here's my code. Anybody know what's wrong?
<!DOCTYPE html>
<html>
<head>
<title class="identifying" id="TOC-proof-of-concept.html">Table of
Contents</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css"
/>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script
src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="../Support/js/jStorage.js"></script>
<script src="../Support/js/bookmark.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="panel" id="mypanel">
<p>panel content</p>
</div><!-- /panel -->
<div data-role="header">
<p>sample text blah blah</p>
</div>
<div data-role="content">
<a href="#mypanel">Open panel</a>
</div>
<div date-role="footer">
here is some footer text
</div>
</div><!-- page -->
</body>
</html>
data show from 4 table mysql
data show from 4 table mysql
How to show the common data from all table on base of vendorID where
vendorID is unique key in my vendor table. and i use this as an foriegn
key for all other(cost table, hour table,employee table, temporary table
and ) table.
This is my Cost table struructre This is my Hour table structure This is
my Temporarytable structure This is my Employee table
This is my Final table vendor there are vendorID is unique Key
And i have use the following query but it is showing the different data.
SELECT * FROM cw_employee_csv as emp
inner join cw_cost_hour as cost on cost.vendorid=emp.vendorid
inner join cw_temp_employee as temp on cost.vendorid=temp.vendorid
inner join cw_hour_company as hour on temp.vendorid=hour.vendorid
inner join cw_vendor as vendor on temp.vendorid=vendor.vendorid
where vendor.companyid=1 ORDER BY hour.timeFrom ASC
How to show the common data from all table on base of vendorID where
vendorID is unique key in my vendor table. and i use this as an foriegn
key for all other(cost table, hour table,employee table, temporary table
and ) table.
This is my Cost table struructre This is my Hour table structure This is
my Temporarytable structure This is my Employee table
This is my Final table vendor there are vendorID is unique Key
And i have use the following query but it is showing the different data.
SELECT * FROM cw_employee_csv as emp
inner join cw_cost_hour as cost on cost.vendorid=emp.vendorid
inner join cw_temp_employee as temp on cost.vendorid=temp.vendorid
inner join cw_hour_company as hour on temp.vendorid=hour.vendorid
inner join cw_vendor as vendor on temp.vendorid=vendor.vendorid
where vendor.companyid=1 ORDER BY hour.timeFrom ASC
Load Aspx with in a razor view
Load Aspx with in a razor view
I have a aspx user controller and functions. I wanna load this controller
with in Razor view. so I wrote a helper class to render this aspx
controller to Razor view but aspx functions are not working it was fine
for static page. this is the link that I used but this is only work for
static pges
http://malvinly.com/2011/02/28/using-web-forms-user-controls-in-an-asp-net-mvc-project/
I have a aspx user controller and functions. I wanna load this controller
with in Razor view. so I wrote a helper class to render this aspx
controller to Razor view but aspx functions are not working it was fine
for static page. this is the link that I used but this is only work for
static pges
http://malvinly.com/2011/02/28/using-web-forms-user-controls-in-an-asp-net-mvc-project/
Thursday, 22 August 2013
Site URL has been been identified as malicious and/or abusive -- Facebook error
Site URL has been been identified as malicious and/or abusive -- Facebook
error
I was creating an app for the first time, on a new domain I purchased, and
I get the message "Site URL has been been identified as malicious and/or
abusive."
Now I am just installing software at this point to the site, and getting
things setup, so I am at least getting this message for something I have
not done. How can I get a review from facebook or how can I get this
status removed for my url?
Thank you in advance.
error
I was creating an app for the first time, on a new domain I purchased, and
I get the message "Site URL has been been identified as malicious and/or
abusive."
Now I am just installing software at this point to the site, and getting
things setup, so I am at least getting this message for something I have
not done. How can I get a review from facebook or how can I get this
status removed for my url?
Thank you in advance.
How to control voice balance via C# code
How to control voice balance via C# code
I am developing an application in C#, at some point of the program, I'd
like to have control of the speaker, more specifically, I'd like to
control the voice balance (which speaker - left/right - the voice is
coming from). Is there a way to do this?
Thank you,
I am developing an application in C#, at some point of the program, I'd
like to have control of the speaker, more specifically, I'd like to
control the voice balance (which speaker - left/right - the voice is
coming from). Is there a way to do this?
Thank you,
Circular references preventing serialization of object graph
Circular references preventing serialization of object graph
I've got a simple data model involving Weeds and Weed Families.
WeedFamily <-1---*-> Weed (WeedFamily and Weed have a one-to-many
relationship)
I'm attempting to complete my first ApiController so that I can easily
retrieve my data as JSON for an AngularJS application. When I access the
/WeedAPI/ URL in my application, I get the following error. I'm pretty
sure the problem is that I have circular references between Weed and
WeedFamily.
How should I change my data model so that the JSON serialization will work
while maintaining the bi-directional quality of the Weed-WeedFamily
relationship?
(ie. I want to still be able to build expressions like the following:
WeedData.GetFamilies()["mustard"].Weeds.Count
and
WeedData.GetWeeds()[3].Family.Weeds
)
The error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body
for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Object graph for type 'WeedCards.Models.WeedFamily' contains
cycles and cannot be serialized if reference tracking is
disabled.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.SerializationException
</ExceptionType>
<StackTrace>
at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.OnHandleReference(XmlWriterDelegator
xmlWriter, Object obj, Boolean canContainCyclicReference) at
WriteWeedToXml(XmlWriterDelegator , Object ,
XmlObjectSerializerWriteContext , ClassDataContract ) at
System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator
xmlWriter, Object obj, XmlObjectSerializerWriteContext
context) at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract
dataContract, XmlWriterDelegator xmlWriter, Object obj,
RuntimeTypeHandle declaredTypeHandle) at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract
dataContract, XmlWriterDelegator xmlWriter, Object obj,
RuntimeTypeHandle declaredTypeHandle) at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator
xmlWriter, Object obj, Boolean isDecl...etc
</StackTrace>
</InnerException>
</Error>
My data:
public class WeedData
{
public static Dictionary<string,WeedFamily> GetFamilies(){
return new Dictionary<string,WeedFamily>
{
{"mustard",new WeedFamily("Mustard","Brassicaceae")}
,{"pigweed",new WeedFamily("Pigweed","Amaranthus")}
,{"sunflower",new WeedFamily("Sunflower","Asteraceae")}
};
}
public static List<Weed> GetWeeds(){
var Families = GetFamilies();
return new List<Weed>
{
new Weed("Hairy Bittercress","Cardamine
hirsuta",Families["mustard"])
,new Weed("Little Bittercress","Cardamine
oligosperma",Families["mustard"])
,new Weed("Shepherd's-Purse","Capsella
bursa-pastoris",Families["mustard"])
,new Weed("Wild Mustard","Sinapis arvensis / Brassica
kaber",Families["mustard"])
,new Weed("Wild Radish","Raphanus
raphanistrum",Families["mustard"])
,new Weed("Radish","Raphanus sativus",Families["mustard"])
,new Weed("Redroot Pigweed","Amaranthus
retroflexus",Families["pigweed"])
,new Weed("Prickly Lettuce","Lactuca
serriola",Families["sunflower"])
,new Weed("Spiny Sowthistle","Sonchus
asper",Families["sunflower"])
,new Weed("Annual Sowthistle","Sonchus
oleraceus",Families["sunflower"])
};
}
}
My model classes:
[Serializable]
public class Weed
{
public string CommonName;
public string LatinName;
public List<WeedPhoto> Photos;
public WeedFamily Family;
public Weed(string commonName, string latinName)
{
CommonName = commonName;
LatinName = latinName;
}
public Weed(string commonName, string latinName, WeedFamily family)
{
CommonName = commonName;
LatinName = latinName;
Family = family;
Family.Weeds.Add(this);
}
override public string ToString()
{
return CommonName + " (" + LatinName + ")";
}
}
and
[Serializable]
public class WeedFamily
{
public string CommonName;
public string LatinName;
public List<Weed> Weeds;
public WeedFamily(string commonName, string latinName)
{
CommonName = commonName;
LatinName = latinName;
Weeds = new List<Weed>();
}
}
Finally, the ApiController:
public class WeedAPIController : ApiController
{
//
// GET: /WeedAPI/
public IEnumerable<Weed> GetAllWeeds()
{
return WeedData.GetWeeds();
}
}
I've got a simple data model involving Weeds and Weed Families.
WeedFamily <-1---*-> Weed (WeedFamily and Weed have a one-to-many
relationship)
I'm attempting to complete my first ApiController so that I can easily
retrieve my data as JSON for an AngularJS application. When I access the
/WeedAPI/ URL in my application, I get the following error. I'm pretty
sure the problem is that I have circular references between Weed and
WeedFamily.
How should I change my data model so that the JSON serialization will work
while maintaining the bi-directional quality of the Weed-WeedFamily
relationship?
(ie. I want to still be able to build expressions like the following:
WeedData.GetFamilies()["mustard"].Weeds.Count
and
WeedData.GetWeeds()[3].Family.Weeds
)
The error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body
for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Object graph for type 'WeedCards.Models.WeedFamily' contains
cycles and cannot be serialized if reference tracking is
disabled.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.SerializationException
</ExceptionType>
<StackTrace>
at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.OnHandleReference(XmlWriterDelegator
xmlWriter, Object obj, Boolean canContainCyclicReference) at
WriteWeedToXml(XmlWriterDelegator , Object ,
XmlObjectSerializerWriteContext , ClassDataContract ) at
System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator
xmlWriter, Object obj, XmlObjectSerializerWriteContext
context) at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract
dataContract, XmlWriterDelegator xmlWriter, Object obj,
RuntimeTypeHandle declaredTypeHandle) at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract
dataContract, XmlWriterDelegator xmlWriter, Object obj,
RuntimeTypeHandle declaredTypeHandle) at
System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator
xmlWriter, Object obj, Boolean isDecl...etc
</StackTrace>
</InnerException>
</Error>
My data:
public class WeedData
{
public static Dictionary<string,WeedFamily> GetFamilies(){
return new Dictionary<string,WeedFamily>
{
{"mustard",new WeedFamily("Mustard","Brassicaceae")}
,{"pigweed",new WeedFamily("Pigweed","Amaranthus")}
,{"sunflower",new WeedFamily("Sunflower","Asteraceae")}
};
}
public static List<Weed> GetWeeds(){
var Families = GetFamilies();
return new List<Weed>
{
new Weed("Hairy Bittercress","Cardamine
hirsuta",Families["mustard"])
,new Weed("Little Bittercress","Cardamine
oligosperma",Families["mustard"])
,new Weed("Shepherd's-Purse","Capsella
bursa-pastoris",Families["mustard"])
,new Weed("Wild Mustard","Sinapis arvensis / Brassica
kaber",Families["mustard"])
,new Weed("Wild Radish","Raphanus
raphanistrum",Families["mustard"])
,new Weed("Radish","Raphanus sativus",Families["mustard"])
,new Weed("Redroot Pigweed","Amaranthus
retroflexus",Families["pigweed"])
,new Weed("Prickly Lettuce","Lactuca
serriola",Families["sunflower"])
,new Weed("Spiny Sowthistle","Sonchus
asper",Families["sunflower"])
,new Weed("Annual Sowthistle","Sonchus
oleraceus",Families["sunflower"])
};
}
}
My model classes:
[Serializable]
public class Weed
{
public string CommonName;
public string LatinName;
public List<WeedPhoto> Photos;
public WeedFamily Family;
public Weed(string commonName, string latinName)
{
CommonName = commonName;
LatinName = latinName;
}
public Weed(string commonName, string latinName, WeedFamily family)
{
CommonName = commonName;
LatinName = latinName;
Family = family;
Family.Weeds.Add(this);
}
override public string ToString()
{
return CommonName + " (" + LatinName + ")";
}
}
and
[Serializable]
public class WeedFamily
{
public string CommonName;
public string LatinName;
public List<Weed> Weeds;
public WeedFamily(string commonName, string latinName)
{
CommonName = commonName;
LatinName = latinName;
Weeds = new List<Weed>();
}
}
Finally, the ApiController:
public class WeedAPIController : ApiController
{
//
// GET: /WeedAPI/
public IEnumerable<Weed> GetAllWeeds()
{
return WeedData.GetWeeds();
}
}
apply an already defined function to all data-frames at once
apply an already defined function to all data-frames at once
I already have defined a function (which works fine). Nevertheless, I have
20 data-frames in the working space to which I want to apply the same
function (dat1 to dat20).
So far it looks like this:
dat1 <- func(dat=dat1)
dat2 <- func(dat=dat2)
dat3 <- func(dat=dat3)
dat4 <- func(dat=dat4)
...
dat20 <- func(dat=dat20)
However, is there a way to do this more elegant with a shorter command,
i.e. to apply the function to all data-frames at once?
I tried this, but it didn´t work:
> mylist <- paste0("dat", 1:20, sep="")
>
> lapply(mylist, func)
Thanx in advance!
I already have defined a function (which works fine). Nevertheless, I have
20 data-frames in the working space to which I want to apply the same
function (dat1 to dat20).
So far it looks like this:
dat1 <- func(dat=dat1)
dat2 <- func(dat=dat2)
dat3 <- func(dat=dat3)
dat4 <- func(dat=dat4)
...
dat20 <- func(dat=dat20)
However, is there a way to do this more elegant with a shorter command,
i.e. to apply the function to all data-frames at once?
I tried this, but it didn´t work:
> mylist <- paste0("dat", 1:20, sep="")
>
> lapply(mylist, func)
Thanx in advance!
detect Internet Connection/Disconnection in Console App C#
detect Internet Connection/Disconnection in Console App C#
I wrote a small console app which connects with a remote site, downloads
some data and process it. As it is network operation so I want my
application to be intelligent enough to go to pause state when there is no
internet connection. If internet connection gets available it should
resume its working.
What I done so far is if I run application it starts downloading data from
remote site. If I disconnects internet connection it behaves correctly by
displaying appropriate info. But as soon as network connection is up it
resumes and only download data for one iteration of while loop.
Here is the code:
class Program
{
static bool networkIsAvailable = false;
static StreamWriter writer = null;
static int i = 1;
static string URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
static void Main(string[] args)
{
writer = new StreamWriter("c:\\StudentsList.txt", true);
NetworkChange.NetworkAvailabilityChanged += new
NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in nics)
{
if (
(nic.NetworkInterfaceType != NetworkInterfaceType.Loopback
&& nic.NetworkInterfaceType !=
NetworkInterfaceType.Tunnel) &&
nic.OperationalStatus == OperationalStatus.Up)
{
networkIsAvailable = true;
}
}
if (!networkIsAvailable)
Console.WriteLine("Internet connection not available! We
resume as soon as network is available...");
else
ConnectToPUServer();
}
public static void ConnectToPUServer()
{
var client = new WebClient();
while (i < 500 && networkIsAvailable)
{
string html = client.DownloadString(URI);
//some data processing
Console.WriteLine(i);
i++;
URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
}
}
static void NetworkChange_NetworkAvailabilityChanged(object sender,
NetworkAvailabilityEventArgs e)
{
networkIsAvailable = e.IsAvailable;
if (!networkIsAvailable)
Console.WriteLine("Internet connection not available! We
resume as soon as network is available...");
while (!networkIsAvailable)
{
//waiting for internet connection
}
ConnectToPUServer();
Console.WriteLine("Complete.");
writer.Close();
}
}
After resuming, why while loop of ConnectToPUServer is executing only once??
Thanks.
I wrote a small console app which connects with a remote site, downloads
some data and process it. As it is network operation so I want my
application to be intelligent enough to go to pause state when there is no
internet connection. If internet connection gets available it should
resume its working.
What I done so far is if I run application it starts downloading data from
remote site. If I disconnects internet connection it behaves correctly by
displaying appropriate info. But as soon as network connection is up it
resumes and only download data for one iteration of while loop.
Here is the code:
class Program
{
static bool networkIsAvailable = false;
static StreamWriter writer = null;
static int i = 1;
static string URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
static void Main(string[] args)
{
writer = new StreamWriter("c:\\StudentsList.txt", true);
NetworkChange.NetworkAvailabilityChanged += new
NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in nics)
{
if (
(nic.NetworkInterfaceType != NetworkInterfaceType.Loopback
&& nic.NetworkInterfaceType !=
NetworkInterfaceType.Tunnel) &&
nic.OperationalStatus == OperationalStatus.Up)
{
networkIsAvailable = true;
}
}
if (!networkIsAvailable)
Console.WriteLine("Internet connection not available! We
resume as soon as network is available...");
else
ConnectToPUServer();
}
public static void ConnectToPUServer()
{
var client = new WebClient();
while (i < 500 && networkIsAvailable)
{
string html = client.DownloadString(URI);
//some data processing
Console.WriteLine(i);
i++;
URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
}
}
static void NetworkChange_NetworkAvailabilityChanged(object sender,
NetworkAvailabilityEventArgs e)
{
networkIsAvailable = e.IsAvailable;
if (!networkIsAvailable)
Console.WriteLine("Internet connection not available! We
resume as soon as network is available...");
while (!networkIsAvailable)
{
//waiting for internet connection
}
ConnectToPUServer();
Console.WriteLine("Complete.");
writer.Close();
}
}
After resuming, why while loop of ConnectToPUServer is executing only once??
Thanks.
Mysql remote connections very slow - host lookups already disabled
Mysql remote connections very slow - host lookups already disabled
I followed every instruction about this issue and nothing helped. Remote
communication with MySQL server takes 4-30 seconds on simple query like
select 1 from table_name and connection attempt often ends up with
SQLSTATE[HY000] [2013] Lost connection to MySQL server at 'reading
authorization packet', system error: 104. This is what I did so far:
[mysqld]
skip-name-resolve
skip-host-cache
bind-address = 37.187.60.211
I set all Host column values in the grant tables to remote IP address or
localhost.
I allowed incoming traffic on port 3306.
Performed tests with every service disabled on the host except MySQL
server. Tested from my home and other vps using mysql client.
I hope you can help me, thank you
I followed every instruction about this issue and nothing helped. Remote
communication with MySQL server takes 4-30 seconds on simple query like
select 1 from table_name and connection attempt often ends up with
SQLSTATE[HY000] [2013] Lost connection to MySQL server at 'reading
authorization packet', system error: 104. This is what I did so far:
[mysqld]
skip-name-resolve
skip-host-cache
bind-address = 37.187.60.211
I set all Host column values in the grant tables to remote IP address or
localhost.
I allowed incoming traffic on port 3306.
Performed tests with every service disabled on the host except MySQL
server. Tested from my home and other vps using mysql client.
I hope you can help me, thank you
Remove specific charcter from string from last index
Remove specific charcter from string from last index
How to remove specific character from String from last.Is it possible to
remove ?
String str="update employee set name='david', where id=?";
How to remove specific character from String from last.Is it possible to
remove ?
String str="update employee set name='david', where id=?";
Wednesday, 21 August 2013
Stackoverflow css template type?
Stackoverflow css template type?
Im looking for some stackoverflow php,ruby on rails, etc template for make
my own question and answers site for a university software enginnering
project....where can i buy or get for free a template like this site?
Kind regards
Im looking for some stackoverflow php,ruby on rails, etc template for make
my own question and answers site for a university software enginnering
project....where can i buy or get for free a template like this site?
Kind regards
Removing a specific element from a class
Removing a specific element from a class
I have this code, it moves every element in the class block 10 pixels to
the left. I want it to remove any of the elements which are left of 300
pixels. Why does $(this).remove() not work and what can I do to fix this?
$(".block").animate({left:"-=10"},speed,"linear",function(){
if(parseInt(this.style.left) < 300)
{
$(this).remove();
//something
}else{
//something
}
});
I have this code, it moves every element in the class block 10 pixels to
the left. I want it to remove any of the elements which are left of 300
pixels. Why does $(this).remove() not work and what can I do to fix this?
$(".block").animate({left:"-=10"},speed,"linear",function(){
if(parseInt(this.style.left) < 300)
{
$(this).remove();
//something
}else{
//something
}
});
Can 'this' pointer be different than the object's pointer?
Can 'this' pointer be different than the object's pointer?
I've recently came across this strange function in some class:
void* getThis() {return this;}
And later in the code it is sometimes used like so: bla->getThis() (Where
bla is a pointer to an object of the class where this function is
defined.) And I can't seem to realize what this can be good for. Is there
any situation where a pointer to an object would be different than the
object's 'this'? (where bla != bla->getThis())
It seems like a stupid question but I wonder if I'm missing something here..
I've recently came across this strange function in some class:
void* getThis() {return this;}
And later in the code it is sometimes used like so: bla->getThis() (Where
bla is a pointer to an object of the class where this function is
defined.) And I can't seem to realize what this can be good for. Is there
any situation where a pointer to an object would be different than the
object's 'this'? (where bla != bla->getThis())
It seems like a stupid question but I wonder if I'm missing something here..
Unable to get text from the X11 clipboard
Unable to get text from the X11 clipboard
I'm essentially trying to run the accepted answer in the question "getting
HTML source or rich text from the X clipboard", however, I get a slew of
errors. The exact code I'm using has been slightly updated for Python 3
and GTK+-3, so here is what I've got:
#!/usr/bin/python
from gi.repository import Gtk as gtk
from gi.repository import GLib as glib
def test_clipboard():
clipboard = gtk.Clipboard()
targets = clipboard.wait_for_targets()
print("Targets available:", ", ".join(map(str, targets)))
for target in targets:
print("Trying '%s'..." % str(target))
contents = clipboard.wait_for_contents(target)
if contents:
print(contents.data)
def main():
mainloop = glib.MainLoop()
def cb():
test_clipboard()
mainloop.quit()
glib.idle_add(cb)
mainloop.run()
if __name__ == "__main__":
main()
And when I run it:
$ python clip_test.py
Gtk-Message: Failed to load module "gnomesegvhandler"
(clip_test.py:17736): Gdk-CRITICAL **:
gdk_display_supports_selection_notification: assertion `GDK_IS_DISPLAY
(display)' failed
/usr/lib64/python3.2/site-packages/gi/types.py:43: Warning:
g_object_get_data: assertion `G_IS_OBJECT (object)' failed
return info.invoke(*args, **kwargs)
(clip_test.py:17736): Gdk-CRITICAL **: gdk_display_get_default_screen:
assertion `GDK_IS_DISPLAY (display)' failed
(clip_test.py:17736): Gtk-CRITICAL **: gtk_invisible_new_for_screen:
assertion `GDK_IS_SCREEN (screen)' failed
/usr/lib64/python3.2/site-packages/gi/types.py:43: Warning: invalid (NULL)
pointer instance
return info.invoke(*args, **kwargs)
/usr/lib64/python3.2/site-packages/gi/types.py:43: Warning:
g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
return info.invoke(*args, **kwargs)
(clip_test.py:17736): Gtk-CRITICAL **: gtk_widget_add_events: assertion
`GTK_IS_WIDGET (widget)' failed
/usr/lib64/python3.2/site-packages/gi/types.py:43: Warning:
g_object_set_data: assertion `G_IS_OBJECT (object)' failed
return info.invoke(*args, **kwargs)
/usr/lib64/python3.2/site-packages/gi/types.py:43: Warning:
g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed
return info.invoke(*args, **kwargs)
(clip_test.py:17736): Gdk-CRITICAL **: gdk_display_get_default_screen:
assertion `GDK_IS_DISPLAY (display)' failed
(clip_test.py:17736): Gtk-CRITICAL **: gtk_invisible_new_for_screen:
assertion `GDK_IS_SCREEN (screen)' failed
(clip_test.py:17736): Gtk-CRITICAL **: gtk_widget_add_events: assertion
`GTK_IS_WIDGET (widget)' failed
(clip_test.py:17736): Gtk-CRITICAL **: gtk_widget_get_window: assertion
`GTK_IS_WIDGET (widget)' failed
(clip_test.py:17736): Gtk-CRITICAL **: gtk_selection_convert: assertion
`GTK_IS_WIDGET (widget)' failed
…and it never returns. (Even if I highlight and copy something to the
clipboard.) The error:
assertion `GDK_IS_DISPLAY (display)' failed
Seems to be that it can't find my display, but if I do:
import os
print('DISPLAY = ' + repr(os.environ['DISPLAY']))
…then I get: DISPLAY = ':0.0'
I'm essentially trying to run the accepted answer in the question "getting
HTML source or rich text from the X clipboard", however, I get a slew of
errors. The exact code I'm using has been slightly updated for Python 3
and GTK+-3, so here is what I've got:
#!/usr/bin/python
from gi.repository import Gtk as gtk
from gi.repository import GLib as glib
def test_clipboard():
clipboard = gtk.Clipboard()
targets = clipboard.wait_for_targets()
print("Targets available:", ", ".join(map(str, targets)))
for target in targets:
print("Trying '%s'..." % str(target))
contents = clipboard.wait_for_contents(target)
if contents:
print(contents.data)
def main():
mainloop = glib.MainLoop()
def cb():
test_clipboard()
mainloop.quit()
glib.idle_add(cb)
mainloop.run()
if __name__ == "__main__":
main()
And when I run it:
$ python clip_test.py
Gtk-Message: Failed to load module "gnomesegvhandler"
(clip_test.py:17736): Gdk-CRITICAL **:
gdk_display_supports_selection_notification: assertion `GDK_IS_DISPLAY
(display)' failed
/usr/lib64/python3.2/site-packages/gi/types.py:43: Warning:
g_object_get_data: assertion `G_IS_OBJECT (object)' failed
return info.invoke(*args, **kwargs)
(clip_test.py:17736): Gdk-CRITICAL **: gdk_display_get_default_screen:
assertion `GDK_IS_DISPLAY (display)' failed
(clip_test.py:17736): Gtk-CRITICAL **: gtk_invisible_new_for_screen:
assertion `GDK_IS_SCREEN (screen)' failed
/usr/lib64/python3.2/site-packages/gi/types.py:43: Warning: invalid (NULL)
pointer instance
return info.invoke(*args, **kwargs)
/usr/lib64/python3.2/site-packages/gi/types.py:43: Warning:
g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
return info.invoke(*args, **kwargs)
(clip_test.py:17736): Gtk-CRITICAL **: gtk_widget_add_events: assertion
`GTK_IS_WIDGET (widget)' failed
/usr/lib64/python3.2/site-packages/gi/types.py:43: Warning:
g_object_set_data: assertion `G_IS_OBJECT (object)' failed
return info.invoke(*args, **kwargs)
/usr/lib64/python3.2/site-packages/gi/types.py:43: Warning:
g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed
return info.invoke(*args, **kwargs)
(clip_test.py:17736): Gdk-CRITICAL **: gdk_display_get_default_screen:
assertion `GDK_IS_DISPLAY (display)' failed
(clip_test.py:17736): Gtk-CRITICAL **: gtk_invisible_new_for_screen:
assertion `GDK_IS_SCREEN (screen)' failed
(clip_test.py:17736): Gtk-CRITICAL **: gtk_widget_add_events: assertion
`GTK_IS_WIDGET (widget)' failed
(clip_test.py:17736): Gtk-CRITICAL **: gtk_widget_get_window: assertion
`GTK_IS_WIDGET (widget)' failed
(clip_test.py:17736): Gtk-CRITICAL **: gtk_selection_convert: assertion
`GTK_IS_WIDGET (widget)' failed
…and it never returns. (Even if I highlight and copy something to the
clipboard.) The error:
assertion `GDK_IS_DISPLAY (display)' failed
Seems to be that it can't find my display, but if I do:
import os
print('DISPLAY = ' + repr(os.environ['DISPLAY']))
…then I get: DISPLAY = ':0.0'
How can I set up an FTP Server?
How can I set up an FTP Server?
I've read this tutorial on installing FTP server:
http://www.wikihow.com/Set-up-an-FTP-Server-in-Ubuntu-Linux
But I don't know if it will fulfill my expectations, I'm running Ubuntu
with XAMPP, I configures everything and I have a Dynamic DNS to my
computer, so basicly I have a website from my home computer, I work with
dreamweaver in another computer and I want to make my ubuntu an FTP Server
so when I push dreamweaver's upload button it will update the files in
ubuntu, is FTP Server the best option for me and will it acomplish what I
need?
Thanks!!
I've read this tutorial on installing FTP server:
http://www.wikihow.com/Set-up-an-FTP-Server-in-Ubuntu-Linux
But I don't know if it will fulfill my expectations, I'm running Ubuntu
with XAMPP, I configures everything and I have a Dynamic DNS to my
computer, so basicly I have a website from my home computer, I work with
dreamweaver in another computer and I want to make my ubuntu an FTP Server
so when I push dreamweaver's upload button it will update the files in
ubuntu, is FTP Server the best option for me and will it acomplish what I
need?
Thanks!!
Unnecessary indenting in bash
Unnecessary indenting in bash
I have been trying to paste text from one file to another in bash. Im
working in Putty.
To be more clear, I have a file hotel.txt with some lines of text that are
indented, thus have tabs and spaces. When I paste a few of those indented
lines into another file created using vi , they are pasted with a tab
extra each.
All my text is automatically indented with each line having an extra tab
as soon as I paste using the right click mouse button.
Does anyone have any solution?
Ive tried :set paste, but doesnt work with me apparantly.
I have been trying to paste text from one file to another in bash. Im
working in Putty.
To be more clear, I have a file hotel.txt with some lines of text that are
indented, thus have tabs and spaces. When I paste a few of those indented
lines into another file created using vi , they are pasted with a tab
extra each.
All my text is automatically indented with each line having an extra tab
as soon as I paste using the right click mouse button.
Does anyone have any solution?
Ive tried :set paste, but doesnt work with me apparantly.
gsoap HTTP Authentication
gsoap HTTP Authentication
I am working with gsoap 2.8.15 and I'm trying to implement the HTTP
Authentication by following the instructions in section 19.14 of gsoap
documentation (http://www.cs.fsu.edu/~engelen/soapdoc2.html#tth_sEc19.14).
The only difference is that the codes introduced in the documentation is
written in C but I'am codeing in c++.
Here is my codes for client side of the web service
// The variable wsp is a instance of web service proxy generated by soapcpp2.
// The proxy is a sub-class of the class soap
wsp.userid = "user";
wsp.passwd = "password";
wsp.get_version(&result);
In the server side, I use these codes to check the authentication:
// The variable wss is the a instance of web service service generated by
soapcpp2.
if (wss.userid == NULL || wss.passwd == NULL)
//......
The problem is when I call the function of web service using the
client-side code, the user userid and passwd is always NULL in
server-side. But when I call the same function using soapUI by passing the
userid and passwd with preemptive authorisation type, the server will get
the information without problem.
I appreciate if anyone can help me work out the problem. Thanks for your
attention.
I am working with gsoap 2.8.15 and I'm trying to implement the HTTP
Authentication by following the instructions in section 19.14 of gsoap
documentation (http://www.cs.fsu.edu/~engelen/soapdoc2.html#tth_sEc19.14).
The only difference is that the codes introduced in the documentation is
written in C but I'am codeing in c++.
Here is my codes for client side of the web service
// The variable wsp is a instance of web service proxy generated by soapcpp2.
// The proxy is a sub-class of the class soap
wsp.userid = "user";
wsp.passwd = "password";
wsp.get_version(&result);
In the server side, I use these codes to check the authentication:
// The variable wss is the a instance of web service service generated by
soapcpp2.
if (wss.userid == NULL || wss.passwd == NULL)
//......
The problem is when I call the function of web service using the
client-side code, the user userid and passwd is always NULL in
server-side. But when I call the same function using soapUI by passing the
userid and passwd with preemptive authorisation type, the server will get
the information without problem.
I appreciate if anyone can help me work out the problem. Thanks for your
attention.
Tuesday, 20 August 2013
Date Comparison in iOS
Date Comparison in iOS
I'm trying to check if the time between two dates is larger than 3 months,
but have had no success. Here is what I am trying. Am I doing something
incorrectly? Even if I set the detailTextDate at yesterday, it will still
display the evaluationLabel. Do I need to set a dateFormat?
NSString *detailTextDate = @"August 11, 2013";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = NSDateFormatterLongStyle;
NSDate *startDate = [dateFormatter dateFromString:detailTextDate];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar
components:NSMonthCalendarUnit
fromDate:startDate
toDate:todaysDate
options:0];
if(components.month >= 3){
evaluationLabel.hidden = NO;
}
}
//tried using NSYearCalendarUnit, Month, Day etc.
//startDate = 2013-08-11 06:00:00 +0000, detailTextDate = August 11, 2013,
components = //<NSDateComponents: 0x176c3c70>
// Month: 0
I'm trying to check if the time between two dates is larger than 3 months,
but have had no success. Here is what I am trying. Am I doing something
incorrectly? Even if I set the detailTextDate at yesterday, it will still
display the evaluationLabel. Do I need to set a dateFormat?
NSString *detailTextDate = @"August 11, 2013";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = NSDateFormatterLongStyle;
NSDate *startDate = [dateFormatter dateFromString:detailTextDate];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar
components:NSMonthCalendarUnit
fromDate:startDate
toDate:todaysDate
options:0];
if(components.month >= 3){
evaluationLabel.hidden = NO;
}
}
//tried using NSYearCalendarUnit, Month, Day etc.
//startDate = 2013-08-11 06:00:00 +0000, detailTextDate = August 11, 2013,
components = //<NSDateComponents: 0x176c3c70>
// Month: 0
Show window size while resizing or moving
Show window size while resizing or moving
In other desktop environments, it was possible to display the window size
(and position) while resizing (or moving) the window. In Xubuntu (Ubuntu
12.04.2 LTS, running Xfce), this feature was terminated.
There are at least two use cases where this is quite useful:
Resizing the web browser to specific dimensions (1024x768).
Comparing two PDFs where the content is scaled to fit page width.
The first can be resolved using a plug-in for Chrome or Firefox. The
second could be resolved using the wmctrl app. The convenience of having
the location and dimensions always shown while moving or resizing is quite
handy. Rather than having multiple solutions, or having to run a command,
it'd be nice to have a solution integrated with the window manager.
Ensuring exact window sizes is more than obtuse pedantry.
How would you get this functionality back?
In other desktop environments, it was possible to display the window size
(and position) while resizing (or moving) the window. In Xubuntu (Ubuntu
12.04.2 LTS, running Xfce), this feature was terminated.
There are at least two use cases where this is quite useful:
Resizing the web browser to specific dimensions (1024x768).
Comparing two PDFs where the content is scaled to fit page width.
The first can be resolved using a plug-in for Chrome or Firefox. The
second could be resolved using the wmctrl app. The convenience of having
the location and dimensions always shown while moving or resizing is quite
handy. Rather than having multiple solutions, or having to run a command,
it'd be nice to have a solution integrated with the window manager.
Ensuring exact window sizes is more than obtuse pedantry.
How would you get this functionality back?
Receiving Invalid policy document or request headers error when using fineuploader for amazon s3
Receiving Invalid policy document or request headers error when using
fineuploader for amazon s3
I am trying to use FineUploader's new feature allowing direct upload to
amazon s3. Currently, I am not able to upload photos. I am getting the
error: "Invalid policy document or request headers!"
The developers asked that questions be posted here at stackoverflow.
I am following their instructions on this page:
http://blog.fineuploader.com/2013/08/16/fine-uploader-s3-upload-directly-to-amazon-s3-from-your-browser/#guide
In setting things up, I have also emulated the example file linked to
there:
https://github.com/Widen/fine-uploader-server/blob/master/php/s3/s3demo.php
I have my javascript set up thusly with very few options:
$('#fineuploader-s3').fineUploaderS3({
request: {
endpoint: "http://thenameofmybucket.s3.amazonaws.com",
accessKey: "mypublicaccesskey"
},
signature: {
endpoint: "s3demo.php"
},
iframeSupport: {
localBlankPagePath: "/success.html"
},
cors: {
expected: true
}
});
I know there are lots of places where this could have gone wrong for me. I
have never used s3 or fineuploader before, so sorry if these are dumb
questions. But here are the places where I felt most confused in setting
up. I have a feeling the problem lies in #1:
(1) In the example javascript, this is how the path to signature is set up:
// REQUIRED: Path to our local server where requests can be signed.
signature: {
endpoint: "/s3/signtureHandler"
},
I wasn't sure if that is meant to be an empty file where some json is
created or if it's supposed to point to the php script where the function
to create the json is, in my case s3demo.php, which I copied directly.
(2) In the s3demo.php file, the only lines I changed were these:
$clientPrivateKey = $_SERVER['I put my private key here'];
$expectedBucket = "http://thenameofmybucket.s3.amazonaws.com";
function handlePreflightedRequest() {
// If you are relying on CORS, you will need to adjust the allowed
domain here.
header('Access-Control-Allow-Origin: http://mywebsitename.org');
}
(3) This is what I have for my CORS file, I wasn't sure if it was right
because the examples on the instructional page don't include the tags:
<CORSRule>
<AllowedOrigin>http://mywebsitename.org</AllowedOrigin>
<AllowedMethod>POST</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
(4) As detailed in the instructions, I went into IAM panel and created a
group with the policy copied from the instructions exactly, but with the
actual name of my bucket:
{
"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Action":"s3:PutObject",
"Resource":"arn:aws:s3:::thenameofmybucket/*"
}]
}
, then a user from which I obtained the public and private access keys
used in the javascript and php files respectively.The username is not
specifically used anywhere in the scripts.
I'm hoping there is something really obvious that I've done incorrectly
here. Thanks for your time.
fineuploader for amazon s3
I am trying to use FineUploader's new feature allowing direct upload to
amazon s3. Currently, I am not able to upload photos. I am getting the
error: "Invalid policy document or request headers!"
The developers asked that questions be posted here at stackoverflow.
I am following their instructions on this page:
http://blog.fineuploader.com/2013/08/16/fine-uploader-s3-upload-directly-to-amazon-s3-from-your-browser/#guide
In setting things up, I have also emulated the example file linked to
there:
https://github.com/Widen/fine-uploader-server/blob/master/php/s3/s3demo.php
I have my javascript set up thusly with very few options:
$('#fineuploader-s3').fineUploaderS3({
request: {
endpoint: "http://thenameofmybucket.s3.amazonaws.com",
accessKey: "mypublicaccesskey"
},
signature: {
endpoint: "s3demo.php"
},
iframeSupport: {
localBlankPagePath: "/success.html"
},
cors: {
expected: true
}
});
I know there are lots of places where this could have gone wrong for me. I
have never used s3 or fineuploader before, so sorry if these are dumb
questions. But here are the places where I felt most confused in setting
up. I have a feeling the problem lies in #1:
(1) In the example javascript, this is how the path to signature is set up:
// REQUIRED: Path to our local server where requests can be signed.
signature: {
endpoint: "/s3/signtureHandler"
},
I wasn't sure if that is meant to be an empty file where some json is
created or if it's supposed to point to the php script where the function
to create the json is, in my case s3demo.php, which I copied directly.
(2) In the s3demo.php file, the only lines I changed were these:
$clientPrivateKey = $_SERVER['I put my private key here'];
$expectedBucket = "http://thenameofmybucket.s3.amazonaws.com";
function handlePreflightedRequest() {
// If you are relying on CORS, you will need to adjust the allowed
domain here.
header('Access-Control-Allow-Origin: http://mywebsitename.org');
}
(3) This is what I have for my CORS file, I wasn't sure if it was right
because the examples on the instructional page don't include the tags:
<CORSRule>
<AllowedOrigin>http://mywebsitename.org</AllowedOrigin>
<AllowedMethod>POST</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
(4) As detailed in the instructions, I went into IAM panel and created a
group with the policy copied from the instructions exactly, but with the
actual name of my bucket:
{
"Version":"2012-10-17",
"Statement":[{
"Effect":"Allow",
"Action":"s3:PutObject",
"Resource":"arn:aws:s3:::thenameofmybucket/*"
}]
}
, then a user from which I obtained the public and private access keys
used in the javascript and php files respectively.The username is not
specifically used anywhere in the scripts.
I'm hoping there is something really obvious that I've done incorrectly
here. Thanks for your time.
Subscribe to:
Posts (Atom)