def main(): load('bookshelf.conf') if config('LOCALE') is not None and config('LOCALE') != '': Locale.setDefault(Locale(config('LOCALE'))) from window import BookshelfView from logic import Bookshelf UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) view = BookshelfView(Bookshelf()) screenSize = Toolkit.getDefaultToolkit().getScreenSize(); view.setLocation(screenSize.width/5, screenSize.height/5) view.setVisible(1)
def __init__(self, parent): JDialog.__init__(self, parent) self._parent = parent e = c.resource('entry') self.open_file_chooser = JFileChooser(c.config('DEFAULT_OPEN_DIRECTORY')) self.open_file_chooser.multiSelectionEnabled = 0 self.open_file_chooser.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY self.open_file_dir = c.config('DEFAULT_OPEN_DIRECTORY') self.open_file_label = JLabel(self.open_file_dir) self.save_file_chooser = JFileChooser(c.config('DEFAULT_SAVE_DIRECTORY')) self.save_file_chooser.multiSelectionEnabled = 0 self.save_file_chooser.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY self.save_file_dir = c.config('DEFAULT_SAVE_DIRECTORY') self.save_file_label = JLabel(self.save_file_dir) self.language = PyLanguageComboBox(c.config('SUPPORTED_LOCALES'), Locale.getDefault()) self.language.set_selection(Locale.getDefault().language) if c.config('MIDLET_LOCALE') is not None and c.config('MIDLET_LOCALE') != '': midlet_locale = Locale(c.config('MIDLET_LOCALE')) else: midlet_locale = Locale.getDefault() self.midlet_language = PyLanguageComboBox(c.config('SUPPORTED_LOCALES')) self.midlet_language.set_selection(midlet_locale.language) main = PyGridBagPanel(title="") main.setPreferredSize(Dimension(400, 200)) lang_panel = PyBorderPanel(west=JLabel(e['language']), east=self.language, title="") main.add(lang_panel, gridx=0, gridy=0, fill="HORIZONTAL", anchor="LINE_START", weightx=0.5, weighty=0.5) midlet_lang_panel = PyBorderPanel(west=JLabel(_d['midlet_language']), east=self.midlet_language, title="") main.add(midlet_lang_panel, gridx=0, gridy=1, fill="HORIZONTAL", anchor="LINE_START", weightx=0.5, weighty=0.5) open_panel = PyBorderPanel(west=JLabel(_d['open_dir']), east=JButton(_d['select'], actionPerformed=self.action_set_open), south=self.open_file_label, title="") main.add(open_panel, gridx=0, gridy=2, fill="HORIZONTAL", anchor="LINE_START", weightx=0.5, weighty=0.5) save_panel = PyBorderPanel(west=JLabel(_d['save_dir']), east=JButton(_d['select'], actionPerformed=self.action_set_save), south=self.save_file_label, title="") main.add(save_panel, gridx=0, gridy=3, fill="HORIZONTAL", anchor="LINE_START", weightx=0.5, weighty=0.5) self.make_folder = JCheckBox() makefolder_panel = PyBorderPanel(west=JLabel(_d['make_dir']), east=self.make_folder, title="") main.add(makefolder_panel, gridx=0, gridy=4, fill="HORIZONTAL", anchor="LINE_START", weightx=0.5, weighty=0.5) self.make_folder.selected = c.config('MAKE_FOLDER') button_panel=PyPanel([JButton(_d['save'], actionPerformed=self.action_ok), JButton(_d['discard'], actionPerformed=self.action_cancel)]) panel=PyBorderPanel(south=button_panel, west=main) self.title = _d['interface_title'] self.contentPane.add(panel)
def get_pdbredo_data(pdbids=[]): global CACHE_EXPIRED alldatapath = os.path.join(PDBfiles.CACHEDIR, os.path.basename(ALLDATA_URL)) # if not os.path.isfile(alldatapath): #Download tries = 3 dateformat = " on %a, %d %b %Y %H:%M:%S " while tries > 0: tries -= 1 if sys.platform.startswith("java"): oldlocale = Locale.getDefault() Locale.setDefault(Locale.ENGLISH) try: download = False olddate = datetime.datetime(1, 1, 1) if os.path.isfile(alldatapath): alldata = open(alldatapath, "r") for line in alldata: if "Created on" in line: olddate = datetime.datetime.strptime(line.split("+")[0].split("Created")[1], dateformat) break alldata.close() rfh = urllib2.urlopen(ALLDATA_URL) firstlines = "" for line in rfh: if download: alldata.write(line) continue firstlines += line if not download and "Created on" in line: newdate = datetime.datetime.strptime(line.split("+")[0].split("Created")[1], dateformat) if newdate <= olddate: print "%s is up to date (%s)" % (alldatapath, olddate.__str__()) CACHE_EXPIRED = False break else: CACHE_EXPIRED = True download = True alldata = open(alldatapath, "w") alldata.write(firstlines) print "Downloading %s" % ALLDATA_URL # alldata.write(rfh.read()) alldata.close() rfh.close() break except Exception, e: print "Could not download", ALLDATA_URL print e print "Retrying...", tries time.sleep(1) if sys.platform.startswith("java"): Locale.setDefault(oldlocale)
def __init__(self, parent): JDialog.__init__(self, parent) e = c.resource('entry') self.language = PyLanguageComboBox(c.config('SUPPORTED_LOCALES'), Locale.getDefault()) self.language.set_selection(c.config('DEFAULT_TEXT_LANGUAGE')) self.encoding = PyComboBox(c.SUPPORTED_ENCODINGS) self.para_start = PyComboBox([(x, x) for x in range(11)]) self.para_start.set_selection(c.config('DEFAULT_PARAGRAPH_START')) main_panel = PyGridBagPanel(title='') main_panel.add(JLabel(e['language']), gridx=0, gridy=0, anchor='LINE_START', weightx=0.5) main_panel.add(self.language, gridx=1, gridy=0, anchor='LINE_END', weightx=0.1, fill='HORIZONTAL') main_panel.add(JLabel(e['encoding']), gridx=0, gridy=1, anchor='LINE_START', weightx=0.5) main_panel.add(self.encoding, gridx=1, gridy=1, anchor='LINE_END', weightx=0.1, fill='HORIZONTAL') main_panel.add(JLabel(e['source_para_start']), gridx=0, gridy=2, anchor='LINE_START', weightx=0.5) main_panel.add(self.para_start, gridx=1, gridy=2, anchor='LINE_END', weightx=0.1, fill='HORIZONTAL') main_panel.setPreferredSize(Dimension(300, 70)) button_panel=PyPanel([JButton(_d['save'], actionPerformed=self.action_ok), JButton(_d['discard'], actionPerformed=self.action_cancel)]) panel=PyGridBagPanel(title='') panel.add(main_panel) panel.add(button_panel, gridy=1) self.title = _d['text_input_title'] self.contentPane.add(panel)
def resource(name): result = {} try: r = ResourceBundle.getBundle("properties/" + name, Locale.getDefault(), imp.getSyspathJavaLoader()) for key in r.getKeys(): result[key] = r.getString(key) except MissingResourceException, e: pass
def __init__(self, app): #name: reference code for this tool used for exmaple in 'config.cfg' self.name = self.title.lower().replace(" ", "_") if self.name in app.toolsStatus: self.isActive = app.toolsStatus[self.name] else: self.isActive = True #localization if self.isTranslated: localeDir = File.separator.join([self.app.SCRIPTDIR, "tools", "data", self.title.replace(" ", ""), "locale"]) urls = [File(localeDir).toURI().toURL()] loader = URLClassLoader(urls) currentLocale = Locale.getDefault() self.strings = ResourceBundle.getBundle("MessagesBundle", currentLocale, loader) if self.name == "favourites": self.title = self.strings.getString("Favourites") if self.name == "favourites": ref = "Favourites" else: ref = self.title.replace(" ", "") self.bigIcon = ImageIcon(File.separator.join([app.SCRIPTDIR, "tools", "data", ref, "icons", "tool_24.png"])) self.smallIcon = ImageIcon(File.separator.join([app.SCRIPTDIR, "tools", "data", ref, "icons", "tool_16.png"])) if not hasattr(self, "isLocal") or not self.isLocal: self.isLocal = False if self.name in app.toolsPrefs: self.update_preferences() if not hasattr(self, "markerPosition"): self.markerPosition = None self.views = [] for viewName, checksList in self.toolInfo.iteritems(): self.views.append(View(app, self, viewName, checksList))
def dateformat(t, format, language=None): """ Format python date to string using Java SimpleDateFormat. :param t: Python date. :returns: Format string of the date """ jt = jdate(t) if language is None: df = SimpleDateFormat(format) else: locale = Locale(language) df = SimpleDateFormat(format, locale) return df.format(jt)
def dateformat(t, format, language=None): """ Format python date to string using Java date time formatter. :param t: Python date. :returns: Format string of the date """ jt = jdate(t) if language is None: df = DateTimeFormatter.ofPattern(format) else: locale = Locale(language) df = DateTimeFormatter.ofPattern(format, locale) return df.format(jt)
def set_i18n(path=None, basename="sos.po.sos"): """Use this method to change the default i18n behavior from gettext to java ResourceBundle.getString. This is really only useful when using jython. Path is expected to be the path to a jarfile that contains the translation files (.properties)""" # Since we are trying to modify the module-level _sos variable # we have to declare it global global _sos try: from java.util import ResourceBundle, Locale rb = ResourceBundle.getBundle(basename, Locale.getDefault(), _get_classloader(path)) def _java(msg): try: return rb.getString(msg).encode('utf-8') except: return msg _sos = _java except: pass
def addForecasts(self, forecasts): self.forecastLayout.removeAllViews() self.scrollView.scrollTo(0, 0) if len(forecasts) == 0: return self.placeLabel.setText(forecasts[0].place) self.creditLabel.setText(forecasts[0].credit) firstDate = forecasts[0].from_ calendar = Calendar.getInstance() calendar.setTime(firstDate) currentDay = calendar.get(Calendar.DAY_OF_MONTH) context = self.getContext() for forecast in forecasts: # Date # Temperature Symbol Description # Wind # Get the day of the month. date = forecast.from_ calendar.setTime(date) day = calendar.get(Calendar.DAY_OF_MONTH) # Add an item for the date for the first item and any item # following a day change. if date == firstDate or day != currentDay: dateView = TextView(context) dateView.setText( calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault()) + " " + \ str(day) + " " + \ calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()) + " " + \ str(calendar.get(Calendar.YEAR))) dateView.setGravity(Gravity.CENTER) dateView.setTypeface(Typeface.create(None, Typeface.BOLD)) dateView.setBackgroundColor(self.lightBackground) dateView.setTextColor(0xff000000) self.forecastLayout.addView(dateView, self.rowLayout()) currentDay = day # Time timeString = String.format( "%02d:%02d:%02d - ", array([ calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND) ])) date = forecast.to_ calendar.setTime(date) timeString += String.format( "%02d:%02d:%02d", array([ calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND) ])) timeView = TextView(context) timeView.setText(timeString) timeView.setGravity(Gravity.CENTER) timeView.setTypeface(Typeface.create(None, Typeface.BOLD)) self.forecastLayout.addView(timeView, self.rowLayout()) # Symbol, temperature, description and wind row = RelativeLayout(context) # Symbol lp = self.itemLayout() lp.addRule(RelativeLayout.CENTER_IN_PARENT) if forecast.symbol != -1: imageView = ImageView(context) imageView.setImageResource(forecast.symbol) row.addView(imageView, lp) else: spacer = Space(context) row.addView(spacer, lp) # Temperature tempView = TextView(context) tempView.setTextSize(tempView.getTextSize() * 2) if forecast.temperatureUnit == "celsius": tempView.setText(forecast.temperature + u"\u2103") else: tempView.setText(forecast.temperature + " " + forecast.temperatureUnit) lp = self.itemLayout() lp.addRule(RelativeLayout.CENTER_VERTICAL) lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT) row.addView(tempView, lp) # Description and wind speed descLayout = LinearLayout(context) descLayout.setOrientation(LinearLayout.VERTICAL) descView = TextView(context) descView.setText(forecast.description) descLayout.addView(descView, lp) windView = TextView(context) windView.setText(forecast.windSpeed) descLayout.addView(windView, lp) lp = self.itemLayout() lp.addRule(RelativeLayout.CENTER_VERTICAL) lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT) row.addView(descLayout, lp) self.forecastLayout.addView(row, self.rowLayout())
isTemporal = True else: isDominant = True isTemporal = False else: isDominant = False isTemporal = False lpath = None if isTemporal: myPath = ".lositemp" elif isDominant: myPath = ".mcheza" else: myPath = ".lositan" for path in sys.path: if path.find(myPath) > -1 and path.find("jar") == -1 and \ path.find("libs") == -1: lpath = path if not lpath: #local mode for path in sys.path: if path.find('scratch') > -1 and path.find("jar") == -1 and \ path.find("libs") == -1: lpath = path Locale.setDefault(Locale.US) openDir() prepareFDist() styleApp() frame = createFrame() dataPath = None disablePanel(empiricalPanel, ["theta", "beta1", "beta2", "crit"])
import java.util.Locale; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); sc.useLocale(Locale.ENGLISH); Locale.setDefault(new Locale("en", "US")); while(sc.hasNext()){ double notas=0.0; double cargas=0.0; double somatoria=0.0; double somacargas=0.0; int n = sc.nextInt(); for (int i=0 ; i<n ; i++){ notas = sc.nextDouble(); cargas = sc.nextDouble(); somatoria += notas * cargas; somacargas += cargas; } double res = somatoria/(somacargas*100.00); System.out.printf("%.4f\n", res); } sc.close(); } }
def aozan_main(): """Aozan main method. """ # Define command line parser parser = OptionParser(usage='usage: ' + Globals.APP_NAME_LOWER_CASE + '.sh [options] conf_file') parser.add_option('-q', '--quiet', action='store_true', dest='quiet', default=False, help='quiet') parser.add_option('-v', '--version', action='store_true', dest='version', help='Aozan version') parser.add_option('-e', '--exit-code', action='store_true', dest='exit_code', help='Returns non zero exit code if a step fails') parser.add_option('-c', '--conf', action='store_true', dest='conf', help='Default Aozan configuration, loads before configuration file.') # Parse command line arguments (options, args) = parser.parse_args() # Print Aozan current version if options.version: print Globals.WELCOME_MSG sys.exit(0) # Print default configuration option if options.conf: print common.print_default_configuration() sys.exit(0) # If no argument print usage if len(args) < 1: parser.print_help() sys.exit(1) # Create configuration object conf = LinkedHashMap() # Set the default value in the configuration object common.set_default_conf(conf) # Use default (US) locale Locale.setDefault(Globals.DEFAULT_LOCALE) # Check if OS is Linux if not SystemUtils.isLinux(): sys.stderr.write('ERROR: Aozan can not be executed. Operating system is not Linux\n') sys.exit(1) # Check if configuration file exists conf_file = args[0] if not os.path.isfile(conf_file): sys.stderr.write('ERROR: Aozan can not be executed. Configuration file is missing: ' + \ conf_file + '\n') sys.exit(1) # Load Aozan conf file common.load_conf(conf, conf_file) # End of Aozan if aozan is not enable if common.is_conf_value_defined(AOZAN_ENABLE_KEY, 'false', conf): sys.exit(0) # Init logger try: Common.initLogger(conf[AOZAN_LOG_PATH_KEY], conf[AOZAN_LOG_LEVEL_KEY]) except AozanException, exp: common.exception_msg(exp, conf)
def __init__(self): self._cogroo = ComponentFactory.create(Locale('pt', 'BR')).createPipe() self._grammar_checker = GrammarChecker(self._cogroo)
def buildMonthYearEntry(entry): localDate = entry.getKey().minusMonths(1) return String.valueOf(localDate.getYear()) + " " + \ localDate.getMonth().getDisplayName(TextStyle.FULL, Locale.getDefault())
import java.util.*; import java.text.*; import java.util.Scanner; import java.text.NumberFormat; import java.util.Locale; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double payment = scanner.nextDouble(); scanner.close(); Locale indiaLocale = new Locale("en", "IN"); NumberFormat us = NumberFormat.getCurrencyInstance(Locale.US); NumberFormat india = NumberFormat.getCurrencyInstance(indiaLocale); NumberFormat china = NumberFormat.getCurrencyInstance(Locale.CHINA); NumberFormat france = NumberFormat.getCurrencyInstance(Locale.FRANCE); System.out.println("US: " + us.format(payment)); System.out.println("India: " + india.format(payment)); System.out.println("China: " + china.format(payment)); System.out.println("France: " + france.format(payment)); } }
def __init__(self, language_list, current_locale=Locale.getDefault()): items = [] for lang in language_list: locale_language = Locale(lang).getDisplayLanguage(current_locale) items.append((lang, locale_language.capitalize())) PyComboBox.__init__(self, items)
def __init__(self): self.SCRIPTDIR = SCRIPTDIR #Localization urls = [ File(File.separator.join([self.SCRIPTDIR, "data", "locale"])).toURI().toURL() ] loader = URLClassLoader(urls) currentLocale = Locale.getDefault() self.strings = ResourceBundle.getBundle("MessagesBundle", currentLocale, loader) #Read config self.favZone = None self.zones = None self.config = ConfigLoader(self) """Build tools instances""" self.allTools = AllTools(self).tools for tool in self.allTools: if tool.name == "favourites": self.favouritesTool = tool break self.realTools = [ tool for tool in self.allTools if tool.name not in ("favourites", "localfile") ] #remove tools disabled from config file self.tools = [ tool for tool in self.allTools if tool.isActive or tool.name in ("favourites") ] #add favourite checks to Favourites tool if "favourites" in self.toolsPrefs: favChecks = self.toolsPrefs["favourites"]["checks"] if favChecks != "": for favCheck in favChecks.split("|"): (toolName, viewName, checkName) = favCheck.split(".") for tool in self.tools: if tool.name == toolName: for view in tool.views: if view.name == viewName: for check in view.checks: if check.name == checkName: self.favouritesTool.views[ 0].checks.append(check) """Build dialog for manual reporting of false positive""" self.falsePositiveDlg = FalsePositiveDialog( Main.parent, self.strings.getString("false_positives_title"), True, self) """Build qat_script toggleDialog""" #BUG: it steals icon from validator. #Is it possible ot use an icon not from 'dialogs' dir? icon = "validator.png" self.dlg = QatDialog(self.strings.getString("qat_dialog_title"), icon, "Show ", None, 250, self) self.create_new_dataset_if_empty() Main.map.addToggleDialog(self.dlg) """Build processing dialog""" self.downloadAndReadDlg = DownloadAndReadDialog( Main.parent, self.strings.getString("download_dialog_title"), False, self) """Build quality assurance tools menu""" self.menu = QatMenu(self, "QA Tools") menu.add(self.menu) menu.repaint() """Initialization""" #Read ids of OSM objects that the user wants to be ignored self.ignore_file = File.separator.join( [self.SCRIPTDIR, "data", "ignoreids.csv"]) self.read_ignore() self.falsePositive = [] # info regarding false positive self.selectedTool = self.tools[0] self.selectedView = self.selectedTool.views[0] # first view self.selectedTableModel = self.selectedView.tableModel self.selectedChecks = [] self.downloadingChecks = [] self.clickedError = None self.errorsData = None self.zoneBbox = None # bbox of current JOSM view self.selectedError = None self.url = None # url of errors self.errorLayers = [] # list of layers with error markers self.selectionChangedFromMenuOrLayer = False self.dlg.toolsCombo.setSelectedIndex(0) print "\nINFO: Quality Assurance Tools script is running: ", self.SCRIPTVERSION # Check if using the latest version if self.checkUpdate == "on": update_checker.Updater(self, "auto")
def __init__(self): self.SCRIPTDIR = SCRIPTDIR #Localization urls = [File(File.separator.join([self.SCRIPTDIR, "data", "locale"])).toURI().toURL()] loader = URLClassLoader(urls) currentLocale = Locale.getDefault() self.strings = ResourceBundle.getBundle("MessagesBundle", currentLocale, loader) #Read config self.favZone = None self.zones = None self.config = ConfigLoader(self) """Build tools instances""" self.allTools = AllTools(self).tools for tool in self.allTools: if tool.name == "favourites": self.favouritesTool = tool break self.realTools = [tool for tool in self.allTools if tool.name not in ("favourites", "localfile")] #remove tools disabled from config file self.tools = [tool for tool in self.allTools if tool.isActive or tool.name in ("favourites")] #add favourite checks to Favourites tool if "favourites" in self.toolsPrefs: favChecks = self.toolsPrefs["favourites"]["checks"] if favChecks != "": for favCheck in favChecks.split("|"): (toolName, viewName, checkName) = favCheck.split(".") for tool in self.tools: if tool.name == toolName: for view in tool.views: if view.name == viewName: for check in view.checks: if check.name == checkName: self.favouritesTool.views[0].checks.append(check) """Build dialog for manual reporting of false positive""" self.falsePositiveDlg = FalsePositiveDialog( Main.parent, self.strings.getString("false_positives_title"), True, self) """Build qat_script toggleDialog""" #BUG: it steals icon from validator. #Is it possible ot use an icon not from 'dialogs' dir? icon = "validator.png" self.dlg = QatDialog(self.strings.getString("qat_dialog_title"), icon, "Show ", None, 250, self) self.create_new_dataset_if_empty() Main.map.addToggleDialog(self.dlg) """Build processing dialog""" self.downloadAndReadDlg = DownloadAndReadDialog(Main.parent, self.strings.getString("download_dialog_title"), False, self) """Build quality assurance tools menu""" self.menu = QatMenu(self, "QA Tools") menu.add(self.menu) menu.repaint() """Initialization""" #Read ids of OSM objects that the user wants to be ignored self.ignore_file = File.separator.join([self.SCRIPTDIR, "data", "ignoreids.csv"]) self.read_ignore() self.falsePositive = [] # info regarding false positive self.selectedTool = self.tools[0] self.selectedView = self.selectedTool.views[0] # first view self.selectedTableModel = self.selectedView.tableModel self.selectedChecks = [] self.downloadingChecks = [] self.clickedError = None self.errorsData = None self.zoneBbox = None # bbox of current JOSM view self.selectedError = None self.url = None # url of errors self.errorLayers = [] # list of layers with error markers self.selectionChangedFromMenuOrLayer = False self.dlg.toolsCombo.setSelectedIndex(0) print "\nINFO: Quality Assurance Tools script is running: ", self.SCRIPTVERSION # Check if using the latest version if self.checkUpdate == "on": update_checker.Updater(self, "auto")