text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Login failed when using custom Grails Spring Security filter I am using Grails with the Spring Security plugin.
I have crafted a custom filter, authentication provider, and token and registered them as beans and into filter chain:
SpringSecurityUtils.clientRegisterFilter('myFilter',SecurityFilterPosition.SECURITY_CONTEXT_FILTER.order + 10)
(I am not really sure what the order should be)
I POST to j_spring_security_check.
All seems to run smoothly to my successfulAuthentication where I set:
SecurityContextHolder.getContext().setAuthentication(authResult);
with no errors and SecurityContextHolder.getContext().getAuthentication() is set.
However Grails redirects me to login failed page.
Is something wrong with the j_spring_security_check page? Where is the error?
A: It was the url j_spring_security_check - it somehow rewrote the security context.
So on using custom filters DO NOT use post url "j_spring_security_check", not necessary also.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Right div fix width, left div extend to max width? I have two divs in the same line, div_left, div_right
I'd like div_right have the fixed width 200px, and left_div extend to the max width and height of the left page, how could I write this with css?
A: html:
<div class="right"></div>
<div class="left"></div>
css:
.right { background: red; height:300px; float:right; width:200px; }
.left { background: green; height:300px; padding-right: 200px; }
code: http://jsfiddle.net/47YMn/1/
A: may be you can use display:table property like this http://jsfiddle.net/sandeep/NCkL4/8/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create curvy corner for a HTML table ? *That should be compatible in IE6* I've a HTML table, i want to make its corners as curvy corners. I've tried but its working only in ff, chrome but not in IE6. I want it to be compatible in different versions of IE. Somebody please tell me how to make it compatible in IE6+?
A: Border-radius is not something that is supported in earlier versions of IE.
However, you can use something like CSS3 Pie to make it work out.
http://css3pie.com
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android build configurations for multiple customers I have Android application that needs to be delivered to multiple customers.
For every customer I have different graphics and configuration XML files which specify features and URLs.
At build time we should be able to specify the customer for which the application should be built. Then resources (like images and run-time configuration) appropriate for the specified client should be built into the app.
The project is build with Maven.
Any ideas?
A: Don't know how well this is supported for Android projects, but the usual way is to define a profile for each customer. In each profile you should override the relevant resource directories with the ones for the specified customer.
A: I ended up using maven profiles and 'renameManifestPackage' and 'resourceOverlayDirectory' properties of the android maven plugin.
The default res/ dir is overriden by 'resourceOverlayDirectory' specific for every customer.
It worked out great.
<!-- profile for zurich -->
<profile>
<id>zurich</id>
<properties>
<customer>zurich</customer>
<customerPackage>zurich.com</customerPackage>
<customerResources>customers/${customer}/res</customerResources>
<customerApkName>${customer}-${project.artifactId}</customerApkName>
</properties>
</profile>
and in the build I have:
<build>
<sourceDirectory>src</sourceDirectory>
<!-- the name of the generated apk and jar -->
<finalName>${customerApkName}-${project.version}</finalName>
<pluginManagement>
<plugins>
<!-- customer specific manifest and package -->
<plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>maven-android-plugin</artifactId>
<configuration>
<renameManifestPackage>${customerPackage}</renameManifestPackage>
<resourceOverlayDirectory>${customerResources}</resourceOverlayDirectory>
</configuration>
</plugin>
</plugins>
</pluginManagement>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Error in while running the android app I got the following error in my emulator while running the my android app.
The application "myapplication name" on a phone(process com.dummies.android.myappname) has stopped unexpectly. Please try agaign
please help me how to solve this error.
A: This error is not helpful ( it just says that the application has crashed ). To get the full trace, you can use Android Debug Bridge ( adb ) which is included in your sdk.
( the default command for checking logs is "adb logcat" )
for more information about adb, you can check http://developer.android.com/guide/developing/tools/adb.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: "Invalid use of 'this' in non-member function" in objective-c context? Using Xcode.
In this code (func is declared in interface), tells subj error, standing on string with 'self'.
+ (void) run: (Action) action after: (int) seconds
{
[self run:action after:seconds repeat:NO];
}
What the... ?
A: self is an instance variable used to refer to an instance of the current object.
You are attempting to use it in a class level method +(void)... where self has no meaning. Try using a shared instance, or passing an instance of the class in question to the method.
+ (void) run:(Action)action on:(MyClass*) instance after:(int) seconds
{
[instance run:action after:seconds repeat:NO];
}
EDIT
My commenters have pointed out that self does have meaning in class level contexts, but it refers to the class itself. That would mean you were trying to call a method that looks like this:
[MyClass run:action after:seconds repeat:NO];
Where you should be aiming for:
[myClassInstance run:action after:seconds repeat:NO];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Array initialization and method count increase ? What's the secret? This Question may be weird or i am plain dumb.
>> Array.methods.count
=> 97
>> a = Array.new.methods
=> 167
What causes the increase in number of methods after an array has been initialized and assigned.
A: You are counting two things: class-methods and instance methods. You may compare it with instance_methods
p Array.methods.count #-> 97
p Array.instance_methods.count #-> 167
p Array.new.methods.count #-> 167
Or take a look if new is a valid method:
p Array.methods.include?(:new) #true
p Array.instance_methods.include?(:new) #false
new is only defined on the class, not in the instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: RPM : How to get Requires(post) list Have generated rpm package with the spec file, where used Requires(post) to specify the required tools for the post installation section.
So how to get the list of Requires(post) tools list from a rpm package ?
rpm -qp --whatrequires .rpm - does not list any tools
A: You are mixing --requires and --whatrequires. The first one will list packages required by package specified, whereas the second one will tell you which packages require given package (or other provided metadata/files).
You should use --requires
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to exclude some values in sorting with MySQL? I have a table like this:
id products_name sort
1 abc 0
2 xyz 1
3 pqr 2
4 qwe 0
I want to sort records through the sort column and in ascending order, but I don't want the rows with 0 at the top in the result set.
The rows having 0 in the sort column should be at the bottom of the result set, and the rest of the rows should be sorted in ascending order using the sort column.
How do I do this?
A: You can use the ORDER BY IF statement:
SELECT *
FROM table
ORDER BY IF(SORT = 0, 999999999, SORT)
or you can use the UNION ALL statement to achieve this:
(SELECT * FROM table WHERE sort > 0 ORDER BY sort)
UNION ALL
(SELECT * FROM table WHERE sort = 0)
A: You could try something like:
ORDER BY IF(SORT=0, 999999999, SORT)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Variable substitution in bash I've recently discovered notify-send, which opens up a notification window, so I can do things like:
compile && notify-send "Done!" || notify-send "Failed"
This made me thing that maybe I want to create a variable:
export NS="&& notify-send \"Done!\" || notify-send \"Failed\""
and then I could easily add it to many command lines for which I want notifications:
compile $NS
send-big-file $NS
start-a-heavy-job $NS
etc. But this obviously doesn't work as it is, and I can't seem to be able to come up with the right combination of variable substitutions to make it work... any ideas?
A: Write a function that takes the command as an argument (untested):
ns() {
"$@" && notify-send Done || notify-send Failed
}
ns compile
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Git cli: get user info from username Is there a way to get the name of the user, given only their username?
Something like this output git show <username> (I know this doesn't work)
username: username
name: First Last
email: email@address
I know I can do this with a GitHub api call, but would prefer to keep it within the CLI.
A: git config --list git config -l will display your username and email together, along with other info
A: Git itself (the command line client, i.e. the "stupid content tracker") has no notion of user names, only GitHub does. In other words: there is no mapping of GitHub usernames to author/committer names and e-mails stored in a Git repository.
When creating a commit with Git it uses the configuration values of user.name (the real name) and user.email (email address). Those config values can be overridden on the console by setting and exporting the environment variables GIT_{COMMITTER,AUTHOR}_{NAME,EMAIL}.
Git doesn't know anything about GitHub's users, because GitHub is not part of Git. So you're only left with an API call to GitHub (I guess you could do that from the command line with a little scripting and make that a Git alias.)
A: You can try this to get infos like:
*
*username: git config --get user.name
*user email: git config --get user.email
There's nothing like "first name" and "last name" for the user.
Hope this will help.
A: Use this to see the logged in user (the actual git account):
git config credential.username
And as other answers the user email and user name (this is differenct from user credentials):
git config user.name
git config user.email
To see the list of all configs:
git config --list
A: Try this
git config user.name
git config command stores and gives all the information.
git config -l
This commands gives you all the required info that you want.
You can change the information using
git config --global user.name "<Your-name>"
Similarly you can change many info shown to you using -l option.
A: if you are using GitHub CLI (because git is already installed):
grep "user:" ~/.config/gh/hosts.yml
2022: Unless you manually set a token by hand, you need to use gh cli with git in order to be able to git push to your own GitHub repos. gh cli can be used to automatically set token credential use, as opposed to onetime (per login), or everytime (per action).
https://github.com/cli/cli
https://cli.github.com
A: Old thread, but since it's still the first hit on Google search, I'll add my two cents. Most answers are technically not correct. As @knittl indicated: to get the username, you'll have to query the service hosting your code, as git itself has no notion of users. You can configure variables like the user.name, but this can be anything and is not necessarily the user creating the commit.
For Github, a way to get the actual username is through their CLI tool gh. Once downloaded and authenticated, you can issue the following to get the username (using jq to retrieve the name):
gh api 'https://api.github.com/user' | jq .login
A: git config user.name
git config user.email
I believe these are the commands you are looking for.
Here is where I found them
A: While its true that git commits don't have a specific field called "username", a git repo does have users, and the users do have names. ;) If what you want is the github username, then knittl's answer is right. But since your question asked about git cli and not github, here's how you get a git user's email address using the command line:
To see a list of all users in a git repo using the git cli:
git log --format="%an %ae" | sort | uniq
To search for a specific user by name, e.g., "John":
git log --format="%an %ae" | sort | uniq | grep -i john
A: Add my two cents, if you're using windows commnad line:
git config --list | findstr user.name will give username directly.
The findstr here is quite similar to grep in linux.
A: its So Simple You Just Copy and Past
For List Of All Config :- git config --list
and Also You Can Try :- git config -l
if you need to perticular Than You Can Use
user name :- git config user.name
user email :- git config user.email
If you need To add Config Than
user name :- git config user.name "name of user"
user email :- git config user.email "email of user"
Hope its HelpFull,
Thank You
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "104"
}
|
Q: MFC C++: how can I lock a file to be used only in my process? I'd like to lock a couple of files to be only used by my process, denying any other application access to these files while my program is running. Of course I know that I can get exclusive access to a file using Createfile, but my application works differently, I read a bunch of filenames froma config, and process these files with a Lib linked to my application, i.e. one of the functions in my lib accesses the files, but I don't get a filoehandle or something similar in return.
So what I want to acchieve is that while my app is processing these files, no other application can modify them. Is this somehow possible? I am developing using MFC in Visual Studio 8.
A: I've never used them, but LockFile/LockFileEx docs say: Locks the specified file for exclusive access by the calling process.
A: You need cooperation from the OS, because that's the only way to influence other processes.
The OS requires that you use handles to refer to files. It's really the only practical way for the OS; using pathnames would be far too complex. So, you will need to call CreateFile. At that point, just request exclusive access.
A: Why doens't the CreateFile()'s exclusive flag achieve this? It looks like you don't need anything fancy. If your library opens the file with CFile::shareDenyRead and CFile::shareDenyWrite, no other process can read your files as long as they are open by your library.
A: What you're asking can't be done.
Because exclusive access is granted per handle, not per process, if you open a file with exclusive access once, every subsequent attempt to open it will fail, even if it is from the same process. Exclusive access here means your handle is the only valid one, not that only your process can access it.
So even if you lock a file, your lib won't be able to open it, so it's useless to you. The only way is to lock a file and pass the handle to your lib, which you can't do because your lib wants a filename. Likewise you can't lock the file once it's open by the lib because it won't give you the handle. If you don't have access to the source code of the lib, you're stuck.
You possibly could try something with user permissions, having you're process run from it's own user account and changing the ownership of the files you're about to modify and then changing it back when you're done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML Form submission with javascript confirm delays on Google Chrome I realized that there's some delay on form submission with javascript confirmation on Google Chrome during my development.
So I tried test with small html page to make sure whether the delay is caused by my application. But it still happening in the test page.
I just don't want to confirm on form's onsubmit event as there will be more than one submission for different purposes.
So here's my test html.
<html>
<head><title>Test</title></head>
<body>
<script type="text/javascript">
var currentTime = new Date()
document.write(currentTime.getMilliseconds());
</script>
<form name="input" method="post">
<input type="submit" value="Submit" onclick="javascript:return confirm('Are you sure to submit?');" />
</form>
</body>
</html>
How can I avoid that delay? Do I need to change anything from my end?
Please correct if that caused by my html which is not construct well form or missing something.
Thanks.
A: There are two issues with your code. The less significant one is that you're using javascript: in your onclick attibute, which is not needed. on* attributes are implicitly evaluated as JavaScript already - they're not like hyperlinks.
Secondly, and most importantly, that timer value you're showing on screen is not showing what you think it does. It's just getting the current date and time, and extracting the millisecond component. That essentially gives you a random number between 0 and 999. If that's what you're using to determine the submission delay, you are mistaken. Rest assured that the form will be submitted as soon as you press OK on the confirmation dialog, and any delay you experience is entirely due to page load time (assuming there are no page unload scripts).
A: Oddly I was having a similar problem as you, but it was also appearing in FF as well... After reworking things I came up with:
<form name='doClear' action='index.php' method='post' >
<input type='submit' value='Clear All' onclick='return confirm(\"Are you sure you want to clear all? This cannot be undone!\");' />
</form>";
Which works instantly for me. I am not sure where my issues were coming from before, but things are working fine now. Good luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Image is chopping off while using SVG converter The image is chopping off when i am trying to convert svg file to png image using org.apache.batik.apps.rasterizer.SVGConverter. The java code is mentioned below.
SVGConverter svgConverter = new SVGConverter();
svgConverter.setDestinationType(DestinationType.PNG);
svgConverter.setSources(new String[]{ new File(svgsource).toURL().toString() });
svgConverter.setDst(new File(imgDest));
svgConverter.execute();
Also please find the code for SVG file.
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<line x1="10" y1="0" x2="10" y2="500" style="stroke: #000000; stroke-width: 1;" />
<line x1="10" y1="500" x2="500" y2="500" style="stroke: #000000; stroke-width: 1;" />
<text x="0" y="520" style="stroke: none; fill: #000000; font-family: Arial; font-size: 10px;" >3PA</text>
<line x1="100" y1="0" x2="100" y2="500" style="stroke: darkgray; stroke-width: 0.2" />
<text x="100" y="520" style="stroke: none; fill: #000000; font-family: Arial; font-size: 10px;" >3PB</text>
<line x1="200" y1="0" x2="200" y2="500" style="stroke: darkgray; stroke-width: 0.2" />
<text x="200" y="520" style="stroke: none; fill: #000000; font-family: Arial; font-size: 10px;" >3PC</text>
<line x1="300" y1="0" x2="300" y2="500" style="stroke: darkgray; stroke-width: 0.2" />
<text x="300" y="520" style="stroke: none; fill: #000000; font-family: Arial; font-size: 10px;" >4PA</text>
<line x1="400" y1="0" x2="400" y2="500" style="stroke: darkgray; stroke-width: 0.2" />
<text x="400" y="520" style="stroke: none; fill: #000000; font-family: Arial; font-size: 10px;" >4PB</text>
<line x1="10" y1="100" x2="500" y2="100" style="stroke: darkgray; stroke-width: 0.2" />
<line x1="10" y1="200" x2="500" y2="200" style="stroke: darkgray; stroke-width: 0.2" />
<line x1="10" y1="300" x2="500" y2="300" style="stroke: darkgray; stroke-width: 0.2" />
<line x1="10" y1="400" x2="500" y2="400" style="stroke: darkgray; stroke-width: 0.2" />
<line x1="10" y1="450" x2="100" y2="450"
style="stroke:yellow; stroke-width:5; stroke-linejoin:miter" />
<line x1="100" y1="450" x2="200" y2="330"
style="stroke:yellow; stroke-width:5; stroke-linejoin:miter" />
<line x1="200" y1="330" x2="300" y2="380"
style="stroke:yellow; stroke-width:5; stroke-linejoin:miter" />
<polygon points="300,380 400,320 400,360 300,380"
style="fill:paleturquoise; stroke: darkturquoise; stroke-width:1" />
<line x1="100" y1="420" x2="100" y2="460"
style="fill:darkturquoise; stroke: darkturquoise; stroke-width:7" />
<line x1="200" y1="340" x2="200" y2="380"
style="stroke:darkturquoise; stroke: darkturquoise; stroke-width:7" />
<line x1="300" y1="310" x2="300" y2="350"
style="stroke:darkturquoise; stroke: darkturquoise; stroke-width:7" />
<line x1="400" y1="320" x2="400" y2="360"
style="stroke:darkturquoise; stroke: darkturquoise; stroke-width:7" />
<text x="400" y="320" style="stroke: none; fill: #000000; font-family: Arial; font-size: 10px;" >320</text>
<text x="400" y="360" style="stroke: none; fill: #000000; font-family: Arial; font-size: 10px;" >360</text>
</svg>
Please also find the online editor image and png file which is generated by the Java code .
Please help me to get the full image as online image editor.
A: Mention the height and width in svg tag like
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="600" height="600">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to build an android project depending on another project I try to build an android project depending on OpenCV. But got
cannot find symbol
[javac] symbol : class utils
[javac] location: package org.opencv
[javac] Mat imagePointsMat = org.opencv.utils.vector_Point_to_Mat(im
it looks like, the 'ant compile' command under my project does not compile the OpenCV project first, but I do not know how to fix it.
A: Make sure that your library in the CLASSPATH! If you are using Eclipse, go to your Android project, right click on it and choose Java Build Path. In there select Libraries path and add your library (either JAR file, class folder, etc).
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Complex SQL statement feasibility I am currently developing a database system for a school that will work with our booking system so students can book their courses and we can better track their activity. Right now I am faced with a complex issue, what I want to do is check which student contracts are valid, I can do so by using the following function, but I want to see if there is an easier way to properly do it (besides storing data I can compute in the system.)
If a contract is valid then the student has not used up all the hours they have purchased, hours purchased is the sum of the length of teach class they have attended added to the sum of the lengths of each class they missed but booked (after a certain number, such as 3 or 5). I can do it with the following query but I feel like there must be a simpler way:
SELECT
level.name
FROM
(
SELECT
contract.level_package_id,
contract_class_hours.hours_purchased,
(
SELECT
isnull(sum(DATEPART(hh, class.end_date - class.start_date)), 0)
FROM
booking
JOIN class ON class.id = booking.class_id
WHERE
booking.booking_state_id = 3
AND booking.contract_id = contract.id
) AS time_attended,
(
SELECT
isnull(sum(absent_class_lengths.length), 0)
FROM
(
SELECT
DATEPART(hh, class.end_date - class.start_date) AS length,
row_number() OVER (ORDER BY class.start_date) AS rn
FROM
booking
JOIN class ON class.id = booking.class_id
WHERE
student_id = 5
AND booking_state_id = 4
AND booking.contract_id = contract.id
) absent_class_lengths
WHERE
rn > contract_class_hours.absences_allowed
) as time_absent
FROM
contract
JOIN contract_class_hours ON contract_class_hours.contract_id = contract.id
) test
JOIN level_package_level ON level_package_level.level_package_id = test.level_package_id
JOIN level ON level.id = level_package_level.level_id
WHERE
test.time_absent + test.time_attended < test.hours_purchased
AND level.study_type_id = 2
*
*booking.state_id = 3 means the student attended class
*booking.state_id = 4 means the student was absent
*level.study_type_id = 2 is just a course subject
The tables contain data columns like these (ignore level_id, it is just a value I need to return):
CLASS
id - int
end_date - datetime
start_date - datetime
BOOKING
id - int
class_id - int
student_id - int
booking_state_id - smallint
BOOKING_STATE
id - int
state - varchar(20) [absent, attended]
CONTRACT
id - int
student_id - int
level_id - int
hours_purchased - smallint
absenses_allowed - smallint
STUDENT
id - int
I realize this may be to complicated a question to ask, but I am just wondering if this really is the proper way to do things, or if I should just save some sort of field in the contract table that has a number of hours attended and assume it is always accurate.
A: Seems like you could do a few things to improve the situation
*
*Create a view with some of the code
*Use the above response to create a stored procedure, and make the hard coded ids variables
WHERE class.student_id = 5
AND booking_state_id = 4
I am guessing these are not always going to be the same and having a stored procedure will allow a plan to be cached as compared to an AD Hoc sql statement. This will allow you to send in various ids to get the results you want and return a data set that could be used in a web applciaiton of simply converted to and Exce or Word table for reporting.
A: This should yield the same functionality and be easier to read:
SELECT
level.name
FROM contract
INNER JOIN contract_class_hours ON contract_class_hours.contract_id = contract.id
INNER JOIN level_package_level ON level_package_level.level_package_id = contract.level_package_id
INNER JOIN level ON level.id = level_package_level.level_id
Outer Apply(
SELECT isnull(sum(DATEPART(hh, class.end_date - class.start_date)), 0) AS time_attended
FROM booking
INNER JOIN class ON class.id = booking.class_id
WHERE booking.booking_state_id = 3
AND booking.contract_id = contract.id
) T1
Outer Apply(
SELECT snull(sum(absent_class_lengths.length), 0) AS time_absent
FROM
(
SELECT DATEPART(hh, class.end_date - class.start_date) AS length,
row_number() OVER (ORDER BY class.start_date) AS rn
FROM booking
INNER JOIN class ON class.id = booking.class_id
WHERE class.student_id = 5
AND booking_state_id = 4
AND booking.contract_id = contract.id
) absent_class_lengths
WHERE
rn > contract_class_hours.absences_allowed
) T2
WHERE T2.time_absent + T1.time_attended < contract_class_hours.hours_purchased
AND level.study_type_id = 2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: google map with route in blackberry how to use google map with route in blackberry . i tried blackberry map with route but in my device (Storm 2) cant display map . i dont know what is the issue ?
any one have idea ragarding google map in blackberry application than let me know.
i tried this http://maps.google.com/maps?saddr=23.4444,72.44445&daddr=23.55555,72.55555
and open this url in BB browser but it cant redirect to map site .
how can we handle google map or blackberry map with route in BB application ?
A: i have implemented Google Map with route in Blackberry via Google Map Installed App.
public void invokeGoogleMap() {
int mh = CodeModuleManager.getModuleHandle("GoogleMaps");
if (mh == 0)
{
try
{
throw new ApplicationManagerException("GoogleMaps isn't installed");
}
catch (ApplicationManagerException e)
{
System.out.println(e.getMessage());
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
stubDialog.inform("GoogleMaps isn't installed on your device.download it from m.google.com/maps.");
}
});
}
else
{
URLEncodedPostData uepd = new URLEncodedPostData(null, false);
uepd.append("action", "ROUT"); // or LOCN
uepd.append("start", "23.039568,72.566005");
uepd.append("end", "23.02,73.07");
String[] args = { "http://gmm/x?" + uepd.toString() };
ApplicationDescriptor ad = CodeModuleManager.getApplicationDescriptors(mh)[0];
ApplicationDescriptor ad2 = new ApplicationDescriptor(ad, args);
try
{
ApplicationManager.getApplicationManager().runApplication(ad2, true);
}
catch (ApplicationManagerException e)
{
System.out.println(e.getMessage());
}
}
}
A: Blackberry browser is not fully functional for java script to display route info in browser field.Instead you have to use Blackberry maps. for this the following link will help you.
How to find the route between two places in BlackBerry?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android MediaPlayer release(); error I have 2 activities and a static mediaplayer in my first activity I prepare and start the media player and jump to other activity. In the second activity I can pause and play this media player when I press back button on the second activity it goes to the first activity and than stop media player and than release media player but mp.release gives me "has stopped unexpectedly error". Can you help me please? I need to make this mp.release() work
new AsyncTask<Void, Double, Void>() {
@Override
protected Void doInBackground(Void... params) {
while (true) {
publishProgress(Math.random());
SystemClock.sleep(3000);
if(isOnline(Start.this) == true && connection == true){
LinkedList<String> urls = readM3UtoUrlList("url.m3u");
mp = new MediaPlayer();
try {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(urls.getFirst());
mp.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
Intent i = new Intent(Start.this, RadyoBabylonActivity.class);
startActivityForResult(i, RadyoBabylonActivity.class.hashCode());
}
});
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@Override
protected void onProgressUpdate(Double... values) {
}
}
}.execute();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode==-1){
Log.d("myerror", "kapanacavk");
mp.stop();
if(!mp.isPlaying())
{
mp.release();
finish();
}
}
}
log
ERROR/AndroidRuntime(7480): FATAL EXCEPTION: main
ERROR/AndroidRuntime(7480): java.lang.IllegalStateException
ERROR/AndroidRuntime(7480): at android.media.MediaPlayer.isPlaying(Native Method)
ERROR/AndroidRuntime(7480): at com.radyobabylon.RadyoBabylonActivity$2.onProgressUpdate(RadyoBabylonActivity.java:189)
ERROR/AndroidRuntime(7480): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:432)
ERROR/AndroidRuntime(7582): at android.os.Handler.dispatchMessage(Handler.java:99)
ERROR/AndroidRuntime(7582): at android.os.Looper.loop(Looper.java:123)
ERROR/AndroidRuntime(7582): at android.app.ActivityThread.main(ActivityThread.java:4627)
ERROR/AndroidRuntime(7582): at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/AndroidRuntime(7582): at java.lang.reflect.Method.invoke(Method.java:521)
ERROR/AndroidRuntime(7582): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
ERROR/AndroidRuntime(7582): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
ERROR/AndroidRuntime(7582): at dalvik.system.NativeStart.main(Native Method)
A: I think you need to stop your progress update loop before releasing the mediaplayer object as you are not allowed to call isPlaying() on a released mediaplayer see here for the list of valid states
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android screenshot - How to? Is there any neat way of accessing screenshot of android device
programatically. I am looking for some 15-20fps.
I found one code
android\generic\frameworks\base\services\surfaceflinger\tests\screencap\scr eencap.cpp,
i built the executable and put it in /data and changed the mode 777
but when i tried to execute it using adb shell it gives the below error.
# chmod 777 test-screencap
chmod 777 test-screencap
# ./test-screencap test
./test-screencap test
screen capture failed: Function not implemented
I also know that we can access fb0 but its not a right method as suggested
by android team. Is it possible to access the screen shot at the frameworks
layer. I beleive surface flinger composes individual layers and gives it to
framebuffer.Where exactly this is done ? Can a application be able to access
such codes.
There are some java apps also which use ddms to actually capture this
framebuffer data without root access. But the fps is really poor.
I beleive there should be some or the other way of doing the above job.
Please suggest me some neat way of doing it. Suggestions are welcome.
A: What you are trying to do is not possible if you don't have a rooted phone, there is an app out there that does what you are trying, Screenshot ER. The latest OEM's are putting it into their /system/apps now... so you may be able to use their apps, check out this article for devices that have enabled this feature. Other than that your really stuck but there are implications with screen captures enabled as this could lead apps saving screen captures and sending that info out, enabling virus type apps...
Information for others .....Through Eclipse you can get a screen capture usig the DDMS perspective. If you take a look at the Eclipse DDMS code base its actually a stand-alone app too. You might be able to use this Java code then.
AdbHelper.getFrameBuffer(AndroidDebugBridge.getSocketAddress(), this);
A: Take a look at droid VNC Server
This is an open source project which you can clone the source code to your private PC. (http://github.com/oNaiPs/droid-VNC-server). I am investigating how VNC can do but It's really hard to do the same.
Read framebuffer content is an good solution also. But it just work with android <3.x only. I don't know how to fix it to work on android 4.x. If you know how (after see my suggestion) please share it here. Through my researching, I see that there are a lot of people looking for this.
Hope this helps.
nguyenminhbinh1602@gmail.com.
Android Freelancer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why does 'git checkout' work only for some branches? Here is the result of two checkouts: why the second is failing? 'git status' shows some files have been modified, but I am sure I haven't touched those files.
praveensripati@MyMini:~/Hadoop/Git/hadoop-common$ git checkout branch-0.21
Switched to branch 'branch-0.21'
praveensripati@MyMini:~/Hadoop/Git/hadoop-common$ git checkout branch-0.20
error: The following untracked working tree files would be overwritten by checkout:
CHANGES.txt
LICENSE.txt
README.txt
bin/hadoop
bin/hadoop-daemon.sh
bin/hadoop-daemons.sh
Please move or remove them before you can switch branches.
Aborting
praveensripati@MyMini:~/Hadoop/Git/hadoop-common$ git status
# On branch trunk
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# CHANGES.txt
# LICENSE.txt
# README.txt
# bin/
# build.xml
# conf/
# lib/
# site/
# src/
nothing added to commit but untracked files present (use "git add" to track)
A: This is occurring because some or all of the files that are not being tracked on your current branch are being tracked by the branch you want to change to.
For example the branch may contain a CHANGES.txt. Because git does not want to overwrite the file you have in your workspace if is giving your this error to allow you to backup the files you have locally. You can either:
*
*Move these files somewhere safe
*If you are sure you don't need these files, you can perform a checkout -f to switch to the branch (this will overwrite any files that conflict)
Stashing does not work for files that are not tracked on the current branch. You can use git diff to work out which files are on the 0.20 but not on 0.21. For example:
git diff --name-only branch-0.20
A: That can happen if there is a filter in place, automatically changing the content of those files on checkout. As in:
core.autocrlf=true
(See Why should I use core.autocrlf=true in Git?)
For instance, if the eol style is changed automatically, you would have modified files in your working tree.
And that would be enough to prevent another checkout with common modified files.
You can stash the changes, as Kit suggests, but I would recommend understanding first why those changes happen in the first place.
A: git stash
git checkout branch-0.20
git stash apply
try above
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: html Text editor not displayed in ajax form I am using a Text Editor which will be displayed in a add form.I am loading the form through ajax.When i click the add button the add form will loaded in ajax.Now the problem is my HTML Text editors script files are not getting loaded in my ajax form.Simple text area alone displays.
How to load the text editor in the ajax form,Please advice me.
This is the editor i am using
<script type='text/javascript'>
var j = jQuery.noConflict();
j(function() {
j("#Textarea1").htmlarea({
toolbar: ["html", "|",
"forecolor",
"|", "bold", "italic", "underline", "|", "p", "h1", "h2", "h3", "|", "link", "unlink"] // Overrides/Specifies the Toolbar buttons to show
});
});
</script>
<textarea id="Textarea1" cols="50" rows="15"><p><h3>Another TextArea</h3>This is some sample text to test out the <b>WYSIWYG Control</b>.</p></textarea>
A: Please try to load all the js files during Ajax load.
Please also mention the type of html editor you are using like FCKEditor, Tiny MCE etc.
A: The js you use to create the editor is probably only getting loaded at run time. Move it to a function, call on ready and on ajax success.
A: No the function will not execute. If you want that to run the script you will need to call a function after your response to "eval" the script for you.
Your new function will need to find and execute the script in the DOM.
pseudo code below
//put your response in a div or something and use the div id to grab the tag with a name = to script
divId.getElementsByTagName("script")
loop...
eval(script.innerHTML)
That will always happen with scripts loaded via AJAX into the document. To get around this you can do two things.
*
*Use DOM to get the AJAX response, and then append it to the head of the document so that it will be treated as a script.
*Use eval(). I discourage doing this, but some people don't care about using it, especially when the code is small.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: when I do order on a counter_cache it returns nil objects first? I have owns_count counter_cache on my items model. When i do
Items.order("owns_cache DESC")
, it returns me objects that are nil before other results. If I do
"owns_cache ASC"
, it is correct.
What should I be doing?
A: How NULLs get ordered depends on the underlying database.
For PostgreSQL, you could do this:
Items.order("owns_cache DESC NULLS LAST")
For MySQL and SQLite:
Items.order("COALESCE(owns_cache, 0) DESC")
I think MySQL sorts NULLs at the bottom of a DESC ordering though so you might not need anything special there. This COALESCE approach will also work in PostgreSQL so this would be a portable solution that should give you consistent results everywhere.
If you wanted NULLs at the bottom on an ASC sort, you'd replace the 0 with something larger than the largest owns_cache number.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: retaining the time zone in NSDateFormatter I have to set a format string for a DateFormatter to convert a NSString to a NSDate.
The string is in the format: 2011-01-31 12:45:00 +0200 (y-m-d h:m:s timezone)
I'm using the format: @"yyyy'-'MM'-'dd' 'HH':'mm':'ss' 'Z" , but the timezone is converted to +0000 and the hour is adjusted, so a string like:
2011-01-31 12:45:00 +0200 is converted to:
2011-01-31 10:45:00 +0000
The Code is here:
- (NSDate *) dateForString: (NSString *)dateString
{
NSDateFormatter *dateFormatter;
NSLocale *enUSPOSIXLocale;
NSDate *date;
dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd' 'HH':'mm':'ss' 'Z"];
// [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
date = [dateFormatter dateFromString:dateString];
return date;
}
A: This is absolutely expected behaviour when using NSDate - NSDate represents a moment in time so in your case the 2 date/times are equivalent.
Just make sure when you display the date using the a dateFormatter you set the timezone on the date formatter to how you want it displayed.
A: Have a look at setTimeZone: in
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html
Some more info can also be found here:
NSDate - Convert Date to GMT (maybe duplicate?)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript - insert image tag at the position of the cursor in the textarea I know there are a few posts with the similar title, but they don't seem to refer to the same question.
I'm trying to put the image tag at the position of the cursor inside of the specific textarea from withing the popup instantiated by the button from the same page as the textearea.
At the moment I simply append the image tag to the end of the content in textarea like so:
window.opener.document.getElementById('textarea_id').value += '<img .... />';
I've found one post here: How To insert an image at cursor position in tinymce, but obviously this one refers to the tinymce, which has some built in functions available.
Any thoughts?
A: You could use selectionStart read more about it at: https://developer.mozilla.org/en-US/docs/DOM/HTMLTextAreaElement
window.opener.document.getElementById('textarea_id').selectionStart
Also see Caret position in textarea, in characters from the start
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Invokes and Delegates in C# Can someone explain the syntax in this block of code?
Invoke((MethodInvoker)
(
() =>
{
checkedListBox1.Items.RemoveAt(i);
checkedListBox1.Items.Insert(i, temp);
checkedListBox1.Update();
}
)
);
I'm using a backgroundworker which needs to update parts of the UI so I used this. It works, but I don't know what the empty () and => mean.
A: () and => is a lambda expression.
Action a = () => {
//code here
}
is a delegate of type Action, which executes the code in the block.
Func<string> f = () => {
//code here
return "string";
}
is a delegate of type Func<string>, which executes the code in the block and then returns a string.
Func<int, int, string> f = (i, j) => {
//code here
return "string"+i+j;
}
is a delegate of type Func<int, int, string>, which has two int parameters referred to i and j in the code block and returns a string.
Etc...
A: () => introduces a lambda expression.
If the lambda expression received parameters then they would be listed inside the parentheses. Your lambda is equivalent to
void foo()
{
...
}
A: that a Lambda eExpression. The epmty brackets mean that it does not accept any parameters.
Although this snippet seems like it's missing something, don't think it compiles. W
hat Invoke does is call the UI thread. When you do processing, you want to do that on a background thread, and only make short calls to the UI thread. That way you keep the UI responsive.
So this snippts passes a piece of work (add items to the Combobox) to the UI thread to have it done. A background thread cannot directly do things on the UI thread.
Regards GJ
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is a day always 86,400 epoch seconds long? While reviewing my past answers, I noticed I'd proposed code such as this:
import time
def dates_between(start, end):
# muck around between the 9k+ time representation systems in Python
# now start and end are seconds since epoch
# return [start, start + 86400, start + 86400*2, ...]
return range(start, end + 1, 86400)
When rereading this piece of code, I couldn't help but feel the ghastly touch of Tony the Pony on my spine, gently murmuring "leap seconds" to my ears and other such terrible, terrible things.
When does the "a day is 86,400 seconds long" assumption break, for epoch definitions of 'second', if ever? (I assume functions such as Python's time.mktime already return DST-adjusted values, so the above snippet should also work on DST switching days... I hope?)
A: In all time zones that "support" daylight savings time, you'll get two days a year that don't have 24h. They'll have 25h or 23h respectively. And don't even think of hardcoding those dates. They change every year, and between time zones.
Oh, and here's a list of 34 other reasons that you hadn't thought about, and why you shouldn't do what you're doing.
A: Whenever doing calendrical calculations, it is almost always better to use whatever API the platform provides, such as Python's datetime and calendar modules, or a mature high-quality library, than it is to write "simpler" code yourself. Date and calendar APIs are ugly and complicated, but that's because real-world calendars have a lot of weird behavior.
For example, if it is "10:00:00 AM" right now, then the number of seconds to "10:00:00 AM tomorrow" could be a few different things, depending on what timezone(s) you are using, whether DST is starting or ending tonight, and so on.
Any time the constant 86400 appears in your code, there is a good chance you're doing something that's not quite right.
And things get even more complicated when you need to determine the number of seconds in a week, a month, a year, a quarter, and so on. Learn to use those calendar libraries.
A: Number of seconds in a day depends on time system that you use e.g., in POSIX, a day is exactly 86400 seconds by definition:
As represented in seconds since the Epoch, each and every day shall be
accounted for by exactly 86400 seconds.
In UTC, there could be a leap second included i.e., a day can be 86401 SI seconds (and theoretically 86399 SI seconds). As of Jun 30 2015, it has happened 26 times.
If we measure days by apparent motion of the Sun then the length of a (solar) day varies through the year by ~16 minutes from the mean.
In turn it is different from UT1 that is also based on rotation of the Earth (mean solar time). An apparent solar day can be 20 seconds shorter or 30 seconds longer than a mean solar day. UTC is kept within 0.9 seconds of UT1 by the introduction of occasional intercalary leap seconds.
If you define a day by local clock then it may be very chaotic due to bizarre political timezone changes. It is not correct to assume that a day may change only by an hour due to DST.
A: According to Wikipedia,
UTC days are almost always 86 400 s long, but due to "leap seconds"
are occasionally 86 401 s and could be 86 399 s long (though the
latter option has never been used as of December 2010); this keeps the
days synchronized with the rotation of the Earth (or Universal Time).
I expect that a double leap second could in fact make the day 86402s long, if that were to ever be used.
EDIT again: second guessed myself due to confusing python documentation. time.mktime always returns UTC epoch seconds. There done. : )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
}
|
Q: Parallel Reduction in CUDA for calculating primes I have a code to calculate primes which I have parallelized using OpenMP:
#pragma omp parallel for private(i,j) reduction(+:pcount) schedule(dynamic)
for (i = sqrt_limit+1; i < limit; i++)
{
check = 1;
for (j = 2; j <= sqrt_limit; j++)
{
if ( !(j&1) && (i&(j-1)) == 0 )
{
check = 0;
break;
}
if ( j&1 && i%j == 0 )
{
check = 0;
break;
}
}
if (check)
pcount++;
}
I am trying to port it to GPU, and I would want to reduce the count as I did for the OpenMP example above. Following is my code, which apart from giving incorrect results is also slower:
__global__ void sieve ( int *flags, int *o_flags, long int sqrootN, long int N)
{
long int gid = blockIdx.x*blockDim.x+threadIdx.x, tid = threadIdx.x, j;
__shared__ int s_flags[NTHREADS];
if (gid > sqrootN && gid < N)
s_flags[tid] = flags[gid];
else
return;
__syncthreads();
s_flags[tid] = 1;
for (j = 2; j <= sqrootN; j++)
{
if ( gid%j == 0 )
{
s_flags[tid] = 0;
break;
}
}
//reduce
for(unsigned int s=1; s < blockDim.x; s*=2)
{
if( tid % (2*s) == 0 )
{
s_flags[tid] += s_flags[tid + s];
}
__syncthreads();
}
//write results of this block to the global memory
if (tid == 0)
o_flags[blockIdx.x] = s_flags[0];
}
First of all, how do I make this kernel fast, I think the bottleneck is the for loop, and I am not sure how to replace it. And next, my counts are not correct. I did change the '%' operator and noticed some benefit.
In the flags array, I have marked the primes from 2 to sqroot(N), in this kernel I am calculating primes from sqroot(N) to N, but I would need to check whether each number in {sqroot(N),N} is divisible by primes in {2,sqroot(N)}. The o_flags array stores the partial sums for each block.
EDIT: Following the suggestion, I modified my code (I understand about the comment on syncthreads now better); I realized that I do not need the flags array and just the global indexes work in my case. What concerns me at this point is the slowness of the code (more than correctness) that could be attributed to the for loop. Also, after a certain data size (100000), the kernel was producing incorrect results for subsequent data sizes. Even for data sizes less than 100000, the GPU reduction results are incorrect (a member in the NVidia forum pointed out that that may be because my data size is not of a power of 2).
So there are still three (may be related) questions -
*
*How could I make this kernel faster? Is it a good idea to use shared memory in my case where I have to loop over each tid?
*Why does it produce correct results only for certain data sizes?
*How could I modify the reduction?
__global__ void sieve ( int *o_flags, long int sqrootN, long int N )
{
unsigned int gid = blockIdx.x*blockDim.x+threadIdx.x, tid = threadIdx.x;
volatile __shared__ int s_flags[NTHREADS];
s_flags[tid] = 1;
for (unsigned int j=2; j<=sqrootN; j++)
{
if ( gid % j == 0 )
s_flags[tid] = 0;
}
__syncthreads();
//reduce
reduce(s_flags, tid, o_flags);
}
A: While I profess to know nothing about sieving for primes, there are a host of correctness problems in your GPU version which will stop it from working correctly irrespective of whether the algorithm you are implementing is correct or not:
*
*__syncthreads() calls must be unconditional. It is incorrect to write code where branch divergence could leave some threads within the same warp unable to execute a __syncthreads() call. The underlying PTX is bar.sync and the PTX guide says this:
Barriers are executed on a per-warp basis as if all the threads in a
warp are active. Thus, if any thread in a warp executes a bar
instruction, it is as if all the threads in the warp have executed the
bar instruction. All threads in the warp are stalled until the barrier
completes, and the arrival count for the barrier is incremented by the
warp size (not the number of active threads in the warp). In
conditionally executed code, a bar instruction should only be used if
it is known that all threads evaluate the condition identically (the
warp does not diverge). Since barriers are executed on a per-warp
basis, the optional thread count must be a multiple of the warp size.
*Your code unconditionally sets s_flags to one after conditionally loading some values from global memory. Surely that cannot be the intent of the code?
*The code lacks a synchronization barrier between the sieving code and the reduction, this can lead to a shared memory race and incorrect results from the reduction.
*If you are planning on running this code on a Fermi class card, the shared memory array should be declared volatile to prevent compiler optimization from potentially breaking the shared memory reduction.
If you fix those things, the code might work. Performance is a completely different issue. Certainly on older hardware, the integer modulo operation was very, very slow and not recommended. I can recall reading some material suggesting that Sieve of Atkin was a useful approach to fast prime generation on GPUs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: didSelectRowAtIndexPath throws exception This is probably some simple mistake, I just can't seem to find it in my code.
When ever I click a cell in my tableview I get an exception
This is my interface:
@interface MenuViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@end
I don't use XIB files so this is my loadView
- (void)loadView
{
UIView *myview = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.title = @"Menu";
UITableView *tableViewMenuItems = [[UITableView alloc] initWithFrame:CGRectMake(10, 10, 300, 150) style:UITableViewStyleGrouped];
tableViewMenuItems.backgroundColor = [UIColor clearColor];
tableViewMenuItems.delegate = self;
tableViewMenuItems.dataSource = self;
tableViewMenuItems.scrollEnabled = NO;
[myview addSubview:tableViewMenuItems];
[tableViewMenuItems release];
self.view = myview;
[myview release];
}
And this is the delegate method for selecting a row
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
SendMessageViewController *sendMessageViewController = [[SendMessageViewController alloc] init];
[self.navigationController pushViewController:sendMessageViewController animated:YES];
[sendMessageViewController release];
}
And my bt
#0 0x94e3c9c6 in __pthread_kill ()
#1 0x98079f78 in pthread_kill ()
#2 0x9806abdd in abort ()
#3 0x9588a921 in abort_message ()
#4 0x958881bc in default_terminate ()
#5 0x010ee23b in _objc_terminate ()
#6 0x958881fe in safe_handler_caller ()
#7 0x95888268 in std::terminate ()
#8 0x958892a0 in __cxa_throw ()
#9 0x010ee416 in objc_exception_throw ()
#10 0x00f9c0bb in -[NSObject(NSObject) doesNotRecognizeSelector:] ()
#11 0x00f0b966 in ___forwarding___ ()
#12 0x00f0b522 in __forwarding_prep_0___ ()
#13 0x0008c870 in -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] ()
#14 0x00082b05 in -[UITableView _userSelectRowAtPendingSelectionIndexPath:] ()
#15 0x0079c79e in __NSFireDelayedPerform ()
#16 0x00f7b8c3 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ ()
#17 0x00f7ce74 in __CFRunLoopDoTimer ()
#18 0x00ed92c9 in __CFRunLoopRun ()
#19 0x00ed8840 in CFRunLoopRunSpecific ()
#20 0x00ed8761 in CFRunLoopRunInMode ()
#21 0x011d21c4 in GSEventRunModal ()
#22 0x011d2289 in GSEventRun ()
#23 0x00023c93 in UIApplicationMain ()
#24 0x00002589 in main (argc=1, argv=0xbffff698) at main.m:14
What am I doing wrong?
A: Look at this line
-[NSObject(NSObject) doesNotRecognizeSelector:] ()
it clearly says that you are calling a method that doesn't exists somewhere in your code when clicking on the table view cell. Try searching for warnings in viewDidLoad and viewWill/DidAppear methods of SendMessageViewController
A: Ok found my problem:
In my delegate is was doing this
MenuViewController *menuViewController = [[[MenuViewController alloc] init] autorelease];
UINavigationController *navController = [[[UINavigationController alloc] initWithRootViewController:menuViewController] autorelease];
So in the end I was calling methods on objects that where released. So I removed the autorelease and the problem was solved. Thanks for all that responded
A: Make sure you are calling the designated initialiser of UIViewController; since you aren't using a nib you should either call:
[[SendMessageViewController alloc] initWithNibName: nil bundle: nil];
Alternatively you could simply call this method in your view controller's init method.
If that doesn't solve it, set a symbolic breakpoint on NSException to get the code to stop at the point of problem and hopefully give you more info.
As an aside - any particular reason why you are creating a container view the size of the screen? You'll get one setup for free. You should just be able to add your UITableView as a sub view of the view controller's view, which would help simplify the code. Alternatively just use a UITableViewController.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to test if a connection to a Db is established successfully? I want to write a unit-test which asserts a connection string is valid so that a conenction is established to a SQL Db.
if I have :
string connectionString = GetCOnenctionString();
bool conenctionEstablished = false;
How can I set 'conenctionEstablished' variable's value as a result of a check to a Db with the 'connectionString' provided?
So that I can use it in an Assert.
A: You could try to connect in a try/catch then set conenctionEstablished based on whether the connection succeeds or not.
A: It is not going to be a "pure" unit test because your database is real but any way. I would use a try catch block and after opening the connection execute a "select 1" statement with ExecuteNonQuery(). At the end of the try block set the flag to true.
A: There are different states available, look at this:
private static void OpenSqlConnection(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}
A: there is an Enumeration called Connectionstate
so you can assert if the connection is closed, open connecting ,etc.
Assert.AreEqual(ConnectionState.Connecting, sqlcon.State);
A: We could rather check, if the connection is open or not, by using the following code:
using System.Data;
if (conn.State == ConnectionState.Open)
{
return true;
}
else
{
return false;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Oracle not available error After a long struggle of installing any Oracle XE on my windows XP I gave up and decided to create my database manually. The setup file provided by Oracle skips fast the Creation of Database services phase and completes. But OracleXEService does not get installed.
I've set evrything up, the directories, the service, Oracle_SID. All of them go normally. Then I connect to sqlplus, to an idle instance:
sqlplus /nolog
connect / as sysdba
then I type
spool create_script.log
and then finally when I enter
@C:\create_script.sql;
I get error stating Oracle is not available. I've checked the task manager, oracle.exe is there. I've restarted the OracleServiceXE. Nothing helps. Many say I should check if ORACLE_SID and ORACLE_HOME match. I wonder how should I know if they match or not?
A: You will need to post more information. What does your DB create script look like? Are you seeing any errors in the alert log or other logs on your server?
The ORACLE_HOME you specify for your service in your listener.ora file should match what your actual ORACLE_HOME path is set to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Solr : file entity processor and delta import I'm using solr 3.3 and i want to use delta import with file entity processor and tika entity processor. Full import works fine but the delta import parameter doesn't import the new documents.
Thanks
A: Changing following values in the data-config.xml will solved the problem
${dih.last_index_time} instead ${dataimporter.last_index_time}
${dih.delta.id} instead ${dataimporter.delta.id} .
A: Delta import works the same as Full import, except that it loads the data after the last build.
Delta import uses the same entities with the relationships, so there should not be any difference.
Do the records get picked up ? Are there any errors ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Detecting a small curve Suppose you have a contour made of lines, arcs, etc. It can be of any size from 1e-6 to 1e+6. How can I detect tiny useless curves inside it? At the moment we are taking the diagonal of the contour bounding rect * 1e-9 and for very distorted contours (where width is for example many times bigger of the height) it fails.
Does any scentific approach exist to eliminate this tiny useless curves?
Thanks.
A: By the phrasing of your question I assume your problem is using floating point for geometry. It is a common mistake. Use integers instead and it will become very clear at what point a curve is really a line. Or when two points are equal. You need to normalize all your data and work with a fixed precision from there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What are the best ways to show live data in Silverlight? I'm using a stream engine that updates my database every second with significant set of data.
A: I would suggest looking into using a WCF Duplex Service. I found several articles about implementing it searching for "Silverlight WCF Duplex Service." You should also consider bring back chunks of your data instead of the whole set each time if the data set is significantly large as you mentioned.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: is request.getRequestDispatcher.forward() asynchronous? When I called one servlet from another inside single if statement I was shocked, that even if my forwarding method was called the flow didnt stopped and next methods were invoked (I had to put them into else statement to stop this). How come? Does this mean that forward is asynchronous (if so, are there any more such a "tricky" methods)?
I've used "standard" forwarding: request.getRequestDispatcher(JSPFileName).forward(request, response);
A: No, it doesn't mean it's asynchronous. It just means that forward is a regular Java method, and that there's no reason for the rest of the code not to execute. It's just of your responsibility to avoid modifying the response after the request has been forwarded. But why wouldn't the following code log everything to the standard output?
System.out.println("About to forward the request to " + jspFileName + "...");
long t0 = System.currentTimeMillis();
request.getRequestDispatcher(jspFileName).forward(request, response);
long t1 = System.currentTimeMillis();
System.out.println("The forward took " + (t1 - t0) + " to complete");
A: No it's not asynchronous, but if you call the forward method in your service method and do not return, you can perform other operations (it's the same thread), but remember the forward remove all uncommitted output in the response added before it was called.
If you want to include the output of a servlet in your response use the include method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Embed Firefox/Gecko in WPF/C# I want to embed the current Gecko in my WPF-Project.
I know there is the possibility with the Winforms-Host and the Skybound-Gecko-Library.
But I do not use the standard wpf-theme for my application. It is another and the scrollbar of the control will not be styled. Furthermore, this is an old library which is designed for Firefox 3.
Which is the best library/strategy to use the current Gecko in WPF?
A: You should have a look at these options, they all use Chromium:
paid: (Awesomium-based)
*
*http://awesomium.com/ (is free for startups)
*http://wpfchromium4.codeplex.com/ (uses awesomium)
free: (Chrome Embedded Framework-based)
*
*https://github.com/chillitom/CefSharp (provides WinForms and WPF, but uses CEF1)
*https://bitbucket.org/xilium/xilium.cefglue/wiki/Home (uses CEF3, and therefore supports Chrome's multi-process model, flash plugin, and WebGL)
A: You can probably use WindowsFormsHost, tutorial here
https://nhabuiduc.wordpress.com/2014/09/18/geckofx-net-webbrowser-setup-and-features/
the interesting part is
WindowsFormsHost host = new WindowsFormsHost();
GeckoWebBrowser browser = new GeckoWebBrowser();
host.Child = browser;
gridWeb.Children.Add(host);
A: WebKit.Net is free: http://sourceforge.net/projects/webkitdotnet/
Their GitHub page seems to have been more recently updated: https://github.com/webkitdotnet
A: Here is my answer. As stated by Roman, Gecko is Winforms-based, not WPF-based and so has to be incorporated via the WindowsFormsHost.
*
*After creating the Visual Studio project, install the Gecko package via NuGet, using the command: Install-Package Geckofx45
*Make sure the WindowsFormsIntegration and System.Windows.Forms references have been added to your project.
*In your Configuration Manager, set your configuration to 32-bit, to get rid of the compiler warnings.
*Update MainWindow.xaml 'Grid' element to give it a name and the handler for the 'Loaded' event
<Grid
Name="GridWeb"
Loaded="Window_Loaded">
</Grid>
*Modify MainWindow.xaml.cs to incorporate the Gecko as well as make it navigate to a page on loading:
public MainWindow()
{
InitializeComponent();
Gecko.Xpcom.Initialize("Firefox");
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
WindowsFormsHost host = new WindowsFormsHost();
GeckoWebBrowser browser = new GeckoWebBrowser();
host.Child = browser;
GridWeb.Children.Add(host);
browser.Navigate("http://www.google.com");
}
I struggle using the SO code editor, so for more detailed explanations and screenshots, see this blog page.
A: This is an old question, but I came up with a pseudo-solution to add GeckoFX as a XAML tag such as:
<local:GeckoBrowser Width="400" Height="250" />
This can be accomplished by simply wrapping the whole thing in a UserControl such as:
XAML:
<UserControl x:Class="WpfApp1.Browser"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Border x:Name="border" Background="Black" Margin="0"></Border>
</UserControl>
C#:
public partial class Browser : UserControl
{
WindowsFormsHost host = new WindowsFormsHost();
GeckoWebBrowser browser = new GeckoWebBrowser();
public Browser()
{
InitializeComponent();
Xpcom.Initialize("Firefox");
browser.Navigate("http://www.google.com");
host.Child = browser;
border.Child = host;
}
}
Now, you can use the tag in WPF, in the same project where the UserControl exists.
I have been trying to get this to work as a Control in a library, so I can easily port it to any other project/solution, but it keeps giving me an error about mozglue.dll missing. I suspect this is due to the Xpcom.Initialize("Firefox") but I need to investigate further.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Why does this CSS cause Firefox to hang/crash? The following CSS background-size and gradient, when applied to large divs, causes Firefox to hang/crash. Rendering gradients can be pretty intensive, but does anyone know why Firefox flat out crashes while Webkit handles similar CSS without failing?
background-size: 4px 4px;
background-image: -moz-linear-gradient(135deg, rgba(255, 255, 255, .02) 25%, transparent 25%,
transparent 50%, rgba(255, 255, 255, .02) 50%, rgba(255, 255, 255, .02) 75%,
transparent 75%, transparent);
Looks like reducing the background-size causes Firefox to crash "harder," as I'm assuming this causes more gradients to be rendered.
Crashes on 6.0.2, 5.0.1, but renders very slowly on 3.6.22.
A: There is no crash for me using http://jsfiddle.net/C8dTT/2/ as test case in either Firefox 6 or Firefox 9.0a1, it simply hangs for a while but gets done eventually. There is clearly an inefficiency in calculating the gradient, it takes too long - and it doesn't help that you ask the browser to repeat that calculation for every 4x4 field of the webpage. Interestingly, when I stop execution in a debugger the code running belongs to the Intel graphics driver. There is also no issue if gfx.direct2d.disabled preference is set to false in Firefox. So the root cause is likely a bug in either Direct2D or the graphics driver - should still be worth filing a bug report at https://bugzilla.mozilla.org/ however, they will want to work around that pathological case.
Note that Firefox 3.6 doesn't have GPU acceleration which is why you don't see the hang there.
A: You're running into https://bugzilla.mozilla.org/show_bug.cgi?id=632324
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: no-scalable broken when hit inputbox in iphone web page I have disabled the touchstart and touchmove event to prevent the viewport to change. And also set 'width=device-width,user-scalable=no'. But when hit the inputbox, the viewport changed and the web page position changed.
How to disable the viewport changing when input something?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java Compile Error, cannot find symbol Getting the error "Cannot Fin Symbol", but I don't know what I am doing wrong.
import java.util.Scanner;
public class Exercise6_1{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberStudents = input.nextInt();
int[] studentScores = new int[numberStudents];
System.out.print("Enter " + numberStudents + " Scores: ");
for (int i = 0; i < numberStudents; i++);{
studentScores[i] = input.nextInt();
}
}
}
A: You have semicolon after the "for" cycle.
Should look like this:
for (int i = 0; i < numberStudents; i++) {
studentScores[i] = input.nextInt();
}
A: you have an ; after the for loop.
Correct impl :-
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of students: ");
int numberStudents = input.nextInt();
int[] studentScores = new int[numberStudents];
System.out.print("Enter " + numberStudents + " Scores: ");
for (int i = 0; i < numberStudents; i++)
{
studentScores[i] = input.nextInt();
}
}
}
A: The last semicolon in the line
for (int i = 0; i < numberStudents; i++);{
should be removed:
for (int i = 0; i < numberStudents; i++) {
A: for (int i = 0; i < numberStudents; i++);{
studentScores[i] = input.nextInt();
}
Here You have ended the for loop with a semi-colon , which results in the termination of the loop at that point . That's why it shows it can't find symbol i , As it is out of the scope of the for loop.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Doubt in Java interface implements interface Device
{
public void doIt();
}
public class Electronic implements Device
{
public void doIt()
{
}
}
abstract class Phone1 extends Electronic
{
}
abstract class Phone2 extends Electronic
{
public void doIt(int x)
{
}
}
class Phone3 extends Electronic implements Device
{
public void doStuff()
{
}
}
Can any one tell me why this compiles.. Because "Phone3" implements Device and it should have doIt() method but it does not have. But still this compiles. May i know Y?
A: Phone3 extends Electronic, and Electronic has the method doIt(), implementing the Device interface. The implementation of the doIt method is thus just inherited from the Electronic base class.
It makes sense if you make the example more realistic. Change Device to Ringable, with a ring method. Create a base class SimplePhone implementing Ringable, with an implementation of the ring method. And make a subclass of SimplePhone called BeautifulPinkPhone. The beautiful pink phone will be able to ring because it's just a simple phone with a pink color.
A: implements Device is redundant in class Phone3 definition. The class in inheriting the fact of implementing the Device interface from the Electronic class.
That is, every class extending Electronic is implementing Device also, and is also inheriting the implementation of doIt that Electronic provides. Every one of them can extend/provide a different implementation of doIt by overriding it.
A: It is because Phone3 extends Electronic and Electronic already implements doIt() method.
A: it works, because Electronic implements Device. have you tried compiling without interface implementation in main class?
A: Phone3 inherits it from the Electronic class.
A: Phone3 extends Electronic and inherits all it's methods. Since Electronic has a doIt() method it compiles.
A: Phone3 extends Electronic hence it inherits doIt() method
A:
If you see in a above code, Phone3 already implemented doIt() method
in a inheritance tree,i.e in a Electronic class, and if you wish to
call doIt() method in your Phone3 class it'll work fine such as.
class Phone3 extends Electronic implements Device
{
public void doStuff()
{
}
public static void main(String...args)
{
Phone3 p3=new Phone3();
p3.doIt();
}
}
A: Phone3 extends Electronic, which already implements doIt.
A: Cause Phone3 also extends Electronic which has a empty implementation for the doIt method.
So it does not need to have it, unless it needs to override the behaviour.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to add custom margins and control their shape using css? I am trying to style h1 using following image...
Currently my code as following...
h1{
background:#add2cb;
padding:15px 20px;
color:#387475;
font-size:16px;
font-weight:bold;
}
But i want yours help to add left and right bottom curve using css. I have tried lots of ways, please help me to rewrite css code to achieve this. thanks.
A: You should totally check out Harry Roberts version, the beauty is you won't be requiring any additional elements to pull it off.
http://csswizardry.com/2011/02/css-powered-ribbons-the-clean-way/
This method will include a few images, however because they're only for the curled under parts there will be less weight to download and will degrade better.
A: You cannot add curves like that with CSS alone, those will have to be a single image. If the H1's are all going to be the same size, then you can have an image of the bottom of that and then add this line to your h1 CSS
background: url("path/to.image") bottom center no-repeat;
I'm not sure if it is possible to make it work with H1's that are different sizes unless you want to use <div>s instead.
With 1`s you can do this:
HTML:
<div class="heading"><span>Text Goes Here</span><div>
CSS:
.heading { background: url("left-curve-image.jpg") left center no-repeat #add2cb;
padding:15px 20px;
color:#387475;
font-size:16px;
font-weight:bold; }
.heading span { background: url("right-curve-image.jpg") right center no-repeat #add2cb; }
Just please note that you will need snips of the left and right side of the curve from top to bottom
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the best way to write an int array (image data) to file I have a large int array containing image data in the format ARGB (alpha, R, G and B channels, 1 byte each). I want to save it to file in onPause() to be able to reload it when the app is restarted. What do you think is the best way to do that?
I found the following methods:
*
*Convert the int array to a byte array manually (see here) and then use a FileOutputStream to output the byte array.
*Wrap the array into a java.nio.IntBuffer and then write the object to file using java.io.ObjectOutputStream.writeObject().
*Write each element one at a time using java.io.ObjectOutputStream.writeInt().
All these methods seem quite wasteful so there is probably another, better way. Possibly even a way to use image compression to reduce the size of the file?
A: From my point of view you can also use android specific storages
*
*Use database/content provider for storing image data
*Use out Bundle in onSaveInstance method
If your still want to write to a file you can use following NIO based code:
static void writeIntArray(int[] array) throws IOException {
FileOutputStream fos = new FileOutputStream("out.file");
try {
ByteBuffer byteBuff = ByteBuffer.allocate((Integer.SIZE / Byte.SIZE) * array.length);
IntBuffer intBuff = byteBuff.asIntBuffer();
intBuff.put(array);
intBuff.flip();
FileChannel fc = fos.getChannel();
fc.write(byteBuff);
} finally {
fos.close();
}
}
A: None of those. Some of them don't even make sense.
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
then call dos.writeInt() as many times as necessary, then close dos. The buffer will take away most of the pain.
Or else create an IntBuffer and use FileChannel.write(), but I've never been able to figure out how that works in the absence of an IntBuffer.asByteBuffer() method. Or else create a ByteBuffer, take it as an IntBuffer via asIntBuffer(), put the data in, then adjust the ByteBuffer's length, which is another missing piece of the API, and again use FileChannel.write(ByteBuffer).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make a common id for more then one row i have a table in my database given like bellow
Requestid(primary key,identity) studentid reqid
1 1 bc1
2 1 bc1
3 2 bc2
I want to generate the same request id for student 1 if he is making more then one request.
I am using SQL server 2005 and Requested id is identity and student id will come when i submit my form but i want to generate reqid as automaticaly. It is same for the the student of same id and when next student submit it should change with the new id.
Plz hel me to solve it. Thanks in advance
A: If I understand what you want you could use a computed column to generate reqid.
create table StudentRequest
(
Requestid int identity primary key,
studentid int not null,
reqid as 'bc'+cast(studentid as varchar(10))
)
Test:
insert into StudentRequest (studentid) values (1)
insert into StudentRequest (studentid) values (1)
insert into StudentRequest (studentid) values (2)
select *
from StudentRequest
Result:
Requestid studentid reqid
----------- ----------- ------------
1 1 bc1
2 1 bc1
3 2 bc2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Test if an element is focused using Selenium Webdriver I'm really surprised I can't find references on the internet to testing for element focus using Selenium Webdriver.
I'm wanting to check when when a form submission is attempted with a mandatory field missed, focus is moved to the empty field. But I cannot see any way to do this using the WebDriver API.
I will be able to find the focused element using a JavascriptExecutor. But reading the FAQ makes me think there must be some way to perform the check using the driver itself.
Thanks for any help.
A: driver.switchTo().activeElement();
returns the currently focused element.
Makes sure you switch back after using
driver.switchTo().defaultContent();
Also if nothing is focused the body of the document is returned.
Take a look at this question as well.
In Selenium how do I find the "Current" object
A: driver.switchTo().activeElement() will return the currently focused WebElement. Equality is well defined for WebElement, so you can call element.equals(driver.switchTo().activeElement()).
Calling the slightly misleading named driver.switchTo().activeElement() does not in fact switch focus, neither does driver.findElement(), so you do not need to switchTo().defaultContent() after; in fact, doing so would probably blur the current element.
A: You can find the active element using selector 'dom=document.activeElement'. Then you can assert whether it's the element you want it to be focused or not.
A: The WebDriver is supposed to change focus when you use Driver.FindElement calls. So you're last element in the Driver context is active.
NOTE: This breaks for any elements injected dynamic (e.g. jQuery), so you'd need to go the script route then.
A: @danielwagner-hall The boolean bb = driver.switchTo().activeElement().equals(driver.findElement(By.id("widget_113_signup_username"))); will always pass but it doesn't prove that the element is brought into focus if the element is out of view.
NB: Unable to comment as not enough reputation points.
One way of approaching this could be to use webElement.getLocation().getX(); getY() methods and reference the coordinates on the page and verify its focus.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: celery get tasks count I am using python celery+rabbitmq. I can't find a way to get task count in some queue.
Some thing like this:
celery.queue('myqueue').count()
Is it posible to get tasks count from certaint queue?
One solution is to run external command from my python scrpit:
"rabbitmqctl list_queues -p my_vhost"
and parse results, is it good way to do this?
A: I suppose that using rabbitmqctl command is not good solution, especially on my ubuntu server, where rabbitmqctl can be executed only with root privileges.
By playing with pika objects I found working solution:
import pika
from django.conf import settings
def tasks_count(queue_name):
''' Connects to message queue using django settings and returns count of messages in queue with name queue_name. '''
credentials = pika.PlainCredentials(settings.BROKER_USER, settings.BROKER_PASSWORD)
parameters = pika.ConnectionParameters( credentials=credentials,
host=settings.BROKER_HOST,
port=settings.BROKER_PORT,
virtual_host=settings.BROKER_VHOST)
connection = pika.BlockingConnection(parameters=parameters)
channel = connection.channel()
queue = channel.queue_declare(queue=queue_name, durable=True)
message_count = queue.method.message_count
return message_count
I did not find documentation about inspecting the AMQP queue with pika, so I do not know about solution's correctness.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Twitter Bootstrap.js Tabs says "ReferenceError: Can't find variable: $" I am new to JS and find the whole paradigm quite confusing.
In trying to implement Twitter's Bootstrap.js library, I have tried to follow their instructions but have had absolutely no luck.
Basically, I want to use the tabs plugin. This is exactly my markup, and the JS console keeps saying: ReferenceError: Can't find variable: $
I gather that perhaps I am not loading jQuery here correctly, but... I don't know how I would do this any differently! Any assistance would be appreciated.
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://twitter.github.com/bootstrap/1.3.0/bootstrap-tabs.js"></script>
<![endif]-->
<!-- Le styles -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/1.3.0/bootstrap.min.css">
<style type="text/css">
body {
padding-top: 60px;
}
</style>
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="images/favicon.ico">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">
<div class="topbar">
<div class="topbar-inner">
<div class="container-fluid">
<a class="brand" href="#">Project Name</a>
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
<p class="pull-right">Logged in as <a href="#">username</a></p>
</div>
</div>
</div>
<div class="container-fluid">
<div class="content">
<ul class="tabs">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
<div class="pill-content">
<div class="active" id="home">Div 1</div>
<div id="profile">Div 2</div>
<div id="messages">Div 3</div>
<div id="settings">Div 4</div>
</ul>
<script>
$(function () {
$('.tabs').tabs()
})
</script>
</div>
</div>
</div>
A: you need to add jquery.js first
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://twitter.github.com/bootstrap/1.3.0/bootstrap-tabs.js"></script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to test Unicode "non-chars" (lsep, rsep etc.)? Is there an application or a utility for generating non-characters, such as U-2028 and U-2029 (line separators)?
A: My preferred method is to type into a browser address bar eg:
javascript:'A\u2028B\u2029C'
and then copy and paste them from the page.
If you really need to enter such characters a lot, you could potentially use MSKLC to create a keyboard layout that can type them directly. For example on my own keyboard layout I've got non-breaking-space, zero-width-space and half-space on shift and alt combinations with the space bar.
Note that browser support for displaying replacement glyphs for these particular characters may vary, so if you don't see them, try another browser. They are visible for me in Chrome (52.0.2743.116).
A: If you are with Windows, you don't need external tools: press alt, and + sign, and the hex code.
If you need \u2028, you press Alt and +, and 2028, the sign appears.
It depends on the code page you are using. Please refer to
https://en.wikipedia.org/wiki/Alt_code
and
https://en.wikipedia.org/wiki/Code_page
In my case, with my code page, I have ý when typing alt code 2028.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can a square root of a non-integer become an integer due to floating point rounding errors? In another unrelated Internet forum a question was asked on how to check if a square root of a given number is an integer. Now in and of itself that is a trivial homework question, but I started to wonder if the naïve approach is correct under all circumstances. That is, in pseudocode:
declare x, y as double
input x
y = sqrt(x)
if round(y) = y then
output "Is integer"
else
output "Isn't integer"
Is it possible to enter such an x, that x itself would not be an integer (or an integer which is not a square of another integer) but sqrt(x) would be and integer because of floating point errors?
A: Yes: when x is on the edge of Machine epsilon.
Consider x = 1.00...0001, where it is still representable in its binary form, not identical to 1.0. A square root of this number will give 1.0, yielding false poitive.
A: The square root of the next representable floating-point number above 1.0 (nextafter(1.0) in C) could plausibly evaluate to 1.0.
A: First off, if the numbers are so large that the precision does not extend down to the decimal point, then you'll only get integers, but they're not correct, so I suppose you don't care about that case.
Concerning exact results: This should be fairly easy to test if you have IEE754 floats. Just take a double that is a perfect integral square, increment or decrement its binary representation by one bit, and then check if the square root is an exact integer. The standard floating point operations are required to be exact to 0.5 units in last place, I believe, so it's possible that the integer is actually the correct nearest representable square root.
A: Of course:
double d = Math.Sqrt(4.000000000000001);
Console.WriteLine(d == 4);
Console.WriteLine(d == 2);
This results in (C#)
False
True
A: Feeding x as a float like 1+epsilon will of course work. But for a non-square integer it also works given the integer is large enough.
For example (c#)
ulong i = ulong.MaxValue; // 2^64-1, a non square integer.
double s = Math.Sqrt(i); // Very nearly 2^32
bool same = Math.Round(s) == s; // true, s is close enough to 2^32.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Fluent nHibernate QueryOver SQL 'CASE' equivalent Basically what I want to do is to write this piece of SQL:
SELECT
CASE
WHEN t.type = 'a' THEN
t.name
ELSE
t.otherName
END
as "Name"
FROM myTable t
in QueryOver
A: maybe there is some nicer syntax possible, but this should do
var result = session.QueryOver<MyEntity>()
.Select(Projections.Alias(
Projections.Conditional(Restrictions.Eq("type", 'a'),
Projections.Property(t => t.name),
Projections.Property(t => t.othername)),
"Name"
)
.List();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: CheckBoxList ASP.Net MVC 3 from database assumed that i have Roles table like this :
tb_role
RoleId Role_Name
1 SalesCreate
2 SalesEdit
3 AgentCreate
4 AgentEdit
i want to list role for Sales in checkbox (SalesCreate and SalesEdit, so its only have 2 checboxes). I made my tb_role using aspnet configuration, so it doesn't use entities.
here my Controller:
RegisterModel account = new RegisterModel();
account.Roles = new MultiSelectList(Roles.GetAllRoles());
and my View:
<td><select id="Roles" name="Roles">
<option>Sales</option>
<option>Agent</option>
</select>
</td>
@foreach (var item in Model.Roles)
{
<label for="@item.Value">
<input type="checkbox" id="@item.Value" name="RolesSelected" value="@item.Value" @(item.Selected ? "checked" : "") />@item.Text</label>
}
when i run my project, my checkbox list all of the roles in tb_role. I want that if I choose Sales, my checkbox list all the Roles for Sales (SalesCreate and SalesEdit). how to do that ?
thanks a lot
A: Couple of ways to do this. One way is this:
Surround the <select> with a <form> tag and do a submit on change.
in your controller:
public ActionResult Index(..., string role)
{
//... rest of your code
RegisterModel account = new RegisterModel();
account.Roles = new MultiSelectList(Roles.GetAllRoles().Where(w => w.StartsWith(role));
//... rest of your code
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Encrypted SQL database? I'm looking for encrypted SQL database, I'm going to install it on client's machines, and I don't want client to database directly.
I know this is not 100% secure, and I'm not interested in SQL Server, SQLite or Oracle.
If you know any solutions of this kind please let me know.
Thanks.
A: One more idea: You can use any kind of DB and encrypt/decrypt data upon saving/retrieving. This way, you are not required to investigate databases with encryption support. You will be handling this operation to your programming language, most common languages have the capability to deal with encryption and decryotion.
A: Given your requirements, I suggest you use MySQL. It supports both Windows and Linux. It's free and open source and has concurrency support. Also it has cryptography support.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: int(11) vs. int(anything else) I'm new to web programming and doing different tutorials that I can find on the net.
I did my research and found out that in int(11), 11 is the maximum display width for integers and it's the default value if unless the integer is UNSIGNED (in this case it's 10).
When I see something like this:
id INT(11) not null AUTO_INCREMENT
I have no questions. But why do I see different things in different tutorials? For examlpe, in some, it says,
id INT(10) not null AUTO_INCREMENT
And even
id INT(4) not null AUTO_INCREMENT
What are the authors of those tuts trying to achieve? None of them seem to bother to give an explanation what 10 or 4 means.
Alright, they're obviously reducing the display width, but why? What's wrong with the default width of 11? Why would they want to change it? Or are there any other reasons I don't know of?
Thanks.
A: The x in INT(x) has nothing to do with space requirements or any other performance issues, it's really just the display width. Generally setting the display widths to a reasonable value is mostly useful with the UNSIGNED ZEROFILL option.
//INT(4) UNSIGNED ZEROFILL
0001
0002
...
0099
...
0999
...
9999
...
10000
//INT(2) UNSIGNED ZEROFILL
01
02
...
09
...
99
...
100
Without the UNSIGNED ZEROFILL option the value will be left-padded with spaces to the appropriate display width.
//INT(4)
1
2
...
99
...
999
...
9999
...
10000
//INT(2)
1
2
...
9
...
99
...
100
A: From the docs:
"This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left-padding them with spaces. (That is, this width is present in the metadata returned with result sets. Whether it is used or not is up to the application.)" That is, int(4) is politely asking that 123 be displayed as " 123". Don't know how many things actually pay attention or why they'd bother in a tutorial.
"The display width does not constrain the range of values that can be stored in the column. Nor does it prevent values wider than the column display width from being displayed correctly." So if you shove 123456 into an int(4) it will still be 123456.
Nothing to do with disk space or performance, just a hint to the application retrieving the data that it would like to be displayed with at least N digits.
The related ZEROFILL option can be used in conjunction to actually pad out the returned data. So 123 in an int(4) ZEROFILL is returned as 0123.
A: It's not performance increase neither difference in maximum allowed size.
It's only used when ZEROFILL is applied on that column. (See: http://alexander.kirk.at/2007/08/24/what-does-size-in-intsize-of-mysql-mean/)
A: The number is just a representational option called "display width". It may be used by some applications to pad the field when displaying numeric datatypes.
The int size is neither bits nor bytes. It's just the display width, that is used when the field has ZEROFILL specified.
This blog explains the meaning of int(size) in MySQL.
A: Yes it specifies the display width, and this comes into play only when ZEROFILL is specified. So at that time it can pad the field value with the required number of zeros.
A: I agree that the MySQL manual is a little vague on the length/display width of integers. You might think that this limits the value you can store in the column to the number of digits but the valid range of the colomn doesnt change, wether you set it to 1 or 11.
What it really does is determine the display width of the column's value. The only case this is usefull is if you use ZEROFILL to pad your values with zero's.
So basically there is no real difference between INT(1) and INT(11) in terms of what you can store in the column, the only case when it becomes relevant is when you want to ZEROFILL your values.
More info:
http://alexander.kirk.at/2007/08/24/what-does-size-in-intsize-of-mysql-mean/
http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html
A: Copying from this blog article:
MySQL has a little know feature for numerical types known as zerofill. This feature effects the display size of numerical types. Unlike the string types the number inside the parentheses is not the storage size in characters for the type. For numerical types the type name itself determines storage size.
The integer type it’s the padding size for zerofill.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "59"
}
|
Q: Overwrite one css rule with another? A question about CSS.
I am working on some dated code. This code has its own css rules which are linked to some 'css manager'... now I want to use jQuery UI with its nice and cute dialogues etc.
Now my question is:
I have a css rule say...
#menu-bar{something}
jQuery UI is using rules like:
.ui-dialog-titlebar{something2}
Can I (without modifying jQueryUI stylesheets) do something akin to :
.ui-dialog-titlebar = #menu-bar?
So .ui-dialog-titlebar will be overwritten with {something} from #menu-bar?
Thanks in advance.
PS. Let me add that I can not simply do
.ui-dialog-titlebar {something}
becasue {something} is changing depending on the 'style manager' used.
A: I don't think a css rule can inherit from another one, definitely not CSS 2 or CSS 3. What you can do is to add multiple css classes to the elements. In your case, you could simply add the ID to the dialog element:
<div id="menu-bar" title="dialog">...</div>
or add it programmically:
$('.dialog').dialog(...).attr('id', 'menu-bar');
Note though, #menu-bar should really be a class rather than an ID, if you want multiple elements to have the style.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there anyway I can use a BroadcastReceiver to catch DownloadManager.ACTION_DOWNLOAD_COMPLETE in Android? I am working on an android application which is related to security. It is about scanning an application after it is downloaded from android market.
Is there anyway I can use a BroadcastReceiver to catch DownloadManager.ACTION_DOWNLOAD_COMPLETE?
I checked a couple of article but at time now the api's are hidden. Is there anyway I can use reflection method or something like to do this?
A: look at this example
you need to use downloadManager class which is available in api 9 or above which calls a broadcast receiver on completion.
http://www.vogella.de/blog/2011/06/14/android-downloadmanager-example/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# CSS Asp: Menu problem I have a menu with a submenu.
The following is the code for the menu on the site master
<div id="menu">
<h2>
Dashboard</h2>
<asp:Menu ID="NavigationMenu" dir="rtl" runat="server" CssClass="menu" EnableViewState="false"
Orientation="Vertical">
<Items>
<asp:MenuItem NavigateUrl="~/Vi.aspx" Text="View "/>
<asp:MenuItem NavigateUrl="~/I.aspx" Text="Import"/>
<asp:MenuItem NavigateUrl="~/S.aspx" Text="Insert "/>
<asp:MenuItem NavigateUrl="~/R.aspx" Text="Reports"/>
<asp:MenuItem NavigateUrl="~/Re.aspx" Text="Re" />
<asp:MenuItem Text="Maintenance">
<asp:MenuItem NavigateUrl="~/F.aspx" Text="For" />
<asp:MenuItem NavigateUrl="~/P.aspx" Text="Prod" />
<asp:MenuItem NavigateUrl="~/T.aspx" Text="T" />
<asp:MenuItem NavigateUrl="~/U.aspx" Text="U" />
<asp:MenuItem NavigateUrl="~/C.aspx" Text="C" />
</asp:MenuItem> </Items>
</asp:Menu>
</div>
The problem is that when i open the submenu it is overlapping the gridview on the page and it not a matter of z-index the background seems to be transparent but i dont want it transparent
A: There are some issues with Z Index not being handled as planned always when working with master pages.. Where messing around with a similar problem a while back and this forum post helped me: http://forums.asp.net/t/1038006.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Save data of custom metabox in Wordpress I added a meta-box to the edit link page & I can't save the data whatever I put in the field. How can I only update the meta-box without saving the data in the database? Here is my code:
// backwards compatible
add_action( 'admin_init', 'blc_add_custom_link_box', 1 );
/* Do something with the data entered */
add_action( 'save_link', 'blc_save_linkdata' );
/* Adds a box to the main column on the Post and Page edit screens */
function blc_add_custom_link_box() {
add_meta_box(
'backlinkdiv',
'Backlink URL',
'blc_backlink_url_input',
'link',
'normal',
'high'
);
}
/* Prints the box content */
function blc_backlink_url_input( $post ) {
// Use nonce for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'blc_noncename' );
// The actual fields for data entry
echo '<input type="text" id="backlink-url" name="backlink_url" value="put your backlink here" size="60" />';
#echo "<p> _e('Example: <code>http://Example.org/Linkpage</code> — don’t forget the <code>http://</code>')</p>";
}
How can I save or update the data of the input field of metabox? Only the data should be updated in the metabox. It should not save in database by any type of custom field.
A: I think it actually would be a good idea to save as a custom field, only one that doesn't show up in the custom field box. You can accomplish the latter by adding a "_" at the beginning of the custom field's name (i.e. "_my_custom_field" instead of "my_custom_field".
Here's a sample function to save your meta box data. I changed the names to match the code you have above.
:
<?php
function blc_save_postdata($post_id){
// Verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['blc_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}
// Verify if this is an auto save routine. If it is our form has not been submitted, so we dont want
// to do anything
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
// Check permissions to edit pages and/or posts
if ( 'page' == $_POST['post_type'] || 'post' == $_POST['post_type']) {
if ( !current_user_can( 'edit_page', $post_id ) || !current_user_can( 'edit_post', $post_id ))
return $post_id;
}
// OK, we're authenticated: we need to find and save the data
$blc = $_POST['backlink_url'];
// save data in INVISIBLE custom field (note the "_" prefixing the custom fields' name
update_post_meta($post_id, '_backlink_url', $blc);
}
//On post save, save plugin's data
add_action('save_post', array($this, 'blc_save_postdata'));
?>
And that should be it. I used this page as a reference: http://codex.wordpress.org/Function_Reference/add_meta_box
A: Hook the action save_post - it receives saved post ID and allows you to update the post the way you need when submitting post editor page. Don't forget that this action will be called for EVERY post saved - you need to only handle posts having your custom meta box.
A: you must disable this code
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
what it does is that it blocks your code below cause it detects that your doing some auto save on it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Limited friend list in Open Graph I received a question from one of the users of my application, and I am doubting if this is a programming bug on our end. When requesting the friend list of the user, the API only returned 480 out of 580 friends. Is the friend list limited to this number? Or is it likely that the other 100 users have very strict privacy settings regarding external applications? If none of these two questions is true there must be a bug in my coding, but before I dive in I thought I'd ask.
A: Use ?limit=5000 or a higher amount because the default limit is 500. Otherwise, make multiple calls using the next and prev navigation links included in the json response. The reason you are getting 480 instead of 500 is probably because users have changed their privacy settings or opted out of Facebook application platform entirely. Their query first gets 500 friends, and then removes the people that have opted out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: IE6 compatibility. Page works fine everywhere but in IE6 I have pretty much the same markup for all pages of the website, and most of them are done via php includes (in other words, the largest chunk of the code is the same throughout all pages).
All pages but one (dynamically generated) work as intended in all browsers including ie6.
The one page (for example, http://mincovlaw.com/doc/euro-excellence) works as intended in FF3.6, Chrome, Safari (including on iPhone) and IE7.
In IE6, it seems that there is some problem with the <DIV>s. I thought it had to do with the floating menu, but even if I remove the code completely, the DIVs are still not displayed correctly.
If you click on About or pretty much any other page of the website in IE6, the same structure of the DIVs works fine.
I do want the website to work in IE6. Please help me figure out why it behaves like this on this page.
To make things clearer, the three problems I am referring to in IE6 are:
*
*The floating Bookmarks menu ends up in the right hand corner of the "paper", not in the right hand corner of the window, as it should.
*Consequently, when I drag the bookmarks menu, the coordinates are all screwed up.
*If you compare the page to, for example, Services in IE6, you will notice that on the Services page, the paper width is the same in the middle and on top and on the bottom, whereas it is slightly wider on the court decision page that I gave you the link for.
PS I know the code has many problems with validation, most of which have to do with ul's not having corresponding li's. This is currently by design.
IMPORTANT UPDATE!!! I have just discovered something. It seems that the problem #3 somehow is related to two lines in the css, namely:
text-align:justify;
for p and .indented
Can someone tell me why this is happening?
A: You should use the HTML validation service to validate your page.
There are plenty of things that the validation complains about. Some things should not be a problem, like obsolete tags like center and u, and problems when the service tries to validate the Javascript code, but there are some actual errors in the code, like some ul tags that are not closed, and ul tags that contain p elements instead of li elements.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Disable dates in a jquery datepicker dynamically var birthDate;
$(function() {
var currentDate = new Date();
$("#BirthDate").datepicker({
dateFormat: "mm/dd/yy",
showOn: "button",
buttonImage: "../Images/cal.gif",
buttonImageOnly: true,
changeMonth: true,
changeYear: true,
maxDate: currentDate,
yearRange: "-90:+10",
onSelect: function(dateText, inst) { birthDate = dateText;}
});
});
$(function() {
var currentDate = new Date();
$("#MaritalStatusDate").datepicker({
dateFormat: "mm/dd/yy",
showOn: "button",
buttonImage: "../Images/cal.gif",
buttonImageOnly: true,
changeMonth: true,
changeYear: true,
minDate: birthDate,
maxDate: currentDate,
yearRange: "-90:+10"
});
});
In the above code I am trying to disable $("#MaritalStatusDate") dates based on the date selected in $("#BirthDate"). I am using the onSelect event in BirthDate to identify the selected date and I'm storing the value in a variable which is globally declared. Using the variable I have set the minDate in $("#MaritalStatusDate"). But the dates are not getting disabled based on minDate value. Do I need to change the date format while assigning the value to the variable? Can anyone please help me in doing this?
A: You can simply set the minDate for $('#MaritalStatusDate') in onSelect event.
$("#BirthDate").datepicker({
...
onSelect: function(dateText, inst) {
$('#MaritalStatusDate').datepicker('option', 'minDate', dateText);
}
});
See this in action: http://jsfiddle.net/william/2q7TN/.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Customizing the edit page title in ActiveAdmin I am trying to change the page title to be the name of the item you are actually editing when you are on the edit page. I read in the active admin docs that you should use @page_title. The problem is I don't know where to put this for it to work for the edit page.
A: This will work:
controller do
def new
@page_title = 'new title'
super
end
def edit
@page_title = 'edit title'
super
end
end
A: I posted this in the active admin google group and they are looking to add this ability in to the next update. If they end up adding it i will post some info here on how it is accomplished.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Ajax request return value I have an Ajax call to my controller action looks like this:
var m = $.ajax({
mtype: "GET",
url: '@Url.Action("GetBrandForValidation")',
data: { actionparameter: value },
async: false,
cache: false
});
As u can see i return actionparametter to my controller and controller have to return either true or false which has to be my "m" value, but i cant get it to work. Any ideas?
Controller Code:
public virtual JsonResult GetBrandForValidation(string actionparameter)
{
var vendorId = _service.GetVendorIdByUsername(GetUserName());
bool k;
var brands = _service.GetBrandsByVendor(vendorId);
var brand = new BrandsViewModel();
brand.BrandName = "Opret ny Brand...";
brands.Add(brand);
foreach (var brandsViewModel in brands)
{
if (brandsViewModel.BrandName == "Intet")
{
brandsViewModel.BrandName = "";
}
}
var list = brands.Select(s => s.BrandName);
if (list.Contains(actionparameter))
{
k = true;
}
else
k = false;
return Json(k,JsonRequestBehavior.AllowGet);
}
And full function code :
var checkBrands = function(value, colname) {
var m = $.ajax({
mtype: "GET",
url: '@Url.Action("GetBrandForValidation")',
data: { actionparameter: value },
async: false,
cache: false
});
if (m == true)
return [true, ""];
else
return [false, "Brand eksistere ikke"];
};
Im quite new and very awfull at javascript, so dont judge hard
A: Is the ajax call being made in JavaScript? If so, mtype should be type.
A: var checkBrands = function(value, colname) {
$.ajax({
mtype: "GET",
url: '@Url.Action("GetBrandForValidation")',
data: { actionparameter: value },
async: false,
cache: false,
success: function(data){
if(data == 'm'){
//do something
}else{
//do something
}
}
});
};
A: SOLVED
var checkBrands = function (value, colname) {
var m = $.ajax({
mtype: "type",
url: '@Url.Action("GetBrandForValidation")',
async: false,
cache: false,
data: { actionparameter: value }
}).responseText;
if (m == 'true'){
return [true, ""];
}
else return [false, "Brand eksistere ikke"];
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to remove special characters from a string? I want to remove special characters like:
- + ^ . : ,
from an String using Java.
A: This will replace all the characters except alphanumeric
replaceAll("[^A-Za-z0-9]","");
A: That depends on what you define as special characters, but try replaceAll(...):
String result = yourString.replaceAll("[-+.^:,]","");
Note that the ^ character must not be the first one in the list, since you'd then either have to escape it or it would mean "any but these characters".
Another note: the - character needs to be the first or last one on the list, otherwise you'd have to escape it or it would define a range ( e.g. :-, would mean "all characters in the range : to ,).
So, in order to keep consistency and not depend on character positioning, you might want to escape all those characters that have a special meaning in regular expressions (the following list is not complete, so be aware of other characters like (, {, $ etc.):
String result = yourString.replaceAll("[\\-\\+\\.\\^:,]","");
If you want to get rid of all punctuation and symbols, try this regex: \p{P}\p{S} (keep in mind that in Java strings you'd have to escape back slashes: "\\p{P}\\p{S}").
A third way could be something like this, if you can exactly define what should be left in your string:
String result = yourString.replaceAll("[^\\w\\s]","");
This means: replace everything that is not a word character (a-z in any case, 0-9 or _) or whitespace.
Edit: please note that there are a couple of other patterns that might prove helpful. However, I can't explain them all, so have a look at the reference section of regular-expressions.info.
Here's less restrictive alternative to the "define allowed characters" approach, as suggested by Ray:
String result = yourString.replaceAll("[^\\p{L}\\p{Z}]","");
The regex matches everything that is not a letter in any language and not a separator (whitespace, linebreak etc.). Note that you can't use [\P{L}\P{Z}] (upper case P means not having that property), since that would mean "everything that is not a letter or not whitespace", which almost matches everything, since letters are not whitespace and vice versa.
Additional information on Unicode
Some unicode characters seem to cause problems due to different possible ways to encode them (as a single code point or a combination of code points). Please refer to regular-expressions.info for more information.
A: Use the String.replaceAll() method in Java.
replaceAll should be good enough for your problem.
A: As described here
http://developer.android.com/reference/java/util/regex/Pattern.html
Patterns are compiled regular expressions. In many cases, convenience methods such as String.matches, String.replaceAll and String.split will be preferable, but if you need to do a lot of work with the same regular expression, it may be more efficient to compile it once and reuse it. The Pattern class and its companion, Matcher, also offer more functionality than the small amount exposed by String.
public class RegularExpressionTest {
public static void main(String[] args) {
System.out.println("String is = "+getOnlyStrings("!&(*^*(^(+one(&(^()(*)(*&^%$#@!#$%^&*()("));
System.out.println("Number is = "+getOnlyDigits("&(*^*(^(+91-&*9hi-639-0097(&(^("));
}
public static String getOnlyDigits(String s) {
Pattern pattern = Pattern.compile("[^0-9]");
Matcher matcher = pattern.matcher(s);
String number = matcher.replaceAll("");
return number;
}
public static String getOnlyStrings(String s) {
Pattern pattern = Pattern.compile("[^a-z A-Z]");
Matcher matcher = pattern.matcher(s);
String number = matcher.replaceAll("");
return number;
}
}
Result
String is = one
Number is = 9196390097
A: Try replaceAll() method of the String class.
BTW here is the method, return type and parameters.
public String replaceAll(String regex,
String replacement)
Example:
String str = "Hello +-^ my + - friends ^ ^^-- ^^^ +!";
str = str.replaceAll("[-+^]*", "");
It should remove all the {'^', '+', '-'} chars that you wanted to remove!
A: To Remove Special character
String t2 = "!@#$%^&*()-';,./?><+abdd";
t2 = t2.replaceAll("\\W+","");
Output will be : abdd.
This works perfectly.
A: You can remove single char as follows:
String str="+919595354336";
String result = str.replaceAll("\\\\+","");
System.out.println(result);
OUTPUT:
919595354336
A: If you just want to do a literal replace in java, use Pattern.quote(string) to escape any string to a literal.
myString.replaceAll(Pattern.quote(matchingStr), replacementStr)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "117"
}
|
Q: In JavaScript, manually controlling order of event listeners Assuming that FORM contains INPUT, have the following listeners:
JavaScript
function formFirst(e) { ... }
function formLast(e) { ... }
function inputFirst(e) { ... }
function inputLast(e) { ... }
function middle(e) { ... }
document.getElementById('form').addEventListener('change',formFirst,true);
document.getElementById('form').addEventListener('change',formLast,false);
document.getElementById('input').addEventListener('change',inputFirst,true);
document.getElementById('input').addEventListener('change',inputLast,false);
Desired order of firing
formFirst() // normal - outer element, useCapture = true
inputFirst() // normal - triggering element, declared first
middle() // -- how to do this?
inputLast() // normal - triggering element, declared second
formLast() // normal - outer element, useCapture = false
Nature of problem and attempted solutions
Own code at FORM level, formFirst, formLast and middle, but have no access to INPUT code, inputFirst and inputLast - although could add own listeners on the INPUT.
Attempt 1 modify formFirst() to create and dispatch a new change Event (would be ignored within formFirst) that would call inputFirst(), but have no way of stopping propagation to prevent inputLast() being called subsequently.
Attempt 2 add middle added as listener to INPUT, but cannot guarantee firing order of two listeners of same type and same useCapture.
Premise of Attempt 2 is incorrect - firing order is determined by declaration order within the target Element.
Here are the rules
*
*non-target Element triggers with useCapture=false, starting at the outermost Element and working toward the target Element
a) if more than one useCapture=true triggers for same element, then order of declaration.
*at target Element, order of declaration, regardless of useCapture
*non-target Element triggers with useCapture=false, starting at the innermost Element and working away from the target Element
a) if more than one useCapture=false triggers for same Element, then order of declaration.
A: I think that this answers just your question. feel free to comment\contact me for more info.
----- edit ------
OK, I just played with it a little as promised, and I found a very simple solution:
<script type="text/javascript">
function formFirst(e) { alert(1); }
function formLast(e) { alert(5); }
function inputFirst(e) { alert(2); }
function inputLast(e) { alert(4); }
function middle(e) { alert(3); }
function init(){
document.getElementById('form').addEventListener('change',formFirst,true);
document.getElementById('form').addEventListener('change',formLast,false);
document.getElementById('input').addEventListener('change',inputFirst,true);
document.getElementById('input').addEventListener('change',middle,true);
/*** alternative to last tow lines
document.getElementById('input').addEventListener('change',function(){inputFirst();middle();},true);
**/
document.getElementById('input').addEventListener('change',inputLast,false);
}
</script>
<body onload="init();">
<form id="form">
<input type="text" id="input" /> <br />
</form>
</body>
notice:
*
*I put the addEventListener part into an init function, so I can call it after the page is loaded and the element are already exist.
*I have run this just on chrome. So I don't want to guarantee you things about other browsers.
*An alternative is writing the event handling on your own. here is an example for that. relaying on this article.
<script type="text/javascript">
function formFirst(e) { alert(1); }
function formLast(e) { alert(5); }
function inputFirst(e) { alert(2); }
function inputLast(e) { alert(4); }
function middle(e) { alert(3); }
function init(){
//create event
myHandler = new Event();
//add handler
myHandler.addHandler(formFirst);
myHandler.addHandler(inputFirst);
myHandler.addHandler(middle);
myHandler.addHandler(inputLast);
myHandler.addHandler(formLast);
//regiser one listener on some object
document.getElementById('input').addEventListener('change',function(){myHandler.execute();},true);
}
function Event(){
this.eventHandlers = new Array();
}
Event.prototype.addHandler = function(eventHandler){
this.eventHandlers.push(eventHandler);
}
Event.prototype.execute = function(){
for(var i = 0; i < this.eventHandlers.length; i++){
this.eventHandlers[i]();
}
}
</script>
<body onload="init();">
<form id="form">
<input type="text" id="input" /> <br />
</form>
</body>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: PDF text selection on iOS I'm looking for ways to implement text selection over a parsed PDF in iOS. I already have the positions of all the glyphs by using the Quartz PDF parsing functions, but I don't know of a good way to implement the selection of the text without writing the selection logic and view from scratch (And display it either in the view displaying the pdf or in some transparent overlay view).
The experience should be similar to selecting text in a UITextField or UIWebView (for example).
Existing 3rd party solutions which I could integrate would be best.
A: Found the Omni framework, which implements a similar selection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How do backup applications detect renames? I recently noticed that SyncToy (by MS) can detect renamed and moved files.
How do they do that? Is it only an elaborate guessing game based on file properties (last modification date, creation date, and file size)?
A: One way to catch file renames, deletes and other is to use FileSystemWatcher class (using dotnet framework).
If you develop an application (or a service) you can monitor file system changes and execute a custom action (with your code, so you can do anything you need).
You can even set which directory monitor and if you want subdirs too.
Problems can arise with permissions on folders and files, but this is not part of your question :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apache Sling - OSGI framework exception when starting in Windows I received the following error message when starting Sling on Windows with Java 1.7 (see below). I'm using Sling 6 (http://www.apache.org/dyn/closer.cgi/sling/org.apache.sling.launchpad-6-standalone.jar). Any idea what could be wrong?
Last time I tried using the same Sling version on Mac OSX and it worked perfectly.
Failed to Start OSGi framework
org.osgi.framework.BundleException: Uncaught Instantiation Issue:
java.lang.ArrayIndexOutOfBoundsException: -1
at
org.apache.sling.launchpad.base.impl.Sling.<init>(Sling.java:245)
at
org.apache.sling.launchpad.base.app.MainDelegate$1.<init>(MainDelegate.java:159)
at
org.apache.sling.launchpad.base.app.MainDelegate.start(MainDelegate.java:159)
at org.apache.sling.launchpad.app.Main.startSling(Main.java:244)
at org.apache.sling.launchpad.app.Main.<init>(Main.java:107)
at org.apache.sling.launchpad.app.Main.main(Main.java:56)
Caused by: java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at
org.apache.felix.framework.BundleImpl.getCurrentModule(BundleImpl.java:1046)
at
org.apache.felix.framework.BundleImpl.getSymbolicName(BundleImpl.java:863)
at
org.apache.sling.launchpad.base.impl.SlingFelix.getSymbolicName(SlingFelix.java:32)
at org.apache.felix.framework.Felix.toString(Felix.java:1012)
at org.apache.felix.framework.Logger.doLog(Logger.java:128)
at org.apache.felix.framework.Logger._log(Logger.java:181)
at org.apache.felix.framework.Logger.log(Logger.java:114)
at
org.apache.felix.framework.ExtensionManager.<init>(ExtensionManager.java:201)
at org.apache.felix.framework.Felix.<init>(Felix.java:374)
at
org.apache.sling.launchpad.base.impl.SlingFelix.<init>(SlingFelix.java:39)
at
org.apache.sling.launchpad.base.impl.Sling.<init>(Sling.java:235)
A: I had exactly the same error when using java 1.7. After switching to 1.6 everything seems to be fine. You check your java version by typing java -version in the terminal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Bluetooth on Android 2.2 : socket doesn't receive "connection canceled" I'm in process of writing Android 2.2 application with BT support. Two BT devices need to exchange messages.
The problem I encountered happens when one of devices (server) crashes/switches off or somehow stops connection. It's socket is disappeared and another participant (client) simply doesn't know it should attempt reconnect.
When the first (crashed) participant raises again, the client has no idea it should reconnect and continues to send messages.
The server is filled with errors of BT stack like:
E/BTL-IFS_WRAPPER (11222): wrp_find_wsock: wrp_find_wsock invalid hdl -1.
I understand the server's BT discovers someone send messages to already closed socket.
So the basic question is how to put client in reconnect mode when the server is crashed?
I see only one possibility to utilize two way "keep alive" packets every few seconds and drop the server to the listener mode and the client to the connecting mode.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Session destroy In my working platform i endedup with a session_destroy problem
function logout()
{
$_SESSION['id'] = '';
session_destroy();
}
Here i unset the session id variable with a null value and uses the session_destroy() function to destroy the session.
But the problem is that after logged out from my account, when i press the back button of the browser it shows the status as logged in. Even i can browse through the profile and links of my account.
Thank you
A: you must unset session as well as destroy session to remove it completely from your system.
you can do it with php functions..
session_unset(); or you can use unset($_SESSION);
session_destroy();
A: it think you should try using session_unset()
In order to kill the session altogether, like to log the user out, the session id must also be unset.
If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that
<?php
session_start();
$sessionName = session_name();
$sessionCookie = session_get_cookie_params();
session_unset();
session_destroy();
setcookie($sessionName, false, $sessionCookie['lifetime'], $sessionCookie['path'], $sessionCookie['domain'], $sessionCookie['secure']);
?>
A: Try this:
unset($_SESSION);
session_destroy();
session_regenerate_id();
A: Instead of rolling your own session code and possibly missing something, try using Zend_Session:
http://framework.zend.com/manual/en/zend.session.html
The constructor of Zend_Session_Namespace will automatically call session_start(), and likewise the Zend_Session::destroy() method will clean everything up in a logout script. Most of the work has already been done for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do you compile CoffeeScript in a Jakefile? I would like to create a Jakefile which compiles some CoffeeScripts to install a NodeJS application.
How do you do that?
I tried with:
https://gist.github.com/1241827
but it's a weak approach, definitely not classy.
Any hints?
A: Approx snippet I have used:
var fs = require('fs')
var coffee = require('coffee-script')
// If you'd like to see compiled code..
// console.log(coffee.compile(fs.readFileSync('coffee.coffee')))
// ..otherwise
fs.writeFileSync('output.js', coffee.compile(fs.readFileSync('input.coffee')))
..assumes you have the coffee-script node module installed, of course.
Translated from this Cakefile of mine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Why would real_connect return null? For some weird reason, the following code is returning null, while the manual states it should either return true or false. There is also no information in the mysqli object.
Code
// Initialize MySQLi
$this->mysqli = new mysqli();
// Connect to the server
var_dump($this->mysqli);
var_dump($this->mysqli->real_connect($host, $username, $password, $database));
var_dump($this->mysqli);
Output
object(mysqli)#2 (17) { ["affected_rows"]=> NULL ["client_info"]=> NULL ["client_version"]=> int(50141) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> NULL ["error"]=> NULL ["field_count"]=> NULL ["host_info"]=> NULL ["info"]=> NULL ["insert_id"]=> NULL ["server_info"]=> NULL ["server_version"]=> NULL ["sqlstate"]=> NULL ["protocol_version"]=> NULL ["thread_id"]=> NULL ["warning_count"]=> NULL }
NULL
object(mysqli)#2 (17) { ["affected_rows"]=> NULL ["client_info"]=> NULL ["client_version"]=> int(50141) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> NULL ["error"]=> NULL ["field_count"]=> NULL ["host_info"]=> NULL ["info"]=> NULL ["insert_id"]=> NULL ["server_info"]=> NULL ["server_version"]=> NULL ["sqlstate"]=> NULL ["protocol_version"]=> NULL ["thread_id"]=> NULL ["warning_count"]=> NULL }
A: You are not using it correctly.
You need to create the object using mysqli_init().
Or you put the connection info in the constructor and don't call real_connect.
A: I wonder what the context is for your code?
I just worked on a project where I set this in a config.php file..
<?php
$h='localhost';$u='username';$pw='PW';$db='test';
$sqli = new mysqli($h,$u,$pw,$db); ?>
then in a functions file this...
<?php
include_once 'include/config.php';
class User {
public function __construct($sqli) {
$this->sqli=$sqli;
} //etc.
} ?>
The connection works well and you call your connection within
Class User functions with $this->sqli -> query("SELECT... for example.
Pass the connection when you create a user ... $user = new User($sqli);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Insert Select Based on IF Condition on a Table Variable I have declared one Table Variable @OpeningTable. I want to insert the some values based on some conditions using Insert Select. I have written one statement which is given below:
DECLARE @OpeningTable TABLE
(
ItemID INT, OpeningBalance DECIMAL(15,3)
)
INSERT INTO @OpeningTable
SELECT
IF EXISTS (SELECT ItemID, OpeningBalance FROM str_stockdaily WHERE stockdate = @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CustomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1))
SELECT ItemID, OpeningBalance FROM str_stockdaily WHERE stockdate = @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID=-1) AND (ItemID = @ItemID OR @ItemID = -1)
ELSE
IF EXISTS (SELECT ItemID FROM str_stockdaily WHERE stockdate = ISNULL((SELECT MAX(stockdate) FROM str_stockdaily WHERE stockdate < @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1)), 0) AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1))
SELECT ItemID, closingbalance AS OpeningBalance FROM str_stockdaily WHERE stockdate = (SELECT MAX(stockdate) FROM str_stockdaily WHERE stockdate = @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1)) AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1)
ELSE
SELECT ItemID, 0.000 AS OpeningBalance FROM str_item
But it gives the error:
"Incorrect syntax near the keyword 'IF'
I don't know whether I have written a correct query or not. How to solve this problem? Please I need all your suggestions..
A: DECLARE @OpeningTable TABLE
(
ItemID INT, OpeningBalance DECIMAL(15,3)
)
--INSERT INTO @OpeningTable
--SELECT
IF EXISTS (SELECT ItemID, OpeningBalance FROM str_stockdaily WHERE stockdate = @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1))
INSERT INTO @OpeningTable
SELECT ItemID, OpeningBalance
FROM str_stockdaily
WHERE stockdate = @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID=-1) AND (ItemID = @ItemID OR @ItemID = -1)
ELSE
IF EXISTS (SELECT ItemID FROM str_stockdaily WHERE stockdate = ISNULL((SELECT MAX(stockdate) FROM str_stockdaily WHERE stockdate < @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1)), 0) AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1))
INSERT INTO @OpeningTable
SELECT ItemID, closingbalance AS OpeningBalance
FROM str_stockdaily
WHERE stockdate = (SELECT MAX(stockdate) FROM str_stockdaily WHERE stockdate = @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1)) AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1)
ELSE
INSERT INTO @OpeningTable
SELECT ItemID, 0.000 AS OpeningBalance
FROM str_item
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I log all outgoing email in Django? My Django application sends out quite a bit of emails and I've tried testing it thoroughly. However, for the first few months, I'd like to log all outgoing emails to ensure that everything is working smoothly. Is there a Django module that allows me to do this and makes the outgoing emails visible through the administration panel
Thanks.
A: Since the OP asked about logging and not about saving to DB, here's a middleware that does that:
import django.core.mail.backends.smtp
import logging
logger = logging.getLogger(__name__) # or you could enter a specific logger name
class LoggingBackend(django.core.mail.backends.smtp.EmailBackend):
def send_messages(self, email_messages):
try:
for msg in email_messages:
logger.info(u"Sending message '%s' to recipients: %s", msg.subject, msg.to)
except:
logger.exception("Problem logging recipients, ignoring")
return super(LoggingBackend, self).send_messages(email_messages)
and then in your settings.py:
EMAIL_BACKEND = 'whereiputit.LoggingBackend'
A: I do not know if there exists a module that works this way, but writing a custom one is a piece of cake. Just create a separate model and every time you send an email, create a new instance ( use a custom method for email sending ). Then, link this model with the admin and bingo..
A: Django offers custom E-Mail backends, you can write one on your own.
A: I wrote a custom email backend which logs the stuff to a model.
Here's my backend:
from django.core.mail.backends.smtp import *
from django.db import transaction
from modules.common.models import *
class LoggingEmailBackend(EmailBackend):
"""
A wrapper around the SMTP backend that logs all emails to the DB.
"""
def send_messages(self, email_messages):
"""
A helper method that does the actual logging
"""
with transaction.commit_on_success():
for email_message in email_messages:
email_record = Email.objects.create(
to='; '.join(email_message.recipients()),
subject=email_message.subject, body=email_message.body,
)
try:
return super(LoggingEmailBackend, self)._send(
email_message
)
except:
email_record.ok = False
return False
finally:
email_record.ok = True
return True
Here's the model:
class Email(models.Model):
"""
Model to store all the outgoing emails.
"""
when = models.DateTimeField(
null=False, auto_now_add=True
)
to = models.EmailField(
null=False, blank=False,
)
subject = models.CharField(
null=False, max_length=128,
)
body = models.TextField(
null=False, max_length=1024,
)
ok = models.BooleanField(
null=False, default=True,
)
Here's my model:
from django.contrib import admin
from modules.common.models import *
class EmailAdmin(admin.ModelAdmin):
"""
Admin part for managing the the Email model
"""
list_display = ['to', 'subject', 'ok',]
list_filter = ['ok']
readonly_fields = ['when', 'to', 'subject', 'body', 'ok']
search_fields = ['subject', 'body', 'to']
def has_delete_permission(self, request, obj=None):
return False
def has_add_permission(self, request):
return False
admin.site.register(Email, EmailAdmin)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Visual Studio Add-On and extensions performance monitoring? I'm using / testing a lot of extensions or add-on to Visual Studio.
As my Visual Studio is quite low, I'm wondering if some extensions are causing high CPU load.
Is there any way to monitor memory, disk and CPU usage per extension ?
Google Chrome Task manager provides such functionality... Is there the same for Visual Studio ?
A: DotTrack addon - visual studio
or
http://en.wikipedia.org/wiki/List_of_performance_analysis_tools#.NET
.net performance analysis
Try this link : http://www.jetbrains.com/profiler/ ^^
A: This one is currently available for 2012, 2013, 2015
Extensions Monitor
https://www.visualstudiogallery.msdn.microsoft.com/8dc77c87-a36b-4b79-809c-0102911786db
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Stumbleupon API url encoding problem I am trying to work with the stumbleupon API to get information about the items on my site.
Documentation: http://www.stumbleupon.com/help/badge-api-documentation/
Now it works perfectly except with some URL's...
But http://lolbin.net/i/fp16jU82/that's-what-beer-is-for.htm for example has a ' in the URL, which is a problem for the Stumbleupon API.
I have tried various things, but I keep getting error pages:
http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://lolbin.net/i/fp16jU82/that's-what-beer-is-for.html
http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://lolbin.net/i/fp16jU82/that\'s-what-beer-is-for.html
http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://lolbin.net/i/fp16jU82/that%27s-what-beer-is-for.html
http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://lolbin.net/i/fp16jU82/that%252527s-what-beer-is-for.html
The item is in the stumbleupon database already with many views: http://www.stumbleupon.com/url/lolbin.net/i/fp16jU82/that%252527s-what-beer-is-for.html
My question is, how can I query this particular item via the API so I get a valid return?
A: It works with %2527
http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://lolbin.net/i/fp16jU82/that%2527s-what-beer-is-for.html
Returns:
{"result":{"url":"http:\/\/lolbin.net\/i\/fp16jU82\/that%27s-what-beer-is-for.html",
"in_index":true,"publicid":"Aq9jhK","views":262882,
"title":"Thats what beer is for - LOLBIN.net","thumbnail":"http:\/\/cdn.stumble-upon.com\/mthumb\/767\/82718767.jpg",
"thumbnail_b":"http:\/\/cdn.stumble-upon.com\/altbthumb\/767\/82718767.jpg","submit_link":
"http:\/\/www.stumbleupon.com\/submit?url=http:\/\/lolbin.net\/i\/fp16jU82\/that%27s-what-beer-is-for.html","badge_link":
"http:\/\/www.stumbleupon.com\/badge?url=http:\/\/lolbin.net\/i\/fp16jU82\/that%27s-what-beer-is-for.html",
"info_link":"http:\/\/www.stumbleupon.com\/url\/lolbin.net\/i\/fp16jU82\/that%252527s-what-beer-is-for.html"},
"timestamp":1317025970,"success":true}
It is, as Godius pointed out, a double urlencoding. ' => %27 => %2527
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why UnManaged Export example is doesnt work in prism XE I'm trying to compile This Example for unmanaged export in XE but I getting (PE9) Unknown identifier "UnmanagedExport" error when build.
*
*Under Compatibility select "Allow unsafe code"
*Under Build, find the General Section and change CPU Type to "x86"
*Right Click on the "ClassLibraryX" tab that was created and select "Save selected Items"
namespace exptest;
interface
uses
System.Runtime.InteropServices;
type
clstest = public static class
private
protected
public
[UnmanagedExport('xmsg',CallingConvention.StdCall)]
function xmsg(amsg : String):String;
end;
implementation
function clstest.xmsg(amsg: String):String;
Begin
Result := amsg + ' mesajı için geri dönüş';
end;
end.
Error Window
Any idea?
@David:Thanks for answer. I've tried your tip
public
[UnmanagedExport('xmsg',CallingConvention.StdCall)]
class method xmsg(amsg : String):String;
end;
implementation
class method clstest.xmsg(amsg: String):String;
Begin
Result := amsg + ' mesajı için geri dönüş';
end;
but same error is continues.
@David 2 :):
I've changed code in this way:
namespace exptest;
interface
uses
RemObjects.Oxygene.System;
type
clstest = public class
private
protected
public
[UnmanagedExport('xmsg',CallingConvention.StdCall)]
class method xmsg(amsg : String):String;
end;
implementation
class method clstest.xmsg(amsg: String):String;
Begin
Result := amsg + ' mesajı için geri dönüş';
end;
end.
Same error :)
@david 3
namespace exptest;
interface
uses
RemObjects.Oxygene.System,System.Runtime.InteropServices;
type
clstest = public class
private
protected
public
[UnmanagedExport('xmsg',CallingConvention.StdCall)]
class method xmsg(amsg : String):String;
end;
implementation
class method clstest.xmsg(amsg: String):String;
Begin
Result := 'a return value for '+amsg ;
end;
end.
still same error. :,(
Can you try on your prism ide my sample project for me please? Thanks for answers.
C:\Program Files\Embarcadero\Delphi Prism\bin>oxygene -version
RemObjects Oxygene for .NET - Version 4.0.25.791
Copyright RemObjects Software 2003-2009. All rights reserved.
Exclusively licensed for Delphi Prism.
Configuration Release not found
my oxygene version 4.0.25.791 I suppose.
..............................
@David: I tried compile on command line too. here is results
C:\Documents and Settings\XPMUser\Desktop\exptest\exptest>oxygene /allowunsafe:y
es /type:library /cputype:x86 clstest.pas
RemObjects Oxygene for .NET - Version 4.0.25.791
Copyright RemObjects Software 2003-2009. All rights reserved.
Exclusively licensed for Delphi Prism.
Preparing resources...
Compiling...
C:\Documents and Settings\XPMUser\Desktop\exptest\exptest\clstest.pas(14,22) :
Error : (PE9) Unknown identifier "UnmanagedExport"
Exiting with 1.
C:\Documents and Settings\XPMUser\Desktop\exptest\exptest>
probably your right. maybe something wrong with my compiler. But i didnt see any error during install Delphi prism.
@Rudy: I was tried VS2010 ide before this. As I Said. Maybe i reinstall delphi prism or try different machine. I'll write results if solve.
A: I think the main problem is that you need to use the RemObjects.Oxygene.System namespace which is where UnmanagedExport is defined.
In fact it looks like that uses is not needed (see below).
You also need to make the method a class method.
[UnmanagedExport('xmsg',CallingConvention.StdCall)]
class function xmsg(amsg: String): String;
And likewise in the implementation.
Note that function and procedure are deprecated in Prism and you should use method instead.
[UnmanagedExport('xmsg',CallingConvention.StdCall)]
class method xmsg(amsg: String): String;
This information was gleaned from the docwiki.
I downloaded the command line compiler for Prism XE. This is version 4.0 and so supports the UnmanagedExport attribute.
I successfully compiled the following unit:
namespace ExportTest;
interface
uses
System.Runtime.InteropServices;
type
test = class
[UnmanagedExport('foo', CallingConvention.StdCall)]
class method foo: Integer;
end;
implementation
class method test.foo: Integer;
begin
Result := 666;
end;
end.
The output was:
C:\Desktop>oxygene /allowunsafe:yes /type:library /cputype:x86 test.pas
RemObjects Oxygene for .NET - Version 4.0.25.791
Copyright RemObjects Software 2003-2009. All rights reserved.
Exclusively licensed for Delphi Prism.
Preparing resources...
Compiling...
Compile complete.
This produced a DLL which I verified contained a single exported function named foo.
Next I called the DLL from Python via ctypes:
>>> import ctypes
>>> lib = ctypes.WinDLL('test.dll')
>>> lib.foo()
666
Thus I can only conclude that your problem is not with the code. You perhaps have a mis-configured Prism installation. Could you try to repeat my command line above? Could you perform a re-installation of Prism.
A: This works for me, using Prism XE2 (5.0.29.893) in the VS2010 Shell. This probably won't work in a version earlier than 3.0.19:
*
*Start a new project - Class Library
*Rename to XClassLibrary and save
*set options as you did (allow unsafe code, x86 target)
Make the code of Class1 look like this:
namespace XClassLibrary;
interface
uses
System.Runtime.InteropServices;
type
Class1 = public class
private
protected
public
[UnmanagedExport('xmsg', CallingConvention.StdCall)]
class method xmsg(aMsg: String): String;
end;
implementation
class method Class1.xmsg(aMsg: string): string;
begin
Result := aMsg + ' plus some Turkish text';
end;
end.
Then Build > Build Solution. I get a successful build:
------ Build started: Project: XClassLibrary, Configuration: Debug ------
XClassLibrary -> c:\users\administrator\documents\visual studio 2010\Projects\XClassLibrary\XClassLibrary\bin\Debug\XClassLibrary.dll
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
A: I Solved problem this way.
RGiesecke.DllExport
using System;
using System.Collections.Generic;
using System.Text;
using RGiesecke.DllExport;
using System.Runtime.InteropServices;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Configuration;
namespace thenamespace
{
{
private static some_members
...
...
...
[DllExport(CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.LPStr)]
static String GetValue(
[MarshalAs(UnmanagedType.LPStr)] String _url,
[MarshalAs(UnmanagedType.LPStr)] String _username,
[MarshalAs(UnmanagedType.LPStr)] String _password,
int _method,
[MarshalAs(UnmanagedType.LPStr)] String _identid,
int _isTestMode,
int _TimeOutAsSecond,
[MarshalAs(UnmanagedType.LPStr)] String _ProxyAddr,
[MarshalAs(UnmanagedType.LPStr)] String _ProxyUsername,
[MarshalAs(UnmanagedType.LPStr)] String _ProxyPassword)
{
...
return result;
}
}
}
And pascal side
_fGetValue = function(_url, _username, _password: pAnsiChar; _method: Integer;
_identid: pAnsiChar; _isTestMode : Integer; _TimeOutAsSecond:Integer;
_ProxyAddr:PAnsiChar;_ProxyUsername:PAnsiChar;_ProxyPassword:PAnsiChar): pAnsiChar; stdcall;
...
...
...
var
dllHandle: cardinal;
dllFunc: _fGetValue;
__url, __username, __password, __tckimlik, __result: pAnsiChar;
__metod: Integer;__ProxyAddr:PAnsiChar;
__ProxyUsername:PAnsiChar;__ProxyPassword:PAnsiChar;
begin
Result := '';
__result := '';
dllHandle := LoadLibrary('thelib.dll');
If dllHandle <> 0 then
begin
dllFunc := nil;
@dllFunc := GetProcAddress(dllHandle, 'GetValue');
if Assigned(dllFunc) then
__result := dllFunc(__url, __username, __password, __metod, __identid,
_isTestMode,_TimeOutAsSecond,__ProxyAddr,__ProxyUsername,__ProxyPassword)
else
Begin
raise Exception.Create('Method is not found');
End;
Result := __result;
FreeLibrary(dllHandle);
end
else
begin
raise Exception.Create('Library not found thelib.dll');
end;
end;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: DWR sometimes die on the GAE server I'm creating web app on the Google App Engine. For the AJAX calling I use DWR.
Latest DWR version doesn't work fine with gae, because of that I work with 2.0.6 version of the DWR.
On the local machine application works good. But on the Google server some methods called with errors. I only get errors in browser console (server logs are clear):
Any ideas? Why the behavior on the local and the server machines is different?
Thanks
A: I found mistake in my server side code.
DWR 2 works fine for me. The question is closed.
Excuse me for your time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Generic Plugins Hi i write a some plugins
it's look like that
public class Person
{
public string Name;
public string Surname;
}
public interface IWork
{
Type GetType {get;}
}
public interface IWorker<T> : IWork
{
T GetSingle();
T[] GetMultiple();
void DoWork(T object);
}
one plugin looks like that
public PersonPlugin : IWroker<Person>
{
//implementation of interface
//return typeof(Person);
}
And now question, how i can dynamic create a instance for example of IWork ?
How cast as IWork if i have only Type, it's possible ?
i want to do (should be dynamic, for all instance of plugins)
IWork<T> iWorkInstalce = (IWork<T>)Activator.CreateInstance(typeof(PersonPlugin));
or
IWork iWorkInstalce = (IWork)Activator.CreateInstance(typeof(PersonPlugin));
IWork<Person> personInstance = (CAST) typeof(IWork<>).MakeGenericType(iWorkInstance.Type);
A: You can't cast to IWorker<T> without specifying what T is. If you do that, your first example is valid:
IWorker<Person> iWorkInstalce = (IWorker<Person>)Activator.CreateInstance(typeof(PersonPlugin));
It is possible to use reflection on the PersonPlugin class to find it's implementation of IWorker<T>, and then discover what T is, but this is only any use as runtime, it won't help you at all in code.
If you know what you expect T to be, specify it explicitly. Otherwise, cast to the non-generic IWork instead and give it versions of your methods that return Object. If you don't know what T is at compile-time, having a generic IWorker<T> can't really help you here.
If your application needs to know what type your plugin works with at runtime, it can call the GetType property.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Does using (var connection = new SqlConnection("ConnectionString")) still close/dispose the connection on error? I have the following code
try
{
using (var connection = new SqlConnection(Utils.ConnectionString))
{
connection.Open();
using (var cmd = new SqlCommand("StoredProcedure", connection))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
var sqlParam = new SqlParameter("id_document", idDocument);
cmd.Parameters.Add(sqlParam);
int result = cmd.ExecuteNonQuery();
if (result != -1)
return "something";
//do something here
return "something else";
}
}
//do something
}
catch (SqlException ex)
{
return "something AKA didn't work";
}
The question is: Does var connection still get closed if an unexpected error happens between the using brackets ({ })?
The problem is that most of my calls to stored procedures are made this way, and recently I have been getting this error:
System.InvalidOperationException: Timeout expired. The timeout
period elapsed prior to obtaining a connection from the pool. This
may have occurred because all pooled connections were in use and max
pool size was reached.
The other way I access the DB is through nHibernate.
A: using Statement (C# Reference)
The using statement ensures that Dispose is called even if an
exception occurs while you are calling methods on the object. You can
achieve the same result by putting the object inside a try block and
then calling Dispose in a finally block; in fact, this is how the
using statement is translated by the compiler. The code example
earlier expands to the following code at compile time (note the extra
curly braces to create the limited scope for the object):
A: Yes, if it gets into the body of the using statement, it will be disposed at the end... whether you reached the end of the block normally, exited via a return statement, or an exception was thrown. Basically the using statement is equivalent to a try/finally block.
Is that the only place you acquire a connection? Has your stored procedure deadlocked somewhere, perhaps, leaving lots of connections genuinely "busy" as far as the client code is concerned?
A: In terms of your connection pool running out of available connections, if you are in a distributed environment and using many applications to access SQL Server but they all use the same connection string, then they will all be using the same pool on the server. To get around this you can change the connection string for each application by setting the connection WorkstationID to the Environment.MachineName. This will make the server see each connection as different and provide a pool to each machine instead of sharing the pool.
In the below example we even pass in a token to allow an application on the same machine to have multiple pools.
Example:
private string GetConnectionStringWithWorkStationId(string connectionString, string connectionPoolToken)
{
if (string.IsNullOrEmpty(machineName)) machineName = Environment.MachineName;
SqlConnectionStringBuilder cnbdlr;
try
{
cnbdlr = new SqlConnectionStringBuilder(connectionString);
}
catch
{
throw new ArgumentException("connection string was an invalid format");
}
cnbdlr.WorkstationID = machineName + connectionPoolToken;
return cnbdlr.ConnectionString;
}
A: Replace your above code.. by this.. and check again..
try
{
using (var connection = new SqlConnection(Utils.ConnectionString))
{
connection.Open();
using (var cmd = new SqlCommand("StoredProcedure", connection))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
var sqlParam = new SqlParameter("id_document", idDocument);
cmd.Parameters.Add(sqlParam);
int result = cmd.ExecuteNonQuery();
if (result != -1)
return "something";
//do something here
return "something else";
}
connection.Close();
connection.Dispose();
}
//do something
}
catch (SqlException ex)
{
return "something AKA didn't work";
}
A: Here's a reference:
http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.80).aspx
What I know is that if you use an object within the using {} clause, that object inherits the IDisposable interface (i.e. SqlConnection inherits DbConnection, and DbConnection inherits IDisposable), which means if you get an exception, any object will be closed and disposed properly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: point from n3290 :alignment A point from ISO standard n3290 draft ,Section 3.11:Alignment : 1st point
Object types have alignment requirements (3.9.1, 3.9.2) which place restrictions on
the addresses at which an object of that type may be allocated. An alignment is an
implementation-defined integer value representing the number of bytes between
successive addresses at which a given object can be allocated.An object type imposes
an alignment requirement on every object of that type; stricter alignment can be requested using the alignment specifier (7.6.2).
can any one please explain the above point with an example ?
A: You mean, something like Wikipedia's article on alignment?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: RapidXML is throwing exception ifstream fin("tree.xml");
if (fin.fail()) return 1;
fin.seekg(0, ios::end);
size_t length = fin.tellg();
fin.seekg(0, ios::beg);
char* buffer = new char[length + 1];
fin.read(buffer, length);
buffer[length] = '\0';
fin.close();
xml_document<> doc;
doc.parse<parse_full>(buffer);
// doc.parse<0>(buffer);
delete [] buffer;
cout << "The first node is '" << doc.first_node()->name() << "'\n";
for (xml_node<>* n = doc.first_node("card")->first_node(); n;
n = n->next_sibling())
{
char* v = n->value();
if (!v || !*v) v = "(empty)";
cout << n->name() << " : " << v << '\n';
}
This is the code which i have written for XML parsing using RapidXML, but it throws exception "rapidxml::parse_error at memory location 0x0011fc20.." Please suggest any fix for this. Thanx
A: You may be able to nail down exactly what is causing this by looking at this link http://rapidxml.sourceforge.net/manual.html#classrapidxml_1_1parse__error
In particular (bold text is my emphasis)
class rapidxml::parse_error
Defined in rapidxml.hpp
Description
Parse error exception. This exception is thrown by the parser when an error
occurs. Use what() function to get human-readable error message. Use
where() function to get a pointer to position within source text where
error was detected.
this will at least let you discover what is causing the exception as well as the location. In addition your code does have an issue that could cause problems. This is taken from the rapidXML description of the parse function http://rapidxml.sourceforge.net/manual.html#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c
The bold text is emphasised by me
Parses zero-terminated XML string according to given flags. Passed
string will be modified by the parser, unless
rapidxml::parse_non_destructive flag is used. The string must persist
for the lifetime of the document. In case of error,
rapidxml::parse_error exception will be thrown.
But in your code
xml_document<> doc;
doc.parse<parse_full>(buffer);
// doc.parse<0>(buffer);
delete [] buffer;
cout << "The first node is '" << doc.first_node()->name() << "'\n";
you are deleting the char buffer containing your string and afterwards calling functions on the doc object. This is a violation of the above documentation. I am not sure if this is the exact cause of your exception, but certainly deleting that buffer is going to cause problems. I would suggest using a try/catch block to catch the parse_error exception and then use the where() and what() functions to pinpoint the error. Also try moving the delete statement to the end of your code after you have completely finished calling functions on the doc object as that could also be causing problems.
A: Your parsed DOM object doc is based on your buffer at the memory so dont delete your buffer or delete just before quit
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Add/Override behavior on Jaxb generated classes by extending them I have a web server responding with xml data and a client consuming it.
Both share the same domain code. One of the domain objects looks like this:
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement(name = "image")
public class Image {
private String filename;
private ImageTypeEnum type;
@XmlElement(name = "imageUri")
public String getAbsoluteUri() {
// some complex computation
return uri;
}
}
When I try to unmarshal the response from the server into this object, since there's no setter for absoluteUri, I don't have the imageUri in the class. So I extend it like this:
public class FEImage extends Image{
private String imageUri;
public String getAbsoluteUri() {
return imageUri;
}
public void setAbsoluteUri(String imageUri) {
this.imageUri = imageUri;
}
}
My ObjectFactory
@XmlRegistry
public class ObjectFactory {
public Image createImage(){
return new FEImage();
}
}
My code to unmarshal is here:
JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setProperty("com.sun.xml.bind.ObjectFactory",new ObjectFactory());
((JAXBElement)unmarshaller.unmarshal((InputStream) response.getEntity())).getValue();
However, the setAbsoluteUri doesn't seem to be getting called in FEImage while unmarshalling. When I add a dummy setAbsoluteUri in Image.java, everything works as expected.
Can someone tell me how can I cleanly extend from Image.java?
A: Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
A JAXB implementation is not required to use the ObjectFactory class when instantiating an object. You can configure instantiation to be done via a factory class using the @XmlType annotation:
@XmlType(factoryClass=ObjectFactory.class, factoryMethod="createImage")
public class Image {
private String filename;
private ImageTypeEnum type;
@XmlElement(name = "imageUri")
public String getAbsoluteUri() {
// some complex computation
return uri;
}
}
*
*http://blog.bdoughan.com/2011/06/jaxb-and-factory-methods.html
If you do the above, then your JAXB implementation will still use the Image class to derive the metadata so it will not solve your problem. An alternate approach would be to use an XmlAdapter for this use case:
*
*http://blog.bdoughan.com/2010/12/jaxb-and-immutable-objects.html
Better still, when a property on your domain object does not have a setter, you can tell your
JAXB implementation (EclipseLink MOXy, Metro, Apache JaxMe, etc) to use field (instance variable) access instead using @XmlAccessorType(XmlAccessType.FIELD):
@XmlAccessorType(XmlAccessType.FIELD)
public class Image {
}
*
*http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
UPDATE #1
If you are not able to modify the domain objects, then you may be interested in MOXy's externalized metadata. This extension provides a means via XML to provide JAXB metadata for classes where you cannot modify the source.
For More Information
*
*http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations.html
*http://wiki.eclipse.org/EclipseLink/UserGuide/MOXy/Runtime/XML_Bindings
UPDATE #2 - Based on results of chat
Image
Below is the implementation of the Image class that I will use for this example. For the complex computation of getAbsoluteUri() I simply add the prefix "CDN" to the filename:
package forum7552310;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement(name = "image")
public class Image {
private String filename;
private ImageTypeEnum type;
@XmlElement(name = "imageUri")
public String getAbsoluteUri() {
return "CDN" + filename;
}
}
binding.xml
Below is the MOXy binding document I put together. In this file I do a few things:
*
*Set XmlAccessorType to FIELD
*Mark the absoluteURI property to be XmlTransient since we will be mapping the filename field instead.
*Specify that an XmlAdapter will be used with the filename field. This is to apply the logic that is done in the getAbsoluteUri() method.
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum7552310">
<java-types>
<java-type name="Image" xml-accessor-type="FIELD">
<java-attributes>
<xml-element java-attribute="filename" name="imageUri">
<xml-java-type-adapter value="forum7552310.FileNameAdapter"/>
</xml-element>
<xml-transient java-attribute="absoluteUri"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
FileNameAdapter
Below is the implementation of the XmlAdapter that applies the same name algorithm as the getAbsoluteUri() method:
package forum7552310;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class FileNameAdapter extends XmlAdapter<String, String> {
@Override
public String marshal(String string) throws Exception {
return "CDN" + string;
}
@Override
public String unmarshal(String adaptedString) throws Exception {
return adaptedString.substring(3);
}
}
Demo
Below is the demo code demonstrating how to apply the binding file when creating the JAXBContext:
package forum7552310;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "forum7552310/binding.xml");
JAXBContext jc = JAXBContext.newInstance(new Class[] {Image.class}, properties);
File xml = new File("src/forum7552310/input.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
Image image = (Image) unmarshaller.unmarshal(xml);
System.out.println(image.getAbsoluteUri());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(image, System.out);
}
}
jaxb.properties
You need to include a file named jaxb.properties with the following contents in the same package as your Image class:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
input.xml
Here is the XML input I used:
<?xml version="1.0" encoding="UTF-8"?>
<image>
<imageUri>CDNURI</imageUri>
</image>
Output
And here is the output from running the demo code:
CDNURI
<?xml version="1.0" encoding="UTF-8"?>
<image>
<imageUri>CDNURI</imageUri>
</image>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Solving the invalid name for Python module warning in PyDev I encountered the Invalid name for Python module: ...filename (it'll not be analyzed) warning message in PyDev and I tried to resolve it by replacing - in the filename with _ but the warning didn't disappeared.
One of the problems is that in fact this is not a module, it's just a python script, still I get the warning and the warning says nothing about how to solve the issue.
What are the real requirements for filenames (not necessary modules) and where are they specified (PIP)?
How do I solve this problem in PyDev?
A: See http://docs.python.org/tutorial/modules.html for information about modules.
To find out what characters are valid, have a look at the syntax of the import statement. It shows you that a module name needs to be a valid identifier which has the following rule:
identifier ::= (letter|"_") (letter | digit | "_")*
A: I had the similar message and when I checked the script file name, I had a "-" [dash character] in the script name. After I removed the dash character and replaced with " _ " [an under score character], the warning message was gone.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Security matter: are parameters in url secure? I have developed myself in the last few months about web development in java (servlets and jsp). I am developing a web server, which is mainly serving for an application. Actually it is running on google app engine. My concern is, although I am using SSL connections, sending parameters in the URL (e.g. https://www.xyz.com/server?password=1234&username=uname) may not be secure. Should I use another way or is it really secure? I don't know if this url is delivered as plaint text as whole (with the parameters)?
Any help would be appreciated!
A: Your problem seems to go further than Web Server and Google App Engine.
Sending a password through a web form to your server is a very common security issue. See this SO threads:
*
*Is either GET or POST more secure than the other? (meaningly, POST will simply not display the parameter in the URL so this is not enough)
*Are https URLs encrypted? (describes something similar to what you intend to do)
A: Everything is encrypted, including the URL and its parameters. You might still avoid them because they might be stored in server-side logs and in the browser history, though.
A: The complete HTTP request including the request line is encrypted inside SSL.
Example http request for the above URL which will all be contained within the SSL tunnel:
GET /server?password=1234&username=uname HTTP/1.1
Host: www.xyz.com
...
It is possible though that your application will log the requested URL, as this contains the users password this may not be OK.
A: Well, apart from the issues to do with logging and visibility of URLs (i.e., what happens before and after the secure communication) both GET and POST are equally secure; there is very little information that is exchanged before the encrypted channel is established, not even the first line of the HTTP protocol. But that doesn't mean you should use GET for this.
The issue is that logging in is changing the state of the server and should not be repeated without the user getting properly notified that this is happening (to prevent surprises with Javascript). The state that is being changed is of the user session information on the server, because what logging in does is associate a verified identity with that session. Because it is a (significant) change of state, the operation should not be done by GET; while you could do it by PUT technically, POST is better because of the non-idempotency assumptions associated with it (which in turn encourages browsers to pop up a warning dialog).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: android linearlayout background selector I am adding some Linearlayout views in a scrollview by inflating them dynamically. I have set the background of the added LinearLayout to a selector list. But after adding to scrollview, when I press the selected view, it does not show any affect of selector list. The example XMLs I am using are:
Selector file: selector_file
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/listbg"
android:state_pressed="true" />
<item android:drawable="@drawable/bgsmall"/>
</selector>
And I am inflating the following view and adding to l1 Linearlayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/selector_file"
android:gravity="center_vertical"
>
<ImageView android:id="@+id/image1" android:layout_width="100dip" android:layout_height="75dip"/>
<TextView android:id="@+id/textitem" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#000000"></TextView>
</LinearLayout>
And the ScrollView to which the above inflated views are being added is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content">
<LinearLayout android:id="@+id/l1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical">
</LinearLayout>
</ScrollView>
</LinearLayout>
Any Idea...???
A: You must make the LinearLayout clickable.
android:clickable="true"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Creating a delta column to plot time series differences in R I have a set of motorsport laptime data (mld) of the form:
car lap laptime
1 1 1 138.523
2 1 2 122.373
3 1 3 121.395
4 1 4 137.871
and I want to produce something of the form:
lap car.1 car.1.delta
1 1 138 NA
2 2 122 -16
3 3 121 -1
4 4 127 6
I can use the R command diff(mld$laptime, lag=1) to produce the difference column, but how do I elegantly create the padded difference column in R?
A: I think this is enough:
mld$car.1.delta = c(NA, diff(mld$laptime, lag = 1))
In your example you have truncated laptimes but rounded car.1.delta, so if you really depends on how you want that to work, but code below gives what you posted.
Wrap everything in with to simplify, and create a new data.frame based on modifications of the existing columns. Prepend an NA to the diff to pad it out.
with(mld,
data.frame(
lap = lap,
car.1 = trunc(laptime),
car.1.delta = c(NA, round(diff(laptime)))
)
)
lap car.1 car.1.delta
1 1 138 NA
2 2 122 -16
3 3 121 -1
4 4 137 16
I wonder if you want to do this by car, and if so it will need a bit more handling but since you've literally asked for column car.1 I think this works so far as that goes.
A: Here are a couple of approaches:
1) zoo
If we represented this as a time series using zoo then the calculation would be particularly simple:
# test data with two cars
Lines <- "car lap laptime
1 1 138.523
1 2 122.373
1 3 121.395
1 4 137.871
2 1 138.523
2 2 122.373
2 3 121.395
2 4 137.871"
cat(Lines, "\n", file = "data.txt")
# read it into a zoo series, splitting it
# on car to give wide form (rather than long form)
library(zoo)
z <- read.zoo("data.txt", header = TRUE, split = 1, index = 2, FUN = as.numeric)
# now that its in the right form its simple
zz <- cbind(z, diff(z))
The last statement gives:
> zz
1.z 2.z 1.diff(z) 2.diff(z)
1 138.523 138.523 NA NA
2 122.373 122.373 -16.150 -16.150
3 121.395 121.395 -0.978 -0.978
4 137.871 137.871 16.476 16.476
To plot zz, one column per panel, try this:
plot(zz, type = "o")
To only plot the differences we do not really need zz in the first place as this will do:
plot(diff(z), type = "o")
(Add the screen=1 argument to the plot command to plot everything on the same panel.)
2) ave. Here is a second solution that uses just plain R (except for the plotting) and keeps the output in long form; however, it is a bit more complex:
# assume same input as above
DF <- read.table("data.txt", header = TRUE)
DF$diff <- ave(DF$laptime, DF$car, FUN = function(x) c(NA, diff(x)))
The result is:
> DF
car lap laptime diff
1 1 1 138.523 NA
2 1 2 122.373 -16.150
3 1 3 121.395 -0.978
4 1 4 137.871 16.476
5 2 1 138.523 NA
6 2 2 122.373 -16.150
7 2 3 121.395 -0.978
8 2 4 137.871 16.476
To plot just the differences, one per panel, try this:
library(lattice)
xyplot(diff ~ lap | car, DF, type = "o")
Update
Added info above on plotting since the title of the question mentions this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to read Nfc tags in android? How can i read and display the NDEF messages from NFC tags? Please help me. Can anyone provide the sample source code to read the Nfc tag?
A: We have two option to read the nfc card.
*
*Read from cache
Ndef ndef = Ndef.get(tag);
if (ndef == null) {
// NDEF is not supported by this Tag.
return null;
}
NdefMessage ndefMessage = ndef.getCachedNdefMessage();
if (ndefMessage == null) {
mTextView.setText("The tag is empty !");
return null;
}
NdefRecord[] records = ndefMessage.getRecords();
for (NdefRecord ndefRecord : records) {
if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
try {
return readText(ndefRecord);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unsupported Encoding", e);
}
}
}
*Read directly by using
public void readFromTag(Intent intent){
Ndef ndef = Ndef.get(detectedTag);
try{
ndef.connect();
txtType.setText(ndef.getType().toString());
txtSize.setText(String.valueOf(ndef.getMaxSize()));
txtWrite.setText(ndef.isWritable() ? "True" : "False");
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (messages != null) {
NdefMessage[] ndefMessages = new NdefMessage[messages.length];
for (int i = 0; i < messages.length; i++) {
ndefMessages[i] = (NdefMessage) messages[i];
}
NdefRecord record = ndefMessages[0].getRecords()[0];
byte[] payload = record.getPayload();
String text = new String(payload);
txtRead.setText(text);
ndef.close();
}
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Cannot Read From Tag.", Toast.LENGTH_LONG).show();
}
}
A: 1) The general description of the NFC on android is here
2) The NFCDemo is here
3) Very good information are also here
4) Also the book "Programming Android" from "Zigurd Mednieks" has a chapter about the NFC
BR
STeN
A: *
*Make sure the AndroidManifest.xml file contains the use-permision, intent-filter and meta-data for the NFC, it should look like this.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mynfcreader">
<uses-permission android:name="android.permission.NFC" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyNFCReader">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<meta-data
android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_filter" />
</activity>
</application>
</manifest>
*Create the xml file nfc_filter.xml referenced in the above manifest file, at the res/xml folder, create the xml folder if it is not yet there, the content should contain the following.
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.Ndef</tech>
<!-- class name -->
</tech-list>
</resources>
*activity_main.xml the layout file with a TextView for displaying the message read from NFC tag.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/nfc_contents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:padding="32dp"
android:textAlignment="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
*The MainActivity.kt with the code for reading message from NFC tag and displaying it to the screen.
package com.example.mynfcreader
import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NdefMessage
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.mynfcreader.databinding.ActivityMainBinding
import java.io.UnsupportedEncodingException
import java.nio.charset.Charset
import kotlin.experimental.and
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var tvNFCContent: TextView
private lateinit var nfcAdapter: NfcAdapter
private lateinit var pendingIntent: PendingIntent
var myTag: Tag? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
tvNFCContent = binding.nfcContents
tvNFCContent.text = "Place the back of the phone over a NFC tag to read message from NFC tag"
nfcAdapter = NfcAdapter.getDefaultAdapter(this)
if (nfcAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show()
finish()
}
readFromIntent(intent)
pendingIntent = PendingIntent.getActivity(
this,
0,
Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
0
)
val tagDetected = IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)
tagDetected.addCategory(Intent.CATEGORY_DEFAULT)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
readFromIntent(intent)
}
private fun readFromIntent(intent: Intent) {
val action = intent.action
if (NfcAdapter.ACTION_TAG_DISCOVERED == action || NfcAdapter.ACTION_TECH_DISCOVERED == action || NfcAdapter.ACTION_NDEF_DISCOVERED == action) {
myTag = intent.getParcelableExtra<Parcelable>(NfcAdapter.EXTRA_TAG) as Tag?
val rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
var msgs = mutableListOf<NdefMessage>()
if (rawMsgs != null) {
for (i in rawMsgs.indices) {
msgs.add(i, rawMsgs[i] as NdefMessage)
}
buildTagViews(msgs.toTypedArray())
}
}
}
private fun buildTagViews(msgs: Array<NdefMessage>) {
if (msgs == null || msgs.isEmpty()) return
var text = ""
val payload = msgs[0].records[0].payload
val textEncoding: Charset = if ((payload[0] and 128.toByte()).toInt() == 0) Charsets.UTF_8 else Charsets.UTF_16 // Get the Text Encoding
val languageCodeLength: Int = (payload[0] and 51).toInt() // Get the Language Code, e.g. "en"
try {
// Get the Text
text = String(
payload,
languageCodeLength + 1,
payload.size - languageCodeLength - 1,
textEncoding
)
} catch (e: UnsupportedEncodingException) {
Log.e("UnsupportedEncoding", e.toString())
}
tvNFCContent.text = "Message read from NFC Tag:\n $text"
}
}
*Install the app on an Android phone, and place the back of the android phone over a NFC tag, the app will be launched and displays message on the screen if the NFC tag has any messages stored on it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to access AfxGetMainWnd() from CWinThread? I'm trying to create a worker thread in a class called ClientManager, but I can't get access to AfxGetMainWnd() from the new CWinThread, i.e:
UINT ClientManager::WorkerThreadProc( LPVOID param ){
ClientManager *pThis = reinterpret_cast<ClientManager*>(param);
return pThis -> DoThreadJob();
}
UINT ClientManager::DoThreadJob(){
createClientSession("1");
return 0;
}
void ClientManager::createThread(){
m_clientManagerThread = AfxBeginThread(WorkerThreadProc,this,0,0,0,NULL);
}
void ClientManager::createClientSession(CString clientID){
if (AfxGetMainWnd()->GetSafeHwnd()== NULL){
_cprintf("NULL");
}
}
Output: NULL
AfxGetMainWnd()->GetSafeHwnd() works in the main thread.
Thanks!
A: AfxGetApp()->GetMainWnd() works in threads.
No need to store the window handle in a member of ClientManager.
A: The documentation says:
If AfxGetMainWnd is called from the application's primary thread, it returns the application's main window according to the above rules. If the function is called from a secondary thread in the application, the function returns the main window associated with the thread that made the call.
So you need to make the call from the main thread. Do this just before you call AfxBeginThread and store the resulting window handle in a member of ClientManager. Then your thread can gain access to the window handle via its ClientManager reference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: CheckStyle rules for Java Code Conventions from 1997 Is there a CheckStyle rule file that checks against the Java Code Conventions from September 12, 1997?
A: According to the checkstyle homepage, it contains an example configuration file supporting the Sun Code Conventions. It does not say how supporting is defined, but it links to exactly the same document as you in your question.
A: Just download checkstyle from sourceforge.net and find sun_checks.xml inside
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to create a barrier in multi-thread on android I need a barrier in my multi-thread project on Linux. I know the pthread_barrier_init() and pthread_barrier_wait(), but I want to run my project on android. It didn't have these functions. I know how to implement it with atomic add and atomic comparison. I want to use a semaphore, can I use a semaphore to implement it?
A: Use a CyclicBarrier, this is more or less identical to a pthread barrier.
Sample code (from linked page)
class Solver {
final int N;
final float[][] data;
final CyclicBarrier barrier;
class Worker implements Runnable {
int myRow;
Worker(int row) { myRow = row; }
public void run() {
while (!done()) {
processRow(myRow);
try {
barrier.await();
} catch (InterruptedException ex) {
return;
} catch (BrokenBarrierException ex) {
return;
}
}
}
}
public Solver(float[][] matrix) {
data = matrix;
N = matrix.length;
barrier = new CyclicBarrier(N,
new Runnable() {
public void run() {
mergeRows(...);
}
});
for (int i = 0; i < N; ++i)
new Thread(new Worker(i)).start();
waitUntilDone();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create RPM package with runtime libraries and executable file I have created a C++ application under redhat linux environment. Beside this application, I have also created many *.so libraries required by the application. The created application uses some Boost C++ libraries, e.g. -lboost_system, -lboost_thread and etc
I wish to deploy this application and its required runtime libraries onto the production machine without exposing/recompiling the source codes and without having Boost C++ full installation on the production machine. Is it possible?
The application directories structure in development machine as follows:
~/SysA/debug/main/main (executable binary file)
~/SysA/debug/main/config (configuration text file)
~/SysA/debug/lib1/libA.so
~/SysA/debug/lib2/libB.so
~/SysA/debug/lib3/libC.so
:
:
I have attempted to make my first following RPM SPEC file as follows, but stucked:
Name: SYSTEM
Version: 0.1
Release: 1.0
BuildRoot: %{_topdir}BUILD/%{name}-%{version}-%{release}
AutoReqProv: no
%description
System testing
%prep
rm -rf $RPM_BUILD_ROOT
%clean
rm -rf %RPM_BUILD_ROOT
%files
%defattr(644, root, root)
%changelog
Wish someone can help me out...
A: You should either create a 2nd RPM for Boost libraries (to be installed together with your RPM) or link Boost libraries statically into your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Loading 10k+ rows in iphone SQLite (FMDB) I am creating a dictionary app and I am trying to load the terms into an iphone dictionary for use. The terms are defined from this table (SQLite):
id -> INTEGER autoincrement PK
termtext -> TEXT
langid -> INT
normalized -> TEXT
Normalized is used because I am writing in GREEK and I don't have icu on the sqlite engine for searching diacritics, so I am making a termtext diacritics/case insensitive. It is also the main search field, in contrast of termtext which could be the "view" field.
I have defined an class (like a POJO) like this:
terms.h
#import <Foundation/Foundation.h>
@interface Terms : NSObject {
NSUInteger termId; // id
NSString* termText; // termtext
NSUInteger langId; // langid
NSString* normalized; // normalized
}
@property (nonatomic, copy, readwrite) NSString* termText;
@property (nonatomic, copy, readwrite) NSString* normalized;
@property (assign, readwrite) NSUInteger termId;
@property (assign, readwrite) NSUInteger langId;
@end
terms.c
#import "Terms.h"
@implementation Term
@synthesize termId;
@synthesize termText;
@synthesize langId;
@synthesize normalized;
@end
Now in my code I use FMDB as the wrapper for the SQLite database. I load the terms using the following code:
[... fmdb defined database as object, opened ]
NSMutableArray *termResults = [[[NSMutableArray alloc] init] autorelease];
FMResultSet *s = [database executeSQL:@"SELECT id, termtext, langid, normalized FROM terms ORDER BY normalized ASC"];
while ([s next]) {
Term* term = [[Terms alloc] init];
term.termId = [s intForColumn:@"id"];
[... other definitions]
[termResults addObject:term];
[term release];
}
The whole termResults is then loaded to a UITableView (on viewdidload) but the loading takes up to 5 seconds every time I start my app. Is there any way to speedup that process? I have indexed id, termText and normalized on SQLite.
*** UPDATE: added cellForRowAtIndexPath ****
[.. standard cell definition...]
// Configure the cell
Term* termObj = [self.termResults objectAtIndex:indexPath.row];
cell.textLabel.text = termObj.termText;
return cell;
A: Since you seem to load the whole DB into memory anyway (and think it is a must) the whole point of using SQLite is almost gone.
So if the data is static (does not change), I would turn the DB into objects once, then serialize the objects (implement the NSCoding protocol) and store this array (or better yet, dictionary) using writeToFile:atomically:. Once you have that file (do that during development) you can easily load it at runtime with arrayWithContentsOfFile: which should be faster in this case.
A: Loading that much data into your app is going to take time. The best approach to take would be to load the data from the db on a separate thread to the main application thread. As each item is loaded, post a message back to the main thread to add an item to the array backing the table view. This way, your app load time will be short and your UI will be responsive whilst the data is loading from the db. Here's the basic idea:
NSMutableArray *termResults = [NSMutableArray array];
// Load each item from the db on a separate thread using a block
dispatch_queue_t globalQueue = dispatch_get_global_queue();
dispatch_async(globalQueue, ^() {
// Init the database
...
// Load the items from the db
FMResultSet *s = [database executeSQL:@"SELECT id, termtext, langid, normalized FROM terms ORDER BY normalized ASC"];
while ([s next]) {
Term* term = [Term new];
term.termId = [s intForColumn:@"id"];
// Add the loaded item to termResults on the main thread
// and refresh the table view
dispatch_queue_t mainDispatchQueue = dispatch_get_main_queue();
dispatch_async(mainDispatchQueue, ^() {
// Add the loaded item to termResults
[termResults addObject:term];
// Refresh the table view. This will only reload the visible items.
[tableView reloadData];
});
[term release];
}
});
Hope this helps.
A: Not a problem to read 10K records from sqlite into UITableView. First, I couldn't see reasons to do that. Second, you couldn't avoid time gap due to a lot of memory allocations. Memory allocation is a system call. And system calls are often slow. During load ios will send memory warnings to run apps resulting in longer gap. What will you do if you will need a million records? sqlite is used to avoid such memory data structures at all. If you see problems using unicode in sqlite on iphone (icu) - read here. I use this technic in several of my apps and all of them were approved to AppStore without problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Best filename to include JQuery in an embedded application I'm using JQuery for an embedded system that is isolated from the outside word. Therefore jquery exists on the local server (the embedded system). The question is: what would be the best file name to include JQuery in my html?
*
*<script type="text/javascript" src="js/jquery.js"></script>
*<script type="text/javascript" src="js/jquery-1.6.4.js"></script>
I searched Stackoverflow and found the following threads despite of being useful they don't answer my specific question in this scenario:
*
*What is the best way to include latest version of jQuery?
*What is the best way to include jQuery in DotNetNuke 4.8.x?
Because if later we switch to a newer version, I don't have to go through the html files and update them. This is an embedded system and once it's running we hardly update any file. Besides the customer doesn't need to know the version of the libraries and developers know the version already.
A: jquery-1.6.4.js is better because
*
*it helps clearly identify which version is being used
*it prevents possible caching issues that might arise if you changed the jQuery version but not the file name.
A: Option 2.
Because when you update the version the version number of the file name will act as a cache buster.
This means if a browser caches your file, a change in file name will force it to redownload, as it's a completely new file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Reading a fortigate configuration file with Python Appologies for the really long drawn out question.
I am trying to read in a config file and get a list of rules out.
I have tried to use ConfigParser to do this but it is not a standard config file.
The file contains no section header and no token.
i.e.
config section a
set something to something else
config subsection a
set this to that
next
end
config firewall policy
edit 76
set srcintf "There"
set dstintf "Here"
set srcaddr "all"
set dstaddr "all"
set action accept
set schedule "always"
set service "TCP_5600"
next
edit 77
set srcintf "here"
set dstintf "there"
set srcaddr "all"
set dstaddr "all"
set action accept
set schedule "always"
set service "PING"
next
end
As I couldn't work out how to get ConfigParser to work I thought I would try to iterate through the file, unfortunately I don't have much programming skill so I have got stuck.
I really think I am making this more complicated than it should be.
Here's the code I have written;
class Parser(object):
def __init__(self):
self.config_section = ""
self.config_header = ""
self.section_list = []
self.header_list = []
def parse_config(self, fields): # Create a new section
new_list = []
self.config_section = " ".join(fields)
new_list.append(self.config_section)
if self.section_list: # Create a sub section
self.section_list[-1].append(new_list)
else: self.section_list.append(new_list)
def parse_edit(self, line): # Create a new header
self.config_header = line[0]
self.header_list.append(self.config_header)
self.section_list[-1].append(self.header_list)
def parse_set(self, line): # Key and values
key_value = {}
key = line[0]
values = line[1:]
key_value[key] = values
if self.header_list:
self.header_list.append(key_value)
else: self.section_list[-1].append(key_value)
def parse_next(self, line): # Close the header
self.config_header = []
def parse_end(self, line): # Close the section
self.config_section = []
def parse_file(self, path):
with open(path) as f:
for line in f:
# Clean up the fields and remove unused lines.
fields = line.replace('"', '').strip().split(" ")
if fields[0] == "set":
pass
elif fields[0] == "end":
pass
elif fields[0] == "edit":
pass
elif fields[0] == "config":
pass
elif fields[0] == "next":
pass
else: continue
# fetch and call method.
method = fields[0]
parse_method = "parse_" + method
getattr(Parser, parse_method)(self, fields[1:])
return self.section_list
config = Parser().parse_file('test_config.txt')
print config
The output I am looking for is something like the following;
[['section a', {'something': 'to something else'}, ['subsection a', {'this': 'to that'}]],['firewall policy',['76',{'srcintf':'There'}, {'dstintf':'Here'}{etc.}{etc.}]]]
and this is what I get
[['section a']]
EDIT
I have changed the above to reflect where I am currently at.
I am still having issues getting the output I expect. I just can't seem to get the list right.
A: class Parser(object):
def __init__(self):
self.my_section = 0
self.flag_section = False
# ...
def parse_config(self, fields):
self.my_section += 1
# go on with fields
# ...
self.flag_section = True
def parse_edit(self, line):
...
def parse_set(self, line):
...
def parse_end(self, line):
...
def parse_file(self, path):
with open(path) as f:
for line in f:
fields = f.strip().split(" ")
method = fields[0]
# fetch and call method
getattr(Parser, "parse_" + method)(self, fields[1:])
A: I post my answer for people who first come here from Google when trying to parse Fortigate configuration file !
I rewrote what I found here based on my own needs and it works great.
from collections import defaultdict
from pprint import pprint
import sys
f = lambda: defaultdict(f)
def getFromDict(dataDict, mapList):
return reduce(lambda d, k: d[k], mapList, dataDict)
def setInDict(dataDict, mapList, value):
getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value
class Parser(object):
def __init__(self):
self.config_header = []
self.section_dict = defaultdict(f)
def parse_config(self, fields): # Create a new section
self.config_header.append(" ".join(fields))
def parse_edit(self, line): # Create a new header
self.config_header.append(line[0])
def parse_set(self, line): # Key and values
key = line[0]
values = " ".join(line[1:])
headers= self.config_header+[key]
setInDict(self.section_dict,headers,values)
def parse_next(self, line): # Close the header
self.config_header.pop()
def parse_end(self, line): # Close the section
self.config_header.pop()
def parse_file(self, path):
with open(path) as f:
gen_lines = (line.rstrip() for line in f if line.strip())
for line in gen_lines:
# pprint(dict(self.section_dict))
# Clean up the fields and remove unused lines.
fields = line.replace('"', '').strip().split(" ")
valid_fields= ["set","end","edit","config","next"]
if fields[0] in valid_fields:
method = fields[0]
# fetch and call method
getattr(Parser, "parse_" + method)(self, fields[1:])
return self.section_dict
config = Parser().parse_file('FGT02_20130308.conf')
print config["system admin"]["admin"]["dashboard-tabs"]["1"]["name"]
print config["firewall address"]["ftp.fr.debian.org"]["type"]
A: I do not know if this can help you too, but it did for me : http://wiki.python.org/moin/ConfigParserExamples
Have fun !
A: I would do it in a simpler way:
flagSection = False
flagSub = False
mySection = 0
mySubsection = 0
myItem = 0
with open('d:/config.txt', 'r') as f:
gen_lines = (line.rstrip() for line in f if line.strip())
for line in gen_lines:
if line[0:7]=='config ':
mySection = mySection + 1
newLine = line[7:]
# Create a new section
# Mark section as open
flagSection == True
elif line[0:5]=='edit '):
mySubsection = mySubsection + 1
newLine = line[5:]
# Create a new sub-section
# Mark subsection as open
flagSub == true
elif line[0:4]=='set '):
myItem = myItem + 1
name, value = x.split(' ',2)[1:]
# Add to whatever is open
elif line=='end':
# If subsection = open then close and goto end
if flagSub:
# Or if section = open then close and goto end
elif flagSection:
# :End
continue
The instruction gen_lines = (line.rstrip() for line in f if line.strip())
creates a generator of not empty lines (thanks to the test if line.strip()) without newline and without blanks at the right (thanks to line.rstrip())
.
If I would know more about the operations you want to perform with name,value and in the section opened with if line=='end' , I could propose a code using regexes.
Edit
from time import clock
n = 1000000
print 'Measuring times with clock()'
te = clock()
for i in xrange(n):
x = ('abcdfafdf'[:3] == 'end')
print clock()-te,
print "\tx = ('abcdfafdf'[:3] == 'end')"
te = clock()
for i in xrange(n):
x = 'abcdfafdf'.startswith('end')
print clock()-te,
print "\tx = 'abcdfafdf'.startswith('end')"
print '\nMeasuring times with timeit module'
import timeit
ti = timeit.repeat("x = ('abcdfafdf'[:3] == 'end')",repeat=10,number = n)
print min(ti),
print "\tx = ('abcdfafdf'[:3] == 'end')"
to = timeit.repeat("x = 'abcdfafdf'.startswith('end')",repeat=10,number = n)
print min(to),
print "\tx = 'abcdfafdf'.startswith('end')"
result:
Measuring times with clock()
0.543445605517 x = ('abcdfafdf'[:3] == 'end')
1.08590449345 x = 'abcdfafdf'.startswith('end')
Measuring times with timeit module
0.294152748464 x = ('abcdfafdf'[:3] == 'end')
0.901923289133 x = 'abcdfafdf'.startswith('end')
Is the fact the times are smaller with timieit than with clock() due to the fact that the GC is unplugged when the program is run ? Anyway, with either clock() or timeit module , executing startswith() takes more time than slicing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: read parameter on js file
Possible Duplicate:
Pass vars to JavaScript via the SRC attribute
May I know how to read get the p value on js file link like filename.js?p=value with local javascript in the js file? Any function to work like the $_GET['p'] in php? Thanks.
A: try this:
var tmp = location.href, it;
if (q) it = tmp.substr(q + 1).split('&');
else it = '';
for (var i in it) {
var t = it[i].split('=');
if (t[0] == 'p') {
//do something
break;
}
}
A: function _GET( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
This will do the equivalent in javascript.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: logback socketappender not working from webapp I use logback in my maven project and send logs using socketappender. However, the socketappender works only when i run a junit test but when I run my project from tomcat (open a web page) only console appender works.
I used lilith and the sample server in the from the logabck jar.
Here is my logback.xml which is the same as logback-test.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="RootSocketAppender" class="ch.qos.logback.classic.net.SocketAppender">
<remoteHost>127.0.0.1</remoteHost>
<port>4560</port>
<reconnectionDelay>30000</reconnectionDelay>
<includeCallerData>false</includeCallerData>
</appender>
<root level="warn">
<appender-ref ref="console" />
<appender-ref ref="RootSocketAppender" />
</root>
</configuration>
I get this messages from tomcat console when I deploy the app:
10:29:45,794 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
10:29:45,794 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback-test.xml] at [file:/D:/programmation/workspace/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/webapp/WEB-INF/classes/logback-test.xml]
10:29:45,794 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback-test.xml] occurs multiple times on the classpath.
10:29:45,794 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback-test.xml] occurs at [file:/D:/programmation/workspace/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/webapp/WEB-INF/classes/logback-test.xml]
10:29:45,794 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback-test.xml] occurs at [jar:file:/D:/programmation/workspace/eclipse/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/webapp/WEB-INF/lib/backoffice.jar!/logback-test.xml]
10:29:45,856 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
10:29:45,856 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
10:29:45,856 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [console]
10:29:45,872 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
10:29:45,903 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [foo] to INFO
10:29:45,903 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [org.springframework.core] to INFO
10:29:45,903 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [org.springframework.beans] to INFO
10:29:45,903 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [org.springframework.context] to INFO
10:29:45,903 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [org.springframework.test] to TRACE
10:29:45,903 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [org.springframework.web] to INFO
10:29:45,903 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to WARN
10:29:45,903 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [console] to Logger[ROOT]
thanks
A: Logback can't found the RootSocketAppender in your logback-test.xml. Make sure that it contains this appender and it's attached to the root logger.
Note that there is a logback-test.xml in the WEB-INF/classes/ directory and an other one in the
WEB-INF/lib/backoffice.jar. Maybe you should have only one in your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: find the next input field which is in next div-jquery I am getting the last element of the form which has got value, now i want to find the id of next input element which is in next div...
var elem1 =$(':text[name^=distanceSlab][value!=""]').last();
var nextElemId = // find the id of next input element which is in next div
the corresponding html code is
<div id ="divid4">
<input type="text" id ="slab4" value ="1"/> // this is the last elemnt which has value
</div>
<div id ="div1d5">
<input type="text" id ="slab5" value =""/> // need to find the id of this element
</id>
A: Assuming that you're starting from the input that you've already identified, then:
$(this).closest('div').next('div').find('input:text').attr('id');
JS Fiddle.
Or:
var thisIndex = $(this).index('input:text');
var next = thisIndex + 1;
var nextElemId = $('input:text').eq(next).attr('id');
JS Fiddle.
I'd probably put those into a blur(), or similar, event.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Flex embedded string resource encoding I embed a text file into my Flex project and read its contents using code like this:
[Embed(source = "../../data/abc.txt", mimeType = "application/octet-stream")]
private var r_Abc:Class;
...
var xx:ByteArray = new r_Abc();
var abc:String = xx.toString();
The contents of the file is abc. The problem is that the string loaded from the file is not comparable to other strings even though when printed or viewed in the debugger (in FlashDevelop) it seems to be perfectly fine.
trace(abc); // abc
trace("abc" == abc); // false
How do I convert it into a proper string? I tried to use the string methods such as substring to create a copy, but that does not seem to be the solution.
A: Here's my sample:
<?xml version="1.0" encoding="utf-8"?>
<s:Application minWidth="955" minHeight="600"
creationComplete="creationCompleteHandler(event)"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import mx.core.ByteArrayAsset;
import mx.events.FlexEvent;
// my file is "ABC "
// strangely enough if I remove the space at the end the string in code is empty
[Embed(source="data/abc.txt", mimeType="application/octet-stream")]
private var abcFile:Class;
protected function creationCompleteHandler(event:FlexEvent):void
{
var abcByteArray:ByteArrayAsset = ByteArrayAsset(new abcFile());
var abc:String = abcByteArray.readUTFBytes(abcByteArray.length);
trace(abc); // ABC (has a space at the end)
trace(abc == "ABC "); // true, but notice the space at the end
}
]]>
</fx:Script>
</s:Application>
My suggestion is to check for trailing spaces, new lines. Also try to place some sort of an EOF character at the end of the file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to read large matrix from a csv efficiently in Octave There are many reports of slow performance of Octave's dlmread. I was hoping that this was fixed in 3.2.4, but when I tried to load a csv file that has a size of ca. 8 * 4 mil (32 mil in total), it also took very, very long time. I searched the web but could not find a workaround for this. Does anybody know a good workaround?
A: I experienced the same problem and had R handy, so my solution was to use "read.csv" in R, and then use the R package "R.matlab" to write a ".mat" file, and then load that in Octave.
"read.csv" can be pretty slow too, but this worked very well in my case.
A: The reason is that Octave has a bug that adding data to a very large matrix takes more time then adding the same amount of data to a small matrix.
Below is my try. I choose to save data each 50000 lines, so meanwhile I could already take a look instead of being forced to wait. It is slower for small files, but much faster for larger files.
function alldata = load_data(filename)
fid = fopen(filename,'r');
s=0;
data=[];
alldata=[];
save "temp.mat" alldata;
if fid == -1
disp("Couldn't find file mydata");
else
while (~feof(fid))
line = fgetl(fid);
[t1,t2,t3,t4,d] = sscanf(line,'%i:%i:%i:%i %f', "C"); #reading time as hh:mm:ss:ms and data as float
s++;
t = (t1 * 3600000 + t2 * 60000 + t3 * 1000 + t4);
data = [data; t, d];
if (mod(s,10000) == 0)
#disp(s), disp(" "), disp(t), disp(" "), disp(d), disp("\n");
disp(s);
fflush(stdout);
end
if (mod(s,50000) == 0)
load "temp.mat";
alldata=[alldata; data];
data=[];
save "temp.mat" alldata;
disp("data saved");
fflush(stdout);
end
end
disp(s);
load "temp.mat";
alldata=[alldata; data];
save "temp.mat" alldata;
disp("data saved");
fflush(stdout);
end
fclose(fid);
A: Here is a workaround that I am using.
I did not find that sscanf will parse input lines as indicated above. Also, I didn't use the temp file.
My .csv file has a large number of rows. They begin with a header of 18 lines and are followed by a data block, each of which has 135 columns. The following code has been tested. My file also begins each row with a dd/mm/yyyy hh:mm field. This will also catch poor lines and indicate where they are by using try/catch.
My .csv file came from a customer who dumped his PARCView load in an Excel file.
function [tags,descr,alldata] = fbcsvread(filename)
fid = fopen(filename,'r');
s = 0;
data=[];
alldata=zeros(1,135);
if fid==-1
disp("Couldn't find file %s\n",filename);
else
linecount = 1;
while (~feof(fid))
line = fgetl(fid);
data2 = zeros(1,135);
if linecount == 1
tags = strsplit(line,",");
elseif linecount == 2
descr = strsplit(line,",");
elseif linecount >= 19
data = strsplit(line,",");
datetime = strsplit(char(data(1))," ");
modyyr = strsplit(char(datetime(1)),"/");
hrmin = strsplit(char(datetime(2)),":");
year1 = sscanf(char(modyyr(3)),"%d","C");
day1 = sscanf(char(modyyr(2)),"%d","C");
month1 = sscanf(char(modyyr(1)),"%d","C");
hour1 = sscanf(char(hrmin(1)),"%d","C");
minute1 = sscanf(char(hrmin(2)),"%d","C");
realtime = datenum(year1,month1,day1,hour1,minute1);
data2(1) = realtime;
for location = 2:134
try
data2(location) = sscanf(char(data(location)),"%f","C");
catch
printf("Error at %s %s\n",char(datetime(1)),char(datetime(2)) );
fflush(stdout);
end_try_catch
endfor
alldata(linecount-18,:) = data2;
if mod(linecount,50) == 0
printf(".");
fflush(stdout);
endif
endif
linecount = linecount + 1;
endwhile
fclose(fid);
endif
endfunction
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: IE with unordered list emty element In my *.ascx file I have a following code:
<ul>
<li><ctl:CustomControl id="ctl1" runat="server"/></li>
<li><ctl:CustomControl id="ctl2" runat="server"/></li>
<li><ctl:CustomControl id="ctl3" runat="server"/></li>
</ul>
User control named "CustomControl" may produce some text, but in particular cases it may produce nothing (empty text).
I found that Firefox doesn't display such empty list element (what is expected behaviour for me), but Internet explorer does.
What is the easiest way (i.e using css, without involving any C# code behind) to prevent IE displaying empty list element?
A: Please check this solution: http://www.howtocreate.co.uk/wrongWithIE/?chapter=Empty+Elements
This should help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HappStack event files I am developing a game and chose Happstack for the persistence part. I find it quite easy to use, i made a quick example for myself to understand it:
getAllObjects :: MonadIO m => m [Thing]
getAllObjects = do
elems <- query GetObjects
return elems
addAnObject :: (MonadIO m) => Thing -> m ()
addAnObject thing = do update $ AddObject thing
test command = do
control <- startSystemState macidProxy
result <- command
shutdownSystem control
return result
checkpoint = do
control <- startSystemState macidProxy
createCheckpoint control
shutdownSystem control
and everytime i 'test' it, it create an event.file. then i 'checkpoint' and creates a new checkpoint file, it is ok for me, the problem is that the old events files keep growing! i manualy delete everyfile (except last checkpoint and current).
Is there some code im missing from happstack to do the 'delete old things'?
A: There is no built-in mechanism for purging old event files. Lemmih has talked about adding such facilities to acid-state at some point in time.
EDIT: The darcs version of acid-state now has a function 'createArchive' to archive old log files that are no longer needed to restore the current state.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why would printing a variable change its value? I have a small function, which is supposed to make a prediction based on a machine learning algorithm. The function wasn't working, so I put a print statement in to check on the value, and all of a sudden it started working. When I comment out the print line, it stops working again. Is there something I'm missing about why this would happen?
int makePrediction( const InstanceT & instance, bool biased ){
double dotProduct = ( biased ? instance * _weights + _bias : instance * _weights );
std::cout << "dotProduct = " << dotProduct << std::endl;
return ( dotProduct > 0 ? 1 : -1 );
}
for some reason produces a different result then
int makePrediction( const InstanceT & instance, bool biased ){
double dotProduct = ( biased ? instance * _weights + _bias : instance * _weights );
return ( dotProduct > 0 ? 1 : -1 );
}
and to show that the results are different given the same inputs, I call this function with:
std::vector<InstanceT> _instances = populate_data() //this works for both versions
for ( int i = 0; i < _instances.size(); i++ ){
std::cout << "prediction: " << makePrediction( _instances[i], true ) << std::endl;
}
Any thoughts?
A: This often happens due to two reasons:
*
*Concurrency issues. If your program is multithreaded, you mask race conditions with debug output. Try a MT debugger like helgrind.
*Broken stacks. Try running valgrind on your program and see if it comes out clean.
These are, of course, pretty generic advices, but you'll have to specify your question better to get better advice :-).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7552406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.