def onTick(timer, e): global ts ts = ts.Add(timer.Interval) entry = Entry() if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")): entry.Title = String.Format("予定の{0}分前になりました", Math.Abs(ts.Minutes).ToString()) else: if Math.Abs(ts.Minutes) == 1: entry.Title = String.Format("{0} minute remaining", Math.Abs(ts.Minutes).ToString()) else: entry.Title = String.Format("{0} minutes remaining", Math.Abs(ts.Minutes).ToString()) if ts.TotalMilliseconds >= 0: timer.Stop() ts = TimeSpan.Zero if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")): entry.Title = "予定の時間になりました" else: entry.Title= "Time expired" entryList = List[Entry]() entryList.Add(entry) Script.Instance.Alert(entryList)
def SearchTracks(composer): WriteLine(String.Format("Searching for tracks by '{0}'...", composer)) tracks = GetAllTracks().Where(lambda t: t.Composer == composer) WriteLine( String.Format("Found {0} tracks by '{1}'", tracks.Count(), composer)) for t in tracks: WriteLine(String.Format("Track Id: {0} Name: {1}", t.Id, t.Name)) WriteLine("Search complete")
def print_maximum_capabilities(setting): # Get Max Capabilities print(String.Format("{0} {1} {2}", "Maximum", setting, "Capabilities:")) for item in experiment.GetMaximumCapabilities(setting): if (setting == CameraSettings.AdcSpeed): print_speeds(item) else: print(String.Format('\t{0} {1}', setting, item))
def onUpdate(): if NetworkInterface.GetIsNetworkAvailable(): try: response = None stream = None try: response = request.GetResponse() stream = response.GetResponseStream() doc = XmlDocument() doc.Load(stream) for itemXmlNode in doc.GetElementsByTagName("item"): entry = Entry() epicenter = None maxLevel = None for xmlNode in itemXmlNode.ChildNodes: if xmlNode.Name.Equals("link"): entry.Resource = Uri(xmlNode.InnerText) elif xmlNode.Name.Equals("description"): entry.Description = xmlNode.InnerText elif xmlNode.Name.Equals("tenkiJP:earthquake"): for attribute in xmlNode.Attributes: if attribute.Name.Equals("epicenter"): epicenter = attribute.Value elif attribute.Name.Equals("max_level"): maxLevel = attribute.Value elif attribute.Name.Equals( "outbreak_datetime"): entry.Created = entry.Modified = DateTime.Parse( attribute.Value) if epicenter is not None: if String.IsNullOrEmpty(maxLevel): maxLevel = "N/A" if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): entry.Title = String.Format( "震度{0} - {1}", maxLevel, epicenter) else: entry.Title = String.Format( "Intensity {0} - {1}", maxLevel, epicenter) entryList.Add(entry) finally: if stream is not None: stream.Close() if response is not None: response.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def get_spectrometer_info(): print( String.Format( "{0} {1}", "Center Wave Length:", str( experiment.GetValue( SpectrometerSettings.GratingCenterWavelength)))) print( String.Format("{0} {1}", "Grating:", str(experiment.GetValue(SpectrometerSettings.Grating))))
def get_spectrometer_info(self, *args): logger.debug('Called get_spectrometer_info directly! Args: ' + str(args)) print( String.Format( "{0} {1}", "Center Wave Length:", str( self.experiment.GetValue( SpectrometerSettings.GratingCenterWavelength)))) print( String.Format( "{0} {1}", "Grating:", str(self.experiment.GetValue(SpectrometerSettings.Grating)))) return "Function Completed"
def TestInvoices(): WriteLine("Testing Invoices...") invoice = GetAllInvoices().FirstOrDefault() WriteLine( String.Format("Invoice Id: {0} Date: {1}", invoice.Id, invoice.InvoiceDate)) lines = invoice.Lines WriteLine(String.Format("Found {0} tracks", lines.Count)) for l in lines: WriteLine( String.Format( "Invoice Line Id: {0} Track Id: {1} Track Name: {2} Price: {3}", l.Id, l.Track.Id, l.Track.Name, l.Track.UnitPrice)) WriteLine("Testing Invoices complete") WriteLine()
def print_setting(setting): # Check for existence before # getting gain, adc rate, or adc quality if experiment.Exists(setting): print( String.Format('{0} {1} = {2}', "\tReading ", str(setting), experiment.GetValue(setting)))
def get_image_data(file): # Get the first frame imageData = file.GetFrame(0, 0) # Print Height and Width of first frame print( String.Format('\t{0} {1}X{2}', "Image Width and Height:", imageData.Width, imageData.Height)) # Get image data buffer = imageData.GetData() # Print first 10 pixel intensities for pixel in range(0, 10): print( String.Format('\t{0} {1}', 'Pixel Intensity:', str(buffer[pixel])))
def print_current_capabilities(setting): # Get current ADC rates that correspond # with the current quality setting print(String.Format("{0} {1} {2}", "Current", setting, "Capabilities:")) for item in experiment.GetCurrentCapabilities(setting): print_speeds(item)
def set_value(setting, value): # Check for existence before setting # gain, adc rate, or adc quality if experiment.Exists(setting): print(String.Format("{0}{1} to {2}", "Setting ", setting, value)) experiment.SetValue(setting, value)
def On_PlayerConnected(self, player): Server.Broadcast(player.Name + " has joined the server!") player.Message( String.Format("This server is working with Pluton[{0}]", Pluton.Bootstrap.Version)) player.Message("Type /help for a list of commands") player.Inventory.Add(6604, 40) player.Inventory.Add(11963, 1)
def get_status(): current = experiment.GetValue(CameraSettings.SensorTemperatureStatus) print( String.Format( "{0} {1}", "Current Status:", "UnLocked" if current == SensorTemperatureStatus.Unlocked else "Locked")) return current
def print_speeds(item): if item < 1: # Values less than 1 are kHz ADC rates rate = "kHz" item = item * 1000 else: rate = "MHz" print(String.Format('\t{0}{1}', item, rate))
def parseSequence(xmlNode, directory, warningList, errorList): for childNode1 in xmlNode.ChildNodes: if childNode1.Name.Equals("sequence"): parseSequence(childNode1, directory, warningList, errorList) elif childNode1.Name.Equals("message"): if childNode1.InnerText.Length == 0: if childNode1.InnerText.Length == 0: if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): warningList.Add("メッセージタグ内のテキストが空です。") else: warningList.Add( "The inner text is empty in message tag.") elif childNode1.Name.Equals("motion"): for childNode2 in childNode1.ChildNodes: if childNode2.Name.Equals("image"): if childNode2.InnerText.Length > 0 and not File.Exists( Path.Combine(directory, childNode2.InnerText)): if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): errorList.Add( String.Format("指定されたファイルが見つかりません。 \"{0}\"", childNode2.InnerText)) else: errorList.Add( String.Format( "Could not find the specified file. \"{0}\"", childNode2.InnerText)) elif childNode1.Name.Equals("sound"): if childNode1.InnerText.Length > 0 and not File.Exists( Path.Combine(directory, childNode1.InnerText)): if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): errorList.Add( String.Format("指定されたファイルが見つかりません。 \"{0}\"", childNode1.InnerText)) else: errorList.Add( String.Format( "Could not find the specified file. \"{0}\"", childNode1.InnerText))
def measurementsetup(self, pattern, eR, eG, eB, eXB, focus, aperture, is_autoexp, rect, distance_unit, spectral_response, rotation): meas_setup = self._device.CreateMeasurementSetup(pattern, eR, eG, eB, eXB, focus, aperture, is_autoexp, rect, distance_unit, spectral_response, rotation) response = int(str(String.Format("Measurement Setup Result for " + pattern +" - ErrorCode: {0}", meas_setup['ErrorCode'])).split(":")[1]) if self._verbose: print response return response
def urlEncode(value): unreserved = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~" sb = StringBuilder() bytes = Encoding.UTF8.GetBytes(value) for b in bytes: if b < 0x80 and unreserved.IndexOf(Convert.ToChar(b)) != -1: sb.Append(Convert.ToChar(b)) else: sb.Append('%' + String.Format("{0:X2}", Convert.ToInt32(b))) return sb.ToString()
def __init__(self, fileName): from System import String from System.Collections.Generic import Dictionary from System.Configuration import IConfigurationSectionHandler, ConfigurationErrorsException self.__customSections = Dictionary[String, IConfigurationSectionHandler]() loaded = self.Load(fileName) if not loaded: raise ConfigurationErrorsException( String.Format( "File: {0} could not be found or was not a valid cofiguration file.", fileName))
def TestCustomers(): WriteLine("Testing Customers...") customer = GetAllCustomers().FirstOrDefault() rep = customer.SupportRep reportsTo = rep.ReportsTo WriteLine( String.Format("Customer: {0} {1}", customer.FirstName, customer.LastName)) WriteLine( String.Format("Support Rep: {0} {1}", rep.FirstName, rep.LastName)) if (reportsTo != None): WriteLine( String.Format("Reports To: {0} {1}", reportsTo.FirstName, reportsTo.LastName)) else: WriteLine("Employee has no boss") WriteLine("Testing Customers complete") WriteLine()
def print_region(region): print("Custom Region Setting:") print(String.Format("{0} {1}", "\tX:", region.X)) print(String.Format("{0} {1}", "\tY:", region.Y)) print(String.Format("{0} {1}", "\tWidth:", region.Width)) print(String.Format("{0} {1}", "\tHeight:", region.Height)) print(String.Format("{0} {1}", "\tXBinning:", region.XBinning)) print(String.Format("{0} {1}", "\tYBinning:", region.YBinning))
def onSave(): try: fs = None sr = None sw = None try: fs = FileStream(__file__, FileMode.Open, FileAccess.ReadWrite, FileShare.Read) encoding = UTF8Encoding(False) sr = StreamReader(fs, encoding, True) lines = Regex.Replace( Regex.Replace( sr.ReadToEnd(), "username\\s*=\\s*\"\"", String.Format("username = \"{0}\"", username), RegexOptions.CultureInvariant), "password\\s*=\\s*\"\"", String.Format("password = \"{0}\"", password), RegexOptions.CultureInvariant) fs.SetLength(0) sw = StreamWriter(fs, encoding) sw.Write(lines) finally: if sw is not None: sw.Close() if sr is not None: sr.Close() if fs is not None: fs.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def update(idx, fixed): record = view.FrequentInspectRecords.Rows[idx] id = record.InspectId print '更新經常巡查資料' print '=' * 50 values = List[str]([ '%s' % getattr(record, 'Data%d' % (i + 1)) for i in range(len(view.FrequentInspectRecords.Headers))]) from System import DateTime, String import time values[2] = '%sk' % str(time.time()) # 里程 values[11] = fixed values[5] = String.Format("{0:yyyy/M/d}", DateTime.Now.Date) print id, values ok = _log(patrolSrv.UpdateFrequentInspectRecord)(id, tunnelId, values) print '成功?', ok print
def prepare_parameter_dictionary_for_query(self, projectName=''): '''prepare_parameter_dictionary_for_query creates a dictionary with mappings for the parameters @me and @project that can be used in WIQL queries. Feed the result as a parameter into the function get_list_of_work_items. Input: projectName (optional, name of project as a string) Output: Dictionary {"project" : projectName, "me" : currentUserDisplayName} ''' from System import String, Environment clr.AddReference('System.Collections') from System.Collections.Generic import Dictionary # securityService = self.server.GetService(IGroupSecurityService) accountName = String.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName) memberInfo = self.gss.ReadIdentity(SearchFactor.AccountName, accountName, getattr(QueryMembership, 'None')) if memberInfo is not None: currentUserDisplayName = memberInfo.DisplayName else: currentUserDisplayName = Environment.UserName tempDict = Dictionary[String, String]() tempDict.Add("project", projectName) tempDict.Add("me", currentUserDisplayName) return tempDict
#!/usr/bin/env python import clr from System import String print(String.Format("{0} {1}", "Hello", "World"))
def On_PlayerConnected(self, player): for p in Server.ActivePlayers: if (p.Name != player.Name): p.Message( String.Format("{0} has joined the server!", player.Name))
def search(self, jql): clr.AddReference("System.Web") from System.Web import HttpUtility from System.Net import HttpWebRequest from System.IO import StreamReader clr.AddReference("Newtonsoft.Json") from Newtonsoft.Json import JsonTextReader from Newtonsoft.Json.Linq import JObject from System import Decimal import Newtonsoft.Json clr.ImportExtensions(Newtonsoft.Json.Linq) usernamepw = Convert.ToBase64String( Encoding.UTF8.GetBytes( String.Format("{0}:{1}", self.username, self.password))) fieldsparam = String.Join(",", self.requestedFields) requestUri = String.Format( "{0}rest/api/2/search?jql={1}&fields={2}", self.repository.AbsoluteUri, HttpUtility.UrlEncode(jql), fieldsparam) Logger.Write(LogLevel.Verbose, "Jira.Search: {0}", requestUri) request = HttpWebRequest.Create(requestUri) request.ContentType = "application/json" request.Headers.Add("Authorization", "Basic " + usernamepw) request.Method = "GET" with request.GetResponse() as response: with StreamReader(response.GetResponseStream()) as sr: with JsonTextReader(sr) as jr: result = JObject.Load(jr) issues = result["issues"] items = list() for issue in issues: item = Issue() item.Key = Newtonsoft.Json.Linq.Extensions.Value[ String](issue["key"]) fields = issue["fields"] item.Updated = Newtonsoft.Json.Linq.Extensions.Value[ DateTime](fields["updated"]) # transform seconds to hours estimate = Newtonsoft.Json.Linq.Extensions.Value[ System.Object](fields["timeoriginalestimate"]) if estimate is not None: estimate = Newtonsoft.Json.Linq.Extensions.Value[ Decimal](fields["timeoriginalestimate"]) estimate = estimate / (60.0 * 60.0) item.TimeOriginalEstimate = estimate status = fields["status"] item.Status = Newtonsoft.Json.Linq.Extensions.Value[ String](status["name"]) item.Summary = Newtonsoft.Json.Linq.Extensions.Value[ String](fields["summary"]) type = fields["issuetype"] item.Type = Newtonsoft.Json.Linq.Extensions.Value[ String](type["name"]) item.Link = self.repository.ToString( ) + "browse/" + item.Key subTasks = fields["subtasks"] item.SubTaskKeys = System.Linq.Enumerable.Cast[ JObject](subTasks).Select( lambda t: Newtonsoft.Json.Linq.Extensions. Value[String](t["key"])).ToArray[String]() items.Add(item) return items
def importJIRATasks(actionContext): from TimeCockpit.Data import EntityObject, DataContextType dc = actionContext.DataContext if dc.DataContextType != DataContextType.Server: raise ArgumentException( "Action can only be executed on a server data context.") clr.AddReference("TimeCockpit.Common") from System.Collections.Generic import List from System.Globalization import CultureInfo from TimeCockpit.Common import Logger, LogLevel from System import DateTime, String, Array, Convert from System.Text import Encoding clr.AddReference("System.Core") import System clr.ImportExtensions(System.Linq) # JIRA API class Issue(object): def __init__(self, key=None, type=None, summary=None, link=None, status=None, updated=None, timeOriginalEstimate=None, subTaskKeys=None): self.Key = key self.Type = type self.Summary = summary self.Link = link self.Status = status self.Updated = updated self.TimeOriginalEstimate = timeOriginalEstimate self.SubTaskKeys = subTaskKeys class Jira(object): def __init__(self, repository, username, password): from System import Uri self.repository = Uri(repository) self.username = username self.password = password self.requestedFields = [ "summary", "issuetype", "status", "updated", "timeoriginalestimate", "subtasks" ] def search(self, jql): clr.AddReference("System.Web") from System.Web import HttpUtility from System.Net import HttpWebRequest from System.IO import StreamReader clr.AddReference("Newtonsoft.Json") from Newtonsoft.Json import JsonTextReader from Newtonsoft.Json.Linq import JObject from System import Decimal import Newtonsoft.Json clr.ImportExtensions(Newtonsoft.Json.Linq) usernamepw = Convert.ToBase64String( Encoding.UTF8.GetBytes( String.Format("{0}:{1}", self.username, self.password))) fieldsparam = String.Join(",", self.requestedFields) requestUri = String.Format( "{0}rest/api/2/search?jql={1}&fields={2}", self.repository.AbsoluteUri, HttpUtility.UrlEncode(jql), fieldsparam) Logger.Write(LogLevel.Verbose, "Jira.Search: {0}", requestUri) request = HttpWebRequest.Create(requestUri) request.ContentType = "application/json" request.Headers.Add("Authorization", "Basic " + usernamepw) request.Method = "GET" with request.GetResponse() as response: with StreamReader(response.GetResponseStream()) as sr: with JsonTextReader(sr) as jr: result = JObject.Load(jr) issues = result["issues"] items = list() for issue in issues: item = Issue() item.Key = Newtonsoft.Json.Linq.Extensions.Value[ String](issue["key"]) fields = issue["fields"] item.Updated = Newtonsoft.Json.Linq.Extensions.Value[ DateTime](fields["updated"]) # transform seconds to hours estimate = Newtonsoft.Json.Linq.Extensions.Value[ System.Object](fields["timeoriginalestimate"]) if estimate is not None: estimate = Newtonsoft.Json.Linq.Extensions.Value[ Decimal](fields["timeoriginalestimate"]) estimate = estimate / (60.0 * 60.0) item.TimeOriginalEstimate = estimate status = fields["status"] item.Status = Newtonsoft.Json.Linq.Extensions.Value[ String](status["name"]) item.Summary = Newtonsoft.Json.Linq.Extensions.Value[ String](fields["summary"]) type = fields["issuetype"] item.Type = Newtonsoft.Json.Linq.Extensions.Value[ String](type["name"]) item.Link = self.repository.ToString( ) + "browse/" + item.Key subTasks = fields["subtasks"] item.SubTaskKeys = System.Linq.Enumerable.Cast[ JObject](subTasks).Select( lambda t: Newtonsoft.Json.Linq.Extensions. Value[String](t["key"])).ToArray[String]() items.Add(item) return items commit = True timeDelta = 0.01 jira = Jira("https://....atlassian.net/", "...", "...") jiraProjects = dc.Select( "From P In Project Where :IsNullOrEmpty(P.JiraProject) = False Select P" ) for jiraProject in jiraProjects: dc.BeginTransaction() try: jiraName = jiraProject.JiraProject Logger.Write(LogLevel.Information, "JiraImport: Handling project '{0}'", jiraName) projectUuid = jiraProject.ProjectUuid lastUpdated = dc.SelectSingleWithParams({ "Query": "From T In Task Where T.Project = @ProjectUuid Select New With { .LastUpdated = Max(T.JiraUpdated) }", "@ProjectUuid": projectUuid }).LastUpdated if lastUpdated is None: lastUpdated = DateTime(1970, 1, 1) jqlAdditionalCondition = String.Format( " and updated >= '{0}' order by updated asc", lastUpdated.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)) jql = String.Format("project='{0}'{1}", jiraName, jqlAdditionalCondition) issues = jira.search(jql).ToDictionary(lambda i: i.Key) if issues.Any(): query = String.Format( "From T In Task.Include(*) Where T.Project = @ProjectUuid And T.Code In ({0}) Select T", String.Join( ", ", issues.Select(lambda i: String.Format('"{0}"', i.Key)). ToArray())) tasks = dc.SelectWithParams({ "Query": query, "@ProjectUuid": projectUuid }).GroupBy(lambda t: t.Code).ToDictionary( lambda g: g.Key, lambda g: g.Single()) newIssues = issues.Keys.Except(tasks.Keys).ToArray() updatedIssues = issues.Keys.Except(newIssues).ToArray() Logger.Write( LogLevel.Information, "JiraImport: {0} new issues, {1} updated issues for query {2}", newIssues.Length, updatedIssues.Length, jql) for key in newIssues: issue = issues[key] task = dc.CreateTask() task.APP_BudgetInHours = issue.TimeOriginalEstimate task.APP_Code = issue.Key task.APP_Project = jiraProject task.USR_JiraLink = issue.Link task.USR_JiraStatus = issue.Status task.USR_JiraType = issue.Type task.USR_JiraUpdated = issue.Updated task.APP_Description = issue.Summary Logger.Write(LogLevel.Information, "JiraImport: Adding task {0}", key) dc.SaveObject(task) for key in updatedIssues: changed = False task = tasks[key] issue = issues[key] if task.APP_BudgetInHours <> issue.TimeOriginalEstimate: if (task.APP_BudgetInHours is None and issue.TimeOriginalEstimate is not None ) or (task.APP_BudgetInHours is not None and issue.TimeOriginalEstimate is None) or ( abs(task.APP_BudgetInHours - issue.TimeOriginalEstimate) > timeDelta): Logger.Write( LogLevel.Verbose, "JiraImport: Changed property for task {0}: {1}", key, "TimeOriginalEstimate") task.APP_BudgetInHours = issue.TimeOriginalEstimate changed = True if task.USR_JiraLink <> issue.Link: Logger.Write( LogLevel.Verbose, "JiraImport: Changed property for task {0}: {1}", key, "Link") task.USR_JiraLink = issue.Link changed = True if task.USR_JiraStatus <> issue.Status: Logger.Write( LogLevel.Verbose, "JiraImport: Changed property for task {0}: {1}", key, "Status") task.USR_JiraStatus = issue.Status changed = True if task.USR_JiraType <> issue.Type: Logger.Write( LogLevel.Verbose, "JiraImport: Changed property for task {0}: {1}", key, "Type") task.USR_JiraType = issue.Type changed = True if task.USR_JiraUpdated <> issue.Updated: Logger.Write( LogLevel.Verbose, "JiraImport: Changed property for task {0}: {1}", key, "Updated") task.USR_JiraUpdated = issue.Updated changed = True if task.APP_Description <> issue.Summary: Logger.Write( LogLevel.Verbose, "JiraImport: Changed property for task {0}: {1}", key, "Summary") task.APP_Description = issue.Summary changed = True if changed: Logger.Write(LogLevel.Information, "JiraImport: Updating task {0}", key) dc.SaveObject(task) else: Logger.Write( LogLevel.Information, "JiraImport: Skipping unchanged task {0}", key) if commit: dc.TryCommitTransaction() else: dc.TryRollbackTransaction() except System.Exception, e: dc.TryRollbackTransaction() Logger.Write( LogLevel.Warning, "JiraImport: Exception while handling {0}: {1}\r\n{2}", jiraProject.JiraProject, e.Message, e.StackTrace)
def ErrorReported(self, source, message, span, errorCode, severity): print self.error self.error += String.Format("{0}({1}:{2}): {3}: RB{4}: {5}", source.Path, span.Start.Line, span.Start.Column, severity, errorCode, message)
def get_on_chip_accumulations(): print(String.Format("{0} {1}", "Current On-Chip Accumulations:", experiment.GetValue( CameraSettings.ReadoutControlAccumulations)))
def print_device_information(): print("Experiment Device Information:") # Print model and serial number of current device for device in experiment.ExperimentDevices: print(String.Format('\t{0} {1}', device.Model, device.SerialNumber))