text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Regular expression to get Url without Query string I am looking for a way to parse URL without queryString using Regular expression.
i have url like "http://abc.com/csd?/aaa/bbb"
expected is like "http://abc.com/csd"
Anybody help me on this.
A: If you just want everything before the query string:
^[^?]+
A: Regex r = new Regex("(^[^?]+)");
Match m = r.Match("http://example.com/csd?/aaa/bbb");
// m.Groups[0].Value is your URL
A: You could use Substring and IndexOf
var someString = "http://abc.com/csd?/aaa/bbb";
someString.Substring(0, someString.IndexOf('?') - 1);
while this does not fully comply with the requirements stated in your question, it might be an easier approach - if actual implementation does not need to be RegEx.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: why terminal mail doesn't work? I've just installed mail
sudo apt-get install mailutils
And I tried to send mail though a pipeline:
echo "message" | mail -s "subject" my@email.com
But I don't receive any mails on my inbox.
Why doesn't work? Do I need another package?
Thanks!
A: I Solved!
I had to edit this file and set this variables /etc/ssmtp/ssmtp.conf’:
root=username@gmail.com
mailhub=smtp.gmail.com:587
rewriteDomain=
hostname=username@gmail.com
UseSTARTTLS=YES
AuthUser=username
AuthPass=password
FromLineOverride=YES
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mobile platform communicating directly to database or via web service? I see two ways of going about feeding data to and from a mobile application.
First would be to directly connect to the database and perform queries directly.
The other option would be to build a REST API and indirectly interact with the database through a web service. There's a bit of a security hole here, which makes me think the former might be best.
I realize this doesn't touch specifically on a question about code, but moreso on the methodology of the scenario.
What are your thoughts?
A: The usual way would be through a REST API (or some other kind of web service / service layer).
Putting the database open in the wild, directly accessible from any outside device, is certainly a bigger security hole than using a service layer.
Plus, if your database is hosted by some web hosting company, there is a big chance that it's not even accessible directly from the web, only from the webspace you ordered with it (for security reasons!).
So you have no other choice than using a service layer in this case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to append the cookies values I have four cookie values like $.cookie('line1side1',{ path:'/'}) and $.cookie('line2side1',{ path:'/'})
I want to append this all values and assign it to the one text-box.
document.getElementsByName('Custom_Field_Custom7')[0].value= all values of cookie
How should I write?
A: This uses jQuery (I'm assuming you're using it since you reference $.cookie). Basically you can grab the current cookie collection, split it into the cookies and map the values into an array. Then just join the array and dump it into your textbox.
alert($.map(document.cookie.split(";"), function(c){ return c.split("=")[0]; }).join(", "));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: OpenLayers Vector Features issue in IE We are using OpenLayers Vector Layer with Features in our application. Everything works fine in FireFox, but in IE we are not able to find vector layer on the map. We are using OpenLayers-2.9 version.
Is this a bug or else we need to add any patch to to the code?
A: What rendering methods did you implement. Old IE won't support canvas, you should specify fallbacks to VML http://dev.openlayers.org/docs/files/OpenLayers/Layer/Vector-js.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Simple Twitter Oauth authorization asking for credentials every time I am making a simple twitter based login/signup system using the tutorial here. I get the oauth_token as well as oauth token secret every time I get the user to login. However, even when the user is already logged in, he is being asked to login again. I just wanted to know how do I check if the user is already logged in?
Do I need to store the oauth_token and oauth token secret in session? If I do store these in a session, how do i authenticate if they are valid?
The library used has something like this:
<?php
session_start();
class EpiOAuth
{
public $version = '1.0';
protected $requestTokenUrl;
protected $accessTokenUrl;
protected $authorizeUrl;
protected $consumerKey;
protected $consumerSecret;
protected $token;
protected $tokenSecret;
protected $signatureMethod;
public function getAccessToken()
{
$resp = $this->httpRequest('GET', $this->accessTokenUrl);
return new EpiOAuthResponse($resp);
}
public function getAuthorizationUrl()
{
$retval = "{$this->authorizeUrl}?";
$token = $this->getRequestToken();
return $this->authorizeUrl . '?oauth_token=' . $token->oauth_token;
}
public function getRequestToken()
{
$resp = $this->httpRequest('GET', $this->requestTokenUrl);
return new EpiOAuthResponse($resp);
}
public function httpRequest($method = null, $url = null, $params = null)
{
if(empty($method) || empty($url))
return false;
if(empty($params['oauth_signature']))
$params = $this->prepareParameters($method, $url, $params);
switch($method)
{
case 'GET':
return $this->httpGet($url, $params);
break;
case 'POST':
return $this->httpPost($url, $params);
break;
}
}
public function setToken($token = null, $secret = null)
{
$params = func_get_args();
$this->token = $token;
$this->tokenSecret = $secret;
}
public function encode($string)
{
return rawurlencode(utf8_encode($string));
}
protected function addOAuthHeaders(&$ch, $url, $oauthHeaders)
{
$_h = array('Expect:');
$urlParts = parse_url($url);
$oauth = 'Authorization: OAuth realm="' . $urlParts['path'] . '",';
foreach($oauthHeaders as $name => $value)
{
$oauth .= "{$name}=\"{$value}\",";
}
$_h[] = substr($oauth, 0, -1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $_h);
}
protected function generateNonce()
{
if(isset($this->nonce)) // for unit testing
return $this->nonce;
return md5(uniqid(rand(), true));
}
protected function generateSignature($method = null, $url = null, $params = null)
{
if(empty($method) || empty($url))
return false;
// concatenating
$concatenatedParams = '';
foreach($params as $k => $v)
{
$v = $this->encode($v);
$concatenatedParams .= "{$k}={$v}&";
}
$concatenatedParams = $this->encode(substr($concatenatedParams, 0, -1));
// normalize url
$normalizedUrl = $this->encode($this->normalizeUrl($url));
$method = $this->encode($method); // don't need this but why not?
$signatureBaseString = "{$method}&{$normalizedUrl}&{$concatenatedParams}";
return $this->signString($signatureBaseString);
}
protected function httpGet($url, $params = null)
{
if(count($params['request']) > 0)
{
$url .= '?';
foreach($params['request'] as $k => $v)
{
$url .= "{$k}={$v}&";
}
$url = substr($url, 0, -1);
}
$ch = curl_init($url);
$this->addOAuthHeaders($ch, $url, $params['oauth']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = $this->curl->addCurl($ch);
return $resp;
}
protected function httpPost($url, $params = null)
{
$ch = curl_init($url);
$this->addOAuthHeaders($ch, $url, $params['oauth']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params['request']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = $this->curl->addCurl($ch);
return $resp;
}
protected function normalizeUrl($url = null)
{
$urlParts = parse_url($url);
$scheme = strtolower($urlParts['scheme']);
$host = strtolower($urlParts['host']);
$port = intval($urlParts['port']);
$retval = "{$scheme}://{$host}";
if($port > 0 && ($scheme === 'http' && $port !== 80) || ($scheme === 'https' && $port !== 443))
{
$retval .= ":{$port}";
}
$retval .= $urlParts['path'];
if(!empty($urlParts['query']))
{
$retval .= "?{$urlParts['query']}";
}
return $retval;
}
protected function prepareParameters($method = null, $url = null, $params = null)
{
if(empty($method) || empty($url))
return false;
$oauth['oauth_consumer_key'] = $this->consumerKey;
$oauth['oauth_token'] = $this->token;
$oauth['oauth_nonce'] = $this->generateNonce();
$oauth['oauth_timestamp'] = !isset($this->timestamp) ? time() : $this->timestamp; // for unit test
$oauth['oauth_signature_method'] = $this->signatureMethod;
$oauth['oauth_version'] = $this->version;
// encoding
array_walk($oauth, array($this, 'encode'));
if(is_array($params))
array_walk($params, array($this, 'encode'));
$encodedParams = array_merge($oauth, (array)$params);
// sorting
ksort($encodedParams);
// signing
$oauth['oauth_signature'] = $this->encode($this->generateSignature($method, $url, $encodedParams));
return array('request' => $params, 'oauth' => $oauth);
}
protected function signString($string = null)
{
$retval = false;
switch($this->signatureMethod)
{
case 'HMAC-SHA1':
$key = $this->encode($this->consumerSecret) . '&' . $this->encode($this->tokenSecret);
$retval = base64_encode(hash_hmac('sha1', $string, $key, true));
break;
}
return $retval;
}
public function __construct($consumerKey, $consumerSecret, $signatureMethod='HMAC-SHA1')
{
$this->consumerKey = $consumerKey;
$this->consumerSecret = $consumerSecret;
$this->signatureMethod = $signatureMethod;
$this->curl = EpiCurl::getInstance();
}
}
class EpiOAuthResponse
{
private $__resp;
public function __construct($resp)
{
$this->__resp = $resp;
}
public function __get($name)
{
if($this->__resp->code < 200 || $this->__resp->code > 299)
return false;
parse_str($this->__resp->data, $result);
foreach($result as $k => $v)
{
$this->$k = $v;
}
return $result[$name];
}
}
A:
The normal flow dictates that applications send request tokens to oauth/authorize in Twitter's implementation of the OAuth Specification. To take advantage of "Sign in with Twitter", applications should send request tokens received in the oauth_token parameter to oauth/authenticate instead.
(c) https://dev.twitter.com/docs/auth/sign-in-with-twitter
So find where their library (or your code) performs request to /authorize endpoint and replace it with /authenticate
About tokens: as long as you've received user tokens - store it in some persistent storage (database, file, etc) since that tokens are permanent (they will be valid until user haven't revoked them manually).
A: Enable option "Sign in with Twitter" for application OAuth Settings
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Equivalent of time(7) SQL Server 2008 datatype in .NET What is the equivalent of SQL Server 2008's time(7) datatype in .NET? I want to store hours and minutes alone in that column, for this which datatype should I use in SQL Server!
A: MSDN gives a mapping between SQL data types and CLR data types - and it suggests TimeSpan and Nullable<TimeSpan> (for nullable columns) too. Note that how you access the data will determine how you actually get the value out though. DbDataReader doesn't have a GetTimeSpan method for example - but SqlDataReader does have such a method. I'd expect LINQ to SQL or Entity Framework to perform the mapping automatically.
A: Got a nice article from this link.
I will use timespan datatype in dot net as equivalent for time(7) datatype in SQL server to store hours and minutes.
A: As Jon Skeet said, Class SqlDataReader does have a GetTimeSpan Method
conn = new SqlConnection(blablabla);
conn.Open();
string sql = "SELECT * FROM MyTable";
SqlCommand sqlCommand = new SqlCommand(sql, conn);
reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
MyVeryOwnModel mvom = new MyVeryOwnModel();
mvom.timeStart = reader.GetTimeSpan(reader.GetOrdinal("column_time_start"));
mvom.timeEnd = reader.GetTimeSpan(reader.GetOrdinal("column_time_end"));
}
reader.Close();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: MAC address to IP conversion While there are many tutorials on IP to MAC address conversion not much is available for the reverse process. I've checked out RARP(which is just the protocol). Is there a method for MAC to IP conversion. Thanks!
A: On Linux you can get this type of information using arp command:
$ sudo arp -n
Address HWtype HWaddress Flags Mask Iface
192.168.1.5 ether 01:00:00:11:44:11 C eth0
192.168.1.6 ether 02:00:00:44:33:22 C eth0
A: I've exact solution of your question let me explain everything which you need like how to convert MAC address to IP address or MAC to IPv4 IPv6 IP address?
What is MAC Address? A mac address is 48 bits, an IPv6 address is 128 bits.
Here is the MAC to IP address conversion process step by step:
take the mac address: for example 52:74:f2:b1:a8:7f.
throw ff:fe in the middle: 52:74:f2:ff:fe:b1:a8:7f.
reformat to IPv6 notation 5274:f2ff:feb1:a87f.
convert the first octet from hexadecimal to binary: 52 -> 01010010.
invert the bit at index 6 (counting from 0): 01010010 -> 01010000.
convert octet back to hexadecimal: 01010000 -> 50.
replace first octet with newly calculated one: 5074:f2ff:feb1:a87f.
prepend the link-local prefix: fe80::5074:f2ff:feb1:a87f.
How MAC address converter tool works?
You can also use perfect MAC address converter can convert any MAC address into IPv4 internet protocol address ranges and IPV6 internet protocol address ranges . It takes MAC Address as input string and generates a query against given MAC address and conversion option like convert into IPv6 to IPv4 or both then performs the above steps. Query generates an output response according to selected options.As well as tool produces an invalid input message response if provided MAC address is invalid or not convert able.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a unified way to get content at a file:// or http:// URI scheme in Ruby? It appears the Net::HTTP library doesn't support loading of local file via file:// . I'd like to configure loading of content from a file or remotely, depending on environment.
Is there a standard Ruby way to access either type the same way, or barring that some succinct code that branches?
A: Do you know about open-uri?
require 'open-uri'
open("/home/me/file.txt") { |f| ... }
open("http://www.google.com") { |f| ... }
So to support either "http://" or "file://" in one statement, simply remove the "file://" from the beginning of the uri if it is present (and no need to do any processing for "http://"), like so:
uri = ...
open(uri.sub(%r{^file://}, ''))
A: Here's some experimental code that teaches "open-uri" to handle "file:" URIs:
require 'open-uri'
require 'uri'
module URI
class File < Generic
def open(*args, &block)
::File.open(self.path, &block)
end
end
@@schemes['FILE'] = File
end
A: As Ben Lee pointed out, open-uri is the way to go here. I've also used it in combination with paperclip for storing resources associated with models, which makes everything brilliantly simple.
require 'open-uri'
class SomeModel < ActiveRecord::Base
attr_accessor :remote_url
has_attached_file :resource # etc, etc.
before_validation :get_remote_resource, :if => :remote_url_provided?
validates_presence_of :remote_url, :if => :remote_url_provided?,
:message => 'is invalid or missing'
def get_remote_resource
self.resource = SomeModel.download_remote_resource(self.remote_url)
end
def self.download_remote_resource (uri)
io = open(URI.parse(uri))
def io.original_filename; base_uri.path.split('/').last; end
io.original_filename.blank? ? nil : io
rescue
end
end
# SomeModel.new(:remote_url => 'http://www.google.com/').save
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How can I combine some UserControls in SilverLight? Maybe it is a simple question, but I can’t find the answer.
I have three User controls that are different only with colour. There is code one of them:
<UserControl x:Class="SilverlightApplication14.NodePicture"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:SilverlightApplication14">
<UserControl.Resources>
<local:NodeViewModel x:Key="Children" />
</UserControl.Resources>
<Grid x:Name="LayoutRootNodePicture" Height="100" Width="100"
HorizontalAlignment="Center" DataContext="{Binding Source={StaticResource Children}, Path=Children}" >
<Canvas x:Name="ParentCanvas" Background="White" Width="100" Height="100" >
<Rectangle Fill="Yellow" Stroke="Blue" Width="100" Height="100" >
</Rectangle >
</Canvas>
<Image HorizontalAlignment="Center"
Source="add.png"
Stretch="Fill"
Width="16"
VerticalAlignment="Top"
Margin="0,0,2,2"
Height="16" MouseLeftButtonDown="Image_MouseLeftButtonDown">
</Image>
</Grid>
</UserControl>
How can I combine them into ObservableCollection Children?
public class NodeViewModel : INotifyPropertyChanged
{
public ObservableCollection<NodeViewModel> Children
{
get { return _children; }
set
{
_children = value;
NotifyChange("Children");
}
}
private void NotifyChange(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
And how can I use then elements of this controls collection?
Is there a simple (or a right way ) way of doing this?
A: As far as I understood you right, you have 3 user controls which have names something like NodePicture, GreenNodePicture and BlueNodePicture.
First of all, if the 3 controls differ to a very little degree, it would be better to have only one control which switches the color using some property value.
Let's suppose that your controls differ by the background color of the rectangle on the canvas. So I would change your control so:
<Grid x:Name="LayoutRootNodePicture" Height="100" Width="100"
HorizontalAlignment="Center">
<Canvas x:Name="ParentCanvas" Background="{Binding NodeColor}" Width="100" Height="100" >
</Canvas>
<Image HorizontalAlignment="Center"
Source="add.png"
Stretch="Fill"
Width="16"
VerticalAlignment="Top"
Margin="0,0,2,2"
Height="16" MouseLeftButtonDown="Image_MouseLeftButtonDown">
</Image>
</Grid>
I've removed the Resources section because the view shouldn't create new view model objects, it should use an existing DataContext. You can see that the background color of the rectangle is based on the property NodeColor of the view model.
Let's add this property to the view model:
public class NodeViewModel : INotifyPropertyChanged
{
private SolidColorBrush _nodeColor;
public SolidColorBrush NodeColor
{
get { return _nodeColor; }
set
{
_nodeColor = value;
NotifyChange("NodeColor");
}
}
//...
And now if you want to display 3 controls with different color you should create 3 view models with different properties. Here is the example of the red, blue and green viewmodels:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
var redBrush = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
var greenBrush = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));
var blueBrush = new SolidColorBrush(Color.FromArgb(255, 0, 0, 255));
this.DataContext = new MainViewModel
{
Nodes = new ObservableCollection<NodeViewModel>{
new NodeViewModel
{
NodeColor = redBrush,
Children = new ObservableCollection<NodeViewModel>{
new NodeViewModel { NodeColor = greenBrush, LeftOffset = 65, TopOffset = 10},
new NodeViewModel { NodeColor = greenBrush, LeftOffset = 55, TopOffset = 60}
}
}, //red
new NodeViewModel { NodeColor = greenBrush}, //green
new NodeViewModel { NodeColor = blueBrush} //blue
}
};
}
}
public class MainViewModel
{
public ObservableCollection<NodeViewModel> Nodes { get; set; }
}
View models are translated into the views using data templates:
<ListBox ItemsSource="{Binding Nodes}">
<ListBox.ItemTemplate>
<DataTemplate>
<local:NodePicture DataContext="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I haven't used the Children property because I haven't understood where to use it. Maybe child nodes are displayed on the canvas. Anyway if it is important - you can provide additional information and I'll help with this.
Update:
The easiest way to draw child items on the canvas is to add the dependency property which updates the canvas when the collection is updated:
public partial class NodePicture : UserControl
{
public NodePicture()
{
InitializeComponent();
}
public IEnumerable<NodeViewModel> ChildViewModels
{
get { return (IEnumerable<NodeViewModel>)GetValue(ChildViewModelsProperty); }
set { SetValue(ChildViewModelsProperty, value); }
}
public static readonly DependencyProperty ChildViewModelsProperty =
DependencyProperty.Register("ChildViewModels", typeof(IEnumerable<NodeViewModel>), typeof(NodePicture),
new PropertyMetadata(null, (s, e) => ((NodePicture)s).UpdateCanvas()));
private void UpdateCanvas()
{
this.ParentCanvas.Children.Clear();
var items = this.ChildViewModels;
if(items == null)
return;
var controls = items.Select(item=>
{
var e = new Ellipse{Width = 20, Height = 20};
e.Fill = item.NodeColor;
//Or using the data binding
//BindingOperations.SetBinding(e, Ellipse.FillProperty, new Binding("NodeColor") { Source = item });
Canvas.SetLeft(e, item.LeftOffset);
Canvas.SetTop(e, item.TopOffset);
return e;
});
foreach(var c in controls)
this.ParentCanvas.Children.Add(c);
}
Where the TopOffset and LeftOffset are the properties of the NodeViewModel class.
After that you should set this property in the xaml code:
<DataTemplate>
<local:NodePicture DataContext="{Binding}" ChildViewModels="{Binding Children}" />
</DataTemplate>
It won't work with the ObservableColelction class because i didn't handle the CollectionChanged event.
Another approach - to use the ListBox control with the custom ItemsPanelTemplate and ListBoxItem ControlTemplate. But it is the much more complex solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android Market statistics frozen nearly month, what's going on? I have several applications in Android Market and 2 or 3 weeks ago I have noticed that statistics still the same. Just before that I have had several hundreds downloads per week. For sure I reported issue to Google guys, but nothing except standard - we're investigating problem...
Probably anyone knows, what's going on? Are there anyone who's experiencing similar troubles?
A: Okay, now it works, statistics were frozen but there were downloads - seems to be Google fixed issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jquery Validation - trying to Validate Radio and checkbox bottons and use ErrorPlacemant to display Error Below each group Newbie here
I am trying to get Radio buttons and checkbox buttons to validate.
Error message should appear under the last it's groups of radio/checkbox
The radio buttons requires a selection
The check buttons Required one selected minimum
--- On the Media, since all have a unique ID I treated it as a group, but am lost on
addMethod to validate group.
--- Also on errorPlacement what do I do if I don't have an Element ID?
http://jsbin.com/aqekah/14
Mostly OK, but now I get wrong number of InValids in my alert
A: We had this come up just the other day actually, this is how I resolved it:
var validator = $('form#yourID').validate({
errorPlacement: function (error, element) {
if (element.is(":radio")) {
element.closest('.rbl').after(error);
element.closest('.rbl').addClass('error');
}
else if (element.is(":checkbox")) {
element.closest('.cbl').after(error);
element.closest('.cbl').addClass('error');
}
else { // This is the default behavior of the script
error.insertAfter(element);
}
},
rules: { ...
Where .rbl is a <table> tag and looks like this with the following css:
<table cellpadding="0" cellspacing="0" class="rbl">
<tr><td><label><input type="radio" name="myradio" value="1"> Radio 1</label></td></tr>
<tr><td><label><input type="radio" name="myradio" value="2"> Radio 2</label></td></tr>
</table>
css:
FORM .rbl
{
float: left;
}
FORM .rbl TD
{
padding: 4px 24px 0 0;
}
The same can be applied for checkbox lists with a .cbl. All other non-radio and checkbox types will use standard error placement.
Hope that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Test if a variable is defined in javascript? How should I test if a variable is defined?
if //variable is defined
//do this
else
//do this
A: Use the in operator.
'myVar' in window; // for global variables only
typeof checks will return true for a variable if,
*
*it hasn't been defined
*it has been defined and has the value undefined, or
*it has been defined but not initialized yet.
The following examples will illustrate the second and third point.
// defined, but not initialized
var myVar;
typeof myVar; // undefined
// defined, and initialized to undefined
var myVar = undefined;
typeof myVar; // undefined
A: if (typeof variable !== 'undefined') {
// ..
}
else
{
// ..
}
find more explanation here:
JavaScript isset() equivalent
A: You simply check the type.
if(typeof yourVar !== "undefined"){
alert("defined");
}
else{
alert("undefined");
}
A: You can use something like this
if (typeof varname !== 'undefined') {
// do this
} else {
// do that
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: CSS Multiple grouped elements with margins Take this HTML:
<div>
<div class="block">Hello</div>
<div class="block">Hello</div>
<div class="block">Hello</div>
<div class="block">Hello</div>
</div>
With the companion CSS:
div.block
{
float: left;
width: 100px;
height: 100px;
margin: 1px;
background: red;
}
The result of this is four blocks, which have between them 2 pixels of space (1px from the right margin of the left block and 1px from the left margin of the right block).
Is there a way that I can achieve a similar effect to border-collapse? ie. I want there to be only one pixel of margin between adjacent blocks.
This is a basic example of often more complex situations that I run into, and I don't want to get around it by by anything similar to only setting margin-left to 1 pixel etc.
A: There are multiple ways to this
One of them is
div.block
{
float: left;
width: 100px;
height: 100px;
margin: 1px 1px 1px 0;
background: red;
}
div.block:last-child {
margin: 1px 0 1px 0;
}
Another is
div.block+div.block { margin-left: 1px; }
You can check the demo of both way here
A: How about using the CSS selector :first-child and :last-child to alter the first and last <div>?
div.block
{
float: left;
width: 100px;
height: 100px;
margin: 2px 1px 2px 0;
background: red;
}
div.block:first-child {
margin-left: 2px;
}
div.block:last-child {
margin-right: 2px;
}
A: If you can alter the markup itself, then I guess we can have a cross browser compatible solution:
<div class="block"> <div class="block_2"></div> </div>
and then apply the css like:
div.block{float: left; width: 100px; height: 100px; }
div.block_2{width:99px; height:100px; background-color:red}
A: Assign a class for last block called 'last'.
The set margin-right of every block to 1px.
Set margin-right of block that has last class to 0.
.block.last { margin-right: 0px; }
Pseudo selectors like forst-child and last-child are not well supported so I think this is the best option you have.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Taking the Response from the Printer by using Xon and Xoff how to retrieve the printer response from the Bluetooth printer in android by using X-On and X-Off. I have tried but It is not working. I have tried with the following code but it is not working:
CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM");
SerialPort sPort = (SerialPort)portId .open(this.getClass().getName(), 30000);
sPort.setSerialPortParams(9600, SerialPort.DATABITS_8,SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
sPort.setFlowControlMode(SerialPort.FLOWCONTROL_XONXOFF_IN | SerialPort.FLOWCONTROL_XONXOFF_OUT);
OutputStream os = sPort.getOutputStream();
os= sPort.getOutputStream();
InputStream is = sPort.getInputStream();
os.write(baos.toByteArray(), 0, baos.toByteArray().length);
StringBuffer inputBuffer = new StringBuffer();
do{
for(int newData = is.read();newData != -1; newData = is.read())
{
inputBuffer.append((char)newData);
}
try
{
Thread.sleep(300);
}
catch
{
}
}while(inputBuffer.length() <= 0);
String sDataIn = inputBuffer.toString();
In the above program when the flow comes in the following line it give an error:
CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM");
Error is::java.lang.ExceptionInInitializerError
A: Huh? CommPortIdentifier class does not exist in Android. How did you even get this to compile?
Also, Android is not Windows so serial ports (if they existed) would not be called "COM".
If you want to talk to your Bluetooth printer, first make sure it supports RFCOMM as this is the only Bluetooth protocol that is available in Android API, second see the Bluetooth tutorial: http://developer.android.com/guide/topics/wireless/bluetooth.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bash: Split string into character array I have a string in a Bash shell script that I want to split into an array of characters, not based on a delimiter but just one character per array index. How can I do this? Ideally it would not use any external programs. Let me rephrase that. My goal is portability, so things like sed that are likely to be on any POSIX compatible system are fine.
A: The most simple, complete and elegant solution:
$ read -a ARRAY <<< $(echo "abcdefg" | sed 's/./& /g')
and test
$ echo ${ARRAY[0]}
a
$ echo ${ARRAY[1]}
b
Explanation: read -a reads the stdin as an array and assigns it to the variable ARRAY treating spaces as delimiter for each array item.
The evaluation of echoing the string to sed just add needed spaces between each character.
We are using Here String (<<<) to feed the stdin of the read command.
A: I have found that the following works the best:
array=( `echo string | grep -o . ` )
(note the backticks)
then if you do: echo ${array[@]} ,
you get: s t r i n g
or: echo ${array[2]} ,
you get: r
A: Pure Bash solution with no loop:
#!/usr/bin/env bash
str='The quick brown fox jumps over a lazy dog.'
# Need extglob for the replacement pattern
shopt -s extglob
# Split string characters into array (skip first record)
# Character 037 is the octal representation of ASCII Record Separator
# so it can capture all other characters in the string, including spaces.
IFS= mapfile -s1 -t -d $'\37' array <<<"${str//?()/$'\37'}"
# Strip out captured trailing newline of here-string in last record
array[-1]="${array[-1]%?}"
# Debug print array
declare -p array
A: You can access each letter individually already without an array conversion:
$ foo="bar"
$ echo ${foo:0:1}
b
$ echo ${foo:1:1}
a
$ echo ${foo:2:1}
r
If that's not enough, you could use something like this:
$ bar=($(echo $foo|sed 's/\(.\)/\1 /g'))
$ echo ${bar[1]}
a
If you can't even use sed or something like that, you can use the first technique above combined with a while loop using the original string's length (${#foo}) to build the array.
Warning: the code below does not work if the string contains whitespace. I think Vaughn Cato's answer has a better chance at surviving with special chars.
thing=($(i=0; while [ $i -lt ${#foo} ] ; do echo ${foo:$i:1} ; i=$((i+1)) ; done))
A: string=hello123
for i in $(seq 0 ${#string})
do array[$i]=${string:$i:1}
done
echo "zero element of array is [${array[0]}]"
echo "entire array is [${array[@]}]"
The zero element of array is [h]. The entire array is [h e l l o 1 2 3 ].
A: Yet another on :), the stated question simply says 'Split string into character array' and don't say much about the state of the receiving array, and don't say much about special chars like and control chars.
My assumption is that if I want to split a string into an array of chars I want the receiving array containing just that string and no left over from previous runs, yet preserve any special chars.
For instance the proposed solution family like
for (( i=0 ; i < ${#x} ; i++ )); do y[i]=${x:i:1}; done
Have left overs in the target array.
$ y=(1 2 3 4 5 6 7 8)
$ x=abc
$ for (( i=0 ; i < ${#x} ; i++ )); do y[i]=${x:i:1}; done
$ printf '%s ' "${y[@]}"
a b c 4 5 6 7 8
Beside writing the long line each time we want to split a problem, so why not hide all this into a function we can keep is a package source file, with a API like
s2a "Long string" ArrayName
I got this one that seems to do the job.
$ s2a()
> { [ "$2" ] && typeset -n __=$2 && unset $2;
> [ "$1" ] && __+=("${1:0:1}") && s2a "${1:1}"
> }
$ a=(1 2 3 4 5 6 7 8 9 0) ; printf '%s ' "${a[@]}"
1 2 3 4 5 6 7 8 9 0
$ s2a "Split It" a ; printf '%s ' "${a[@]}"
S p l i t I t
A: As an alternative to iterating over 0 .. ${#string}-1 with a for/while loop, there are two other ways I can think of to do this with only bash: using =~ and using printf. (There's a third possibility using eval and a {..} sequence expression, but this lacks clarity.)
With the correct environment and NLS enabled in bash these will work with non-ASCII as hoped, removing potential sources of failure with older system tools such as sed, if that's a concern. These will work from bash-3.0 (released 2005).
Using =~ and regular expressions, converting a string to an array in a single expression:
string="wonkabars"
[[ "$string" =~ ${string//?/(.)} ]] # splits into array
printf "%s\n" "${BASH_REMATCH[@]:1}" # loop free: reuse fmtstr
declare -a arr=( "${BASH_REMATCH[@]:1}" ) # copy array for later
The way this works is to perform an expansion of string which substitutes each single character for (.), then match this generated regular expression with grouping to capture each individual character into BASH_REMATCH[]. Index 0 is set to the entire string, since that special array is read-only you cannot remove it, note the :1 when the array is expanded to skip over index 0, if needed.
Some quick testing for non-trivial strings (>64 chars) shows this method is substantially faster than one using bash string and array operations.
The above will work with strings containing newlines, =~ supports POSIX ERE where . matches anything except NUL by default, i.e. the regex is compiled without REG_NEWLINE. (The behaviour of POSIX text processing utilities is allowed to be different by default in this respect, and usually is.)
Second option, using printf:
string="wonkabars"
ii=0
while printf "%s%n" "${string:ii++:1}" xx; do
((xx)) && printf "\n" || break
done
This loop increments index ii to print one character at a time, and breaks out when there are no characters left. This would be even simpler if the bash printf returned the number of character printed (as in C) rather than an error status, instead the number of characters printed is captured in xx using %n. (This works at least back as far as bash-2.05b.)
With bash-3.1 and printf -v var you have slightly more flexibility, and can avoid falling off the end of the string should you be doing something other than printing the characters, e.g. to create an array:
declare -a arr
ii=0
while printf -v cc "%s%n" "${string:(ii++):1}" xx; do
((xx)) && arr+=("$cc") || break
done
A: Try
echo "abcdefg" | fold -w1
Edit: Added a more elegant solution suggested in comments.
echo "abcdefg" | grep -o .
A: If your string is stored in variable x, this produces an array y with the individual characters:
i=0
while [ $i -lt ${#x} ]; do y[$i]=${x:$i:1}; i=$((i+1));done
A: If the text can contain spaces:
eval a=( $(echo "this is a test" | sed "s/\(.\)/'\1' /g") )
A: $ echo hello | awk NF=NF FS=
h e l l o
Or
$ echo hello | awk '$0=RT' RS=[[:alnum:]]
h
e
l
l
o
A: I know this is a "bash" question, but please let me show you the perfect solution in zsh, a shell very popular these days:
string='this is a string'
string_array=(${(s::)string}) #Parameter expansion. And that's it!
print ${(t)string_array} -> type array
print $#string_array -> 16 items
A: This is an old post/thread but with a new feature of bash v5.2+ using the shell option patsub_replacement and the =~ operator for regex. More or less same with @mr.spuratic post/answer.
str='There can be only one, the Highlander.'
regexp="${str//?/(&)}"
[[ "$str" =~ $regexp ]] &&
printf '%s\n' "${BASH_REMATCH[@]:1}"
Or by just: (which includes the whole string at index 0)
declare -p BASH_REMATCH
If that is not desired, one can remove the value of the first index (index 0), with
unset -v 'BASH_REMATCH[0]'
instead of using printf or echo to print the value of the array BASH_REMATCH
One can check/see the value of the variable "$regexp" with either
declare -p regexp
Output
declare -- regexp="(T)(h)(e)(r)(e)( )(c)(a)(n)( )(b)(e)( )(o)(n)(l)(y)( )(o)(n)(e)(,)( )(t)(h)(e)( )(H)(i)(g)(h)(l)(a)(n)(d)(e)(r)(.)"
or
echo "$regexp"
Using it in a script, one might want to test if the shopt is enabled or not, although the manual says it is on/enabled by default.
Something like.
if ! shopt -q patsub_replacement; then
shopt -s patsub_replacement
fi
But yeah, check the bash version too! If you're not sure which version of bash is in use.
if ! ((BASH_VERSINFO[0] >= 5 && BASH_VERSINFO[1] >= 2)); then
printf 'No dice! bash version 5.2+ is required!\n' >&2
exit 1
fi
Space can be excluded from regexp variable, change it from
regexp="${str//?/(&)}"
To
regexp="${str//[! ]/(&)}"
and the output is:
declare -- regexp="(T)(h)(e)(r)(e) (c)(a)(n) (b)(e) (o)(n)(l)(y) (o)(n)(e) (t)(h)(e) (H)(i)(g)(h)(l)(a)(n)(d)(e)(r)(.)"
*
*Maybe not as efficient as the other post/answer but it is still a solution/option.
A: If you want to store this in an array, you can do this:
string=foo
unset chars
declare -a chars
while read -N 1
do
chars[${#chars[@]}]="$REPLY"
done <<<"$string"x
unset chars[$((${#chars[@]} - 1))]
unset chars[$((${#chars[@]} - 1))]
echo "Array: ${chars[@]}"
Array: f o o
echo "Array length: ${#chars[@]}"
Array length: 3
The final x is necessary to handle the fact that a newline is appended after $string if it doesn't contain one.
If you want to use NUL-separated characters, you can try this:
echo -n "$string" | while read -N 1
do
printf %s "$REPLY"
printf '\0'
done
A: AWK is quite convenient:
a='123'; echo $a | awk 'BEGIN{FS="";OFS=" "} {print $1,$2,$3}'
where FS and OFS is delimiter for read-in and print-out
A: For those who landed here searching how to do this in fish:
We can use the builtin string command (since v2.3.0) for string manipulation.
↪ string split '' abc
a
b
c
The output is a list, so array operations will work.
↪ for c in (string split '' abc)
echo char is $c
end
char is a
char is b
char is c
Here's a more complex example iterating over the string with an index.
↪ set --local chars (string split '' abc)
for i in (seq (count $chars))
echo $i: $chars[$i]
end
1: a
2: b
3: c
A: If you also need support for strings with newlines, you can do:
str2arr(){ local string="$1"; mapfile -d $'\0' Chars < <(for i in $(seq 0 $((${#string}-1))); do printf '%s\u0000' "${string:$i:1}"; done); printf '%s' "(${Chars[*]@Q})" ;}
string=$(printf '%b' "apa\nbepa")
declare -a MyString=$(str2arr "$string")
declare -p MyString
# prints declare -a MyString=([0]="a" [1]="p" [2]="a" [3]=$'\n' [4]="b" [5]="e" [6]="p" [7]="a")
As a response to Alexandro de Oliveira, I think the following is more elegant or at least more intuitive:
while read -r -n1 c ; do arr+=("$c") ; done <<<"hejsan"
A: zsh solution: To put the scalar string variable into arr, which will be an array:
arr=(${(ps::)string})
A: declare -r some_string='abcdefghijklmnopqrstuvwxyz'
declare -a some_array
declare -i idx
for ((idx = 0; idx < ${#some_string}; ++idx)); do
some_array+=("${some_string:idx:1}")
done
for idx in "${!some_array[@]}"; do
echo "$((idx)): ${some_array[idx]}"
done
A: Pure bash, no loop.
Another solution, similar to/adapted from Léa Gris' solution, but using read -a instead of readarray/mapfile :
#!/usr/bin/env bash
str='azerty'
# Need extglob for the replacement pattern
shopt -s extglob
# Split string characters into array
# ${str//?()/$'\x1F'} replace each character "c" with "^_c".
# ^_ (Control-_, 0x1f) is Unit Separator (US), you can choose another
# character.
IFS=$'\x1F' read -ra array <<< "${str//?()/$'\x1F'}"
# now, array[0] contains an empty string and the rest of array (starting
# from index 1) contains the original string characters :
declare -p array
# Or, if you prefer to keep the array "clean", you can delete
# the first element and pack the array :
unset array[0]
array=("${array[@]}")
declare -p array
However, I prefer the shorter (and easier to understand for me), where we remove the initial 0x1f before assigning the array :
#!/usr/bin/env bash
str='azerty'
shopt -s extglob
tmp="${str//?()/$'\x1F'}" # same as code above
tmp=${tmp#$'\x1F'} # remove initial 0x1f
IFS=$'\x1F' read -ra array <<< "$tmp" # assign array
declare -p array # verification
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "74"
}
|
Q: How to remember a URL and redirect to the same URL after login and not to the default page I am currently working in cakephp and is facing problem in redirecting a page. By default after login user is taken to a particular page. Now i want to change it a little but dont want to disturb the default functionality. If a user is not logged in the user is redirected to the login page by the following function :
$this->Auth->loginAction = array(
'controller' => 'users',
'action' => 'login'
);
I have defined a link which redirects to login page if user is not logged in when clicked
<div class="bid-button"><a href="/users/login" class="b-login-big"></a></div>
or else this is done when clicked
<?php if($session->check('Auth.User')):?>
<div class="bid-loading" style="display: none; height:59px;"><?php echo $html->image('ajax-arrows-white.gif');?></div>
<div class="bid-button"><a class="bid-button-link button-big" title="<?php echo $auction['Auction']['id'];?>" href="/bid.php?id=<?php echo $auction['Auction']['id'];?>">Bid!</a></div>
<?php endif;?>
Now what i want to do is if a user logs in normally he should go to the default page after login but if he clicks the link then the user should be redirected to the same page after login and not the default page.The URL of the page from which the user is redirected to the login page after clicking the link can be fetched by the following way
<?php echo AppController::AuctionLinkFlat($auction['Auction']['id'], $auction['Product']['title']);?>
How will i be able to do it? I have no idea how and what to do. Please suggest me some solution.
A: Add to beforeFilter in the user controller:
function beforeFilter() {
$this->Auth->autoRedirect = false;
parent::beforeFilter();
}
You can also replace the redirect with this to the login method of your user controller:
$this->redirect($this->Auth->redirect());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bound ajax calendar extender to specific month and year only I have two calendar extender, Which I want to restrict. When user selects any year from year drowdown list and month from month dropdown list, the calendar extender should show dates for selected month and year only and use is not allowed to selected any other month and year from the calendar extender. For eg. If I select year=2011 and month = September from year and month drop down lists respectively, then both the calendar extenders should show date for September-2011 + 1st October and I should be allowed to selected date form these dates only and selection of any other date is not allowed.I dont want to use Jquery.
A: I believe you may use following approach (fast and quite dirty): add script and style below onto the page:
<style type="text/css" >
div.ajax__calendar_prev,
div.ajax__calendar_next,
div.ajax__calendar_today
{
display: none !important;
}
</style>
<script type="text/javascript">
function pageLoad() {
var extender = $find("calendarExtenderBehaviorID");
extender._switchMode = function () { };
}
</script>
This will prohibit calendar mode switching and hide elements that may be used for changing month and year.
Also you need a RangeValidator attached to target textbox for checking selected date value.
In dropdown's selected index changed event handler you need to set calendar extender selected date and set range validator's minimum and maximum values in accordance with selected year and month.
As an alternative you can use CustomValidator and perform all checks and assignments in javascript.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Import an existing class file in project (Using Eclipse) We all can import an existing Android project into workspace using File->Import->Existing projects into workspace. Is there any such method to include an existing java file( Activity)
into a project.
For example if I have activity hello.java in project P1. Can I copy hello.java in project P2 in src/ folder and then import into the project somehow?
What I do normally in such cases is create a new class in Project P2 and copy the code from hello.java from P1 manually. Is there any better approach?
I am using Eclipse as editor.
Regards,
A: You can just right click on your hello.class from Project1 and select COPY , than go to your Project2's src folder and right click --> select PASTE and that's it.As I know that's the easiest way to do that.I'm not really sure if you can import classes from other Projects.You can create a library project and just include it to your current project. This way you will need to write a code once and you will be able to use it from all your application that you need. You just have to include it to your project's properities on Eclipse. That's it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sending mail takes long time in localhost I am using Ubuntu.I installed sendmail in my local host using the following command
sudo apt-get install sendmail
Now I would like to check whether mail goes from my localhost using following php code.
<?php
$to = "test@test.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
When i execute the code, It takes very long time and finally echo the message as Mail Sent.
Is there any possibilities to fix this ?
A: I know this question has already been answered, but I'm posting this in the hope it may help someone else looking for a different solution to this issue.
For me, I just needed to put my server's Fully Qualified Domain Name (FQDN) into /etc/mailname. For example: server.example.com.
Restart Sendmail to apply the changes.
$ sudo service sendmail restart
A: This answer helped me https://serverfault.com/a/221894/186680
Postfix and sendmail where installed. Removed sendmail Yum remove sendmail
A: Edit the file /etc/hosts and make sure the first line is the following:
127.0.0.1 localhost.localdomain localhost myhostname
Edit the sendmail configuration file ( /etc/mail/sendmail.cf in Ubuntu) and Uncomment the line #O:
O HostsFile=/etc/hosts
Restart the computer, or run sudo service sendmail restart.
The computer should boot up much faster now and the mail() function should return almost immediately.
HOWEVER, the emails won't actually be sent unless you follow step 5.
You must new use the sendmail -f option whenever using the mail function.
For example:
mail('recipient@somewhere.com', 'the subject', 'the message', null, '-fsender@somewhere.com');
A: The delay is usually indicating a DNS time-out. Is your machine configured with proper DNS entries? I would try doing a test using mail on the command line as this would isolate the issue.
A: Unless you know Sendmail well, you are probably bettter off installing some other MTA. ssmtpd was already suggested in another answer; a common choice is Posfix.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Is it possible to insert text in an TextView? Appending text in an Android TextView adds the text to the end of the current text. I want to insert some text in a specified location of a TextView without disturbing it's movement while the textview scrolls. Is it possible to insert text? Please help
A: You can set BufferType of TextView as Editable. It is required only once.
textView.setText(textView.getText(), BufferType.EDITABLE);
Then you can use:
((Editable) textView.getText()).insert(where, text)
I believe this way is more efficient if you need to insert text often.
A: I would read the text currently in the TextView, split it at the point I wanted to insert and then put it all together. Like this:
String text = myTextView.getText().toString();
String first = text.substring( 0, splitPoint );
String second = text.substring( splitPoint, text.length );
myTextView.setText( first + insertText + second );
A: String old=textView.getText().toString();
String new= "pre"+old+"after"; // can manipulate using substring also
textView.setText(new);
A: try like below using string buffer.
String string=yourTextView.getText().toString();
StringBuffer sb=new StringBuffer(string);
sb.insert(index, "string_to_insert");
string=sb.toString();
yourTextView.setText(string);
A: You can do like this and this probably easiest way to do this
String text_view_text=textView.getText().toString();
StringBuffer sb=new StringBuffer(text_view_text);
sb.insert(position_to_insert,text_to_insert);
textView.setText(sb.toString());
A: A little off-topic, but if your 'TextView' happens to be EditText...
EditText.getText() actually returns an Editable, not CharSequence or String as one might expect. Editable does have methods to insert and replace text.
Editable e = editText.getText();
e.insert(pos, text);
e.replace(start, end, text);
// etc.
The above methods crafting a new string from substrings and then putting it to back to editText is OK, however if your text had any markup it would be lost. Contrary to that editable.insert() / replace() preserves any markup outside of inserted/replaced text.
A: Try this:
private void insertTextAtPoint(String textToAdd, int point) {
private textBefore = textView.substring(0, point);
private textAfter = textView.substring(point, textView.getText().toString().length);
textView.setText(textBefore + textToAdd + textAfter);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Storing 'session values' in MS MVC3 I'm getting started in MVC3 with a jquery/js driven front end. I realise that the paradigm of MVC is not to rely much on the concept of session variables and the like, instead using the actions and controllers to drive the user experience. I have the situation below, what's the proper way to do it?
a) I have a little menu with a set of 'select exhibit' options - show summary, show user details etc. Clicking one calls a controller (lets say 'rendersummary' or 'renderuserdetails') which returns a partialview back a certain div on my page.
b) I have a separate 'filters' panel, which lets you select how many records to include, etc. In that, I have an 'apply' button. When you click apply, I'd like it to re-execute the last action again (eg rendersummary) but now using the new filter settings.
I recall you could use HTMLRoutings or something to see what the current action/args are, but am not sure how you'd do this for the most recent partialview.
Any thoughts?
Thanks!
A: You can define a special controller that get the data from the filter panel and redirect the call to the last action/controller executed. If you don't want to use Session to store the navigation's information, you can add some hidden input field to the filter panel and valorize them using js.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Prevent downloading with htaccess I've searched around but have found no solutions.
I have a directory with all my fonts (svg, eot, woff, ttf, otf) in which I'd like to restrict downloading. Is there a way with .htaccess or..?
Edit: I am using Wordpress
A: Assuming you want the fonts to be useable within a webpage, then there isn't a way.
The browser has to be able to download them in order to display them.
A: Simple hotlinking example here: http://www.easymodrewrite.com/example-hotlinking
A: Put a .htaccess file into that directory with the following:
Order allow,deny
Deny from all
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ordering input tags in XML::Simple using Perl while printing the output in XML format How to order the input tags in Perl code using XML::Simple module for printing the output in XML format in specified order..
i have tried this
use XML::Simple;
use Data::Dumper;
open (FH,"> xml4.txt") || die ();
# create array
@arr = {
'name'=>['Cisco102'],
'SSIDConfig'=>[
{'SSID'=> [{'name'=>'Cisco102'}]}],
'connectionType'=>['ESS'],
'connectionMode'=>['auto'],
'autoSwitch'=>['false'],
'MSM'=>[{'security' =>[ { 'authEncryption' =>[{'authentication' => 'open',
'encryption' => 'WEP',
'useOneX' => 'false'
}],
'sharedKey' =>[ {
'keyType' => 'networkKey',
'protected' => 'false',
'keyMaterial' => '1234567890'
}]}]}]};
# create object
$xml = new XML::Simple(NoAttr=>1,RootName=>'WLAN Profile');
# convert Perl array ref into XML document
$data = $xml->XMLout(@arr,xmldecl => '<?xml version="1.0" encoding="US-ASCII"?>');
# access XML data
print FH $data;
but i am not getting the order which i required..i need the order ->name,SSID Config,Connectionmode,connectiontype,autoswitch,MSM .help me
A: Hashes aren't ordered. You could try using a Tie::IxHash (which looks like a hash, but maintains insertion order) instead of a normal hash. If that doesn't work, XML::Simple won't be of use to you.
A: It looks to me that you want 2 things for your XML:
*
*no attributes, hence the NoAttr option in the XML::Simple object creation
*the order of the elements should be as specified
I am not sure why you don't want attributes in your XML, and why the data structure you use to create it has them. You may want to look into that. In any case XML::Simple gives you this feature.
For the second part, XML::Simple doesn't keep the order, and I have found no way to make it do it, so you will need something else.
For a quick and dirty solution, A little bit of XML::Twig in there would do:
# instead of the print FH $data; line
my $twig= XML::Twig->new( )->parse( $data);
$twig->root->set_content( map { $dtwig->root->first_child( $_) } (qw( name SSIDConfig connectionMode connectionType autoSwitch MSM)) );
$twig->print( \*FH);
A couple more comments:
*
*you can't use 'WLAN Profile` as the root tag, XML names cannot include spaces
*it is generally considered polite, when you ask a question about Perl, to show code that uses strict and warnings
*the proper way to open the output file would be my $out_file= xml4.txt; open ( my $fh,'>', $out_file) or die "cannot create $out_file: $!"; (or use autodie instead of the die), using 3 args open and lexical filehandles is a good habit (this message from the 3-arg open police department ;--)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Facebook Graph API - Search for Work I noticed the "/Search" works only on "Names". How would it be possible to search Facebook user's programmatically, by searching their "Work".
For instance, I want to search for all users who work "web development". Is this available?
Thanks
A: Not at the current time. The Graph API documentation states that the format for searches is https://graph.facebook.com/search?q=QUERY&type=OBJECT_TYPE, which does not allow for any granularity in search parameters.
Note that user searches do not only work with names - if you do a search for a non-name term, like "programming", you will likely receive results for profiles who do not contain the term in their names. Depending on their privacy settings, it might be impossible to use the API to figure out why they are showing up for this term.
A possible alternate solution would be to request the friends_work_history permission from your users and manually search through their work history. Note that this would only help you search a user's friends' work history (and not all users' work history), and that you would restricted by the Platform Policies on how you could use this data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to show Separator line for currently displaying cells in the UITableView using MonoTouch? I have showing 5 to 8 items in the UITableView. But Separator line showing empty cells also. There are no value on that empty cells. Why Separator line showing on these empty cells? I choose the Separator value is Single Line in Interface Builder. How to show Separator line for currently displaying cells in the UITableView using MonoTouch?
Look at the screenshot. I have showing 5 items in the UITableView. But separator showing all the cells of UITableView. I need separator line for used cells in the UITableView.
A: If I understand you correctly, you want to eliminate empty cells from your UITableView?
If yes, do this to clear out the empty cells/space below your data:
/// <summary>
/// Removes empty lines below a tableview. Attention: calls the table's delegate implicitly, so make sure it is initialized.
/// </summary>
public static void ClearEmptyTableViewSpacers ( UITableView oTableView )
{
UIView oViewSpacerClear = new UIView (new System.Drawing.RectangleF (0, 0, oTableView.Frame.Width, 10));
oViewSpacerClear.BackgroundColor = UIColor.Clear;
oTableView.TableFooterView = oViewSpacerClear;
}
A: It's not possible to say a seperator line only for special cells. The tableview always draws seperator lines for the complete height of the UITableView.
The only way to made this possible is to set the TableView SeperatorColor to Transparent and draw the Seperator Line within a Cell. But i think that's heavily drain performance on large lists.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Wordpress Custom Search Form within a page I need to add a custom search form within a page, and the search form results should return/highlight items within that page..
ex..
in a page:
monkey
pig
tree
when a user searches for 'pig'
it'll either display only 'pig' or highlight the word pig.
I thought of using custom query but I realized it'll display the whole content instead of the actual text/searched item itself.
A: You can highlight your search results with a few simple steps. For this solution your theme needs to have a search.php file. If it does, follow these simple steps:
Open the search.php file and find <?php the_title(); ?>
Replace that with this:
<?php echo $title; ?>
Now you'll need to place this bit of code before the title tag you just changed (anywhere before should work, just be sure not to place it inside an open
<?php
$title = get_the_title();
$keys= explode(" ",$s);
$title = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-keywords">\0</strong>',
$title);
?>
What that code does is add a class to the title or in this case the results of the search. The class in my example is .search-keywords. Now you need to open your themes style.css file and add some styles to it. Here is an example (change it however you need:
.search-keywords {
background:yellow;
color:blue;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Finding contents inside a pattern? AS3 I have always sucked at regular expressions and now I'm stuck with a problem. I am loading a webpage onto my AIR application now what i want to do is, I want to locate the text inside a certain pattern. See below.
<html>
<head></head>
<body>
Blah blah blah..
Blah blah var my_variable = "this is a value";
</body>
</html>
On the above example, I want to get this is a value without the quotes. That value is in a pattern of var[space]my_variable[space]=[space]"content"; How do I extract JUST the value?
A: Try this one:
/var [^ ]* = "([^"]*)"/
Which means:
var
space
everything but a space a certain amount of times
space
=
space
"
everything but a " a certain amount of times (caught)
"
A: Pretty simple really. Extracting just the value requires that you use a capture group in the regex to match the contents between the quotes and then fetch the value of that capture group after a successful match. Assuming that the quoted string being assigned to the variable may contain escaped characters (including escaped double quotes), then the following tested code should work:
var re = /\bvar\s+my_variable\s+=\s+"([^"\\]*(?:\\[\Ss][^"\\]*)*)"/;
var results = text.match(re);
var content = results ? results[1] : null;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to display information from MySQL in a textbox? I an new in creating programs in Visual Studio C#. I want to create a program that reads the information from MySQL and display the selected information in a textbox. What I have here is a code for displaying the information in a combobox.
This is the code to display information from MySQL in a combobox:
private void comboBoxDistrict_SelectedIndexChanged(object sender, EventArgs e)
{
comboBoxDistrictName.Items.Clear();
string query = "SELECT employee_lastname, employee_firstname, employee_middlename FROM employee WHERE employee_district = '" + comboBoxDistrict.Text.ToString() + "'";
DBConn db = new DBConn();
DataTable tbl = db.retrieveRecord(query);
foreach (DataRow row in tbl.Rows)
comboBoxDistrictName.Items.Add(row[0].ToString() + ", " + row[1].ToString() + " " + row[2].ToString());
}
What I need is to display the information in a textbox. Please help. Thanks.
A: Just Change the assign from your ComboBox to be your textBox
txtBox1.Text = row[0].ToString() + ", " + row[1].ToString() + " " + row[2].ToString());
You may take care of iteration, since just last row in this case will be shown in the textBox
A: Use StringBuilder for performance reasons and to get around the "problem" of just the last row showing up in your TextBox as in Rami's example:
var sb = new StringBuilder();
foreach (DataRow row in tbl.Rows)
{
sb.AppendLine(string.Format("{0}, {1} {2}",
row[0].ToString(),
row[1].ToString(),
row[2].ToString()));
}
txtBox1.Text = sb.ToString();
or simply append the next row to the TextBox using "+=":
txtBox1.Text += row[0].ToString() + ", " +
row[1].ToString() + " " +
row[2].ToString()) + "\r\n";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Date Picker edition of fields Is it possible to disable the edition of fields in DatePicker? Indeed when I touch on the editable box in the DatePicker, the keyboard
appears, and I don't want this.
Someone have an idea?
Thanks a lot for your response :)
A: This is actually really easy. Just use
datePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
The NumberPickers will never receive the focus when they are tapped and the soft input keyboard should not appear. I have been using this method on API level 7 with success.
A: Yeh i got the answer..the thing we need to do is...
DatePicker m_dtPicker = (DatePicker) findViewById(R.id.dt_picker);
setDisabledTextViews(m_dtPicker);
private void setDisabledTextViews(ViewGroup dp)
{
for (int x = 0, n = dp.getChildCount(); x < n; x++)
{
View v = dp.getChildAt(x);
if (v instanceof TextView)
{
v.setEnabled(false);
}
else if (v instanceof ViewGroup)
{
setDisabledTextViews((ViewGroup)v);
}
}
}
A: This should not be done. DatePicker has that functionality specifically to allow users convenient option instead of tapping/holding +/-
What you are trying to achieve is the iOS for of Picker which although looks nice but really is inconvenient on Android.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to emit string into user control from code behind? I have a main aspx page in which there is a list of items. Each item is shown using the user control.
Now i am trying to emit string in user control is page receives specific parameter through user control as below.
//ASCX code
..
<span><%=custString %></span>
..
// .CS code
protected string custString = string.Empty;
..
protected void Page_Load(object sender, EventArgs e){
if(Request.params["chages_done"]){
custString = "Values updated ";
}
}
So while debugging i can see the value of the string getting updated but its not getting reflected on the ascx control when its added to page. Any idea how it can be achived ? or what can be wrong ?
I have also tried to create the server side control in user control and setting its value from code behind but it too was not working.
A: Add a public string property to your control, and a Literal control to the .ascx markup. When the property is set, set the value of the Literal control as well. Should do the trick.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Browser to browser VoIP calling using SIP? I am trying to call from one browser to another browser.
What I have done:
*
*I set up my asterisk server just like getonsip.com
*I wrote a client using pjsua python binding which acts as a server
Here is the situation:
*
*I can call from my browser ( My browser is on the same machine on which pjsua client is running) to my sip client on my android phone.
*I am not able to do same from the browser from another machine.
*What should I do for making a browser to browser call happen?
*Does streaming and flash required for doing this?
A: You won't be able to do browser-to-browser calls with SIP at least not without a lot of plugin magic. The first problem is that by default SIP uses UDP port 5060, the browser sandbox won't let you communicate on that port so you'd need a plugin (Flash, Silverlight, Java Applet etc.). Once you've overcome the SIP side, and dealt with the NAT headaches along the way, you'd then need to work out how to get the browser to process the RTP media stream. That would mean more plugins.
There is actually an upcoming standard that deals with exactly what you are after, see RTC-WEB. While you're waiting for that you could try and get by with phono which is a javascript/flash component from Tropo that supports browser based calling but with the caveat being the call will traverse Tropo's SIP servers.
A: It's possible now, since WebRTC finally became standard and there are already implementations in both browsers and SIP server
*
*Asterisk 11 is officially support WebRTC
*Google Chrome has built-in WebRTC support since version 23
See this tutorial for more details http://www.html5rocks.com/en/tutorials/webrtc/basics/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: The difference between Task.Factory.FromAsync and BeginX/EndX? I have very similar code when using the standard BeginRead and EndRead methods from the TcpClient and using Task.Factory.FromAsync.
Here are some examples.. Error handling code not shown.
Task.Factory.FromAsync:
private void Read(State state)
{
Task<int> read = Task<int>.Factory.FromAsync(state.Stream.BeginRead, state.Stream.EndRead, state.Bytes, state.BytesRead, state.Bytes.Length - state.BytesRead, state, TaskCreationOptions.AttachedToParent);
read.ContinueWith(FinishRead);
}
private void FinishRead(Task<int> read)
{
State state = (State)read.AsyncState;
state.BytesRead += read.Result;
}
Standard use of callbacks with BeginRead and EndRead:
private void Read(State state)
{
client.BeginRead(state.Bytes, state.BytesRead, state.Bytes.Length - state.Bytes.Read, FinishRead, state);
}
private void FinishRead(IAsyncResult async)
{
State state = (State)async.AsyncState;
state.BytesRead += state.Stream.EndRead(async);
}
Both of these work fine but I am curious of their differences. The lines of code for both are pretty much equivalent and they both seem to perform the exact same function and have the same efficiency. Which one is preferable? What would you rather see in production code?
A: I would much rather see Task<T> based code:
*
*It provides for composition more easily; for example, it's reasonably easy to write a method which takes a collection of Task<T> tasks and returns another task which represents the majority verdict of those tasks. Likewise you can wait until any one of a collection of tasks has completed, etc.
*It provides more flexible scheduling of where the continuation is run.
*It allows the task itself to be returned with type safety and a lot more information than the somewhat anaemic IAsyncResult type returned by BeginRead.
*It's simpler to specify error handling and cancellation with tasks than using the Begin/End model.
*Task<T> is getting better language support in C# 5 with async/await - if your codebase already uses Task<T> pervasively, it'll be much easier to take advantage of this
Basically in modern code running on .NET 4, Task<T> is the idiomatic way of representing an on-going task. It's a much richer environment to work in than earlier attempts, and I would embrace it if you have the chance. Obviously if you're using .NET 3.5 or earlier, life is a bit harder, but I'm assuming that as you're asking the question, Task<T> is an option...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: The string "ďťż" appears on my page randomly but only in firefox. IE and chrome don't have this problem. Nothing actually prints that anywhere in my code. So far i've found it in only two places one of them being:
<li class="spatiu"> </li>
<li class="memento_li">
<div id="afisare_alerte">
<script language="javascript">
afisare_alerte_php();
</script>
</div>
</li>';
and this is "afisare_alerte_php()"
xmlhttp_alerte.onreadystatechange=function() {
if (xmlhttp_alerte.readyState == 4) {
if(document.getElementById("afisare_alerte").innerHTML=xmlhttp_alerte.responseText){
}
schimbare_tip_cursor('default');
}
else{
schimbare_tip_cursor('progress');
}
};
well the ajax part of it.
the file it loads is
<?php
echo'
0 Notificari
';
?>
and the output :
ďťż 0 Notificari
A: That sequence ďťż is called the Windows Byte Order Mark. It shows up whenever you save a file as UTF in most Windows programs. So the problem here is that you must be serving that ajax endpoint from a Windows server, and the server is configured to output a BOM. How to fix this depends on what web server you are using.
A: Those characters actually do exist in your code, you just can't see them. Some editors add these when the file is saved as UTF. Too see the characters, open your code in an ISO-only editor (e.g. a simple notepad program). You'll be able to see the ďťż then, and you can do a global search/replace to just remove all instances of it. Then save your file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Why margin-top of the top div would apply to ``? Here I posted a demo http://jsfiddle.net/LxYMv/1/.
As you can see <body> gets margin-top:10px from the top div, and therefor <html>'s black background leaks out. Does it mean that I can't give the top div a positive margin-top?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
html{color:#000;background:#FFF}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,select,p,blockquote,th,td{margin:0;padding:0}table{border-collapse:collapse;border-spacing:0}fieldset,img{border:0}address,button,caption,cite,code,dfn,em,input,optgroup,option,select,strong,textarea,th,var{font:inherit}del,ins{text-decoration:none}li{list-style:none}caption,th{text-align:left}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal}q:before,q:after{content:''}abbr,acronym{border:0;font-variant:normal}sup{vertical-align:baseline}sub{vertical-align:baseline}legend{color:#000}
html{background:black}
body{background:white}
</style>
</head>
<body>
<div style="margin-top:10px;background:red;height:100px">Here the top div begins</div>
<div style="height:800px">A long long div</div>
</body>
</html>
A: You can get around this by adding padding: 0.01px; to the <body>. As it's so small it is effectively rounded to 0px, but the body then starts where it should.
A: This is called margin collapsing.
When an element with a margin is inside an element with no padding or border, the margin will be applied outside the parent element instead of between the child element and the parent edge.
The basic reason for this behaviour is that margin specifies the minimum distinace between elements, not a distance around an element like padding specifies distance around the element content.
A: It meants that if the child starts exactly where the parent - that has no margin - starts then the childs margin will affect it. You can use the padding property instead to get the result you want like:
body{
padding-top:10px;
}
A: This is how margins work. The margin of the parent and child elements collapse together in the same way an element appearing below another would collapse. Use padding on the child element if you want the parent element to not move.
A: I think the box model explains this behavior: http://www.w3.org/TR/CSS2/box.html
Specifically these lines:
"A collapsed margin is considered adjoining to another margin if any of its component margins is adjoining to that margin." &
"The top margin of an in-flow block element collapses with its first in-flow block-level child's top margin if the element has no top border, no top padding, and the child has no clearance."
Instead of adding margin to child element, you can add same px padding to parent or apply some border to parent element and you get what you want.
A: As @Guffa said:
This is called margin collapsing.
When an element with a margin is inside an element with no padding or
border, the margin will be applied outside the parent element instead
of between the child element and the parent edge.
To elaborate a bit: the solution is to use padding instead of margin. In your case, you'd add padding-top: 10px to body, and remove the margin-top from your <div>
If you want to make a container that will prevent interior margins from collapsing beyond the bounds of the container, you'll either need to add padding or border to the container. If you don't want either of these visible features, you can add a negative margin and cancel it with positive padding. Like this:
<div style="margin:-1px; padding:1px;"> ... </div>
you could do the same thing on your body element if you want.
Edit: here's your jsFiddle, updated to use the margin/padding trick on the body element
A: Try to add this:
<div style="overflow:hidden;height:1%">
<div style="margin-top:10px;background:red;height:100px">Here the top div begins</div>
</div>
I think, it solves your problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Facebook Connect API Work Flow behind the scene I have visited a site . I have observed that When I am not logged in Facebook it ask for connect to facebook to download file. After that I have authenticated their Application. Now Whenever I logging in to Facebook and open this site it automatically detect that I am login in Facebook without any authentication.
I want to know that how it can identify that I am logged in Facebook? Can anybody suggest any good artical which shows the workflow of FaceBook conntect authetication behind the scene?
A: Authorization and Authentication. Slideshare shares login state with facebook.com via the session cookie on your browser.
The Facebook JavaScript SDK allows your users to register and sign-in
to your site using their Facebook accounts. This is done by sharing
the logged in user state between http://www.facebook.com/ and your
site. A Facebook user remains logged in to your site as long as they
are logged in to Facebook and there is a valid access token for your
app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use SQL Server Integration Services to update production server I have a development server (SQL Server 2008) it has database. i.e. Employee (database) on it, I have tables,stored procedure and data as well.
And I have another production server (SQL Server 2008) also it has same database i.e. Employee (database) on it, I have tables, stored procedure and data as well.
Now my website running from production server.
When I make changes in development server and create one more table, stored procedure and also insert some data, then I want to update my production server so that my changes will go to running website
Make sure i can do it following ways:
*
*Using Backup SQL Server (.bak file).
*Using SQL script with data.
*Using MDf LDF file.
But I want to do this by using SQL Server Integration Services (SSIS).
Thanks in advance.
Salman ansari
A: Why do you want to use SSIS? I believe you're asking about how to deploy database changes from development to production, and SSIS is not a good tool for that purpose; it's used for data integration and is not at all suitable for synchronizing schema or object changes.
I think you need to define your requirements a bit more clearly before you decide on a solution. For example, it's very unusual to upgrade a production database by using a complete copy of your development database, because you lose all the data in production. Perhaps your use case allows for this, though.
In any case, you need to focus on finding a deployment solution that works for your environment, e.g. VS database projects or a schema comparison tool such as SQL Compare. After you've done some research, you may be able to ask more specific questions about the best solution for your particular case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: POST not accepting int parameter I have a problem with ASP.NET MVC3.
I'm trying to post some parameters to a JSONResult action. It works great when i use GET, but when i use POST, i get an error, because apparently when using POST, it won't accept my integer parameters as such, and say that the parameters dictionary contains a null value for them.
Anyone run across this before? Thanks.
Edit: some code, as requested:
public JSONResult PostingHere(string username, int someotherparameter) {
//Code
}
Really, that's all that matters, because the exception is thrown then and there when POSTing because apparantly a null value gets passed to the someotherparameter parameter. When using GET, as said before, it works just dandy.
The intended use is to post with a NSURLRequest from an iPhone, but I've been debugging with a firefox extension called Poster and i get the same result. Full error:
The parameters dictionary contains a null entry for parameter 'someotherparameter' of non-nullable type 'System.Int16' for method 'System.Web.Mvc.JsonResult PostingHere(System.String, Int16)'
Edit 2: By request, I'll add an example of calling the action which results in the error:
<form action="http://fullurlhere.com/Controller/PostingHere" method="POST">
<input type="hidden" name="userid" value="astring" />
<input type="hidden" name="someotherparameter" value="100" />
<input type="submit" value="Brace for impact" />
</form>
Edit 3: The post data; never mind the discrepancy in variable names, these are the actual names of them.
Edit 4: Adding to the mystery, the problem disappears when testing against a local server on my own computer, with the very same MVC Project the server is running. So the problem is likely within a server-side setting.
Solved: Turns out when i evalutated the request, that the server was redirecting me to https:// from the http://, causing me to lose my POSTed data. Thanks to everyone for being such good sports.
A: try
public JSONResult PostingHere(string username, int? someotherparameter) {
//Code
}
A: Solved: Turns out when i evalutated the request, that the server was redirecting me to https:// from the http://, causing me to lose my POSTed data. Thanks to everyone for being such good sports.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is this possible to count index posistion of my current node that belonging to the child of using xslt2.0? This is my Xml Document.
<w:document xmlns:w="w">
<w:body>
<w:p>
<w:r>
<w:t>
Para1
</w:t>
</w:r>
</w:p>
<w:p>
<w:r>
<w:t>
Para2
</w:t>
</w:r>
</w:p>
<w:p>
<w:r>
<w:t>
Para3
</w:t>
</w:r>
</w:p>
<w:p>
<w:r>
<w:t>
Para4
</w:t>
</w:r>
</w:p>
<w:p>
<w:r>
<w:t>
Para5
</w:t>
</w:r>
</w:p>
<w:tbl>
<w:tr>
<w:tc>
<w:p>
<w:r>
<w:t>
Para6
</w:t>
</w:r>
</w:p>
</w:tc>
<w:tc>
<w:p>
<w:r>
<w:t>
Para7 <!-- Just Assume, this is current Node -->
</w:t>
</w:r>
</w:p>
</w:tc>
</w:tr>
</w:tbl>
<w:p>
<w:r>
<w:t>
Para8
</w:t>
</w:r>
</w:p>
</w:body>
</w:document>
So, now i want to get the index position of current node that belonging to the child of <w:body>.So My expected output is :6.
for example,
*
*if current node is para6 then my output is also 6.
*if current node is para8 then my output is 7.
*if current node is para5 then my output is 5.
If possible, Please Guide me to get this...
New Update:
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"
xmlns:exsl="http://exslt.org/common"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
extension-element-prefixes="exsl">
<xsl:output method="html" indent="yes"/>
<xsl:template match="*">
<Document>
<xsl:apply-templates select="//w:p">
</xsl:apply-templates>
</Document>
</xsl:template>
<xsl:template match="w:p">
<xsl:variable name="index">
<xsl:call-template name="get-para-index">
<xsl:with-param name="node" select="."/>
</xsl:call-template>
</xsl:variable>
<Paragraph>
<xsl:attribute name="index">
<xsl:value-of select="$index" />
</xsl:attribute>
<xsl:apply-templates select="./w:r/w:t"/>
</Paragraph>
</xsl:template>
<xsl:template match="w:t">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template name="get-para-index">
<xsl:param name="node"/>
<xsl:value-of select="count($node/ancestor::*[parent::w:body]/preceding-sibling::*)+1"/> <!-- Need to write logic here -->
</xsl:template>
</xsl:stylesheet>
I just calling the get-para-index template for get the index position of each and every <w:p>.But it returns always 1 for every <w:p>. Please Guide me to get out of this problem...
Thanks & Regards,
P.SARAVANAN
A: I'm not 100% sure of what you want but this expression
count(ancestor::*[parent::w:body]/preceding-sibling::*)+1
from the context node, finds the ancestor whose parent is <w:body>, then selects all preceding sibling elements and counts those. Adding 1 should give you the position.
A: My Updated Xslt that fulfilled my requests...
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"
xmlns:exsl="http://exslt.org/common"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
extension-element-prefixes="exsl">
<xsl:output method="html" indent="yes"/>
<xsl:template match="*">
<Document>
<xsl:apply-templates select="//w:p">
</xsl:apply-templates>
</Document>
</xsl:template>
<xsl:template match="w:p">
<xsl:variable name="index">
<xsl:call-template name="get-para-index">
<xsl:with-param name="node" select="."/>
</xsl:call-template>
</xsl:variable>
<Paragraph>
<xsl:attribute name="index">
<xsl:value-of select="$index" />
</xsl:attribute>
<xsl:apply-templates select="./w:r/w:t"/>
</Paragraph>
</xsl:template>
<xsl:template match="w:t">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template name="get-para-index">
<xsl:param name="node"/>
<xsl:choose>
<xsl:when test="$node/ancestor::*[parent::w:body]">
<xsl:value-of select="count($node/ancestor::*[parent::w:body]/preceding-sibling::*)"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="count($node/preceding-sibling::*)"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Query/Filter M2M 'through' object in Django I have the following basic model…
class Campaign(models.Model):
name = models.CharField(_('name'), max_length=80, unique=True)
recipients = models.ManyToManyField('Person', blank=True, null=True, through='Recipient')
class Recipient(models.Model):
campaign = models.ForeignKey(Campaign)
person = models.ForeignKey('Person')
class Person(models.Model):
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
I'd like to have a queryset that queries all Person objects that are not within a given Campaign.
It'd be nice if it was as easy as:
Person.objects.all().exclude(<mycampaign>.recipients.all())
but we know that doesn't work.
To be more specific, I'm trying to get this to work in a form class as follows and the Q object comment seems right but I can't get it to work… Here's my form:
class RecipientsForm(forms.Form):
def __init__(self, campaign, *args, **kwargs):
self.campaign = campaign
self.helper = FormHelper()
self.helper.add_input(Submit('submit','Add',css_class='primaryAction'))
self.helper.layout = Layout(
Fieldset(
'',
'recipients',
css_class='inlineLabels')
)
return super(RecipientsForm, self).__init__(*args, **kwargs)
recipients = forms.ModelMultipleChoiceField(
# old queryset queryset=Person.objects.all(),
queryset=Person.objects.filter(~Q(id__in=self.campaign.recipients.all())),
widget=forms.widgets.CheckboxSelectMultiple,
label="Add Recipients",
required=True,)
def save(self, force_insert=False, force_update=False, commit=True):
recipients = self.cleaned_data['recipients']
for person in recipients:
recipient = Recipient(campaign=self.campaign,person=person)
recipient.save()
A: I believe this will do it.
from django.db.models import Q
Person.objects.filter(~Q(id__in=<mycampaign>.recipients.all())
A: Here's the answer… the problem was that my form was for the Recipient object instead of the Campaign object… the Furbeenator answer was a good step in the right direction… along with some help on the django IRC
class RecipientsForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.campaign = kwargs.pop('campaign', None)
super(RecipientsForm, self).__init__(*args, **kwargs)
if self.instance and self.campaign:
self.fields['recipients'] = forms.ModelMultipleChoiceField(
queryset=Person.objects.filter(~Q(id__in=self.campaign.recipients.all())),
widget=forms.widgets.CheckboxSelectMultiple,
label='Recipients', help_text='Pick the recipients to add to the campaign',
required=False,
)
elif self.campaign:
self.fields['recipients'] = forms.ModelMultipleChoiceField(
queryset=Person.objects.filter(~Q(id__in=self.campaign.recipients.all())),
widget=forms.widgets.CheckboxSelectMultiple,
label='Recipients', help_text='Pick the recipients to add to the campaign',
required=False,
)
else:
pass
def save(self, force_insert=False, force_update=False, commit=True):
recipients = self.cleaned_data['recipients']
for person in recipients:
recipient = Recipient(campaign=self.campaign,person=person)
recipient.save()
class Meta:
model = Campaign
fields = ['recipients',]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to disable the GotFocus on textbox? I have a textbox that does something on GotFocus.
How can I disable the GotFocus event on this textbox?
How to enable it back?
Sorry, I forgot - i work on Windows-mobile 6.5
Thanks in advance.
A: May be TextBox.CanFocus = false; and then CanFocus = true; ?
A: You could always Enable or Disable the control as well
void ButtonEnabled(bool value) {
textBox1.Enabled = value;
}
The code above is much too short to write a routine for, but gets the point across easier.
A: if you use WPF, TesxBox.Focusable property should be used.
TesxBox.Focusable = true enables you to got focus. TesxBox.Focusable = false - disables you to got focus
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: javascript - keep track of successful ajax requests / returns I am trying to find a way to keep track of successful ajax returns using javascript only not jquery or other libs. What I want to do is to show a loading graphic when the function is fired and clear the graphic when all the results are returned. My function breaks up the input and calls a defined number of ajax requests.
I read that there is no straight forward way to do it. I am trying to set up a function to count the successful requests, but I am running into a logical barrier that I can't solve. My basic outline is below:
TIA
Edited to update solution.
The solution is to create ct as a global variable
My working code outline is
var ct = 0;//declare outside of function as global
function ajaxcallback(...) {
...
if (success)
{
//output/do something
ct++; //increase global ct by 1
countajax (total);//call countajax
}
}//end function
function countajax (total)
{
if (ct == total)
{
//turn off loading graphic
}
}//end countajax
I suppose the function countajax is not necessary, the comparison of ct == total can be done without calling the function countajax.
A: One way to do this is to keep a variable that tracks how many requests you made and another that tracks how many responses you've received. Then after you've kicked off all of your ajax calls start a poller (setInterval) that checks for the response count variable to match the total requests variable.
var totalRequests = 0,
successfulRequests = 0,
poller = null;
// psuedo code
totalRequests++;
ajax("http://server.com", function(resp){ successfulRequests++; } /** callback */);
totalRequests++;
ajax("http://server.com", function(resp){ successfulRequests++; } /** callback */);
totalRequests++;
ajax("http://server.com", function(resp){ successfulRequests++; } /** callback */);
// run poller after you've kicked off all your ajax requests
poller = window.setInterval(function(){
if(totalRequests === successfulRequests){
alert("all ajax finished");
window.clearInterval(poller);
poller = null;
}
},100);
A: There is actually a very straightforward way to do this:
Call a method from inside every ajax callback, and make sure that this function only actually does anything if all the ajax calls are completed, like this:
(function() {
var ajax1_done = ajax2_done = ajax3_done = false;
function ajax1_callback() {
ajax1_done = true;
run_when_all_is_done();
}
function ajax2_callback() {
ajax2_done = true;
run_when_all_is_done();
}
function ajax3_callback() {
ajax3_done = true;
run_when_all_is_done();
}
function run_when_all_is_done() {
if(ajax1_done && ajax2_done && ajax3_done) {
//do stuff here
}
}
})();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to mail with the use of UIWebView? I am using a UIWebView and i have written this code
NSString *str = [NSString stringWithFormat:@"Hey, my id is abc@xyz.com"];
[aboutWebView loadHTMLString:str baseURL:nil];
Now In this code I want to detect that id and I want the option that user can do mail to this id
I am able to detect the link but nothing happen after it. i am using simulator.
A: Mail.app is not install on the iPhone simulator. You will need to test that part of your code on an actual device.
A: You can use mailto function and then
U can call following function:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[[request URL] scheme] isEqual:@"mailto"]) {
[[UIApplication sharedApplication] openURL:[request URL]];
return NO;
}
return YES;
}
U need to set delegate too
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: making test account admin of a facebook page using graph api? can we make a test account admin of a page on facebook, using facebook graph api?
I have created test users for a facebook app, but when i try to access the page using api, it just gives back the real world data, is there a way to read the test data posted on the app's wall?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CoreData One-To-Many I have a core data mode that has 1 to many relationship, but i'm struggling to get the value e.g.
Features.h model like this:
@interface Features : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * version;
@property (nonatomic, retain) NSNumber * expires;
@property (nonatomic, retain) NSNumber * used;
@property (nonatomic, retain) NSNumber * licenses;
@property (nonatomic, retain) NSManagedObject *featureToProducts;
@property (nonatomic, retain) NSSet *featureToUsers;
@property (nonatomic, retain) NSManagedObject *featureToDaemons;
@end
@interface Features (CoreDataGeneratedAccessors)
- (void)addFeatureToUsersObject:(NSManagedObject *)value;
- (void)removeFeatureToUsersObject:(NSManagedObject *)value;
- (void)addFeatureToUsers:(NSSet *)values;
- (void)removeFeatureToUsers:(NSSet *)values;
@end
And trying to access it like this:
Features *feature = (Features *)[[self.sectionInfoArray objectAtIndex:indexPath.section] features];
NSLog(@"featureToUsers = %@", [feature.featureToUsers valueForKey:@"user"]);
NSLog shows:
2011-09-28 01:06:59.719 Product Name[74092:fb03] featureToUsers = {(
"david.wilson" )}
I'm trying to populate a UITableViewCell but I keep getting:
'NSInvalidArgumentException', reason: '-[__NSCFSet isEqualToString:]:
unrecognized selector sent to instance 0x6b59a50'
Thanks,
dfox
A: Take a step back, take a deep breath and look. You have this declaration:
@property (nonatomic, retain) NSSet *featureToUsers;
And the diagnostic you get is that __NSCFSet doesn't understand the isEqualToString: message. Where did you get the impression that an NSSet should be able to respond to the isEqualToString: message? It does't, and it tells you so. isEqualToString: is an NSString message. You don't say, but I guess, that you want to get some string from your model, and do something with it. Which string? You don't say, but I guess that you have declared that relation to point to another entity named Users. You don't say, but I guess (as an aside, you should write better questions by including relevant context) that the Users entity has a string attribute of some sort, perhaps name or so.
So if you want that string, you need to pull it out from a Users instance, perhaps like this:
Users *myUSer = ...; // see below
NSString *myUserName = myUser.name;
if ([myUserName isEqualToString:@"Superman"]) { ... }
So key point #1: Core Data lets you manipulate instance of entities, not strings. But entity attributes can be string.
So how are you going to get you Users instance? If you write:
Users *myUSer = feature.featureToUsers.name;
This will not work either. Because the featureToUsers is declared as an NSSet, not as a Users.
So why is this property, which implements the to-many relation, declared as an NSSet? Because it's a to-many relation, and thus, you need it to be typed as a collection, in order to reach all the related objects.
So key point #2: a to-many relation is declared as a collection (namely an NSSet).
So what is inside this collection? Well, the Users you want to reach. So you can iterate through every related users for example like:
for (Users *aRelatedUser in feature.featureToUsers) {
NSString *relatedUserName = aRelatedUser.name;
if ([relatedUserName isEqualToString:@"Superman"]) { ... }
}
And now you should be good to go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Null Pointer Exception When want to set the value in Serializable Class I have a problem that I want to set and get Arraylists from a Serializable class but when we want to set an Arraylist into the Same class it returns NullPointerException, I don't know why? Please suggest me for right result.
Error Stack:
09-28 11:30:20.422: ERROR/AndroidRuntime(511): java.lang.NullPointerException
09-28 11:30:20.422: ERROR/AndroidRuntime(511): at com.example.test.Test_serializableActivity.parse_json(Test_serializableActivity.java:88)
09-28 11:30:20.422: ERROR/AndroidRuntime(511): at com.example.test.Test_serializableActivity$2.run(Test_serializableActivity.java:55)
Code: inserting the values Class
package com.example.test;
import java.util.ArrayList;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
public class Test_serializableActivity extends Activity {
/** Called when the activity is first created. */
public ArrayList<String> ibx_id = new ArrayList<String>();
public ArrayList<String> ibx_name = new ArrayList<String>();
public ArrayList<String> ibx_naturalKey = new ArrayList<String>();
setIbx ibx;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpPost post = new HttpPost("http://qa.mobile.equinix.com/eqixmobile/siteservice/um/ibx");
try{
StringEntity se = new StringEntity("{\"credentials\":{\"username\":\"mobileuser1\",\"password\":\"welcome1\"}}");
final Service_Call obj = new Service_Call(post, se, "mobileuser1", "welcome1",false);
final ProgressDialog dialog = ProgressDialog.show(Test_serializableActivity.this, " EQUINIX ", "Loading.... ", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
Intent intent = new Intent(Test_serializableActivity.this,GetIbx.class);
startActivity(intent);
dialog.dismiss();
}
};
final Thread checkUpdate = new Thread() {
public void run() {
ibx_name.clear();
ibx_name.add("Select");
String json_string = obj.call_Service();
// new Parse_Json(json_string).parse();
parse_json(json_string);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}catch(Exception e)
{
e.printStackTrace();
}
}
public void parse_json(String json_string)
{
try{
JSONObject ja = new JSONObject(json_string);
JSONArray jo = ja.getJSONArray("ibx");
for(int i=0;i<jo.length();i++)
{
JSONObject j_data = jo.getJSONObject(i);
System.out.println("The id is:"+j_data.getString("id"));
ibx_id.add(j_data.getString("id"));
System.out.println("The Name is:"+j_data.getString("name"));
ibx_name.add(j_data.getString("name"));
System.out.println("The naturalKey is:"+j_data.getString("naturalKey"));
ibx_naturalKey.add(j_data.getString("naturalKey"));
}
}catch(Exception e)
{
e.printStackTrace();
}
ibx.setId(ibx_id);--------------->**NPE presents**
ibx.setName(ibx_name);
ibx.setNaturalKey(ibx_naturalKey);
}
}
Get the Value Class:
package com.example.test;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class GetIbx extends Activity{
ArrayAdapter<String> statusAdapter;
Spinner sp_ibx;
List<String> ibx_list = new ArrayList<String>();
setIbx ibx;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.newmain);
ibx_list = ibx.getName();
sp_ibx = (Spinner)findViewById(R.id.spinner1);
statusAdapter = new ArrayAdapter<String>( this,android.R.layout.simple_spinner_item, ibx_list);//Sets an status adapter
statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_ibx.setAdapter(statusAdapter);
}
}
Edited: Getter/Setter Class--
package com.example.test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public abstract class setIbx implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public List<String> id = new ArrayList<String>();
public List<String> name = new ArrayList<String>();
public List<String> naturalKey = new ArrayList<String>();
public void setId(ArrayList<String> id)
{
this.id = id;
}
public List<String> getId()
{
return id;
}
public void setName(ArrayList<String> name)
{
this.name = name;
}
public List<String> getName()
{
return name;
}
public void setNaturalKey(ArrayList<String> naturalKey)
{
this.naturalKey = naturalKey;
}
public List<String> getNaturalKey()
{
return naturalKey;
}
}
A: None of the code you've shown ever sets the ibx field in either class. That field will always be null, as far as I can see.
Note that this isn't a problem with the ArrayList - it's the setIbx ibx field which is null. It's not clear to me what the setIbx class even is, but I would concentrate on working out how you expect this to be non-null rather than the ArrayList fields.
Might it be as simple as a statement of
ibx = new setIbx();
in your constructor? (Or in the field declaration?) I'm not an Android developer, so I may well be off-base, but that's what I think you should be looking at.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create MySQL prepared statement string without connecting to database How do I create a mysql prepared statement 'string' without actually connecting to MySQL. I want to utilize PDO's bindparam to generate a 'mysql string'.
I just need the mysql string. I don't want to do inline variables on the mysql string because it's messy and hard to maintain.
If this can't be done. Do you know any (PHP) string builder library that build a MySQL string?
A: Does PDOStatement->debugDumpParams give you some help?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Comparing Latitude and Longitude In my iPad application i am drawing one rectangle on map using overlay.
I have lat/long of one edge as well as length and width of rectangle.
I have some other lat/longs coming from database.
Now how can i get which lat-long from database is inside rectangle?
Thanks,
A: Solved.
first of all convert four latlons to point using this method :
CGPoint point = [mapView convertCoordinate:location toPointToView:overlayView];
then you have to apply method of point in poly.
A: You can calculate the Distance and if Distance is greater then the current Lat-Long then it is out side otherwise it is inside the circle. You can calculate the Distance using the following lines.
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2];
NSLog(@"Distance i meters: %f", [location1 getDistanceFrom:location2]);
[location1 release];
[location2 release];
A: Try this
Please use the below code to get lat and long for touch point.
CGRect r = mapView.bounds;
float longitudePercent = overlay.point.x / r.size.width;
float latitudePercent = overlay.point.y / r.size.height;
CLLocationCoordinate2D coord = mapView.centerCoordinate;
MKCoordinateSpan span = mapView.region.span;
float lat = coord.latitude + (span.latitudeDelta/2);
float lon = coord.longitude - (span.longitudeDelta/2);
Just add your rectangle's length and width in overlay.point.x and overlay.point.y and get other lat and long.
after getting all 4 lat and long make a sql query on database and get related results for that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Releasing an object that can be [NSNull null] or not I have a memory management problem I can't get my head around on iOS. I'm getting data from a SQLite db where some cells can be empty. So to handle this case, I assign [NSNull null] to my recipient if empty, or the value if not:
NSString *email = (const char *) sqlite3_column_text(statement, 6) == NULL ? [NSNull null] : [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 6)];
But then if I do that:
[email release];
the analyser doesn't like it and I think it crashes my program when the object is actually [NSNull null].
So I've tried:
(id) email == [NSNull null] ? nil:[email release];
But it doesn't work (still crashes and analyser doesn't like it). Any ideas?
Thanks in advance
A: I'm using in that case nil value. For example:
NSString *email = (const char *) sqlite3_column_text(statement, 6) == NULL ? nil : [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 6)];
In such case you can safely call [email release]; // email can be NSString or nil and all will work as you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adding image in awt I was trying to add an image in one of GridBagLayout cells. But i am not able to achieve it.
public class imageInAwt extends Applet{
Panel p;
BufferedImage img;
public void init(){
setLayout(new GridBagLayout());
GridBagConstraints gbc =new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
try {
img = ImageIO.read(new File("settings.gif"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
add(new junaid(img),gbc);
gbc.gridy = GridBagConstraints.RELATIVE;
add(new Label("Junaid"),gbc);
}
}
class junaid extends Canvas {
Image img;
public junaid(Image img) {
this.img = img;
}
public void paint (Graphics g) {
BufferedImage image = null;
g.drawImage(image, 2, 3, null);
g.drawString("Junaid", 22, 16);
}
public void setImage (Image img){
this.img = img;
}
}
Please help.
Thanks in advance
A: public void paint (Graphics g) {
BufferedImage image = null;
g.drawImage(image, 2, 3, null);
g.drawString("Junaid", 22, 16);
}
Huh?!?
public void paint (Graphics g) {
g.drawImage(img, 2, 3, this);
g.drawString("Junaid", 22, 16);
}
A: Use Applet.getImage() method of the Applet class.
Image img=getImage(getCodeBase(),"settings.gif");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When will memory used in a function become free ??(C programming) Below is the code
The Code:
#include <stdio.h>
int * num(void);
int main(void)
{
int * num2;
num2 =num();
printf("%d\n" , *num2);
return 0;
}
int * num(void)
{
int num = 20;
return #
}
The Question :
*
*As we know , the function num is local to its function num() , so in this code I try to return the address of the variable num in the function to the function that calls it , which is main().
*After that I just use the dereferencing operator to extract the value of the specific num variable and print it out in main() function.
*There's one thing i'm confused . I remember i read a book about javascript that mention a variable lifetime is within the function , which mean after the function finish performing its instructions and pass the control back to the function that calls it , the value of each variable in the function will be clean out(garbage collector).But why in this code my main() function still can point to the value of that specific memory address??
A: The reason you can see the value of the variable is because of how the stack works. Effectively as you enter the function num, a pointer (the stack pointer) is moved to add space in for the local storage of the function. When you exit the function the stack pointer is moved back effectively meaning that the next function call will overwrite the stack storage used in the previous function call. Until it is overwritten, however, the value exists in a sort of limbo. It's still actually there in memory but may get overwritten at any moment. The existence of the actual value there may or may not be the case. That is why doing as you do above is known as undefined behaviour.
Basically ... don't do it.
A: Just adding to what @Goz has very well explained. Try this code:
#include <stdio.h>
int * num(void);
int fib(int n)
{
if( 0 == n || 1 == n )
return n;
return fib(n-1) + fib(n-2);
}
int main(void)
{
int * num2;
num2 =num();
(void)fib(7);
printf("%d\n" , *num2);
return 0;
}
int * num(void)
{
int num = 20;
return #
}
There is very good chance that you will not get "20" as the output (There is a chance of program termination as well)
Also when you are compiling the compiler does warn you about this "warning: function returns address of local variable" :)
A: Returning a pointer to a local variable is not right. The variable num is deallocated when that function returns and that memory address is free to be used by the C runtime for another value. The pointer returned is now invalid, because it's pointing to an unallocated region of memory, and will invoke undefined behaviour if used. Undefined behaviour means it may or may not do what you want. In some cases the program will crash, in other case it may work. Why it works in this case is because that part of memory will still hold the value 20. The C runtime doesn't fill that part of memory with 0's after deallocation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is this a good use for "mutable" in C++? I have a class that wraps a file handle:
class FileHandle
{
HANDLE hFile;
TCHAR name[256];
public:
LPCTSTR getName() const { /*(query system for name)*/ return this->name; }
};
I have come up with a design choice:
Since I will be querying the file name often, in order to minimize heap allocations which would happen if I returned std::wstring (I have repeatedly seen that this is a bottleneck in my programs), I have instead decided to keep a name field inside the object itself, and just return a pointer to it as shown.
Of course, the name of the file can change over time, so I can't avoid querying it every time. I can only avoid the reallocation.
Of course, the section saying (query system for name) would not work as shown because name isn't mutable.
On the one hand, the caller doesn't expect the file name to change. But on the other hand, that's not what const means, anyway. The name can certainly change, it's just that the caller can't modify it. So it doesn't look like it should be a problem, but I'm not too sure.
Under what circumstances would it be a good idea for me to use mutable here? Why?
Note 1: Windows guarantees that file names are at most 256 characters long, so there's no buffer overflow issue to consider here.
Note 2: The class is only designed for single-threaded use. I'm not worried about concurrent modifications, only modifications in between statements.
Why const doesn't imply immutability:
This should be self-explanatory:
FileHandle file = ...;
const FileHandle &fileConst(file);
LPCTSTR name1 = fileConst.getName();
file.setName(_T("new name"));
LPCTSTR name2 = fileConst.getName();
Now name1 and name2 aren't equal. So not only can the file name change quite easily, but name1 itself can also change -- even though they're both const. There's no rule saying that const members can't change, just that they can't be changed through the const reference.
A: The missing method here, as I see it, is setName. There's no problem with your code as it is, because there's no way to change name, and changing it via getName is awkward. So, assuming you'd have some
void setName(LPCTSTR newName) { _tcscpy(name, newName); /*or so*/ }
Question now is how you'd expect it to be used. It makes sense that whoever is supposed to be changing the name, has access to a non-const FileHandle. In such case, there's no problem using this trivial setName. If, however, the file name should be changed on a const FileHandle, you have two problems: first, it's awkward... and second, you won't be able to call the setName above. To be able to call it, you'd have to change it to
void setName(LPCTSTR newName) const { _tcscpy(name, newName); /*or so*/ }
which doesn't really makes sense either, but let's pretend it does. Now, this won't work, because FileHandle being const would effectively make name const as well. And this finally brings us to mutable: changing name's declaration to:
mutable TCHAR name[256 + 1 /*for NULL terminator*/];
will indeed allow you to use setName to change the name of a const FileHandle. To me, this looks like a sign of a bad design, where you're actually hacking your own code. For that matter, you can just const_cast the FileHandle, and change it without using mutable. But I really don't know the specifics of your case, so maybe it does make sense...
Update, given the information that getName actually checks the name of the file, and updates name if needed before returning it: in that case, making name mutable would indeed be the way to go, because otherwise it can't be changed from within a const method. It is generally not advised for a getter to change the value of the member whose value it's getting, but if your case dictates that, then making name a mutable would make sense.
A:
Of course, the name of the file can change over time
Are you sure about that? Can a file name be changed while there is an open handle to it? If that's the case, then this is not a good use of mutable. mutable is there to achieve logical constness when bitwise constness cannot be achieved, like is the case with cached data. However, callers of your getName() function would be surprissed if two consecutive const calls would return different values.
Update:
If the property is expected to change from outside the program declaration, then you should make that statement by declaring the function const volatile, and then the use of mutable may be justified. However note there is another problem with this approach, in that a caller of the function keeps the pointer to the file name around and a subsequent call to the function will change its contents. That means that the result of this function should be considered volatile as well.
Update 2:
There is no rule in the standard that dictates the uses of const, no one will stop you from flagging all your functions const and your members volatile. However, const is usually used to indicate that the logical constness of the object won't change by invoking a member function; and volatile is usually used to indicate that the value may be changed from outside the application. The question is about good use of mutable -which I consider subjective-, and mutable is not an outsider to this particular use case specially if the function has a volatile modifier as well. However, const volatile modifiers are rare, const functions returning different values after subsequent calls are rare, and values being changed outside your control are rare. Considering not only the function signature but the ammount of warnings that the documentation should include, I think that the surprise factor is high enough for this to be considered a bad use case at least in my book.
A: I would say it is acceptable, but not ideal. I think logically you have a name that is independent the file handle. You are not asking for the name of the file handle, you are asking for the name of the file that the file handle is referring to. Getting that name doesn't change the file handle, so the logical constness is preserved. What is not ideal is that the results could change in unexpected ways:
LPCTSTR old_name = filehandle.getname();
changeFileName(filehandle);
LPCTSTR new_name = filehandle.getname();
// but old_name and new name still match!
But that is really independent of whether or not the member should be made mutable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Generating html tags programmatically I'm not sure if this is the best solution design. But i would like to know how to add code in view to generate tags like div,p,span etc and also define there attributes programmatically.
For example i have a list of objects that i pass it as Model and then calculate width of div to be generated dynamically from number of objects and then generated div for each object. Div ids would also need to be controlled like div_1,div_2 and also if i could set other attributes like class from the helper directly.
So far i've seen example of Html helper for controls only like textbox and listbox. I am not being able to intuitively think about autogenerated div, span etc.
I'm still a beginner in mvc and it seems like i'm asking something different from similar titled questions. Pardon me if i'm wrong.
Thank you.
A: I think you need to take a look at how to create your own html helper.
they work in much the same way as Html.Textbox etc except they are your own that will create your specific control needs.
http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs
and this one from ScottGu
http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx
Also, when defining widths post render you may want to create a jQuery plugin that can set attributes etc.
And seeing as you are a beginner take a look at this site. I think it's where we all start.
http://weblogs.asp.net/scottgu/archive/2009/04/28/free-asp-net-mvc-nerddinner-tutorial-now-in-html.aspx
A: U Can Assign These Tags to variables and Then use them Programatically.. In fact it is always better way to write those tags manually coz there is always a need to use a closing tag at the end and u need to store that in another variable.. and variables will take some memory and will become a adhac for you... And Adventage for using direct tags is that your IDE also supports them and make it easy for u programme tags rather than using variables for these tags... I hope is The Answer of Your Question
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Wince 6.0 file system corruption - directories appear to be recursing We have a mature Wince 6.0 R2 custom device that is capable of downloading files via WiFi and storing them in a NAND flash FAT file system partition. This has been running on over 15000 devices around the world for over a year now, but recently on some test systems for new software and OS versions, we have been seeing some file system corruptions where a particular directory seems to have a recursive link back to the top level \Flash contents. In particular, we have a \Flash\Manifest directory that includes a subdirectory called GCMaps. Normally this contains a number of map images, but when the corruption occurs, it also includes all of the high level \Flash files and subdirectories in an apparent recursive loop, e.g. \Flash\Manifest\GCMaps\program.exe and \Flash\Manifest\GCMaps\Manifest\GCMaps\Manifest...
It is always the same directory that has the problem, and it is happening on multiple devices on our test rack, although many of our test devices are completely unaffected. I am able to temporarily fix the affected devices by either reformatting the file system partition or by erasing the entire flash device, repartitioning, reflashing the OS, and recreating the file system. But the affected devices continue to develop the corruption within a couple of days.
Recent testing has shown that the file system remains intact after changing the Manifest files multiple times, but then we have an automated reboot at midnight, and upon bootup, some of the affected devices exhibit the problem.
What is strange is that we have not recently changed any of the manifest download or integration logic, nor anything that has anything to do with GCMaps at all. One major change I have made recently was to remove the Windows Shell and run our devices in "Kiosk Mode" with our applications being the only UI.
Has anyone encountered this kind of recursive directory corruption on CE before, and if so, did you find a solution? Is there any reason that removing the shell could have caused this? Any suggestions or information would be appreciated!
Thanks,
Rich Jones
A: FAT is prone to corruption if you don't flush filesystem buffers before rebooting (or if you forcefully turn off the device). This applies to both PCs and other devices that use FAT. So it's probably rebooting that causes the problem. Removal of shell can be related or unrelated - it's possible that shell performs some flushes periodically and this saved you from the issue before.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Groovy char stream pattern matching I have the following code, from the reader stream i want to remove all occurances of Command ran successfully. Please help me suggest any solution
String ostream="license_all (47286) Command ran successfully. License a Command ran successfully."
Reader reader = new StringReader(ostream)
for(c in reader)
{
print(c)
}
A: If you only want the exact form of Command ran successfully., then you can do this:
reader.eachLine{ c ->
println c.replaceAll('Command ran successfully.', '')
}
However, if you want to be more flexible, and replace it disregarding spaces and case, use this:
reader.eachLine{ c ->
println c.replaceAll(/(?i)command\s+ran\s+successfully\s*\./, '')
}
Note, that in both instances, because we are looping over each line, it may be important to add back in the line break (println vs print). Also, due looping over each line, this will not replace the string if it occurs split on more than one line.
Here's a complete example which you can run and modify on the Groovy Web Console. (Link to original one with for...in.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Condition in Two Date field with Two Date Parameters I have an ID field two date fields in table named as From_Date and To_Date. I want to select this dates with date criteria.
ID From_Date To_Date
1 2011-05-03 2011-05-28
2 2011-04-29 2011-05-10
3 2011-05-09 2011-05-20
4 2011-04-28 2011-05-09
5 2011-04-29 2011-05-19
6 2011-05-09 2011-05-09
7 2011-05-09 2011-05-09
8 2011-05-09 2011-05-09
9 2011-05-21 2011-05-21
10 2011-06-06 2011-06-06
11 2011-05-21 2011-05-28
12 2011-05-14 2011-05-28
13 2011-05-23 2011-05-24
14 2011-05-27 2011-05-27
15 2011-05-23 2011-05-24
Now I want two parameter for condition of start date and end date
like
@StartDate = '05/01/2011'
@EndDate = '05/10/2011'
And I want Output from these parameters when ever array of dates between startdate and enddate parameter should be compare to array of dates between From_Date and To_Date field
Output:
ID From_Date To_Date
1 2011-05-03 2011-05-18
2 2011-04-29 2011-05-10
3 2011-05-09 2011-05-20
4 2011-04-28 2011-05-09
5 2011-04-29 2011-05-19
6 2011-05-09 2011-05-09
7 2011-05-09 2011-05-09
8 2011-05-09 2011-05-09
is this possible in single query instead use of trigger or function?
A: If you want to get all records which have From_Date or To_Date are in between your date range (@StartDate and @EndDate) then it's simple query like :
SELECT * FROM TableName
WHERE (From_Date BETWEEN @StartDate AND @EndDate) OR (To_Date BETWEEN @StartDate AND @EndDate);
A: select *
from YourTable
where From_Date <= @EndDate and
To_Date >= @StartDate
https://data.stackexchange.com/stackoverflow/q/113761/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: how to extract data from getJson? How to extract the contents of "data" and load them inside form inputs ?
the situation is like this, I have a data displayed, it's being pulled out from
a database table. now on that displayed data, I placed an "edit" link. now my problem is,
how to use this json thing, in order for me to be able to load the data of the
clicked/to be edited data in the input forms ?
$(function() {
//retrieve comments to display on page
$.getJSON("testfile.php?jsoncallback=?", function(data) {
//what to code here?
});
});
A: Traverse the DOM then Modify the HTML
A: parse json coming from server using jquery parser and then place data wherever you want
A: if you have simple field value mapping returned back, following do the trick for you
$.each(data, function(key, val) {
$('#'+key).val(val);
});
Sample data -
{
"name": "name",
"address": "address"
}
but if nested data is returning, you need to traverse you objects.
A: I name my input fields the same as JSON properties. So if i have the following object:
{
"foo": "",
"bar": {
"baz": ""
}
}
the fields would be defined as:
<input name="foo" class="jsonItem">
<input name="bar.baz" class="jsonItem">
and JSON success handler would fill them recursively:
$.getJSON("testfile.php?jsoncallback=?", function(data) {
function(root) {
var fillInputs = function(obj, prefix) {
prefix = prefix ? prefix + '.' : '';
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var prefixOrName = prefix + prop;
var propVal = obj[prop];
if (typeof propVal === 'object') {
fillInputs(propVal, prefixOrName);
}
else {
$('input.jsonItem[name=' + prefixOrName + ']').val(propVal);
}
}
}
};
fillInputs(root, '');
});
If you want to use the id instead of name, be sure to escape the dots in the selector:
prefix = prefix ? prefix + '\.' : '';
...
$('input.jsonItem#' + prefixOrName).val(propVal);
Also, since I was lazy, the above function does not take into account arrays in the JSON object, but that shouldn't be hard to add.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Paypal Website Payments Pro - Current Exchange Rates? I am just getting started creating a payment form using Website Payments Pro. I will have customers from all over the world. Does Paypal have an option for dynamically calculating real-time exchange rates for transactions? If I post all transactions in USD, does this conversion happen automatically on Paypal's end? Any insight is appreciated.
A: Buyers are charged in the currency you specify in the DoDirectPayment call (part of Website Payments Pro). The conversion then takes place on their card (or PayPal account, if you're using Express Checkout as well).
Website Payments Pro does not offer an API to calculate exchange rates unfortunately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do i fix error?? Error: expected ";" before "factorial"? it says in Line 16 I'm getting an error and do not know how to fix it. My code is as follows:
#include <iostream>
using namespace std;
int main(){
int factorial = 1, current = 2, n;
cout << "enter number to calculate factorial of: ";
cin >> n;
while (current <= n){
factorial = current * factorial;
current++;
}
cout << n << "!= " factorial << endl;
while (n < 0) {
cout << "Must enter a positive number!\n";
cout << "re-Enter number to calculate factorial of: ";
cin >> n;
}
return 0;
}
A: You're missing an operator:
cout << n << "!= " factorial << endl;
Should be:
cout << n << "!= " << factorial << endl;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Retain memory leak in iphone menuitem How to solve memory leak in this:
NSArray *keyboard = [[[NSDictionary alloc] initWithContentsOfFile:menuPath] objectForKey:@"Menu"];
[self setMenuItems:keyboard];
[keyboard release];
setMenuItems is defined in header file.
@property (nonatomic,retain) NSArray *menuItems;
A: NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:menuPath];
self.menuItems = [dict objectForKey:@"Menu"];
[dict release];
And in your dealloc method
- (void)dealloc
{
[menuItems release], menuItems = nil;
}
A: In dealloc method
- (void)dealloc
{
self.menuItems = nil;
[super dealloc];
}
NSArray *keyboard = [[[NSDictionary alloc] initWithContentsOfFile:menuPath] objectForKey:@"Menu"];
self.menuItems = keyboard;
[keyboard release];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Allocating large amount of memory and usage of size_t? In my application ,I am allocating memory to store "volume data" which read from stack of bitmap images.
I stored the data in a "unsigned char" and ,during allocation, first I try to allocate continuous memory-block for entire data.if that fails then tries for scattered allocation.(one small memory-block for each image).
unsigned char *data;
here is my method to allocate memory,I call with "tryContinouseBlock=true".
bool RzVolume::initVolumeData(int xsize, int ysize, int zsize, int bbpsize,bool tryContinouseBlock) {
this->nx = xsize;
this->ny = ysize;
this->nz = zsize;
this->bbp_type=bbpsize;
bool succ = false;
if (tryContinouseBlock) {
succ = helper_allocContinouseVolume(xsize, ysize, zsize, bbpsize);
}
if (!succ) {
succ = helper_allocScatteredVolume(xsize, ysize, zsize, bbpsize);
} else {
isContinousAlloc = true;
}
if (!succ) {
qErrnoWarning("Critical ERROR - Scattered allocation also failed!!!!");
}
return succ;
}
bool RzVolume::helper_allocContinouseVolume(int xsize, int ysize, int zsize,
int bbpsize) {
try {
data = new unsigned char*[1];
int total=xsize*ysize*zsize*bbpsize;
data[0] = new unsigned char[total];
qDebug("VoxelData allocated - Continouse! x=%d y=%d Z=%d bytes=%d",xsize,ysize,zsize,xsize * ysize * zsize * bbpsize);
} catch (std::bad_alloc e) {
return false;
}
return true;
}
bool RzVolume::helper_allocScatteredVolume(int xsize, int ysize, int zsize,
int bbpsize) {
data = new unsigned char*[zsize];
//isContinousAlloc=false;
int allocCount = 0;
try { //Now try to allocate for each image
for (int i = 0; i < zsize; i++) {
data[i] = new unsigned char[xsize * ysize];
allocCount++;
}
} catch (std::bad_alloc ee) {
//We failed to allocated either way.Failed!
//deallocate any allocated memory;
for (int i = 0; i < allocCount; i++) {
delete data[i];
}
delete data;
data = NULL;
return false;
}
qDebug("VoxelData allocated - Scattered!");
return true;
}
I want this code to run in both 32bit and 64bit platforms.
Now the problem is, even in 64Bit environment (with 12Gb memory) ,helper_allocContinouseVolume() method fails when I load (1896*1816*1253) size of data (with bbpsize=1).
Its because of, I use "int" datatype for memory address access and the maxmum of "int" is 4294967295.
In both 32bit and 64bit environment following code gives the value "19282112".
int sx=1896;
int sy=1816;
int sz=1253;
printf("%d",sx*sy*sz);
where the correct value should be "4314249408".
So which datatype should I use for this ? I want to use the same code in 32bit and 64bit environments.
A: I encounter the same problem very often when working on workstations with > 32GB of memory and large datasets.
size_t is generally the right datatype to use for all indices in such situations as it "usually" matches the pointer size and stays compatible with memcpy() and other library functions.
The only problem is that on 32-bit, it may be hard to detect cases where it overflows. So it may be worthwhile to use a separate memory computation stage using the maximum integer size to see if it's even possible on 32-bit so that you can handle it gracefully.
A: Use ptrdiff_t from <stddef.h>.
Reason: it's signed, thus avoiding the problems with implicit promotion where unsigned is involved, and it has the requisite range on any system except 16-bit (in the formal it works nicely also on 16-bit, but that's because the formal has the silly requirement of at least 17 (sic) bits).
A: size_t is defined to be large enough to describe the largest valid object size. So generally, when allocating objects, that is the right size to use.
ptrdiff_t is defined to be able to describe the difference between any two addresses.
Use the one that fits your purpose. That way you'll be ensured it has the appropriate size.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: In BlackBerry LED why stops I am adding a custom LED color in BlackBerry programmatically using LED.etColorPattern(int[] pattern, boolean repeat) method.
LED start successfully.
But when any system event occur and deice goes to start RED color LED (which is default) color for system events, then my custom LED stops, instead of blinking both my custom LED
and system default LED (RED).
Please tell me what is the reason.???
A: The LED can blink with one color at a time. When a system event occurs, and after this system event, you start your own LED color, it will replace the system's LED color. In reverse when you make that LED colored, the system will override it when an event occurs. You can't manage to keep the color you wish for your LED anytime, especially when a system event occurs.
You can resolve this by making your LED color red. In that case this color will not change. Or you will have to accept the fact that the color will become red when another event occurs
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reset password function in php codeigniter I am trying to write reset password function in codeigniter php and mind mind not clicking where to start and what is the best way to do so pls help
my db as like this
CREATE TABLE `members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`verifystring` varchar(15) NOT NULL,
`lostkey` varchar(100) NOT NULL,
`active` enum('0','1') NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
and function goes like this
//forget password
public function forget_password(){
$this->form_validation->set_rules('email','Email Address','xss_clean|required|valid_email|callback_reset_password');
if($this->form_validation->run() == FALSE){
$this->load->view('account/forget_password');
}else{
//send an email
$this->load->library('email');
$this->email->set_newline("\r\n");
$this->email->from('me@gmail.com', 'Raju');
$this->email->to('me@gmail.com');
$this->email->subject('Email my');
$key = 12334455;
$message = "Please click this url to change your password ". base_url()."reset_now/".$key ;
$message .="<br/>Thank you very much";
$this->email->message($message);
if($this->email->send())
{
echo 'Please check your email to reset password.';
}
else
{
show_error($this->email->print_debugger());
}
}
}
//email check for forget password
function reset_password($email){
$query = $this->db->get_where('members', array('email'=>$email));
if(!$query->num_rows()>0){
$this->form_validation->set_message('forget_email_check', 'The %s does not exists in our database');
return FALSE;
}else{
//check database fields
/*
$this->db->where('email', $email);
$this->db->limit(1);
$Q = $this->db->get('members');
if($Q->num_rows()>0){
$data = $Q->result_array();
echo $data[0]['username'].'<br/>';
echo $data[0]['password'].'<br/>';
}
*/
echo '<br/>'. $email.'<br/>';
}
//$query->free_result();
//return true;
}
A: It's simple. First ask the user to enter their username or id or email or whatever their login credential is. (Not the password of course). Now with that value, query the database and if the value exists, just retrieve the corresponding email address. (If the login credential is email, then just check for the presence of the email address in the database). Then,
*
*Create a random string
*Retrieve the user's email from the database and send this newly created string to the user's email ID.
*Update the current password of the user in the database.
*Now, set a flag which basically prompts the user to create a new password when the user logs in with the auto-generated password.
*Once the user creates a new password, then Update the password in the database and also update the flag.
From now on, whenever the user logs in, your application won't prompt the user to reset the user's password.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: $facebook->api() always fails and throws name lookup timeout exception I m creating FB application using new graph api(iframe). Application works fine but when I call api method it throws exception. Say call to
$permissions = $facebook->api("/me/permissions");
OR
$fbme = $facebook->api('/me');
always fails and throws "Name lookup timeout" exception. So I browse for this problem and found one solution that is changing facebook.php file in that set CURLOPT_CONNECTTIMEOUT from default 10 to higher value. But this solution doesn't work for me and I m getting same problem. Why this is happening. Is there any solution for this problem or any alternate method for api() on serverside.
Thanks in advance..
A: Are you sure you are using the new graph API?
You might try replacing "api-read.facebook.com" with "api.facebook.com" in the library you downloaded from facebook. (I think it's name is facebook.php)
And sometimes the Facebook server is not running 100%, you can check that here:
http://api-status.com/6404/50042/Facebook-Graph-API
Also you should check your config, maybe you didn't set the correct App Id or Secret key.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I do shell scripting in Windows I am a new Unix programmer. I want to practice some Unix programs but don't want to install a Unix system. I want to work only on Windows. Is there any way by which I can run shell programs on Windows?
A: You have a number of options.
*
*You can install cygwin for a Unix like environment.
*You can run the GNU software compiled for Windows with GnuWin32.
*Higher level scripting with Perl, Python, Ruby etc. is easy since those languages all have good Windows versions.
*There is Windows PowerShell but that will probably feel very alien to you.
A: You can install a virtual machine with Ubuntu or other distribution of Linux on your Windows. VirtualBox is a good free product to do so.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: IOS, How to add a custom SelectionIndicator to a UIPickerView? I want to add a checkmark instead of the default SelectionIndicator for UIPickerView.
I am trying to add an image as subview
UIImageView * checkMark = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 102, 13, 13)] autorelease];
[checkMark setImage:[UIImage imageNamed:@"pickerChechmark.png"]];
checkMark.layer.borderColor = [[UIColor redColor] CGColor];
checkMark.layer.borderWidth = 2;
[picker addSubview:checkMark];
but its been added behind the picker see the following image.
image 1 for x =0, image 2 for x =5, image 3 for x = 10
(x position of checkmark)
also see the red rectangle on top left, for clarification on my question
UIView * redblock = [[[UIView alloc] initWithFrame:CGRectMake(0, -20, 50, 40)] autorelease];
redblock.backgroundColor = [UIColor redColor];
[picker addSubview:redblock];
[picker bringSubviewToFront:redblock];
how fix this?
A: I also needed to customize the selection indicator because I populate the picker with custom views (they are similar to table view cells) that are higher than the standard indicator.
My initial attempt to specify a semi-transparent view to be superimposed to the UIPickerView upon creation led to the same result. While tracing I noticed that the picker view doesn't have subviews yet at the time of creation, which is probably the reason for the custom selection indicator be sent to the back of the visual hierarchy.
My solution consists of specifying the custom view for the selection indicator the first time the delegate method pickerView:viewForRow:forComponent:reusingView: is called. At that point in time the UIPickerView is ready with all its subviews and my new custom view is properly appended on top of the rest. If you don't need to use custom views for the contents, you could do the same using the other data source method pickerView:titleForRow:forComponent:.
The following snippet shows my solution.
Notes: if the delegate method serves more than one UIPickerView you need to handle the flag differently; SLPickerCell is my own cell class, just a UIView subclass.
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
SLPickerCell *pickerCell = nil;
NSArray *topLevelObjects;
const CGFloat kPickerBorderSize = 10;
const CGFloat kIndicatorVerticalMargin = 2;
// if this is the first time we enter the function, add selection indicator view on top of everything else
if ( ![self pickerSelectionIndicatorInstalled] )
{
UIView *customSelectionIndicator;
CGRect selectionIndicatorFrame;
CGRect pickerViewFrame;
pickerViewFrame = [pickerView frame];
// Create and add a custom selection indicator (a superimposed semi-transparent view)
// Use the cell height as reference for the height of the indicator
selectionIndicatorFrame = CGRectMake(kPickerBorderSize, (pickerViewFrame.size.height - ( [SLPickerCell height] + kIndicatorVerticalMargin )) / 2, pickerViewFrame.size.width - (2 * kPickerBorderSize), ( [SLPickerCell height] + kIndicatorVerticalMargin ));
customSelectionIndicator = [[UIView alloc] initWithFrame:selectionIndicatorFrame];
[customSelectionIndicator setUserInteractionEnabled:NO];
[customSelectionIndicator setAlpha:0.25];
[customSelectionIndicator setBackgroundColor:[UIColor lightGrayColor]];
[[customSelectionIndicator layer]setBorderWidth:1.0];
[[customSelectionIndicator layer]setBorderColor:[[UIColor darkGrayColor]CGColor]];
// Add the indicator on top of the picker
[pickerView addSubview:customSelectionIndicator];
// set the flag; remember to reset it upon creation of a new UIPickerView
[self setPickerSelectionIndicatorInstalled:YES];
}
// [...]
A: try this code,I have added a checkmark and label in my picker view
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)theView{
UIView *pickerviewtemp=[[UIView alloc] initWithFrame:CGRectZero];
UILabel *lbl=[[UILabel alloc] initWithFrame:CGRectMake(-105, -15, 240, 30)];
[lbl setBackgroundColor:[UIColor clearColor]];
[lbl setText:[self.folderNameArray objectAtIndex:row]];
[lbl setFont:[UIFont boldSystemFontOfSize:20]];
[pickerviewtemp addSubview:lbl];
UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(-130, -5, 15, 15)];
if ([self.folderCheckArray containsObject:[NSString stringWithFormat:@"%d",row]]) {
[imgView setImage:[UIImage imageNamed:@"tick.png"]];
}
else {
[imgView setImage:nil];
}
[pickerviewtemp addSubview:imgView];
return pickerviewtemp;
}
A: Try adding the check mark to view itself like this:
[self.view addSubview:checkMark];
Your going to have to fiddle around with the coordinate but you should be able to see it on the picker view.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Problem handling keyboard with openGL and SDL in OCaml I've a problem handling keyboards events using SDL (only for keyboard events) and openGL (to display graphics, I'm planning to display 3d graphics). When I use Sdlevent.poll nothing happen and I can't use wait_event because I've to display in real time. I've tried almost everyting I thinks and NOTHING has been successful, you are my only hope ! ^^
Here is my source code (it's just a spinning square ...)
let rotate = ref 1.0
let _ = Sdl.init [`VIDEO] ; at_exit Sdl.quit
let key_handler k = match k with
| {Sdlevent.keysym=Sdlkey.KEY_ESCAPE} ->
print_endline "I'll miss you so much..." ;
| {Sdlevent.keysym=Sdlkey.KEY_SPACE} ->
print_endline "UP" ;
| {Sdlevent.keysym=Sdlkey.KEY_DOWN} ->
print_endline "DOWN";
| _ -> ()
let renderScene () =
let current_time = ref (Sdltimer.get_ticks()) in
GlClear.clear[`color;`depth];
GlMat.rotate3 (!rotate) (0.0,0.0,1.0);
GlDraw.begins `quad_strip;
GlDraw.color (1.0, 0.0, 0.0);
GlDraw.vertex3 (-0.5, 0.5, 0.0);
GlDraw.vertex3 (-0.5, -0.5, 0.0);
GlDraw.color (0.0, 0.0, 1.0);
GlDraw.vertex3 (0.5, 0.5, 0.0);
GlDraw.vertex3 (0.5,-0.5, 0.0);
GlDraw.ends ();
current_time := Sdltimer.get_ticks() - !current_time;
if(!current_time < 10) then
Sdltimer.delay (10 - !current_time);
Glut.swapBuffers();
Glut.postRedisplay();
begin
match Sdlevent.poll () with
| Some (Sdlevent.KEYDOWN k) ->
print_endline "nope"; key_handler k
| None | _ -> print_endline "nopeee";
end;
Gl.flush();;
let () =
ignore(Glut.init Sys.argv);
Glut.initDisplayMode ~alpha:true ~double_buffer:true ~depth:true ();
Glut.initWindowPosition ~x:100 ~y:100;
Glut.initWindowSize ~w:500 ~h:500;
ignore(Glut.createWindow ~title:"3DMapPro - Edition Expert Business 2012");
GlClear.color(1.,1.,1.);
Glut.displayFunc ~cb:(renderScene);
print_string "oui";
Glut.keyboardFunc (fun ~key ~x ~y -> if key=27 then exit 0);
Glut.mainLoop();;
Since I don't understand how to post code properly on stackoverflow, you can also find my source code well indented and highlighted here : Pastebin
A: First things first: You're mixing GLUT with SDL, both will battle for dealing with windowing and input event handling. Settle for one of those. GLUT is not part of OpenGL
I presume you have this from some tutorial. The key line is this one, which uses GLUT:
Glut.keyboardFunc (fun ~key ~x ~y -> if key=27 then exit 0);
Here a lambda (=anonymous) function is created in situ and passed to Glut.keyboadFunc as handler. This lambda will call exit 0 if ESC is passed. To fix this you first need to get rid of GLUT (all statements beginning with Glut.) and replace it with SDL counterparts.
Furthermore you placed the SDL event polling in the render function. This is just WRONG! Event polling should happen, where at the moment Glut.mainLoop() is.
Also your render function lacks proper viewport, projection and modelview setup, this needs fixing as well.
A: It looks to me like both SDL and Glut think they are supposed to be reading the keys. So maybe Glut is winning and SDL is losing. Does the program exit if you hit ESC (which has a code of 27)?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Session still exist after facebook logout in my application hi i am using facebook graph api for invite friends in my codeigniter application . if i have already logged in to facebook the following screeen is shown
if i am not logged in the page redirects to facebook login page , after suceesfuliy login redirects back to above page . every thing works fine . but the problem is
1) i log in to facebook .
2) i run my application and get the list of friends to invite (above view) .
3)then i log out from facebook .
4)then refresh (F5) my friends invite page .
exeption occurs ,
part of the exception
Error:FacebookApiException Object
(
[result:protected] => Array
(
[error] => Array
(
[message] => Error validating access token: The session is invalid because the user logged out.
[type] => OAuthException
)
)
[message:protected] => Error validating access token: The session is invalid because the user logged out.
[string:Exception:private] =>
[code:protected] => 0
[file:protected] => C:\xampp\htdocs\elephanti\application\frontend\libraries\connections\facebook.php
[line:protected] => 530
[trace:Exception:private] => Array
my code is
public function invite_friends()
{
$fbconfig = array(
'appId' => $this->co_config_items['fb_appid'],
'secret' => $this->co_config_items['fb_secret'],
'cookie' => true,
'domain' => $this->ci->config->item('domain')
);
$this->ci->load->library('connections/facebook', $fbconfig);
$facebook = new Facebook($fbconfig);
$session = $facebook->getSession();
if (!isset($session)) {
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0
));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
} else {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$updated = date("l, F j, Y", strtotime($me['updated_time']));
} catch (FacebookApiException $e) {
echo "Error:" . print_r($e, true);
}
}
$data=array('fb_appid'=>$this->co_config_items['fb_appid']);
return $data;
}
exception prints from the
} catch (FacebookApiException $e) {
echo "Error:" . print_r($e, true);
}
block
the thing is in the if else condition the else part is working , but there shouldn't be a session when i logged out from the facebook . but the session has not cleared , i var_dump the sessions in the first and second time .
before log out
array(7) {
["session_key"]=>
string(46) "2.AQC0otQQWydT6w0l.3600.1317193200.0-770398599"
["uid"]=>
string(9) "770398599"
["expires"]=>
int(1317193200)
["secret"]=>
string(24) "E9oNYQCuQdggyp_pJyLnqA__"
["base_domain"]=>
string(9) "localhost"
["access_token"]=>
string(90) "140577549320080|2.AQC0otQQWydT6w0l.3600.1317193200.0-770398599|5ZoDt4wTt16ve0fgaj8m_X70ojw"
["sig"]=>
string(32) "74a283a7cd2f4d62bb7739deaf65affc"
}
after logout and refresh one time
array(7) {
["access_token"]=>
string(90) "140577549320080|2.AQC0otQQWydT6w0l.3600.1317193200.1-770398599|C84xhtx_dnakmf-7oCZlb07FQL8"
["base_domain"]=>
string(9) "localhost"
["expires"]=>
string(10) "1317193200"
["secret"]=>
string(24) "E9oNYQCuQdggyp_pJyLnqA__"
["session_key"]=>
string(46) "2.AQC0otQQWydT6w0l.3600.1317193200.1-770398599"
["sig"]=>
string(32) "6eedc49e4957708a551c4155ff8f57a6"
["uid"]=>
string(9) "770398599"
}
in the second refresh the session is NULL and redirects to the login page and works correct , why is session not clearing in the first time , please help .
UPDATE
after session is NULL i print the session and addede a die , and logged in to facebook again ;
$session = $facebook->getSession();
print_r($session);
die ;
the thing is every time now gives NULL , so i think a place after
$session = $facebook->getSession();
session is creating , i think that's why i get the correct result in the second time , from where the session is changing ??
i searched and saw similar questions but could not get help. please help ..............
A: Try adding a listener for when the user logs out;
FB.subscribe('auth.logout', function(response){
// Do something to let your program know that the user is now logged out.
});
And/or, add your own facebook logout to your site with FB.logout(). This should clear your website/s fb session as well as log them out of facebook.com.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why numeric constraint didn't work on Virtual keyboard in LWUIT? I have tested many ways to give the numeric and password constraint in the TextField. But its not working, See the below code.
textField.setConstraint(TextField.NUMERIC | TextField.PASSWORD);
textField.setInputModeOrder(new String[]{"123"});
Above code should work on the non touch mobiles. But its not working on the touch mobiles. So i have set the input mode value for VKB and bind that TextField with VKB, see this code.
TextField txt = new TextField();
txt.setConstraint(TextField.NUMERIC |TextField.PASSWORD);
txt.setInputModeOrder(new String[]{"123"});
VirtualKeyboard vkb = new VirtualKeyboard();
vkb.setInputModeOrder(new String[]{VirtualKeyboard.NUMBERS_MODE});
VirtualKeyboard.bindVirtualKeyboard(txt, vkb);
VirtualKeyboard.NUMBERS_MODE not working when I use above code. VKB showing as usual format. That means AlphaNumeric format. Why its showing like this?
A: This is a bug in LWUIT, thanks for bringing it to our attention I'll try to commit a fix for it in the next couple of weeks. It would be sooner but we need to fly to JavaOne soon.
If you want to try the fix locally just update this method in VirtualKeyboard.java:
public void setInputType(int inputType) {
if((inputType & TextArea.NUMERIC) == TextArea.NUMERIC ||
(inputType & TextArea.PHONENUMBER) == TextArea.PHONENUMBER) {
setInputModeOrder(new String []{NUMBERS_MODE});
return;
}
if((inputType & TextArea.DECIMAL) == TextArea.NUMERIC) {
setInputModeOrder(new String []{NUMBERS_SYMBOLS_MODE});
return;
}
setInputModeOrder(defaultInputModeOrder);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to pass variable between methods in Ruby?
Newbie ruby question.
I have a class
class ReportPage < Page
def badge_item(item_int)
case item_int
when 1..50 then @item= 1
when 50..100 then @item= 50
end
def check_completed_items_badge
badge_item(50)
puts @item
end
end
Sure enough, it puts nil. And here comes my question - how can I use @item variable inside of the other method of the class?
Thank you a lot!
A: The thing is you miss end keyword for your case. And there is another problem in this program. when(1..50) contain all cases between 1 to 50, and when(50..100) covers 50 to 100, this will lead confusion cause badge_item(50) will go into the first line, set @item to 1 and quit the case ... end block. So at the end it will print 1 on the screen.
To make your intent more clearly, you should use
def badge_item(item_int)
@item = case item_int
when 1..49 then 1 #two dots, cover 1 to 49
when 50..100 then 50
end
end
OR
def badge_item(item_int)
@item = case
when 1...50 then 1 #three dots between, cover 1 to 49
when 50..100 then 50
end
end
A: The problem is not with the variable assignment but instead with your usage of the case/when syntax. When you give case an argument it uses exact matching to compare the different scenarios. A better way in your case would probably be to use something like this instead:
def badge_item(item_int)
case
when (1..50).include?(item_int) then @item = 1
when (50..100).include?(item_int) then @item = 50
end
end
Edit
Corrections from Tumtu:
case uses === method to compare values. i.e.: (1..50) === 50
A: The correct approach in your case is to use the OOP:
class ReportPage < Page
class BadgeItem
def initialize( int )
fail "Badge item integer should be in the range 0..99!" unless 0..99 === int
@int = int
end
def classify
case @int
when 0...50 then 1
when 50..99 then 50
end
end
end
def check_completed_items_badge
badge_item = BadgeItem.new 50
puts badge_item.classify
end
end
A: I know an answer has already been accepted but I wanted to present a more general answer to the question about how instance variables get tossed around.
Straight from ruby-lang you get the following:
Ruby needs no variable declarations. It uses simple naming conventions
to denote the scope of variables.
*
*var could be a local variable.
*@var is an instance variable.
*$var is a global variable.
These sigils enhance readability by allowing the programmer to easily
identify the roles of each variable. It also becomes unnecessary to
use a tiresome self. prepended to every instance member
It is important to understand the distinction between these different types of variables. To do this I whipped up a small example that should help give anyone with navigates here a good starting point on how these behave.
class Scoping
@unreachable = "but found it. trololol"
$instance = "and found it. swag swag"
def initialize( int )
trial = @unreachable ? @unreachable : " but failed to find."
puts "reaching for the unreachable . . ." + trial
@int = int
end
end
puts $instance
Scoping.new 10
trial = @int ? @int : " but failed to find."
puts "Reaching for instance from class . . ." + trial
trial = $instance ? $instance : " but failed to find."
puts "Reaching for global variable . . ." + trial
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Pass argv[1] by reference I've an issue with passing argv to a function. Basically, I want to pass &argv[1] to the function and work from that. However, I don't understand why the following does work:
void fun(char**&argv, const int& argc);
int main(int argc, char** argv)
{
fun(++argv, --argc);
return 0;
}
yet the following doesn't work:
void fun(char**&argv, const int& argc);
int main(int argc, char** argv)
{
fun(&argv[1], --argc);
return 0;
}
A: Prototype:
void myfunc (char **argv, int argc)
Example usage:
myfunc (argv, argc)
If you wanted to pass ONLY one string (argv[1]):
void myfunc (char *arg, int argc)
...
myfunc (argv[1], argc)
And if you wanted to pass an array of strings starting at argv[1]:
void myfunc (char **arg, int argc)
...
myfunc (&argv[1], argc)
A: The error I get when I try this is that argv[1] is a temporary value and you can't assign that to a non-const reference. If you instead do this:
void fun( char** const&argv, const int& argc);
Then either ++argv or &argv[1] will work.
Obviously, if you planned to actually change the value of argv itself, this won't work, but I presume that you aren't planning to do this since you're not passing a reference to argv itself but rather to the memory location of the second entry in argv.
The reason that the first one works and the second doesn't is that the ++ operator at the front modifies the variable and then returns not just its value after the modification, but the variable itself. As a result, the variable can then be passed into fun as a reference. But the &argv[1] is just the value of a memory location. It's a computed value, not a variable in its own right, so it can't be passed in as a non-const reference.
If you're planning to try to change the value of argv itself (to point it to a different array of character arrays), then &argv[1] doesn't work for that anyway, since it's not argv. ++argv, however, is argv, just after it's had its value adjusted.
You could also handle all of this without references at all, which would make things much easier, but that's up to you. If it were my code, though, I wouldn't be using references here. The const reference to an int could just be passed by value (which would be easier) and passing a reference to a double pointer doesn't save you any null checking (as it could still well be null). So there isn't much point to it. But if you like your code to be complex, feel free.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JGroups Instances communication I have two machines in which the JGroups is running. The Problem I am facing is, once a Instances is created in one of the machines, few seconds later I start the other Instances. Both of them initiate separatly(Same Cluster) i.e they don not join the cluster together. After 10 to 15 seconds they both communicate and join together.
This delay is causing problem with my Business in the code...
There is also a Warning thrown while startin the Program
WARNING: send buffer of socket java.net.MulticastSocket@5954864a was set to 640KB, but the OS only allocated 135.17KB. This might lead to performance problems. Please set your max send buffer in the OS correctly (e.g. net.core.wmem_max on Linux)
Do this has some thing to do with the Issue?
A:
You will absolutely need to increase these values – otherwise UNICAST
is almost unusable.
If you aren’t familiar with how to do so, modify the /etc/sysctl.conf
file. These are my values on my nodes.
JGroups UDP configuration
net.core.rmem_max = 25480000
net.core.wmem_max = 25480000
To reload these values, issue a "sysctl -p" as root to force a reload
of this file.
Source: http://comments.gmane.org/gmane.comp.java.javagroups.general/7922
A: The Warning is not related to your problem, this can only lead to performance issues, because the OS buffer is to small for your Multicast-Buffer.
Concerning your problem: check your log for all jgroups messages (not only warnings) and check the timings of them. And post your cluster configuration.
A: Edit the /etc/sysctl.conf by changing this value (net.core.wmem_max) and run the "sysctl -p"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Rails 3: How to format a Date in other than English languages? To format a Date in English I do:
Date.today.to_s(:long_ordinal) # => September 28th, 2011
How could I format a date in Russian (or any other language) ?
A: There is the Internationalization API in Rails that explains how to do that. See for example section 3.2 Adding Date/Time Formats.
<p><%= l Date.today, :format => :short %></p>
You can then add for your locale (russian?) a file ru.yml and include there the definition for your format.
# config/locales/ru.yml
ru:
date:
formats:
short: "%m/%d/%Y"
See the section 4.4 Setting and Passing a Locale how to set the locale.
A: Date formats and locales are defined in ActiveSupport. You can add these values to your locale file and modify them to fit your requirements.
Also check this for russian language.
A: Use strftime. Example:
Date.today.strftime('%m/%d/%Y')
You set the %-symbols according to how you want the date to format. See the documentation I linked to see what symbols you can use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to reset a timer every minute if there is no query to the database? I have a basic server in PHP and from the mobile device I send data and save the server every 1 minute.
But when ever my mobile phone loses the connection, I would like to set a counter on the server and if the mobile does not insert anything the database longer than 2 min. I would like to call a function in the server saying that your mobile lost connection. Every time the mobile phone sends the data to the server, timer will be reset.
I am not familiar to PHP but I searched and couldn't find any similar things. I am sure there must be an easy way of doing it. setting a listener or creating a count down timer.
A: You can't set a timer in your PHP code as it runs only when a client requests a page.
As you doesn't have an access to CRON jobs, you can't do it from CLI side either.
However, some webservices allow you to periodically call a page of your choice, so you can save() on every http://something/save.php call. Take a look at http://www.google.fr/search?ie=UTF-8&q=online+cron for more informations.
Note that if someone get the save() url, he can easily overload your server. Try to secure it as most as possible, maybe with a user/password combination passed as parameters.
A: Finally I got it worked. What I learned is that the server cant do anything if there is no request:) So I created a timestamp field in the database and update the current time with the request. Of course before updating the field gets it and compare it with the current time and see when was the last request. and find out the time difference. if the time difference bigger than 2 min change the position. I hope this helps other people as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rampart Client throwing exception when trying to consume the service I am trying to invoke a axis2 web service enabled with Rampart security. When I try to invoke the service through the client I am getting the following exception, (I have also included Jaxen Jar in my project)
Exception in thread "main" org.apache.axis2.AxisFault: java.lang.NoClassDefFoundError: org/jaxen/JaxenException
at org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(Utils.java:446)
at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:371)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:417)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at com.tcs.secure.SecureServiceStub.add(SecureServiceStub.java:186)
at com.tcs.secure.Client.main(Client.java:16)
I have generated stubs for my password call back class and my sample class and imported it to my client. Here is my sample client.
public class Client {
public static void main(String[] args) throws RemoteException {
SecureServiceStub stub = new SecureServiceStub();
Add request = new Add();
request.setA(23);
request.setB(389);
AddResponse response = stub.add(request);
System.out.println(response);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android java development time of acceleration to How can I calculate the time of acceleration to 100kmh?
Well, I registered a location listener when the !location.hasSpeed() is true store the time of location into a variable. When the speed is reach of the given speed in this case 100km/h (27.77 m/s) I substract from the spped of location and the result I divide by 1000.
Here is the "pseudo code"
@Override
public void onLocationChanged(Location currentLoc) {
// when stop reseted, when start reset again
if (isAccelerationLoggingStarted) {
if (currentLoc.hasSpeed() && currentLoc.getSpeed() > 0.0) {
// dismiss the time between reset to start to move
startAccelerationToTime = (double) currentLoc.getTime();
}
}
if (!currentLoc.hasSpeed()) {
isAccelerationLoggingStarted = true;
startAccelerationToTime = (double) currentLoc.getTime();
acceleration100 = 0.0;
}
if (isAccelerationLoggingStarted) {
if (currentLoc.getSpeed() >= 27.77) {
acceleration100 = (currentLoc.getTime() - startAccelerationToTime) / 1000;
isAccelerationLoggingStarted = false;
}
}
}
A: The main problem i see here, is that whenever the device is moving, startAccelerationToTime is reset. (The first if only checks whether there's movement; it doesn't check whether there's already a start time recorded.
I don't see where isAccelerationLoggingStarted is needed at all -- the speed, and the variables themselves, can be cleaned up a bit to make it clear what the next step should be.
Your pseudocode probably ought to look something like:
if speed is 0
clear start time
else if no start time yet
start time = current time
clear acceleration time
else if no acceleration time yet, and if speed >= 100 mph
acceleration time = current time - start time
In Java, that'd look like...
long startTime = 0;
double accelerationTime = 0.0;
@Override
public void onLocationChanged(Location currentLoc) {
// when stopped (or so slow we might as well be), reset start time
if (!currentLoc.hasSpeed() || currentLoc.getSpeed() < 0.005) {
startTime = 0;
}
// We're moving, but is there a start time yet?
// if not, set it and clear the acceleration time
else if (startTime == 0) {
startTime = currentLoc.getTime();
accelerationTime = 0.0;
}
// There's a start time, but are we going over 100 km/h?
// if so, and we don't have an acceleration time yet, set it
else if (accelerationTime == 0.0 && currentLoc.getSpeed() >= 27.77) {
accelerationTime = (double)(currentLoc.getTime() - startTime) / 1000.0;
}
}
Now, i'm not sure exactly how location listeners work, or how often they notify you when you're moving. So this may only semi work. In particular, onLocationChanged might not get called when you're not moving; you may need to request an update (perhaps via a "reset" button or something) or set certain params in order to trigger the stuff that happens when speed == 0.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get the form id on page load jquery How to get form id using JQuery on page load.
I am having a form in a page. I need to get that form's id using JQuery .
How can I do that..
thanks in advance...
A: $(document).ready(function(){
var formId = $('form').attr('id');
});
A: try
$(document).ready(function(){
alert($('form').attr('id'));
});
A: $(document).ready(function(){
$('form').each(function(){
alert($(this).attr('id')); // or simple this.id
})
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Why is the address bar not editable? Sometimes in websites when you click on some link a new browser windows appears where there's no back button and address bar is not editable,it's locked (greyed out) so you can't change the URL. Just a box containing some information or text boxes to enter data. I would like to know why. Is this because of some security issues or is there something else?
A: You are right - it has something to do with security, and in particular, preventing spoofing attempts.
The address bar is usually present in the popup windows of many browsers to indicate which page is being displayed. This way, the user is aware of their current location and will be able to tell if the popup is navigating to an illegitimate website.
The address bar is disabled as a cue to the user that they should not be navigating to a different page within the new window, but should continue their browsing experience by closing the popup and returning to the main window.
Please see this Mozilla ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=470051 - and especially Nochum Sossonko's comment for reference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Setting the width of a division dynamically I have a jScrollPane on a magento product page which is fetching in options which are displayed as an inline list (see screenshot - http://awesomescreenshot.com/06dlbao6b ).
Is it possible to dynamically set a division size depending on the content as some products will only have 2 options but some may have 27.
So far I've only worked out a way of showing more than 4 options if I manually set the division width, this isn't really an option as if I only have 3 products I don't need to show the scroll controls.
The division in question is the product-options-chooser div.
Not sure if it helps but here is the code in question from \template\catalog\product\view\options\type\select.phtml :
<?php /* @var $this Mage_Catalog_Block_Product_View_Options_Type_Select */ ?>
<?php $_option = $this->getOption() ?>
<script>
jQuery(function()
{
var pane = jQuery('.product-options-container');
pane.jScrollPane(
{
showArrows: true,
animateScroll: true
}
);
});
</script>
<div class="product-options-title">
<dt>
<label<?php if ($_option->getIsRequire()) echo ' class="required"' ?>>
<?php if ($_option->getIsRequire()) echo '<em>*</em>' ?>
<?php echo $this->htmlEscape($_option->getTitle()) ?></label>
</dt>
</div>
<div class="product-options-container">
<div class="product-options-chooser">
<dd<?php if ($_option->decoratedIsLast){?> class="options-last"<?php }?>>
<div class="input-box"> <?php echo $this->getValuesHtml() ?>
<?php if ($_option->getIsRequire()): ?>
<?php if ($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_RADIO || $_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_CHECKBOX): ?>
<span id="options-<?php echo $_option->getId() ?>-container"></span>
<?php endif; ?>
<?php endif;?>
</div>
</dd>
</div>
</div>
A: Have a workaround for this now as managed to set widths to specific classes for specific products
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how can I bind values to form inputs Django I am trying to do an edit page where I fill the input boxes with the values taken from the database.
Say I have a model Employees and a field name, a form EmployeeForm and an input field name
emp_info = Employees.objects.get(pk=1)
emp_form = EmployeeForm()
I am currently doing this and it does not seem to work
emp_form.name = emp_info.name
template:
{{ emp_form.name }}
What is the correct way to do it?
A: If you can't use a model form for some reason, try this
emp_info = Employees.objects.get(pk=1)
emp_form = EmployeeForm(initial={'name': emp_info.name})
A: emp_info = Employees.objects.get(pk=1)
This will populate your form with the emp_info.
emp_form = EmployeeForm(instance=emp_info)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Animate background color's saturation or lightness using JQuery I did a search, and I found a function that randomly changes RGB values only, namely
http://buildinternet.com/2009/09/its-a-rainbow-color-changing-text-and-backgrounds/
However, I simply want to change a header color's HSL value (either saturation or lightness). I want the color's saturation or lightness to change very slowly and subtly.
Any hints or advice would be appreciated. Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript issue. Need help with a loop and .append I a search result page. This search result page is a table. I can not change the html of the page. This is the html:
<table class="product-table">
<tr>
<td>
<dl>
<dt>
<h1>Item</h1>
</dt>
<dd class="title fn">
<a class="url" href="/product.jsp?id=EHS_FR_BS-PK-409674&navAction=jump&navCount=0">
Pratique de l'accouchement, 5ème Edition
</a>
</dd>
</dl>
</td>
</tr>
<tr>
<td>
<dl>
<dt>
<h1>Item</h1>
</dt>
<dd class="title fn">
<a class="url" href="/product.jsp?id=EHS_FR_BS-PK-409674&navAction=jump&navCount=0">
Pratique de l'accouchement, 5ème Edition
</a>
</dd>
</dl>
</td>
</tr>
</table>
My Question
But i want in the dd class title fn. A new element. This a element is a link to more information of the page. The element must get the href of the a class=url element.
I make this javascript:
$("table.product-table .pricing").append('<a class="information" href="" title="plus d’information">plus d’information</a>');
But how can i fix this better. And how can i put the href of the class url in the new a element that i append.
Do you understand my question??
Thanks for helping!
A: $("dd.title.fn").each(function() {
var $this = $(this);
$this.append('<a class="information" href="' + $this.find(".url").attr("href") + '" title="plus d’information">plus d’information</a>');
});
Does this help you? Check out this link for more information on each method which might help you getting the url of each link you want to append.
http://api.jquery.com/jQuery.each/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to save contact along with address, Organization and categoriesin iphone using phonegap Anyone help me..
var addresses = [4];
addresses[0] = new ContactAddress('streetAddress','Die Strasse 45',true);
addresses[1] = new ContactAddress('locality','Hamburg',true);
addresses[2] = new ContactAddress('postalCode','22041',true);
addresses[3] = new ContactAddress('country','Deutschland',true);
myContact.addresses = addresses;
Above is the code i am trying to add contact address to iOS using Phonegap. But the address not added to Addressbook, rest like Name, phonenumbers are updated properly.
Looking forward to the solution.
A: In PhoneGap, the addresses array contains several addresses, not several address-details.
To add your address, try :
addresses[0] = new ContactAddress();
addresses[0].streetAddress = 'yourStreet';
addresses[0].locality = 'yourLocality';
addresses[0].postalCode = 'yourPostalCode';
addresses[0].country = 'yourCountry';
A: Try This:
var addresses = [1];
var address = new ContactAddress();
address.streetAddress='MyAddress';
address.locality='MyLocality';
address.postalCode='MyPostCode';
address.country='MyCountry';
addresses[0] = address;
contact.addresses = addresses;
A: Thanks Vinayak.
I got the solution, problem with iOS not phonegap and below is the working code.The type property required for adding contactAddress in iOS addressbook.
var addresses= [];
addresses[0] = new ContactAddress();
**addresses[0].type = 'home';**
addresses[0].streetAddress = 'yourStreet';
addresses[0].locality = 'yourLocality';
addresses[0].postalCode = 'yourPostalCode';
addresses[0].country = 'yourCountry';
myContact.addresses = addresses;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Starting a service: "Error 1053: The service did not respond to the start or control request in a timely fashion" I installed my c# application as windows service, by using the command installutil.
It get successfully installed. While starting the service I am getting the following error.
"Error 1053: The service did not respond to the start or control request in a timely fashion"
Why it happens?
Below is the source code
static void Main(string[] args)
{
// Get the version of the current application.
Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName assemName = assem.GetName();
Version ver = assemName.Version;
// Console.WriteLine("{0}, Version {1}", assemName.Name, ver.ToString());
Console.WriteLine("{0} version {1}", assemName.Name, ver.ToString());
TouchService touchService = new TouchService();
if (Environment.UserInteractive)
{
bool show_help = false;
bool install_service = false;
bool uninstall_service = false;
string servicename = "";
OptionSet p = new OptionSet()
.Add("h|?|help", delegate(string v) { show_help = v != null; })
.Add("s|servicename=", "name of installed service", delegate(string v) { servicename = v; })
.Add("i|install", "install program as a Windows Service. A valid servicename is needed.", delegate(string v) { install_service = v != null; })
.Add("u|uninstall", "uninstall program from Windows Services. A valid servicename is needed.", delegate(string v) { uninstall_service = v != null; });
List<string> extra;
try
{
extra = p.Parse(args);
}
catch (OptionException e)
{
Console.Write("TouchServer: ");
Console.WriteLine(e.Message);
Console.WriteLine("Try `TouchServer --help' for more information.");
return;
}
if (show_help)
{
ShowHelp(p);
return;
}
else if (install_service)
{
IntegratedServiceInstaller Inst = new IntegratedServiceInstaller();
Inst.Install(servicename, null, "Provides XML data over HTTP for Touch clients",
System.ServiceProcess.ServiceAccount.NetworkService,
System.ServiceProcess.ServiceStartMode.Manual);
return;
}
else if (uninstall_service)
{
IntegratedServiceInstaller Inst = new IntegratedServiceInstaller();
Inst.Uninstall(servicename);
return;
}
// start and run the server,
// and receive commands from the console
else
{
touchService.OnStart(args);
while (true)
{
Console.Write("TouchServer>");
string commandLine = Console.ReadLine().ToLower();
if (commandLine == "exit" || commandLine == "x")
{
break;
}
if (commandLine == "quit" || commandLine == "q")
{
break;
}
else if (commandLine == "version" || commandLine == "v")
{
Console.WriteLine("{0} version {1}", assem.GetName().Name, assem.GetName().Version.ToString());
}
else if (commandLine == "list" || commandLine == "l")
{
TouchServer.showURLs = (TouchServer.showURLs == false) ? true : false;
Console.WriteLine("List URLs: {0}", (TouchServer.showURLs ? "active" : "inactive"));
}
else if (commandLine == "status" || commandLine == "s")
{
Console.WriteLine("{0,-20} {1,8}", "Name", "Sessions");
Console.WriteLine("----------------------------");
foreach (Site site in TouchServer.siteCollection.All)
{
Console.WriteLine("{0,-20} {1,8}", site.Name, site.AllSessions.Length);
}
Console.WriteLine();
}
}
touchService.OnStop();
}
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new TouchService()
};
ServiceBase.Run(ServicesToRun);
}
}
static void ShowHelp(OptionSet p)
{
Console.WriteLine("Usage: TouchServer [OPTIONS]+ ");
Console.WriteLine();
Console.WriteLine("Options:");
p.WriteOptionDescriptions(Console.Out);
Console.WriteLine();
Console.WriteLine("Providing no options results in the server running in console mode (for debugging purposes).");
}
public TouchService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
taskList.Clear();
taskList.Add(new TouchServerTask("TouchServer"));
taskList.Add(new HouseKeeperTask());
//TouchServer.Execute();
setupSynchronizerTasks();
taskList.StartAllTasks();
}
A: Your question has been answered here.
What's assumed is that there's a problem within your code that resides in
void OnStart(string[] args)
in your code. In that case, attach a service debugger to troubleshoot your problem.
Good luck.
A: Your service does to much in OnStart.
Start the service choose Tools->attach to process in Visual Studio, choose your service. Break the process and try to figure out what the process is doing so long time in OnStart.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: facebook comment plugin asp.net i want to include facebook comment box in facebook application built in asp.net
i have already tried facebook comment plugin but somehow it does not work and gives all.jss errors can anyone suggest working sample
for example my current one looks like.
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head runat="server">
<title></title>
<%-- <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"
type="text/javascript" />--%>
<%-- <script type="text/javascript">
FB.init("163659850382295", "xdreciever.htm");
</script>--%>
</head>
<body>
<form id="form1" runat="server">
<div id="fb-root">
</div>
<div class="fb-comments" data-href="http://aspspider.ws/prashantkurlekar/likeTest.aspx"
data-num-posts="10" data-width="500">
</div>
</form>
</body>
</html>
A: It looks like you are using the original Comments box, which has been replaced by a newer version. I would view the current documentation and see if the errors disappear.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JMeter NaN issue in reports I have used jmeter 2.5 and ANT 1.8.2 and jdk 1.6. Also, I have used latest .xsl file path in build.xml.
Issue is iam getting NaN value for Min, Max in html reports.
Please let me know any solutions.
A: This problem is encountered in newer versions of Java.
I faced the same problem and this solution worked for me - Copy xalan-2.7.1.jar and serializer-2.7.1.jar from the apache-jmeter/lib folder and include it in apache-ant/lib folder of ant.
A: Somehow it's a problem related to newer Java versions: If you use Java 1.5 or higher it wont work out of the box, unless you:
*
*Use the build file: http://svn.apache.org/repos/asf/jmeter/trunk/extras/build.xml
*Include xalan.jar and serializer.jar both in jmeter lib directory
There are two bugs in apache bugzilla regarding this issue. More info:
*
*http://vishnuagrawal.blogspot.com/2009/04/jmeter-run-tests-using-ant.html
*http://jmeter.512774.n5.nabble.com/Min-and-Max-times-are-returning-NaN-td525870.html
A: Given it works in XP and not windows 7, try running in either:
*
*As Administrator
*Compatibility mode
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: fixing child layout/widget position in QT I wanted to know whether is there any way of fixing child layouts within a parent layout. For example...
QVBoxLayout *vbox = new QVBoxLayout;
// adding pushbuttons/layouts...
vbox->addWidget(one);
vbox->addWidget(two);
vbox->addWidget(three);
vbox->addWidget(four);
Now this ends up as four buttons/layouts in a vertical layout in the sequence that they are added. But if I remove buttons/layouts "one", "two" and "three"...
vbox->removeWidget(one);
vbox->removeWidget(two);
vbox->removeWidget(three);
After doing this, the pushbutton "four" will move up the layout as you remove widgets on top of "four". I don't want this to happen.
Is there any way that even if I remove the widget/layout on top, I need that last widget/layout to stay where it is currently.
How do I achieve this ?
UPDATE: Well I was experimenting and I was kind of able to achieve what I wanted using QGridLayout. Here is the code, but I am using QGridLayout instead of QVBoxLayout.
connect(one,SIGNAL(clicked()),this,SLOT(remove_btns()));
g = new QGridLayout(this);
g->addWidget(one,0,0,1,2);
g->addWidget(two,1,0,1,2);
g->addWidget(three,2,0,1,2);
g->addWidget(four,3,0,1,2,Qt::AlignBottom);
setLayout(g);
If I delete the above three buttons, the fourth one stays where it is, because of QT::AlignBottom , it does not work without that thing.
Here is the SLOT remove_btns()
void test::remove_btns()
{
g->removeWidget(one);
g->removeWidget(two);
g->removeWidget(three);
delete one;
delete two;
delete three;
}
When I click "one", top three buttons vanish, and the fourth one stays where it is. But it does not work if I don't give the QT::AlignBottom . Also, these alignment things are a mystery to me, I am unable to find how exactly they work.
This is definitely NOT an answer..., because I don't understand how it worked :P
A: If you are immediately replacing the widgets you removed, you can always insert your new widgets by index.
void insertWidget ( int index, QWidget * widget, int stretch = 0, Qt::Alignment alignment = 0 )
A: Yes, just hide the widgets instead of removing them:
one->hide();
two->hide();
three->hide();
If you really have to remove the widgets, perhaps you can replace them with some lightweight widget like a QLabel with no text.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Switching between activities in a tab gives error the application has stopped unexpectedly. Please try again I am working on android application and I am struck at the below error. Can anybody of you help me out with this error:
When I switch between activities in a tab I was able to do it for 2 times on 3rd time I get the error saying Sorry...application has stopped unexpectedly. Please try again.
I tried to take the info from LogCat file below is the information:
10-19 03:21:53.794: INFO/dalvikvm(460): threadid=1: stack overflow on call to Lsun/misc/Unsafe;.compareAndSwapInt:ZLJII
10-19 03:21:53.804: INFO/dalvikvm(460): method requires 24+20+0=44 bytes, fp is 0x4186931c (28 left)
10-19 03:21:53.804: INFO/dalvikvm(460): expanding stack end (0x41869300 to 0x41869000)
10-19 03:21:53.815: INFO/dalvikvm(460): Shrank stack (to 0x41869300, curFrame is 0x4186bc60)
10-19 03:21:53.844: DEBUG/AndroidRuntime(460): Shutting down VM
10-19 03:21:53.854: WARN/dalvikvm(460): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): FATAL EXCEPTION: main
10-19 03:21:53.984: ERROR/AndroidRuntime(460): java.lang.StackOverflowError
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at java.util.concurrent.locks.AbstractQueuedSynchronizer.compareAndSetState(AbstractQueuedSynchronizer.java:522)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at java.util.concurrent.locks.ReentrantLock$NonfairSync.lock(ReentrantLock.java:182)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:261)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at java.util.concurrent.CopyOnWriteArrayList.remove(CopyOnWriteArrayList.java:490)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewTreeObserver.removeOnPreDrawListener(ViewTreeObserver.java:377)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.widget.TextView.onDraw(TextView.java:3875)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.View.draw(View.java:6740)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.View.draw(View.java:6743)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.View.draw(View.java:6743)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.widget.FrameLayout.draw(FrameLayout.java:352)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.View.draw(View.java:6743)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.widget.FrameLayout.draw(FrameLayout.java:352)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.View.draw(View.java:6743)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.widget.FrameLayout.draw(FrameLayout.java:352)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.View.draw(View.java:6743)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.widget.FrameLayout.draw(FrameLayout.java:352)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.View.draw(View.java:6743)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.widget.FrameLayout.draw(FrameLayout.java:352)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.View.draw(View.java:6743)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.widget.FrameLayout.draw(FrameLayout.java:352)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.View.draw(View.java:6743)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.widget.FrameLayout.draw(FrameLayout.java:352)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.View.draw(View.java:6743)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.widget.FrameLayout.draw(FrameLayout.java:352)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.View.draw(View.java:6743)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.widget.FrameLayout.draw(FrameLayout.java:352)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
10-19 03:21:53.984: ERROR/AndroidRuntime(460): at android.view
10-19 03:21:54.265: DEBUG/dalvikvm(460): GC_FOR_MALLOC freed 3579 objects / 314384 bytes in 218ms
10-19 03:21:54.335: WARN/ActivityManager(59): Force finishing activity com.muo.Livegroups/.Main
10-19 03:21:54.984: WARN/ActivityManager(59): Activity pause timeout for HistoryRecord{450548b0 com.muo.Livegroups/.Main}
10-19 03:21:57.244: INFO/Process(460): Sending signal. PID: 460 SIG: 9
10-19 03:21:57.334: INFO/ActivityManager(59): Process com.muo.Livegroups (pid 460) has died.
10-19 03:21:57.364: INFO/WindowManager(59): WIN DEATH: Window{45054b98 com.muo.Livegroups/com.muo.Livegroups.Main paused=false}
10-19 03:21:57.414: WARN/InputManagerService(59): Got RemoteException sending setActive(false) notification to pid 460 uid 10036
10-19 03:22:04.183: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol
10-19 03:22:06.441: WARN/ActivityManager(59): Activity destroy timeout for HistoryRecord{450548b0 com.muo.Livegroups/.Main}
I tried to use logcat and got the above information.
Can anybody help me to find the solution I get the error only when I go to different activity on 3rd time. First 2 times it works fine.
A: Your UI is too complicated, and you are running out of stack space when trying to render it. Use Hierarchy View and try to reduce the number of layers between the root View of your activity and the farthest leaves.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: String and character sequence error (force close) Android I am facing a problem in solving this issue.
I have 30 smiley images. In a grid view I display all the 30 images. So when I select the image based on the position of the image, the corresponding special character will be displayed from SQLite DB. Before I send message to service it is like "hi :)". What I need is to replace the ":)" with the corresponding smiley image in the local folder of my project (eg. R.drawable.facea.png). I am able to fetch the data and replace ":)" with "aaaaa"(example). But when I try to replace the ":)" with Char Sequence (Image), I get 'force close error'. Where am I going wrong?
I have a function to draw image and I get image as in Character Sequence. How can I use the value in this function globally. I also tried to create a global variable and use the CS value globally. But I still get 'force close error.
A: You need to use a span (specifically an ImageSpan) to be able to embed bitmap in a string. I have written about this on my blog which also covers some common pitfalls.
If you still cannot get it to work I would suggest posting the precise details of what is going wrong: i.e. your code, and the stacktrace that is getting dumped to logcat.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: write into csv file in php I have to create and write into a csv file. Now I tried with the following code:
header('Content-type: application/octet-stream');
header('Content-disposition: attachment; filename="data.csv"');
$data = array (
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"');
$fp = fopen('php://output', 'w+');
foreach($data as $line){
$val = explode(",",$line);
fputcsv($fp, $val);
}
fclose($fp);
It gives me my source file code also in the csv file? How can I solve this?
A: Wrap it in <?php and ?> tags.
A: Change the first header to header('Content-type: text/csv');
A: header() needs to come after the array and fopen
try this:
$data = array (
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"');
$fp = fopen('php://output', 'w+');
header('Content-type: application/octet-stream');
header('Content-disposition: attachment; filename="data.csv"');
foreach($data as $line){
$val = explode(",",$line);
fputcsv($fp, $val);
}
fclose($fp);
A: Try this:
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$data = array (
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"');
$fp = fopen('php://output','w');
foreach ($data as $line) {
fputcsv($fp, array_map('utf8_decode',array_values($line)), ',', '"');
}
fclose($fp);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Trouble with ImageView gravity on Java, Android I have this code:
<LinearLayout
android:layout_weight="0.5"
android:layout_width="0px"
android:id="@+id/linearLayout2"
android:orientation="vertical"
android:layout_height="fill_parent">
<LinearLayout
android:layout_weight="0.45"
android:layout_width="fill_parent"
android:id="@+id/linearLayoutMainLogo"
android:orientation="horizontal"
android:gravity="center"
android:layout_height="0px">
<ImageView
android:src="@drawable/logo"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:id="@+id/imageViewLogo"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
I need to set ImageView in center of LinearLayout by horizontal and by vertical simultaneously, but my code doesn't work. Where did I do mistake? Thank you
A: This is wrong i think:
android:layout_width="0px"
android:layout_height="0px"
Just correct with this:
<LinearLayout
android:layout_width="fill_parent"
android:id="@+id/linearLayout2"
android:orientation="vertical"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_weight="0.45"
android:layout_width="fill_parent"
android:id="@+id/linearLayoutMainLogo"
android:orientation="horizontal"
android:gravity="center"
android:layout_height="wrap_content">
<ImageView
android:src="@drawable/icon"
android:gravity="center"
android:layout_width="wrap_content"
android:id="@+id/imageViewLogo"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using the latest (r13) version of Android SDK Manager on win7 64 bit fails to retrieve repository.xml So I've got a brand new PC with win7 64 bit on it. I'm trying to get up and running with android SDK and eclipse. I've done this before on other win7 32 bit machines and never had issues. But now on this new machine, I have installed JDK 1.7.0 (64 bit), I have installed eclipse indigo 64 bit, and I've installed r13 of the sdk from here.
http://developer.android.com/sdk/index.html
But every time I try to launch the sdk manager (yes, I did get it installed with the "back" and "next" trick to make sure it found java) it fails to download the repository.xml file. The error I get 4 times is:
Failed to fetch URL http://dl-ssl.google.com/android/repository/repository.xml, reason: Invalid argument: connect
Note that I did shut off mcafee firewall so I don't think that's the issue. I also tried the tricks mentioned many many places about trying with and without https://... I have a direct connection, so I don't believe I need a proxy at all. And I've verified that URL can load the xml into chrome.
So I'm totally out of ideas now!!! Please help!
A: I executed C:\android-sdk-windows\toolandroid.bat to get the repository.XML, which opened the Android SDK Manager and downloaded the list of things to install. Then I clicked "Accept All" for the agreements.
The first time I tried to install, it looked like it did, but didn't. (Each item said "null" as it attempted to install.) After I put the proxy settings into the SDK manager (Tools > Options), each of the packages (68!) downloaded. (I copied the proxy info from IE Internet Options > Connections > LAN Settings.)
HTC and MOTODEV request logins when you attempt to install their packages, but I haven't created an account, and so just skipped them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CommportIdentifier in android We are trying to establish an flow Control from android device to Bluetooth Thermal Printer for that we need to understand the xon and xoff signal sent by printer. We are stuck at getportIdentifier("COM1") its giving exception . Iguess the com1 for bluetooth device is uuid but its not helping. Any help so that we could trace the port for android device.
Regards,
Sebs
A: You are using the JavaComm interface: this does not exist on Android at all, so you will not be able to use that particular semantics. If this is a Bluetooth serial device you will need to specify the device's Bluetooth MAC address and use the RFCOMM UUID, as shown here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MySQL for Qt on Mac I have wasted around 6 hours trying to get MySQL working with Qt following all sorts of instructions from the web. I want to cut my wrist off now!
Does anyone have a simple and a verbose explanation of how to install QMYSQL driver into Qt?
I have Mac 10.6 and I am a beginner n00b.
Your help will be appreciated from the bottom of my heart!
Sana.
EDIT:
I get the following files when I do the grep, so among these just for kicks I copied libqsqlmysql.dylib into all of the folders, but still I don't get to compile... I get an error saying that QSqlDatabase: QMYSQL driver not loaded
/Library/Application Support/DivX/QtPlugins/sqldrivers/libqsqlite.dylib
/Users/pfn368/QtSDK/Assistant.app/Contents/PlugIns/sqldrivers/libqsqlite.dylib
/Users/pfn368/QtSDK/Designer.app/Contents/PlugIns/sqldrivers/libqsqlite.dylib
/Users/pfn368/QtSDK/Desktop/Qt/4.8.0/gcc/plugins/sqldrivers/libqsqlite.dylib
/Users/pfn368/QtSDK/Desktop/Qt/4.8.0/gcc/plugins/sqldrivers/libqsqlite_debug.dylib
/Users/pfn368/QtSDK/Desktop/Qt/474/gcc/plugins/sqldrivers/libqsqlite.dylib
/Users/pfn368/QtSDK/Desktop/Qt/474/gcc/plugins/sqldrivers/libqsqlite_debug.dylib
/Users/pfn368/QtSDK/Madde/sysroots/harmattan-arm-sysroot/usr/lib/qt4/plugins/sqldrivers/libqsqlite.so
/Users/pfn368/QtSDK/Madde/sysroots/harmattan-nokia-arm-sysroot/usr/lib/qt4/plugins/sqldrivers/libqsqlite.so
/Users/pfn368/QtSDK/Maemo/4.6.2/sysroots/fremantle-arm-sysroot-20.2010.36-2-slim/usr/lib/qt4/plugins/sqldrivers/libqsqlite.so
/Users/pfn368/QtSDK/Qt Creator.app/Contents/MacOS/qmlpuppet.app/Contents/PlugIns/sqldrivers/libqsqlite.dylib
/Users/pfn368/QtSDK/Qt Creator.app/Contents/PlugIns/sqldrivers/libqsqlite.dylib
/Users/pfn368/QtSDK/QtSources/4.8.0/plugins/sqldrivers/libqsqlite.dylib
/Users/pfn368/QtSDK/QtSources/4.8.0/plugins/sqldrivers/libqsqlite_debug.dylib
/Users/pfn368/QtSDK/Simulator/Application/simulator.app/Contents/PlugIns/sqldrivers/libqsqlite.dylib
/Users/pfn368/QtSDK/Simulator/Qt/gcc/plugins/sqldrivers/libqsqlite.dylib
/Users/pfn368/QtSDK/Simulator/Qt/gcc/plugins/sqldrivers/libqsqlite_debug.dylib
This is my .pro file
QT += sql core gui\
network
TARGET = mini-stock-exchange
TEMPLATE = app
SOURCES += ./src/main.cpp\
./src/mainwindow.cpp
HEADERS += ./header/mainwindow.h
FORMS += ./ui/mainwindow.ui
My includes
#include "./header/mainwindow.h"
#include "ui_mainwindow.h"
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QFile>
#include <QtSql/QSqlError>
#include <qsqldatabase.h>
#include <QtCore>
#include <QtSql>
Code to call the database
QSqlDatabase defaultDB = QSqlDatabase::addDatabase("QMYSQL3");
if ( !defaultDB.isValid() ) {
qWarning( "Failed to connect to the database driver" );
}
defaultDB.setDatabaseName( "nicu" );
defaultDB.setUserName( "root" );
defaultDB.setPassword( "root" );
defaultDB.setHostName( "http://localhost:8889" );
A: First download the Qt SDK sources and a version of the mysql server sources, extract them both.
Create Symlinks to MySQL's lib files:
sudo ln -s /Users/simon/Downloads/mysql-5.6.11-osx10.7-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.dylib
sudo ln -s /Users/simon/Downloads/mysql-5.6.11-osx10.7-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient_r.dylib
sudo ln -s /Users/simon/Downloads/mysql-5.6.11-osx10.7-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
sudo ln -s /Users/simon/Downloads/mysql-5.6.11-osx10.7-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient_r.18.dylib
After that cd to your extracted Qt SDK into the folder /Users/simon/Downloads/qt-everywhere-opensource-src-4.8.4/src/plugins/sqldrivers/mysql
Build the Libraries:
qmake -spec macx-g++ -o Makefile "INCLUDEPATH+=/Users/simon/Downloads/mysql-5.6.11-osx10.7-x86_64/include" "LIBS+=-L/usr/lib -lmysqlclient_r" mysql.pro
make
mv libqsqlmysql_debug.dylib libqsqlmysql.dylib
cp -R libqsqlmysql.dylib /Developer/Applications/Qt/plugins/sqldrivers/
After that you should be able to use the QMYSQL plugin. Check if the library was loaded correctly with this line of code (put it in some constructor so that you'll the the output right after starting the app):
qDebug() << QCoreApplication::libraryPaths();
qDebug() << QSqlDatabase::drivers();
For e.g. my output looks like this now:
("/Developer/Applications/Qt/plugins", "/Users/simon/Coding/qt4c/build-SQLtable-Desktop-Debug/SQLtable.app/Contents/MacOS")
("QSQLITE", "QMYSQL3", "QMYSQL", "QODBC3", "QODBC", "QPSQL7", "QPSQL")
A: The Qt 4 packages from Mac Homebrew have an option to install mysql-drivers as a Qt Plugin for default (it's not a default option, that's why you are missing this).
Download and install Mac OS X Homebrew software as described here: http://brew.sh.
After installing homebrew, remove the previously Qt4 installation.
If you have installed it using brew just type on the terminal:
$ brew remove qt4
To install it with mysql support run:
$ brew install qt4 --with-mysql
And everytime you need to install a package with some options in brew but you don't know the supported options just type:
$ brew options FORMULA_NAME
And it will show all the build options available for the given formula.
A: Sana, I'm going to try save that hand, alrighty.
First you need the Qt everywhere opensource package from the internets. I've got no idea what version of Qt you're running, but you need the same version as your core install.
Second, you get into the source package and go through the plugins until you find the sql drivers and the mysql plugin. At this stage make sure you know what path your mysql libs and includes are on, as you'll need them.
Third, modify the .pro for the mysql plugin and add your MySql include path to INCLUDEPATH+= and the libs to....LIBS+=
Fourth, run qmake on the .pro to generate a Makefile, then make the make file and you'll have some pretty little .dylib files looking at you with eyes full of joy.
Fifth, the fun part, you need to find where the other plugins are, and this varies system by system. Quickest way to find them is in Terminal type 'sudo find / | grep libqsqlite' and it'll give you the location of that, and that's your Qt sqldrivers plugin directory. Copy the dylib you just built into there.
And that should do it. It's worked for me on quite a few builds and rebuilds.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Is there an interactive way to learn Vim? Years ago I was looking for a way to learn Vim that didn't involve a wall of text, or scrolling through vimtutor without knowing the commands to do so. I wondered if anything else existed for such a purpose.
A: http://kikuchiyos-vim-game.herokuapp.com
Spiked this mid 2011, around time vim adventures was made, but never went nearly as far as vim adventures did. Never got much play, but still a free alternative for anyone interested in getting over the vim learning curve - basic movement and changing modes.
A: haven't used it, but it looks close to what you're asking for
http://www.openvim.com/tutorial.html
A: Interactive tutorial:
*
*http://www.openvim.com/
HJKL-learning game:
*
*http://www.vim.org/scripts/script.php?script_id=3409
Screencasts:
*
*http://derekwyatt.org/vim/tutorials/index.html
*http://vimcasts.org
A: For the very beginner http://vimsnake.com is also a nice one.
It will interestingly improves the muscle memory for keys h,j,k,l, esc and i
Now after getting prepared for those keys, we can move to http://www.vimgenius.com/ for learning. It is just similar and alternative for shortcutfoo.com and more it is vim specific.
A: To answer your question: vimtutor is the good way to interactively learn vim. If you read through it, it gives you all the necessary commands to go through it, and you actually learn to use vim.
If that's too much effort, I really doubt vim is for you.
A: I programmed a game just for this purpose! It's an online game where you move the cursor using vim commands and motions. Check it out on http://vim-adventures.com.
The first couple of levels teach hjkl and word navigation. The rest is planned to cost money.
A: Old question, but for others looking for something similar that has not been mentioned: https://www.shortcutfoo.com/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "93"
}
|
Q: Converting MVC2 aspx project to use MVC3 Razor view engine I need advice.
We have a MVC2 aspx project that we would want to (nice to do, not need to do) upgrade so that we can use the Razor view engine instead of the aspx/webforms engine.
In total there is about 200aspx files that would need to be converted.
What`s your opinion of how much time it would take? And is it worth doing it?
A: If you do this manually, it takes long time to do this. But you can use MVC 3 Project Upgrade Tool - this will be a good choice
A: Telerik has conversion tool. It works quite well on simple cases, just does not help with converting master pages to layouts. I've used it to convert my project (several hundred views, up to ten master pages) - it took some time to figure out how to map master pages to layouts, but overall went quite well.
Is it worth it?
Well, it depends, mostly on how much is your project covered with tests. Razor syntax is much cleaner, I like layouts better than master pages. I always think, that migrating to new version has one serious advantage - it is a reason to review all your code, refactor things and so on, another serious advantage is to work with current technologies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get the given date string format(pattern) in java? I want to get the format of a given date string.
Example: I have a string like 2011-09-27T07:04:21.97-05:00 and the date format of this string is yyyy-MM-dd'T'HH:mm:ss.SSS.
Here I want to find out this date format when I pass string(2011-09-27T07:04:21.97-05:00) to a method which will return the format(yyyy-MM-dd'T'HH:mm:ss.SSS), then later I will format my given date string according to my requirement(like yy-mm--dd or mm/dd/yyyy).
Can any one tell me how can I get it achieved?
A: you can do like this way, I don't know good way or not but try this
first create the SimpleDateFormat object
SimpleDateFormt sdf = new SimpleDateFormat("yyyy-MM-dd 'T' HH:mm:ss.SSS");
now when check the date if this will parse in this format then change as per your format
try{
Date date = sdf.parse(yourdate);
sdf.applyPattern("yy-mm--dd or mm/dd/yyyy");
String dateformat = sdf.format(date);
}catch(Exception ex) { // here forgot the exact exception class Parse exception was used
// do something here
}
updated post:
Returning a date format from an unknown format of date string in java
How to convert String to Date without knowing the format?
Parse any date in Java
A: import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NewClass {
private static final String[] formats = {
"yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ssZ",
"yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd HH:mm:ss",
"MM/dd/yyyy HH:mm:ss", "MM/dd/yyyy'T'HH:mm:ss.SSS'Z'",
"MM/dd/yyyy'T'HH:mm:ss.SSSZ", "MM/dd/yyyy'T'HH:mm:ss.SSS",
"MM/dd/yyyy'T'HH:mm:ssZ", "MM/dd/yyyy'T'HH:mm:ss",
"yyyy:MM:dd HH:mm:ss", "yyyyMMdd", };
/*
* @param args
*/
public static void main(String[] args) {
String yyyyMMdd = "20110917";
parse(yyyyMMdd);
}
public static void parse(String d) {
if (d != null) {
for (String parse : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(parse);
try {
sdf.parse(d);
System.out.println("Printing the value of " + parse);
} catch (ParseException e) {
}
}
}
}
}
A: I think you should try to parse input string with some predefine patterns. The one that works is the one you need. Remember that some patterns are quite tricky.
01.12.12 is 01 December 2012 in Europe but 12 January 2012 in USA. It could be 12 December 2001 too.
A: If I understand you correctly, you want to parse arbitrary strings (that is, string of a format you don't know) as dates by using DateFormat.parse()? Then you have to deal with issues like how to handle 01-02-03 (2 Jan 2003? 1 Feb 2003? etc.)
You should know at least something about the expected format, like a choice of several predefined formats for your input.
A: Madhu's code is can workout, but some performance problem will arise because every failure case will raise the exception.
i think we need to find the reguler expression solution to find the pattern form the given date String.
you can find all most all reg expressions to date and time format in the following link
http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5&AspxAutoDetectCookieSupport=1
A: Here is a generic solution the determine the pattern without knowing the date pattern in advance and without calling the parse method of SimpleDateFormat for all formats. You can get any date pattern from date string value by using the regex.
package com.utility.utils.modelmapper.datetime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class DateParser {
private static final Map<String, String> DATE_FORMAT_REGEXPS = new HashMap<String, String>() {
{
put("^\\d{8}$", "yyyyMMdd");
put("^\\d{12}$", "yyyyMMddHHmm");
put("^\\d{8}\\s\\d{4}$", "yyyyMMdd HHmm");
put("^\\d{14}$", "yyyyMMddHHmmss");
put("^\\d{8}\\s\\d{6}$", "yyyyMMdd HHmmss");
put("^\\d{1,2}-\\d{1,2}-\\d{4}$", "dd-MM-yyyy");
put("^\\d{4}-\\d{1,2}-\\d{1,2}$", "yyyy-MM-dd");
put("^\\d{1,2}/\\d{1,2}/\\d{4}$", "MM/dd/yyyy");
put("^\\d{4}/\\d{1,2}/\\d{1,2}$", "yyyy/MM/dd");
put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}$", "dd MMM yyyy");
put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}$", "dd MMMM yyyy");
put("^\\d{1,2}-\\d{1,2}-\\d{4}\\s\\d{1,2}:\\d{2}$", "dd-MM-yyyy HH:mm");
put("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{2}$", "yyyy-MM-dd HH:mm");
put("^\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}:\\d{2}$", "MM/dd/yyyy HH:mm");
put("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{2}$", "yyyy/MM/dd HH:mm");
put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}\\s\\d{1,2}:\\d{2}$", "dd MMM yyyy HH:mm");
put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}\\s\\d{1,2}:\\d{2}$", "dd MMMM yyyy HH:mm");
put("^\\d{1,2}-\\d{1,2}-\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd-MM-yyyy HH:mm:ss");
put("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{2}:\\d{2}$", "yyyy-MM-dd HH:mm:ss");
put("^\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "MM/dd/yyyy HH:mm:ss");
put("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{2}:\\d{2}$", "yyyy/MM/dd HH:mm:ss");
put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd MMM yyyy HH:mm:ss");
put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd MMMM yyyy HH:mm:ss");
put("^\\d{4}-\\d{1,2}-\\d{1,2}T\\d{1,2}:\\d{2}:\\d{2}\\.\\d{2}[-+]\\d{2}:\\d{2}$", "yyyy-MM-dd'T'HH:mm:ss.SSS");
}
};
/**
* To Determine the pattern by the string date value
*
* @param dateString
* @return The matching SimpleDateFormat pattern, or null if format is unknown.
*/
public static String determineDateFormat(String dateString) {
for (String regexp : DATE_FORMAT_REGEXPS.keySet()) {
if (dateString.matches(regexp) || dateString.toLowerCase().matches(regexp)) {
return DATE_FORMAT_REGEXPS.get(regexp);
}
}
return null;
}
public static void main(String[] args) {
parse("2011-09-27T07:04:21.97-05:00"); //here is your value
parse("20110917");
parse("01/02/2018");
parse("02-01-2018 06:07:59");
parse("02 January 2018");
}
public static void parse(String value) {
if (value != null) {
String format = determineDateFormat(value);
if (format != null) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
Date date = sdf.parse(value);
System.out.println(String.format("Format : %s | Value : %s | Parsed Date : %s", value, date, format));
} catch (ParseException e) {
// Failed the execution
}
}
}
}
}
Console output of the class:
Format : 2011-09-27T07:04:21.97-05:00 | Value : Tue Sep 27 07:04:21 LINT 2011 | Parsed Date : yyyy-MM-dd'T'HH:mm:ss.SSS
Format : 20110917 | Value : Sat Sep 17 00:00:00 LINT 2011 | Parsed Date : yyyyMMdd
Format : 01/02/2018 | Value : Tue Jan 02 00:00:00 LINT 2018 | Parsed Date : MM/dd/yyyy
Format : 02-01-2018 06:07:59 | Value : Tue Jan 02 06:07:59 LINT 2018 | Parsed Date : dd-MM-yyyy HH:mm:ss
Format : 02 January 2018 | Value : Tue Jan 02 00:00:00 LINT 2018 | Parsed Date : dd MMMM yyyy
Maybe I missed some of the date-time patterns here but for that the correct regex pattern should be added in the map.
A: You will need to take the inital date string and covert it to a date object and pass that converted date object and format it to your required string.
A: You could try dateparser.
It can recognize any String automatically, and parse it into Date, Calendar, LocalDateTime, OffsetDateTime correctly and quickly(1us~1.5us).
It doesn't based on any natural language analyzer or SimpleDateFormat or regex.Pattern.
With it, you don't have to prepare any appropriate patterns like yyyy-MM-dd'T'HH:mm:ss'Z' or MM/dd/yyyy HH:mm:ss etc:
Date date = DateParserUtils.parseDate("2015-04-29T10:15:00.500+0000");
Calendar calendar = DateParserUtils.parseCalendar("2015-04-29T10:15:00.500Z");
LocalDateTime dateTime = DateParserUtils.parseDateTime("2015-04-29 10:15:00.500 +00:00");
And it has better performance than loop-try multiple SimpleDateFormat.
Please enjoy it.
A: java.time and its predefined formatters
We cannot do this for just any date-time format. There are thousands of them, we cannot know them all (someone will invent a new one tomorrow), and some look alike so much we can’t tell which we’ve got.
I suggest that for the majority of purposes you need to parse the string, but you don’t need to know a format pattern for doing so. In very many cases, including the example from your question, 2011-09-27T07:04:21.97-05:00, we don’t need to specify a pattern (your string matches DateTimeFormatter.ISO_OFFSET_DATE_TIME).
Since Java 8 came out in 2014 (and even if still using Java 6 or 7), use java.time, the modern Java date and time API, for your date and time work.
I am defining an array of formatters for the formats we want to cater for. Please substitute your own set.
private static final DateTimeFormatter[] formatters = {
DateTimeFormatter.ISO_OFFSET_DATE_TIME,
DateTimeFormatter.RFC_1123_DATE_TIME,
new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_LOCAL_DATE)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.toFormatter(),
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withLocale(Locale.US),
DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm")
.withZone(ZoneId.of("America/Los_Angeles"))
};
The following method tries the formatters in turn until one works:
private static OffsetDateTime parse(String dateTimeString) {
for (DateTimeFormatter formatter : formatters) {
try {
return ZonedDateTime.parse(dateTimeString, formatter)
.toOffsetDateTime();
} catch (DateTimeParseException dtpe) {
// Ignore, try next formatter
}
}
throw new IllegalArgumentException("String " + dateTimeString + " could not be parsed");
}
Let’s try it out with some different strings:
String[] dateTimeStrings = {
"2011-09-27T07:04:21.97-05:00",
"20110917",
"2012-07-04",
"12/27/2014 23:45",
"Mon, 12 Nov 2018 01:32:10 GMT",
"July 29, 2015 at 10:19:36 AM EDT",
};
for (String dts : dateTimeStrings) {
try {
System.out.format("%32s -> %s%n", dts, parse(dts));
} catch (IllegalArgumentException iae) {
System.out.format("%32s -> %s%n", dts, iae);
}
}
Output is:
2011-09-27T07:04:21.97-05:00 -> 2011-09-27T07:04:21.970-05:00
20110917 -> java.lang.IllegalArgumentException: String 20110917 could not be parsed
2012-07-04 -> 2012-07-04T00:00Z
12/27/2014 23:45 -> 2014-12-27T23:45-08:00
Mon, 12 Nov 2018 01:32:10 GMT -> 2018-11-12T01:32:10Z
July 29, 2015 at 10:19:36 AM EDT -> 2015-07-29T10:19:36-04:00
Other options
Techniques for parsing dates and times in multiple formats include:
*
*Take a taste of the string to decide its format and use an appropriate formatter based on that. It’s best suited if you have just a few formats, though the answer by Vinit Solanki shows an elaborate version for quite many formats.
*Use optional parts in a format pattern string. For example [uuuu][uu] will parse either four digit or two digit year (2021 or just 21).
*Try several formatters in turn as shown in my code above. If you do need to know the pattern, use an array of patterns instead of an array of formatters.
*Requiring the supplier of the string to supply a format patterns string too. This is not always as simple as it may sound, though.
Beware of ambiguity. The classical example is the two formats MM-dd-yyyy and dd-MM-yyyy. If we get a string of 03-09-2020, there’s no way to tell whether it means March 9 or 3rd September. Even worse, 02-05-07 might be yy-MM-dd, dd-MM-yy, MM-dd-yy and even more possibilities. As a consequence, make sure you don’t include two (or more) formatters that may parse the same string into different results.
Links
*
*Oracle tutorial: Date Time explaining how to use java.time.
*A fine answer by Arvind Kumar Avinash showing the use of optional parts in the format pattern string for parsing different formats.
A: HH:mm:ss.SSS => ([0-2]{1,}[0-9]{1,})(:)([0-5]{1,}[0-9]{1,})(:)([0-5]{1,}[0-9]{1,})(.)([0-9]{1,3})
yyyy-mm-dd => ([0-9]{4})(-)([0-1]{1,}[0-9]{1,})(-)([0-3]{1,}[0-9]{1,})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
}
|
Q: how to display graphically layout in Eclipse? This error is create when I open graphically layout in eclipse? I make android apps..
java.lang.UnsupportedOperationException
Exception details are logged in Window > Show View > Error Log
A: You are probably using a Custom View that you created, or some error. Follow the instructions and check the Error Log.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how searchview work for listView in android? suppose i have listview content like this.
------------------------------------------------------
TextView TextView
--------------------------------------------------
TextView TextView
----------------------------------------------------
TextView TextView
-------------------------------------------------------
TextView TextView
----------------------------------------------------
so is it possible to search my search content on each component of listview using searchview in android.
for example if i type in searchview "bob". then it will check bob in all 4 textview and give a updated result to you....
A: Yes, it's possible, and it can be achieved using SearchView. Your Adapter should Implement Filterable and it's getFilter() method will have your filtering criteria.
I am using SearchView in ActionBar for showing this functionality.
My Activity -
public class MyActivity extends SherlockListActivity implements OnQueryTextListener {
private MyMessage myMessage; // list item, which is a model class in my case
private ListView mListView;
private MessageAdapter mAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.layout_containing_listView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//Create the search view
SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
mListView = getListView();
mListView.setTextFilterEnabled(true);
setupSearchView(searchView);
menu.add(0, 1, 1, null)
.setIcon(R.drawable.ic_search)
.setActionView(searchView)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return super.onCreateOptionsMenu(menu);
}
private void setupSearchView(SearchView mSearchView) {
mSearchView.setIconifiedByDefault(false);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setQueryHint("Search Sender");
}
@Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
} else {
mListView.setFilterText(newText);
}
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
My Adapter -
public class MessageAdapter extends BaseAdapter implements Filterable {
List<MyMessage> msgsList;
List<MyMessage> mOriginalValues;
List<String> mListItem; // any key of MyMessage Model Class
MyMessage message;
public MessageAdapter(List<MyMessage> msgList) {
super();
this.msgsList = msgList;
}
….
….
…
@Override
public Filter getFilter() {
/**
* A filter object which will
* filter message key
* */
Filter filter = new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,FilterResults results) {
msgsList = (List<MyMessage>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values. Only filtered values will be shown on the list
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation for publishing
List<MyMessage> FilteredArrList = new ArrayList<MyMessage>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<MyMessage>(msgsList); // saves the original data in mOriginalValues
}
if(mListItem == null){
mListItem = new ArrayList<String>();
for(MyMessage message : mOriginalValues){
mListItem.add(message.getMessage());
}
}
/**
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
**/
if (constraint == null || constraint.length() == 0) {
/* CONTRACT FOR IMPLEMENTING FILTER : set the Original values to result which will be returned for publishing */
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
/* Do the filtering */
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mListItem.size(); i++) {
String data = mListItem.get(i);
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(mOriginalValues.get(i));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
For convenience, my model class MyMessage -
public class MyMessage implements Parcelable{
private String messageKey = "";
private String key = "";
private String key2 = "";
//getters and setters
}
A: Yes it's possible.
You need to do something like this:
public class SearchViewFilterMode extends Activity implements SearchView.OnQueryTextListener {
private static final String TAG = "SearchViewFilterMode";
private SearchView mSearchView;
private ListView mListView;
private ArrayAdapter<String> mAdapter;
private final String[] mStrings = Cheeses.sCheeseStrings;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.searchview_filter);
mSearchView = (SearchView) findViewById(R.id.search_view);
mListView = (ListView) findViewById(R.id.list_view);
mListView.setAdapter(mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
mStrings));
mListView.setTextFilterEnabled(true);
setupSearchView();
}
@TargetApi(11)
private void setupSearchView() {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setQueryHint(getString(R.string.cheese_hunt_hint));
}
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
} else {
mListView.setFilterText(newText.toString());
}
return true;
}
public boolean onQueryTextSubmit(String query) {
return false;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Interrupt repeater to add advertisement and continue with the repeater Between the comments and blog entries i want to add some stuff to earn some money :D
I use
<asp:repeater>
</asp:repeater>
To write out all the blog entries.
Is it possible in some way to interrupts the repeater to be able to write out the code for the ad-banner?
For example run 3 entries, then add some code for the advertisement and continue with another 3 rows of blog entries?
And so on...
A: It's not possible out-of-the-box, but there is a quite simple workaround.
Add a Panel in the end of your repeater ItemTemplate, put the ad inside it, and set it's Visible attribute to be "<%# Container.DataItemIndex == 3 %>" or whatever,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7579235",
"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.