text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: jQuery draggable: limiting drag for an irregular area I have an image-based map. I want to drag a div within a specified area of the map. Is it possible using jQuery?
A: here is useful info:
http://jqueryui.com/demos/draggable/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to find index based on sorted elements among siblings.? <div id="container">
<div class="aa"></div>
<div class="bb"></div>
<div class="aa"></div>
<div class="bb"></div>
<div class="bb"></div>
<div class="bb"></div>
<div class="bb"></div>
</div>
i just need to find the index of element based on particular class while looping.
Normal index will give the element index no: among the siblings.
I want to consider siblings with same class only, and give the index based on that sorted siblings.
$("#container div").each(function(){
if($(this).hasClass('bb')){
var index = $(this).index();
//will give me 1,3,4,5 etc
//I want 0,1,2 etc ie: list the index based on class
}
if($(this).hasClass('aa')){
var index = $(this).index();
//will give me 0 , 2
//I want 0,1 etc ie: list the index based on class
}
})
A: For .index() you can pass a selector as a parameter (for example '.bb').
As you can find in the online documentation.
If a selector string is passed as an argument, .index() returns an
integer indicating the position of the original element relative to
the elements matched by the selector. If the element is not found,
.index() will return -1.
So you could do something like:
$("#container div").each(function(i){
if($(this).hasClass('bb')){
var index = $(this).index('.bb');
}
else if($(this).hasClass('aa')){
var index = $(this).index('.aa');
}
});
jsFiddle Demo
A: If you pass an element to the index() method, it will return the index of that element among the matched elements instead of its siblings.
So, you can match all the elements with the same class as the current one and call index() on the resulting jQuery object, passing the current element as an argument:
$("#container div").each(function() {
var index = $("#container div." + $(this).attr("class")).index(this);
// ...
}
A: Split them:
var $as = $('container > .aa'),
$bs = $('container > .bb');
for (...) {
if ($this.hasClass('aa')) console.log($as.index($this));
if ($this.hasClass('bb')) console.log($bs.index($this));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: simple login implementation using php. (clearing a session so that hitting 'back' doesn't work when you logout) I've got a simple login system going with php sessions. The issue I'm having is even after hitting "logout", I can still go back to the previous page by hitting the back button.
The way I'm logging out is done by the following...
<?php
session_start();
session_unset();
session_destroy();
header("Location: ./login.php"); // redirect to login page.
?>
How do I completely delete a session..?
A: This will log you out. As commented, hitting back will more than likly be loading browser cache. Therefore as long as you have security properly in place - clicking on something should result in your login page being displayed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Finding the nearest quantity based on price and amount to get I've got a small maths problem in which I need to determine a quantity based on a cost price and a final amount.
Now this is easy in theory as it's simply final amount/actual cost = quantity, except in my case the actual cost changes based on the quantity.
Quantity = Final Amount / (Item Cost + Overhead Cost) where the overhead cost is on a sliding scale.
An example would be
If i want to make $500 for selling sheep, and the base price for each sheep is say $50, but the cost of selling one sheep is $5, so the actual cost would be $55 for one sheep, but if i sell 2 sheep then the cost of selling one becomes $7, so the actual cost would be $107 and so on and so forth.
What would be the most optimal way to get to as close to the final amount (but not over) as possible, without having to loop almost unconditionally?
A: Based on the assumption that your overhead cost is always non-negative and monotonic you know that
0 <= Quantity <= Final Amount/Item Cost
Therefore, a binary search algorithm should do the job.
A: Note that the overhead cost is a function of the quantity sold. That means that your equation is in a form that is easy to iterate. You make an initial guess as to the quantity, plug it into the right hand side of the equation, and use it to get a new guess at the quantity. Once the quantity stabilizes, you've reached a fixed point and can stop.
For the sheep-selling example with an economy of scale in the overhead, I'd begin by calculating the number of sheep assuming minimal overhead costs. This might be right, or it might overestimate. The number of updates needed for the process isn't clear in advance, but I'd expect rapid convergence.
Here's how it might look in Python written to be as pseudocode-like as I can make it:
import math
def overhead(n):
# Not given in problem, so I can't give an implementation
raise NotImplementedError("Sorry, don't know what this is")
def rhs(n, u, t):
return math.floor(t / (u + overhead(n)))
def best_quantity(unit_cost, total_cost, min_overhead):
prev_guess = 0
current_guess = math.floor(total_cost / (unit_cost + min_overhead))
while (current_guess != prev_guess):
prev_guess = current_guess
current_guess = rhs(current_guess, unit_cost, total_cost)
return current_guess
print best_quantity(50.0, 500.0, 0.0)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I parse non-English dates with DateTime strptime in Ruby? I am trying to parse dates exported from a CMS. Unfortunately with a Swedish locale set. The month names are abbreviated to three characters which makes a difference when it comes to the months May and October ("maj" vs. "May", and, "okt" vs. "Oct").
I would expect to use DateTime.strptime with correct locale set to solve this issue, like this:
require 'locale'
Locale.default = "sv_SE"
require 'date'
DateTime.strptime("10 okt 2009 04:32",'%d %b %Y %H:%M')
The date is however still parsed as it would be using abbreviated month names in English:
ArgumentError: invalid date
from lib/ruby/1.9.1/date.rb:1691:in `new_by_frags'
from lib/ruby/1.9.1/date.rb:1716:in `strptime'
from (irb):9
from bin/irb:16:in `<main>'
Question 4339399 touches on the same subject and links to a complex solution for fixing this.
Is there a more elegant solution to this? Is this even considered a bug in Ruby?
A: To be honest, since you only have two months that are different, I'd probably just gsub them:
DateTime.strptime("10 okt 2009 04:32".gsub(/okt/,'Oct'),'%d %b %Y %H:%M')
If you want you can put that into a small helper:
def swedish_to_english_date(date_string)
date_string.gsub(/may|okt/, 'may' => 'May', 'okt' => 'Oct')
end
DateTime.strptime(swedish_to_english_date("10 okt 2009 04:32"),'%d %b %Y %H:%M')
#=> #<DateTime: 110480161/45,0,2299161>
Edit: Note that the gsub with a hash as the second argument is a 1.9 thing, in 1.8 you can do something like
>> months = { 'may' => 'May', 'okt' => 'Oct' }
=> {"okt"=>"Oct", "may"=>"May"}
>> "may okt".gsub(/may|okt/) { |match| months[match] }
=> "May Oct"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Transfer always empty in php curl I've never worked with curl before so I'm trying to just set up something basic: query google.com and write it. This is what I have:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$buffer = curl_exec($curl_handle);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($curl_handle);
if ($curl_errno > 0) {
echo "cURL Error ($curl_errno): $curl_error\n";
} else {
if(empty($buffer)) {
echo "No data received.";
} else {
echo "Data received: $buffer\n";
}
}
?>
However, it's returning "No data received" every single time.
This is in Kubuntu 11.04 x64 with PHP version 5.3.5 and cURL version 7.21.3.
A: You are mixing your variable names $ch and $curl_handle. You can't do this. Be consistent ($ch is pretty standard):
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$buffer = curl_exec($ch); // Changed variable name here
$curl_errno = curl_errno($ch); // Removed duplicate line here
curl_close($ch); // Changed variable name here
?>
A: Fix this
$buffer = curl_exec($curl_handle);
to
$buffer = curl_exec($ch);
and also it should be,
curl_close($ch)
not $curl_handle. Btw, closing curl is not really necessary for what ur doing. But its a good practice nevertheless.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Node JS - Express JS -- TypeError: Object # has no method 'compile' I created a test code for using node(0.5.7), express(2.3.9) and ejs(1.0). Here is the sample code
core.js
var express = require('express');
var http = require('http');
var ejs = require('ejs');
var app = express.createServer();
app.set('views', __dirname + '/views');
app.set( "view engine", "ejs" );
app.get('/', function(req, res) {
res.render('index');
});
app.listen(8000);
console.log('Listening 8000');
Mentioned is the path where the ejs file lies --> views/index.ejs
I am getting the error "TypeError: Object # has no method 'compile'"
Can you please help me what solution would be the best applicable over here?
A: What might be wrong is that express version 2.3.9 is not comaptible with node version 0.5.7 (which is an unstable branch for 0.6.x series), therefore you should try it with stable version of node from 0.4.x series. From express docs:
Express 1.x is compatible with node 0.2.x and connect < 1.0.
Express 2.x is compatible with node 0.4.x and connect 1.x
Express 3.x (master branch) is compatible with node 0.6.x and connect
2.x
A: Make sure you follow these instructions when using express to create the skeleton project particularly the portion where you use npm install to install the dependencies.
Create the app:
$ npm install -g express
$ express /tmp/foo && cd /tmp/foo
Install dependencies:
$ npm install
Start the server:
$ node app
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting Twitter Follower's names iPhone SDK
Possible Duplicate:
Get twitter Follower in IOS 5
Is there a direct API for just getting followers' names?
I was looking through and found out "friends/ids" will return ids? But, I just want screen_name?
Am I supposed to parse ids first and then send to "users/lookup" to get screen_name?
Thanks
A: Your question can be answered by sifting through this page in the Twitter development documentation.
Most important from that page is
GET https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=twitterapi
You may parse the numeric IDs, but the above will return to you the numeric IDs first, if I'm not at all mistaken.
*Additionally, to answer your question, "[can I convert the Twitter numeric ID to their screen name?]"
According to the description in the docs found here:
GET users/show
Returns extended information of a given user, specified by ID or
screen name as per the required id parameter. The author's most recent
status will be returned inline.
So you can parse the returned data from this call as it suits your needs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Return results in Robot Framework keyword? How can I return the results after running a keyword?
Example:
mykey word [Arguments] input
${results}= getme input
But I want to use these results:
${results} = mykey word newinput
A: The Robot Framework user's guide describes how to return a value from a keyword. See User keyword return values.
The short version is: set a variable in your keyword, and use the [return] testcase setting to return that variable.
Here's an example:
*** Keywords ***
mykey word
[Arguments] ${input}
${string}= set variable the string is "${input}"
[return] ${string}
*** Test Cases ***
Call custom keyword and get result
${results}= mykey word newinput
Should be equal ${results} the string is "newinput"
Robot also provides several keywords to explicitly return a value from anywhere in a keyword:
*
*Return from keyword
*Return from keyword if
*Run keyword and return
*Run keyword and return if
*Run keyword and return status
A: Use [Return] to return results.
An example is:
Time Stamp
[Return] ${time_stamp}
${secs}= Get Time epoch
${time}= Get Time
${time_stamp}= Convert To String ${secs}
The value of ${time_stamp} will be stored in the Time Stamp keyword.
A: # This example will explain the usage of build in library keywords.
# The "Evaluate", "Log", and "Return" settings by using Fahrenheit to Centigrade
# conversion logic on the variable ${var1}.
*** Variables ***
${var1} 32
*** Keywords ***
Convert temperature Fahrenheit To Centigrade
[Arguments] ${ftemp}
${ftemp} = Convert To Number ${ftemp}
${ctemp} = evaluate (5 * (${ftemp} - 32))/9
[Return] ${ctemp}
*** Test Cases ***
Verify Temperature Conversion F to C
${result} = Convert temperature Fahrenheit To Centigrade ${var1}
Log ${result}
Should Be Equal As Numbers ${result} 0.0
A: A simple example may help:
*** Keywords ***
Convert temperature F To Centigrade
[Arguments] ${ftemp}
${ftemp} = Convert To Float ${ftemp}
${ctemp} = ${0.9} * ${ftemp} - ${32}
[Return] ${ctemp}
Convert temperature C To Fahrenheit
[Arguments] ${ctemp}
${ctemp} = Convert To Float ${ctemp}
${ftemp} = ${1.8} * ${ctemp} + ${32}
[Return] ${ftemp}
*** Test Cases ***
Verify Temperature Conversion
${result} = Convert temperature F To Centigrade ${32}
Should Be Equal ${result} ${0}
${result} = Convert temperature C To Fahrenheit ${0}
Should Be Equal ${result} ${32}
A: The easiest way is to use the suggested [Return] tag at the end of your keyword, though other ways exist.
Using the keyword Set Global Variable, you can make a variable accessible outside of the keyword it's run in without having to return anything from the keyword itself. This is useful if you want to avoid cluttering up your main variable list and have a few variables sitting in the background, but use it with as much caution as you would any global variable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: @ validation for email in BlackBerry I am developing a form where the user needs to enter a valid email. He/she will use it as a loginid to play the game.I want to know how can I validate the username containing @, similar to string.contains function. I learnt we can use string.indexOf() but it is not supporting "@". Kindly suggest how do I carry out this validation. When the email editfield loses focus, the username must be checked to see if it contains "@" or not.
A: please try to use EmailAdressEditField class
A: Use EmailAddressEditField.. here is the way
EmailAddressEditField email=new EmailAddressEditField("Email Address: ", "");
String address =email.getText();
int at = address.indexOf("@");
int len = address.length();
String host = address.substring(at + 1, len);
int dot = host.lastIndexOf('.');
len = host.length();
if (at <= 0 || at > len - 6 && dot < 0 || dot >= len - 3)
Dialog.alert("Invalid email");
else
{
if (host.indexOf("..") >= 0)
{
Dialog.alert("Invalid email");
}
else
{
//correct mail id.. continue your process
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: pattern matching using regex in groovy I have the below groovy code
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String myInput="License_All (12313)"
String myRegex="\\(\\d+\\)"
String ResultString
Pattern regex
Matcher regexMatcher
regex = Pattern.compile(myRegex, Pattern.DOTALL);
regexMatcher = regex.matcher(myInput);
List<String> matchList = new ArrayList<String>();
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
for(int i=0;i<matchList.size();i++)
{
myInput=myInput.replaceAll( matchList[i], '')
println matchList[i]
}
println myInput
It is supposed to remove (12313) part but instead it gives me the below output
(12313)
License_All ()
How do i remove all the bracket portion (12313)?
A: The matchList will contain the matched part, i.e. (12313). This one is then again taken as regular expression within replaceAll and therefore interpreted as group. Thus the brackets are not removed.
Instead you can use your regex directly in replaceAll:
myInput.replaceAll(myRegex, "")
A: Becaue you are using replaceAll, it is expecting a Pattern as the first element
myInput = myInput.replaceAll( Pattern.compile(myRegex, Pattern.DOTALL), '' )
Should do it...
As an aside, your original code can be made into more idiomatic Groovy (rather than basically Java) like so -- obviously, this has the same issue as in your original question, it's just a more Groovy way of writing code:
import java.util.regex.Pattern
String myInput = "License_All (12313)"
def regex = Pattern.compile( /\(\d+\)/, Pattern.DOTALL);
List<String> matchList = ( myInput =~ regex ) as List
matchList.each { m ->
myInput = myInput.replaceAll( m, '')
println m
}
println myInput
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error : An exception occured during a webclient request(FTP) - Powershell 2.0 I tried using this sample i got from a post here like :
I'm using powershell 2.0
$File = "D:\28.csv"
$ftp = "ftp://username:Pwd@IPAddress/in/28.csv"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $File..."
$webclient.UploadFile($uri,$File)
I'm trying to upload a file to an FTP server
But i keep getting the error:
Exception calling "UploadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At D:\Scripts\test.ps1:14 char:22
+ $webclient.UploadFile <<<< ($uri,$File)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
A: it will accept a string as the first parameter as well as System.Uri:
UploadFile Method byte[] UploadFile(string address, string fileName)
you could try this:
$webclient.UploadFile($ftp,$File)
Saw your comment after posting - you should edit you're question to include that info.
Have a look at this:
http://mycodetrip.com/2008/10/29/fix-for-error-the-requested-ftp-command-is-not-supported-when-using-http-proxy_118/
The gist:
After a bit of investigation, I found that the error was happening
because the method call from SQL Server was attempting to use the
HttpProxy on the Server machine. If the proxy is not set to null
explicitly in your code, then you will get this error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Problem with authenticating Username and password in my midlet I have modified the login in and implemented this instead.
public void login() {
HttpConnection c = null;
InputStream is = null;
StringBuffer str = new StringBuffer();
String url = "http://101.00.00.000/...../"
+ "?user=" + getUsername().getString().trim()
+ "&password=" + getPass().getString().trim();
try {
c = (HttpConnection) Connector.open(url);
is = c.openInputStream();
int len = (int)c.getLength();
int ch;
String getS = "";
while((ch = is.read()) != -1){
str.append((char)ch);
getS = str.toString();
String msg = "Login successful";
System.out.println(getS.substring(0, getS.length()));
if (getS.substring(0, 16).equals(msg)){
System.out.println(getS);
switchDisplayable(null, svgMenu.getSvgCanvas());
}else{
switchDisplayable(null, getAlert2());
// }
}
System.out.println(getS);
}
catch (IOException exception) {
try {
if (is != null)
is.close();
if (c != null)
c.close();
exception.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The response from the url on debugging gave a right answer that the login was successfull i.e in the commandline. But I noticed that the string comparison doesn't return a correct logic
i.e
if (getS.substring(0, 16).equals(msg)){
System.out.println(getS);
switchDisplayable(null, svgMenu.getSvgCanvas());
}
The if statement never gets to execute. What do I do.
A: You made a mistake on server side. Because you sending the string value of username and password from client side(mobile). you need to validate on server side. Before that you need to check if any white space on username and password on client side(mobile). use getUsername().getString().trim() and getPass().getString().trim() and also If need check the case sensitive.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Removing a line inside a from the DOM When I remove a line from a <pre> tag the rest of the lines below it don't move up like they would if using a standard <div> or any other element.
You can see an example of this at http://jsfiddle.net/NN6LC/
Has anybody encountered this issue before or knows how to resolve this?
A: You are removing the span, but the newline is still there.
And technically you are not even allowed to have <span>s in a <pre>.
From http://lib.ru/WEBMASTER/elements.html#PRE:
Elements Allowed Within...
elements <A> <HR> <BR> and parsed character data.
The way around it is to use a <div> instead of a <pre> and set styles on the div to make it look like a a <pre>.
EDIT: Someone else had posted the answer below, then deleted their answer. I do not know why, since it was a good answer. But this is how they did it:
If you don't care about <span>s not technically being allowed, you can manually remove it and the newline like this: http://jsfiddle.net/doktormolle/KgYyp/
function removeLine() {
var line=$('pre span.line_1');
if(line.length) {
if(line[0].nextSibling && line[0].nextSibling.nodeType == 3) {
line[0].parentNode.removeChild(line[0].nextSibling);
}
}
line.remove();
}
This will check for a newline after the element before removing it, and remove the newline too if it exists.
A: You must remove the linebreak after the line too.
http://jsfiddle.net/doktormolle/KgYyp/
A: What curious behaviour. Here's a way around it, but I admit it's not entirely satisfactory.
Add the following CSS:
pre {white-space: normal}
pre span {display: block}
See http://jsfiddle.net/tG8V6/ for a working version.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: System.OutOfMemoryException I'm appending string variable text, after appending a line throws System.OutOfMemoryException?
Can any one explain why it is throwing error.
str+="something Text"
str+="something Text"
and lastly I assign it to a lable text
When I assign the value of str it throws exception.....
A: I think you have two problems:
*
*You probably shouldn't be using <asp:Label> for the thing you're doing. Try <asp:Literal> instead or provide us with more information on exactly why you're using a label and what it is you want to accomplish (visually, or in HTML terms).
*You should build your string with System.Text.StringBuilder and not concatenate it with +=. This will improve performance and reduce memory usage, but since your exception seems to be occurring on label.Text = str;, just replacing the concatenation with StringBuilder won't solve the problem.
Say you have this ASP.NET markup:
<asp:Label id="MyLabel" runat="server" />
and this C# codebehind:
string str = String.Empty;
str += "Some text "
str += "some more text";
MyLabel.Text = str;
Try to replace both of these with:
<asp:Literal id="MyLiteral" runat="server" />
and
StringBuilder sb = new StringBuilder();
sb.Append("Some text ");
sb.Append("some more text");
MyLiteral.Text = sb.ToString();
Another option is to write directly to the output stream with Response.Write(). Without knowing exactly what it is you're trying to accomplish and why you have such a large string that you end up with an OutOfMemoryException, it's hard to help you any further than this, I'm afraid.
A: Probably you're trying to concatenate a lot of strings. Each time you change/concat strings a new string will be produced, because string is an immutable type.
Try using StringBuider to get your big-big string :)
var builder = new StringBuilder();
builder.Append("something Text");
builder.Append("something else");
builder.Append("etc.");
builder.ToString();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to check that installed application is mine? I want to publish a donation stab application (as Minimalistic Text does). As I understand I can check in my main free application that this donation application is installed through PackageManager:
try
{
ApplicationInfo info = getPackageManager()
.getApplicationInfo("com.myproject", 0 );
//-- application exists
} catch(PackageManager.NameNotFoundException e) {
//-- application doesn't exist
}
But in fact anyone can provide their own free application with the same package name. How can I receive evidence that this application is truly mine?
A: If you sign both apps with the same key/certificate, you can check for a signature match. Assuming only you have access to the private key, if they match, it is your own app. Something like:
String myPackageName = application.getPackageName();
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo("com.myproject", 0);
boolean isMine = pm.checkSignatures(myPackageName, pi.packageName) == PackageManager.SIGNATURE_MATCH;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: how to obtain HTML-free contents for non-div tags I want to find the HTML-free content of all the tags except for tags inside <div id="nav">
For example, with the following HTML:
<div id="nav">
<h1>Navigate!</h1>
<nav role="navigation">
<h2 class="structural">Main navigation</h2>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about/">About</a></li>
</ul>
</nav>
<div id="inside_nav">
<ul>
<li><a href="/">inside_home</a></li>
<li><a href="/about/">inside_About</a></li>
</ul>
</div>
</div>
Code:
div = soup1.find("div", id="nav")
def match_only_non_divs(tag):
return (tag.findParent("div").get('id') == div.get('id')) and tag.name != "div"
print div.findAll(match_only_non_divs, text=True)
This code should output:
[u'\n', u'Navigate!', u'Main navigation',
u'Home', u'About', u'\n']
BUT! it is actually outputting:
[u'\n', u'Navigate!', u'Main navigation',
u'Home', u'About', u'\n',
u'inside_home', u'inside_About', u'\n']
The code should not walk inside the inner div (id="inside_nav") but it is going inside that.
Please help !!
A: Two alternatives for you:
print [t.string for t in div.findAll(match_only_non_divs)]
# [u'Navigate!', None, u'Main navigation', None, None, u'Home', None, u'About']
print [t.string for t in div.findAll(match_only_non_divs) if t.string]
# [u'Navigate!', u'Main navigation', u'Home', u'About']
A: As for the cause of the problem, here is what doc says regarding text keyword:
If you use text, then any values you give for name and the keyword arguments are ignored.
So, findAll is basically ignoring match_only_non_divs in div.findAll(match_only_non_divs, text=True). You should get the text after you do the matching (as John Keyes suggested).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to set key font size in gnuplot? How to set key(legend) font size in gnuplot?
I read the gnuplot introduction file and find no related configuration about this property. I can set font type and size for labels, tics, but only key can not be set the font?
A: The font for the key can be set in gnuplot 4.4. For example:
set key font ",20"
would set the size of the font to 20.
A: For older gnuplot versions like 4.2, you can do:
set terminal enhanced font "Helvetica,18"
It will apply to any textual labels in the terminal.
A: You can also set and unset key font depending on your needs, for example, I needed a title and label bigger than the sizes of the tag labels inside the plot:
set terminal svg size 300, 480\
set termoption enhanced\
set key font "Times New Roman, 18"\
....\
unset key\
set key font "Times New Roman, 14"\
plot '' ... title "Cd-4d". **<--** This is smaller than the other labels
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
}
|
Q: How can I get tab notifications in chrome extension, so that the extension can show desktop alert each time when new notification arrives Is it possible to read the tab notifications (facebook, twitter, gmail etc shows a notification count) through a google chrome extension. So that I can display an desktop alert whenever a new notification arrives.
A: You could do this by periodically checking the titles of all relevant tabs, extracting the current notification number (if available) and notifying the user if a change in the number of notifications is detected.
However, depending on how often you perform this check the user will likely notice before you. An alternative approach would be to use content scripts to inject JavaScript (again, only to relevant pages - facebook etc) that listens to changes in the page's title element and sends a message to your background page when one is detected which should then display a desktop notification.
I didn't know if this would work originally as I wasn't aware that title changes could be listened to but a quick Google provided this answer;
how to listen for changes to the title element?
So all you should need to do is change the code in that question's answer to send a message to your background page instead of showing an alert. For example;
function titleModified() {
chrome.extension.sendRequest({
title: document.title
});
}
The background page must have an onRequest listener that would then attempt to parse the title received and determine whether or not a notification has been made.
Remember to correctly setup the permissions in your manifest in order to inject the JavaScript when your users are on the target sites as well as using desktop notifications.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Why use the params keyword? I know this is a basic question, but I couldn't find an answer.
Why use it? if you write a function or a method that's using it, when you remove it the code will still work perfectly, 100% as without it. E.g:
With params:
static public int addTwoEach(params int[] args)
{
int sum = 0;
foreach (var item in args)
sum += item + 2;
return sum;
}
Without params:
static public int addTwoEach(int[] args)
{
int sum = 0;
foreach (var item in args)
sum += item + 2;
return sum;
}
A: With params you can call your method like this:
addTwoEach(1, 2, 3, 4, 5);
Without params, you can’t.
Additionally, you can call the method with an array as a parameter in both cases:
addTwoEach(new int[] { 1, 2, 3, 4, 5 });
That is, params allows you to use a shortcut when calling the method.
Unrelated, you can drastically shorten your method:
public static int addTwoEach(params int[] args)
{
return args.Sum() + 2 * args.Length;
}
A: params also allows you to call the method with a single argument.
private static int Foo(params int[] args) {
int retVal = 0;
Array.ForEach(args, (i) => retVal += i);
return retVal;
}
i.e. Foo(1); instead of Foo(new int[] { 1 });. Can be useful for shorthand in scenarios where you might need to pass in a single value rather than an entire array. It still is handled the same way in the method, but gives some candy for calling this way.
A: Adding params keyword itself shows that you can pass multiple number of parameters while calling that method which is not possible without using it. To be more specific:
static public int addTwoEach(params int[] args)
{
int sum = 0;
foreach (var item in args)
{
sum += item + 2;
}
return sum;
}
When you will call above method you can call it by any of the following ways:
*
*addTwoEach()
*addTwoEach(1)
*addTwoEach(new int[]{ 1, 2, 3, 4 })
But when you will remove params keyword only third way of the above given ways will work fine. For 1st and 2nd case you will get an error.
A: It allows you to add as many base type parameters in your call as you like.
addTwoEach(10, 2, 4, 6)
whereas with the second form you have to use an array as parameter
addTwoEach(new int[] {10,2,4,6})
A: One danger with params Keyword is, if after Calls to the Method have been coded,
*
*someone accidentally / intentionally removes one/more required Parameters from the Method Signature,
and
*one/more required Parameters immediately prior to the params Parameter prior to the Signature change were Type-Compatible with the params Parameter,
those Calls will continue to compile with one/more Expressions previously intended for required Parameters being treated as the optional params Parameter. I just ran into the worst possible case of this: the params Parameter was of Type object[].
This is noteworthy because developers are used to the compiler slapping their wrists with the much, much more common scenario where Parameters are removed from a Method with all required Parameters (because the # of Parameters expected would change).
For me, it's not worth the shortcut. (Type)[] without params will work with 0 to infinity # of Parameters without needing Overrides. Worst case is you'll have to add a , new (Type) [] {} to Calls where it doesn't apply.
Btw, imho, the safest (and most readable practice) is to:
*
*pass via Named Parameters (which we can now do even in C# ~2 decades after we could in VB ;P), because:
1.1. it's the only way that guarantees prevention of unintended values passed to Parameters after Parameter order, Compatible-Type and/or count change after Calls have been coded,
1.2. it reduces those chances after a Parameter meaning change, because the likely new identifier name reflecting the new meaning is right next to the value being passed to it,
1.3. it avoids having to count commas and jump back & forth from Call to Signature to see what Expression is being passed for what Parameter, and
1.3.1. By the way, this reason alone should be plenty (in terms of avoiding frequent error-prone violations of the DRY Principle just to read the code not to mention also modify it), but this reason can be exponentially more important if there are one/more Expressions being Passed that themselves contain commas, i.e. Multi-Dimensional Array Refs or Multi-Parameter Function Calls. In that case, you couldn't even use (which even if you could, would still be adding an extra step per Parameter per Method Call) a Find All Occurrences in a Selection feature in your editor to automate the comma-counting for you.
1.4. if you must use Optional Parameters (params or not), it allows you to search for Calls where a particular Optional Parameter is Passed (and therefore, most likely is not or at least has the possibility of being not the Default Value),
(NOTE: Reasons 1.2. and 1.3. can ease and reduce chances of error even on coding the initial Calls not to mention when Calls have to be read and/or changed.))
and
*do so ONE - PARAMETER - PER - LINE for better readability (because:
2.1. it's less cluttered, and
2.2. it avoids having to scroll right & back left (and having to do so PER - LINE, since most mortals can't read the left part of multiple lines, scroll right and read the right part)).
2.3. it's consistent with the "Best Practice" we've already evolved into for Assignment Statements, because every Parameter Passed is in essence an Assignment Statement (assigning a Value or Reference to a Local Variable). Just like those who follow the latest "Best Practice" in Coding Style wouldn't dream of coding multiple Assignment Statements per line, we probably shouldn't (and won't once "Best Practice" catches up to my "genius" ;P ) do so when Passing Parameters.
NOTES:
*
*Passing in Variables whose names mirror the Parameters' doesn't help when:
1.1. you're passing in Literal Constants (i.e. a simple 0/1, false/true or null that even "'Best Practices'" may not require you use a Named Constant for and their purpose can't be easily inferred from the Method name),
1.2. the Method is significantly lower-level / more generic than the Caller such that you would not want / be able to name your Variables the same/similar to the Parameters (or vice versa), or
1.3. you're re-ordering / replacing Parameters in the Signature that may result in prior Calls still Compiling because the Types happen to still be compatible.
*Having an auto-wrap feature like VS does only eliminates ONE (#2.2) of the 8 reasons I gave above. Prior to as late as VS 2015, it did NOT auto-indent (!?! Really, MS?!?) which increases severity of reason #2.2.
VS should have an option that generates Method Call snippets with Named Parameters (one per line of course ;P) and a compiler option that requires Named Parameters (similar in concept to Option Explicit in VB which, btw, the requirement of was prolly once thought equally as outrageous but now is prolly required by "'Best Practices'"). In fact, "back in my day" ;), in 1991 just months into my career, even before I was using (or had even seen) a language with Named Parameters, I had the anti-sheeple / "just cuz you can, don't mean you should" / don't blindly "cut the ends of the roast" sense enough to simulate it (using in-line comments) without having seen anyone do so. Not having to use Named Parameters (as well other syntax that save "'precious'" source code keystrokes) is a relic of the Punch Card era when most of these syntaxes started. There's no excuse for that with modern hardware and IDE's and much more complex software where readability is much, Much, MUCH more important. "Code is read much more often than is written". As long as you're not duplicating non-auto-updated code, every keystroke saved is likely to cost exponentially more when someone (even yourself) is trying to read it later.
A: Using params allows you to call the function with no arguments. Without params:
static public int addTwoEach(int[] args)
{
int sum = 0;
foreach (var item in args)
{
sum += item + 2;
}
return sum;
}
addtwoEach(); // throws an error
Compare with params:
static public int addTwoEach(params int[] args)
{
int sum = 0;
foreach (var item in args)
{
sum += item + 2;
}
return sum;
}
addtwoEach(); // returns 0
Generally, you can use params when the number of arguments can vary from 0 to infinity, and use an array when numbers of arguments vary from 1 to infinity.
A: No need to create overload methods, just use one single method with params as shown below
// Call params method with one to four integer constant parameters.
//
int sum0 = addTwoEach();
int sum1 = addTwoEach(1);
int sum2 = addTwoEach(1, 2);
int sum3 = addTwoEach(3, 3, 3);
int sum4 = addTwoEach(2, 2, 2, 2);
A: One more important thing needs to be highlighted. It's better to use params because it is better for performance. When you call a method with params argument and passed to it nothing:
public void ExampleMethod(params string[] args)
{
// do some stuff
}
call:
ExampleMethod();
Then a new versions of the .Net Framework do this (from .Net Framework 4.6):
ExampleMethod(Array.Empty<string>());
This Array.Empty object can be reused by framework later, so there are no needs to do redundant allocations. These allocations will occur when you call this method like this:
ExampleMethod(new string[] {});
A: Might sound stupid,
But Params doesn't allow multidimensional array.
Whereas you can pass a multidimensional array to a function.
A: Another example
public IEnumerable<string> Tokenize(params string[] words)
{
...
}
var items = Tokenize(product.Name, product.FullName, product.Xyz)
A: It enhances code brevity. Why be lengthy when you can be concise?
using System;
namespace testingParams
{
class Program
{
private void lengthy(int[] myArr)
{
foreach (var item in myArr)
{
//...
}
}
private void concise(params int[] myArr) {
foreach (var item in myArr)
{
//...
}
}
static void Main(string[] args)
{
Program p = new Program();
//Why be lengthy...:
int[] myArr = new int[] { 1, 2, 3, 4, 5 };
p.lengthy(myArr);
//When you can be concise...:
p.concise(1, 2, 3, 4, 5);
}
}
}
If you remove the keyword params, the caller code will not work as desired.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "361"
}
|
Q: How to move Activity to mapActivity in android application I have one application. I need to display map view when we click on button. Actually this button is in one class and google map is in another class. Now when i click on that button , In android Emulator it displays message android application stopped unexpectedly.
A: Posting some code will help. Make sure you have extended the second activity as MapActivity. Also, the emulator must be google-maps emulator and not the normal ones. Depending on your SDK, create the new AVD and choose GoogleMaps API. I think that should solve the problem
A: Make sure you have put
<uses-library android:name="com.google.android.maps" />
in your AndroidManfiest file
A: These examples may help you to understand why you are getting the error msg ,and both are doing same (call one map activity class from another...)
http://eagle.phys.utk.edu/guidry/android/mappingDemo.html
http://eagle.phys.utk.edu/guidry/android/mapOverlayDemo.html
Donot forget to add your map activity in the manifest.xml :
A: *
*Like @Nipuna Silva said , add a
<uses-library android:name="com.google.android.maps" />
in your AndroidManfiest.xml. Inside the <application> node.
*Try Project->clean in your Eclipse to rebuild your project.
*Answers in this question May help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Log 4j referencing input I would like to reference input on my log 4j properties file such that when it recieves an input command externally it looks it up on a list and acts accordingly.
This is how it looks like:
log4j.appender.R.File=/home/oracle/conf/ATL_${log_file_name}/ATL_${log_file_name}.dlg
where ${log_file_name} is an integer passed on the d-switch
now the integer is referenced to the list:
1-Food
2-Fruits
3-Vegetables
such that when ${log_file_name} is 1, the command will become:
log4j.appender.R.File=/home/oracle/conf/ATL_food/ATL_food.log
how can I set this on the properties file?
A: There is no such feature for the log4j properties file.
However, you can add a file appender to the root logger programmatically, see the example below:
import java.io.IOException;
import org.apache.log4j.*;
public class LogTest {
public static void main(String args[]) throws IOException {
String category = System.getProperty("logCategory");
Logger rootLogger = Logger.getRootLogger();
PatternLayout layout = new PatternLayout("%d{ISO8601} [%t] %-5p %c %x - %m%n"); // replace with your layout
String logFileName = "/home/oracle/conf/ATL_" + category + "/ATL_" + category + ".dlg";
rootLogger.addAppender(new FileAppender(layout, logFileName, false));
}
}
You pass a VM parameter -DlogCategory=food on the command line. You can do a numeric replacement yourself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Readonly textbox for WPF with visible cursor (.NET 3.5) I need my textbox to be read-only. However, when I set the IsReadOnly to true, then the user can no longer interact with the textbox using the keyboard since the cursor no longer appears.
In .NET 4 there is a IsReadOnlyCaretVisible property, however, I am forced to use .NET 3.5.
Is there a good solution?
Thanks!
A: I've ended it doing it myself using an attached property, it does the following:
*
*Disables all input and modification to the textbox using keyboard
*Sets the context menu to have Copy only
*Disables cut/paste commands
*Disables modification using mouse selection & dragging
*Changes the bacgrkound color of the textbox to notify it being read-only.
Usage:
<TextBox AttachedProperties:ReadOnlyModeWithCursor.IsModeEnabled="True">
This textbox has some long text and it can't be edited.
</TextBox>
The class:
public static class ReadOnlyModeWithCursor
{
public static readonly DependencyProperty IsModeEnabledProperty = DependencyProperty.RegisterAttached("IsModeEnabled",
typeof(bool),
typeof(ReadOnlyModeWithCursor),
new FrameworkPropertyMetadata(OnModeEnabledChanged));
private static ContextMenu _contextMenuWithCopyOnly = new ContextMenu();
static ReadOnlyModeWithCursor()
{
_contextMenuWithCopyOnly.Items.Add(new MenuItem { Command = ApplicationCommands.Copy });
}
public static bool GetIsModeEnabled(TextBox textBox)
{
if (textBox == null)
{
throw new ArgumentNullException("textBox");
}
return (bool)textBox.GetValue(IsModeEnabledProperty);
}
public static void SetIsModeEnabled(TextBox textBox, bool value)
{
if (textBox == null)
{
throw new ArgumentNullException("textBox");
}
textBox.SetValue(IsModeEnabledProperty, value);
}
private static void NoCutting(object sender, ExecutedRoutedEventArgs e)
{
if (e.Command == ApplicationCommands.Cut)
{
e.Handled = true;
}
}
private static void NoDragCopy(object sender, DataObjectCopyingEventArgs e)
{
if (e.IsDragDrop)
{
e.CancelCommand();
}
}
private static void OnModeEnabledChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
var textBox = (TextBox)dependencyObject;
var isEnabled = (bool)e.NewValue;
if (isEnabled)
{
textBox.PreviewTextInput += textBox_PreviewTextInput;
textBox.PreviewKeyDown += textBox_PreviewKeyDown;
DataObject.AddPastingHandler(textBox, Pasting);
DataObject.AddCopyingHandler(textBox, NoDragCopy);
CommandManager.AddPreviewExecutedHandler(textBox, NoCutting);
// Default context menu has cut & paste, we want only copy.
textBox.ContextMenu = _contextMenuWithCopyOnly;
// Remove if you want to set the style of readonly textboxes via styles
textBox.Background = new SolidColorBrush(Color.FromRgb(240, 240, 240));
}
else
{
textBox.PreviewTextInput -= textBox_PreviewTextInput;
textBox.PreviewKeyDown -= textBox_PreviewKeyDown;
DataObject.RemovePastingHandler(textBox, Pasting);
DataObject.RemoveCopyingHandler(textBox, NoDragCopy);
CommandManager.RemovePreviewExecutedHandler(textBox, NoCutting);
textBox.ClearValue(TextBox.ContextMenuProperty);
textBox.ClearValue(TextBox.BackgroundProperty);
}
}
private static void Pasting(object sender, DataObjectPastingEventArgs e)
{
e.CancelCommand();
}
private static void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
//pressing space doesn't raise PreviewTextInput, reasons here http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/446ec083-04c8-43f2-89dc-1e2521a31f6b?prof=required
if (e.Key == Key.Space || e.Key == Key.Back || e.Key == Key.Delete)
{
e.Handled = true;
}
}
private static void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = true;
}
}
A: use both of these in your XAML
IsReadOnly="True"
IsReadOnlyCaretVisible="True"
IsReadOnlyCaretVisible only works when the first property is being used.
A: You could try extracting the templates from .NET 4.0, and use them in your .NET 3.5 application.
Hopefully you can use it without too many adjustments.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: How to determine whether T is a value type or reference class in generic? I have a generic method behavior of which depends on T is reference type or value type. It looks so:
T SomeGenericMethod <T> (T obj)
{
if (T is class) //What condition I must write in the brackets?
//to do one stuff
else //if T is a value type like struct, int, enum and etc.
//to do another stuff
}
I can't duplicate this method like:
T SomeGenericMethod <T> (T obj) where T : class
{
//Do one stuff
}
T SomeGenericMethod <T> (T obj) where T : struct
{
//Do another stuff
}
because their signatures are equal. Can anyone help me?
A: [The following answer does not check the static type of T but the dynamic type of obj. This is not exactly what you asked for, but since it might be useful for your problem anyway, I'll keep this answer for reference.]
All value types (and only those) derive from System.ValueType. Thus, the following condition can be used:
if (obj is ValueType) {
...
} else {
...
}
A: Type.IsValueType tells, naturally, if Type is a value type. Hence, typeof(T).IsValueType.
A: try this:
if (typeof(T).IsValueType)
A: I'm late to the party, but I just stumbled on this.
So as of determining if it's a Reference-Type,
typeof(T).IsClass
respectively
obj.GetType().IsClass
could work (.net 4.7+ , not checked on former Versions)
A: You can use the typeof operator with generic types, so typeof(T) will get the Type reference corresponding to T, and then use the IsValueType property:
if (typeof(T).IsValueType)
Or if you want to include nullable value types as if they were reference types:
// Only true if T is a reference type or nullable value type
if (default(T) == null)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "61"
}
|
Q: mac os x lion configuration problem with gitosis I'm trying to setup gitosis on my mac mini with mac os x lion (clean install).
Basically a followed this guide
I also looked at this question
If I try to clone the gitosis-admin.git repo i get the following error:
git clone git@127.0.0.1:gitosis-admin.git
Cloning into gitosis-admin...
Assertion failed: (argv0_path), function system_path, file exec_cmd.c, line 30.
error: git-shell died of signal 6
fatal: The remote end hung up unexpectedly
I also tried to use localhost, the ip or the remote ip.
One thing i noticed, if i try to login as my git user (a standard mac user, without password) trough ssh i can't login (makes sens), but if I set a password I thought I should get an answer like
PTY allocation request failed on channel 0
Connection to gitserver closed.
but I can login like normal.
I've been searching for around a week, and a found no result in the internet with this error...
Edit:
One thing, I also installed gitosis on my macbook pro, following the same instructions and it worked! What am I missing?
A: okay strange, I figured out... Somehow I've to specify the complete path from the git user's home direcotry:
git clone git@host:repositories/gitosis-admin.git
with this command I can clone the directory
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: radio buttons and php and thanks in advance for offering your time for reading this.
I am newbie with PHP and i am doing a project for the university.
Until now for adding boolean values i have used checkboxes. For example in my db i have a boolean record called DB_FOR_SALE that i am updating using this piece of code...
HTML part
<input type="checkbox" name="DB_FOR_SALE" value="1"<#DB_FOR_SALE#>>For>For Sale
PHP part
/* Update of a Record */
if($_REQUEST['DB_ID'] != '')
{
$objectid = $_REQUEST['DB_ID'];
$upd = "update " . G_DB_PREFIX . "OBJECTS set DB_FOR_SALE='" . $_REQUEST['DB_FOR_SALE'] . "' where DB_ID='" . $_REQUEST['DB_ID'] . "'";
$gupd = $conn->update($upd, G_NORMDB);
In the same way i can enter the value if the object is inserted for the first time.
How can i use that in the radio buttons case, since they have the same name.
Thanx for reading this!!
A: The value attribute of the selected radio button will be submitted as the value for the set with the give name.
A: This worked for me:
HTML:
<html>
<body>
<form method="POST" action="someaction.php">
<input type="radio" name="group1" value="1"> For Rent<br>
<input type="radio" name="group1" value="2" checked> For Sale<br>
<input type="submit" value="submit">
</form>
<body>
</html>
PHP:
Selection:
<?php
echo $_POST['group1'] == 1 ? "For Rent" : "For Sale";
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to combine two NSString? I have the following two NSString:
NSString *latitudeString, *longitudeString;
latitudeString = @"50.1338";
and
longitudeString = @"8.91583";
What I want to obtain is a NSString that looks like this: 50.1338,8.91583.
How do I obtain that?Thanks
IMPORTANT: The values I showed are only for the purpose of better understanding, ussually latitudeString and longitudeString have random values.
A: Just use stringWithFormat method
[NSString stringWithFormat:@"%@,%@", latitudeString, longitudeString];
A: To get what you want you can use
NSString *coordinates = [NSString stringWithFormat:@"%@,%@", latitudeString, longitudeString];
A: A thousand years late:
[latitudeString stringByAppendingFormat:@",%@", longitudeString]
Would slightly reduce runtime parsing costs and, historically, would have given you greater type safety (before the compiler checked type strings). So some of us old timers got used to it and still mentally make the fairly feeble performance argument to justify what's comfortable.
[@[latitudeString, longitudeString] componentsJoinedByString:@","]
May also be preferable if you'd rather raise an exception upon one string being missing than silently produce something nonsensical.
A: Try this
NSString *combine = [NSString stringWithFormat:@"%@,%@", latitudeString, longitudeString];
A: Maybe it was better:
[NSString stringWithFormat:@"%.4f,%.4f",[latitudeString floatValue],[longitudeString floatValue]];
A: String* coord = [NSString stringWithFormat:@"%@,%@", latitudeString, longitudeString];
A: [NSString stringWithFormat:@"%@,%@",latitudeString,longitudeString];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: How to monitor a group of twitter accounts Here's what I'm trying to do. I have a list of twitter users (2-3000) whose tweets I need to monitor for keywords.
I thought of two solutions to implement that but don't think any is optimal.
1- Create a private list on twitter, add all the accounts i want to monitor and use the list api to get all the tweets
2- use the search or stream api to monitor all of twitter for my keywords and then cross check on my side with the list of users i have.
Are these the only ways to do it? any idea on how to be more efficient?
One thing to keep in mind, I need to keep the list of accounts I'm monitoring private. Every account holder can know he is followed but can't know who else is.
A: Yes. This is how I would do it:
1) create an account on twitter that will follow all these people
2) I presume you have this list of people stored somehow, parse/grep/format that data so you have a list of all their user_ids
3) create an twitter application for you to use
4) download you favorite languages most popular twitter library
5) authenticate your user with your application
6) create a simple little program that reads your list from 2 and works it's way through following those users. Put a sleep between these calls as you will be subject to rate limiting.
6) create a simple little program that reads your list from (2) and works it's way through adding each user to a private list, creating a new private list each time you hit the 500 cap. These calls are subject to rate limiting, so stagger or batch the calls over the required time window
7) now you simply query your timeline via the API and you are away.
Key thing is 2, if you have that list in some digital format(text file,database,someone else's followers) or somehow is able to calculated (read:avoid manual search and follow) , this should be a breeze.
I use java, you could do everything in my steps + your filtering requirements with scribe (auth library) and gson (Json parser) in a couple methods. In terms of cleanliness and efficiency, I think this fits the brief.
A: You can use the stream API to follow multiple accounts, too, with the follow parameter, and then search by keyword on your end. That would be a lot more efficient.
You can also follow people with GET statuses/user_timeline, although it's only one user at a time. You can get 200 posts back in the past though.
I would do the streaming API, but also write some code to use user_timeline, in case your streaming receiving thing ever goes down you'll be able to quickly get anything you missed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: System.Management.ManagementClass.GetInstances() throws exception On different machines, we see different exceptions.
One machine reports
System.Runtime.InteropServices.COMException (The RPC server is
unavailable. (Exception from HRESULT: 0x800706BA))
Another reports
System.BadImageFormatException ( An attempt was made to load a program
with an incorrect format. (Exception from HRESULT: 0x8007000B))
Yet another reports
System.InvalidCastException (Specified cast is not valid.)
What causes this and what's the correct fix?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Django: configuring multiple domains for a website? how can i manage in django multiple domains? Our website will be configured like this
jobs.site.com
cars.site.com
homes.site.com
jobs.site.co.uk
cars.site.co.uk
....
and so on. basically, we will have three third level domains (jobs,cars,homes) and some country specific domains.
i'm actually working locally with urls like "localhost/uk/jobs/" but when we're going live we should use jobs.site.co.uk instead...
i really have no clue, nor i know what i should search on google, can somebody please provide me a brief but full "howto" to configure my settings (or full django app) to do exactly what i need?
thanks in advance!
A: If they share the same code or database, you will have to retrieve the subdomain name creating your own subdomain middleware.
Have a look to this http://thingsilearned.com/2009/01/05/using-subdomains-in-django/
A: It depends on how you run your Django projects, but to me it looks like xyz.site.com could be different projects. If they all share the same code, see the second paragraph below.
Take a look at the Django "sites" framework if you need to distinguish between different hosts within a single Django project (like jobs.site.co.uk and jobs.site.com).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to disable data connections(3g/gprs) on android
Possible Duplicate:
How to disable Mobile Data on Android
I know that this is possible in version 2.2 and below but since 2.3 it is not possible, unless you have a application that has a certificate supplied by google that specifies it as a secure application or if you place your application in the /system/app directory. I have attempted to place the application in the system/app dir and found this to be impossible on the emulator even with su rights. How would I make my application secure for android market (so google will give me the certificates required) or install the application to the system/app dir. The only other possibility is to use the ndk, but i am not so sure if it will work and the time and effort that would have to go in to hack around this will just be a pain. Can some one assist in the problem.
A: Disabling 3G using methods provided by the SDK is not possible, anyway I think I remember a solution where the APN was set to a invalid one to kind of disable 3G
EDIT:
I just figured out that APNDroid uses exactly this renaming-workaround to disable the 3G connection.
Here you can browse the source code of the application
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create database in Android without context? I know how to create database with context,but how to create it without context?
It's fine Like this:
SQLiteDatabase db = SQLiteDatabase.create(null);
but it creates a database in memory while I need create the database in file.
So I use
SQLiteDatabase.openOrCreateDatabase("/data/data/appname/databases/temp.db", null),it always throw SQLiteException:unable to open database file.
Can somebody help me?It drives me crazy.
A: As far as i know file handling needs to be happen with the support of Activity (context). I think its not in the level our (developers) control to change the way android does it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Split Result from SQL Query For example this SQL statement returns 1k rows
SELECT * FROM tableName WHERE someCondition
my question is: is it possible by using WHERE
1) Split Resultset to the 10 partial resultsets, then
*
*1st. would be returns 0% - 10%,
*2nd. 10% - 20%,
*etc..
2) cuts range between 50 - 150th rows
A: If you are using oracle database this is very simple.
you can use ROWNUM keyword to achive this task in following manner..
select * from
(
select tb.*,rownum t_count from table_name tb
) ss
where ss.t_count >= @min_value and ss.t_count <= @max_value
where @min_value and @max_value is the range for what you want to get data...
actually it will work on concept of inner query and temprory tables.
that's why it will give good performance over fatching all the data in one shot.
A:
my question is: is it possible by using WHERE
My answer is: yes, it is possible.
One of the solutions would be to use the MOD function.
The MOD function returns the remainder of one number divided by another and the function accepts two arguments:
MOD(dividend,divisor)
*
*dividend is a literal number or a numeric expression to divide.
*divisor is a literal number or a numeric expression by which to divide the dividend.
In particular, dividing the data into ten parts, in your example, would look like this:
SELECT * FROM tableName WHERE mod(INDEX_ID, 10) = 1
SELECT * FROM tableName WHERE mod(INDEX_ID, 10) = 2
SELECT * FROM tableName WHERE mod(INDEX_ID, 10) = 3
SELECT * FROM tableName WHERE mod(INDEX_ID, 10) = 4
SELECT * FROM tableName WHERE mod(INDEX_ID, 10) = 5
SELECT * FROM tableName WHERE mod(INDEX_ID, 10) = 6
SELECT * FROM tableName WHERE mod(INDEX_ID, 10) = 7
SELECT * FROM tableName WHERE mod(INDEX_ID, 10) = 8
SELECT * FROM tableName WHERE mod(INDEX_ID, 10) = 9
SELECT * FROM tableName WHERE mod(INDEX_ID, 10) = 0
INDEX_ID is index from table_name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Django Try Except Not Working I have this code,
try:
print "what"
newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact = nameAndNumberStore[0])
print newClassName
except:
print "HAHA"
This always prints "HAHA", despite the fact that I've run the newClassName = ... code in console and it's worked.
Why is this happening?
EDIT
def newGetAllInformation(searchTerm):
nameAndNumberStore = modifySearchTerm(searchTerm)
urlStore = modifyUrl(nameAndNumberStore) # need to make the change here -- why not I go to the site, check for Course name - if that is not there switch, if it is then scrape
soup = getHtml(urlStore)
storeOfBooks = []
storeOfBooks = scrape(soup,nameAndNumberStore)
print nameAndNumberStore[0]
try:
newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact = nameAndNumberStore[0])
nameAndNumberStore = modifySearchTerm(newClassName.departmentName + " " + nameAndNumberStore[1])
urlStore = modifyUrl(nameAndNumberStore)
soup = getHtml(urlStore)
storeOfBooks = scrape(soup,nameAndNumberStore)
except:
print "HAHA"
return storeOfBooks
EDIT
After further investigation - that is, entering a valid code manually (which worked), I think that there's something up with taking the code from the array- despite the fact that both are the same data type (string).
so newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact = "econ") works from file, but newClassName = CourseNameAndCodeAssocition.objects.get(departmentCode__iexact = nameAndNumberStore[0]),where nameAndNumberStore[0] holds econ
A: Change it to:
except CourseNameAndCodeAssociation.DoesNotExist:
Each model you create gets its own DoesNotExist exception that extends core ObjectDoesNotExist exception.
Also the best approach is to only use try … except around the precise line that you expect to fail. A more pythonic way to write what you have there would be:
department_code = name_and_number_store[0]
class_names = CourseNameAndCodeAssociation.objects.all()
try:
new_class_name = class_names.get(departmentCode__iexact=department_code)
except CourseNameAndCodeAssociation.DoesNotExist:
print "HAHA"
else:
search_term = u'%s %s' % (new_class_name.departmentName,
name_and_number_store[1])
name_and_number_store = modify_search_term(search_term)
url_store = modify_url(name_and_number_store)
soup = get_html(url_store)
store_of_books = scrape(soup, name_and_number_store)
Please also note that the convention in Python is to use lowercase_underscored_names for variables, attributes and function names and CamelCaseNames for class names (instance names are either variables or attributes).
A: Please modify the code to this, run it and tell us what exception you are getting:
try:
print "what"
newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact = nameAndNumberStore[0])
print newClassName
except Exception as e:
print "HAHA"
print e
Also, it would probably help to have a debugger installed on your box. I can recommend Eclipse in combination with PyDev, but that is a personal choice. There are lots of great options out there.
Eclipse IDE - download the basic Java version of 120MB
then install this plugin on top of it - Pydev
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Regular expression - only digits, dots,commas and first character should be $ I would like to have a regex for the following expression
$123,456,789
$1.23
$123
what i have done so far is if use enter 123456789 i will convert this to dollar format as follows $123,456,789.00
But i would like to valid the above values if he enters in a text box. I would like to allow only . with the numeric values. The $ symbol will come after my conversion but at the time of leaving i would like to validate the text box as per the requirement any idea please
A: \$(\d{1,3},)*(\d{1,3})(\.\d+)?
A: try this:
^\$\d{1,3}(,\d{1,3})*(\.\d+)?$
A: My proposal (untested):
\$(\d{1,3})(,\d{3})*(\.\d+)?
we require a dollar, followed by a up to 3 digits.
then there might come more exactly 3-digit long groups.
at the end there might be a comma followed by at least one digit (or no comma and no digits)
A: Try this
^\$?\d{1,3}(?:,\d{3})*(?:\.\d{1,2})?$
See it here online on Regexr
The $ at the start is optional. The 1 to 3 digits, then can be groups of 3 digits separated by commas, at last an optional 1 or two digit fraction.
Important are the anchors ^ and $ they ensure, that the complete string is matched and not only a part of the string.
Bugfix: Also important, the . needs to be escaped, to be matched literally, I added this to my Regex.
Extension
If the , are not mandatory and you want also e.g. 1000 to be valid, I added an alternation to my regex:
^\$?(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d{1,2})?$
See it here online on Regexr
A: Why not to use common approach for formatting and use appropriate IFormatProvider? Have no idea why do you need regex here...
public static string GetFormattedCurrency(decimal value)
{
var formatInfo = new NumberFormatInfo
{
CurrencyDecimalSeparator = ".",
CurrencyGroupSeparator = ",",
CurrencyGroupSizes = new[] { 3 },
CurrencySymbol = "$"
};
return value.ToString("C", formatInfo);
}
A: How about this
[$]?(?:\d\,?){0,}(?:\.\d*)?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Local variable or a pointer Given a class in a any random C++ framework, how do you know if you have to create a simple object on stack or a pointer to an object on heap?
Assume a function which accepts argument in the form of a reference(&) variable. The caller can pass a local variable to it or a pointer too(*ptr). The called function may or may not copy dat from the passed object.
This question is a followup of my previous question related to C++ Bada development.
A: In general, every well-designed C++ library will allow both. In most cases the library doesn’t care where the caller allocates memory, since the caller handles its own memory. If the library has additional requirements (e.g. that it takes over possession of a pointer) then it will carefully document this.
Furthermore, as a general guideline, avoid pointers and freestore memory. C++ is designed with stack objects in mind. If there is no compelling reason to use something different, then don’t. new should be used only very sparingly in your code, and delete should never be used – that is, always let your allocated memory be handled in an automatic fashion (smart pointers).
A: How you create the object depends on what you intend to do with.
If you create an object using new statement, you get a pointer to a manually allocated object. This object will live as long as it isn't deallocated manually, using delete.
If you create a simple object on stack, it remains as long as the current stack is used, that is to say as long as the scope doesn't change.
Common library such as the STL will allow both objects.
If the library has special requirements, it must be documented somewhere, and explained mainly because it want to own the object.
A: There's no such thing as a "simple object". An object is an object is an object.
What matters is the object lifetime: automatic (scoped), dynamic (manual) or static (permanent).
As much as you can, and unless you have a really, really good reason to do otherwise, use objects with automatic lifetime.
If you think about how one object may depend on another, you'll see that if you only ever use automatic objects, then you won't have a problem with dangling references (or "references to local variable"), because the dependent object will have more deeply nested scope than the referenced object.
You should have a very convincing argument why a particular object must have manual lifetime. These situations happen, of course, but they should be abstracted and factored away. For example, most standard library containers do of course require manual management of their elements, but all that is handled by the container, so that the user can just use an container object of automatic lifetime and all is well. Finally, if you decided that you really must manage an object's lifetime manually, then use a single-responsibility resource managing class like shared_ptr or unique_ptr to pass a handle to that object around -- the handler classes are now automatic again, and once they go out of scope, they release the managed object for you. You get the best of both worlds: the benefits of manual object allocation and scoped responsibilities.
If you follow these ideas methodically, you should find that you will only very rarely create dynamic objects yourself, and if you do, then there's a single line of code that's relevant (this gives you "locality"); for example, auto p = std::make_shared<T>(a,b,c);, or std::unique_ptr<T> p(new T(a,b,c));. A simple grep for new on all your source code can easily audit whether all your dynamic allocations are handled responsibly.
A: There are a bunch of things to consider. Lifetime, the need for polymorphism, references and performance are all things to think about when deciding whether or not to use a pointer.
As others have said, stack space has scope lifetime. Once the variable goes out of scope, it's done. The memory allocated through a pointer will persist until delete is called on it, but remember the pointer itself will go out of scope still! So make sure to keep a reference somewhere!
As for polymorphism, using stack space kind of makes that not possible due to the slicing problem. So if you need to use this technique, stick with a pointer.
References should be an obvious one. Do you need to move the same memory around to various places in the program? Do multiple things need to access the EXACT same piece of memory, and not just a copy?
Last, performance. Will using heap memory give you a performance hit? Pointers are slower because of the extra need for allocation time. They also require a bit extra memory to store the pointer itself (insignificant really, but you might as well consider it anyway. Really depends on your application).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Where to place Unix Domain (AF_UNIX) sockets' end points (files)? Is there a convention where to place the 'files' representing the end points to Unix Domain Sockets?
I tend to put them to /tmp/some-application-specific-subdir-name/, but I wonder if there is a more common place.
The background is, that POSIX is not clear about the maximum path length to access such 'files':
The size of sun_path has intentionally been left undefined. This is because different implementations use different sizes. For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size of 104. Since most implementations originate from BSD versions, the size is typically in the range 92 to 108.
Applications should not assume a particular length for sun_path or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
So this "restriction" on the path's length should be kept out of the application's file/path name configurations.
A: On Ubuntu, the netstat command shows UNIX Domain Sockets in multiple different places. Some, however a few, in /var/run, as JB suggested; most of them in @/tmp/… (I believe the @ designate abstract names, which is Linux specific), and some others in various application's specific places. So in practice, the most common location seems to be in /tmp, at least on Ubuntu, which is a rather common platform. Note the /tmp location particularly makes sense here, as UDS has to be created by each bind and to be deleted afterwards (either when the socket is closed, or when the application exit, or when the application starts the next time and before its next invocation to bind).
A: The FHS says: /run
(It used to be /var/run.)
A: In Android you can place it in /dev/socket/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
}
|
Q: XSD date types with minOccurs set to 0 now has a value of "Forgive me in advance if I don't provide enough information, this is an issue I am seeing and tasked with fixing but I did not personally write this code originally (the person who did has moved on).
We are using Apache XMLBeans to generate some Java classes from a set of XSDs. Our web application then generates a web HTML form to create instances of these classes (or modify fields of existing classes). To put this into some context; one of our XSDs represents a person. We can then use our generic form generation code to generate an HTML form for a user to supply information about a particular person. There a number of date attributes associated with a person, e.g. date of birth.
I have made some substantial changes recently to the project's structure and dependencies, but nothing directly related to the code the generates these Java classes and HTML form from them. Before these changes were made everything worked, now, all of the date fields have a value of <xml-fragment uid="theAttributesId"/> if they have not had any value set. In the XSDs, these date attributes/elements have the minOccurs attribute set to 0 (and hence should be optional). If I set the attribute nillable to true for each one the probably no longer exists.
Having spent some time debugging I can see that an empty date value is not a valid value unless nillable is true. In the XMLBeans class XmlObjectBase the validate method returns false for null date fields. What I don't understand is what has changed and why is there now a need for the nillable attribute. Dependencies have changed but having compared XMLBean versions they all seem the same:
We have three jars in our web app's lib directory that contain the class XmlObjectBase; tika-app-0.7, xbeans-2.2.0 and xmlBeans-2.3.0. All versions are identical to the lib directory before the massive restructure. The XSD files haven't changed. What has?
I have found the following links which helped in my investigations so far:
*
*https://issues.apache.org/jira/browse/XMLBEANS-220
*nillable and minOccurs XSD element attributes
*http://www.dimuthu.org/blog/2008/08/18/xml-schema-nillabletrue-vs-minoccurs0/
*http://www.ibm.com/developerworks/xml/library/ws-tip-null/index.html
I have accepted that maybe the only realistic way of solving this issue without vasts amount of time is to add the nillable attribute. However, I am not keen to add it for all date elements in the XSDs. Fortunately I have 3 date base types defined that all date elements are. I have tried modifying the base types' default nillable attribute to true without success:
Original NonFutureDateBaseType:
<xs:complexType name="nonFutureDateType">
<xs:simpleContent>
<xs:extension base="cr:nonFutureDateBaseType">
<xs:attribute name="uid" type="xs:int" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
(where cr:nonFutureDateBaseType is a simple type with a restriction of the standard XSD date type)
New with attempted nillable default as true:
<xs:complexType name="nonFutureDateType">
<xs:simpleContent>
<xs:extension base="cr:nonFutureDateBaseType">
<xs:attribute name="uid" type="xs:int" />
<xs:attribute name="nillable" type="xs:boolean" default="true" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
Anyone have any suggestions as to why the above doesn't work? Or what else I should look into?
Apologies for the lengthy question (and lack of formatting - I have no SO images/icons for some reason) and thanks in advance.
More Detail Edit
I've just been looking in the database at the XML that represents a person. I have something like this:
<PERSON>
...
<BIRTH_DATE uid="12"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:nil="true" />
...
</PERSON>
And then the value of BIRTH_DATE evaluates to <xml-fragment uid="theAttributesId"/>. Wtf? From what I have read that should mean it evaluates to ''. Hmmm...
Another Edit:
I'm getting seriously fed up with this issue so have started investigating the differences between the latest web app and the one running the earlier codebase. The major difference I see when debugging is this:
New codebase: invoking java.beans.PropertyEditorSupport.getValue() returns
<xml-fragment uid="12"/>
Old codebase: invoking java.beans.PropertyEditorSupport.getValue() returns
<xml-fragment uid="12" xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
Between my JSP that generates the form and the setter for the value, there are a lot of Spring classes. The key difference between the new codebase and the old (working) codebase is the Spring version.
The new codebase depends on spring-context-3.0.5.RELEASE, whereas the old depends on spring-context-2.5.6.SEC02.
Any suggestions would greatly appreciated!
A: Nillable is not something you implement yourself. It's part of the XSD definition.
xsi:nil="true" is used to indicate that the an instance of a field has no value.
nillable="true" is used to indicate that the schema definition of the field allows no value.
Or have I missed the point?
A: Having done a significant amount of debugging, I have an answer - I now know what the difference between the two versions is:
The Spring class org.springframework.web.servlet.tags.form.ValueFormatter has a slight difference between version 2.5.6.SEC02 and 3.0.5.RELEASE.
The implementation of the method getDisplayString differs between the two versions:
2.5.6.SEC02 (Working correctly in my application)
if (propertyEditor != null && !(value instanceof String)) {
try {
propertyEditor.setValue(value);
return getDisplayString(propertyEditor.getAsText(), htmlEscape);
}
catch (Throwable ex) {
// The PropertyEditor might not support this value... pass through.
return getDisplayString(value, htmlEscape);
}
}
else {
return getDisplayString(value, htmlEscape);
}
3.0.5.RELEASE (Display the XML fragment if no date value is set):
if (propertyEditor != null && !(value instanceof String)) {
try {
propertyEditor.setValue(value);
String text = propertyEditor.getAsText();
if (text != null) {
return getDisplayString(text, htmlEscape);
}
}
catch (Throwable ex) {
// The PropertyEditor might not support this value... pass through.
}
}
return getDisplayString(value, htmlEscape);
The text returned from propertyEditor.getAsText() always returns null for me when the date has no value and hence the 'value' property is used. I believe the issue is actually in some code in my application (the custom XmlBaseTypePropertyEditor is as fault it seems) and I pressume there is no issue with the Spring change.
Sorry for wasting anyone's time. Thanks anyway.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: LinkedIn auth request page in iFrame? Has anyone any experience with LinkedIn? I'm trying to put their auth request (the allow this application to access my...) page in an iFrame and load it into my page.
However, immediately after loading - it reloads itself into the entire window. Does anyone know if this is deliberately blocked... I thought it wasn't possible for the child iFrame to do such a thing?
Appears this is relevant Using JS how can I stop child Iframes from redirecting or at least prompt users about the redirect but this redirects to another page you request, no stops the iframe reloading.
A: We don't want you to do this. We want people to be able to see the URL in their browser, so they know it's not a phishing attempt. Otherwise, anyone could just create a fake page and redirect people to it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Float comparison gives different results Look at the following two codes, and tell me the reason why answers vary a lot.
#include<stdio.h>
int main() {
float a = 0.9;
if(a<0.9)
printf("hi"); // This will be the answer
else
printf("bye");
return 0;
}
And if we change 0.9 to 0.8, then else's statement is printed:
#include<stdio.h>
int main() {
float a = 0.8;
if(a<0.8)
printf("hi");
else
printf("bye");//this will be the answer
return 0;
}
So why this output changes when we just change a single digit?
A: The literals 0.9 and 0.8 have type double. Since both values cannot be represented exactly, they will in fact be 0.9000000000000000222... and 0.8000000000000000444....
When stored in the float (single precision) variable a they will be converted to single and become even more inaccurate: 0.89999997... and 0.8000000119....
For the comparison with the literal double value they are converted back to double retaining the more inaccurate value.
As you can see from the numbers above, the comparison yields different results for 0.9 and 0.8.
All this is assuming your platform has IEEE754 floats which is most probably the case.
You can see single/double representations of numbers at www.binaryconvert.com.
A: This error is due to floating point accuracy and because you are comparing a float type with a double value. Try to compare it versus floating point literals: if(a<0.8f)
I suggest you read the according wikipedia article, it explains in detail why your error happens.
A: You have to know how floating points works.
Floating points are represented by using powers of two, each digit is used to represent 2^-x where X is the n-th digit.
For example, 0.011 (binary) would be 2^-2 + 2^-3, which is 0.25 + 0.125 = 0.375
Now try to represent 0.9. You are in trouble, since no power of two to represent it. The value this is represented in 32-bits and probably 64-bits machines will give a result slightly smaller than 0.9, whereas for 0.8 the result is precise and representable by powers of two.
You can try this out by opening a python prompt. Try and type a few numbers, eventually one will end with ...99999999.
A: According to the C Standard:
6.3.1.5 Real floating types
1) When a float is promoted to double or long double, or a double is
promoted to long double, its value is unchanged.
2) When a double is demoted to float, a long double is demoted to double
or float, or a value being represented in greater precision and range
than required by its semantic type (see 6.3.1.8) is explicitly
converted to its semantic type, if the value being converted can be
represented exactly in the new type, it is unchanged. If the value
being converted is in the range of values that can be represented but
cannot be represented exactly, the result is either the nearest higher
or nearest lower representable value, chosen in an
implementation-defined manner. If the value being converted is outside
the range of values that can be represented, the behavior is undefined.
The standard can be found here.
A: First of all, as others mentioned, use values like 0.8f when working with floats.
Also, floating point == comparison is something you would want to avoid because of the precision of this operation in the FPU. What always worked best for me, was to define a margin, let's say 1e-6f (or the precision you need based on your application) and instead of this:
if (LHS == RHS)
you write:
if (LHS-RHS < MARGIN && RHS-LHS < MARGIN)
You could write a function (if you are a c++ fan) or macro (if you are a c fan (here comes the -1s)) that does this for you.
A: This is due to rounding errors, to see the value of that you are using insert a printf before the if:
printf("a=%f\n", a);
A: Try this:
Instead of "if(a<0.9)" compare using "if(a<0.9f)"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Existing engine for bouncing balls? I'm looking at creating a game which involves many bouncing balls on the screen, and the user can sortof select one of those balls and take it out...
The balls should be able to bounce of eachother and the walls.
I've tried implementing this from scratch, following the tutorials at http://www.tonypa.pri.ee/vectors/tut11.html - but it's not quite working for me, and if I need the game to become more complicated- probably best to use an existing engine.
So is there an existing engine that will work very fast and well for this sort of thing? At a glance- it didn't seem like box2d or flixel would work for this... but what do you say?
A: There are many physics engine out there. Take a look at APE. It's a bit old but very simple an efficient.
A: Bouncing grabbable balls on a screen? Box2d for Flash could definitely do that.
*
*http://www.box2dflash.org/
*http://www.kerp.net/box2d/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get random object from Array I want to get random object from array, is there any way how can I find random object from mutable array?
A: id obj;
int r = arc4random() % [yourArray count];
if(r<[yourArray count])
obj=[yourArray objectAtIndex:r];
else
{
//error message
}
A: id randomObject = nil;
if ([array count] > 0){
int randomIndex = arc4random()%[array count];
randomObject = [array objectAtIndex:randomIndex];
}
A: @interface NSArray (Random)
- (id) randomObject;
@end
@implementation NSArray (Random)
- (id) randomObject
{
if ([self count] == 0) {
return nil;
}
return [self objectAtIndex: arc4random() % [self count]];
}
@end
A: The best way would be to do something like this
int length = [myMutableArray count];
// Get random value between 0 and 99
int randomindex = arc4random() % length;
Object randomObj = [myMutableArray objectAtIndex:randomindex];
A: Just Copy and Paste
-(NSMutableArray*)getRandomValueFromArray:(NSMutableArray*)arrAllData randomDataCount:(NSInteger)count {
NSMutableArray *arrFilterData = [[NSMutableArray alloc]init];
for(int i=0; i<count; i++){
NSInteger index = arc4random() % (NSUInteger)(arrAllData.count);
[arrFilterData addObject:[arrAllData objectAtIndex:index]];
[arrAllData removeObjectAtIndex:index];
}
return arrFilterData;
}
Note: Count = number of random values you want to fetch
A: Here's a Swift solution using an extension on Arrays:
extension Array {
func sample() -> Element? {
if self.isEmpty { return nil }
let randomInt = Int(arc4random_uniform(UInt32(self.count)))
let randomIndex = self.startIndex.advancedBy(randomInt)
return self[randomIndex]
}
}
You can use it as simple as this:
let digits = Array(0...9)
digits.sample() // => 6
If you prefer a Framework that also has some more handy features then checkout HandySwift. You can add it to your project via Carthage then use it exactly like in the example above:
import HandySwift
let digits = Array(0...9)
digits.sample() // => 8
A: If you don't want to extend NSArray this will get a random value from a given array in one line:
id randomElement = [myArray objectAtIndex:(arc4random() % myArray.count)];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Javascript - Can't determine if JSON object contains true I have a JSON object I'm retrieving from a server, sometimes its really simple such as:
{ "urls": ["http://google.com", "http://bing.com"] }
However I need to check if urls['tasks']['ipv6'] contains true, the code I'm using is:
if (urls['tasks']['ipv6'] === true) {
console.log('true');
}
But because urls['tasks'] doesn't exist I get the following error:
Uncaught TypeError: Cannot read property 'ipv6' of undefined
Is there an easy way to do this? I'm having a really hard time find a solution online. I've also tried jQuery's $.isEmptyObject and would be happy with a jQuery based solution. For reference I'm actually using this code in node.js.
A: This should do the trick for you.
if (urls["tasks"] && urls["tasks"]["ipv6"] && urls["tasks"]["ipv6"] === true)
{
...
}
You can add urls checking at left as well if you need to and you can omit the middle check urls["tasks"]["ipv6"], because if it's undefined it definitely isn't true.
The thing is that you have to check first whether upper level properties exist before drilling down. And since Javascript (as well as majority of today's languages) doesn't use full boolean evolution this works.
A: if (urls && urls["tasks"] && urls["tasks"]["ipv6"] === true) {
console.log("true");
}
A: check the typeof before you check for true or false...
if(typeof(urls['tasks']) != "undefined")
{
if(typeof(urls['tasks']['ipv6']) != "undefined")
{
if(urls['tasks']['ipv6'] === true)
{
console.log("I am true & I exist");
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Checking a list of objects against another list of objects I have a user profile that contains a manytomany field which points to a set of favorite objects.
I have a queryset that returns an set of those types of objects, independent of the favorites (though it may contain favorites).
What I want to do is this:
{% for object in objects %}
<p>{% if user.get_profile.favorites contains object %} Unfavorite {% else %} Favorite {% endif %}</p>
{% endfor %}
But thus far, I cannot find an easy to way do this. Ideas?
A: in
A: Have you tried object in user.get_profile.favorites?
In any case, do your processing in your views, not in your templates.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: how can i use local storage for storing values of multiple variables? How can i use local storage for storing values of multiple variables ? is there any limit for local storage. which all browsers currently support local storage ?
A: Here is a good discussion regarding HTML5 Local storage limits
HTML5 localStorage size limit for subdomains
Regarding browsers, here is a list,
Firefox 3.5, Safari 4, IE8, Chrome 4+: HTML5 localStorage; these modern browsers all support the core localStorage functionality defined in the HTML5 draft.
Firefox 2.x and 3.0: Gecko globalStorage, a very early implementation similar to HTML5’s localStorage.
Safari 3.1 & 3.2: HTML5 Database Storage, because Safari 3.1 and 3.2 don’t support HTML5 localStorage.
IE6, IE7: userData persistence, a rarely used IE feature for associating string data with an element on a web page and persisting it between pageviews.
Google Chrome Pre 4: Gears Database API, which is built into earlier versions of Chrome and thus doesn’t require a separate install.
Here is alist of browsers that support this functionality.
https://stackoverflow.com/questions/1194784/which-browsers-support-html5-offline-storage
There is no limit for the number of variables, a detailed explanation for using HTML5 local storage can be found here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: UTF-8 not supported message from logging subsystem, Fuse ESB 4.4 I've upgraded my ServiceMix to Fuse ESB 4.4 compilation. I got, however, errors from logging system, which I can't find how to handle.
The error message is:
Warning: encoding "UTF-8" not supported, using UTF-8
The encoding UTF-8 is NOT used. Files are encoded in Windows-1250 encoding (characters from that set are correctly converted, others are, of course, not available).
I've found discussion about similar problem here on StackOverflow, where there was identified a problem with Xerces parser, however without a clue, how to solve it in this particular case. Had anyone dealt successfully with it?
A: The problem is that something is attempting to access the UTF-8 character set (probably via Charset.forName("UTF-8")) which is attempting to instantiate a class in a package sun.nio.cs.UTF_8.
Although this will exist in the runtime of a JVM with no class loader constraints, in an OSGi runtime the code will fail.
The solution will be to modify the bundle that's generating this error message with the following:
Import-Package: ...,sun.nio.cs;resolution:=optional
That means that should it attempt to instantiate a class in that package, it should be able to find it - however, if it's not present (say, because you are using a different runtime) then it will still work.
Note that this implies the System.bundle is exporting the sun.nio.cs package, which you can do by generating a Fragment (see http://wiki.osgi.org/wiki/Fragment) or by having the system bundle export the sun.nio.cs package with the org.osgi.framework.system.packages property.
Either way, it sounds like something that the logging bundle should fix rather than something you'd need to fix - have you reported the bug upstream?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: simple object-oriented JavaScript example I'm learning OO JavaScript (again). I've written this simple object
function circle(){
this.radius = 4;
}
circle.prototype.area = function(){
this.radius * this.radius * 3.14;
};
var c = new circle();
c.area();
The value returned by c.area() is undefined. I guess this can only because this.radius is not returning 4, why not?
A: radius has the value of 4, but the area method doesn't return any value.
circle.prototype.area = function(){
return this.radius * this.radius * 3.14;
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: css() function call failing silently? I am having a strange problem with the css() function. Here's my code snippet.
console.log('' + $(this).css('left') + ':' + $(this).css('top'));
console.log('Desired position - ' + return_to_left + ':' + return_to_top);
$(this).css('top', return_to_top + 'px');
$(this).css('left', return_to_left + 'px');
console.log('Finally: ' + $(this).css('left') + ':' + $(this).css('top'));
The output I get on the console is this.
458px:2113px
Desired position - 448px:2102px;
Finally: 458px:2113px;
Could anyone suggest why this might be happening? I have tried experimenting with '!important'. Doesn't help.
(Also, for context, this code is part of a callback function after an animation. It tries to position the element back to where it was before animation began.)
Thank you for your help.
A: Found the problem!!
This:
console.log('Desired position - ' + return_to_left + ':' + return_to_top);
Outputs...
Desired position - 448px:2102px;
therefore your variables return_to_left and return_to_top ALREADY have the px string at the end.
Your css call looks like this:
$(this).css('top', '448pxpx');
$(this).css('left', '2102pxpx');
Which won't work! :p Remove the + 'px' from the end of the css calls.
A: return_to_left and return_to_top already includes 'px' but you are appending it a second time.
$(this).css('top', return_to_top );
$(this).css('left', return_to_left );
A: I tried the code you posted.
It worked.
Is it possible that in your variables return_to_left and return_to_top already a "px" is?
i put this in the variable:
return_to_left = 100;
it worked.
I think your content will be saved dynamic.
So if you load the infos via
$(this).css('left')
then there will be already a "px"
try this code instead of yours:
$(this).css('top', return_to_top);
$(this).css('left', return_to_left);
i dont know your complete code but maybe this will resolve your problem
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Dynamically adding input controls with validators to a view I have a registration page, which asks for some data from the user, e.g. email address. Administrators should be able to customize the form. For example, he may be interested in the birthplace of the user, in which case an additional textbox should appear in the registration form.
Because the fields in the form are so dynamic, I can not add these as properties to the viewmodel. How can I add input controls and validators to the view at runtime?
A: You can create a model class for your dynamic form using a collection. For example:
public class MyParam {
public string Name {get; set;}
public string Value{get; set;}
}
public class MyDynamicForm {
public List<MyParam> parameters {get; set;}
}
Than you can create a view that build the form using a loop on the parameters. To validate the input parameters, you need to develope a validation method that receive in input the FormCollection and validate every parameter by Name.
A: I solved this in the following less-than-optimal way:
In my view, I loop through my custom attributes and call an extension method on the HtmlHelper to render the Html:
foreach (var attribute in group.Attributes)
{
<tr>
<td>
@attribute.Name
</td>
<td>
@Html.ValidationMessage(attribute.Id)
@Html.AttributeEditor(attribute)
</td>
</tr>
}
In the AttributeEditor() method, I set the unobtrusive Javascript validation attributes to enable client-side validation:
if (IsRequired)
{
attributes["data-val-required"] = MvcCompaniesResources.UserProfileValidatorMessages.RequiredField;
attributes["data-val"] = "true";
}
This gives client side validation, and works well with @Html.ValidationMessage(). However, I would still need to implement server-side validation separately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Performing CUDA in LabVIEW I want to perform CUDA operation in LabVIEW to transfer multiple files in GPU in parallel and then perform arithmetic operations on GPU and then save the data in new file. I learnt that in order to perform operations in GPU, we need to create a DLL file and then import it to LabVIEW but I don't know how. Can you give me some example of a similar operation?
A: Here is the link that you might find interesting:
LabVIEW GPU Computing
A: LabVIEW has no support of CUDA, as you said. Calling DLL in LabVIEW is quite easy, Use the Call Library Function node for this purpose.
Even easier, once you've written the dll, have LabVIEW generate VI wrappers around your DLL by entering the wizard in Tools menu -> Import -> Shared library
See also this article that explains things quite extensively.
A: NI should also has a set of CUDA VIs available on their site. I don't know if those would help in your case, since you already seem to have the C code, but it might.
A: Yes, NI can provide support. Please join this community group. There is a library that you can install so you can have CUDA support in LabVIEW. Also, please post questions to this community group for help if needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: how to map multiple OBJECTS to one object using AutoMapper - asp.net mvc 3 Hi All / very new to Auto-Mapper. i can map one to one objects but was wondering is it possible to map multiple objects to one object or multiple objects to multiple objects?
consider i have a following scenario...
User Model
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Company Company { get; set; } // 1 user work in 1 company
}
Company Model
public class Company
{
public string CompanyName { get; set; }
public string Website { get; set; }
public ICollection<User> Users { get; set; } // 1 Company can have many users
}
UserCompanyViewModel
i want to show List of users with their company details in one view..
public class UserCompanyViewModel
{
public ICollection<User> Users { get; set; }
ppublic ICollection<Company> Companies { get; set; }
}
Now, is it possible to map in this situation and if yes, i can show in one view and when editing that view i want to map again with the updated fields back to their respective Models.
any help would be appreciated...thx
A: In this case, are you really using multiple (types of) objects as your source? It looks like from your defined problem that your source is a list of users - judging by "i want to show List of users with their company details".
If that's the case, whilst you can't do it implicitly you can use a TypeConverter to perform the map easily enough:
Mapper.CreateMap<ICollection<User>, UserCompanyViewModel>()
.ConvertUsing<UserCompanyViewModelConverter>();
Then define your converter as:
public class UserCompanyViewModelConverter : ITypeConverter<ICollection<User>, UserCompanyViewModel>
{
public UserCompanyViewModel Convert(ResolutionContext context)
{
UserCompanyViewModel model = new UserCompanyViewModel();
ICollection<User> sourceUsers = (ICollection<User>)context.SourceValue;
model.Users = sourceUsers;
model.Companies = sourceUsers.Select(u => u.Company).Distinct().ToList();
return model;
}
}
Then when you want to map you just take your collection of users someUsers and map it:
UserCompanyViewModel model = Mapper.Map<ICollection<User>, UserCompanyViewModel>(someUsers);
If you really do need to map multiple source types into a single destination type, it looks like this blog post includes a short Helper class that will help you. In short, AutoMapper doesn't quite support this so you will be making a couple of Map requests to fill up your ViewModel. You will need to use another TypeConverter to make sure that the second call doesn't replace the Companies added by the first.
A: you can use modelMapper
@Autowired
private ModelMapper modelMapper;
and in function
Desination desination = modelMapper.map(obj1, Desination.class);
modelMapper.map(obj2, desination);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Content Based Routing in Apache HTTP Server I am have a requirement wherein I need to route between two platforms based on the element value of the incoming xml requests.
If the text for the element is like: <name>Websphere</name> then I need to route the message to host1.
If the text for the element is like: <name>oracle</name> then I need to route the request to host2.
host1 and host2 are two instances of weblogic application servers. There is a apache http server in front of these two weblogic instances.
The xml element (<name>) is in the content of the xml message and not as a part of the URL.
Please advice whow this can be achieved in apache http server.
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# Embedded FTP Server I'm searching a library which allows me to embed a FTP Server in a C# application.
I've only very basic needs:
*
*Have the possibility to have at least one user/password
*Have an event on which I can register when someone has sent a file
*Need to configure the port/directory
*I need it to works with framework .Net 2.0
*Not too expensive
For the FTP, I only need they can send a file.
I've already made some research:
*
*http://www.codeguru.com/csharp/csharp/cs_network/sockets/article.php/c7409
--> tested, but no command are working, I can't even list the content of the folder
*http://www.c-sharpcorner.com/UploadFile/psingh/FTPServerinCSharp11162005015958AM/FTPServerinCSharp.aspx --> Is just awful: I've saw that thread relative to the server and the client are coded in the same file
*http://www.remobjects.com/ip.aspx --> Didn't understand how to make something with this internet package, if I install it and start the demo applicatin, I've several failures which makes me impossible to test it
*http://sourceforge.net/projects/csftpserver/ --> Cannot download anything
*http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=0a7606f3-f8ec-4e39-8d0e-517248b7164c --> not accessible
*http://forum.junowebdesign.com/general-programming/27873-%5Bc-%5D-ftp-server.html
--> event when logged, I can't download the file
So is something existing for doing this like this??? Something you can recommend. I don't need to have great performances, ...
Thank you very much
A: FTPSBlackbox package of our SecureBlackbox product (.NET edition) lets you create both simple and sophisticated FTP and FTPS (FTP-over-SSL) servers. Components have only managed code and let you use any socket class you want (including our sockets, which support various proxies).
If you need SFTP server in future, we have one as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Parsing complex XML in PHP5 Hello this is my first post.
i'm trying to parse an xml using php, but i'm stuck with it
example of my xml :
<xml xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
xmlns:rs='urn:schemas-microsoft-com:rowset'
xmlns:z='#RowsetSchema'>
<s:Schema id='RowsetSchema'>
<s:ElementType name='row' content='eltOnly' rs:CommandTimeout='30'>
<s:AttributeType name='ows_LinkTitle' rs:name='Phone Number*' rs:number='1'>
<s:datatype dt:type='string' dt:maxLength='512' />
</s:AttributeType>
<s:AttributeType name='ows_GSM_x0020_PUK' rs:name='GSM PUK' rs:number='2'>
<s:datatype dt:type='string' dt:maxLength='512' />
</s:AttributeType>
</s:ElementType>
</s:Schema>
<rs:data>
<z:row ows_LinkTitle='628558621183' ows_GSM_x0020_PUK='41016732'/>
<z:row ows_LinkTitle='628558621181' ows_GSM_x0020_PUK='21783670'/>
</rs:data>
</xml>
i'm trying to get the value from each of 'z:row'
Any help is very appreciated. Thanks
i'm trying this code and it doesnt work
$xml_all = simplexml_load_string($xmlnya);
echo '<ol>';
foreach ($xml_all->xml->rs->z as $zrow)
{
echo '<li> ows_LinkTitle: '.$zrow['ows_LinkTitle'];
echo '</li>';
}
echo '</ol>';
A: The snippets below assume the (fixed) XML document is a string in $xml.
SimpleXML
$xml = simplexml_load_string($xml);
$rows = $xml->children('rs', TRUE)->data->children('z', TRUE)->row;
foreach ($rows as $row) {
$attributes = $row->attributes();
$link_title = (string) $attributes->ows_LinkTitle;
$gsm_puk = (string) $attributes->ows_GSM_x0020_PUK;
var_dump($link_title, $gsm_puk);
}
To read: SimpleXML usage, SimpleXMLElement::children(), SimpleXMLElement::attributes().
DOM
$doc = new DOMDocument;
$doc->loadXML($xml);
$rows = $doc->getElementsByTagNameNS('#RowsetSchema', 'row');
foreach ($rows as $row) {
$link_title = $row->getAttribute('ows_LinkTitle');
$gsm_puk = $row->getAttribute('ows_GSM_x0020_PUK');
var_dump($link_title, $gsm_puk);
}
To read: DOMDocument::getElementsByTagNameNS(), DOMElement::getAttribute().
A: When you get your xml fixed, you should have a look at the simpleXML documentation and specifically the xpath method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How i can use the SQLDATE in codeigniter php? Can you explain below line? pls give some example.
strtotime(SQLDATE." +1 month")
A: This is not specific to CodeIgniter, it's a generic PHP function:
From the docs:
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC)
Also, regarding the relative date/time format:
Format: number space? (unit | 'week')
Handles relative time items where the value is a number.
Example: "+5 weeks", "12 day", "-7 weekdays"
So your example:
SQLDATE = '2011-10-28';
strtotime(SQLDATE. "+1 month");
will return the Unix timestamp for the date 1 month after the 28th October 2011.
A: Simply put you are just adding 1 month to the value of the date in SQLDATE. So in your example, the value that strtotime will return is 1 month after 2011-10-28 which is 2011-11-28.
Strtotime returns the number of seconds since the epoch. The return values of strtotime will make more sense if you format it:
php > define("SQLDATE",'2011-10-28');
php > echo date("Y-m-d",strtotime(SQLDATE));
2011-10-28
php > echo date("Y-m-d",strtotime(SQLDATE . "+1 month"));
2011-11-28
php >
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Add weighted average line to flot point chart? I have a scatter (point) chart in jQuery's Flot.
I'd like to add a weighted average line to the point chart, as you can do in Excel charts. (Or a logarithmic or similar "line of best fit" would be acceptable, actually.)
Is this possible in Flot?
I can't see anything about it in the docs, but perhaps someone here knows how.
Thanks!
A: No this isn't something Flot does itself.
You can work out your own line of best fit by doing some simple calculations on your data. You can then plot the result using Flot. The link contains a worked example but is not Flot specific.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Please explain Zeromq eventloop How is different from multiplexing several sockets via a POLLIN?
while True:
socks = dict(poller.poll())
if socks.get(control_receiver) == zmq.POLLIN:
...
if socks.get(work_receiver) == zmq.POLLIN:
...
How can it make listener threads more reliable and easier to handle?
Background: I am rolling my own API server and wondering how to make the controller (the part that receives the requests from external source and control signals from the workers)
A: ØMQ Poller can be used to serve and communicate with multiple sockets.
How ever, with ØMQ Poller, you end up with explicit blocks (under if loop) for handling the sockets. Each socket registered with ØMQ Poller has to have an explicit “if block” to handle it.
This becomes unwieldy as you start writing bigger programs. I would like to add - "a bit ugly"
With Event Loops, this becomes more streamlined as you can register callbacks to receive and send data and you can structure your callback else where.
I have following examples from the tutorial that I am writing.
*
*http://learning-0mq-with-pyzmq.readthedocs.org/en/latest/pyzmq/multisocket/zmqpoller.html
*http://learning-0mq-with-pyzmq.readthedocs.org/en/latest/pyzmq/multisocket/tornadoeventloop.html
Others can add on to this understanding or correct it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Generics using constructor with overload?
Possible Duplicate:
Generics constructor with parameter constraint?
In my venture into Generics, I've now come to a dead end where I hope someone can point me to the hidden door :-)
Given this type
type
TMyClass = class
private
FMyString: String;
FMyStringList: TStringList;
procedure SetMyString(const Value: String);
procedure SetMyStringList(const Value: TStringList);
public
constructor Create; overload;
constructor Create(InitString : String); overload;
destructor Destroy; override;
property MyString: String read FMyString write SetMyString;
property MyStringList : TStringList read FMyStringList write SetMyStringList;
end;
TMyClassList<T:TMyClass, constructor> = class(TObjectList<T>)
public
constructor Create; overload;
end;
implementation
{ TMyClass }
constructor TMyClass.Create;
begin
inherited;
MyString := '';
MyStringList := TStringList.Create;
MyStringList.Add('This');
MyStringList.Add('is');
MyStringList.Add('a');
MyStringList.Add('test.');
end;
constructor TMyClass.Create(InitString: String);
begin
Create;
MyString := InitString;
end;
I would like to be able to use both TMyClass constructors as needed.
constructor TMyClassList<T>.Create;
begin
Add(T.Create);
// Add(T.Create('test')); // <--- THIS FAILS ????
end;
But only the one without parameters is usable.
I forgot to mention - It does NOT fail ... It will not COMPILE !!
Why is that?
Regards
Bimmer_R
A: I got it working like this:
type
TMyClassClass = class of TMyClass;
...
constructor TMyClassList<T>.Create;
begin
Add(T.Create);
Add(TMyClassClass(T).Create('test'));
end;
...
var
Test : TMyClassList<TMyClass>;
begin
Test := TMyClassList<TMyClass>.Create;
end;
A: You can't specify general constructor constraints on generic types. All you can do is specify that they have a single parameterless constructor, as you have done. Work around it like this:
TMyClassList<T: TMyClass> = class(TObjectList<T>)
//no need for constructor constraint
...
type
TMyClassClass = class of TMyClass;
...
constructor TMyClassList<T>.Create;
begin
Add(TMyClassClass(T).Create('test'));
end;
You'll want to use a virtual constructor on TMyClass to make this work as you intend.
TMyClass = class
constructor Create(InitString : String); virtual;
end;
The other option is to use a parameterless constructor and use a separate routine for initialization.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to overcome endless problems with web.config when working with team? I'm in a team of people working from various places and on different machines. Everyone has it's own connection string, nhibernate setting (schema etc.) and wcf endpoints.
What drives me crazy is that every now and then when someone adds new key to AppSettings section, my settings are overwritten by his.
Does anyone know a way to somehow preserve or rather overwrite again certain web.config settings? Maybe somehow replace in on compile time and define them elsewhere?
A: Here is the approach we use. In source control we have file web.config.development with common settings. Every developer on his machine has file web.config which is basically a web.config.development merged with developer's individual settings.
Whenever any common changes are made to the web.config.development, their author announces that (via Skype, or email, etc.) and every developer merges these changes with his own web.config. In most cases web.config is not being changed very often, so this is not a time consuming work. However we were thinking about automating this process but have not come up with any good solution so far.
The key point here is that web.config is not in the source control, it never was, it never will be. That guarantees that individual settings like connection strings won't be overridden accidentally.
P.S. One more point to be considered is the continuous integration (in case you have one). There we have added a step during deployment, on which web.config.development is renamed into web.config.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to set HTTP proxy in ChromeDriver of Selenium 2? how do I set a HTTP proxy for Selenium 2's ChromeDriver in Java? I know how to do it for the FirefoxDriver using a FirefoxProfile, but there doesn't seem to be a ChromeProfile.
A: You could simply set the chrome proxy prefs at the chrome level. Unlike the firefox driver, the chrome driver does not reset chrome prefs each time it initiates a session.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android - Post Video with additional data to the server I would like to ask you how to upload video to the server with additional data (Multipart)
For example :
The user should send his name, Email, Phone number and video from gallery.....
Thank you..
A: Try this
Upload video from Android to server?
http://vikaskanani.wordpress.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://w3mentor.com/Upload.aspx");
byte[] data = IOUtils.toByteArray(is);
InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data),"uploadedFile");
StringBody sb1 = new StringBody("someTextGoesHere");
StringBody sb2 = new StringBody("someTextGoesHere too");
MultipartEntity multipartContent = new MultipartEntity();
multipartContent.addPart("uploadedFile", isb);
multipartContent.addPart("one", sb1);
multipartContent.addPart("two", sb2);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tomcat, open a socket - doesn't work My web-app needs to talk to a device in my local network via a soket. I am trying to open a ServerSocket on port > 45000 and listen to it for incoming connections. The class that implements this worked perfectly well while i was developing it and running it as a stand-alone thing, but it throws an exception when i try to run it as a part of my web-app under Tomcat.
What can i do to fix it? I do need to listen to that port, and it is not HTTP traffic that i receive through it, so i can't listen to it by opening it in the config.xml file.
Here is, basically, the code that fails:
private void start() {
ServerSocket s = 0;
try {
s = new ServerSocket(45678); // this is line 38 (see stacktrace)
} catch (IOException e) {
Misc.log("Could not listen on port: 45678.\n" + Misc.getStackTrace(e));
// System.exit(-1);
}
...
}
Here is the stacktrace:
Could not listen on port: 45634.
java.net.BindException: Address already in use: JVM_Bind
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at x.x.x.userland.logging.WebServer.start(WebServer.java:38)
...
Thanks for your help.
Best regards,
Timofey.
UPD added the top of the stacktrace. PS. it writes it even when i run it the first time
UPD 2
It turns out that that port is used by something called Coyote...
INFO: Initializing Coyote HTTP/1.1 on http-80
28.09.2011 13:04:36 org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-45634
28.09.2011 13:04:36 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 267 ms
I will try to "pursuade" Coyote not to use it. Can it be done at all?
A:
Could not listen on port: 45634.
java.net.BindException: Address already in use: JVM_Bind
That means the port is in use. Maybe by the standalone program you used to test it. Maybe it was not closed properly and will need to time-out.
Try with a different port number for now, and make sure you close the socket when done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How do I achieve a better performance of my website Hy there!
I'm running IIS7 on a Windows 2008 server.
On peek times we have following behaviour:
*
*CPU load is near idle
*Requests get queued (monitored with Resource Monitor)
*Exeuction time gets over 10sec
1-4) Please see previous versions and edits
5) Doing stuff async
As suggested, I've created a simple web ... one page ... with this codebehind:
using System;
using System.Threading;
using System.Web;
using System.Web.UI;
namespace PerformanceTest
{
public partial class AsyncPage : Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
var pageAsyncTask = new PageAsyncTask(this.BeginAsyncOperation, this.EndAsyncOperation, this.TimeoutAsyncOperation, null);
this.RegisterAsyncTask(pageAsyncTask);
// or
//this.AddOnPreRenderCompleteAsync(this.BeginAsyncOperation, this.EndAsyncOperation);
// this might be useful for doing cleanup or sth alike
this.PreRenderComplete += HandlePreRenderComplete;
}
private void HandlePreRenderComplete(object sender, EventArgs e)
{
this.Trace.Write("HandlePreRenderComplete");
this.Trace.Write(string.Format("managedThreadId #{0}", Thread.CurrentThread.ManagedThreadId));
}
private delegate void Sleep(int miliseconds);
private IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback asyncCallback, object state)
{
this.Trace.Write("BeginAsyncOperation");
this.Trace.Write(string.Format("managedThreadId #{0}", Thread.CurrentThread.ManagedThreadId));
var sleep = new Sleep(Thread.Sleep);
return sleep.BeginInvoke(1000, asyncCallback, state);
}
private void EndAsyncOperation(IAsyncResult asyncResult)
{
this.Trace.Write("EndAsyncOperation");
this.Trace.Write(string.Format("managedThreadId #{0}", Thread.CurrentThread.ManagedThreadId));
}
private void TimeoutAsyncOperation(IAsyncResult asyncResult)
{
this.Trace.Write("TimeoutAsyncOperation");
this.Trace.Write(string.Format("managedThreadId #{0}", Thread.CurrentThread.ManagedThreadId));
}
}
}
Seems quite good, doesn't it? Actually it changes nothing, as stressing for more than 30 seconds, response time goes up to 8 seconds with CPU usage near 0%.
6) Updated machine.config
<system.net>
<connectionManagement>
<add address="*" maxconnection="12" />
</connectionManagement>
</system.net>
<system.web>
<processModel autoConfig="true"
maxWorkerThreads="100"
maxIoThreads="100"
minWorkerThreads="50"
minIoThreads="50" />
<httpRuntime minFreeThreads="88"
minLocalRequestFreeThreads="76" />
</system.web>
A: http://geekswithblogs.net/StuartBrierley/archive/2009/09/30/tuning-iis---machine.config-settings.aspx
A: You use a Page, and probably Session, so every page load lock all the other because of the Session. ! So you may call it Async, or call the PageAsyncTask, but the page is lock all the other calls because of the Session, and the page calls are get in a line to execute.
Disable the Session just for test, and then if you not use any session data, keep it disable for this page.
Look also: Replacing ASP.Net's session entirely
Web Garder
You can setup a web garden, that is give more pools to the same web application. By do that you need to re-check all your code and include synchronization with mutex, or database lock, because with two or more pools the same data can be access and write by different threads.
http://msdn.microsoft.com/en-us/library/aa479328.aspx
A: The answer to this is quite easy:
Don't block the thread
The fact of the matter is that IIS and an ASP.NET AppDomain is only able to handle N amount of concurrent requests. You can increase this number, but having a complete lock on thousands of concurrently running threads is a bottleneck nightmare. Without knowing exactly what's causing the ASP.NET page to respond in less than one second it's hard to suggest any performance tweaks, but the problem here is probably not with IIS, but in the code.
If the code is blocking a thread for several seconds without actually doing anything (as the CPU usage is witness to), there is some kind of IO that is so slow it should obviously be made asynchronously. A web-server can server an almost infinite amount of concurrent requests (only limited by available hardware resources) if these requests don't block threads. If they block threads, it can only perform as many requests as there are available threads, which has a hard upper limit.
Do stuff asynchronously
Rewrite your code so it doesn't lock the thread by invoking Begin... and End... method instead of their synchronous siblings. The Async CTP can help with wrapping these Begin and End calls in code that looks synchronous, but the performance benefit here looks to be so huge that you should consider rewriting whatever code it is that is locking up the page even without the async stuff.
A: We had a similar problem once. It turned out that it was not our code that was causing the problem.
In our case the problem was with the TCP Chimney offload in windows 2008 R2. Windows 2008 trys to be clever by offloading work to the network card, but if the network card gets maxed out things slow down, but all the normal performance values show little load.
http://www.iislogs.com/steveschofield/troubleshooting-iis-7-network-performance-issues-and-tcp-chimney-offload-receive-side-scaling-and-network-direct-memory-access
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: SimpleXML works on emulator, not on Android device I'm using Simple 2.6.1 on an Android project for serialize some complex xml files. I use Eclipse and followed the procedure described on the project site (Simple XML in Android 1.5 and Up):
1) created the "libs" folder on the project root
2) put simple-xml-2.6.1.jar in the "libs" folder
3) added the jar to the build path
4) selected for export on the build path
All works fine when I run the application on the android emulator. But when I install the application on the device I get a crash at the time of serialization.
What's wrong?
P.S. I'm developing with android api level 8 (android 2.2)
Here's logcat:
I/WindowManager( 3002): CREATE SURFACE Surface(name=Please wait..., identity=2186, mNativeSurface=0) IN SESSION android.view.SurfaceSession@40966108: pid=13036 format=-2 flags=0x0 / Window{40b8a978 Please wait... paused=false}
I/WindowManager( 3002): CREATE SURFACE Surface(name=data5.android/data5.android.activity.CompileForm, identity=2187, mNativeSurface=0) IN SESSION android.view.SurfaceSession@40966108: pid=13036 format=-1 flags=0x0 / Window{40ce66e8 data5.android/data5.android.activity.CompileForm paused=false}
I/dalvikvm(13036): Could not find method javax.xml.stream.XMLInputFactory.newInstance, referenced from method org.simpleframework.xml.stream.StreamProvider.<init>
W/dalvikvm(13036): VFY: unable to resolve static method 1532: Ljavax/xml/stream/XMLInputFactory;.newInstance ()Ljavax/xml/stream/XMLInputFactory;
D/dalvikvm(13036): VFY: replacing opcode 0x71 at 0x0003
D/dalvikvm(13036): VFY: dead code 0x0006-0009 in Lorg/simpleframework/xml/stream/StreamProvider;.<init> ()V
D/dalvikvm(13036): GC_CONCURRENT freed 120K, 50% free 2855K/5639K, external 857K/1168K, paused 4ms+4ms
W/dalvikvm(13036): VFY: unable to find class referenced in signature (Ljavax/xml/stream/XMLEventReader;)
W/dalvikvm(13036): VFY: unable to find class referenced in signature (Ljavax/xml/stream/XMLEventReader;)
I/dalvikvm(13036): Could not find method javax.xml.stream.XMLInputFactory.createXMLEventReader, referenced from method org.simpleframework.xml.stream.StreamProvider.provide
W/dalvikvm(13036): VFY: unable to resolve virtual method 1530: Ljavax/xml/stream/XMLInputFactory;.createXMLEventReader (Ljava/io/InputStream;)Ljavax/xml/stream/XMLEventReader;
D/dalvikvm(13036): VFY: replacing opcode 0x6e at 0x0002
D/dalvikvm(13036): VFY: dead code 0x0005-000a in Lorg/simpleframework/xml/stream/StreamProvider;.provide (Ljava/io/InputStream;)Lorg/simpleframework/xml/stream/EventReader;
I/dalvikvm(13036): Could not find method javax.xml.stream.XMLInputFactory.createXMLEventReader, referenced from method org.simpleframework.xml.stream.StreamProvider.provide
W/dalvikvm(13036): VFY: unable to resolve virtual method 1531: Ljavax/xml/stream/XMLInputFactory;.createXMLEventReader (Ljava/io/Reader;)Ljavax/xml/stream/XMLEventReader;
D/dalvikvm(13036): VFY: replacing opcode 0x6e at 0x0002
D/dalvikvm(13036): VFY: dead code 0x0005-000a in Lorg/simpleframework/xml/stream/StreamProvider;.provide (Ljava/io/Reader;)Lorg/simpleframework/xml/stream/EventReader;
D/dalvikvm(13036): GC_CONCURRENT freed 453K, 52% free 2890K/5959K, external 834K/1168K, paused 1ms+2ms
I/ActivityManager( 3002): Displayed data5.android/.activity.CompileForm: +409ms
W/WindowManager( 3002): Window Window{40ada338 data5.android/data5.android.activity.StartForm paused=false} destroyed surface Surface(name=data5.android/data5.android.activity.StartForm, identity=-1, mNativeSurface=0), session Session{40cbdc28 uid 10226}
W/SurfaceFlinger( 3002): data5.android/data5.android.activity.StartForm[2184] is not removed from mLayerMap
D/dalvikvm(13036): GC_CONCURRENT freed 512K, 52% free 2907K/6023K, external 834K/1168K, paused 1ms+3ms
D/dalvikvm(13036): GC_CONCURRENT freed 509K, 52% free 2909K/6023K, external 834K/1168K, paused 2ms+2ms
D/PowerManagerService( 3002): onSensorChanged: light value: 1000
D/dalvikvm(13036): GC_CONCURRENT freed 553K, 53% free 2917K/6087K, external 834K/1168K, paused 1ms+2ms
D/dalvikvm(13036): GC_CONCURRENT freed 461K, 52% free 2954K/6087K, external 834K/1168K, paused 2ms+2ms
D/dalvikvm(13036): GC_CONCURRENT freed 449K, 52% free 2968K/6087K, external 834K/1168K, paused 2ms+2ms
D/dalvikvm(13036): GC_CONCURRENT freed 514K, 52% free 2957K/6087K, external 834K/1168K, paused 1ms+2ms
D/dalvikvm(13036): GC_CONCURRENT freed 502K, 52% free 2967K/6087K, external 834K/1168K, paused 2ms+2ms
D/dalvikvm(13036): GC_CONCURRENT freed 506K, 52% free 2972K/6087K, external 834K/1168K, paused 1ms+2ms
D/dalvikvm(13036): GC_CONCURRENT freed 574K, 52% free 2972K/6151K, external 834K/1168K, paused 2ms+2ms
E/lights ( 3002): write_int: path /sys/devices/virtual/misc/melfas_touchkey/brightness, value 2
W/PowerManagerService( 3002): Timer 0x7->0x3|0x0
I/PowerManagerService( 3002): Ulight 7->3|0
D/PowerManagerService( 3002): setLightBrightness : mButtonLight : 0
D/dalvikvm(13036): GC_CONCURRENT freed 489K, 52% free 2995K/6151K, external 834K/1168K, paused 1ms+2ms
D/dalvikvm(13036): GC_CONCURRENT freed 520K, 52% free 2986K/6151K, external 834K/1168K, paused 2ms+2ms
D/dalvikvm(13036): GC_CONCURRENT freed 508K, 52% free 2990K/6151K, external 834K/1168K, paused 2ms+2ms
D/dalvikvm(13036): GC_CONCURRENT freed 512K, 52% free 2990K/6151K, external 834K/1168K, paused 2ms+2ms
D/dalvikvm(13036): GC_CONCURRENT freed 510K, 52% free 2992K/6151K, external 834K/1168K, paused 1ms+2ms
W/dalvikvm(13036): threadid=12: thread exiting with uncaught exception (group=0x4001e578)
A: Change java compiler version into higher
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Extjs4 iconCls can't display in symfony I have a project which use Extjs4 and symfony.
I put extJS source code in symonfy's web/js folder and web/css.
So i can load extjs like :
<?php
use_stylesheet('ext/resources/css/ext-all.css');
?>
I created a formpanel and config the iconCls: 'icon-add' but it doesn't work in the page,the icon can't display.
A: Could you test inside firebug and try to see what ressource symfony / extJS is trying to load, you'll maybe have a network error or something like that.
How do you declare your icon-add css class?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Programmatically set PIN/Password used to unlock device Our software allows the users to lock their Windows mobile 6 devices using the following API call.
[DllImport("aygshell.dll")]
public static extern int SHDeviceLockAndPrompt();
When deploying our software our client would like to be able to set a universal unlock PIN/Password for all of their users so that each device does not need to be set-up manually.
Is there any way to set this either programmatically or through a reg key?
A: I'm not sure about the Shell function call you have mentioned. But Local Authentication Sub System (LASS) Application Development should help you in doing this. Secondly it is most secure device mechanism for windows mobile 6.5 and earlier versions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to zoom background together with graph using JUNG? It's easy to zoom in/out graph using GraphZoomScrollPane in JUNG. However, I cannot make the graph background image zooming together with the graph itself. How to do it?
A: If I can understand you correctly, try to see JUNG's StaticLayout example in WorldMapGraphDemo.class sample from JUNG example source package. In this example, you can zoom in/out both layout and view--in effect the background image will zoom in/out together with the elements of the graph.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to translate one language to another using java programming in my project, there is a content section. where user can view contents in four diff languages. Is there any way, that i put contents in one language, and according to user's choice my java program translate it to the selected language and now user can view it to that selected language.(Say for example translate English to French)
A: http://code.google.com/apis/language/translate/overview.html
Google Translate provides an API for just that. Of course, the translations aren't always good.
And you have to pay money for it.
Alternative: you write your content in every language you support, and at the correct event you update the UI with another version.
A: I assume that you're not talking about machine translation. Take a look at ResourceBundles, but the solution depends also on the frameworks you are using.
A: Depending on your implementation ResourceBundles may be what you are looking for, see:
http://java.sun.com/developer/technicalArticles/Intl/ResourceBundles/
and
http://download.oracle.com/javase/6/docs/api/java/util/ResourceBundle.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to make delivery task plan/schedule based on individual task estimates I am wondering, how "real" work day (7-8 hours) relates to "engineer hours" term used in estimation of the time necessary for completion of some task. I think that estimated effort in EH (if correctly estimated) cannot be simply translated into work days by dividing with 8, and that effective work day of a programmer is shorter than the time he spends in the building in which he works. This can lead to big errors in estimates when estimating small chunks of tasks (i.e. what is scope of one iteration in SCRUM) and when there are no best/worst case estimates, but planning is done based on individual task estimates done by programmers. When programmers need to estimate time necessary to do some individual tasks, they usually estimate the time from the moment they start working on it to the moment they complete it. Needless to say, it is insane to expect that someone will do 4 tasks of 2 hours each in one day.
I would like to know what are best practices in successful companies for relating effective time vs. time spent "at work" and are there some books or researches which estimate what is average time programmer spend working (focused on the tasks at hand), not doing other activities which are not included into estimate, like reading/writing mails (except ones included in estimate, if it is support task or similar), brainstorming, meeting, drinking coffee, estimating tasks and updating status in bug/task tracking tool.
If there are no books or researches, any links to articles about this issue by respected members of community will be of help also as I couldn't find any, these keywords are too generic.
A: There are two things that we do when we program:
*
*Things which we've done that are similar to what's gone before, and
*new things that we've never done before.
When we're repeating similar things, estimating - whether in points of relative effort / complexity or in hours - is usually fairly straightforward. Even when estimating in points, these can easily be correlated back to hours after a sprint or two, once the team has got up to speed.
The problem most teams face is that they're often doing new stuff. This is because:
*
*doing a project where it's all been done before is pointless (see "Waltzing with Bears")
*if it's all been done before, there's probably Open Source or off-the-shelf products which will do it for you, so learning how to use those may be new
*developers hate doing the same thing over and over again, and would rather learn something new by automating it or producing a reusable library.
Thus, a lot of what we do on software projects tends to be new. The usual same-old same-old frequently ends up being given to junior developers, for whom it's new.
The trouble with new things is that you have no idea how long they're going to take. You've never done them before!
I've seen a number of strategies for handling this, depending on how determined someone is to (force devs to) produce reliable estimates, how much trust you have with stakeholders, etc.
*
*Pad the estimates horribly and then make the work fit them (this is what developers end up doing if PMs / SMs force them to produce reliable estimates, whether the devs realise it or not).
*Kanban's "classes of service" allow you to mix some new things with some familiar things. This will tend to allow a less variable flow through the development pipeline, so you can base your estimates on that.
*Do everything that's risky first (particularly if you don't know how risky it is!). Gradually the flow will stabilise. On a 9 month project, it took 3 months to start producing any kind of useful estimates, so careful with this one. The upside is that your stakeholders will see you addressing the things which keep them awake at night early, so trust can be high. Your PM / SM will go spare during this time. It's OK.
*Accept that the old metaphor of "time spent = work done" is a myth in projects involving high amounts of learning and knowledge work. It might have been appropriate in the days when developers were treated like a factory - churning out the implementation of others' designs - but in the world of Agile and Scrum, it's completely inappropriate. Even Scrum.org have recently removed the necessity for estimation and velocity measurements from their guide. Find other ways to develop trust, manage risk, win budgets and have conversations around the work - since these are the only reasons you need estimates in the first place.
A: Besides the mythical man month, which is always worth reading, Agile estimating and planning is one of the best books I found on the topic.
Best quote ever:
“There's no sense in being precise when you don't even know what
you're talking about.” (John von Neumann)
Also, experimental software engineering attempts to draw statistically relevant conclusions out of experiments in a controlled environment. Very roughly you get to design experiments applying the scientific method, choosing input variables (ie. experience of the programmers, time of the week, language/framework, etc.), and measuring the output.
From wikipedia:
The scientific method suggests a cycle of observations, laws, and
theories to advance science. Experimental software engineering applies
this method to software.
A good book I remember from a remarkable university class on the topic is “Experimental Software Engineering”. It assumes you have a grasp over statistical distributions and descriptive statistics, but it's a very nice read.
A: An easy way to get on top of planned vs actual time spent (which in itself is always fluid to a certain degree) is to use an agile management tool. Target process can run with the heavies, but you can get the full system for free if you use less than 6 licenses. I have used it at 4 different clients over the past 5 years with great success each time.
I do not have the exact answer you want (i.e hours * 1.75 = working time), but TargetProcess' continous adjustment of estimates matched up with time spent will very quickly give you the ratio that applies to YOU.
PS- I do not work for them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: problem with break while using it to break nested loops in php When I execute this code:
$result = mysql_query("SELECT * FROM example_table");
$i = 0;
while ($row = mysql_fetch_array($result))
{
for ($j = 0; $j < $c; $j++)
{
if ($db_array[$j]['ID'] == $row['id'])
{
$del_counter = 0;
break 2;
}
else
$del_counter = 1;
}
if ($del_counter == 1)
{
$del_array[$i] = $row['id'];
$i++;
}
}
This does not break the two level looping. Instead, the $del_array stores all the row ids. I need to compare db_array[][id] with the array "row" (fetched from the database). And need to check which elements of db_array are deleted from the database. So, what I did is I tried to store the ids of deleted items in an array. But the break does not work. Am I missing something?
Thanks in anticipation.
BG
A: According to the PHP manual:
1) break ends execution of the current for, foreach, while, do-while or switch structure
2) break accepts an optional numeric argument which tells it
how many (the above mentioned) nested enclosing structures are to be broken out of
Your break is at the level 2, and hence break 2; should work as expected, so the problem is elsewhere. Is the break 2 executed at all?
In any case, I would recommend a more robust solution, e.g.
$ok = True;
while (($row = mysql_fetch_array($result)) && $ok) {
...
if (...) $ok = False; // anywhere deep
...
if ($ok) {...}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .htaccess : what is wrong with this rule? may you please tell me where is my fault ?
RewriteRule ^project/([^.]+)/$ /wordpress/wp-content/plugins/pr/cp.php?id=$1 [QSA,L]
i get Internal Server Error everytime i apply it
Thank you
EDIT
127.0.0.1/wordpress/project/43928fdsf
redirects to
127.0.0.1/wordpress/wp-content/plugins/pr/cp.php?id=43928fdsf
A: Your expression is fine which would suggest mod_rewrite is not installed/working/turned on. Change your code to look like this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^project/([^.]+)/$ /wordpress/wp-content/plugins/pr/cp.php?id=$1 [QSA,L]
</IfModule>
That should stop there being any 500 errors (if they were indeed mod_rewrite related). If your URL rewrites still don't work then you don't have mod_rewrite installed/enabled, in which case you can install and enable it.
UPDATE
You have a forward slash at the end o your RewriteRule but you want to match a URL like 127.0.0.1/wordpress/project/43928fdsf, which has no forward slash at the end. Just remove the forward slash and the rule should match:
RewriteRule ^project/([^.]+)$ /wordpress/wp-content/plugins/pr/cp.php?id=$1 [QSA,L]
From then on if you're still getting a 500 error then try printing the $_GET variables at the top of your PHP file, then call exit() and see if you still have the problem. This should help to narrow down whether the problem is with PHP or Apache.
A: If you're trying to match a single URL part with that group then you are doing it wrong because [^.]+ will also match /. E.g.: project/a/b/c/ will also match => $1 will be a/b/c
On another note, have you checked what groups you're capturing? And if those values that you then send through parameter id are not causing cp.php to crash?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create Folders and rules in exchange server 2003 I would like to know How to Create Folders and rules in exchange server 2003 as i am using webdav code in c#. I have tried with few examples but not able to get it.
A: To create a folder, just issue a MKCOL request on the target url.
This is a small sample (withouth any error handling or so):
var request = WebRequest.Create("http://exchangeserver/exchange/username/NewFolder");
request.Method = "MKCOL";
request.UseDefaultCredentials = true;
request.GetResponse();
Regarding the rules. There is no good way to do this using WebDAV. You should check another technology, like Redemption. It can be used from .NET and offers the functionality you need.
Outlook Redemption: http://www.dimastr.com/redemption/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Extracting HTTP link(http://) for the string in VB.NET I have the following column values in my table
Sample values:
*
*Check out ABC Group Blog post about XYZ Today! http://blog.saedg.org/
*'Join ABC in urging the county to help create new jobs and economic opportunities for XYZCounty. http://starabcnet.com/news/science/environment/article_4b3d2f7e-96c6-5007-a036-b4613250755e.html
I want to have 2 variables having the links and content separate – example:
*
*Var1 = Check out ABC Group Blog post about XYZ Today!
Var2 = http://blog.saedg.org/
*Var1 = Join ABC in urging the county to help create new jobs and economic opportunities for XYZCounty
Var2 = http://starabcnet.com/news/science/environment/article_4b3d2f7e-96c6-5007-a036-b4613250755e.html
I guess it can be done via String funcions or regular expression.
A: Try this:
' This is the regex that is used to get the addresses
Public Shared URL As New Regex("(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])", RegexOptions.Compiled)
' URL.Matches returns a collection of results that you can iterate through eg:
for each ele in URL.Matches("INPUT STRING")
' do something with each link that you get
' like removing them from the input string
next
A: Can you separate the column in two different columns? Like, "Message" and "Link" for example.
If you can not do that, assuming the Http is always in the end of string and there is no other reference to HTTP:// in the string, you can get the string after "HTTP://".
Look at IndexOf and Substring methods of string in VB.NET.
Something like this (I didn't test):
string url = var.SubString(var.IndexOf("http"))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get a node value with XmlPullParser Im trying to get values from an XML with the XmlPullParser but can't reach the values I want.
The XML-structure is similar to the Android Strings.xml:
<string name="value"> 1 </string>
I can get "string", "name" & "value" from the XML but can't reach the actual value "1". It seems like the XmlPullParser only works for structures like this:
<value> 1 </value>
Do I need to use another parser or is there a way to reach "1" (the value above) in some way?
Thanks!
A: Have you checked the documentation of the XmlPullParser? It has an example how to use it.
Basically you can get the value inside the tags by calling getText when the parser reaches correct position when you're calling next.
A: nextText() method will do the trick
A: To extend the previous answers with a code snippet of how to actually use this.
/* initialization skipped */
eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
Log.d("Task2/Parser","Start document");
} else if(eventType == XmlPullParser.START_TAG) {
Log.d("Task2/Parser", "Start tag "+xpp.getName());
if (xpp.getName().equals("temperature")){
temperature = Double.parseDouble(xpp.nextText());
return temperature;
}
} else if(eventType == XmlPullParser.END_TAG) {
Log.d("Task2/Parser", "End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
Log.d("Task2/Parser", "Text "+xpp.getText());
}
eventType = xpp.next();
}
This code returns the value within the xml tag <temperature> as a double. Obviously, it would need more error handling, but just so other people ending up here can get it with less googling.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: eclipse plugin handler to invoke jax-ws webservice i have a jax-ws "hello world service" running in my tomcat.i am working on designing a eclipse plugin to invoke the web service.could anyone please guide me doing so.
A: you could start reading this tutorial: it's a comprehensive tutorial about developing eclipse based RCP and plug-ins.
the simplest thing you could do is writing a vewi (chap 7 in the tutorial) and whiring the data displayed to the webservice output.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: group by join and aggregate (linq) I have a problem with a LINQ query and don't know how to solve it :/
I've got two tables. One is with attributes and the second are rows from attributes, but I need to sum hours from rows and get it to attributes; can't explain it very well ;) Here is my query that I tried to create:
var query = (from ta in session.db.TimesheetAttributes
join tr in session.db.TimesheetRows on ta.Id equals tr.TimesheetAttributesId into tempTR
from ttr in tempTR.DefaultIfEmpty()
group ttr by new { ta.TimesheetId, ta.Date, ta.SickNote, ta.Vacation, ta.OccasionVacation } into g
select new
{
Id = g.Key.TimesheetId,
Date = g.Key.Date,
WeekDay = g.Key.Date.ToString("dddd", new CultureInfo("pl-PL")),
Description = String.Format("{0:dd/MM/yyyy}", g.Key.Date),
SickNote = g.Key.SickNote,
Vacation = g.Key.Vacation,
OccasionVacation = g.Key.OccasionVacation,
Hours = String.Format("{0:HH:mm}", (new DateTime(g.Aggregate(TimeSpan.Zero, (subtotal, t) => subtotal + (t.DateTo - t.DateFrom)).Ticks)))
}).OrderBy(c=>c.Date).ToList();
The problem is that not every attribute's got rows, that's why I tried to use DefaultIfEmpty(), however this query is not working :(
My old query is working, but my ORM makes a new query for each row, so if I have 1000 TimesheetAttributes it makes 1000 selects :/
Here is my old query:
var query = (from c in session.db.TimesheetAttributes
where ((c.Active == true)
&& (c.Timesheet.Active == true)
&& (c.ValidFrom <= validDate)
&& (c.ValidTo > validDate)
&& (c.Timesheet.ContactPersonId == session.ContactPersonAttributes.ContactPersonId))
select new
{
Id = c.TimesheetId,
c.Date,
WeekDay = c.Date.ToString("dddd", new CultureInfo("pl-PL")),
Description = String.Format("{0:dd/MM/yyyy}", c.Date),
Hours = String.Format("{0:HH:mm}", (new DateTime((c.TimesheetRows.Aggregate(TimeSpan.Zero, (subtotal, t) => subtotal + (t.DateTo - t.DateFrom)).Ticks)))),
c.SickNote,
c.Vacation,
c.OccasionVacation
}).OrderBy(c => c.Date).ToList();
EDIT:
This is what I get as exception: "Exception has been thrown by the target of an invocation"
InnerException: "Object reference not set to an instance of an object"
A: The problem you were having with you're old query is often referred to as the n+1 problem.
You should be able to adapt your original query as follows:
var query = (from c in session.db.TimesheetAttributes
from cr in c.TimesheetRows
where ((c.Active == true)
&& (c.Timesheet.Active == true)
&& (c.ValidFrom <= validDate)
&& (c.ValidTo > validDate)
&& (c.Timesheet.ContactPersonId == session.ContactPersonAttributes.ContactPersonId))
select new
{
Id = c.TimesheetId,
c.Date,
WeekDay = c.Date.ToString("dddd", new CultureInfo("pl-PL")),
Description = String.Format("{0:dd/MM/yyyy}", c.Date),
Hours = String.Format("{0:HH:mm}", (new DateTime((cr.Aggregate(TimeSpan.Zero, (subtotal, t) => subtotal + (t.DateTo - t.DateFrom)).Ticks)))),
c.SickNote,
c.Vacation,
c.OccasionVacation
}).OrderBy(c => c.Date).ToList();
If that still whinges, you can try adding a tenary operator to the Hours property...
Hours = String.Format("{0:HH:mm}", !(cr == null) && cr.Any() ? (new DateTime((cr.Aggregate(TimeSpan.Zero, (subtotal, t) => subtotal + (t.DateTo - t.DateFrom)).Ticks))) : DateTime.MinValue
EDIT:
I see what you mean now, my brain hasn't quite woken up yet. The problem you have is that the underlying query provider isn't noticing that it needs to fetch TimesheetAttributes AND the associated/related TimesheetRows. This is probably because the TimesheetRows are buried quite deeply within the expression that generates the anonymous types you're selecting.
My query syntax isn't brilliant (I prefer to do it in lambda - I feel it's more future proof but that's just a feeling), but I'll give it a shot...
var query = (from res in
(from c in session.db.TimesheetAttributes
where ((c.Active == true)
&& (c.Timesheet.Active == true)
&& (c.ValidFrom <= validDate)
&& (c.ValidTo > validDate)
&& (c.Timesheet.ContactPersonId == session.ContactPersonAttributes.ContactPersonId))
select new
{
c = c,
cr = c.TimesheetRows
})
select new
{
Id = c.TimesheetId,
c.Date,
WeekDay = c.Date.ToString("dddd", new CultureInfo("pl-PL")),
Description = String.Format("{0:dd/MM/yyyy}", c.Date),
Hours = String.Format("{0:HH:mm}", (new DateTime((cr.Aggregate(TimeSpan.Zero, (subtotal, t) => subtotal + (t.DateTo - t.DateFrom)).Ticks)))),
c.SickNote,
c.Vacation,
c.OccasionVacation
}).OrderBy(c => c.Date).ToList();
It looks uglier than the original, and I'm sure there's a better way of doing it, but it should make the expression clear enough for your query provider (L2S or whatever) to realise it needs to return both entities, and avoid the n+1 issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how can i write a byte array to a file using a SaveFileDialog? Basically I have have a program that creates an array of bytes (manually entered via a richtextbox and I want to be able to create a new file and save the bytes in that file via a SaveFileDialog() method.
The code I have come up with is:
byte[] bytes = Encoding.ASCII.GetBytes(richTextBox1.Text);
Stream stream = new MemoryStream(bytes);
SaveFileDialog file = new SaveFileDialog();
file.ShowDialog();
if (file.FileName != "")
{
using (BinaryWriter bw = new BinaryWriter(stream))
{
bw.Write(bytes);
}
}
A: You say you've got the bytes "manually entered via a richtextbox" - but you're just getting the ASCII-encoded value of the text. If you were expecting that to (say) parse hex, then you'll be disappointed. It's not really clear what you're trying to do, but if you are trying to save text, you don't need to convert it into a byte array yourself.
Next, you're currently writing to a MemoryStream, so it's clearly not going to save to a file... if you really wanted to do this, you should use a FileStream instead (either constructed directly or via File.OpenWrite etc). However, you don't need to do all that work yourself...
The simplest way to save a bunch of bytes is:
File.WriteAllBytes(file.FileName, bytes);
The simplest way to save a string is:
File.WriteAllText(file.FileName, text); // Optionally specify an encoding too
A: you can do that simply by using File.WriteAllText method:
SaveFileDialog file = new SaveFileDialog();
file.ShowDialog();
if (file.FileName != "")
{
File.WriteAllText(file.FileName, richTextBox1.Text);
}
A: You should use FileInfo to Read/Write to files. So you can do more checks before accessing it.
Create the ByteArray as you already done it, so you can decide your encoding, and your are safe for the future.
Check the response of the user by using the DialogResult, and then crosscheck the result FileName.
Please don't forget, that maybe the File already exists, and the user wants to override or append it :-)
SaveFileDialog file = new SaveFileDialog();
DialogResult dialogResult = file.ShowDialog();
if (dialogResult == DialogResult.OK) {
if (String.IsNullOrEmpty(file.FileName)) {
//Inform the user
}
string path = file.FileName;
FileInfo fi = new FileInfo(path);
// Open the stream for writing.
using (FileStream fs = fi.OpenWrite()) {
Byte[] info = Encoding.ASCII.GetBytes(richTextBox1.Text);
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
} else {
//Inform the user
}
More Information about FileInfo:
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx
More Information about the OpenWrite Method:
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.openwrite.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get month range from a given date range For example if i give the startdate as 15-mar-2009 and enddate as 15-mar-2010, I want to get the date range as given below,
Start Date End Date
15-mar-2009 15-Apr-2009
15-apr-2009 15-may-2009
...
15-mar-2010 15-apr-2010
Can anyone please help me in getting this.
A: You could try something like this, have an extension method (or non extension method) that returns an IEnumerable<DateTime>, you can iterate over this or use it in linq expression etc.
public static IEnumerable<DateTime> EnumerateUntilAfter(this DateTime startDate, DateTime endDate)
{
if(endDate < startDate)
throw new ArgumentOutOfRangeException("End date must be less than start date");
return EnumerateUntilAfterImpl(startDate, endDate);
}
private static IEnumerable<DateTime> EnumerateUntilAfterImpl(DateTime startDate, DateTime endDate)
{
while (startDate <= endDate)
{
yield return startDate;
startDate = startDate.AddMonths(1);
}
}
used like
public void DoTheThing(DateTime start, DateTime end)
{
Console.WriteLine("StartDate\tEndDate");
foreach (var date in start.EnumerateUntilAfter(end))
Console.WriteLine("{0}\t{1}", date, date.AddMonths(1));
}
Gives you
StartDate EndDate
15-Mar-2009 15-Apr-2009
15-Apr-2009 15-May-2009
15-May-2009 15-Jun-2009
15-Jun-2009 15-Jul-2009
15-Jul-2009 15-Aug-2009
15-Aug-2009 15-Sep-2009
15-Sep-2009 15-Oct-2009
15-Oct-2009 15-Nov-2009
15-Nov-2009 15-Dec-2009
15-Dec-2009 15-Jan-2010
15-Jan-2010 15-Feb-2010
15-Feb-2010 15-Mar-2010
15-Mar-2010 15-Apr-2010
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting Chrome to accept self-signed localhost certificate I have created a self-signed SSL certificate for the localhost CN. Firefox accepts this certificate after initially complaining about it, as expected. Chrome and IE, however, refuse to accept it, even after adding the certificate to the system certificate store under Trusted Roots. Even though the certificate is listed as correctly installed when I click "View certificate information" in Chrome's HTTPS popup, it still insists the certificate cannot be trusted.
What am I supposed to do to get Chrome to accept the certificate and stop complaining about it?
A: Linux
If you're using Linux, you can also follow this official wiki pages:
*
*Configuring SSL certificates on Linux.
*NSS Shared DB And LINUX
*NSS Shared DB Howto
Basically:
*
*click the lock icon with an X,
*choose Certificate Information
*go to Details tab
*Click on Export... (save as a file)
Now, the following command will add the certificate (where YOUR_FILE is your exported file):
certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n YOUR_FILE -i YOUR_FILE
To list all your certificates, run the following command:
certutil -d sql:$HOME/.pki/nssdb -L
If it still doesn't work, you could be affected by this bug:
Issue 55050: Ubuntu SSL error 8179
P.S. Please also make sure that you have libnss3-tools, before you can use above commands.
If you don't have, please install it by:
sudo apt-get install libnss3-tools # on Ubuntu
sudo yum install nss-tools # on Fedora, Red Hat, etc.
As a bonus, you can use the following handy scripts:
$ cat add_cert.sh
certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n $1 -i $1
$ cat list_cert.sh
certutil -d sql:$HOME/.pki/nssdb -L # add '-h all' to see all built-in certs
$ cat download_cert.sh
echo QUIT | openssl s_client -connect $1:443 | sed -ne '/BEGIN CERT/,/END CERT/p'
Usage:
add_cert.sh [FILE]
list_cert.sh
download_cert.sh [DOMAIN]
Troubleshooting
*
*Run Chrome with --auto-ssl-client-auth parameter
google-chrome --auto-ssl-client-auth
A:
UPDATE 11/2017: This answer probably won't work for most newer versions of Chrome.
UPDATE 02/2016: Better Instructions for Mac Users Can be Found Here.
*
*On the site you want to add, right-click the red lock icon in the address bar:
*Click the tab labeled Connection, then click Certificate Information
*Click the Details tab, the click the button Copy to File.... This will open the Certificate Export Wizard, click Next to get to the Export File Format screen.
*Choose DER encoded binary X.509 (.CER), click Next
*Click Browse... and save the file to your computer. Name it something descriptive. Click Next, then click Finish.
*Open Chrome settings, scroll to the bottom, and click Show advanced settings...
*Under HTTPS/SSL, click Manage certificates...
*Click the Trusted Root Certification Authorities tab, then click the Import...
button. This opens the Certificate Import Wizard. Click Next to get to the File to Import screen.
*Click Browse... and select the certificate file you saved earlier, then click Next.
*Select Place all certificates in the following store. The selected store should be Trusted Root Certification Authorities. If it isn't, click Browse... and select it. Click Next and Finish
*Click Yes on the security warning.
*Restart Chrome.
A: UPDATED Apr 23/2020
Recommended by the Chromium Team
https://www.chromium.org/Home/chromium-security/deprecating-powerful-features-on-insecure-origins#TOC-Testing-Powerful-Features
Quick Super-Easy Solution
There is a secret bypass phrase that can be typed into the error page to have Chrome proceed despite the security error: thisisunsafe (in earlier versions of Chrome, type badidea, and even earlier, danger). DO NOT USE THIS UNLESS YOU UNDERSTAND EXACTLY WHY YOU NEED IT!
Source:
https://chromium.googlesource.com/chromium/src/+/d8fc089b62cd4f8d907acff6fb3f5ff58f168697%5E%21/
(NOTE that window.atob('dGhpc2lzdW5zYWZl') resolves to thisisunsafe)
The latest version of the source is @ https://chromium.googlesource.com/chromium/src/+/refs/heads/master/components/security_interstitials/core/browser/resources/interstitial_large.js and the window.atob function can be executed in a JS console.
For background about why the Chrome team changed the bypass phrase (the first time):
https://bugs.chromium.org/p/chromium/issues/detail?id=581189
If all else fails (Solution #1)
For quick one-offs if the "Proceed Anyway" option is not available, nor the bypass phrase is working, this hack works well:
*
*Allow certificate errors from localhost by enabling this flag (note Chrome needs a restart after changing the flag value):
chrome://flags/#allow-insecure-localhost
(and vote-up answer https://stackoverflow.com/a/31900210/430128 by @Chris)
*If the site you want to connect to is localhost, you're done. Otherwise, setup a TCP tunnel to listen on port 8090 locally and connect to broken-remote-site.com on port 443, ensure you have socat installed and run something like this in a terminal window:
socat tcp-listen:8090,reuseaddr,fork tcp:broken-remote-site.com:443
*Go to https://localhost:8090 in your browser.
If all else fails (Solution #2)
Similar to "If all else fails (Solution #1)", here we configure a proxy to our local service using ngrok. Because you can either access ngrok http tunnels via TLS (in which case it is terminated by ngrok with a valid certificate), or via a non-TLS endpoint, the browser will not complain about invalid certificates.
Download and install ngrok and then expose it via ngrok.io:
ngrok http https://localhost
ngrok will start up and provide you a host name which you can connect to, and all requests will be tunneled back to your local machine.
A: I went down the process of using what bjnord suggested which was:
Google Chrome, Mac OS X and Self-Signed SSL Certificates
What is shown in the blog did not work.
However, one of the comments to the blog was gold:
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain site.crt
You'll need to follow the blog on how to get the cert file, after that you can use the command above and should be good to go.
A: The GUI for managing SSL certs on Chromium on Linux did NOT work properly for me. However, their docs gave the right answer. The trick was to run the command below that imports the self-signed SSL cert. Just update the name of the <certificate-nickname> and certificate-filename.cer, then restart chromium/chrome.
From the Docs:
On Linux, Chromium uses the NSS Shared DB. If the built-in manager does not work for you then you can configure certificates with the NSS command line tools.
Get the tools
*
*Debian/Ubuntu: sudo apt-get install libnss3-tools
*Fedora: su -c "yum install nss-tools"
*Gentoo: su -c "echo 'dev-libs/nss utils' >> /etc/portage/package.use && emerge dev-libs/nss" (You need to launch all commands below with the nss prefix, e.g., nsscertutil.)
Opensuse: sudo zypper install mozilla-nss-tools
To trust a self-signed server certificate, we should use
certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n <certificate-nickname> -i certificate-filename.cer
List all certificates
certutil -d sql:$HOME/.pki/nssdb -L
The TRUSTARGS are three strings of zero or more alphabetic characters, separated by commas. They define how the certificate should be trusted for SSL, email, and object signing, and are explained in the certutil docs or Meena's blog post on trust flags.
Add a personal certificate and private key for SSL client authentication
Use the command:
pk12util -d sql:$HOME/.pki/nssdb -i PKCS12_file.p12
to import a personal certificate and private key stored in a PKCS #12 file. The TRUSTARGS of the personal certificate will be set to “u,u,u”.
Delete a certificate
certutil -d sql:$HOME/.pki/nssdb -D -n <certificate nickname>
Excerpt From: https://chromium.googlesource.com/chromium/src/+/HEAD/docs/linux_cert_management.md
A: For Fedora, Ubuntu, Linux, if you're getting example.com Not a Certification authority error when adding the certificate using the gui to add a new root authority. If you want to trust a server self signed certificate, it cannot make mention of an invalid authority... even if that's itself. I've only managed to make it work by trusting my authority and using that authorities key to sign server certificates.
Here's the self signed CA certificate that it accepted. This is the only way that I found works to get around cert_authority_invalid, I tried for hours to get it to accept a self signed end point certificate, no cigar. The UI will accept self signed authorities, as long as it's declared CA:TRUE. After that, all certs signed by that key with the correct DN will be accepted by chrome without needing to add them independently.
openssl req -new -x509 -extensions v3_req -days 8440 -config ca.conf -key rockstor.key -out rockstor.cert
[req]
distinguished_name=dn
req_extensions=v3_req
prompt = no
[v3_req]
basicConstraints=CA:TRUE,pathlen:0
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName=@alt_names
[alt_names]
DNS.1 = ca.tdpowerskills.com
[dn]
C = US
ST = LA
L = Alexandria
O = TDPS Certification Authority
OU = LEARNOPS
CN = ca.tdpowerskills.com
openssl req -new -x509 -extensions v3_req -days 8440 -config config.conf -key rockstor.key -out rockstor.cert
[req]
distinguished_name=dn
req_extensions=v3_req
prompt = no
[v3_req]
basicConstraints=CA:FALSE
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName=@alt_names
issuerAltName=DNS:ca.tdpowerskills.com
[alt_names]
DNS.1 = big.tdps.app
[dn]
C = US
ST = LA
L = Alexandria
O = TDPS Certification Authority
OU = LEARNOPS
CN = ca.tdpowerskills.com
If that doesn't work:
*
*chrome://restart to actually restart
*Try to get more details on the error using firefox, it tends to explain errors better... while chrome will say, ERR_CERTIFICATE_INVALID, firefox will throw: MOZILLA_PKIX_ERROR_CA_CERT_USED_AS_END_ENTITY.
*Remember that chrome now requires Subject Alternate Name and nearly ignores CN.
For others:
*
*certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n <nickname> -i <my.crt> // For server sertificates
*certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n <nickname> -i <my.crt> for CA's https://blogs.oracle.com/meena/about-trust-flags-of-certificates-in-nss-database-that-can-be-modified-by-certutil
*For Firefox, the UI adding an exception certificate does work and it will trust it once you do that.
*Perhaps you have funky settings in /etc/pki/tls/openssl.cnf which get merged with your config.
*perhaps you're no adding an extension to the config or command line, such as v3_req
*Note, my method bypasses the need for a CSR by just signing the certificates with the authority key and adding details for the dev servers. CSR's allow more keys for actual security.
*I tried everything, but chrome requires an authority with basicconstraints CA:true set. And server certificates must all be singed by a valid Authority... even if that's just another certificate that the signed themselves with CA:true.
A: Allowing insecure localhost work fine via this method chrome://flags/#allow-insecure-localhost
Just that you need to create your development hostname to xxx.localhost.
A: To create a self signed certificate in Windows that Chrome v58 and later will trust, launch Powershell with elevated privileges and type:
New-SelfSignedCertificate -CertStoreLocation Cert:\LocalMachine\My -Subject "fruity.local" -DnsName "fruity.local", "*.fruity.local" -FriendlyName "FruityCert" -NotAfter (Get-Date).AddYears(10)
#notes:
# -subject "*.fruity.local" = Sets the string subject name to the wildcard *.fruity.local
# -DnsName "fruity.local", "*.fruity.local"
# ^ Sets the subject alternative name to fruity.local, *.fruity.local. (Required by Chrome v58 and later)
# -NotAfter (Get-Date).AddYears(10) = make the certificate last 10 years. Note: only works from Windows Server 2016 / Windows 10 onwards!!
Once you do this, the certificate will be saved to the Local Computer certificates under the Personal\Certificates store.
You want to copy this certificate to the Trusted Root Certification Authorities\Certificates store.
One way to do this: click the Windows start button, and type certlm.msc.
Then drag and drop the newly created certificate to the Trusted Root Certification Authorities\Certificates store per the below screenshot.
A: This worked for me. See: http://www.robpeck.com/2010/10/google-chrome-mac-os-x-and-self-signed-ssl-certificates/#.Vcy8_ZNVhBc
In the address bar, click the little lock with the X. This will bring up a small information screen. Click the button that says "Certificate Information."
Click and drag the image to your desktop. It looks like a little certificate.
Double-click it. This will bring up the Keychain Access utility. Enter your password to unlock it.
Be sure you add the certificate to the System keychain, not the login keychain. Click "Always Trust," even though this doesn't seem to do anything.
After it has been added, double-click it. You may have to authenticate again.
Expand the "Trust" section.
"When using this certificate," set to "Always Trust"
A: mkdir CA
openssl genrsa -aes256 -out CA/rootCA.key 4096
openssl req -x509 -new -nodes -key CA/rootCA.key -sha256 -days 1024 -out CA/rootCA.crt
openssl req -new -nodes -keyout example.com.key -out domain.csr -days 3650 -subj "/C=US/L=Some/O=Acme, Inc./CN=example.com"
openssl x509 -req -days 3650 -sha256 -in domain.csr -CA CA/rootCA.crt -CAkey CA/rootCA.key -CAcreateserial -out example.com.crt -extensions v3_ca -extfile <(
cat <<-EOF
[ v3_ca ]
subjectAltName = DNS:example.com
EOF
)
A: As of March 2020, on MacOS Catalina using Chrome 81, this has changed once you create a valid certificate using openssl as outlined above.
First, I browsed to my site using Safari and clicked on the link at the bottom of the the warning page that allows me to Access the Site Anyway. This added the certificate to my Mac Keychain (ie Keychain.app). Safari then would let me view the page. Chrome showed that the certificate was trusted, but wouldn't let me view the page. I continued to get the CERTIFICATE_INVALID error.
In Keychain, select All Items in the pane on the bottom left. Then search for your localhost DNS name (ie myhost.example.com).
Double click on your certificate. It’ll open an edit dialog for your cert.
Change "When using this Certificate" to "Always Trust"
This was totally counterintuitive because SSL was already set to Always Trust, presumably by Safari when the cert was added. Chrome only started working once I changed it globally to Always Trust. When I changed it back, it stopped working.
A: If you're on a mac and not seeing the export tab or how to get the certificate this worked for me:
*
*Click the lock before the https://
*Go to the "Connection" tab
*Click "Certificate Information"
Now you should see this:
*Drag that little certificate icon do your desktop (or anywhere).
*Double click the .cer file that was downloaded, this should import it into your keychain and open Keychain Access to your list of certificates.
In some cases, this is enough and you can now refresh the page.
Otherwise:
*Double click the newly added certificate.
*Under the trust drop down change the "When using this certificate" option to "Always Trust"
Now reload the page in question and it should be problem solved! Hope this helps.
Edit from Wolph
To make this a little easier you can use the following script (source):
*
*Save the following script as whitelist_ssl_certificate.ssh:
#!/usr/bin/env bash -e
SERVERNAME=$(echo "$1" | sed -E -e 's/https?:\/\///' -e 's/\/.*//')
echo "$SERVERNAME"
if [[ "$SERVERNAME" =~ .*\..* ]]; then
echo "Adding certificate for $SERVERNAME"
echo -n | openssl s_client -connect $SERVERNAME:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | tee /tmp/$SERVERNAME.cert
sudo security add-trusted-cert -d -r trustRoot -k "/Library/Keychains/System.keychain" /tmp/$SERVERNAME.cert
else
echo "Usage: $0 www.site.name"
echo "http:// and such will be stripped automatically"
fi
*Make the script executable (from the shell):
chmod +x whitelist_ssl_certificate.ssh
*Run the script for the domain you want (simply copy/pasting the full url works):
./whitelist_ssl_certificate.ssh https://your_website/whatever
A: When clicking the little crossed out lock icon next to the URL, you'll get a box looking like this:
After clicking the Certificate information link, you'll see the following dialog:
It tells you which certificate store is the correct one, it's the Trusted Root Certification Authorities store.
You can either use one of the methods outlined in the other answers to add the certificate to that store or use:
certutil -addstore -user "ROOT" cert.pem
*
*ROOT is the internal name of the certificate store mentioned earlier.
*cert.pem is the name of your self-signed certificate.
A: Fix for Chrome on Windows.
First, you need to export the certificate.
*
*Locate the url in the browser. “https” segment of the url will be
crossed out with the red line and there will be a lock symbol to the left.
*Right click on the crossed-out "https" segment.
*You will see an information window with various information
*Click “details”.
*Export the certificate, follow directions accept default settings.
To import
*
*Go to Chrome Settings
*Click on "advanced settings"
*Under HTTPS/SSL click to "Manage Certificates"
*Go to "Trusted Root Certificate Authorities"
*Click to "Import"
*There will be a pop up window that will ask you if you want to install this certificate. Click "yes".
A: As of Chrome 58+ I started getting certificate error on macOS due missing SAN. Here is how to get the green lock on address bar again.
*
*Generate a new certificate with the following command:
openssl req \
-newkey rsa:2048 \
-x509 \
-nodes \
-keyout server.key \
-new \
-out server.crt \
-subj /CN=*.domain.dev \
-reqexts SAN \
-extensions SAN \
-config <(cat /System/Library/OpenSSL/openssl.cnf \
<(printf '[SAN]\nsubjectAltName=DNS:*.domain.dev')) \
-sha256 \
-days 720
*Import the server.crt into your KeyChain, then double click in the certificate, expand the Trust, and select Always Trust
Refresh the page https://domain.dev in Google Chrome, so the green lock is back.
A: This post is already flooded with responses, but I created a bash script based on some of the other answers to make it easier to generate a self-signed TLS certificate valid in Chrome (Tested in Chrome 65.x). Hope it's useful to others.
self-signed-tls bash script
After you install (and trust) the certificate, don't forget to restart Chrome (chrome://restart)
Another tool worth checking out is CloudFlare's cfssl toolkit:
cfssl
A: I fixed this problem for myself without changing the settings on any browsers with proper SSL certifications. I use a mac so it required a keychain update to my ssl certifications. I had to add subject alt names to the ssl certification for chrome to accept it. As of today, this is for Chrome version number: 62.0.3202.94
My example are easy to use commands and config files:
add these files and this example is all in one root directory
ssl.conf
[ req ]
default_bits = 4096
distinguished_name = req_distinguished_name
req_extensions = req_ext
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
stateOrProvinceName = State or Province Name (full name)
localityName = Locality Name (eg, city)
organizationName = Organization Name (eg, company)
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
Run command to create certification:
openssl req -newkey rsa:4096 -nodes -keyout key.pem -x509 -days 3650 -out certificate.pem -extensions req_ext -config ssl.conf -subj '/CN=localhost/O=Stackflow/C=US/L=Los Angeles/OU=StackflowTech'
For macs only to add trusted certification (required):
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ./certificate.pem
For windows you will have to find how to verify our ssl certs locally independently. I don't use Windows. Sorry windows guys and gals.
I am using a node.js server with express.js with only requires my key and certification with something like this:
app.js
const https = require('https');
const Express = require('express');
const fs = require('fs');
const app = new Express();
const server = https.createServer({
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./certificate.pem'),
}, app);
server.listen(3000);
I may be doing this for other backend frames in the future, so I can update example this for others in the future. But this was my fix in Node.js for that issue. Clear browser cache and run your app on https://
Here's an example of running https://localhost on a Node.js server for Mac users:
https://github.com/laynefaler/Stack-Overflow-running-HTTPS-localhost
Happy Coding!
A: For Chrome on MacOS, if you have prepared a certificate:
*
*Quit Chrome (cmd+Q).
*Start the Keychain Access app and open the "Certificates" category.
*Drag your certificate file onto the Keychain Access window and type the password for the certificate file.
*Double click on your certificate and unfold the "Trust" list.
*
*In row "When using this certificate," choose "Always Trust."
*Close this stuff and type your password.
*Start Chrome and clear all caches.
*Check that everything is ok.
A: I tried everything and what made it work: When importing, select the right category, namely Trusted Root Certificate Authorities:
(sorry it's German, but just follow the image)
A: This worked for me:
*
*Using Chrome, hit a page on your server via HTTPS and continue past the red warning page (assuming you haven't done this already).
*Open up Chrome Settings > Show advanced settings > HTTPS/SSL > Manage Certificates.
*Click the Authorities tab and scroll down to find your certificate under the Organization Name that you gave to the certificate.
*Select it, click Edit (NOTE: in recent versions of Chrome, the button is now "Advanced" instead of "Edit"), check all the boxes and click OK. You may have to restart Chrome.
You should get the nice green lock on your pages now.
EDIT: I tried this again on a new machine and the certificate did not appear on the Manage Certificates window just by continuing from the red untrusted certificate page. I had to do the following:
*
*On the page with the untrusted certificate (https:// is crossed out in red), click the lock > Certificate Information. NOTE: on newer versions of chrome, you have to open Developer Tools > Security, and select View certificate.
*Click the Details tab > Export. Choose PKCS #7, single certificate as the file format.
*Then follow my original instructions to get to the Manage Certificates page. Click the Authorities tab > Import and choose the file to which you exported the certificate, and make sure to choose PKCS #7, single certificate as the file type.
*If prompted certification store, choose Trusted Root Certificate Authorities
*Check all boxes and click OK. Restart Chrome.
A: This is something that keeps coming up -- especially for Google Chrome on Mac OS X Yosemite!
Thankfully, one of our development team sent me this link today, and the method works reliably, whilst still allowing you to control for which sites you accept certificates.
https://www.reddit.com/r/sysadmin/comments/3ercx4/chrome_shortcut_past_the_your_connection_is_not/cthporl
jersully posts:
If you don't want to bother with internal certificates...
*
*Type chrome://flags/ in the address bar.
*Scroll to or search for Remember decisions to proceed through SSL errors for a specified length of time.
*Select Remember for three months.
A: SSL / HTTPS localhost fix on the mac / osx:
*
*Click the red lock with the cross in your address bar when trying to open your https localhost environment. There'll open a window with some information about the certificate.
*Click on "Details"
information window
*The chrome Developer tools opens on the tab 'Security'. Click on View Certificate.
The certificate image
*Add it to your 'System' keychain (not your 'login' keychain which is selected by default).
*Open your keychain (again) and find the certificate. Click on it and make sure you "Trust" all.
*Restart chrome and it should work.
A: I was experiencing the same issue: I had installed the certificate in to Windows' Trusted Root Authorities store, and Chrome still refused the certificate, with the error ERR_CERT_COMMON_NAME_INVALID. Note that when the certificate is not properly installed in the store, the error is ERR_CERT_AUTHORITY_INVALID.
As hinted by the name of the error, this comment, and this question, the problem was lying in the declared domain name in the certificate. When prompted for the "Common Name" while generating the certificate, I had to enter the domain name I was using to access the site (localhost in my case). I restarted Chrome using chrome://restart and it was finally happy with this new certificate.
A: It didn't work for me when I tried to import the certificate in the browser...
In chrome open Developer Tools > Security, and select View certificate.
Click the Details tab and export it.
// LINUX
sudo apt-get install libnss3-tools
certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n [EXPORTED_FILE_PATH] -i [EXPORTED_FILE_PATH]
Run this command and if you see the file You've just imported You are good to go!
certutil -d sql:$HOME/.pki/nssdb -L
// Windows
Start => run => certmgr.msc
On the left side select Trusted Root Certification Authorities => Personal.
Click on actions tab => All actions/import then choose the file You exported before from the browser
Don't forget to restart chrome!!!
GOOD LUCK! ;)
A: here my solution for WINDOWS maybe will work for LINUX
Git has openssl
C:\Program Files\Git\usr\bin\openssl.exe.
navigate to C:\Program Files\Git\usr\bin\ but add to the PATH best
create a folder for the certificate
create a file req.cnf
change the values like my company
do not delete the
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
there Chrome complains
C = CA CA is two letters country code CA=Canada, US...
ST = ON is Province ON = Ontario
req.cnf
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = CA
ST = ON
L = Toronto
O = MyCompany
OU = MyDivision
CN = localhost
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
DNS.2 = www.mydomainname.com
DNS.3 = mydomainname.com
create the certificate in CMD
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt -config req.cnf -sha256
cat server.crt server.key > server.pem
overwrite the dev certificate
yourproject\node_modules\webpack-dev-server\ssl with the **server.pem**
in chrome settings -> Manage certificates
import the server.crt to Trusted Certification Authorizes restart chrome
in package.json
"scripts": {
"start": "set HTTPS=true&&react-scripts start",
A: I just enabled allow-insecure-localhost flag in my chrome and that's it.
Steps.
*
*Type chrome://flags in your chrome tab.
*Search for allow-insecure-localhost flag and enable it.
*Relaunch the chrome browser.
Now you will not see the insecure warning for your https://localhost sites.
A: With only 5 openssl commands, you can accomplish this.
(Please don't change your browser security settings.)
With the following code, you can (1) become your own CA, (2) then sign your SSL certificate as a CA. (3) Then import the CA certificate (not the SSL certificate, which goes onto your server) into Chrome/Chromium. (Yes, this works even on Linux.)
NB: For Windows, some reports say that openssl must be run with winpty to avoid a crash.
######################
# Become a Certificate Authority
######################
# Generate private key
openssl genrsa -des3 -out myCA.key 2048
# Generate root certificate
openssl req -x509 -new -nodes -key myCA.key -sha256 -days 825 -out myCA.pem
######################
# Create CA-signed certs
######################
NAME=mydomain.example # Use your own domain name
# Generate a private key
openssl genrsa -out $NAME.key 2048
# Create a certificate-signing request
openssl req -new -key $NAME.key -out $NAME.csr
# Create a config file for the extensions
>$NAME.ext cat <<-EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = $NAME # Be sure to include the domain name here because Common Name is not so commonly honoured by itself
DNS.2 = bar.$NAME # Optionally, add additional domains (I've added a subdomain here)
IP.1 = 192.168.0.13 # Optionally, add an IP address (if the connection which you have planned requires it)
EOF
# Create the signed certificate
openssl x509 -req -in $NAME.csr -CA myCA.pem -CAkey myCA.key -CAcreateserial \
-out $NAME.crt -days 825 -sha256 -extfile $NAME.ext
To recap:
*
*Become a CA
*Sign your certificate using your CA cert+key
*Import myCA.pem as an "Authority" (not into "Your Certificates") in your Chrome settings (Settings > Manage certificates > Authorities > Import)
*Use the $NAME.crt and $NAME.key files in your server
Extra steps (for Mac, at least):
*
*Import the CA cert at "File > Import file", then also find it in the list, right click it, expand "> Trust", and select "Always"
*Add extendedKeyUsage=serverAuth,clientAuth below basicConstraints=CA:FALSE, and make sure you set the "CommonName" to the same as $NAME when it's asking for setup
You can check your work to ensure that the certificate is built correctly:
openssl verify -CAfile myCA.pem -verify_hostname bar.mydomain.example mydomain.example.crt
A: June 2021 - Windows 10 - Chrome v91 (SIMPLE)
Follow the cert generation instructions from selfsignedcertificate.com:
Example domain name: mydomain.local, replace it with your domain name.
*
*To generate a key:
openssl genrsa -out mydomain.local.key 2048
*Create the config file mydomain.local.conf with only the following content:
[req]
distinguished_name=req
[SAN]
subjectAltName=DNS:mydomain.local
Note: In subcjectAltName you can define more domains (optional), like:
subjectAltName=DNS:mydomain.local, DNS:*.mydomain.local, DNS:otherdomain.local, IP:192.168.1.10
*Create the certificate:
openssl req -new -x509 -key mydomain.local.key -out mydomain.local.crt -days 3650 -subj /CN=mydomain.local -extensions SAN -config mydomain.local.conf
*Add the Cert to Trusted Root Certification Authorities
*
*Right click the mydomain.local.crt file
*Select Install Certificate from the context menu.
*Choose Local Machine in the popup.
*Choose Place all certificates in the following store.
*Click Browse.
*Choose Trusted Root Certification Authorities.
*Click Ok, Next, Finish.
*Restart Chrome.
A: For a test environment
You can use --ignore-certificate-errors as a command line parameter when launching chrome (Working on Version 28.0.1500.52 on Ubuntu).
This will cause it to ignore the errors and connect without warning. If you already have a version of chrome running, you will need to close this before relaunching from the command line or it will open a new window but ignore the parameters.
I configure Intellij to launch chrome this way when doing debugging, as the test servers never have valid certificates.
I wouldn't recommend normal browsing like this though, as certificate checks are an important security feature, but this may be helpful to some.
A: WINDOWS JUN/2017 Windows Server 2012
I followed @Brad Parks answer. On Windows you should import rootCA.pem in Trusted Root Certificates Authorities store.
I did the following steps:
openssl genrsa -out rootCA.key 4096
openssl req -x509 -new -nodes -key rootCA.key -newkey rsa:4096 -sha256 -days 1024 -out rootCA.pem
openssl req -new -newkey rsa:4096 -sha256 -nodes -keyout device.key -out device.csr
openssl x509 -req -in device.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out device.crt -days 2000 -sha256 -extfile v3.ext
Where v3.ext is:
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
IP.1 = 192.168.0.2
IP.2 = 127.0.0.1
Then, in my case I have a self hosted web app, so I need to bind certificate with IP address and port, certificate should be on MY store with private key information, so I exported to pfx format.
openssl pkcs12 -export -out device.pfx -inkey device.key -in device.crt
With mmc console (File/Add or Remove Snap-ins/Certificates/Add/Computert Account/LocalComputer/OK) I imported pfx file in Personal store.
Later I used this command to bind certificate (you could also use HttpConfig tool):
netsh http add sslcert ipport=0.0.0.0:12345 certhash=b02de34cfe609bf14efd5c2b9be72a6cb6d6fe54 appid={BAD76723-BF4D-497F-A8FE-F0E28D3052F4}
certhash=Certificate Thumprint
appid=GUID (your choice)
First I tried to import the certificate "device.crt" on Trusted Root Certificates Authorities in different ways but I'm still getting same error:
But I realized that I should import certificate of root authority not certificate for domain. So I used mmc console (File/Add or Remove Snap-ins/Certificates/Add/Computert Account/LocalComputer/OK) I imported rootCA.pem in Trusted Root Certificates Authorities store.
Restart Chrome and et voilà it works.
With localhost:
Or with IP address:
The only thing I could not achieve is that, it has obsolete cipher (red square on picture). Help is appreciated on this point.
With makecert it is not possible add SAN information.
With New-SelfSignedCertificate (Powershell) you could add SAN information, it also works.
A:
What am I supposed to do to get Chrome to accept the certificate and stop complaining about it?
You should create a PKI with;
*
*self-signed Root CA.
*sub / intermediate certificate [signed by Root CA].
*normal / end-entity certificate [signed either by Root CA or sub-CA]
*
*commonName or subjectAltName (SAN) as "localhost".
*also include https://localhost/ as the URI in SAN.
*Import / Install that Root CA in your Windows OS as 'Trusted Root Certification Authorities'.
*
*Because you mentioned IE: Google Chrome is using the same resources while looking for certificates chain.
*Install that end-entity certificate as your web server certificate, and it stops complaining that error message.
Hope this helps.
A: I had success following the answer by kellen with the vital update from Toby J, but had to make this revision:
When creating the self-signed certificate, it was necessary to place the new subjectAltName field under the v3_ca extensions, instead of v3_req. I copied /etc/ssl/openssl.conf to a temporary file and then added a line subjectAltName = DNS:*.example.com under [ v3_ca ]. Then passed that file to the cert creation command, something like
openssl req -x509 -nodes -newkey rsa:2048 \
-config /tmp/openssl-revised.cfg \
-keyout example.com.key -out example.com.crt
and followed kellen's updated steps.
A: My solution and explanation:
I had self signed certificate, created with the IIS resource kit tool SelfSSL.exe. In the certificates lists on my local computer I saw that this self signed certificate had only one purpose: Server Authentication.
So I created new self signed certificate with both purposes: Server Authentication and Client Authentication. And now Chrome does not complain any more.
This article shows a lot of ways to generate self signed certificates. Note that not all options allow you to specify certificate purpose.
I used the PowerShell way:
$cert = New-SelfSignedCertificate -certstorelocation cert:\localmachine\my -dnsname company.co.nz
Note: As stated by this answer by kellen Chrome does allow you set the purposes for certificates, however IMO it cannot add new purpose for a certificate if the last was not created with such in mind.
A: Filippo Valsorda wrote a cross-platform tool, mkcert, to do this for lots of trust stores. I presume he wrote it for the same reason that there are so many answers to this question: it is a pain to do the "right" thing for SubjectAltName certificates signed by a trusted root CA.
mkcert is included in the major package management systems for Windows, macOS, and several Linux flavors. It is also mentioned in the Chromium docs in Step 4 of Testing Powerful Features.
mkcert
mkcert is a simple tool for making locally-trusted development certificates. It requires no configuration.
$ mkcert -install
Created a new local CA at "/Users/filippo/Library/Application Support/mkcert"
The local CA is now installed in the system trust store! ⚡️
The local CA is now installed in the Firefox trust store (requires browser restart)!
$ mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1
Using the local CA at "/Users/filippo/Library/Application Support/mkcert" ✨
Created a new certificate valid for the following names
- "example.com"
- "*.example.com"
- "example.test"
- "localhost"
- "127.0.0.1"
- "::1"
The certificate is at "./example.com+5.pem" and the key at "./example.com+5-key.pem" ✅
A: Click anywhere on the page and type a BYPASS_SEQUENCE:
BYPASS_SEQUENCE
Chrome Version
thisisunsafe
65 - ?
badidea
62 - 64
danger
? - 61
You don't need to look for input field, just type it. It feels strange but it works. I tried it on Mac High Sierra.
To double check if they changed it again, go to the latest Chromium source code. At the moment the BYPASS_SEQUENCE looks like this:
var BYPASS_SEQUENCE = window.atob('dGhpc2lzdW5zYWZl');
Now they have it camouflaged, but to see the real BYPASS_SEQUENCE you can run following line in a browser console.
console.log(window.atob('dGhpc2lzdW5zYWZl'));
OR
Alternatively to typing phrase you can paste the part of code in console
sendCommand(SecurityInterstitialCommandId.CMD_PROCEED)
A: As someone has noted, you need to restart ALL of Chrome, not just the browser windows. The fastest way to do this is to open a tab to...
chrome://restart
A: None of the answers above helped me on Windows 10 when testing locally on
https://localhost:<port>.
However I found this page, indicating another flag to pass:
https://www.chromium.org/blink/serviceworker/service-worker-faq
If you want to test on https://localhost with a self-signed certificate, do:
$ ./chrome --allow-insecure-localhost https://localhost
That did not get rid of the red warning, but it did enable me to use https-only feature like service workers and web push notifications.
A: Assuming you're on Mac OSX, you can also just open the URL in question in Safari; say; https://localhost:8080/css/app.css, allow the cert. Re-start Chrome, and it will work.
A: Update for Chrome 58+ (Released 2017-04-19)
As of Chrome 58, the ability to identify the host using only commonName was removed. Certificates must now use subjectAltName to identify their host(s). See further discussion here and bug tracker here. In the past, subjectAltName was used only for multi-host certs so some internal CA tools don't include them.
If your self-signed certs worked fine in the past but suddenly started generating errors in Chrome 58, this is why.
So whatever method you are using to generate your self-signed cert (or cert signed by a self-signed CA), ensure that the server's cert contains a subjectAltName with the proper DNS and/or IP entry/entries, even if it's just for a single host.
For openssl, this means your OpenSSL config (/etc/ssl/openssl.cnf on Ubuntu) should have something similar to the following for a single host:
[v3_ca] # and/or [v3_req], if you are generating a CSR
subjectAltName = DNS:example.com
or for multiple hosts:
[v3_ca] # and/or [v3_req], if you are generating a CSR
subjectAltName = DNS:example.com, DNS:host1.example.com, DNS:*.host2.example.com, IP:10.1.2.3
In Chrome's cert viewer (which has moved to "Security" tab under F12) you should see it listed under Extensions as Certificate Subject Alternative Name:
A: *
*Add the CA certificate in the trusted root CA Store.
*Go to chrome and enable this flag!
chrome://flags/#allow-insecure-localhost
At last, simply use the *.me domain or any valid domains like *.com and *.net and maintain them in the host file. For my local devs, I use *.me or *.com with a host file maintained as follows:
*Add to host.
C:/windows/system32/drivers/etc/hosts
127.0.0.1 nextwebapp.me
Note: If the browser is already opened when doing this, the error will keep on showing. So, please close the browser and start again. Better yet, go incognito or start a new session for immediate effect.
A: On the Mac, you can use the Keychain Access utility to add the self-signed certificate to the System keychain, and Chrome will then accept it. I found the step-by-step instructions here:
Google Chrome, Mac OS X and Self-Signed SSL Certificates
Basically:
*
*double-click the lock icon with an X and drag-and-drop the certificate icon to the desktop,
*open this file (ending with a .cer extension); this opens the keychain application which allows you to approve the certificate.
A: Are you sure the address the site is being served up as is the same as the certificate? I had the same problems with Chrome and a self-signed cert, but in the end I found it was just incredibly picky about the validation of the domain name on the cert (as it should be).
Chrome doesn't have it's own cert store and uses Window's own. However Chrome provides no way to import certs into the store so you should add them via IE instead.
Installing Certificates in Google Chrome
Installing Certificates in Internet Explorer
Also take a look at this for a couple of different approaches to creating self-signed certs (I'm assuming you're using IIS as you haven't mentioned).
How to Create a Self Signed Certificate in IIS 7
A: On the Mac, you can create a certificate that's fully trusted by Chrome and Safari at the system level by doing the following:
# create a root authority cert
./create_root_cert_and_key.sh
# create a wildcard cert for mysite.com
./create_certificate_for_domain.sh mysite.com
# or create a cert for www.mysite.com, no wildcards
./create_certificate_for_domain.sh www.mysite.com www.mysite.com
The above uses the following scripts, and a supporting file v3.ext, to avoid subject alternative name missing errors
If you want to create a new self signed cert that's fully trusted using your own root authority, you can do it using these scripts.
create_root_cert_and_key.sh
#!/usr/bin/env bash
openssl genrsa -out rootCA.key 2048
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem
create_certificate_for_domain.sh
#!/usr/bin/env bash
if [ -z "$1" ]
then
echo "Please supply a subdomain to create a certificate for";
echo "e.g. www.mysite.com"
exit;
fi
if [ ! -f rootCA.pem ]; then
echo 'Please run "create_root_cert_and_key.sh" first, and try again!'
exit;
fi
if [ ! -f v3.ext ]; then
echo 'Please download the "v3.ext" file and try again!'
exit;
fi
# Create a new private key if one doesnt exist, or use the xeisting one if it does
if [ -f device.key ]; then
KEY_OPT="-key"
else
KEY_OPT="-keyout"
fi
DOMAIN=$1
COMMON_NAME=${2:-*.$1}
SUBJECT="/C=CA/ST=None/L=NB/O=None/CN=$COMMON_NAME"
NUM_OF_DAYS=825
openssl req -new -newkey rsa:2048 -sha256 -nodes $KEY_OPT device.key -subj "$SUBJECT" -out device.csr
cat v3.ext | sed s/%%DOMAIN%%/"$COMMON_NAME"/g > /tmp/__v3.ext
openssl x509 -req -in device.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out device.crt -days $NUM_OF_DAYS -sha256 -extfile /tmp/__v3.ext
# move output files to final filenames
mv device.csr "$DOMAIN.csr"
cp device.crt "$DOMAIN.crt"
# remove temp file
rm -f device.crt;
echo
echo "###########################################################################"
echo Done!
echo "###########################################################################"
echo "To use these files on your server, simply copy both $DOMAIN.csr and"
echo "device.key to your webserver, and use like so (if Apache, for example)"
echo
echo " SSLCertificateFile /path_to_your_files/$DOMAIN.crt"
echo " SSLCertificateKeyFile /path_to_your_files/device.key"
v3.ext
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = %%DOMAIN%%
One more step - How to make the self signed certs fully trusted in Chrome/Safari
To allow the self signed certificates to be FULLY trusted in Chrome and Safari, you need to import a new certificate authority into your Mac. To do so follow these instructions, or the more detailed instructions on this general process on the mitmproxy website:
You can do this one of 2 ways, at the command line, using this command which will prompt you for your password:
$ sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain rootCA.pem
or by using the Keychain Access app:
*
*Open Keychain Access
*Choose "System" in the "Keychains" list
*Choose "Certificates" in the "Category" list
*Choose "File | Import Items..."
*Browse to the file created above, "rootCA.pem", select it, and click "Open"
*Select your newly imported certificate in the "Certificates" list.
*Click the "i" button, or right click on your certificate, and choose "Get Info"
*Expand the "Trust" option
*Change "When using this certificate" to "Always Trust"
*Close the dialog, and you'll be prompted for your password.
*Close and reopen any tabs that are using your target domain, and it'll be loaded securely!
and as a bonus, if you need java clients to trust the certificates, you can do so by importing your certs into the java keystore. Note this will remove the cert from the keystore if it already exists, as it needs to update it in case things change. It of course only does this for the certs being imported.
import_certs_in_current_folder_into_java_keystore.sh
KEYSTORE="$(/usr/libexec/java_home)/jre/lib/security/cacerts";
function running_as_root()
{
if [ "$EUID" -ne 0 ]
then echo "NO"
exit
fi
echo "YES"
}
function import_certs_to_java_keystore
{
for crt in *.crt; do
echo prepping $crt
keytool -delete -storepass changeit -alias alias__${crt} -keystore $KEYSTORE;
keytool -import -file $crt -storepass changeit -noprompt --alias alias__${crt} -keystore $KEYSTORE
echo
done
}
if [ "$(running_as_root)" == "YES" ]
then
import_certs_to_java_keystore
else
echo "This script needs to be run as root!"
fi
A: For localhost only
*
*Simply visit this link in your Chrome:
chrome://flags/#allow-insecure-localhost
*You should see highlighted text saying:
Allow invalid certificates for resources loaded from localhost
*Click Enable.
Options for other sites
*
*Try typing thisisunsafe anywhere on the window, and the browser should let you visit the page.
*For a local self-signed cert that avoids arcane commands, specialized knowledge, and manual steps, try mkcert from this answer.
A: I had to tweak the Chrome launcher on macosx and added below script.
Saved it as below;
/Applications/Google\ Chrome.app/Contents/MacOS/Chrome.command
#!/bin/sh
RealBin="Google Chrome"
AppDir="$(dirname "$0")"
exec "$AppDir/$RealBin" --ignore-certificate-errors "$@"
When I start Chrome with this script self-signed certificates are working without a problem. But don't browse the web with the browser launched with this script you will not be warned about invalid certificates!
A: Here is a solution using only Java 8 keytool.exe instead of openssl:
@echo off
set PWD=changeit
set DNSNAME=%COMPUTERNAME%
echo create ca key
keytool -genkeypair -alias ca -keystore test.jks -keyalg RSA -validity 3650 -ext bc:critical=ca:true -dname "CN=CA" -storepass:env PWD -keypass:env PWD
echo generate cert request for ca signing
keytool -certreq -keystore test.jks -storepass:env PWD -alias ca -file ca.csr -ext bc:critical=ca:true
echo generate signed cert
keytool -gencert -keystore test.jks -storepass:env PWD -alias ca -infile ca.csr -outfile ca.cer -validity 3650 -ext bc:critical=ca:true
echo CA created. Import ca.cer in windows and firefox' certificate store as "Trusted CA".
pause
echo create server cert key for %DNSNAME%
keytool -genkeypair -alias leaf -keystore test.jks -keyalg RSA -validity 3650 -ext bc=ca:false -ext san=dns:%DNSNAME%,dns:localhost,ip:127.0.0.1 -dname "CN=Leaf" -storepass:env PWD -keypass:env PWD
echo generate cert request
keytool -certreq -keystore test.jks -storepass:env PWD -alias leaf -file leaf.csr -ext bc=ca:false -ext san=dns:%DNSNAME%,dns:localhost,ip:127.0.0.1
echo generate signed cert
keytool -gencert -keystore test.jks -storepass:env PWD -alias ca -infile leaf.csr -outfile leaf.cer -validity 3650 -ext bc=ca:false -ext san=dns:%DNSNAME%,dns:localhost,ip:127.0.0.1
rem see content
rem keytool -printcert -file leaf.cer -storepass:env PWD
echo install in orig keystore
keytool -importcert -keystore test.jks -storepass:env PWD -file leaf.cer -alias leaf
echo content of test.jks:
keytool -list -v -storepass:env PWD -keystore test.jks
pause
You could also use pipes instead of files, but with the files, you can check the intermediate results if something goes wrong.
SSL tested with IE11, Edge, FF54, Chrome60 on windows and Chrome60 on Android.
Please change the default password before using the script.
A: Windows: Generate and self sign certificate
This is a "single-file" example to generate root and actual domain certificate on windows. Edit the first four variables, no further input from the CMD is required:
SET ROOT=my-root
SET NAME=demodomain
SET SUBJECT=/C=CH/O=My Demo Company
SET PASSWORD=ptGXHr3sudczSL9Q
:: Generate private key
openssl genrsa -des3 -out %ROOT%.key -passout pass:"%PASSWORD%" 2048
:: Generate root certificate
openssl req -x509 -new -nodes -key %ROOT%.key -sha256 -days 3650 -out %ROOT%.crt -passin pass:"%PASSWORD%" -subj "%SUBJECT%"
openssl genrsa -out %NAME%.key 2048
openssl req -new -key %NAME%.key -subj "%SUBJECT%/CN=%NAME%" -out %NAME%.csr
(
echo authorityKeyIdentifier=keyid,issuer
echo basicConstraints=CA:FALSE
echo keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
echo subjectAltName = @alt_names
echo [alt_names]
echo DNS = %NAME%)>config.ext
openssl x509 -req -in %NAME%.csr -CA "%ROOT%.crt" -CAkey "%ROOT%.key" -CAcreateserial -out %NAME%.crt -days 1780 -sha256 -extfile config.ext -passin pass:"%PASSWORD%"
:: cleanup files used for certificate generation
del %NAME%.csr
del config.ext
If you want to have the complete chain in one file add the following to your bat file:
:: build chain in certificate-file
echo %ROOT%.crt >> %NAME%.crt
Type "%ROOT%.crt" >> %NAME%.crt
Append the following if you want to verify the certificate:
openssl verify -CAfile "%ROOT%.crt" -verify_hostname %NAME% %NAME%.crt
Open your root certificate my-root.crt and add it to the windows certificate store (choose Trusted Root Certificate Authorities):
Final result in Chrome:
A: Okay, assume you have created a "Valid" self-signed cert. And it installs correctly on chrome ver 94. But when you go to the site, you do not get an ssl lock and get "not a valid certificate authority" error. In fact, it is a valid cert. But if you do not browse the site correctly, you will get this error. My DNS for my cert was DNS1: TFDM, DNS2: TFDM.local, DNS3: 172.31.42.251, DNS4: 192.168.20.50.
I was browsing 192.168.20.50 and it would not secure(lock). The problem was, the cert was for DNS1: TFDM. So I had to enter into my /etc/hosts file (centos7) 192.168.20.50 TFDM for resolution - then browse https://TFDM.
Problem solved. You MUST browse to the site properly. I thought it would resolve on the server side, but it must resolve on the client side. This is easily overlooked and can be your problem if everything else is correct.
Overriding security and the ssl features is asking for trouble, and I don't consider a proper solution. Self-signed certs work if applied correctly and follow the rules that Chrome keeps changing.
A: For mac with Angular Micro-frontend using NX
Step 1: create a self-signed root certificate
openssl req -x509 -nodes -new -sha256 -days 390 -newkey rsa:2048 -keyout "RootCA.key" -out "RootCA.pem" -subj "/C=de/CN=localhost.local"
openssl x509 -outform pem -in "RootCA.pem" -out "RootCA.crt"
Step 2: define domains and subdomains that should be included in the certificate
For this, just create a text file named vhosts_domains.ext and insert the following contents:
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
DNS.2 = *.mixable.blog.local
DNS.3 = mixable.blog.local
This example includes subdomains for a local development environment for the domain mixable.blog.local and all subdomains like www.mixable.blog.local or apps.mixable.blog.local.
Step 3: create the certificate
openssl req -new -nodes -newkey rsa:2048 -keyout localhost.key -out localhost.csr -subj "/C=de/ST=State/L=City/O=Organization/CN=localhost.local"
openssl x509 -req -sha256 -days 1024 -in localhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile vhosts_domains.ext -out localhost.crt
Step 4: make the certificate available for Angular application
nx serve host --open --devRemotes=<app names> --ssl --ssl-key <folder_location>/localhost.key --ssl-cert <folder_location>/localhost.crt
Step 5: add the certificates to macOS keychain from import
On chrome if you still get invalid certificate, then download the certificate and add to keychain and make all trusted.
A: For development purposes on Windows you canadd to Chrome shortcut flag --ignore-certificate-errors
It expected to ignore certificate errors and allow you to access invalid certificate websites.
Better detailed instructions in https://support.opendns.com/entries/66657664.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1663"
}
|
Q: Linq vb.net: Find Item in DataRow[] gefundeneID = drTerminal.AsEnumerable().Single(Function(s) s("TerminalID") = RandomID)
Have an array of DataRow and want to look if the RandomID is in one of the rows.
What's wrong with this code?
EDIT:
Got this error: The operator = isn't defined for DBNull and Integer
A: Apparently, your code has trouble comparing TerminalID, which can be DBNull, with the integer RandomID. You can avoid this problem by accessing TerminalID as follows:
...(Function(s) s.Field(Of Integer?)("TerminalID") = RandomID)
DataRow.Field provides strongly typed access to data fields, and, when used with nullable types (such as Integer?), automatically converts DBNulls to Nothing. Since Integer? (your field) and Integer (RandomID) can be compared with =, the above code should work fine.
As a side comment: I would recommend to turn on Option Strict, this avoids using a lot of implicit conversions all over the place and encourages good coding style. (Yes, you will get a lot of compile errors after turning it on, but it's for a good cause... for improving the quality of your code. With Option Strict On, your code example would not even have compiled.)
A: If you want to check to see if the ID is in your set, don't use Single as that will throw an exception if no match is found. If you only want to return true or false if the match is found, use .Any. If you want to return the found result, consider SingleOrDefault (if you know that there can only be 0-1 matches) or FirstOrDefault if you potentially can return multiple matches.
@Heinzi's comments regarding field nullability and Option Strict are worth considering as well.
A: try the following function:
Private Function ItemAdded(UserID As String) As Boolean
Return (tbl.Select(String.Format("UserID ='{0}'", UserID)).Count > 0)
End Function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Java listening for http messages I have a java program that can ask client programs questions. I would like to add functionality by embedding the questions I might ask into a hyperlink so that they can be asked by clicking on that link (i.e. main use in powerpoint slides).
The generated link might look something like this: "http://localhost:port/questiondata/"
The receiving program receives the link, decrypts the question data to post the question.
Could I make it so that my program on localhost listening on the port could detect when that link is pressed/sent?
There doesn't need to be any 2 way communication and it would always be asked on localhost, can I do that simply using java sockets listening on the port, or would i need to set up some form of webserver as a median.
I know very limited stuff about how http works, and I know tcp sockets need to be 2-way. Can anyone give me a recommendation of how I could possibly do this?
A: Sounds like you want an embedded HTTP server in your Java program (something like Jetty).
Or maybe you just need to make a web application and run that using something like Tomcat or Jetty.
Could I make it so that my program on localhost listening on the port could detect when that link is pressed/sent?
The web server would see the HTTP request that results in the user clicking on the link.
There doesn't need to be any 2 way communication
If you click a link in Powerpoint, it will open the page in a browser window. So your program gets to display something.
A: If you need a web server embedded inside your application you can write your own
or embed one like Jetty inside your program
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to create Bookmarklet for my website which requires user authentication I want to create a bookmarklet for my website. I just want to do same as Readitlater or as delicious.
Whenever you click on Read It Later or save on delicious bookmarklet if user is not logged in, it asks user to login to continue & then save the bookmark. Otherwise if user is logged in then it directly saves the bookmark for user.
I want to implement exactly the same in my website & I am working on Ruby on Rails platform.
I have following javascript code for bookmarklet
<a href="javascript:u=document.location.href;t=document.title; s=window.getSelection();
void(window.open('http://www.example.com/node/add/web2ob?edit[title]='+escape(t)+
'&edit[body_field][body]='+escape(s)+'&edit[field_link][0][url]='+escape(u),
'_blank','width=600,height=500,status=yes,resizable=yes,scrollbars=yes'));">
Add to my list</a>
I am new to this stuff so please guide me.
Thank you!
A: You have to check if the user is connected, if he is then just put your link, else, put another link which will pop up an authentication form and if he successfully sign in you'll execute your js code.
Like following: (I assume you're in a rails view, so in a html.erb file)
<% if user_signed_in? %>
<a href="javascript:u=document.location.href;t=document.title; s=window.getSelection();
void(window.open('http://www.example.com/node/add/web2ob?edit[title]='+escape(t)+
'&edit[body_field][body]='+escape(s)+'&edit[field_link][0][url]='+escape(u),
'_blank','width=600,height=500,status=yes,resizable=yes,scrollbars=yes'));">
Add to my list</a>
<% else %>
<a onclick="showLoginForm();">Add to my list</a>
<% end %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Problem with jquery and ajax I have two functions:
$(function() {
$(".deactivated").click(function() {
var Container = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('social/activate') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
Container.fadeOut(1000, function(){
$(this).load("<?php echo site_url('social/social_icon') ?>", {id: id}, function(){
$(this).hide().fadeIn(700);
$(this).click();
})
});
}
});
return false;
});
});
$(function() {
$(".activated").click(function() {
var Container = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('social/deactivate') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
Container.fadeOut(1000, function(){
$(this).load("<?php echo site_url('social/social_icon') ?>", {id: id}, function(){
$(this).hide().fadeIn(700);
})
});
}
});
return false;
});
});
One is to activate link and other is to deactivate it. Functions are working fine, but when link is activated or deactivated, it can't be clicked again to change it (page needs to be refreshed in order for functions to work again). What I need to do to make it work?
A: Change:
$(".activated").click(function() {
$(".deactivated").click(function() {
To:
$(".activated").live('click',function() {
$(".deactivated").live('click',function() {
A: You seem to be replacing the container and the elements inside it, so the elements that had the click events bound to them will have been removed.
You can fix this by changing your event handlers to use live:
$(".deactivated").live('click', function() {
and
$(".activated").live('click', function() {
A: Looks like you're replacing the links that you click which loses the event bindings.
Change the .click() to use .live('click'..
$(".deactivated").live('click', function() {
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why comparing 2 strings doesn't give desired result? Below is the code I've come up with and in all honesty tonight is my first attempt at coding at all. However I cannot seem to get my if statement to work properly. It just simply jumps to else even if I type Westley or westley or (space)Westley.
I want the program to be able to accept any of my team members names however I figured I get my name working and then I could add the rest of them later. Any thoughts or help would be wonderful. Also as a side note I was going to try and loop it if it went to the else back up to the begining any thoughts on that as well? Thank you
#include <iostream>
using namespace std;
int main ()
{
char Westley[] = "Westley";
char Alex[] = "Alex";
char Andrea[] = "Andrea";
char Bee[] = "Bee";
char Gia[] = "Gia";
char KaYeng[] = "Ka Yeng";
char Chi[] = "Chi";
char Corinne[] = "Corinne";
char Joyce[] = "Joyce";
char Parish[] = "Parish";
char membername [80];
cout << "Please Enter a Beta Team Members Name.\n";
cin >> membername;
if (membername == Westley)
{ cout << "BETA TEAM ROSTER!!\n";
cout << "Westley.\n";
cout << "Alex.\n";
cout << "Andrea.\n";
cout << "Bee.\n";
cout << "Gia.\n";
cout << "Ka Yeng.\n";
cout << "Chi.\n";
cout << "Corinne.\n";
cout << "Joyce.\n";
cout << "Parish.\n";
}
else
cout << "Not a Valid Beta Team Members Name!\n" << "Please Enter a Beta Team Members Name"<< endl;
cin >> membername;
return 0;
}
A: Don't use char[]; use std::string for this sort of thing as that knows how to do comparisons in a helpful way (comparisons between char arrays test if they are the same array, not if the contents is identical).
A: You can not use "==" operator. Try to find out more about
strcmp
if (strcmp(membername, "Westley") == 0)
...
A: this is c++ and you are using a char array not a string you need to use strcmp for string comparison
you can do this like
if(strcmp(membarname, Westley))
or if possible you can use std::string instead of char[] to store a string then you can use == operator
you can use the std::string as follows
#include <string>
using namespace std;
int main(){
string Westley = "Westley";
....
string membername;
cout << "Please Enter a Beta Team Members Name.\n";
cin >> membername;
if (membername == Westley){
....
}
....
}
A: Instead of character array char[]; use std::string and you will get the desired result.
if (membername == Westley)
Because, for char[] data, above comparison results in address comparison and not the content comparison.
A: Since it is arrays you are working with you need to use strmcp instead e.g.
if (!strcmp(membername, Westley) ...
since you are working in C++ use instead string:
#include <string>
using namespace std;
string Westley = "Westley";
...
then you can do
if (membername == Westley) ...
A: First of all, if you are coding with C++ you should use std::string instead of char []. It has the convenience that you can compare two strings (alas with char [] you have to call functions like strcmp or the like).
For example:
#include <iostream>
#include <string> // <-- important
using namespace std;
int main ()
{
string Westley("Westley");
...
if(membername == Westley) // now works!
{
...
A: The == operator you are using compares the addresses of the strings. To compare two C Strings use the strcmp function from <cstring> (string.h). In C++ you should use the std::string class template, which can be intuitively compared using the == operator.
A: if (membername == Westley)
only compare two pointers' value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: eclipse rcp : custom drawing on composite which has a FillLayout not work I am trying to add a PaintListener to draw a top border on a Composite :
pageComposite.addPaintListener(new PaintListener(){
@Override
public void paintControl(PaintEvent e) {
e.gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
e.gc.drawLine(0, 0, pageComposite.getBounds().width, 0);
}
});
but if the pageComposite is set with a FillLayout, the border will not be drawn.
Composite c = new Composite(parent, SWT.NONE);
c.setLayout(new FillLayout());
new Label(c, SWT.NONE).setText("类方法列表页面,尚未实现");
return c;
the composite created in above code looks like this:
another composite has a FormLayout:
final Composite c = new Composite(parent, SWT.NONE);
c.setLayout(new FormLayout());
Label l = new Label(c, SWT.NONE);
l.setText("角色用户机构列表页面,尚未实现");
FormData fd_content = new FormData();
fd_content.top = new FormAttachment(0, 10);
fd_content.left = new FormAttachment(0, 10);
l.setLayoutData(fd_content);
return c;
Did I miss anything ?
best regards!
A: With the SWT org.eclipse.swt.layout.FillLayout your paint event listener is not getting called and that's why your border is not getting drawn.
The reason is when you use FillLayout like this:
FillLayout fillLayout = new FillLayout();
composite.setLayout(fillLayout);
Then you are not setting any additional decorations like indentation, margin etc and hence an OS level update is not called on your window.
If you want to make it work then set some additional layout data like marginHeight. For example:
FillLayout fillLayout = new FillLayout();
fillLayout.marginHeight = 5;
composite.setLayout(fillLayout);
This is how it looks like after setting the above said layout decoration (note the top border):
>>Code
I have put some commented code. Try to remove the comment and see how it behaves.
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class FillLayoutTest
{
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout()); shell.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final Color c = new Color(display, new RGB(127, 127, 127));
final Composite composite = new Composite(shell, SWT.NONE);
FillLayout fillLayout = new FillLayout();
fillLayout.marginHeight = 5;
composite.setLayout(fillLayout);
//composite.setLayout(new GridLayout()); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
new Label(composite, SWT.BORDER).setText("Hello World!!");
new Label(composite, SWT.BORDER).setText("Hello World Version 2.0!!");
composite.addPaintListener(new PaintListener(){
public void paintControl(PaintEvent e) {
e.gc.setForeground(c);
e.gc.drawLine(0, 0, composite.getParent().getBounds().width, 0);
//throw new RuntimeException();
}
});
shell.open();
shell.pack();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
if(c != null && !c.isDisposed())
c.dispose();
if(display != null && !display.isDisposed())
display.dispose();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I set the tab order for multiple controls in XAML Do I have to manually set the TabIndex property of each control on my page, or is there a way I can select multiple controls and get either Expression Blend or Visual Studio to apply the tab index in the order I selected them.
I know this is a feature of other UI tools, but it seems Blend / VS doesn't have this option. If I have a page with many fields that could change position or add a new fields in half way it takes a lot of effort for not much gain to manually update all the tab indexes.
A: Why is the default tab order not sufficient? It's constructed from the ordering of the visual tree. Simply move your XAML around to create a different tab order; set IsTabStop to false to remove that control from the tab order.
A: I was able to solve this by setting IsTabStop="False" on the container element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to check whether a method exists in Python? In the function __getattr__(), if a referred variable is not found then it gives an error. How can I check to see if a variable or method exists as part of an object?
import string
import logging
class Dynamo:
def __init__(self,x):
print "In Init def"
self.x=x
def __repr__(self):
print self.x
def __str__(self):
print self.x
def __int__(self):
print "In Init def"
def __getattr__(self, key):
print "In getattr"
if key == 'color':
return 'PapayaWhip'
else:
raise AttributeError
dyn = Dynamo('1')
print dyn.color
dyn.color = 'LemonChiffon'
print dyn.color
dyn.__int__()
dyn.mymethod() //How to check whether this exist or not
A: How about looking it up in dyn.__dict__?
try:
method = dyn.__dict__['mymethod']
except KeyError:
print "mymethod not in dyn"
A: Maybe like this, assuming all method is callable
app = App(root) # some object call app
att = dir(app) #get attr of the object att #['doc', 'init', 'module', 'button', 'hi_there', 'say_hi']
for i in att:
if callable(getattr(app, i)):
print 'callable:', i
else:
print 'not callable:', i
A: If your method is outside of a class and you don't want to run it and raise an exception if it doesn't exist:
'mymethod' in globals()
A: I use below utility function. It works on lambda, class methods as well as instance methods.
Utility Method
def has_method(o, name):
return callable(getattr(o, name, None))
Example Usage
Let's define test class
class MyTest:
b = 'hello'
f = lambda x: x
@classmethod
def fs():
pass
def fi(self):
pass
Now you can try,
>>> a = MyTest()
>>> has_method(a, 'b')
False
>>> has_method(a, 'f')
True
>>> has_method(a, 'fs')
True
>>> has_method(a, 'fi')
True
>>> has_method(a, 'not_exist')
False
A: You can try using 'inspect' module:
import inspect
def is_method(obj, name):
return hasattr(obj, name) and inspect.ismethod(getattr(obj, name))
is_method(dyn, 'mymethod')
A: Check if class has such method?
hasattr(Dynamo, key) and callable(getattr(Dynamo, key))
or
hasattr(Dynamo, 'mymethod') and callable(getattr(Dynamo, 'mymethod'))
You can use self.__class__ instead of Dynamo
A: It's easier to ask forgiveness than to ask permission.
Don't check to see if a method exists. Don't waste a single line of code on "checking"
try:
dyn.mymethod() # How to check whether this exists or not
# Method exists and was used.
except AttributeError:
# Method does not exist; What now?
A: How about dir() function before getattr()?
>>> "mymethod" in dir(dyn)
True
A: For the people that likes simplicity.
class ClassName:
def function_name(self):
return
class_name = ClassName()
print(dir(class_name))
# ['__init__', .... ,'function_name']
answer = 'function_name' in dir(class_name)
print("is'function_name' in class ? >> {answer}")
# is 'function_name' in class ? >> True
A: I think you should look at the inspect package. It allows you to 'wrap' some of the things. When you use the dir method it also list built in methods, inherited methods and all other attributes making collisions possible, e.g.:
class One(object):
def f_one(self):
return 'class one'
class Two(One):
def f_two(self):
return 'class two'
if __name__ == '__main__':
print dir(Two)
The array you get from dir(Two) contains both f_one and f_two and a lot of built in stuff. With inspect you can do this:
class One(object):
def f_one(self):
return 'class one'
class Two(One):
def f_two(self):
return 'class two'
if __name__ == '__main__':
import inspect
def testForFunc(func_name):
## Only list attributes that are methods
for name, _ in inspect.getmembers(Two, inspect.ismethod):
if name == func_name:
return True
return False
print testForFunc('f_two')
This examples still list both methods in the two classes but if you want to limit the inspection to only function in a specific class it requires a bit more work, but it is absolutely possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "118"
}
|
Q: Git: set branch to current ref Due to the use of submodules in my projects I'm finding myself often on "(no branch)". As I'm also adding code to those submodules I'm committing in there. When I then want to push those submodules I need to be on a branch of course. Hence my question:
Is there a way/shortcut in git (command line) to set a local branch to the current commit/HEAD without the detour of
git checkout the_branch
git reset --hard <previous commit-ish>
To be more precise, my real problem with the above "detour" is that I'm temporarily leaving the original HEAD with the checkout-command. That can be avoid with the git branch -f command (thanks to CharlesB).
A: Checkout the branch with -B: this will reset the branch to HEAD, which is the current ref.
git checkout -B <branch>
From the docs:
If -B is given, is created if it doesn’t exist;
otherwise, it is reset. This is the transactional equivalent of
$ git branch -f <branch> [<start point>]
$ git checkout <branch>
that is to say, the branch is not reset/created unless "git
checkout" is successful.
A: git checkout -B the_branch HEAD
This will checkout the_branch at commit HEAD, even if the_branch pointed somewhere else before. It was added in one of the last few git releases, so you might not have it available. An alternate route would be git branch -D the_branch && git checkout -b the_branch
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "64"
}
|
Q: Respond with video file from local disk I'm trying to create controllers action that responds with local video file that is outside of the applications public directory. What I have now is
def video
render :text => File.read('D:/test.mp4'), :content_type => 'video/mp4'
end
browser recognizes that it should threat response as a video file however video content is not played appropriately. Am I missing something here? Do you know some better/other solution? Copying each file to the public directory seems to be a workaround but it also seems to be a really bad idea ). Thanks.
A: You should use send_file or send_data instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Evaluate a JQUERY statement I use this kind of script to evaluate my javascript code that is injected in the DOM
function wilEval(source) {
if ('function' == typeof source) {
source = '(' + source + ')();'
}
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.textContent = source;
document.body.appendChild(script);
if (window.execScript) {
window.execScript(source);
}
}
it works in IE and other major browsers but my problem is the code to be evaluated is a jquery code like this $("#<?php echo "utm".$thr_id; ?>").effect("highlight", {}, 1000); So how can evaluate it like a normal javascript code? thanks
P.S. the php echo just produce a dynamic element id =)
A: One thing you could do is use globalEval()
function wilEval(source) {
if ('function' == typeof source) {
source = '(' + source + ')();'
}
if (window.execScript) {
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.textContent = source;
document.body.appendChild(script);
window.execScript(source);
}else{
jQuery.globalEval(source);
}
}
A: so, your code is not a function but rather a statement
then, wrap it like that:
(function () { YOUR STATEMENT }());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NSOperationQueue problem with 1 maxConcurrentOperations I am confused and need your support.
I am implementing synchron http requests in separate thread and therefore I want to
use NSOperationQueue .
But there is a one problem connected with following:
When current request failed,I am going to do another recovery request,this means I should
add new prior item to my queue and after that repeat that request which failed .
Thanks for help
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Add an Apache POI WorkBook as attachment to a Javamail's MimeMessage without writing in the filesystem I'm trying to figure out how to pass a WorkBook (from the Apache POI library) "directly" to a MimeMessage object (from the Javamail library) as an attachment, without having to write it directly in the filesystem.
The simplest way to do this seems the following:
File attachmentSource = new File("tmpsource.xls");
WorkBook tmpWorkbook = new HSSFWorkBook();
//Do stuff with workbook
tmpWorkBook.write(new FileOutputStream(attachmentSource));
//Create all the Session, MimeMessage and MimeMultipart
MimeBodyPart attachment = new MimeBodyPart();
attachment.setDataHandler(new DataHandler(new FileDataSource(attachmentSource)));
attachment.setFileName(attachmentSource.getName());
//Do stuff with the message and send it
This way it works but I'm forced to write down the file into the FS.
While reading the related questions I found out about ByteArrayInputStream and ByteArrayOutputStream and seemed to solve my problem (Unless the file swells up to 2GB which seems very unlikely).
I hope I explained myself, I think the ByteArray streams will do the trick, by the way any help or advice are appreciated!
[09/29/2011]
I created a very simple DataSource implementation called (guess what) ByteArrayDataSource, so I have the automatic headers setup and Base64 encoding.
A: One of the MimeBodyPart constructors takes a byte array (the content of the attachment) as argument. So just write your workbook to a ByteArrayOutputStream, transform this stream to a byte array, and pass this byte array to the constructor:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
tmpWorkBook.write(baos);
MimeBodyPart attachment = new MimeBodyPart(internetHeaders, baos.toByteArray());
// or MimeBodyPart attachment =
// new MimeBodyPart(new ByteArrayInputStream(baos.toByteArray()));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Jquery, Add png data into src attr~ in php file,
...
...
header('Content-type: image/png');
imagepng($image1);
in html using jquery,(after loading, insert the image data)
$(document).ready(function(){
$.ajax({
"url": 'righturl/thephp.php',
"type": 'POST',
"data": {},
"success":function(result){
$("#hey").attr({"src":result});
}
})
});
but this makes just binary data inserted.
can not see the image.
<img id="hey" src="�PNG ��� IHDR������������j��� �IDATx�<�ٳ��q��U�[����}���eV�u0�@�Hɔ��P���?9�;�7�[M��D"�7`���C����=��ݷ����[m�~hH�P�|*��9'�����]X߸z���'v���?�w����/jQ�k�Ӗ��I����U��sOO������NǾ�M:�`H�!~���O^9����k�����w{W��k��<�����^��O��o���߄�4�#\�������ݟ�,/�q�ة�����H ����{�mC�N��4��ifl�@"�(�j�y9��|��իW��3���KKM-�����Ν;[��Q1��H� !z���4*-��������VVVvG��~#���Ή��A����`S���X3�a6A�00KCD�1���|���ML�&5��G�Rk���N��a�����E��>�ӡ�<�H1��P3#hA�Y�03(��LD���$Q��Ss#i*FEq�UC�����hQ7�E...1��Y�@���T�7q�?���&31HL�O��4������������3 �rj�鳗�U�Z�E�����(WC�on��7_M늽�|�]0��*v}@36�{�<�(��g�@��o@2%"F�"$��`2�QIfQ-b�rB33W$&�_�a�4l[kvy���5�)"A-�<:��:r�� ��^|�%��kJYUcJf��ui�6�� �̌��TTPA#��u�n�,�;�s���6 ��Y �R���AqВ}Q� �>`(�,}a��d]Rfed�FhH���U9q�U��t������b2"O�Kyc��<�m�1_:[Y��Tm�����߮���q�ic�q��yv:�ǁ��{�A�d#5K>��yo���5�������W-N��ߡ��eT�7���ۣ��Ӄ���A�bhH۾�m/+��ٔ�Lr`EjU�UI!眽3��~+���rZU؋����90����"$c�ө;����F���(}���g�����??훵�aG�ˢ�F)�zM�m2w�����D��|����IEND�B`�">
any idea to insert the image data into src attr dynamically?
A: I think you need something like
<img id="hey" src="righturl/thephp.php" />
So if it must be jquery
$("#hey").attr({"src":"righturl/thephp.php"});
Or am I missing something?
A: To insert an image data direct into a src attribute will never work. The attribute expect a value with type of string only. Try this way instead.
A: You need to base64 encode your image data and use the Data URI scheme:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Causes for crash during garbage collection I've been struggling now for some time with a crash in a C# application that also uses a fair share of C++/CLI modules that are mostly wrappers around native libraries to access device drivers.
The crash is not always easily reproducible but I was able to collect half a dozen crash dumps that shows that the program always crashes with an access violation during a garbage collection. This is the native callstack and the last event log:
0:000> k
ChildEBP RetAddr
0012d754 79f95a8f mscorwks!WKS::gc_heap::find_first_object+0x62
0012d7dc 79f933bb mscorwks!WKS::gc_heap::mark_through_cards_for_segments+0x493
0012d814 79f92cbf mscorwks!WKS::gc_heap::mark_phase+0xc3
0012d838 79f93245 mscorwks!WKS::gc_heap::gc1+0x62
0012d84c 79f92f5a mscorwks!WKS::gc_heap::garbage_collect+0x253
0012d878 79f94e26 mscorwks!WKS::GCHeap::GarbageCollectGeneration+0x1a9
0012d904 79f926ce mscorwks!WKS::gc_heap::try_allocate_more_space+0x15b
0012d918 79f92769 mscorwks!WKS::gc_heap::allocate_more_space+0x11
0012d938 79e73291 mscorwks!WKS::GCHeap::Alloc+0x3b
0:000> .lastevent
Last event: 7e8.88: Access violation - code c0000005 (first/second chance not available)
debugger time: Mon Sep 26 11:34:53.646 2011 (UTC + 2:00)
So let me first ask my question and give more details below. My question is: besides a managed heap corruption is there any other cause for a crash during garbage collection?
Now elaborating a bit, the reason I ask this is because I'm having a really hard time trying to identify the code that is corrupting the managed heap and can't seem to find a pattern for the memory that is (supposedly) overwritten.
I already tried to comment all "dangerous" C++/CLI code (specially the parts that use pinned handles) but this didn't help. In trying to find a pattern in the memory that is overwritten I looked at the dissassembled code at the point of the crash:
0:000> u .-a .+a
mscorwks!WKS::gc_heap::find_first_object+0x54:
79f935b9 89450c mov dword ptr [ebp+0Ch],eax
79f935bc 8bd0 mov edx,eax
79f935be 8b02 mov eax,dword ptr [edx]
79f935c0 83e0fe and eax,0FFFFFFFEh
79f935c3 f70000000080 test dword ptr [eax],80000000h <<<<CRASH
79f935c9 0f84b1000000 je mscorwks!WKS::gc_heap::find_first_object+0x73
0:000> r
eax=00000000 ebx=01c81000 ecx=01c80454 edx=01c82fe0 esi=012f0000 edi=000027e1
eip=79f935c3 esp=0012d738 ebp=0012d754 iopl=0 nv up ei pl zr na pe nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010246
mscorwks!WKS::gc_heap::find_first_object+0x62:
79f935c3 f70000000080 test dword ptr [eax],80000000h ds:0023:00000000=????????
The crash happens when trying to dereference the EAX register which is null. Now from what I see EAX was loaded from contents pointed to by the EDX register so I looked at the address stored there:
0:000> dd @edx-10
01c82fd0 06542778 00000000 00000000 01c82494
01c82fe0 00000000 00000000 00000000 00000000
01c82ff0 01b641d0 00000000 00000000 01c82380
EDIT: I now see that my analysis was wrong, lacking was an understanding of x86 addressing modes.
So I can see that starting at address 01c82fed (the value stored at EDX) the next 16 bytes are null.
But when looking at another similar crash dump I see the following:
0:000> dd @edx-10
018defd4 00000000 00000000 00000000 00000000
018defe4 00000000 00000000 018b468c 01742354
018deff4 00e0907f 00000000 00000000 00000000
So here the 16 bytes before address pointed by EDX and the next 8 from there are null. And the same happens in the other crash dumps that I have, I don't see a pattern here, i.e. it doesn't seem that some piece of code is simply overwriting this region of the memory.
Going back to the question what I would like to know is if there is some other explanation for the crash besides one piece of the code overwriting memory that it shouldn't. Or any advice at all in how to proceed, I'm really lost in this one here..
(could the pinned handles cause a problem? We have quite a few of them and what I think that is that is funny is that I always see 137 - no more no less - pinned handles with !gchandles at the point of the crash, it's a strange coincidence for me..).
EDIT: forgot to mention that we're using version 3.5 of the .Net framework. I see reports of similar crashes in .Net 4 when the background GC is active (somewhere there is a mention that this is a bug in .Net) but I don't think that this is relevant here since AFAIK there is no background GC in .Net 3.5.
A: Not sure if this helps, but generally don't use destructors or let GC handle unmanaged memory. Use the Dispose pattern instead, and move all destructor code to finalizers instead:
ref class MyClass
{
UnsafeObject data;
MyClass()
{
data = CreateUnsafeDataObject();
}
!MyClass() // IDisposable.Dispose()
{
DeleteUnsafeDataObject(data);
}
~MyClass() // Destructor
{
}
}
This will implement the IDisposable pattern on the object. Call Dispose to clear unmanaged data, and you'll at worst have a better chance of figuring out what exactly happens.
A: So unfortunately my question was a bit misleading since I was looking for alternative explanations besides a managed heap corruption - which turned out to be the problem in the end (caused by an unsafe copy of an unmanged to managed struct).
The problem is now solved and I'm posting my findings here in a separate answer, hope that this is ok.
A: You probably have an exception in one of your finalizers. I believe you need to check them one by one, because there is no place for errors in finalization queue. In case you don't have unmanaged code, its better to not have finalizer at all, just manually call Dispose.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Python app crashes when emit signal from callback I use my c++ library from python application with QT. It uses callback to communicate with UI.
My library is 'ts'. The problem is that my program crashes sometimes.
As I understood it crashes when call to emit(), but it happens rarely.
The simplified version of my program looks like this:
import ts
...
class Parser(QObject):
sig = Signal(ts.ProgramDescriptions)
ts = ts.Ts()
def init(self):
self.ts.SetProgramChangeCB(SetProgramListCB)
...
class Ui_Dialog(QMainWindow):
def __init__(self, pars):
self.parser = pars
...
def SetProgramListCB(programDesc):
print "SetProgramListCB"
ui.parser.sig.emit(programDesc)
def SetProgramList(programDesc):
print "SetProgramList"
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
Dialog = QDialog()
parser = Parser()
parser.init()
parser.sig.connect(SetProgramList, Qt.QueuedConnection)
parser.Start()
ui = Ui_Dialog(parser)
...
Help!
A: After finding out that the cause of crash is C++ exception (with help of phihag), I changed my code in this way, and that fixed the problem:
def SetProgramListCB(programDesc):
try:
print ui.ravisParser.sig
ui.ravisParser.sig.emit(programDesc)
except:
print "Error"
In case of proper work I have (output):
<PySide.QtCore.Signal object at 0x01DD88C0>
<PySide.QtCore.Signal object at 0x01DD88C0>
<PySide.QtCore.Signal object at 0x01DD88C0>
...
And in case of Error:
Error
<PySide.QtCore.Signal object at 0x01DD88C0>
<PySide.QtCore.Signal object at 0x01DD88C0>
<PySide.QtCore.Signal object at 0x01DD88C0>
...
So the reason why it crashed was that in first call to emit() signal 'sig' was not initialized.
I can't understand how it could happen, because callback is called from thread which starts when call to 'parser.Start()' which called after connect signal 'sig' :
parser.sig.connect(SetProgramList, Qt.QueuedConnection)
parser.Start()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Magento Cron Tab Job Time zone Im trying to figure out if my module cron is running at the correct time.
The cron for my module is set at 1am (0 1 * * *), the time zone of the default store is Western Europe (Paris, Berlin etc GMT +2), the server time is EDT (Eastern Daylight Time).
So on which time zone is the 1am schedule based on?
Thanks,
A: The Magento cron process runs under the UTC timezone.
This can be verified by temporarily adding a small log statement to the cron observer.
The method is:
Mage_Cron_Model_Observer::dispatch()
Look for this code in the first few lines:
$now = time();
Either right before or after, add this:
Mage::log("cron timezone: " . date_default_timezone_get(), Zend_Log::DEBUG);
Then check your var/log/system.log file and you will see that PHP/Magento is using the UTC timezone.
A: The Magento cron job log times are recorded in UTC. Actual run times are based off the TZ offset (server time). Here's a Cron Job Monitor script that shows you the jobs as they're scheduled and then their completion times. It also gives you UTC, the server time and your store time (single store). All three can be different.
Cron Job Monitor
For it to be useful, I set System Config to keep errors and logged information for 24 hours. That way you can actually monitor the big jobs that run in the early AM and confirm they're really running.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Restrict density in API 7 How can I restrict density in Manifest in early version than API 9. As I know since this API there is a tag
<compatible-screens>
<screen android:screenSize=["small" | "normal" | "large" | "xlarge"]
android:screenDensity=["ldpi" | "mdpi" | "hdpi" | "xhdpi"] />
...
</compatible-screens>
But in early versions I can only restrict screen size with
<supports-screens android:smallScreens="false"
android:normalScreens="true" android:largeScreens="true"
/>
Thanks in advance,
A: You can simple set your target SDK version to 9, and minSDK version to whatever you want. This way the density will be restricted on devices with API version 9 and higher, and on devices with API version lower than 9 only the screen size parameter will be checked. AFAIK, there's no other way to resolve this problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Omniture SiteCatalyst WATS addon I have a Flex Application, and I need to track site catalyst data with Omniture site-catalyst.
For testing the data, I am using WATS addon on ForeFox. All is going very fine, except to get site data in Report Suite History Panel of WATS addon, which available on bottom of this addon. Because I am not getting any data in Report Suite History Panel of WATS addon.
However with some suggestions, I tried different versions of Firefox, but all is in vain till now.
Thanks.
Himanshu Pareek
A: Oh, I got it. I was facing this problem with the latest version of WATS addon as 0.31, but when I added WATS version 0.30 its working for Report Suite Data Track. But be sure you have a firefox version below FF4.0, otherwise you won't be able to add WATS version 0.30 Thanks.
A: To use the WATS addon you could also modify the firefox configuration by entering "about:config" into the address bar.
Next you add the following entry ("extensions.checkCompatibility.4.0" (without quotes)) by right-clicking the browser -> new -> boolean. Set the boolean to false.
The "extensions.checkCompatibility.version" item will change the behavior of extensions checking the Firefox version. When, for example, you're working with Firefox 9 and want to use the WATS extension. You can add the compatibility setting: "extensions.checkCompatibility.version.9.0" (without quotes).
If you have any questions don't hesitate to ask.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change the content of fieldset html tag (or div, or whatever tag) dynamically. I'm creating a "Settings" web-page for a project (using asp.net framework 3.5 under VS 2010).
There is 2 fieldsets on the page:
the first) as menu with buttons that are named "Configuration", "Data output formats", etc
the second) for showing set of web-controls for particular chosen menu item.
The question:
As you can guess I need to change dynamically the content of that second fieldset.
By had searched in the internet I came to 2 choices:
1) create separate web-pages with web-controls for each of menu item and show them on the Settings web-page via use of iframe tag
2) write something like fieldset.innerHtml = "VERY long long long string line with html code" for every menu item choice. And it will be several such very long string lines caused several options available on the Settings page.
So what would you advise me to do, developers? Maybe it exists the 3 way to do this that allows to avoid of using iframes and writing long awkward hard-to-maintain string lines of html code?
A: I'm not familiar with ASP, but, couldn't you just code the HTML for the controls of each menu item in a separate file and perform some kind of conditional server-side inclusion?
If not, you could always build your elements server-side in a single asp page.
A: There's a third way, you can make your page with all the fields that you need, having a fieldset for "Configuration", another for "Data Output Formats", etc...
Then you play with the visibility, when you click on the buttons it hides all the other fieldsets and shows only the desired one.
It's easier to maintain, and you don't have to do any extra requests to the server
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook Like button causing error in Firefox I'm trying to use the Facebook 'Like' button on my site, but I cannot get it to work properly in Firefox. Using Firebug I can see that I am getting the error 'FB.provide is not a function', but I have no idea how to fix this.
It also appears that when I refresh the page in IE there is only about a 50/50 chance of the 'Like' button loading without causing an error.
Any help here would be appriciated.
Thanks.
A: This happens if you add the Facebook script twice on the site (search for "all.js").
Source: https://stackoverflow.com/a/4084335/2440
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7580595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.