Daily Archives

Articles indexed Thursday September 6 2012

Page 13/19 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • When do instance variables get initialized and values assigned?

    - by AKh
    When doees the instance variable get initialized? Is it after the constructor block is done or before it? Consider this example: public abstract class Parent { public Parent(){ System.out.println("Parent Constructor"); init(); } public void init(){ System.out.println("parent Init()"); } } public class Child extends Parent { private Integer attribute1; private Integer attribute2 = null; public Child(){ super(); System.out.println("Child Constructor"); } public void init(){ System.out.println("Child init()"); super.init(); attribute1 = new Integer(100); attribute2 = new Integer(200); } public void print(){ System.out.println("attribute 1 : " +attribute1); System.out.println("attribute 2 : " +attribute2); } } public class Tester { public static void main(String[] args) { Parent c = new Child(); ((Child)c).print(); } } OUTPUT: Parent Constructor Child init() parent Init() Child Constructor attribute 1 : 100 attribute 2 : null When the memory for the atribute 1 & 2 are allocated in the heap ? Curious to know why is attribute 2 is NULL ? Are there any design flaws?

    Read the article

  • PHP Flatten Array with multiple leaf nodes

    - by tafaju
    What is the best way to flatten an array with multiple leaf nodes so that each full path to leaf is a distinct return? array("Object"=>array("Properties"=>array(1, 2))); to yield Object.Properties.1 Object.Properties.2 I'm able to flatten to Object.Properties.1 but 2 does not get processed with recursive function: function flattenArray($prefix, $array) { $result = array(); foreach ($array as $key => $value) { if (is_array($value)) $result = array_merge($result, flattenArray($prefix . $key . '.', $value)); else $result[$prefix . $key] = $value; } return $result; } I presume top down will not work when anticipating multiple leaf nodes, so either need some type of bottom up processing or a way to copy array for each leaf and process (althought that seems completely inefficient)

    Read the article

  • Jquery remove class from image

    - by user1269625
    Hey ya'll I have these 3 images thumbnails here... <div class="wpcart_gallery" style="text-align:center; padding-top:5px;"> <a class="thickbox cboxElement" title="DSC_0118" href="http://www.taranmarlowjewelry.com/wp-content/uploads/2012/07/DSC_0118.jpg" rel="Teardrop Druzy Amethyst Ring" rev="http://www.taranmarlowjewelry.com/wp-content/uploads/2012/07/DSC_0118.jpg"> <img class="attachment-gold-thumbnails colorbox-736" width="50" height="50" title="DSC_0118" alt="DSC_0118" src="http://www.taranmarlowjewelry.com/wp-content/uploads/2012/07/DSC_0118-50x50.jpg"> </a> <a class="thickbox cboxElement" title="P7230376" href="http://www.taranmarlowjewelry.com/wp-content/uploads/2012/07/P7230376.jpg" rel="Teardrop Druzy Amethyst Ring" rev="http://www.taranmarlowjewelry.com/wp-content/uploads/2012/07/P7230376.jpg"> <img class="attachment-gold-thumbnails colorbox-736" width="50" height="50" title="P7230376" alt="P7230376" src="http://www.taranmarlowjewelry.com/wp-content/uploads/2012/07/P7230376-50x50.jpg"> </a> <a class="thickbox cboxElement" title="P7230378" href="http://www.taranmarlowjewelry.com/wp-content/uploads/2012/07/P7230378.jpg" rel="Teardrop Druzy Amethyst Ring" rev="http://www.taranmarlowjewelry.com/wp-content/uploads/2012/07/P7230378.jpg"> <img class="attachment-gold-thumbnails colorbox-736" width="50" height="50" title="P7230378" alt="P7230378" src="http://www.taranmarlowjewelry.com/wp-content/uploads/2012/07/P7230378-50x50.jpg"> </a> </div> What I am trying to do is come up with a jquery code that would remove the cboxElement from the first image and if I click on one of the images to remove cboxElement and place cboxElement to the other images... I also have this big image and when you click on one of the thumbnails, the image is replaced by the thumbnail and thats really the thumbnail I want to exclude...Could I possible just say if one of the 3 images src = this one image = src remove the class from this thumbnail? Which way would be better? I am very new at jquery :( I hope this makes sense. Here is the code for the big image... <a class="preview_link cboxElement" style="text-decoration:none;" href="http://www.taranmarlowjewelry.com/wp-content/uploads/2012/07/DSC_0118.jpg" rel="Teardrop Druzy Amethyst Ring"> <img id="product_image_736" class="product_image colorbox-736" width="400" src="http://www.taranmarlowjewelry.com/wp-content/uploads/2012/07/DSC_0118.jpg" title="Teardrop Druzy Amethyst Ring" alt="Teardrop Druzy Amethyst Ring"> <br> <div style="text-align:center; color:#F39B91;">Click To Enlarge</div> </a> Any help or a point in the right direction would be awesome!!

    Read the article

  • Is it thread safe to read a form controls value (but not change it) without using Invoke/BeginInvoke from another thread

    - by goku_da_master
    I know you can read a gui control from a worker thread without using Invoke/BeginInvoke because my app is doing it now. The cross thread exception error is not being thrown and my System.Timers.Timer thread is able to read gui control values just fine (unlike this guy: can a worker thread read a control in the GUI?) Question 1: Given the cardinal rule of threads, should I be using Invoke/BeginInvoke to read form control values? And does this make it more thread-safe? The background to this question stems from a problem my app is having. It seems to randomly corrupt form controls another thread is referencing. (see question 2) Question 2: I have a second thread that needs to update form control values so I Invoke/BeginInvoke to update those values. Well this same thread needs a reference to those controls so it can update them. It holds a list of these controls (say DataGridViewRow objects). Sometimes (not always), the DataGridViewRow reference gets "corrupt". What I mean by corrupt, is the reference is still valid, but some of the DataGridViewRow properties are null (ex: row.Cells). Is this caused by question 1 or can you give me any tips on why this might be happening? Here's some code (the last line has the problem): public partial class MyForm : Form { void Timer_Elapsed(object sender) { // we're on a new thread (this function gets called every few seconds) UpdateUiHelper updateUiHelper = new UpdateUiHelper(this); foreach (DataGridViewRow row in dataGridView1.Rows) { object[] values = GetValuesFromDb(); updateUiHelper.UpdateRowValues(row, values[0]); } // .. do other work here updateUiHelper.UpdateUi(); } } public class UpdateUiHelper { private readonly Form _form; private Dictionary<DataGridViewRow, object> _rows; private delegate void RowDelegate(DataGridViewRow row); private readonly object _lockObject = new object(); public UpdateUiHelper(Form form) { _form = form; _rows = new Dictionary<DataGridViewRow, object>(); } public void UpdateRowValues(DataGridViewRow row, object value) { if (_rows.ContainsKey(row)) _rows[row] = value; else { lock (_lockObject) { _rows.Add(row, value); } } } public void UpdateUi() { foreach (DataGridViewRow row in _rows.Keys) { SetRowValueThreadSafe(row); } } private void SetRowValueThreadSafe(DataGridViewRow row) { if (_form.InvokeRequired) { _form.Invoke(new RowDelegate(SetRowValueThreadSafe), new object[] { row }); return; } // now we're on the UI thread object newValue = _rows[row]; row.Cells[0].Value = newValue; // randomly errors here with NullReferenceException, but row is never null! }

    Read the article

  • Recursive search Linq to xml

    - by Raj Esh
    this is my sample xml. <Messages> <Conversation> <id>Z100</id> <ReplyToId></ReplyToId> <Message>Topic</Message> </Conversation> <Conversation> <id>A100</id> <ReplyToId></ReplyToId> <Message>This is a test</Message> </Conversation> <Conversation> <id>M100</id> <ReplyToId>A100</ReplyToId> <Message>What kind of test</Message> </Conversation> <Conversation> <id>A200</id> <ReplyToId>M100</ReplyToId> <Message>Stage 1</Message> </Conversation> <Conversation> <id>M200</id> <ReplyToId>A200</ReplyToId> <Message>Test result for </Message> </Conversation> </Messages> How to get the conversation list based on id using linq in C#. Say for example, If i want to get the conversation for id "A100" which has a link to other conversation based on ReplyToid.

    Read the article

  • Sql Server as logging, best connection practise

    - by ozz
    I'm using SqlServer as logging. Yes this is wrong decision, there are better dbs for this requirement. But I have no other option for now. Logging interval is 3 logs per second. So I've static Logger class and it has static Log method. Using "Open Connection" as static member is better for performance. But what is the best implemantation of it? This is not that I know. public static class OzzLogger { static SqlConnection Con; static OzzLogger() { Con=ne SqlConnection(....); Con.Open(); } public static void Log(....) { Con.ExecuteSql(......); } } UPDATE I asked because of my old information. People say "connection pooling performance is enough". If there is no objection I'm closing the issue :)

    Read the article

  • Python script is exiting with no output and I have no idea why

    - by Adam Tuttle
    I'm attempting to debug a Subversion post-commit hook that calls some python scripts. What I've been able to determine so far is that when I run post-commit.bat manually (I've created a wrapper for it to make it easier) everything succeeds, but when SVN runs it one particular step doesn't work. We're using CollabNet SVNServe, which I know from the documentation removes all environment variables. This had caused some problems earlier, but shouldn't be an issue now. Before Subversion calls a hook script, it removes all variables - including $PATH on Unix, and %PATH% on Windows - from the environment. Therefore, your script can only run another program if you spell out that program's absolute name. The relevant portion of post-commit.bat is: echo -------------------------- >> c:\svn-repos\company\hooks\svn2ftp.out.log set SITENAME=staging set SVNPATH=branches/staging/wwwroot/ "C:\Python3\python.exe" C:\svn-repos\company\hooks\svn2ftp.py ^ --svnUser="svnusername" ^ --svnPass="svnpassword" ^ --ftp-user=ftpuser ^ --ftp-password=ftppassword ^ --ftp-remote-dir=/ ^ --access-url=svn://10.0.100.6/company ^ --status-file="C:\svn-repos\company\hooks\svn2ftp-%SITENAME%.dat" ^ --project-directory=%SVNPATH% "staging.company.com" %1 %2 >> c:\svn-repos\company\hooks\svn2ftp.out.log echo -------------------------- >> c:\svn-repos\company\hooks\svn2ftp.out.log When I run post-commit.bat manually, for example: post-commit c:\svn-repos\company 12345, I see output like the following in svn2ftp.out.log: -------------------------- args1: c:\svn-repos\company args0: staging.company.com abspath: c:\svn-repos\company project_dir: branches/staging/wwwroot/ local_repos_path: c:\svn-repos\company getting youngest revision... done, up-to-date -------------------------- However, when I commit something to the repo and it runs automatically, the output is: -------------------------- -------------------------- svn2ftp.py is a bit long, so I apologize but here goes. I'll have some notes/disclaimers about its contents below it. #!/usr/bin/env python """Usage: svn2ftp.py [OPTION...] FTP-HOST REPOS-PATH Upload to FTP-HOST changes committed to the Subversion repository at REPOS-PATH. Uses svn diff --summarize to only propagate the changed files Options: -?, --help Show this help message. -u, --ftp-user=USER The username for the FTP server. Default: 'anonymous' -p, --ftp-password=P The password for the FTP server. Default: '@' -P, --ftp-port=X Port number for the FTP server. Default: 21 -r, --ftp-remote-dir=DIR The remote directory that is expected to resemble the repository project directory -a, --access-url=URL This is the URL that should be used when trying to SVN export files so that they can be uploaded to the FTP server -s, --status-file=PATH Required. This script needs to store the last successful revision that was transferred to the server. PATH is the location of this file. -d, --project-directory=DIR If the project you are interested in sending to the FTP server is not under the root of the repository (/), set this parameter. Example: -d 'project1/trunk/' This should NOT start with a '/'. 2008.5.2 CKS Fixed possible Windows-related bug with tempfile, where the script didn't have permission to write to the tempfile. Replaced this with a open()-created file created in the CWD. 2008.5.13 CKS Added error logging. Added exception for file-not-found errors when deleting files. 2008.5.14 CKS Change file open to 'rb' mode, to prevent Python's universal newline support from stripping CR characters, causing later comparisons between FTP and SVN to report changes. """ try: import sys, os import logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='svn2ftp.debug.log', filemode='a' ) console = logging.StreamHandler() console.setLevel(logging.ERROR) logging.getLogger('').addHandler(console) import getopt, tempfile, smtplib, traceback, subprocess from io import StringIO import pysvn import ftplib import inspect except Exception as e: logging.error(e) #capture the location of the error frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace) print(stack_trace) #end capture sys.exit(1) #defaults host = "" user = "anonymous" password = "@" port = 21 repo_path = "" local_repos_path = "" status_file = "" project_directory = "" remote_base_directory = "" toAddrs = "[email protected]" youngest_revision = "" def email(toAddrs, message, subject, fromAddr='[email protected]'): headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (fromAddr, toAddrs, subject) message = headers + message logging.info('sending email to %s...' % toAddrs) server = smtplib.SMTP('smtp.company.com') server.set_debuglevel(1) server.sendmail(fromAddr, toAddrs, message) server.quit() logging.info('email sent') def captureErrorMessage(e): sout = StringIO() traceback.print_exc(file=sout) errorMessage = '\n'+('*'*80)+('\n%s'%e)+('\n%s\n'%sout.getvalue())+('*'*80) return errorMessage def usage_and_exit(errmsg): """Print a usage message, plus an ERRMSG (if provided), then exit. If ERRMSG is provided, the usage message is printed to stderr and the script exits with a non-zero error code. Otherwise, the usage message goes to stdout, and the script exits with a zero errorcode.""" if errmsg is None: stream = sys.stdout else: stream = sys.stderr print(__doc__, file=stream) if errmsg: print("\nError: %s" % (errmsg), file=stream) sys.exit(2) sys.exit(0) def read_args(): global host global user global password global port global repo_path global local_repos_path global status_file global project_directory global remote_base_directory global youngest_revision try: opts, args = getopt.gnu_getopt(sys.argv[1:], "?u:p:P:r:a:s:d:SU:SP:", ["help", "ftp-user=", "ftp-password=", "ftp-port=", "ftp-remote-dir=", "access-url=", "status-file=", "project-directory=", "svnUser=", "svnPass=" ]) except getopt.GetoptError as msg: usage_and_exit(msg) for opt, arg in opts: if opt in ("-?", "--help"): usage_and_exit() elif opt in ("-u", "--ftp-user"): user = arg elif opt in ("-p", "--ftp-password"): password = arg elif opt in ("-SU", "--svnUser"): svnUser = arg elif opt in ("-SP", "--svnPass"): svnPass = arg elif opt in ("-P", "--ftp-port"): try: port = int(arg) except ValueError as msg: usage_and_exit("Invalid value '%s' for --ftp-port." % (arg)) if port < 1 or port > 65535: usage_and_exit("Value for --ftp-port must be a positive integer less than 65536.") elif opt in ("-r", "--ftp-remote-dir"): remote_base_directory = arg elif opt in ("-a", "--access-url"): repo_path = arg elif opt in ("-s", "--status-file"): status_file = os.path.abspath(arg) elif opt in ("-d", "--project-directory"): project_directory = arg if len(args) != 3: print(str(args)) usage_and_exit("host and/or local_repos_path not specified (" + len(args) + ")") host = args[0] print("args1: " + args[1]) print("args0: " + args[0]) print("abspath: " + os.path.abspath(args[1])) local_repos_path = os.path.abspath(args[1]) print('project_dir:',project_directory) youngest_revision = int(args[2]) if status_file == "" : usage_and_exit("No status file specified") def main(): global host global user global password global port global repo_path global local_repos_path global status_file global project_directory global remote_base_directory global youngest_revision read_args() #repository,fs_ptr #get youngest revision print("local_repos_path: " + local_repos_path) print('getting youngest revision...') #youngest_revision = fs.youngest_rev(fs_ptr) assert youngest_revision, "Unable to lookup youngest revision." last_sent_revision = get_last_revision() if youngest_revision == last_sent_revision: # no need to continue. we should be up to date. print('done, up-to-date') return if last_sent_revision or youngest_revision < 10: # Only compare revisions if the DAT file contains a valid # revision number. Otherwise we risk waiting forever while # we parse and uploading every revision in the repo in the case # where a repository is retroactively configured to sync with ftp. pysvn_client = pysvn.Client() pysvn_client.callback_get_login = get_login rev1 = pysvn.Revision(pysvn.opt_revision_kind.number, last_sent_revision) rev2 = pysvn.Revision(pysvn.opt_revision_kind.number, youngest_revision) summary = pysvn_client.diff_summarize(repo_path, rev1, repo_path, rev2, True, False) print('summary len:',len(summary)) if len(summary) > 0 : print('connecting to %s...' % host) ftp = FTPClient(host, user, password) print('connected to %s' % host) ftp.base_path = remote_base_directory print('set remote base directory to %s' % remote_base_directory) #iterate through all the differences between revisions for change in summary : #determine whether the path of the change is relevant to the path that is being sent, and modify the path as appropriate. print('change path:',change.path) ftp_relative_path = apply_basedir(change.path) print('ftp rel path:',ftp_relative_path) #only try to sync path if the path is in our project_directory if ftp_relative_path != "" : is_file = (change.node_kind == pysvn.node_kind.file) if str(change.summarize_kind) == "delete" : print("deleting: " + ftp_relative_path) try: ftp.delete_path("/" + ftp_relative_path, is_file) except ftplib.error_perm as e: if 'cannot find the' in str(e) or 'not found' in str(e): # Log, but otherwise ignore path-not-found errors # when deleting, since it's not a disaster if the file # we want to delete is already gone. logging.error(captureErrorMessage(e)) else: raise elif str(change.summarize_kind) == "added" or str(change.summarize_kind) == "modified" : local_file = "" if is_file : local_file = svn_export_temp(pysvn_client, repo_path, rev2, change.path) print("uploading file: " + ftp_relative_path) ftp.upload_path("/" + ftp_relative_path, is_file, local_file) if is_file : os.remove(local_file) elif str(change.summarize_kind) == "normal" : print("skipping 'normal' element: " + ftp_relative_path) else : raise str("Unknown change summarize kind: " + str(change.summarize_kind) + ", path: " + ftp_relative_path) ftp.close() #write back the last revision that was synced print("writing last revision: " + str(youngest_revision)) set_last_revision(youngest_revision) # todo: undo def get_login(a,b,c,d): #arguments don't matter, we're always going to return the same thing try: return True, "svnUsername", "svnPassword", True except Exception as e: logging.error(e) #capture the location of the error frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace) #end capture sys.exit(1) #functions for persisting the last successfully synced revision def get_last_revision(): if os.path.isfile(status_file) : f=open(status_file, 'r') line = f.readline() f.close() try: i = int(line) except ValueError: i = 0 else: i = 0 f = open(status_file, 'w') f.write(str(i)) f.close() return i def set_last_revision(rev) : f = open(status_file, 'w') f.write(str(rev)) f.close() #augmented ftp client class that can work off a base directory class FTPClient(ftplib.FTP) : def __init__(self, host, username, password) : self.base_path = "" self.current_path = "" ftplib.FTP.__init__(self, host, username, password) def cwd(self, path) : debug_path = path if self.current_path == "" : self.current_path = self.pwd() print("pwd: " + self.current_path) if not os.path.isabs(path) : debug_path = self.base_path + "<" + path path = os.path.join(self.current_path, path) elif self.base_path != "" : debug_path = self.base_path + ">" + path.lstrip("/") path = os.path.join(self.base_path, path.lstrip("/")) path = os.path.normpath(path) #by this point the path should be absolute. if path != self.current_path : print("change from " + self.current_path + " to " + debug_path) ftplib.FTP.cwd(self, path) self.current_path = path else : print("staying put : " + self.current_path) def cd_or_create(self, path) : assert os.path.isabs(path), "absolute path expected (" + path + ")" try: self.cwd(path) except ftplib.error_perm as e: for folder in path.split('/'): if folder == "" : self.cwd("/") continue try: self.cwd(folder) except: print("mkd: (" + path + "):" + folder) self.mkd(folder) self.cwd(folder) def upload_path(self, path, is_file, local_path) : if is_file: (path, filename) = os.path.split(path) self.cd_or_create(path) # Use read-binary to avoid universal newline support from stripping CR characters. f = open(local_path, 'rb') self.storbinary("STOR " + filename, f) f.close() else: self.cd_or_create(path) def delete_path(self, path, is_file) : (path, filename) = os.path.split(path) print("trying to delete: " + path + ", " + filename) self.cwd(path) try: if is_file : self.delete(filename) else: self.delete_path_recursive(filename) except ftplib.error_perm as e: if 'The system cannot find the' in str(e) or '550 File not found' in str(e): # Log, but otherwise ignore path-not-found errors # when deleting, since it's not a disaster if the file # we want to delete is already gone. logging.error(captureErrorMessage(e)) else: raise def delete_path_recursive(self, path): if path == "/" : raise "WARNING: trying to delete '/'!" for node in self.nlst(path) : if node == path : #it's a file. delete and return self.delete(path) return if node != "." and node != ".." : self.delete_path_recursive(os.path.join(path, node)) try: self.rmd(path) except ftplib.error_perm as msg : sys.stderr.write("Error deleting directory " + os.path.join(self.current_path, path) + " : " + str(msg)) # apply the project_directory setting def apply_basedir(path) : #remove any leading stuff (in this case, "trunk/") and decide whether file should be propagated if not path.startswith(project_directory) : return "" return path.replace(project_directory, "", 1) def svn_export_temp(pysvn_client, base_path, rev, path) : # Causes access denied error. Couldn't deduce Windows-perm issue. # It's possible Python isn't garbage-collecting the open file-handle in time for pysvn to re-open it. # Regardless, just generating a simple filename seems to work. #(fd, dest_path) = tempfile.mkstemp() dest_path = tmpName = '%s.tmp' % __file__ exportPath = os.path.join(base_path, path).replace('\\','/') print('exporting %s to %s' % (exportPath, dest_path)) pysvn_client.export( exportPath, dest_path, force=False, revision=rev, native_eol=None, ignore_externals=False, recurse=True, peg_revision=rev ) return dest_path if __name__ == "__main__": logging.info('svnftp.start') try: main() logging.info('svnftp.done') except Exception as e: # capture the location of the error for debug purposes frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace[:-1]) print(stack_trace) # end capture error_text = '\nFATAL EXCEPTION!!!\n'+captureErrorMessage(e) subject = "ALERT: SVN2FTP Error" message = """An Error occurred while trying to FTP an SVN commit. repo_path = %(repo_path)s\n local_repos_path = %(local_repos_path)s\n project_directory = %(project_directory)s\n remote_base_directory = %(remote_base_directory)s\n error_text = %(error_text)s """ % globals() email(toAddrs, message, subject) logging.error(e) Notes/Disclaimers: I have basically no python training so I'm learning as I go and spending lots of time reading docs to figure stuff out. The body of get_login is in a try block because I was getting strange errors saying there was an unhandled exception in callback_get_login. Never figured out why, but it seems fine now. Let sleeping dogs lie, right? The username and password for get_login are currently hard-coded (but correct) just to eliminate variables and try to change as little as possible at once. (I added the svnuser and svnpass arguments to the existing argument parsing.) So that's where I am. I can't figure out why on earth it's not printing anything into svn2ftp.out.log. If you're wondering, the output for one of these failed attempts in svn2ftp.debug.log is: 2012-09-06 15:18:12,496 INFO svnftp.start 2012-09-06 15:18:12,496 INFO svnftp.done And it's no different on a successful run. So there's nothing useful being logged. I'm lost. I've gone way down the rabbit hole on this one, and don't know where to go from here. Any ideas?

    Read the article

  • What is the state of model driven development in 2012?

    - by eriktheblond
    I haven't heard a lot of talk lately on model driven development, but some of my company's customers are using it. I know briefly what it is, but after trying to refresh my memory using Google I found that most of the information is from 2006-2007. Was it something that never really took off? More worryingly is the reason why the customers are asking: They want IEC 61508 complience. Is this actually a "not-so-good" idea that will live on simply because it is prescribed by a standard? I have too little experience to say if MDD is good idea or not (I'm guessing the right answer starts with "It depends"...), but the reasons for using it, that is standard complience, seems just wrong.

    Read the article

  • Data won't save to SQL database, getting error "close() was never explicitly called on database"

    - by SnowLeppard
    I have a save button in the activity where the user enters data which does this: String subjectName = etName.getText().toString(); String subjectColour = etColour.getText().toString(); SQLDatabase entrySubject = new SQLDatabase(AddSubject.this); entrySubject.open(); entrySubject.createSubjectEntry(subjectName, subjectColour); entrySubject.close(); Which refers to this SQL database class: package com.***.schooltimetable; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class SQLDatabase { public static final String KEY_SUBJECTS_ROWID = "_id"; public static final String KEY_SUBJECTNAME = "name"; public static final String KEY_COLOUR = "colour"; private static final String DATABASE_NAME = "Database"; private static final String DATABASE_TABLE_SUBJECTS = "tSubjects"; private static final int DATABASE_VERSION = 1; private DbHelper ourHelper; private final Context ourContext; private SQLiteDatabase ourDatabase; private static class DbHelper extends SQLiteOpenHelper { public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE " + DATABASE_TABLE_SUBJECTS + " (" + KEY_SUBJECTS_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_SUBJECTNAME + " TEXT NOT NULL, " + KEY_COLOUR + " TEXT NOT NULL);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_SUBJECTS); onCreate(db); } } public SQLDatabase(Context c) { ourContext = c; } public SQLDatabase open() throws SQLException { ourHelper = new DbHelper(ourContext); ourDatabase = ourHelper.getWritableDatabase(); return this; } public void close() { ourHelper.close(); } public long createSubjectEntry(String subjectName, String subjectColour) { // TODO Auto-generated method stub ContentValues cv = new ContentValues(); cv.put(KEY_SUBJECTNAME, subjectName); cv.put(KEY_COLOUR, subjectColour); return ourDatabase.insert(DATABASE_TABLE_SUBJECTS, null, cv); } public String[][] getSubjects() { // TODO Auto-generated method stub String[] Columns = new String[] { KEY_SUBJECTNAME, KEY_COLOUR }; Cursor c = ourDatabase.query(DATABASE_TABLE_SUBJECTS, Columns, null, null, null, null, null); String[][] Result = new String[1][]; // int iRow = c.getColumnIndex(KEY_LESSONS_ROWID); int iName = c.getColumnIndex(KEY_SUBJECTNAME); int iColour = c.getColumnIndex(KEY_COLOUR); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { Result[0][c.getPosition()] = c.getString(iName); Result[1][c.getPosition()] = c.getString(iColour); Settings.subjectCount = c.getPosition(); TimetableEntry.subjectCount = c.getPosition(); } return Result; } This class has other variables and other variations of the same methods for multiple tables in the database, i've cut out the irrelevant ones. I'm not sure what I need to close and where, I've got the entrySubject.close() in my activity. I used the methods for the database from the NewBoston tutorials. Can anyone see what I've done wrong, or where my problem is? Thanks.

    Read the article

  • SDK2 query for counting: which is more efficient?

    - by user1195996
    I have an app that is displaying metrics about defects in a project. I have the option of making one query that returns all the defects, and from that I can break out about four different metrics (How many defects escaped QA in 90 days, 180 days, and then the same metrics again but only counting sev1/sev2 defects). I could make four queries and limit the results to one so that I just get a count for each. Or I could make one query that encompass them all (all defects that escaped QA in 180 days) and then count up the difference. I'm figuring worst case, the number of defects that escaped QA in the last six months will generally be less than 100, certainly less 500 worst case. Which would you do-- four queryies with one result each, or one single query that on average might return 50, perhaps worst case 500? And I guess the key question is-- where are the inflections points? Perhaps I have more metrics tomorrow (who knows, 8?) and a different average defect counts. Is there a rule of thumb I could use to help choose which approach?

    Read the article

  • How to get number of elements of a class before a certain element

    - by David Shaikh
    I want to know how many elements of a certain class appear in the DOM before an element that let's say has been clicked on. <html> <div class="a"> </div> <div class="b"> <div class="a"> </div> </div> <button>CLick me!</button> <div class="a"> </div> </html> So in the previous DOM tree if the element to be clicked is the button, and Im looking for divs with class "a" it should return 2, even though in the whole tree there are 3, but "before" the button there are only 2. How could I do that? Thanks

    Read the article

  • Creating an OpenID provider with DotNetOpenAuth

    - by user1652616
    I'm trying to implement an OpenID provider with DotNetOpenAuth. I supply an OpenID url, and the consumer discovers my endpoint. I log into my provider, and the provider returns a Claimed Identifier and a Local Identifier to the consumer. But the consumer response has the following exception: The OpenID Provider issued an assertion for an Identifier whose discovery information did not match. Assertion endpoint info: ClaimedIdentifier: http://localhost/OpenIDUser.aspx/myuser ProviderLocalIdentifier: http://localhost/OpenIDUser.aspx/myuser ProviderEndpoint: http://localhost/OpenIDAuth.aspx OpenID version: 2.0 Service Type URIs: Discovered endpoint info: [] http://localhost/OpenIDAuth.aspx is my endpoint. http://localhost/OpenIDUser.aspx/myuser is my user identifier url, and I can browse to it successfully. It has a link to the endpoint in the header as follows: <link rel="openid.server" href="http://localhost/OpenIDAuth.aspx"></link> No matter what I try, the "Discovered endpoint info: []" part of the exception is always an empty array. Can anyone please help?

    Read the article

  • Freemarker rendering differently on IE8

    - by scphantm
    we have a template that uses this for the record line <input type="${inputType}" name="${variableName}.code" id="${variable}.${vnum}.${answer.code}" class="checkbox" value="${answer.code}" [#nested/] [#if (answer.textLength > 0) && scripting]onchange="showOtherBox( this, '${variable}.[#if descriptionHack]${variableNumber}[#else]${vnum}[/#if].${answer.code}.description' )"[/#if] [#if showValues && (existing == answer.code)]checked="checked"[/#if]/> On IE8 it renders as this <span class="field"> <INPUT id=responses.8.L class=checkbox value=L type=checkbox name="responses['8'].answers['L'].code"> <LABEL for=responses.8.L>Award(s) for special accomplishment or performance related to activity participation (please list)</LABEL> <TEXTAREA id=responses.8.L.description class=" visible" rows=4 cols=60 name="responses['8'].answers['L'].description"></TEXTAREA> </span> and on every other browser we tried, it renders as this <span class="field"> <input type="checkbox" name="responses['8'].answers['L'].code" id="responses.8.L" class="checkbox" value="L" onchange="showOtherBox( this, 'responses.8.L.description' )"> <label for="responses.8.L">Award(s) for special accomplishment or performance related to activity participation (please list)</label> <textarea rows="4" cols="60" name="responses['8'].answers['L'].description" id="responses.8.L.description" class="visible" classname="visible"></textarea> </span> The difference being that in the FTL script, the if statement [#if (answer.textLength > 0) && scripting] is true for everything except IE. In IE8 its false for some reason and therefore it does not put the OnChange javascript event on the input tag. Has anyone seen anything like this before? we are using Freemarker 2.3.9 Update, it kinda works if i turn compatibility mode on for IE8. but not exactly. when i do that, the onchange event doesn't fire until the check box loses focus. which is very different than everything else. Is there a quick way to fix this without too much trouble? i suppose i could put something in that says if ie8, insert onclick instead of onchange. that may work, but i would need an authorization from the client to fix it like that.

    Read the article

  • loading google maps drawing manager object

    - by psychok7
    So i am using Google Maps Drawing Manager to draw some polygons and i am saving the lat e long coordinates to my database. Now my question is, after i load that to my array, how can i rebuild the saved polygon back into my map? I can't seem to find a code to understand that. this is what i have now : window.initialize_2 = function () { var mapOptions = { center: new google.maps.LatLng(-34.397, 150.644), zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = maplimits; var drawingManager = new google.maps.drawing.DrawingManager({ drawingMode: google.maps.drawing.OverlayType.MARKER, drawingControl: true, drawingControlOptions: { position: google.maps.ControlPosition.TOP_CENTER, drawingModes: [ google.maps.drawing.OverlayType.POLYGON] }, markerOptions: { icon: 'images/beachflag.png' }, polygonOptions: { fillColor: '#ffff00', fillOpacity: 10, strokeWeight: 5, clickable: true, editable: true, zIndex: 1 } }); var coord_listener = google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon) { var coordinates = (polygon.getPath().getArray()); console.log(coordinates); window.poly = polygon; }); //delete shape google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) { if (e.type != google.maps.drawing.OverlayType.MARKER) { // Switch back to non-drawing mode after drawing a shape. drawingManager.setDrawingMode(null); // Add an event listener that selects the newly-drawn shape when the user // mouses down on it. var newShape = e.overlay; newShape.type = e.type; google.maps.event.addListener(newShape, 'click', function () { setSelection(newShape); }); setSelection(newShape); } }); // Clear the current selection when the drawing mode is changed, or when the // map is clicked. google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection); google.maps.event.addListener(map, 'click', clearSelection); drawingManager.setMap(map); }

    Read the article

  • Passing a NSString to another ViewController using classes

    - by Jeff Kranenburg
    I know this insanely simple, but I am re-teaching myself the basics and trying to get my head around this:-) I have one ViewController called MainVC and I have one called ClassVC In ClassVC I have this code: @interface ClassVC : UIViewController { NSString *mainLine; } @property (nonatomic, retain) NSString *mainLine; @end and I have this in the implementation file: @synthesize mainLine = _mainLine; -(NSString *)_mainLine { _mainLine = @"This a string from a Class"; return _mainLine; } Now I was thinking that if I #import the ClassVC into MainVC I would be able to transfer that string along as well like so: This code is in the viewDidLoad _mainLabel.text = _secondClass.mainLine; NSLog(@"%@", _secondClass.mainLine); But that is not working - so cannot I not pass strings in through this way???

    Read the article

  • lapply slower than for-loop when used for a BiomaRt query. Is that expected?

    - by ptocquin
    I would like to query a database using BiomaRt package. I have loci and want to retrieve some related information, let say description. I first try to use lapply but was surprise by the time needed for the task to be performed. I thus tried a more basic for-loop and get a faster result. Is that expected or is something wrong with my code or with my understanding of apply ? I read other posts dealing with *apply vs for-loop performance (Here, for example) and I was aware that improved performance should not be expected but I don't understand why performance here is actually lower. Here is a reproducible example. 1) Loading the library and selecting the database : library("biomaRt") athaliana <- useMart("plants_mart_14") athaliana <- useDataset("athaliana_eg_gene",mart=athaliana) 2) Querying the database : loci <- c("at1g01300", "at1g01800", "at1g01900", "at1g02335", "at1g02790", "at1g03220", "at1g03230", "at1g04040", "at1g04110", "at1g05240" ) I create a function for the use in lapply : foo <- function(loci) { getBM("description","tair_locus",loci,athaliana) } When I use this function on the first element : > system.time(foo(cwp_loci[1])) utilisateur système écoulé 0.020 0.004 1.599 When I use lapply to retrieve the data for all values : > system.time(lapply(loci, foo)) utilisateur système écoulé 0.220 0.000 16.376 I then created a new function, adding a for-loop : foo2 <- function(loci) { for (i in loci) { getBM("description","tair_locus",loci[i],athaliana) } } Here is the result : > system.time(foo2(loci)) utilisateur système écoulé 0.204 0.004 10.919 Of course, this will be applied to a big list of loci, so the best performing option is needed. I thank you for assistance. EDIT Following recommendation of @MartinMorgan Simply passing the vector loci to getBM greatly improves the query efficiency. Simpler is better. > system.time(lapply(loci, foo)) utilisateur système écoulé 0.236 0.024 110.512 > system.time(foo2(loci)) utilisateur système écoulé 0.208 0.040 116.099 > system.time(foo(loci)) utilisateur système écoulé 0.028 0.000 6.193

    Read the article

  • Find all those columns which have only null values, in a MySQL table

    - by Robin v. G.
    The situation is as follows: I have a substantial number of tables, with each a substantial number of columns. I need to deal with this old and to-be-deprecated database for a new system, and I'm looking for a way to eliminate all columns that have - apparently - never been in use. I wanna do this by filtering out all columns that have a value on any given row, leaving me with a set of columns where the value is NULL in all rows. Of course I could manually sort every column descending, but that'd take too long as I'm dealing with loads of tables and columns. I estimate it to be 400 tables with up to 50 (!) columns per table. Is there any way I can get this information from the information_schema? EDIT: Here's an example: column_a column_b column_c column_d NULL NULL NULL 1 NULL 1 NULL 1 NULL 1 NULL NULL NULL NULL NULL NULL The output should be 'column_a' and 'column_c', for being the only columns without any filled in values.

    Read the article

  • Decode html tag so that it can be read when it goes back to the server more specifically the controller

    - by Yusuf
    My engine is Aspx. How can I decode/encode the html tags that is in my text box. I have the html tag to make it more readable. I tried the ValidationRequest and the htmlDecode(freqQuestion.Answer) but no luck. I just keep getting the same message. Server Error in '/Administrator' Application. A potentially dangerous Request.Form value was detected from the client (QuestionAnswer="...ics Phone:123-456-7890 Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. To allow pages to override application request validation settings, set the requestValidationMode attribute in the httpRuntime configuration section to requestValidationMode="2.0". Example: . After setting this value, you can then disable request validation by setting validateRequest="false" in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case. For more information, see http://go.microsoft.com/fwlink/?LinkId=153133. View Page <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" validateRequest="false" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> EditFreqQuestionsUser </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <script type="text/javascript"> $(document).ready(function () { $("#freqQuestionsUserUpdateButton").click(function () { $("#updateFreqQuestionsUser").submit(); }); }); </script> <h2>Edit Freq Questions User </h2> <%Administrator.DarkstarAdminProductionServices.FreqQuestionsUser freqQuestionsUser = ViewBag.freqQuestionsUser != null ? ViewBag.freqQuestionsUser : new Administrator.DarkstarAdminProductionServices.FreqQuestionsUser(); %> <%List<string> UserRoleList = Session["UserRoles"] != null ? (List<string>)Session["UserRoles"] : new List<string>(); %> <form id="updateFreqQuestionsUser" action="<%=Url.Action("SaveFreqQuestionsUser","Prod")%>" method="post"> <table> <tr> <td colspan="3" class="tableHeader">Freq Questions User Details <input type ="hidden" value="<%=freqQuestionsUser.freqQuestionsUserId%>" name="freqQuestionsUserId"/> </td> </tr> <tr> <td colspan="2" class="label">Question Description:</td> <td class="content"> <input type="text" maxlength="2000" name="QuestionDescription" value="<%=freqQuestionsUser.questionDescription%>" /> </td> </tr> <tr> <td colspan="2" class="label">QuestionAnswer:</td> <td class="content"> <input type="text" maxlength="2000" name="QuestionAnswer" value="<%=Server.HtmlDecode(freqQuestionsUser.questionAnswer)%>" /> </td> </tr> <tr> <td colspan="3" class="tableFooter"> <br /> <a id="freqQuestionsUserUpdateButton" href="#" class="regularButton">Save</a> <a href="javascript:history.back()" class="regularButton">Cancel</a> </td> </tr> </table> </form> </asp:Content> Controller [AuthorizeAttribute(AdminRoles = "EditFreqQuestionsUser")] public ActionResult SaveFreqQuestionsUser(string QuestionDescription, string QuestionAnswer) { Guid freqQuestionsUserId = Request.Form["freqQuestionsUserId"] != null ? new Guid(Request.Form["freqQuestionsUserId"]) : Guid.Empty; //load agreement eula ref AdminProductionServices.FreqQuestionsUser freqqQuestionsUser = Administrator.Models.AdminProduction.FreqQuestionsUser.LoadFreqQuestionsUser(freqQuestionsUserId, string.Empty, string.Empty)[0]; freqqQuestionsUser.questionDescription = QuestionDescription; freqqQuestionsUser.questionAnswer = QuestionAnswer; //save it Administrator.Models.AdminProduction.FreqQuestionsUser.addFreqQuestionsUser(freqqQuestionsUser); return RedirectToAction("SearchFreqQuestionsUser", "Prod", new { FreqQuestionsUserId = freqQuestionsUserId }); }

    Read the article

  • Chrome Apps Office Hours: TextDrive and AngularJS

    Chrome Apps Office Hours: TextDrive and AngularJS Ask and vote for questions: goo.gl In this episode, the AngularJS team joins us to talk about how they used Angular to build TextDrive. TextDrive is an open source text editor application that demonstrates of the power and simplicity of AngularJS and Chrome Apps. It features integration with Google Drive, web intents, and Ace (ace.ajax.org) in a simple and clean interface built upon HTML5 and web standards. To learn more visit github.com From: GoogleDevelopers Views: 0 0 ratings Time: 00:00 More in Science & Technology

    Read the article

  • A WPF Image Button

    - by psheriff
    Instead of a normal button with words, sometimes you want a button that is just graphical. Yes, you can put an Image control in the Content of a normal Button control, but you still have the button outline, and trying to change the style can be rather difficult. Instead I like creating a user control that simulates a button, but just accepts an image. Figure 1 shows an example of three of these custom user controls to represent minimize, maximize and close buttons for a borderless window. Notice the highlighted image button has a gray rectangle around it. You will learn how to highlight using the VisualStateManager in this blog post.Figure 1: Creating a custom user control for things like image buttons gives you complete control over the look and feel.I would suggest you read my previous blog post on creating a custom Button user control as that is a good primer for what I am going to expand upon in this blog post. You can find this blog post at http://weblogs.asp.net/psheriff/archive/2012/08/10/create-your-own-wpf-button-user-controls.aspx.The User ControlThe XAML for this image button user control contains just a few controls, plus a Visual State Manager. The basic outline of the user control is shown below:<Border Grid.Row="0"        Name="borMain"        Style="{StaticResource pdsaButtonImageBorderStyle}"        MouseEnter="borMain_MouseEnter"        MouseLeave="borMain_MouseLeave"        MouseLeftButtonDown="borMain_MouseLeftButtonDown">  <VisualStateManager.VisualStateGroups>  ... MORE XAML HERE ...  </VisualStateManager.VisualStateGroups>  <Image Style="{StaticResource pdsaButtonImageImageStyle}"         Visibility="{Binding Path=Visibility}"         Source="{Binding Path=ImageUri}"         ToolTip="{Binding Path=ToolTip}" /></Border>There is a Border control named borMain and a single Image control in this user control. That is all that is needed to display the buttons shown in Figure 1. The definition for this user control is in a DLL named PDSA.WPF. The Style definitions for both the Border and the Image controls are contained in a resource dictionary names PDSAButtonStyles.xaml. Using a resource dictionary allows you to create a few different resource dictionaries, each with a different theme for the buttons.The Visual State ManagerTo display the highlight around the button as your mouse moves over the control, you will need to add a Visual State Manager group. Two different states are needed; MouseEnter and MouseLeave. In the MouseEnter you create a ColorAnimation to modify the BorderBrush color of the Border control. You specify the color to animate as “DarkGray”. You set the duration to less than a second. The TargetName of this storyboard is the name of the Border control “borMain” and since we are specifying a single color, you need to set the TargetProperty to “BorderBrush.Color”. You do not need any storyboard for the MouseLeave state. Leaving this VisualState empty tells the Visual State Manager to put everything back the way it was before the MouseEnter event.<VisualStateManager.VisualStateGroups>  <VisualStateGroup Name="MouseStates">    <VisualState Name="MouseEnter">      <Storyboard>        <ColorAnimation             To="DarkGray"            Duration="0:0:00.1"            Storyboard.TargetName="borMain"            Storyboard.TargetProperty="BorderBrush.Color" />      </Storyboard>    </VisualState>    <VisualState Name="MouseLeave" />  </VisualStateGroup></VisualStateManager.VisualStateGroups>Writing the Mouse EventsTo trigger the Visual State Manager to run its storyboard in response to the specified event, you need to respond to the MouseEnter event on the Border control. In the code behind for this event call the GoToElementState() method of the VisualStateManager class exposed by the user control. To this method you will pass in the target element (“borMain”) and the state (“MouseEnter”). The VisualStateManager will then run the storyboard contained within the defined state in the XAML.private void borMain_MouseEnter(object sender,  MouseEventArgs e){  VisualStateManager.GoToElementState(borMain,    "MouseEnter", true);}You also need to respond to the MouseLeave event. In this event you call the VisualStateManager as well, but specify “MouseLeave” as the state to go to.private void borMain_MouseLeave(object sender, MouseEventArgs e){  VisualStateManager.GoToElementState(borMain,     "MouseLeave", true);}The Resource DictionaryBelow is the definition of the PDSAButtonStyles.xaml resource dictionary file contained in the PDSA.WPF DLL. This dictionary can be used as the default look and feel for any image button control you add to a window. <ResourceDictionary  ... >  <!-- ************************* -->  <!-- ** Image Button Styles ** -->  <!-- ************************* -->  <!-- Image/Text Button Border -->  <Style TargetType="Border"         x:Key="pdsaButtonImageBorderStyle">    <Setter Property="Margin"            Value="4" />    <Setter Property="Padding"            Value="2" />    <Setter Property="BorderBrush"            Value="Transparent" />    <Setter Property="BorderThickness"            Value="1" />    <Setter Property="VerticalAlignment"            Value="Top" />    <Setter Property="HorizontalAlignment"            Value="Left" />    <Setter Property="Background"            Value="Transparent" />  </Style>  <!-- Image Button -->  <Style TargetType="Image"         x:Key="pdsaButtonImageImageStyle">    <Setter Property="Width"            Value="40" />    <Setter Property="Margin"            Value="6" />    <Setter Property="VerticalAlignment"            Value="Top" />    <Setter Property="HorizontalAlignment"            Value="Left" />  </Style></ResourceDictionary>Using the Button ControlOnce you make a reference to the PDSA.WPF DLL from your WPF application you will see the “PDSAucButtonImage” control appear in your Toolbox. Drag and drop the button onto a Window or User Control in your application. I have not referenced the PDSAButtonStyles.xaml file within the control itself so you do need to add a reference to this resource dictionary somewhere in your application such as in the App.xaml.<Application.Resources>  <ResourceDictionary>    <ResourceDictionary.MergedDictionaries>      <ResourceDictionary         Source="/PDSA.WPF;component/PDSAButtonStyles.xaml" />    </ResourceDictionary.MergedDictionaries>  </ResourceDictionary></Application.Resources>This will give your buttons a default look and feel unless you override that dictionary on a specific Window or User Control or on an individual button. After you have given a global style to your application and you drag your image button onto a window, the following will appear in your XAML window.<my:PDSAucButtonImage ... />There will be some other attributes set on the above XAML, but you simply need to set the x:Name, the ToolTip and ImageUri properties. You will also want to respond to the Click event procedure in order to associate an action with clicking on this button. In the sample code you download for this blog post you will find the declaration of the Minimize button to be the following:<my:PDSAucButtonImage       x:Name="btnMinimize"       Click="btnMinimize_Click"       ToolTip="Minimize Application"       ImageUri="/PDSA.WPF;component/Images/Minus.png" />The ImageUri property is a dependency property in the PDSAucButtonImage user control. The x:Name and the ToolTip we get for free. You have to create the Click event procedure yourself. This is also created in the PDSAucButtonImage user control as follows:private void borMain_MouseLeftButtonDown(object sender,  MouseButtonEventArgs e){  RaiseClick(e);}public delegate void ClickEventHandler(object sender,  RoutedEventArgs e);public event ClickEventHandler Click;protected void RaiseClick(RoutedEventArgs e){  if (null != Click)    Click(this, e);}Since a Border control does not have a Click event you will create one by using the MouseLeftButtonDown on the border to fire an event you create called “Click”.SummaryCreating your own image button control can be done in a variety of ways. In this blog post I showed you how to create a custom user control and simulate a button using a Border and Image control. With just a little bit of code to respond to the MouseLeftButtonDown event on the border you can raise your own Click event. Dependency properties, such as ImageUri, allow you to set attributes on your custom user control. Feel free to expand on this button by adding additional dependency properties, change the resource dictionary, and even the animation to make this button look and act like you want.NOTE: You can download the sample code for this article by visiting my website at http://www.pdsa.com/downloads. Select “Tips & Tricks”, then select “A WPF Image  Button” from the drop down list.

    Read the article

  • DDoS attacks to PBX

    - by user316687
    I'm wondering if DDOS attacks to PBX or telecommunications systems is possibe real. According to this links: http://threatpost.com/en_us/blogs/firm-sees-more-ddos-attacks-aimed-telecom-systems-073112 http://news.softpedia.com/news/DDOS-Attacks-Against-Telecom-Systems-Cost-as-Little-as-20-16-Per-Day-284875.shtml it is possible. There are DDOs attacks to web servers, which mostly give them so much concurrent loads or connections that service get unavailable. Many government or non-profit organizations that suffered this kind of attacks, eventually could choose to shutdown their web server and that's it, waiting for these attacks to end. For a DDOs attacks to PBX, I imagine that it would result in telephones getting busy or ringing all the time unstoppably. This kind of attack could really damage any kind organization. Is it possible to do that or are we just in the beginnings?

    Read the article

  • How to build a small network/server at home, basics

    - by Moe
    I'm one class away from my BA IT, I took several classes in general IT. Out of all the books I found just two to be really beneficial. I'm trying to get the hands on experience so my question is.... I want to build a small network in my home, wireless and also wired; printer, laptop, desktop, server (I have 4 1TB external drives of movies/music I want to be available to all computers) Where would I start from building a server with my hard drives, good modem, router, switch port, firewall internet speed/connection etc. This is my first project I want to try.

    Read the article

  • Multiboot USB (OSX only): How to customize partition name?

    - by wrk2bike
    Trying to deal with all the Mac OSX recovery disks I've got by moving them to bootable USB images. I've got a big USB drive with multiple partitions for each recovery disk, and it's easy to use Disk Utility to "restore" the recovery DVD to a partition. When I boot my target Mac while holding down the Alt key, I can see all my bootable images and they work great. Problem is, they've all got the same name: "Mac OS X Install DVD." I manage Macs of various vintages. If my target Mac needs 10.6.3 for example, my only option seems to be to try each one until I get past the "Mac OSX can't be installed on this computer" message. I originally named my partitions with the OSX revision number, but that name is replaced by the disk image name during Disk Utility restore. Is there any way to customize the name during or after Disk Utility restore? I tried making a new DVD image on disk first and renaming it, but when I restore it to my recovery partition it has the original name. EDIT: After booting to the wrong partition, and getting the "..can't be installed" message, I can open the Startup Disk menu and see the other partitions - and as I select each one, the info at the bottom indicates which OS revision is on that partition. So I know the info is in there! Just want it at the boot screen if possible.

    Read the article

  • openVAS - Microsoft RDP Server Private Key Information Disclosure Vulnerability - false Alarm?

    - by huebkov
    I performed a openVAS scan on a Windows Server 2008 R2 and got a report for a high threat level vulnerability called Microsoft RDP Server Private Key Information Disclosure Vulnerability. An remote attacker could perform a man-in-the-middle attack to gain access to a RDP session. Affected Software is Microsoft RDP 5.2 and below. My server uses RDP 7.1, is this alarm a false alarm? Security Advisor Pages say: Solution Status Unpatched, No remedy... References http://secunia.com/advisories/15605/ http://xforce.iss.net/xforce/xfdb/21954/ http://www.oxid.it/downloads/rdp-gbu.pdf CVE: CVE-2005-1794 BID:13818

    Read the article

  • NIS AD password synch for new accounts

    - by user135004
    I have a Win2k3R2 DC with NIS. All is working well but its no longer synching the passwords for new accounts. When creating a new AD user, NIS does its thing and sends its Unix account to the synched linux server. It's doing everything its supposed to do but not the users password to the server (getent passwd returns the ABCD!efgh12345$67890 password for the new account). Thinking that password synchronization is not working, I changed the password of an existing working account and it synchs the new password. If I delete a new or old AD user, it deletes it on the linked linux server as well. All this tells me that NIS is doing its thing (at least with existing accounts) No updates have been installed on the DC. I am not even sure where to start here.

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19  | Next Page >