prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>ErrorMessages.tsx<|end_file_name|><|fim▁begin|>import * as React from 'react'; import { FormErrorMap } from './FormErrorMap'; import { ErrorMessagesContext } from './ErrorMessagesContext'; export interface ErrorMessagesProps { <|fim▁hole|>} export default function ErrorMessages({errors, children}: ErrorMessagesProps) { return ( <ErrorMessagesContext.Provider value={{ errors: errors }}> {errors && children} </ErrorMessagesContext.Provider> ) }<|fim▁end|>
errors?: FormErrorMap children: React.ReactNode
<|file_name|>color.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution # Copyright (C)2013-2022 The MMGen Project <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ color.py: color handling for the MMGen suite """ _colors = { 'black': ( 232, (30,0) ), 'red': ( 210, (31,1) ), 'green': ( 121, (32,1) ), 'yellow': ( 229, (33,1) ), 'blue': ( 75, (34,1) ), 'magenta': ( 205, (35,1) ), 'cyan': ( 122, (36,1) ), 'pink': ( 218, (35,1) ), 'orange': ( 216, (31,1) ), 'gray': ( 246, (30,1) ), 'purple': ( 141, (35,1) ), 'brown': ( 208, (33,0) ), 'grndim': ( 108, (32,0) ), 'redbg': ( (232,210), (30,101) ), 'grnbg': ( (232,121), (30,102) ), 'blubg': ( (232,75), (30,104) ), 'yelbg': ( (232,229), (30,103) ), } def nocolor(s): return s def set_vt100(): 'hack to put term into VT100 mode under MSWin' from .globalvars import g if g.platform == 'win': from subprocess import run<|fim▁hole|> def get_terminfo_colors(term=None): from subprocess import run,PIPE cmd = ['infocmp','-0'] if term: cmd.append(term) try: cmdout = run(cmd,stdout=PIPE,check=True).stdout.decode() except: return None else: s = [e.split('#')[1] for e in cmdout.split(',') if e.startswith('colors')][0] from .util import is_hex_str if s.isdecimal(): return int(s) elif s.startswith('0x') and is_hex_str(s[2:]): return int(s[2:],16) else: return None def init_color(num_colors='auto'): assert num_colors in ('auto',8,16,256,0) import mmgen.color as self if num_colors == 'auto': import os t = os.getenv('TERM') num_colors = 256 if (t and t.endswith('256color')) or get_terminfo_colors() == 256 else 16 reset = '\033[0m' if num_colors == 0: ncc = (lambda s: s).__code__ for c in _colors: getattr(self,c).__code__ = ncc elif num_colors == 256: for c,e in _colors.items(): start = ( '\033[38;5;{};1m'.format(e[0]) if type(e[0]) == int else '\033[38;5;{};48;5;{};1m'.format(*e[0]) ) getattr(self,c).__code__ = eval(f'(lambda s: "{start}" + s + "{reset}").__code__') elif num_colors in (8,16): for c,e in _colors.items(): start = ( '\033[{}m'.format(e[1][0]) if e[1][1] == 0 else '\033[{};{}m'.format(*e[1]) ) getattr(self,c).__code__ = eval(f'(lambda s: "{start}" + s + "{reset}").__code__') set_vt100() for _c in _colors: exec(f'{_c} = lambda s: s')<|fim▁end|>
run([],shell=True)
<|file_name|>lnbin.py<|end_file_name|><|fim▁begin|>import numpy as np #x must be a np array def lnbin(x, BinNum): """ Logarithmically bins a numpy array, returns (midpoints, Freq) This function take the input of a data vector x, which is to be binned; it also takes in the amount bins one would like the data binned into. The output is two vectors, one containing the normalised frequency of each bin (Freq), the other, the midpoint of each bin (midpts). Added and error to the binned frequency: eFreq (As of June 30 2010). If this option is not required, just call the function without including the third out put; i.e.: [midpts Freq]=lnbin(x,BinNum). Updated 2/6/14 to change the min to scale automatically """ if type(x) != np.ndarray: try: x = np.array(x) except: print 'Improper input format!' raise x = np.sort(x) i = 0<|fim▁hole|> percent_binned = float((x.size-(i+1))) / x.size*100 #print 'Percentage of input vec binned {}'.format(percent_binned) FPT = x[i:] LFPT = np.log(FPT) max1 = np.log( np.ceil(np.amax(FPT))) #min1 = 1 min1 = np.log(np.floor(np.min(FPT))) LFreq = np.zeros((BinNum, 1)) LTime = np.zeros((BinNum, 1)) Lends = np.zeros((BinNum, 2)) step = (max1-min1) / BinNum #LOG Binning Data ########################### for i in range(FPT.size): for k in range(BinNum): if( k*step+min1 <= LFPT[i] and LFPT[i] < (k+1)*step+min1): LFreq[k] += 1 #check LFreq on the first bin LTime[k] = (k+1)*step-(0.5*step)+min1 Lends[k, 0] = k*step+min1 Lends[k, 1] = (k+1)*step+min1 ends = np.exp(Lends) widths = ends[:,1] - ends[:,0] Freq = LFreq.T / widths / x.size eFreq = 1.0 / np.sqrt(LFreq) * Freq midpts = np.exp(LTime) return (midpts[:,0], Freq.T[:,0])<|fim▁end|>
while x[i] <= 0: i += 1
<|file_name|>builder.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Appcelerator Titanium Mobile # Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved. # Licensed under the terms of the Apache Public License # Please see the LICENSE included with this distribution for details. # # General builder script for staging, packaging, deploying, # and debugging Titanium Mobile applications on Android # import os, sys, subprocess, shutil, time, signal, string, platform, re, glob, hashlib, imp, inspect import run, avd, prereq, zipfile, tempfile, fnmatch, codecs, traceback, simplejson from mako.template import Template from os.path import splitext from compiler import Compiler from os.path import join, splitext, split, exists from shutil import copyfile from xml.dom.minidom import parseString from tilogger import * from datetime import datetime, timedelta template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename)) top_support_dir = os.path.dirname(template_dir) sys.path.append(top_support_dir) sys.path.append(os.path.join(top_support_dir, 'common')) sys.path.append(os.path.join(top_support_dir, 'module')) from tiapp import * from android import Android from androidsdk import AndroidSDK from deltafy import Deltafy, Delta from css import csscompiler from module import ModuleDetector import localecompiler import fastdev ignoreFiles = ['.gitignore', '.cvsignore', '.DS_Store']; ignoreDirs = ['.git','.svn','_svn', 'CVS']; android_avd_hw = {'hw.camera': 'yes', 'hw.gps':'yes'} res_skips = ['style'] log = None # Copied from frameworks/base/tools/aapt/Package.cpp uncompressed_types = [ ".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg", ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl", ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2", ".amr", ".awb", ".wma", ".wmv" ] MIN_API_LEVEL = 7 def render_template_with_tiapp(template_text, tiapp_obj): t = Template(template_text) return t.render(tiapp=tiapp_obj) def remove_ignored_dirs(dirs): for d in dirs: if d in ignoreDirs: dirs.remove(d) # ZipFile.extractall introduced in Python 2.6, so this is workaround for earlier # versions def zip_extractall(zfile, target_dir): file_infos = zfile.infolist() for info in file_infos: if info.file_size > 0: file_path = os.path.join(target_dir, os.path.normpath(info.filename)) parent_path = os.path.dirname(file_path) if not os.path.exists(parent_path): os.makedirs(parent_path) out_file = open(file_path, "wb") out_file.write(zfile.read(info.filename)) out_file.close() def dequote(s): if s[0:1] == '"': return s[1:-1] return s def pipe(args1,args2): p1 = subprocess.Popen(args1, stdout=subprocess.PIPE) p2 = subprocess.Popen(args2, stdin=p1.stdout, stdout=subprocess.PIPE) return p2.communicate()[0] def read_properties(propFile, separator=":= "): propDict = dict() for propLine in propFile: propDef = propLine.strip() if len(propDef) == 0: continue if propDef[0] in ( '!', '#' ): continue punctuation= [ propDef.find(c) for c in separator ] + [ len(propDef) ] found= min( [ pos for pos in punctuation if pos != -1 ] ) name= propDef[:found].rstrip() value= propDef[found:].lstrip(separator).rstrip() propDict[name]= value propFile.close() return propDict def info(msg): log.info(msg) def debug(msg): log.debug(msg) def warn(msg): log.warn(msg) def trace(msg): log.trace(msg) def error(msg): log.error(msg) def copy_all(source_folder, dest_folder, ignore_dirs=[], ignore_files=[], ignore_exts=[], one_time_msg=""): msg_shown = False for root, dirs, files in os.walk(source_folder): for d in dirs: if d in ignore_dirs: dirs.remove(d) for f in files: if f in ignore_files: continue ext = os.path.splitext(f)[1] if ext in ignore_exts: continue if one_time_msg and not msg_shown: info(one_time_msg) msg_shown = True from_ = os.path.join(root, f) to_ = from_.replace(source_folder, dest_folder, 1) to_directory = os.path.split(to_)[0] if not os.path.exists(to_directory): os.makedirs(to_directory) shutil.copyfile(from_, to_) def remove_orphaned_files(source_folder, target_folder): is_res = source_folder.endswith('Resources') or source_folder.endswith('Resources' + os.sep) for root, dirs, files in os.walk(target_folder): for f in files: full = os.path.join(root, f) rel = full.replace(target_folder, '') if rel[0] == os.sep: rel = rel[1:] is_orphan = False if not os.path.exists(os.path.join(source_folder, rel)): is_orphan = True # But it could be under android/... too (platform-specific) if is_orphan and is_res: if os.path.exists(os.path.join(source_folder, 'android', rel)): is_orphan = False if is_orphan: os.remove(full) def is_resource_drawable(path): if re.search("android/images/(high|medium|low|res-[^/]+)/", path.replace(os.sep, "/")): return True else: return False def resource_drawable_folder(path): if not is_resource_drawable(path): return None else: pattern = r'/android/images/(high|medium|low|res-[^/]+)/' match = re.search(pattern, path.replace(os.sep, "/")) if not match.groups(): return None folder = match.groups()[0] if re.match('high|medium|low', folder): return 'drawable-%sdpi' % folder[0] else: return 'drawable-%s' % folder.replace('res-', '') class Builder(object): def __init__(self, name, sdk, project_dir, support_dir, app_id): self.top_dir = project_dir self.project_tiappxml = os.path.join(self.top_dir,'tiapp.xml') self.project_dir = os.path.join(project_dir,'build','android') self.res_dir = os.path.join(self.project_dir,'res') self.platform_dir = os.path.join(project_dir, 'platform', 'android') self.project_src_dir = os.path.join(self.project_dir, 'src') self.project_gen_dir = os.path.join(self.project_dir, 'gen') self.name = name self.app_id = app_id self.support_dir = support_dir self.compiled_files = [] self.force_rebuild = False self.debugger_host = None self.debugger_port = -1 self.fastdev_port = -1 self.fastdev = False temp_tiapp = TiAppXML(self.project_tiappxml) if temp_tiapp and temp_tiapp.android and 'tool-api-level' in temp_tiapp.android: self.tool_api_level = int(temp_tiapp.android['tool-api-level']) else: self.tool_api_level = MIN_API_LEVEL self.sdk = AndroidSDK(sdk, self.tool_api_level) self.tiappxml = temp_tiapp self.set_java_commands() # start in 1.4, you no longer need the build/android directory # if missing, we'll create it on the fly if not os.path.exists(self.project_dir) or not os.path.exists(os.path.join(self.project_dir,'AndroidManifest.xml')): android_creator = Android(name, app_id, self.sdk, None, self.java) parent_dir = os.path.dirname(self.top_dir) if os.path.exists(self.top_dir): android_creator.create(parent_dir, project_dir=self.top_dir, build_time=True) else: android_creator.create(parent_dir) self.force_rebuild = True sys.stdout.flush() # we place some files in the users home if platform.system() == "Windows": self.home_dir = os.path.join(os.environ['USERPROFILE'], '.titanium') self.android_home_dir = os.path.join(os.environ['USERPROFILE'], '.android') else: self.home_dir = os.path.join(os.path.expanduser('~'), '.titanium') self.android_home_dir = os.path.join(os.path.expanduser('~'), '.android') if not os.path.exists(self.home_dir): os.makedirs(self.home_dir) self.sdcard = os.path.join(self.home_dir,'android2.sdcard') self.classname = Android.strip_classname(self.name) def set_java_commands(self): self.jarsigner = "jarsigner" self.javac = "javac" self.java = "java" if platform.system() == "Windows": if os.environ.has_key("JAVA_HOME"): home_jarsigner = os.path.join(os.environ["JAVA_HOME"], "bin", "jarsigner.exe") home_javac = os.path.join(os.environ["JAVA_HOME"], "bin", "javac.exe") home_java = os.path.join(os.environ["JAVA_HOME"], "bin", "java.exe") found = True # TODO Document this path and test properly under windows if os.path.exists(home_jarsigner): self.jarsigner = home_jarsigner else: # Expected but not found found = False error("Required jarsigner not found") if os.path.exists(home_javac): self.javac = home_javac else: error("Required javac not found") found = False if os.path.exists(home_java): self.java = home_java else: error("Required java not found") found = False if found == False: error("One or more required files not found - please check your JAVA_HOME environment variable") sys.exit(1) else: found = False for path in os.environ['PATH'].split(os.pathsep): if os.path.exists(os.path.join(path, 'jarsigner.exe')) and os.path.exists(os.path.join(path, 'javac.exe')): self.jarsigner = os.path.join(path, 'jarsigner.exe') self.javac = os.path.join(path, 'javac.exe') self.java = os.path.join(path, 'java.exe') found = True break if not found: error("Error locating JDK: set $JAVA_HOME or put javac and jarsigner on your $PATH") sys.exit(1) def wait_for_home(self, type): max_wait = 20 attempts = 0 while True: processes = self.sdk.list_processes(['-%s' % type]) found_home = False for process in processes: if process["name"] == "android.process.acore": found_home = True break if found_home: break attempts += 1 if attempts == max_wait: error("Timed out waiting for android.process.acore") return False time.sleep(1) return True def wait_for_device(self, type): debug("Waiting for device to be ready ...") t = time.time() max_wait = 30 max_zero = 6 attempts = 0 zero_attempts = 0 timed_out = True no_devices = False while True: devices = self.sdk.list_devices() trace("adb devices returned %s devices/emulators" % len(devices)) if len(devices) > 0: found = False for device in devices: if type == "e" and device.is_emulator() and not device.is_offline(): found = True elif type == "d" and device.is_device(): found = True if found: timed_out = False break else: zero_attempts += 1 try: time.sleep(5) # for some reason KeyboardInterrupts get caught here from time to time except KeyboardInterrupt: pass attempts += 1 if attempts == max_wait: break elif zero_attempts == max_zero: no_devices = True break if timed_out: if type == "e": device = "emulator" extra_message = "you may need to close the emulator and try again" else: device = "device" extra_message = "you may try reconnecting the USB cable" error("Timed out waiting for %s to be ready, %s" % (device, extra_message)) if no_devices: sys.exit(1) return False debug("Device connected... (waited %d seconds)" % (attempts*5)) duration = time.time() - t debug("waited %f seconds on emulator to get ready" % duration) if duration > 1.0: info("Waiting for the Android Emulator to become available") return self.wait_for_home(type) #time.sleep(20) # give it a little more time to get installed return True def create_avd(self,avd_id,avd_skin): name = "titanium_%s_%s" % (avd_id,avd_skin) name = name.replace(' ', '_') if not os.path.exists(self.home_dir): os.makedirs(self.home_dir) avd_path = os.path.join(self.android_home_dir, 'avd') my_avd = os.path.join(avd_path,"%s.avd" % name) own_sdcard = os.path.join(self.home_dir, '%s.sdcard' % name) if not os.path.exists(my_avd) or os.path.exists(own_sdcard): # starting with 1.7.2, when we create a new avd, give it its own # SDCard as well. self.sdcard = own_sdcard if not os.path.exists(self.sdcard): info("Creating 64M SD card for use in Android emulator") run.run([self.sdk.get_mksdcard(), '64M', self.sdcard]) if not os.path.exists(my_avd): info("Creating new Android Virtual Device (%s %s)" % (avd_id,avd_skin)) inputgen = os.path.join(template_dir,'input.py') pipe([sys.executable, inputgen], [self.sdk.get_android(), '--verbose', 'create', 'avd', '--name', name, '--target', avd_id, '-s', avd_skin, '--force', '--sdcard', self.sdcard]) inifile = os.path.join(my_avd,'config.ini') inifilec = open(inifile,'r').read() inifiledata = open(inifile,'w') inifiledata.write(inifilec) # TODO - Document options for hw_option in android_avd_hw.keys(): inifiledata.write("%s=%s\n" % (hw_option, android_avd_hw[hw_option])) inifiledata.close() return name def run_emulator(self,avd_id,avd_skin): info("Launching Android emulator...one moment") debug("From: " + self.sdk.get_emulator()) debug("SDCard: " + self.sdcard) debug("AVD ID: " + avd_id) debug("AVD Skin: " + avd_skin) debug("SDK: " + sdk_dir) # make sure adb is running on windows, else XP can lockup the python # process when adb runs first time if platform.system() == "Windows": run.run([self.sdk.get_adb(), "start-server"], True, ignore_output=True) devices = self.sdk.list_devices() for device in devices: if device.is_emulator() and device.get_port() == 5560: info("Emulator is running.") sys.exit() # this will create an AVD on demand or re-use existing one if already created avd_name = self.create_avd(avd_id,avd_skin) # start the emulator emulator_cmd = [ self.sdk.get_emulator(), '-avd', avd_name, '-port', '5560', '-sdcard', self.sdcard, '-logcat', '*:d,*', '-no-boot-anim', '-partition-size', '128' # in between nexusone and droid ] debug(' '.join(emulator_cmd)) p = subprocess.Popen(emulator_cmd) def handler(signum, frame): debug("signal caught: %d" % signum) if not p == None: debug("calling emulator kill on %d" % p.pid) if platform.system() == "Windows": os.system("taskkill /F /T /PID %i" % p.pid) else: os.kill(p.pid, signal.SIGTERM) if platform.system() != "Windows": signal.signal(signal.SIGHUP, handler) signal.signal(signal.SIGQUIT, handler) signal.signal(signal.SIGINT, handler) signal.signal(signal.SIGABRT, handler) signal.signal(signal.SIGTERM, handler) # give it some time to exit prematurely time.sleep(1) rc = p.poll() if rc != None: handler(3,None) sys.exit(rc) # wait for the emulator to finish try: rc = p.wait() except OSError: handler(3,None) info("Android Emulator has exited") sys.exit(rc) def check_file_exists(self, path): output = self.run_adb('shell', 'ls', path) if output != None: if output.find("No such file or directory") == -1 \ and output.find("error: device offline") == -1: return True return False def is_app_installed(self): return self.check_file_exists('/data/app/%s*.apk' % self.app_id) <|fim▁hole|> return self.check_file_exists(self.sdcard_resources+'/app.js') def include_path(self, path, isfile): if not isfile and os.path.basename(path) in ignoreDirs: return False elif isfile and os.path.basename(path) in ignoreFiles: return False return True def warn_dupe_drawable_folders(self): tocheck = ('high', 'medium', 'low') image_parent = os.path.join(self.top_dir, 'Resources', 'android', 'images') for check in tocheck: if os.path.exists(os.path.join(image_parent, check)) and os.path.exists(os.path.join(image_parent, 'res-%sdpi' % check[0])): warn('You have both an android/images/%s folder and an android/images/res-%sdpi folder. Files from both of these folders will end up in res/drawable-%sdpi. If two files are named the same, there is no guarantee which one will be copied last and therefore be the one the application uses. You should use just one of these folders to avoid conflicts.' % (check, check[0], check[0])) def copy_module_platform_folders(self): for module in self.modules: platform_folder = os.path.join(module.path, 'platform', 'android') if os.path.exists(platform_folder): copy_all(platform_folder, self.project_dir, one_time_msg="Copying platform-specific files for '%s' module" % module.manifest.name) def copy_project_platform_folder(self, ignore_dirs=[], ignore_files=[]): if not os.path.exists(self.platform_dir): return copy_all(self.platform_dir, self.project_dir, ignore_dirs, ignore_files, one_time_msg="Copying platform-specific files ...") def copy_resource_drawables(self): debug('Processing Android resource drawables') def make_resource_drawable_filename(orig): normalized = orig.replace(os.sep, "/") matches = re.search("/android/images/(high|medium|low|res-[^/]+)/(?P<chopped>.*$)", normalized) if matches and matches.groupdict() and 'chopped' in matches.groupdict(): chopped = matches.groupdict()['chopped'].lower() for_hash = chopped if for_hash.endswith('.9.png'): for_hash = for_hash[:-6] + '.png' extension = "" without_extension = chopped if re.search("\\..*$", chopped): if chopped.endswith('.9.png'): extension = '9.png' without_extension = chopped[:-6] else: extension = chopped.split(".")[-1] without_extension = chopped[:-(len(extension)+1)] cleaned_without_extension = re.sub(r'[^a-z0-9_]', '_', without_extension) cleaned_extension = re.sub(r'[^a-z0-9\._]', '_', extension) result = cleaned_without_extension[:80] + "_" + hashlib.md5(for_hash).hexdigest()[:10] if extension: result += "." + extension return result else: trace("Regexp for resource drawable file %s failed" % orig) return None def delete_resource_drawable(orig): folder = resource_drawable_folder(orig) res_file = os.path.join(self.res_dir, folder, make_resource_drawable_filename(orig)) if os.path.exists(res_file): try: trace("DELETING FILE: %s" % res_file) os.remove(res_file) except: warn('Unable to delete %s: %s. Execution will continue.' % (res_file, sys.exc_info()[0])) def copy_resource_drawable(orig): partial_folder = resource_drawable_folder(orig) if not partial_folder: trace("Could not copy %s; resource folder not determined" % orig) return dest_folder = os.path.join(self.res_dir, partial_folder) dest_filename = make_resource_drawable_filename(orig) if dest_filename is None: return dest = os.path.join(dest_folder, dest_filename) if not os.path.exists(dest_folder): os.makedirs(dest_folder) trace("COPYING FILE: %s => %s" % (orig, dest)) shutil.copy(orig, dest) fileset = [] if self.force_rebuild or self.deploy_type == 'production' or \ (self.js_changed and not self.fastdev): for root, dirs, files in os.walk(os.path.join(self.top_dir, "Resources")): remove_ignored_dirs(dirs) for f in files: if f in ignoreFiles: continue path = os.path.join(root, f) if is_resource_drawable(path) and f != 'default.png': fileset.append(path) else: if self.project_deltas: for delta in self.project_deltas: path = delta.get_path() if is_resource_drawable(path): if delta.get_status() == Delta.DELETED: delete_resource_drawable(path) else: fileset.append(path) if len(fileset) == 0: return False for f in fileset: copy_resource_drawable(f) return True def copy_project_resources(self): info("Copying project resources..") resources_dir = os.path.join(self.top_dir, 'Resources') android_resources_dir = os.path.join(resources_dir, 'android') self.project_deltafy = Deltafy(resources_dir, include_callback=self.include_path) self.project_deltas = self.project_deltafy.scan() self.js_changed = False tiapp_delta = self.project_deltafy.scan_single_file(self.project_tiappxml) self.tiapp_changed = tiapp_delta is not None if self.tiapp_changed or self.force_rebuild: info("Detected tiapp.xml change, forcing full re-build...") # force a clean scan/copy when the tiapp.xml has changed self.project_deltafy.clear_state() self.project_deltas = self.project_deltafy.scan() # rescan tiapp.xml so it doesn't show up as created next time around self.project_deltafy.scan_single_file(self.project_tiappxml) def strip_slash(s): if s[0:1]=='/' or s[0:1]=='\\': return s[1:] return s def make_relative(path, relative_to, prefix=None): relative_path = strip_slash(path[len(relative_to):]) if prefix is not None: return os.path.join(prefix, relative_path) return relative_path for delta in self.project_deltas: path = delta.get_path() if re.search("android/images/(high|medium|low|res-[^/]+)/", path.replace(os.sep, "/")): continue # density images are handled later if delta.get_status() == Delta.DELETED and path.startswith(android_resources_dir): shared_path = path.replace(android_resources_dir, resources_dir, 1) if os.path.exists(shared_path): dest = make_relative(shared_path, resources_dir, self.assets_resources_dir) trace("COPYING FILE: %s => %s (platform-specific file was removed)" % (shared_path, dest)) shutil.copy(shared_path, dest) if delta.get_status() != Delta.DELETED: if path.startswith(android_resources_dir): dest = make_relative(path, android_resources_dir, self.assets_resources_dir) else: # don't copy it if there is an android-specific file if os.path.exists(path.replace(resources_dir, android_resources_dir, 1)): continue dest = make_relative(path, resources_dir, self.assets_resources_dir) # check to see if this is a compiled file and if so, don't copy if dest in self.compiled_files: continue if path.startswith(os.path.join(resources_dir, "iphone")) or path.startswith(os.path.join(resources_dir, "blackberry")): continue parent = os.path.dirname(dest) if not os.path.exists(parent): os.makedirs(parent) trace("COPYING %s FILE: %s => %s" % (delta.get_status_str(), path, dest)) shutil.copy(path, dest) if (path.startswith(resources_dir) or path.startswith(android_resources_dir)) and path.endswith(".js"): self.js_changed = True # copy to the sdcard in development mode if self.sdcard_copy and self.app_installed and (self.deploy_type == 'development' or self.deploy_type == 'test'): if path.startswith(android_resources_dir): relative_path = make_relative(delta.get_path(), android_resources_dir) else: relative_path = make_relative(delta.get_path(), resources_dir) relative_path = relative_path.replace("\\", "/") self.run_adb('push', delta.get_path(), "%s/%s" % (self.sdcard_resources, relative_path)) def generate_android_manifest(self,compiler): self.generate_localizations() # NOTE: these are built-in permissions we need -- we probably need to refine when these are needed too permissions_required = ['INTERNET','ACCESS_WIFI_STATE','ACCESS_NETWORK_STATE', 'WRITE_EXTERNAL_STORAGE'] GEO_PERMISSION = [ 'ACCESS_COARSE_LOCATION', 'ACCESS_FINE_LOCATION', 'ACCESS_MOCK_LOCATION'] CONTACTS_PERMISSION = ['READ_CONTACTS'] VIBRATE_PERMISSION = ['VIBRATE'] CAMERA_PERMISSION = ['CAMERA'] WALLPAPER_PERMISSION = ['SET_WALLPAPER'] # this is our module method to permission(s) trigger - for each method on the left, require the permission(s) on the right permission_mapping = { # GEO 'Geolocation.watchPosition' : GEO_PERMISSION, 'Geolocation.getCurrentPosition' : GEO_PERMISSION, 'Geolocation.watchHeading' : GEO_PERMISSION, 'Geolocation.getCurrentHeading' : GEO_PERMISSION, # MEDIA 'Media.vibrate' : VIBRATE_PERMISSION, 'Media.showCamera' : CAMERA_PERMISSION, # CONTACTS 'Contacts.createContact' : CONTACTS_PERMISSION, 'Contacts.saveContact' : CONTACTS_PERMISSION, 'Contacts.removeContact' : CONTACTS_PERMISSION, 'Contacts.addContact' : CONTACTS_PERMISSION, 'Contacts.getAllContacts' : CONTACTS_PERMISSION, 'Contacts.showContactPicker' : CONTACTS_PERMISSION, 'Contacts.showContacts' : CONTACTS_PERMISSION, 'Contacts.getPersonByID' : CONTACTS_PERMISSION, 'Contacts.getPeopleWithName' : CONTACTS_PERMISSION, 'Contacts.getAllPeople' : CONTACTS_PERMISSION, 'Contacts.getAllGroups' : CONTACTS_PERMISSION, 'Contacts.getGroupByID' : CONTACTS_PERMISSION, # WALLPAPER 'Media.Android.setSystemWallpaper' : WALLPAPER_PERMISSION, } VIDEO_ACTIVITY = """<activity android:name="ti.modules.titanium.media.TiVideoActivity" android:configChanges="keyboardHidden|orientation" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:launchMode="singleTask" />""" MAP_ACTIVITY = """<activity android:name="ti.modules.titanium.map.TiMapActivity" android:configChanges="keyboardHidden|orientation" android:launchMode="singleTask" /> <uses-library android:name="com.google.android.maps" />""" FACEBOOK_ACTIVITY = """<activity android:name="ti.modules.titanium.facebook.FBActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" />""" CAMERA_ACTIVITY = """<activity android:name="ti.modules.titanium.media.TiCameraActivity" android:configChanges="keyboardHidden|orientation" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />""" activity_mapping = { # MEDIA 'Media.createVideoPlayer' : VIDEO_ACTIVITY, 'Media.showCamera' : CAMERA_ACTIVITY, # MAPS 'Map.createView' : MAP_ACTIVITY, # FACEBOOK 'Facebook.setup' : FACEBOOK_ACTIVITY, 'Facebook.login' : FACEBOOK_ACTIVITY, 'Facebook.createLoginButton' : FACEBOOK_ACTIVITY, } # this is a map of our APIs to ones that require Google APIs to be available on the device google_apis = { "Map.createView" : True } activities = [] # figure out which permissions we need based on the used module methods for mn in compiler.module_methods: try: perms = permission_mapping[mn] if perms: for perm in perms: try: permissions_required.index(perm) except: permissions_required.append(perm) except: pass try: mappings = activity_mapping[mn] try: if google_apis[mn] and not self.google_apis_supported: warn("Google APIs detected but a device has been selected that doesn't support them. The API call to Titanium.%s will fail using '%s'" % (mn,my_avd['name'])) continue except: pass try: activities.index(mappings) except: activities.append(mappings) except: pass # Javascript-based activities defined in tiapp.xml if self.tiapp and self.tiapp.android and 'activities' in self.tiapp.android: tiapp_activities = self.tiapp.android['activities'] for key in tiapp_activities: activity = tiapp_activities[key] if not 'url' in activity: continue activity_name = self.app_id + '.' + activity['classname'] activity_str = '<activity \n\t\t\tandroid:name="%s"' % activity_name for subkey in activity: if subkey not in ('nodes', 'name', 'url', 'options', 'classname', 'android:name'): activity_str += '\n\t\t\t%s="%s"' % (subkey, activity[subkey]) if 'android:config' not in activity: activity_str += '\n\t\t\tandroid:configChanges="keyboardHidden|orientation"' if 'nodes' in activity: activity_str += '>' for node in activity['nodes']: activity_str += '\n\t\t\t\t' + node.toxml() activities.append(activity_str + '\n\t\t</activity>\n') else: activities.append(activity_str + '\n\t\t/>\n') activities = set(activities) services = [] # Javascript-based services defined in tiapp.xml if self.tiapp and self.tiapp.android and 'services' in self.tiapp.android: tiapp_services = self.tiapp.android['services'] for key in tiapp_services: service = tiapp_services[key] if not 'url' in service: continue service_name = self.app_id + '.' + service['classname'] service_str = '<service \n\t\t\tandroid:name="%s"' % service_name for subkey in service: if subkey not in ('nodes', 'service_type', 'type', 'name', 'url', 'options', 'classname', 'android:name'): service_str += '\n\t\t\t%s="%s"' % (subkey, service[subkey]) if 'nodes' in service: service_str += '>' for node in service['nodes']: service_str += '\n\t\t\t\t' + node.toxml() services.append(service_str + '\n\t\t</service>\n') else: services.append(service_str + '\n\t\t/>\n') self.use_maps = False self.res_changed = False iconname = self.tiapp.properties['icon'] iconpath = os.path.join(self.assets_resources_dir, iconname) iconext = os.path.splitext(iconpath)[1] res_drawable_dest = os.path.join(self.project_dir, 'res','drawable') if not os.path.exists(res_drawable_dest): os.makedirs(res_drawable_dest) default_icon = os.path.join(self.support_resources_dir, 'default.png') dest_icon = os.path.join(res_drawable_dest, 'appicon%s' % iconext) if Deltafy.needs_update(iconpath, dest_icon): self.res_changed = True debug("copying app icon: %s" % iconpath) shutil.copy(iconpath, dest_icon) elif Deltafy.needs_update(default_icon, dest_icon): self.res_changed = True debug("copying default app icon") shutil.copy(default_icon, dest_icon) # make our Titanium theme for our icon res_values_dir = os.path.join(self.project_dir, 'res','values') if not os.path.exists(res_values_dir): os.makedirs(res_values_dir) theme_xml = os.path.join(res_values_dir,'theme.xml') if not os.path.exists(theme_xml): self.res_changed = True debug('generating theme.xml') theme_file = open(theme_xml, 'w') theme_flags = "Theme" # We need to treat the default values for fulscreen and # navbar-hidden the same as android.py does -- false for both. theme_fullscreen = False theme_navbarhidden = False if (self.tiapp.properties.get("fullscreen") == "true" or self.tiapp.properties.get("statusbar-hidden") == "true"): theme_fullscreen = True elif self.tiapp.properties.get("navbar-hidden") == "true": theme_navbarhidden = True if theme_fullscreen: theme_flags += ".NoTitleBar.Fullscreen" elif theme_navbarhidden: theme_flags += ".NoTitleBar" # Wait, one exception. If you want the notification area (very # top of screen) hidden, but want the title bar in the app, # there's no theme for that. So we have to use the default theme (no flags) # and when the application code starts running, the adjustments are then made. # Only do this when the properties are explicitly set, so as to avoid changing # old default behavior. if theme_flags.endswith('.Fullscreen') and \ self.tiapp.properties.get("navbar-hidden") == 'false' and \ ('fullscreen' in self.tiapp.explicit_properties or \ 'statusbar-hidden' in self.tiapp.explicit_properties) and \ 'navbar-hidden' in self.tiapp.explicit_properties: theme_flags = 'Theme' TITANIUM_THEME="""<?xml version="1.0" encoding="utf-8"?> <resources> <style name="Theme.Titanium" parent="android:%s"> <item name="android:windowBackground">@drawable/background</item> </style> </resources> """ % theme_flags theme_file.write(TITANIUM_THEME) theme_file.close() # create our background image which acts as splash screen during load resources_dir = os.path.join(self.top_dir, 'Resources') android_images_dir = os.path.join(resources_dir, 'android', 'images') # look for density-specific default.png's first if os.path.exists(android_images_dir): pattern = r'/android/images/(high|medium|low|res-[^/]+)/default.png' for root, dirs, files in os.walk(android_images_dir): remove_ignored_dirs(dirs) for f in files: if f in ignoreFiles: continue path = os.path.join(root, f) if re.search(pattern, path.replace(os.sep, "/")): res_folder = resource_drawable_folder(path) debug('found %s splash screen at %s' % (res_folder, path)) dest_path = os.path.join(self.res_dir, res_folder) dest_file = os.path.join(dest_path, 'background.png') if not os.path.exists(dest_path): os.makedirs(dest_path) if Deltafy.needs_update(path, dest_file): self.res_changed = True debug('copying %s splash screen to %s' % (path, dest_file)) shutil.copy(path, dest_file) default_png = os.path.join(self.assets_resources_dir, 'default.png') support_default_png = os.path.join(self.support_resources_dir, 'default.png') background_png = os.path.join(self.project_dir, 'res','drawable','background.png') if os.path.exists(default_png) and Deltafy.needs_update(default_png, background_png): self.res_changed = True debug("found splash screen at %s" % os.path.abspath(default_png)) shutil.copy(default_png, background_png) elif Deltafy.needs_update(support_default_png, background_png): self.res_changed = True debug("copying default splash screen") shutil.copy(support_default_png, background_png) android_manifest = os.path.join(self.project_dir, 'AndroidManifest.xml') android_manifest_to_read = android_manifest # NOTE: allow the user to use their own custom AndroidManifest if they put a file named # AndroidManifest.xml in platform/android, in which case all bets are off is_custom = False # Catch people who may have it in project root (un-released 1.4.x android_native_refactor branch users) if os.path.exists(os.path.join(self.top_dir, 'AndroidManifest.xml')): warn('AndroidManifest.xml file in the project root is ignored. Move it to platform/android if you want it to be your custom manifest.') android_custom_manifest = os.path.join(self.project_dir, 'AndroidManifest.custom.xml') if not os.path.exists(android_custom_manifest): android_custom_manifest = os.path.join(self.platform_dir, 'AndroidManifest.xml') else: warn('Use of AndroidManifest.custom.xml is deprecated. Please put your custom manifest as "AndroidManifest.xml" in the "platform/android" directory if you do not need to compile for versions < 1.5') if os.path.exists(android_custom_manifest): android_manifest_to_read = android_custom_manifest is_custom = True info("Detected custom ApplicationManifest.xml -- no Titanium version migration supported") default_manifest_contents = self.android.render_android_manifest() custom_manifest_contents = None if is_custom: custom_manifest_contents = open(android_manifest_to_read,'r').read() manifest_xml = '' def get_manifest_xml(tiapp, template_obj=None): xml = '' if 'manifest' in tiapp.android_manifest: for manifest_el in tiapp.android_manifest['manifest']: # since we already track permissions in another way, go ahead and us e that if manifest_el.nodeName == 'uses-permission' and manifest_el.hasAttribute('android:name'): if manifest_el.getAttribute('android:name').split('.')[-1] not in permissions_required: perm_val = manifest_el.getAttribute('android:name') if template_obj is not None and "${" in perm_val: perm_val = render_template_with_tiapp(perm_val, template_obj) permissions_required.append(perm_val) elif manifest_el.nodeName not in ('supports-screens', 'uses-sdk'): this_xml = manifest_el.toprettyxml() if template_obj is not None and "${" in this_xml: this_xml = render_template_with_tiapp(this_xml, template_obj) xml += this_xml return xml application_xml = '' def get_application_xml(tiapp, template_obj=None): xml = '' if 'application' in tiapp.android_manifest: for app_el in tiapp.android_manifest['application']: this_xml = app_el.toxml() if template_obj is not None and "${" in this_xml: this_xml = render_template_with_tiapp(this_xml, template_obj) xml += this_xml return xml # add manifest / application entries from tiapp.xml manifest_xml += get_manifest_xml(self.tiapp) application_xml += get_application_xml(self.tiapp) # add manifest / application entries from modules for module in self.modules: if module.xml == None: continue manifest_xml += get_manifest_xml(module.xml, self.tiapp) application_xml += get_application_xml(module.xml, self.tiapp) # build the permissions XML based on the permissions detected permissions_required = set(permissions_required) permissions_required_xml = "" for p in permissions_required: if '.' not in p: permissions_required_xml+="<uses-permission android:name=\"android.permission.%s\"/>\n\t" % p else: permissions_required_xml+="<uses-permission android:name=\"%s\"/>\n\t" % p def fill_manifest(manifest_source): ti_activities = '<!-- TI_ACTIVITIES -->' ti_permissions = '<!-- TI_PERMISSIONS -->' ti_manifest = '<!-- TI_MANIFEST -->' ti_application = '<!-- TI_APPLICATION -->' ti_services = '<!-- TI_SERVICES -->' manifest_source = manifest_source.replace(ti_activities,"\n\n\t\t".join(activities)) manifest_source = manifest_source.replace(ti_services,"\n\n\t\t".join(services)) manifest_source = manifest_source.replace(ti_permissions,permissions_required_xml) if len(manifest_xml) > 0: manifest_source = manifest_source.replace(ti_manifest, manifest_xml) if len(application_xml) > 0: manifest_source = manifest_source.replace(ti_application, application_xml) return manifest_source default_manifest_contents = fill_manifest(default_manifest_contents) # if a custom uses-sdk or supports-screens has been specified via tiapp.xml # <android><manifest>..., we need to replace the ones in the generated # default manifest supports_screens_node = None uses_sdk_node = None if 'manifest' in self.tiapp.android_manifest: for node in self.tiapp.android_manifest['manifest']: if node.nodeName == 'uses-sdk': uses_sdk_node = node elif node.nodeName == 'supports-screens': supports_screens_node = node if supports_screens_node or uses_sdk_node or ('manifest-attributes' in self.tiapp.android_manifest and self.tiapp.android_manifest['manifest-attributes'].length) or ('application-attributes' in self.tiapp.android_manifest and self.tiapp.android_manifest['application-attributes'].length): dom = parseString(default_manifest_contents) def replace_node(olddom, newnode): nodes = olddom.getElementsByTagName(newnode.nodeName) retval = False if nodes: olddom.documentElement.replaceChild(newnode, nodes[0]) retval = True return retval if supports_screens_node: if not replace_node(dom, supports_screens_node): dom.documentElement.insertBefore(supports_screens_node, dom.documentElement.firstChild.nextSibling) if uses_sdk_node: replace_node(dom, uses_sdk_node) def set_attrs(element, new_attr_set): for k in new_attr_set.keys(): if element.hasAttribute(k): element.removeAttribute(k) element.setAttribute(k, new_attr_set.get(k).value) if 'manifest-attributes' in self.tiapp.android_manifest and self.tiapp.android_manifest['manifest-attributes'].length: set_attrs(dom.documentElement, self.tiapp.android_manifest['manifest-attributes']) if 'application-attributes' in self.tiapp.android_manifest and self.tiapp.android_manifest['application-attributes'].length: set_attrs(dom.getElementsByTagName('application')[0], self.tiapp.android_manifest['application-attributes']) default_manifest_contents = dom.toxml() if application_xml: # If the tiapp.xml <manifest><application> section was not empty, it could be # that user put in <activity> entries that duplicate our own, # such as if they want a custom theme on TiActivity. So we should delete any dupes. dom = parseString(default_manifest_contents) package_name = dom.documentElement.getAttribute('package') manifest_activities = dom.getElementsByTagName('activity') activity_names = [] nodes_to_delete = [] for manifest_activity in manifest_activities: if manifest_activity.hasAttribute('android:name'): activity_name = manifest_activity.getAttribute('android:name') if activity_name.startswith('.'): activity_name = package_name + activity_name if activity_name in activity_names: nodes_to_delete.append(manifest_activity) else: activity_names.append(activity_name) if nodes_to_delete: for node_to_delete in nodes_to_delete: node_to_delete.parentNode.removeChild(node_to_delete) default_manifest_contents = dom.toxml() if custom_manifest_contents: custom_manifest_contents = fill_manifest(custom_manifest_contents) new_manifest_contents = None android_manifest_gen = android_manifest + '.gen' if custom_manifest_contents: new_manifest_contents = custom_manifest_contents # Write the would-be default as well so user can see # some of the auto-gen'd insides of it if they need/want. amf = open(android_manifest + '.gen', 'w') amf.write(default_manifest_contents) amf.close() else: new_manifest_contents = default_manifest_contents if os.path.exists(android_manifest_gen): os.remove(android_manifest_gen) manifest_changed = False old_contents = None if os.path.exists(android_manifest): old_contents = open(android_manifest, 'r').read() if new_manifest_contents != old_contents: trace("Writing out AndroidManifest.xml") amf = open(android_manifest,'w') amf.write(new_manifest_contents) amf.close() manifest_changed = True if self.res_changed or manifest_changed: res_dir = os.path.join(self.project_dir, 'res') output = run.run([self.aapt, 'package', '-m', '-J', self.project_gen_dir, '-M', android_manifest, '-S', res_dir, '-I', self.android_jar], warning_regex=r'skipping') r_file = os.path.join(self.project_gen_dir, self.app_id.replace('.', os.sep), 'R.java') if not os.path.exists(r_file) or (self.res_changed and output == None): error("Error generating R.java from manifest") sys.exit(1) return manifest_changed def generate_stylesheet(self): update_stylesheet = False resources_dir = os.path.join(self.top_dir, 'Resources') project_gen_pkg_dir = os.path.join(self.project_gen_dir, self.app_id.replace('.', os.sep)) app_stylesheet = os.path.join(project_gen_pkg_dir, 'ApplicationStylesheet.java') if not os.path.exists(app_stylesheet): update_stylesheet = True else: for root, dirs, files in os.walk(resources_dir): remove_ignored_dirs(dirs) for f in files: if f in ignoreFiles: continue if f.endswith(".jss"): absolute_path = os.path.join(root, f) if Deltafy.needs_update(absolute_path, app_stylesheet): update_stylesheet = True break if not update_stylesheet: return cssc = csscompiler.CSSCompiler(resources_dir, 'android', self.app_id) if not os.path.exists(project_gen_pkg_dir): os.makedirs(project_gen_pkg_dir) debug("app stylesheet => %s" % app_stylesheet) asf = codecs.open(app_stylesheet, 'w', 'utf-8') asf.write(cssc.code) asf.close() def generate_localizations(self): # compile localization files localecompiler.LocaleCompiler(self.name,self.top_dir,'android',sys.argv[1]).compile() # fix un-escaped single-quotes and full-quotes offending_pattern = '[^\\\\][\'"]' for root, dirs, files in os.walk(self.res_dir): remove_ignored_dirs(dirs) for filename in files: if filename in ignoreFiles or not filename.endswith('.xml'): continue full_path = os.path.join(root, filename) f = codecs.open(full_path, 'r', 'utf-8') contents = f.read() f.close() if not re.search(r"<string ", contents): continue doc = parseString(contents.encode("utf-8")) string_nodes = doc.getElementsByTagName('string') if len(string_nodes) == 0: continue made_change = False for string_node in string_nodes: if not string_node.hasChildNodes(): continue string_child = string_node.firstChild if string_child.nodeType == string_child.CDATA_SECTION_NODE or string_child.nodeType == string_child.TEXT_NODE: string_value = string_child.nodeValue if not re.search(offending_pattern, string_value): continue offenders = re.findall(offending_pattern, string_value) if offenders: for offender in offenders: string_value = string_value.replace(offender, offender[0] + "\\" + offender[-1:]) made_change = True string_child.nodeValue = string_value if made_change: new_contents = doc.toxml() f = codecs.open(full_path, 'w', 'utf-8') f.write(new_contents) f.close() def recurse(self, paths, file_glob=None): if paths == None: yield None if not isinstance(paths, list): paths = [paths] for path in paths: for root, dirs, files in os.walk(path): remove_ignored_dirs(dirs) for filename in files: if filename in ignoreFiles: continue if file_glob != None: if not fnmatch.fnmatch(filename, file_glob): continue yield os.path.join(root, filename) def generate_aidl(self): # support for android remote interfaces in platform/android/src framework_aidl = self.sdk.platform_path('framework.aidl') aidl_args = [self.sdk.get_aidl(), '-p' + framework_aidl, '-I' + self.project_src_dir, '-o' + self.project_gen_dir] for aidl_file in self.recurse(self.project_src_dir, '*.aidl'): run.run(aidl_args + [aidl_file]) def build_generated_classes(self): src_list = [] self.module_jars = [] class_delta = timedelta(seconds=1) for java_file in self.recurse([self.project_src_dir, self.project_gen_dir], '*.java'): if self.project_src_dir in java_file: relative_path = java_file[len(self.project_src_dir)+1:] else: relative_path = java_file[len(self.project_gen_dir)+1:] class_file = os.path.join(self.classes_dir, relative_path.replace('.java', '.class')) if Deltafy.needs_update(java_file, class_file) > 0: # the file list file still needs each file escaped apparently debug("adding %s to javac build list" % java_file) src_list.append('"%s"' % java_file.replace("\\", "\\\\")) if len(src_list) == 0: # No sources are older than their classfile counterparts, we can skip javac / dex return False classpath = os.pathsep.join([self.android_jar, os.pathsep.join(self.android_jars)]) project_module_dir = os.path.join(self.top_dir,'modules','android') for module in self.modules: if module.jar == None: continue self.module_jars.append(module.jar) classpath = os.pathsep.join([classpath, module.jar]) module_lib = module.get_resource('lib') for jar in glob.glob(os.path.join(module_lib, '*.jar')): self.module_jars.append(jar) classpath = os.pathsep.join([classpath, jar]) if len(self.module_jars) > 0: # kroll-apt.jar is needed for modules classpath = os.pathsep.join([classpath, self.kroll_apt_jar]) if self.deploy_type != 'production': classpath = os.pathsep.join([classpath, os.path.join(self.support_dir, 'lib', 'titanium-verify.jar'), os.path.join(self.support_dir, 'lib', 'titanium-debug.jar')]) debug("Building Java Sources: " + " ".join(src_list)) javac_command = [self.javac, '-encoding', 'utf8', '-classpath', classpath, '-d', self.classes_dir, '-proc:none', '-sourcepath', self.project_src_dir, '-sourcepath', self.project_gen_dir] (src_list_osfile, src_list_filename) = tempfile.mkstemp() src_list_file = os.fdopen(src_list_osfile, 'w') src_list_file.write("\n".join(src_list)) src_list_file.close() javac_command.append('@' + src_list_filename) (out, err, javac_process) = run.run(javac_command, ignore_error=True, return_error=True, return_process=True) os.remove(src_list_filename) if javac_process.returncode != 0: error("Error(s) compiling generated Java code") error(str(err)) sys.exit(1) return True def create_unsigned_apk(self, resources_zip_file): unsigned_apk = os.path.join(self.project_dir, 'bin', 'app-unsigned.apk') self.apk_updated = False apk_modified = None if os.path.exists(unsigned_apk): apk_modified = Deltafy.get_modified_datetime(unsigned_apk) debug("creating unsigned apk: " + unsigned_apk) # copy existing resources into the APK apk_zip = zipfile.ZipFile(unsigned_apk, 'w', zipfile.ZIP_DEFLATED) def skip_jar_path(path): ext = os.path.splitext(path)[1] if path.endswith('/'): return True if path.startswith('META-INF/'): return True if path.split('/')[-1].startswith('.'): return True if ext == '.class': return True if 'org/appcelerator/titanium/bindings' in path and ext == '.json': return True def compression_type(path): ext = os.path.splitext(path)[1] if ext in uncompressed_types: return zipfile.ZIP_STORED return zipfile.ZIP_DEFLATED def zipinfo(path): info = zipfile.ZipInfo(path) info.compress_type = compression_type(path) return info def is_modified(path): return apk_modified is None or Deltafy.needs_update_timestamp(path, apk_modified) def zip_contains(zip, entry): try: zip.getinfo(entry) except: return False return True if is_modified(resources_zip_file): self.apk_updated = True resources_zip = zipfile.ZipFile(resources_zip_file) for path in resources_zip.namelist(): if skip_jar_path(path): continue debug("from resource zip => " + path) apk_zip.writestr(zipinfo(path), resources_zip.read(path)) resources_zip.close() # add classes.dex if is_modified(self.classes_dex) or not zip_contains(apk_zip, 'classes.dex'): apk_zip.write(self.classes_dex, 'classes.dex') # add all resource files from the project for root, dirs, files in os.walk(self.project_src_dir): remove_ignored_dirs(dirs) for f in files: if f in ignoreFiles: continue if os.path.splitext(f)[1] != '.java': absolute_path = os.path.join(root, f) relative_path = os.path.join(root[len(self.project_src_dir)+1:], f) if is_modified(absolute_path): self.apk_updated = True debug("resource file => " + relative_path) apk_zip.write(os.path.join(root, f), relative_path, compression_type(f)) def add_resource_jar(jar_file): jar = zipfile.ZipFile(jar_file) for path in jar.namelist(): if skip_jar_path(path): continue debug("from JAR %s => %s" % (jar_file, path)) apk_zip.writestr(zipinfo(path), jar.read(path)) jar.close() for jar_file in self.module_jars: add_resource_jar(jar_file) for jar_file in self.android_jars: add_resource_jar(jar_file) def add_native_libs(libs_dir): if os.path.exists(libs_dir): for abi_dir in os.listdir(libs_dir): libs_abi_dir = os.path.join(libs_dir, abi_dir) if not os.path.isdir(libs_abi_dir): continue for file in os.listdir(libs_abi_dir): if file.endswith('.so'): native_lib = os.path.join(libs_abi_dir, file) if is_modified(native_lib): self.apk_updated = True debug("installing native lib: %s" % native_lib) apk_zip.write(native_lib, '/'.join(['lib', abi_dir, file])) # add any native libraries : libs/**/*.so -> lib/**/*.so add_native_libs(os.path.join(self.project_dir, 'libs')) # add module native libraries for module in self.modules: add_native_libs(module.get_resource('libs')) apk_zip.close() return unsigned_apk def run_adb(self, *args): command = [self.sdk.get_adb()] command.extend(self.device_args) command.extend(args) return run.run(command) def package_and_deploy(self): ap_ = os.path.join(self.project_dir, 'bin', 'app.ap_') rhino_jar = os.path.join(self.support_dir, 'js.jar') # This is only to check if this has been overridden in production has_compile_js = self.tiappxml.has_app_property("ti.android.compilejs") compile_js = not has_compile_js or (has_compile_js and \ self.tiappxml.to_bool(self.tiappxml.get_app_property('ti.android.compilejs'))) pkg_assets_dir = self.assets_dir if self.deploy_type == "production" and compile_js: non_js_assets = os.path.join(self.project_dir, 'bin', 'non-js-assets') if not os.path.exists(non_js_assets): os.mkdir(non_js_assets) copy_all(self.assets_dir, non_js_assets, ignore_exts=[".js"]) pkg_assets_dir = non_js_assets run.run([self.aapt, 'package', '-f', '-M', 'AndroidManifest.xml', '-A', pkg_assets_dir, '-S', 'res', '-I', self.android_jar, '-I', self.titanium_jar, '-F', ap_], warning_regex=r'skipping') unsigned_apk = self.create_unsigned_apk(ap_) if self.dist_dir: app_apk = os.path.join(self.dist_dir, self.name + '.apk') else: app_apk = os.path.join(self.project_dir, 'bin', 'app.apk') output = run.run([self.jarsigner, '-storepass', self.keystore_pass, '-keystore', self.keystore, '-signedjar', app_apk, unsigned_apk, self.keystore_alias]) run.check_output_for_error(output, r'RuntimeException: (.*)', True) run.check_output_for_error(output, r'^jarsigner: (.*)', True) # TODO Document Exit message #success = re.findall(r'RuntimeException: (.*)', output) #if len(success) > 0: # error(success[0]) # sys.exit(1) # zipalign to align byte boundaries zipalign = self.sdk.get_zipalign() if os.path.exists(app_apk+'z'): os.remove(app_apk+'z') ALIGN_32_BIT = 4 output = run.run([zipalign, '-v', str(ALIGN_32_BIT), app_apk, app_apk+'z']) # TODO - Document Exit message if output == None: error("System Error while compiling Android classes.dex") sys.exit(1) else: os.unlink(app_apk) os.rename(app_apk+'z',app_apk) if self.dist_dir: self.post_build() sys.exit() if self.build_only: return (False, False) out = self.run_adb('get-state') #out = subprocess.Popen([self.sdk.get_adb(), self.device_type_arg, 'get-state'], stderr=subprocess.PIPE, stdout=subprocess.PIPE).communicate()[0] out = str(out).strip() # try a few times as sometimes it fails waiting on boot attempts = 0 launched = False launch_failed = False while attempts < 5: try: if self.install: self.wait_for_device('d') info("Installing application on emulator") else: self.wait_for_device('e') info("Installing application on device") output = self.run_adb('install', '-r', app_apk) #output = run.run(cmd) if output == None: launch_failed = True elif "Failure" in output: error("Failed installing %s: %s" % (self.app_id, output)) launch_failed = True elif not self.install: launched = True break except Exception, e: error(e) time.sleep(3) attempts+=1 return (launched, launch_failed) def run_app(self): info("Launching application ... %s" % self.name) output = self.run_adb('shell', 'am', 'start', '-a', 'android.intent.action.MAIN', '-c','android.intent.category.LAUNCHER', '-n', '%s/.%sActivity' % (self.app_id , self.classname)) trace("Launch output: %s" % output) def wait_for_sdcard(self): info("Waiting for SDCard to become available..") waited = 0 max_wait = 60 while waited < max_wait: output = self.run_adb('shell', 'mount') if output != None: mount_points = output.splitlines() for mount_point in mount_points: tokens = mount_point.split() if len(tokens) < 2: continue mount_path = tokens[1] if mount_path in ['/sdcard', '/mnt/sdcard']: return True else: error("Error checking for SDCard using 'mount'") return False time.sleep(1) waited += 1 error("Timed out waiting for SDCard to become available (%ds)" % max_wait) return False def push_deploy_json(self): deploy_data = { "debuggerEnabled": self.debugger_host != None, "debuggerPort": self.debugger_port, "fastdevPort": self.fastdev_port } deploy_json = os.path.join(self.project_dir, 'bin', 'deploy.json') open(deploy_json, 'w+').write(simplejson.dumps(deploy_data)) sdcard_available = self.wait_for_sdcard() if sdcard_available: self.run_adb('shell', 'mkdir /sdcard/%s || echo' % self.app_id) self.run_adb('push', deploy_json, '/sdcard/%s/deploy.json' % self.app_id) os.unlink(deploy_json) def verify_fastdev(self): lock_file = os.path.join(self.top_dir, '.fastdev.lock') if not fastdev.is_running(self.top_dir): if os.path.exists(lock_file): os.unlink(lock_file) return False else: data = simplejson.loads(open(lock_file, 'r').read()) self.fastdev_port = data["port"] return True def fastdev_kill_app(self): lock_file = os.path.join(self.top_dir, ".fastdev.lock") if os.path.exists(lock_file): class Options(object): pass options = Options() options.lock_file = lock_file try: return fastdev.kill_app(self.top_dir, options) except Exception, e: return False def merge_internal_module_resources(self): if not self.android_jars: return for jar in self.android_jars: if not os.path.exists(jar): continue res_zip = jar[:-4] + '.res.zip' if not os.path.exists(res_zip): continue res_zip_file = zipfile.ZipFile(res_zip, "r") try: zip_extractall(res_zip_file, self.project_dir) except: raise finally: res_zip_file.close() def build_and_run(self, install, avd_id, keystore=None, keystore_pass='tirocks', keystore_alias='tidev', dist_dir=None, build_only=False, device_args=None, debugger_host=None): deploy_type = 'development' self.build_only = build_only self.device_args = device_args self.postbuild_modules = [] if install: if self.device_args == None: self.device_args = ['-d'] if keystore == None: deploy_type = 'test' else: deploy_type = 'production' if self.device_args == None: self.device_args = ['-e'] self.deploy_type = deploy_type (java_failed, java_status) = prereq.check_java() if java_failed: error(java_status) sys.exit(1) # attempt to load any compiler plugins if len(self.tiappxml.properties['plugins']) > 0: titanium_dir = os.path.abspath(os.path.join(template_dir,'..','..','..','..')) local_compiler_dir = os.path.abspath(os.path.join(self.top_dir,'plugins')) tp_compiler_dir = os.path.abspath(os.path.join(titanium_dir,'plugins')) if not os.path.exists(tp_compiler_dir) and not os.path.exists(local_compiler_dir): error("Build Failed (Missing plugins directory)") sys.exit(1) compiler_config = { 'platform':'android', 'tiapp':self.tiappxml, 'project_dir':self.top_dir, 'titanium_dir':titanium_dir, 'appid':self.app_id, 'template_dir':template_dir, 'project_name':self.name, 'command':self.command, 'build_dir':s.project_dir, 'app_name':self.name, 'android_builder':self, 'deploy_type':deploy_type, 'dist_dir':dist_dir, 'logger':log } for plugin in self.tiappxml.properties['plugins']: local_plugin_file = os.path.join(local_compiler_dir,plugin['name'],'plugin.py') plugin_file = os.path.join(tp_compiler_dir,plugin['name'],plugin['version'],'plugin.py') info("plugin=%s" % plugin_file) if not os.path.exists(local_plugin_file) and not os.path.exists(plugin_file): error("Build Failed (Missing plugin for %s)" % plugin['name']) sys.exit(1) info("Detected compiler plugin: %s/%s" % (plugin['name'],plugin['version'])) code_path = plugin_file if os.path.exists(local_plugin_file): code_path = local_plugin_file compiler_config['plugin']=plugin fin = open(code_path, 'rb') m = hashlib.md5() m.update(open(code_path,'rb').read()) code_hash = m.hexdigest() p = imp.load_source(code_hash, code_path, fin) module_functions = dict(inspect.getmembers(p, inspect.isfunction)) if module_functions.has_key('postbuild'): debug("plugin contains a postbuild function. Will execute after project is built and packaged") self.postbuild_modules.append((plugin['name'], p)) p.compile(compiler_config) fin.close() # in Windows, if the adb server isn't running, calling "adb devices" # will fork off a new adb server, and cause a lock-up when we # try to pipe the process' stdout/stderr. the workaround is # to simply call adb start-server here, and not care about # the return code / pipes. (this is harmless if adb is already running) # -- thanks to Bill Dawson for the workaround if platform.system() == "Windows" and not build_only: run.run([self.sdk.get_adb(), "start-server"], True, ignore_output=True) ti_version_file = os.path.join(self.support_dir, '..', 'version.txt') if os.path.exists(ti_version_file): ti_version_info = read_properties(open(ti_version_file, 'r'), '=') if not ti_version_info is None and 'version' in ti_version_info: ti_version_string = 'Titanium SDK version: %s' % ti_version_info['version'] if 'timestamp' in ti_version_info or 'githash' in ti_version_info: ti_version_string += ' (' if 'timestamp' in ti_version_info: ti_version_string += '%s' % ti_version_info['timestamp'] if 'githash' in ti_version_info: ti_version_string += ' %s' % ti_version_info['githash'] ti_version_string += ')' info(ti_version_string) if not build_only: if deploy_type == 'development': self.wait_for_device('e') elif deploy_type == 'test': self.wait_for_device('d') self.install = install self.dist_dir = dist_dir self.aapt = self.sdk.get_aapt() self.android_jar = self.sdk.get_android_jar() self.titanium_jar = os.path.join(self.support_dir,'titanium.jar') self.kroll_apt_jar = os.path.join(self.support_dir, 'kroll-apt.jar') dx = self.sdk.get_dx() self.apkbuilder = self.sdk.get_apkbuilder() self.sdcard_resources = '/sdcard/Ti.debug/%s/Resources' % self.app_id self.resources_installed = False if deploy_type == "production": self.app_installed = False else: self.app_installed = not build_only and self.is_app_installed() debug("%s installed? %s" % (self.app_id, self.app_installed)) #self.resources_installed = not build_only and self.are_resources_installed() #debug("%s resources installed? %s" % (self.app_id, self.resources_installed)) if keystore == None: keystore = os.path.join(self.support_dir,'dev_keystore') self.keystore = keystore self.keystore_pass = keystore_pass self.keystore_alias = keystore_alias curdir = os.getcwd() self.support_resources_dir = os.path.join(self.support_dir, 'resources') try: os.chdir(self.project_dir) self.android = Android(self.name, self.app_id, self.sdk, deploy_type, self.java) if not os.path.exists('bin'): os.makedirs('bin') resources_dir = os.path.join(self.top_dir,'Resources') self.assets_dir = os.path.join(self.project_dir,'bin','assets') self.assets_resources_dir = os.path.join(self.assets_dir,'Resources') if not os.path.exists(self.assets_dir): os.makedirs(self.assets_dir) shutil.copy(self.project_tiappxml, self.assets_dir) finalxml = os.path.join(self.assets_dir,'tiapp.xml') self.tiapp = TiAppXML(finalxml) self.tiapp.setDeployType(deploy_type) self.sdcard_copy = False sdcard_property = "ti.android.loadfromsdcard" if self.tiapp.has_app_property(sdcard_property): self.sdcard_copy = self.tiapp.to_bool(self.tiapp.get_app_property(sdcard_property)) fastdev_property = "ti.android.fastdev" fastdev_enabled = (self.deploy_type == 'development' and not self.build_only) if self.tiapp.has_app_property(fastdev_property): fastdev_enabled = self.tiapp.to_bool(self.tiapp.get_app_property(fastdev_property)) if fastdev_enabled: if self.verify_fastdev(): info("Fastdev server running, deploying in Fastdev mode") self.fastdev = True else: warn("Fastdev enabled, but server isn't running, deploying normally") self.classes_dir = os.path.join(self.project_dir, 'bin', 'classes') if not os.path.exists(self.classes_dir): os.makedirs(self.classes_dir) if (not debugger_host is None) and len(debugger_host) > 0: hostport = debugger_host.split(":") self.debugger_host = hostport[0] self.debugger_port = int(hostport[1]) debugger_enabled = self.debugger_host != None and len(self.debugger_host) > 0 self.copy_project_resources() last_build_info = None built_all_modules = False build_info_path = os.path.join(self.project_dir, 'bin', 'build_info.json') if os.path.exists(build_info_path): last_build_info = simplejson.loads(open(build_info_path, 'r').read()) built_all_modules = last_build_info["include_all_modules"] include_all_ti_modules = self.fastdev if (self.tiapp.has_app_property('ti.android.include_all_modules')): if self.tiapp.to_bool(self.tiapp.get_app_property('ti.android.include_all_modules')): include_all_ti_modules = True if self.tiapp_changed or (self.js_changed and not self.fastdev) or \ self.force_rebuild or self.deploy_type == "production" or \ (self.fastdev and (not self.app_installed or not built_all_modules)): trace("Generating Java Classes") self.android.create(os.path.abspath(os.path.join(self.top_dir,'..')), True, project_dir = self.top_dir, include_all_ti_modules=include_all_ti_modules) open(build_info_path, 'w').write(simplejson.dumps({ "include_all_modules": include_all_ti_modules })) else: info("Tiapp.xml unchanged, skipping class generation") # compile resources full_resource_dir = os.path.join(self.project_dir, self.assets_resources_dir) compiler = Compiler(self.tiapp, full_resource_dir, self.java, self.classes_dir, self.project_dir, include_all_modules=include_all_ti_modules) compiler.compile() self.compiled_files = compiler.compiled_files self.android_jars = compiler.jar_libraries self.merge_internal_module_resources() if not os.path.exists(self.assets_dir): os.makedirs(self.assets_dir) self.resource_drawables_changed = self.copy_resource_drawables() self.warn_dupe_drawable_folders() # Detect which modules are being used. # We need to know this info in a few places, so the info is saved # in self.missing_modules and self.modules detector = ModuleDetector(self.top_dir) self.missing_modules, self.modules = detector.find_app_modules(self.tiapp, 'android') self.copy_module_platform_folders() special_resources_dir = os.path.join(self.top_dir,'platform','android') if os.path.exists(special_resources_dir): debug("found special platform files dir = %s" % special_resources_dir) ignore_files = ignoreFiles ignore_files.extend(['AndroidManifest.xml']) # don't want to overwrite build/android/AndroidManifest.xml yet self.copy_project_platform_folder(ignoreDirs, ignore_files) self.generate_stylesheet() self.generate_aidl() self.manifest_changed = self.generate_android_manifest(compiler) my_avd = None self.google_apis_supported = False # find the AVD we've selected and determine if we support Google APIs for avd_props in avd.get_avds(self.sdk): if avd_props['id'] == avd_id: my_avd = avd_props self.google_apis_supported = (my_avd['name'].find('Google')!=-1 or my_avd['name'].find('APIs')!=-1) break if build_only: self.google_apis_supported = True remove_orphaned_files(resources_dir, os.path.join(self.project_dir, 'bin', 'assets', 'Resources')) generated_classes_built = self.build_generated_classes() # TODO: enable for "test" / device mode for debugger / fastdev if not self.build_only and self.deploy_type == "development": self.push_deploy_json() self.classes_dex = os.path.join(self.project_dir, 'bin', 'classes.dex') def jar_includer(path, isfile): if isfile and path.endswith(".jar"): return True return False support_deltafy = Deltafy(self.support_dir, jar_includer) self.support_deltas = support_deltafy.scan() dex_built = False if len(self.support_deltas) > 0 or generated_classes_built or self.deploy_type == "production": # the dx.bat that ships with android in windows doesn't allow command line # overriding of the java heap space, so we call the jar directly if platform.system() == 'Windows': dex_args = [self.java, '-Xmx1024M', '-Djava.ext.dirs=%s' % self.sdk.get_platform_tools_dir(), '-jar', self.sdk.get_dx_jar()] else: dex_args = [dx, '-JXmx1536M', '-JXX:-UseGCOverheadLimit'] dex_args += ['--dex', '--output='+self.classes_dex, self.classes_dir] dex_args += self.android_jars dex_args += self.module_jars if self.deploy_type != 'production': dex_args.append(os.path.join(self.support_dir, 'lib', 'titanium-verify.jar')) dex_args.append(os.path.join(self.support_dir, 'lib', 'titanium-debug.jar')) # the verifier depends on Ti.Network classes, so we may need to inject it has_network_jar = False for jar in self.android_jars: if jar.endswith('titanium-network.jar'): has_network_jar = True break if not has_network_jar: dex_args.append(os.path.join(self.support_dir, 'modules', 'titanium-network.jar')) # substitute for the debugging js jar in non production mode for jar in self.android_jars: if jar.endswith('js.jar'): dex_args.remove(jar) dex_args.append(os.path.join(self.support_dir, 'js-debug.jar')) info("Compiling Android Resources... This could take some time") # TODO - Document Exit message run_result = run.run(dex_args, warning_regex=r'warning: ') if (run_result == None): dex_built = False error("System Error while compiling Android classes.dex") sys.exit(1) else: dex_built = True debug("Android classes.dex built") if dex_built or generated_classes_built or self.tiapp_changed or self.manifest_changed or not self.app_installed or not self.fastdev: # metadata has changed, we need to do a full re-deploy launched, launch_failed = self.package_and_deploy() if launched: self.run_app() info("Deployed %s ... Application should be running." % self.name) elif launch_failed==False and not build_only: info("Application installed. Launch from drawer on Home Screen") elif not build_only: # Relaunch app if nothing was built info("Re-launching application ... %s" % self.name) relaunched = False killed = False if self.fastdev: killed = self.fastdev_kill_app() if not killed: processes = self.run_adb('shell', 'ps') for line in processes.splitlines(): columns = line.split() if len(columns) > 1: pid = columns[1] id = columns[len(columns)-1] if id == self.app_id: self.run_adb('shell', 'kill', pid) relaunched = True self.run_app() if relaunched: info("Relaunched %s ... Application should be running." % self.name) self.post_build() #intermediary code for on-device debugging (later) #if debugger_host != None: #import debugger #debug("connecting to debugger: %s, debugger=%s" % (debugger_host, str(debugger))) #debugger.run(debugger_host, '127.0.0.1:5999') finally: os.chdir(curdir) sys.stdout.flush() def post_build(self): try: if self.postbuild_modules: for p in self.postbuild_modules: info("Running postbuild function in %s plugin" % p[0]) p[1].postbuild() except Exception,e: error("Error performing post-build steps: %s" % e) if __name__ == "__main__": def usage(): print "%s <command> <project_name> <sdk_dir> <project_dir> <app_id> [key] [password] [alias] [dir] [avdid] [avdsdk]" % os.path.basename(sys.argv[0]) print print "available commands: " print print " emulator build and run the emulator" print " simulator build and run the app on the simulator" print " install build and install the app on the device" print " distribute build final distribution package for upload to marketplace" print " run build and run the project using values from tiapp.xml" print " run-emulator run the emulator with a default AVD ID and skin" sys.exit(1) argc = len(sys.argv) if argc < 2: usage() command = sys.argv[1] template_dir = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename)) get_values_from_tiapp = False if command == 'run': if argc < 4: print 'Usage: %s run <project_dir> <android_sdk>' % sys.argv[0] sys.exit(1) get_values_from_tiapp = True project_dir = sys.argv[2] sdk_dir = sys.argv[3] avd_id = "7" elif command == 'run-emulator': if argc < 4: print 'Usage: %s run-emulator <project_dir> <android_sdk>' % sys.argv[0] sys.exit(1) get_values_from_tiapp = True project_dir = sys.argv[2] sdk_dir = sys.argv[3] # sensible defaults? avd_id = "7" avd_skin = "HVGA" else: if argc < 6 or command == '--help' or (command=='distribute' and argc < 10): usage() if get_values_from_tiapp: tiappxml = TiAppXML(os.path.join(project_dir, 'tiapp.xml')) app_id = tiappxml.properties['id'] project_name = tiappxml.properties['name'] else: project_name = dequote(sys.argv[2]) sdk_dir = os.path.abspath(os.path.expanduser(dequote(sys.argv[3]))) project_dir = os.path.abspath(os.path.expanduser(dequote(sys.argv[4]))) app_id = dequote(sys.argv[5]) log = TiLogger(os.path.join(os.path.abspath(os.path.expanduser(dequote(project_dir))), 'build.log')) log.debug(" ".join(sys.argv)) s = Builder(project_name,sdk_dir,project_dir,template_dir,app_id) s.command = command try: if command == 'run-emulator': s.run_emulator(avd_id, avd_skin) elif command == 'run': s.build_and_run(False, avd_id) elif command == 'emulator': avd_id = dequote(sys.argv[6]) avd_skin = dequote(sys.argv[7]) s.run_emulator(avd_id, avd_skin) elif command == 'simulator': info("Building %s for Android ... one moment" % project_name) avd_id = dequote(sys.argv[6]) debugger_host = None if len(sys.argv) > 8: debugger_host = dequote(sys.argv[8]) s.build_and_run(False, avd_id, debugger_host=debugger_host) elif command == 'install': avd_id = dequote(sys.argv[6]) device_args = ['-d'] if len(sys.argv) >= 8: device_args = ['-s', sys.argv[7]] s.build_and_run(True, avd_id, device_args=device_args) elif command == 'distribute': key = os.path.abspath(os.path.expanduser(dequote(sys.argv[6]))) password = dequote(sys.argv[7]) alias = dequote(sys.argv[8]) output_dir = dequote(sys.argv[9]) avd_id = dequote(sys.argv[10]) s.build_and_run(True, avd_id, key, password, alias, output_dir) elif command == 'build': s.build_and_run(False, 1, build_only=True) else: error("Unknown command: %s" % command) usage() except SystemExit, n: sys.exit(n) except: e = traceback.format_exc() error("Exception occured while building Android project:") for line in e.splitlines(): error(line) sys.exit(1)<|fim▁end|>
def are_resources_installed(self):
<|file_name|>nconns.py<|end_file_name|><|fim▁begin|>import sys import time import ldap url, binddn, bindpw, basedn, nconns, niters = sys.argv[1:] conns = [] for ii in xrange(0, int(nconns)):<|fim▁hole|> conn.simple_bind(binddn, bindpw) for ii in xrange(0, int(niters)): for conn in conns: ents = conn.search_s(basedn, ldap.SCOPE_SUBTREE, "uid=scarter") assert(len(ents) == 1) assert(ents[0][1]['uid'][0] == 'scarter') for conn in conns: conn.unbind_s()<|fim▁end|>
conn = ldap.initialize(url) conns.append(conn) for conn in conns:
<|file_name|>HdmiCec.py<|end_file_name|><|fim▁begin|>import struct import os from sys import maxint from enigma import eTimer, eHdmiCEC, eActionMap from config import config, ConfigSelection, ConfigYesNo, ConfigSubsection, ConfigText from Tools.StbHardware import getFPWasTimerWakeup from Tools.Directories import fileExists config.hdmicec = ConfigSubsection() config.hdmicec.enabled = ConfigYesNo(default = False) config.hdmicec.control_tv_standby = ConfigYesNo(default = True) config.hdmicec.control_tv_wakeup = ConfigYesNo(default = True) config.hdmicec.report_active_source = ConfigYesNo(default = True) config.hdmicec.report_active_menu = ConfigYesNo(default = True) config.hdmicec.handle_tv_standby = ConfigYesNo(default = True) config.hdmicec.handle_tv_wakeup = ConfigYesNo(default = True) config.hdmicec.tv_wakeup_detection = ConfigSelection( choices = { "wakeup": _("Wakeup"), "tvreportphysicaladdress": _("TV physical address report"), "sourcerequest": _("Source request"), "streamrequest": _("Stream request"), "osdnamerequest": _("OSD name request"), "activity": _("Any activity"), }, default = "streamrequest") config.hdmicec.fixed_physical_address = ConfigText(default = "0.0.0.0") config.hdmicec.volume_forwarding = ConfigYesNo(default = False) config.hdmicec.control_receiver_wakeup = ConfigYesNo(default = False) config.hdmicec.control_receiver_standby = ConfigYesNo(default = False) config.hdmicec.handle_deepstandby_events = ConfigYesNo(default = False) config.hdmicec.preemphasis = ConfigYesNo(default = False) choicelist = [] for i in (10, 50, 100, 150, 250, 500, 750, 1000, 1500, 2000): choicelist.append(("%d" % i, "%d ms" % i)) config.hdmicec.minimum_send_interval = ConfigSelection(default = "0", choices = [("0", _("Disabled"))] + choicelist) class HdmiCec: instance = None def __init__(self): if config.hdmicec.enabled.value: assert not HdmiCec.instance, "only one HdmiCec instance is allowed!" HdmiCec.instance = self self.wait = eTimer() self.wait.timeout.get().append(self.sendCmd) self.queue = [] eHdmiCEC.getInstance().messageReceived.get().append(self.messageReceived) config.misc.standbyCounter.addNotifier(self.onEnterStandby, initial_call = False) config.misc.DeepStandby.addNotifier(self.onEnterDeepStandby, initial_call = False) self.setFixedPhysicalAddress(config.hdmicec.fixed_physical_address.value) self.volumeForwardingEnabled = False self.volumeForwardingDestination = 0 eActionMap.getInstance().bindAction('', -maxint - 1, self.keyEvent) config.hdmicec.volume_forwarding.addNotifier(self.configVolumeForwarding) config.hdmicec.enabled.addNotifier(self.configVolumeForwarding) if config.hdmicec.handle_deepstandby_events.value: if not getFPWasTimerWakeup(): self.wakeupMessages() # if fileExists("/proc/stb/hdmi/preemphasis"): # self.sethdmipreemphasis() def getPhysicalAddress(self): physicaladdress = eHdmiCEC.getInstance().getPhysicalAddress() hexstring = '%04x' % physicaladdress return hexstring[0] + '.' + hexstring[1] + '.' + hexstring[2] + '.' + hexstring[3] def setFixedPhysicalAddress(self, address): if address != config.hdmicec.fixed_physical_address.value: config.hdmicec.fixed_physical_address.value = address config.hdmicec.fixed_physical_address.save() hexstring = address[0] + address[2] + address[4] + address[6] eHdmiCEC.getInstance().setFixedPhysicalAddress(int(float.fromhex(hexstring))) def sendMessage(self, address, message): if config.hdmicec.enabled.value: cmd = 0 data = '' if message == "wakeup": cmd = 0x04 elif message == "sourceactive": address = 0x0f # use broadcast for active source command cmd = 0x82 physicaladdress = eHdmiCEC.getInstance().getPhysicalAddress() data = str(struct.pack('BB', int(physicaladdress/256), int(physicaladdress%256))) elif message == "standby": cmd = 0x36 elif message == "sourceinactive": physicaladdress = eHdmiCEC.getInstance().getPhysicalAddress() cmd = 0x9d data = str(struct.pack('BB', int(physicaladdress/256), int(physicaladdress%256))) elif message == "menuactive": cmd = 0x8e data = str(struct.pack('B', 0x00)) elif message == "menuinactive": cmd = 0x8e data = str(struct.pack('B', 0x01)) elif message == "givesystemaudiostatus": cmd = 0x7d address = 0x05 elif message == "setsystemaudiomode": cmd = 0x70 address = 0x05 physicaladdress = eHdmiCEC.getInstance().getPhysicalAddress() data = str(struct.pack('BB', int(physicaladdress/256), int(physicaladdress%256))) elif message == "osdname": cmd = 0x47 data = os.uname()[1] data = data[:14] elif message == "poweractive": cmd = 0x90 data = str(struct.pack('B', 0x00)) elif message == "powerinactive": cmd = 0x90 data = str(struct.pack('B', 0x01)) elif message == "reportaddress": address = 0x0f # use broadcast address cmd = 0x84 physicaladdress = eHdmiCEC.getInstance().getPhysicalAddress() devicetype = eHdmiCEC.getInstance().getDeviceType() data = str(struct.pack('BBB', int(physicaladdress/256), int(physicaladdress%256), devicetype)) elif message == "vendorid": cmd = 0x87 data = '\x00\x00\x00' elif message == "keypoweron": cmd = 0x44 data = str(struct.pack('B', 0x6d)) elif message == "keypoweroff": cmd = 0x44 data = str(struct.pack('B', 0x6c)) if cmd: if config.hdmicec.minimum_send_interval.value != "0" and message != "standby": # Use no interval time when message is standby. usefull for Panasonic TV self.queue.append((address, cmd, data)) if not self.wait.isActive(): self.wait.start(int(config.hdmicec.minimum_send_interval.value), True) else: eHdmiCEC.getInstance().sendMessage(address, cmd, data, len(data)) def sendCmd(self): if len(self.queue): (address, cmd, data) = self.queue.pop(0) eHdmiCEC.getInstance().sendMessage(address, cmd, data, len(data)) self.wait.start(int(config.hdmicec.minimum_send_interval.value), True) def sendMessages(self, address, messages): for message in messages: self.sendMessage(address, message) def wakeupMessages(self): if config.hdmicec.enabled.value: messages = [] if config.hdmicec.control_tv_wakeup.value: messages.append("wakeup") if config.hdmicec.report_active_source.value: messages.append("sourceactive") if config.hdmicec.report_active_menu.value: messages.append("menuactive") if messages: self.sendMessages(0, messages) if config.hdmicec.control_receiver_wakeup.value: self.sendMessage(5, "keypoweron") self.sendMessage(5, "setsystemaudiomode") def standbyMessages(self): if config.hdmicec.enabled.value: messages = [] if config.hdmicec.control_tv_standby.value: messages.append("standby") else: if config.hdmicec.report_active_source.value: messages.append("sourceinactive") if config.hdmicec.report_active_menu.value: messages.append("menuinactive") if messages: self.sendMessages(0, messages) if config.hdmicec.control_receiver_standby.value: self.sendMessage(5, "keypoweroff") self.sendMessage(5, "standby") def onLeaveStandby(self): self.wakeupMessages() def onEnterStandby(self, configElement): from Screens.Standby import inStandby inStandby.onClose.append(self.onLeaveStandby) self.standbyMessages() def onEnterDeepStandby(self, configElement): if config.hdmicec.handle_deepstandby_events.value: self.standbyMessages() def standby(self): from Screens.Standby import Standby, inStandby if not inStandby: from Tools import Notifications Notifications.AddNotification(Standby) def wakeup(self): from Screens.Standby import Standby, inStandby if inStandby: inStandby.Power() def messageReceived(self, message): if config.hdmicec.enabled.value: from Screens.Standby import inStandby cmd = message.getCommand() data = 16 * '\x00' length = message.getData(data, len(data)) if cmd == 0x00: # feature abort if data[0] == '\x44': print 'eHdmiCec: volume forwarding not supported by device %02x'%(message.getAddress()) self.volumeForwardingEnabled = False elif cmd == 0x46: # request name self.sendMessage(message.getAddress(), 'osdname') elif cmd == 0x7e or cmd == 0x72: # system audio mode status if data[0] == '\x01': self.volumeForwardingDestination = 5 # on: send volume keys to receiver else: self.volumeForwardingDestination = 0 # off: send volume keys to tv if config.hdmicec.volume_forwarding.value: print 'eHdmiCec: volume forwarding to device %02x enabled'% self.volumeForwardingDestination self.volumeForwardingEnabled = True elif cmd == 0x8f: # request power status if inStandby: self.sendMessage(message.getAddress(), 'powerinactive') else: self.sendMessage(message.getAddress(), 'poweractive') elif cmd == 0x83: # request address self.sendMessage(message.getAddress(), 'reportaddress') elif cmd == 0x86: # request streaming path physicaladdress = ord(data[0]) * 256 + ord(data[1]) ouraddress = eHdmiCEC.getInstance().getPhysicalAddress() if physicaladdress == ouraddress: if not inStandby: if config.hdmicec.report_active_source.value: self.sendMessage(message.getAddress(), 'sourceactive') elif cmd == 0x85: # request active source if not inStandby: if config.hdmicec.report_active_source.value: self.sendMessage(message.getAddress(), 'sourceactive') elif cmd == 0x8c: # request vendor id self.sendMessage(message.getAddress(), 'vendorid') elif cmd == 0x8d: # menu request requesttype = ord(data[0]) if requesttype == 2: # query if inStandby: self.sendMessage(message.getAddress(), 'menuinactive') else: self.sendMessage(message.getAddress(), 'menuactive') # handle standby request from the tv if cmd == 0x36 and config.hdmicec.handle_tv_standby.value: self.standby() # handle wakeup requests from the tv if config.hdmicec.handle_tv_wakeup.value: if cmd == 0x04 and config.hdmicec.tv_wakeup_detection.value == "wakeup": self.wakeup() elif cmd == 0x84 and config.hdmicec.tv_wakeup_detection.value == "tvreportphysicaladdress": if (ord(data[0]) * 256 + ord(data[1])) == 0 and ord(data[2]) == 0: self.wakeup() elif cmd == 0x85 and config.hdmicec.tv_wakeup_detection.value == "sourcerequest": self.wakeup() elif cmd == 0x86 and config.hdmicec.tv_wakeup_detection.value == "streamrequest": physicaladdress = ord(data[0]) * 256 + ord(data[1]) ouraddress = eHdmiCEC.getInstance().getPhysicalAddress() if physicaladdress == ouraddress: self.wakeup() elif cmd == 0x46 and config.hdmicec.tv_wakeup_detection.value == "osdnamerequest": self.wakeup() elif cmd != 0x36 and config.hdmicec.tv_wakeup_detection.value == "activity": self.wakeup() def configVolumeForwarding(self, configElement): if config.hdmicec.enabled.value and config.hdmicec.volume_forwarding.value: self.volumeForwardingEnabled = True self.sendMessage(0x05, 'givesystemaudiostatus') else: self.volumeForwardingEnabled = False def keyEvent(self, keyCode, keyEvent): if not self.volumeForwardingEnabled: return cmd = 0 data = '' if keyEvent == 0: if keyCode == 115: cmd = 0x44 data = str(struct.pack('B', 0x41))<|fim▁hole|> if keyCode == 113: cmd = 0x44 data = str(struct.pack('B', 0x43)) if keyEvent == 2: if keyCode == 115: cmd = 0x44 data = str(struct.pack('B', 0x41)) if keyCode == 114: cmd = 0x44 data = str(struct.pack('B', 0x42)) if keyCode == 113: cmd = 0x44 data = str(struct.pack('B', 0x43)) if keyEvent == 1: if keyCode == 115 or keyCode == 114 or keyCode == 113: cmd = 0x45 if cmd: eHdmiCEC.getInstance().sendMessage(self.volumeForwardingDestination, cmd, data, len(data)) return 1 else: return 0 def sethdmipreemphasis(self): try: if config.hdmicec.preemphasis.value == True: file = open("/proc/stb/hdmi/preemphasis", "w") file.write('on') file.close() else: file = open("/proc/stb/hdmi/preemphasis", "w") file.write('off') file.close() except: return hdmi_cec = HdmiCec()<|fim▁end|>
if keyCode == 114: cmd = 0x44 data = str(struct.pack('B', 0x42))
<|file_name|>at2_e2.cc<|end_file_name|><|fim▁begin|>// // Copyright (c) 2014 Limit Point Systems, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /// @file /// Implementation for class at2_e2 #include "SheafSystem/at2_e2.impl.h" #include "SheafSystem/abstract_poset_member.impl.h" #include "SheafSystem/assert_contract.h" #include "SheafSystem/at0.h" #include "SheafSystem/at1_space.h" #include "SheafSystem/fiber_bundles_namespace.h" #include "SheafSystem/schema_poset_member.h" #include "SheafSystem/wsv_block.h" using namespace std; using namespace fiber_bundle; // Workaround for MS C++ bug. //============================================================================== // CLASS AT2_E2_LITE //============================================================================== //============================================================================== // AT2_E2 FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS fiber_bundle::at2_e2_lite:: at2_e2_lite() { // Preconditions: // Body: // Postconditions: ensure(invariant()); // Exit: } fiber_bundle::at2_e2_lite:: at2_e2_lite(const at2_e2_lite& xother) { // Preconditions: // Body: *this = xother; // Postconditions: ensure(invariant()); // Exit: } fiber_bundle::at2_e2_lite& fiber_bundle::at2_e2_lite:: operator=(const at2_e2_lite& xother) { // Preconditions: // Body: if(this == &xother) return *this; _row_dofs = xother._row_dofs; // Postconditions: ensure(invariant()); ensure(isunordered_or_equals(component(0), xother[0])); // Exit: return *this; } fiber_bundle::at2_e2_lite:: ~at2_e2_lite() { // Preconditions: // Body: // Postconditions: // Exit: } fiber_bundle::at2_e2_lite:: at2_e2_lite(const row_dofs_type& xrow_dofs) { // Preconditions: // Body: *this = xrow_dofs; // Postconditions: ensure(invariant()); // Exit: } fiber_bundle::at2_e2_lite& fiber_bundle::at2_e2_lite:: operator=(const row_dofs_type& xrow_dofs) { // Preconditions: // Body: _row_dofs = xrow_dofs; // Postconditions: ensure(invariant()); // Exit: return *this; } fiber_bundle::at2_e2_lite:: at2_e2_lite(const matrix_type& xmatrix) { // Preconditions: // Body: *this = xmatrix; // Postconditions: ensure(invariant()); // Exit: } fiber_bundle::at2_e2_lite& fiber_bundle::at2_e2_lite:: operator=(const matrix_type& xmatrix) { // Preconditions: // Body: _row_dofs = reinterpret_cast<const row_dofs_type&>(xmatrix); // Postconditions: ensure(invariant()); // Exit: return *this; } fiber_bundle::at2_e2_lite:: operator at2_e2_lite::matrix_type& () { // Preconditions: // Body: matrix_type& result = _row_dofs; // Postconditions: // Exit: return result; } fiber_bundle::at2_e2_lite:: operator const at2_e2_lite::matrix_type& () const { // Preconditions: // Body: const matrix_type& result = _row_dofs; // Postconditions: // Exit: return result; } fiber_bundle::at2_e2_lite:: operator at2_e2_lite::row_dofs_type& () { // Preconditions: // Body: row_dofs_type& result = _row_dofs; // Postconditions: // Exit: return result; } fiber_bundle::at2_e2_lite:: operator const at2_e2_lite::row_dofs_type& () const { // Preconditions: // Body: const row_dofs_type& result = _row_dofs; // Postconditions: // Exit: return result; } fiber_bundle::at2_e2_lite:: at2_e2_lite(const value_type& xy) { // Preconditions: // Body: put_component(xy); // Postconditions: ensure(invariant()); ensure(isunordered_or_equals(component(0), xy)); // Exit: } void fiber_bundle::at2_e2_lite:: put_component(value_type xy) { // Preconditions: // Body: put_component(0, xy); // Postconditions: ensure(invariant()); ensure(isunordered_or_equals(component(0), xy)); // Exit: } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // TENSOR ALGEBRA (TP) FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS int fiber_bundle::at2_e2_lite:: dd() const { // Preconditions: // Body: int result = 2; // Postconditions: ensure(invariant()); ensure(result == 2); // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // VECTOR ALGEBRA (VD) FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS const fiber_bundle::tp_lite& fiber_bundle::at2_e2_lite:: tp_prototype(int xp) const { // Preconditions: require(precondition_of(e2_lite::static_tp_prototype(xp))); // Body: const tp_lite& result = e2_lite::static_tp_prototype(xp); // Postconditions: ensure(postcondition_of(e2_lite::static_tp_prototype(xp))); // Exit: return result; } const fiber_bundle::atp_lite& fiber_bundle::at2_e2_lite:: atp_prototype(int xp) const { // Preconditions: require(precondition_of(e2_lite::static_atp_prototype(xp))); // Body: const atp_lite& result = e2_lite::static_atp_prototype(xp); // Postconditions: ensure(postcondition_of(e2_lite::static_atp_prototype(xp))); // Exit: return result; } const fiber_bundle::stp_lite& fiber_bundle::at2_e2_lite:: stp_prototype(int xp) const { // Preconditions: require(precondition_of(e2_lite::static_stp_prototype(xp))); // Body: const stp_lite& result = e2_lite::static_stp_prototype(xp); // Postconditions:<|fim▁hole|> ensure(postcondition_of(e2_lite::static_stp_prototype(xp))); // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // TUPLE FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // ABSTRACT POSET MEMBER FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS const std::string& fiber_bundle::at2_e2_lite:: class_name() const { // Preconditions: // Body: const string& result = static_class_name(); // Postconditions: ensure(!result.empty()); // Exit: return result; } const std::string& fiber_bundle::at2_e2_lite:: static_class_name() { // Preconditions: // Body: static const string result("at2_e2_lite"); // Postconditions: ensure(!result.empty()); // Exit: return result; } fiber_bundle::at2_e2_lite* fiber_bundle::at2_e2_lite:: clone() const { at2_e2_lite* result = 0; // Preconditions: // Body: result = new at2_e2_lite(); // Postconditions: ensure(result != 0); ensure(is_same_type(*result)); // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // ANY FACET OF CLASS AT2_E2_LITE //============================================================================== // PUBLIC MEMBER FUNCTIONS bool fiber_bundle::at2_e2_lite:: is_ancestor_of(const any_lite& xother) const { // Preconditions: require(&xother != 0); // Body: // True if other conforms to this. bool result = dynamic_cast<const at2_e2_lite*>(&xother) != 0; // Postconditions: return result; } bool fiber_bundle::at2_e2_lite:: invariant() const { bool result = true; if(invariant_check()) { // Prevent recursive calls to invariant. disable_invariant_check(); // Must satisfy base class invariant. invariance(at2_lite::invariant()); // Invariances for this class: // Finished, turn invariant checking back on. enable_invariant_check(); } // Exit return result; } void* fiber_bundle::at2_e2_lite:: row_dofs() { return &_row_dofs; } const void* fiber_bundle::at2_e2_lite:: row_dofs() const { return &_row_dofs; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // CLASS AT2_E2 //============================================================================== // =========================================================== // HOST FACTORY FACET OF CLASS AT2_E2 // =========================================================== // PUBLIC MEMBER FUNCTIONS const sheaf::poset_path& fiber_bundle::at2_e2:: standard_schema_path() { // Preconditions: // Body: static const poset_path result(standard_schema_poset_name(), "at2_e2_schema"); // Postconditions: // Exit: return result; } void fiber_bundle::at2_e2:: make_standard_schema(namespace_poset& xns) { // Preconditions: require(xns.state_is_read_write_accessible()); require(xns.contains_poset(standard_schema_poset_name())); require(!xns.contains_poset_member(standard_schema_path())); // Body: string lmember_names = "xy DOUBLE false"; schema_poset_member lschema(xns, standard_schema_path().member_name(), at2::standard_schema_path(), lmember_names, false); lschema.detach_from_state(); // Postconditions: ensure(xns.contains_poset_member(standard_schema_path())); // Exit: return; } fiber_bundle::at2_e2::host_type& fiber_bundle::at2_e2:: new_host(namespace_type& xns, const poset_path& xhost_path, const poset_path& xschema_path, const poset_path& xvector_space_path, bool xauto_access) { // cout << endl << "Entering at2_e2::new_host." << endl; // Preconditions: require(xns.state_is_auto_read_write_accessible(xauto_access)); require(!xhost_path.empty()); require(!xns.contains_path(xhost_path, xauto_access)); require(xschema_path.full()); require(xns.path_is_auto_read_accessible(xschema_path, xauto_access)); require(schema_poset_member::conforms_to(xns, xschema_path, standard_schema_path())); require(schema_poset_member::row_dof_ct(xns, xschema_path, xauto_access) == 1); require(xns.path_is_auto_read_accessible(xvector_space_path, xauto_access)); require(xns.contains_poset<vector_space_type::host_type>(xvector_space_path, xauto_access)); require(xns.member_poset(xvector_space_path, xauto_access).schema(xauto_access).conforms_to(vector_space_type::standard_schema_path())); require(xns.member_poset<vector_space_type::host_type>(xvector_space_path, xauto_access).d(xauto_access) == 2); // Body: host_type& result = host_type::new_table(xns, xhost_path, xschema_path, 2, xvector_space_path, xauto_access); // Postconditions: ensure(xns.owns(result, xauto_access)); ensure(result.path(true) == xhost_path); ensure(result.state_is_not_read_accessible()); ensure(result.schema(true).path(xauto_access) == xschema_path); ensure(result.factor_ct(true) == 1); ensure(result.d(true) == 1); ensure(result.scalar_space_path(true) == xns.member_poset<vector_space_type::host_type>(xvector_space_path, xauto_access).scalar_space_path()); ensure(result.p(true) == 2); ensure(result.dd(true) == 2); ensure(result.vector_space_path(true) == xvector_space_path); // Exit: // cout << "Leaving at2_e2::new_host." << endl; return result; } fiber_bundle::at2_e2::host_type& fiber_bundle::at2_e2:: standard_host(namespace_type& xns, const std::string& xsuffix, bool xauto_access) { // cout << endl << "Entering at2_e2::new_host." << endl; // Preconditions: require(xns.state_is_auto_read_write_accessible(xauto_access)); require(xsuffix.empty() || poset_path::is_valid_name(xsuffix)); require(standard_host_is_available<at2_e2>(xns, xsuffix, xauto_access)); require(xns.path_is_auto_read_accessible(standard_schema_path(), xauto_access)); require(xns.path_is_auto_read_available(standard_host_path<vector_space_type>(xsuffix), xauto_access)); // Body: // Create the vector space if necessary. poset_path lvector_space_path = vector_space_type::standard_host(xns, xsuffix, xauto_access).path(true); poset_path lpath(standard_host_path<at2_e2>(xsuffix)); host_type* result_ptr; if(xns.contains_path(lpath, xauto_access)) { result_ptr = &xns.member_poset<host_type>(lpath, xauto_access); } else { result_ptr = &new_host(xns, lpath, standard_schema_path(), lvector_space_path, xauto_access); } host_type& result = *result_ptr; // Postconditions: ensure(xns.owns(result, xauto_access)); ensure(result.path(true) == standard_host_path<at2_e2>(xsuffix)); ensure(result.state_is_not_read_accessible()); ensure(result.schema(true).path(xauto_access) == standard_schema_path()); ensure(result.factor_ct(true) == 1); ensure(result.d(true) == 1); ensure(result.scalar_space_path(true) == standard_host_path<vector_space_type::scalar_type>(xsuffix) ); ensure(result.p(true) == 2); ensure(result.dd(true) == 2); ensure(result.vector_space_path(true) == standard_host_path<vector_space_type>(xsuffix) ); // Exit: // cout << "Leaving at2_e2::new_host." << endl; return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // AT2_E2 FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS fiber_bundle::at2_e2:: at2_e2() { // Preconditions: // Body: // Postconditions: ensure(invariant()); } fiber_bundle::at2_e2:: at2_e2(const poset_state_handle* xhost, pod_index_type xhub_id) { // Preconditions: require(xhost != 0); require(xhost->state_is_read_accessible()); require(xhost->contains_member(xhub_id)); // Body: attach_to_state(xhost, xhub_id); // Postconditions: ensure(invariant()); // ensure(host() == xhost); ensure(index() == xhub_id); ensure(is_attached()); } fiber_bundle::at2_e2:: at2_e2(const poset_state_handle* xhost, const scoped_index& xid) { // Preconditions: require(xhost != 0); require(xhost->state_is_read_accessible()); require(xhost->contains_member(xid)); // Body: attach_to_state(xhost, xid.hub_pod()); // Postconditions: ensure(invariant()); // ensure(host() == xhost); ensure(index() ==~ xid); ensure(is_attached()); } fiber_bundle::at2_e2:: at2_e2(const poset_state_handle* xhost, const std::string& xname) { // Preconditions: require(xhost != 0); require(xhost->state_is_read_accessible()); require(!xname.empty()); require(xhost->contains_member(xname)); // Body: attach_to_state(xhost, xname); // Postconditions: ensure(invariant()); // ensure(host() == xhost); ensure(name() == xname); ensure(is_attached()); } fiber_bundle::at2_e2:: at2_e2(abstract_poset_member* xother) { // Preconditions: require(xother != 0); // Body: attach_to_state(xother); // Postconditions: ensure(invariant()); ensure(is_attached()); ensure(is_same_state(xother)); } fiber_bundle::at2_e2:: at2_e2(poset_state_handle* xhost, bool xauto_access) { // Preconditions: require(precondition_of(new_jim_state(xhost, 0, false, xauto_access))); // Body: new_jim_state(xhost, 0, false, xauto_access); // Postconditions: ensure(postcondition_of(new_jim_state(xhost, 0, false, xauto_access))); // Exit: return; } fiber_bundle::at2_e2:: at2_e2(poset_state_handle& xhost, const row_dofs_type& xrdt, bool xauto_access) { // Preconditions: require(precondition_of(new_jim_state(&xhost, 0, false, xauto_access))); // Body: new_jim_state(&xhost, 0, false, xauto_access); if(xauto_access) { xhost.get_read_write_access(); } *this = xrdt; if(xauto_access) { xhost.release_access(); } // Postconditions: ensure(postcondition_of(new_jim_state(&xhost, 0, false, xauto_access))); // Exit: return; } fiber_bundle::at2_e2& fiber_bundle::at2_e2:: operator=(const row_dofs_type& xrdt) { // Preconditions: require(state_is_read_write_accessible()); // Body: sheaf::row_dofs(*this) = xrdt; // Postconditions: ensure(isunordered_or_equals(component(0), xrdt.components[0])); // Exit: return *this; } /// fiber_bundle::at2_e2& fiber_bundle::at2_e2:: operator=(const abstract_poset_member& xother) { // Preconditions: require(is_ancestor_of(&xother)); require(precondition_of(attach_to_state(&xother))); // Body: attach_to_state(&xother); // Postconditions: ensure(postcondition_of(attach_to_state(&xother))); // Exit: return *this; } /// fiber_bundle::at2_e2& fiber_bundle::at2_e2:: operator=(const at2_e2& xother) { // Preconditions: require(precondition_of(attach_to_state(&xother))); // Body: attach_to_state(&xother); // Postconditions: ensure(postcondition_of(attach_to_state(&xother))); // Exit: return *this; } fiber_bundle::at2_e2:: ~at2_e2() { // Preconditions: // Body: // Postconditions: // Exit: } const fiber_bundle::at2_e2::volatile_type& fiber_bundle::at2_e2:: lite_prototype() const { // Preconditions: // Body: static const volatile_type result; // Postconditions: // Exit: return result; } /// fiber_bundle::at2_e2::volatile_type* fiber_bundle::at2_e2:: lite_type() const { // Preconditions: // Body: volatile_type* result = new volatile_type(sheaf::row_dofs(*this)); // Postconditions: // Exit: return result; } void fiber_bundle::at2_e2:: put_components(dof_type xy_comp) { // Preconditions: require(state_is_read_write_accessible()); // Body: put_component(0, xy_comp); // Postconditions: ensure(invariant()); ensure(isunordered_or_equals(component(0), xy_comp)); // Exit: return; } fiber_bundle::at2_e2:: operator at2_e2::row_dofs_type& () //operator row_dofs_type& () { // Preconditions: // Body: row_dofs_type& result = sheaf::row_dofs(*this); // Postconditions: // Exit: return result; } fiber_bundle::at2_e2:: operator const at2_e2::row_dofs_type& () const //operator const row_dofs_type& () const { // Preconditions: // Body: const row_dofs_type& result = sheaf::row_dofs(*this); // Postconditions: // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // AT2 FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // ATP FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // TP FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // VD FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // TUPLE FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS fiber_bundle::tp* fiber_bundle::at2_e2:: new_tp(int xp, bool xauto_access) const { // Preconditions: require(precondition_of(e2::new_tp(vector_space(xauto_access), xp))); // Body: tp* result = e2::new_tp(vector_space(xauto_access), xp); // Postconditions: ensure(postcondition_of(e2::new_tp(vector_space(xauto_access), xp))); // Exit: return result; } fiber_bundle::atp* fiber_bundle::at2_e2:: new_atp(int xp, bool xauto_access) const { // Preconditions: require(precondition_of(e2::new_atp(vector_space(xauto_access), xp))); // Body: atp* result = e2::new_atp(vector_space(xauto_access), xp); // Postconditions: ensure(postcondition_of(e2::new_atp(vector_space(xauto_access), xp))); // Exit: return result; } fiber_bundle::stp* fiber_bundle::at2_e2:: new_stp(int xp, bool xauto_access) const { // Preconditions: require(precondition_of(e2::new_stp(vector_space(xauto_access), xp))); // Body: stp* result = e2::new_stp(vector_space(xauto_access), xp); // Postconditions: ensure(postcondition_of(e2::new_stp(vector_space(xauto_access), xp))); // Exit: return result; } //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // ABSTRACT POSET MEMBER FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS const std::string& fiber_bundle::at2_e2:: class_name() const { // Preconditions: // Body: const string& result = static_class_name(); // Postconditions: ensure(!result.empty()); // Exit: return result; } const std::string& fiber_bundle::at2_e2:: static_class_name() { // Preconditions: // Body: static const string result("at2_e2"); // Postconditions: ensure(!result.empty()); // Exit: return result; } fiber_bundle::at2_e2* fiber_bundle::at2_e2:: clone() const { // Preconditions: // Body: // Create new handle of the current class. at2_e2* result = new at2_e2(); // Postconditions: ensure(result != 0); ensure(result->invariant()); // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // ANY FACET OF CLASS AT2_E2 //============================================================================== // PUBLIC MEMBER FUNCTIONS bool fiber_bundle::at2_e2:: is_ancestor_of(const any* xother) const { // Preconditions: require(xother != 0); // Body: bool result = dynamic_cast<const at2_e2*>(xother) != 0; // Postconditions: // Exit: return result; } bool fiber_bundle::at2_e2:: invariant() const { bool result = true; // Body: // Must satisfy base class invariant. invariance(at2::invariant()); if(invariant_check()) { // Prevent recursive calls to invariant. disable_invariant_check(); // Must satisfy base class invariant. invariance(at2::invariant()); // Invariances for this class: invariance((state_is_read_accessible() ? dd() == 2 : true)); // Finished, turn invariant checking back on. enable_invariant_check(); } // Exit: return result; } // PROTECTED MEMBER FUNCTIONS // PRIVATE MEMBER FUNCTIONS //============================================================================== // NON-MEMBER FUNCTIONS //============================================================================== #include "SheafSystem/at0.h" void fiber_bundle::atp_algebra:: hook(const e2& x0, const e2& x1, at0& xresult, bool xauto_access) { // Preconditions: require(x0.state_is_auto_read_accessible(xauto_access)); require(x1.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); require(x0.is_p_form(xauto_access) == x1.is_p_form(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); x1.get_read_access(); xresult.get_read_write_access(true); } // The hook operation is essentially a contract, so here we // could call the vd facet contract function here, but we'll // reimplement it for efficiency. vd_value_type a0 = x0.component(0); vd_value_type a1 = x0.component(1); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); vd_value_type lcomp = a0*b0 + a1*b1; xresult.put_component(0, lcomp); // Set the variance of the result. x0.is_p_form(false) ? xresult.put_is_p_form(false) : xresult.put_is_p_vector(false); if(xauto_access) { x0.release_access(); x1.release_access(); xresult.release_access(); } // Postconditions: ensure(xresult.is_p_form(xauto_access) == x0.is_p_form(xauto_access)); // Exit: return; } void fiber_bundle::atp_algebra:: hook(const e2_lite& x0, const e2_lite& x1, at0_lite& xresult) { // Preconditions: // Body: // The hook operation is essentially a contract, so we // could call the vd facet contract function here, but we'll // reimplement it for efficiency. vd_value_type a0 = x0.component(0); vd_value_type a1 = x0.component(1); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); vd_value_type lcomp = a0*b0 + a1*b1; xresult.put_component(0, lcomp); // Postconditions: // Exit: return; } void fiber_bundle::atp_algebra:: hook(const at2_e2& x0, const e2& x1, e2& xresult, bool xauto_access) { // Preconditions: require(x0.state_is_auto_read_accessible(xauto_access)); require(x1.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); require(x0.is_p_form(xauto_access) == x1.is_p_form(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); x1.get_read_access(); xresult.get_read_write_access(true); } // The hook operation is essentially a contract operation // on the first index. In 2d this is pretty simple, // so we implement it explicitly for efficiency. // at2_e2 has just 1 component. vd_value_type a = x0.component(0); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); int lrank = 2; vd_value_type lcomp0 = lrank*(-a*b1); vd_value_type lcomp1 = lrank*( a*b0); xresult.put_component(0, lcomp0); xresult.put_component(1, lcomp1); // Set the variance of the result. x0.is_p_form(false) ? xresult.put_is_p_form(false) : xresult.put_is_p_vector(false); if(xauto_access) { x0.release_access(); x1.release_access(); xresult.release_access(); } // Postconditions: ensure(xresult.is_p_form(xauto_access) == x0.is_p_form(xauto_access)); // Exit: return; } void fiber_bundle::atp_algebra:: hook(const at2_e2_lite& x0, const e2_lite& x1, e2_lite& xresult) { // Preconditions: // Body: // The hook operation is essentially a contract operation // on the first index. In 2d this is pretty simple, // so we implement it explicitly for efficiency. // at2_e2 has just 1 component. vd_value_type a = x0.component(0); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); int lrank = 2; vd_value_type lcomp0 = lrank*(-a*b1); vd_value_type lcomp1 = lrank*( a*b0); xresult.put_component(0, lcomp0); xresult.put_component(1, lcomp1); // Postconditions: // Exit: return; } void fiber_bundle::atp_algebra:: star(const at2_e2& x0, at0& xresult, bool xauto_access) { require(x0.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); xresult.get_read_write_access(true); } vd_value_type a123 = x0.component(0); xresult.put_component(0, a123); if(xauto_access) { x0.release_access(); xresult.release_access(); } // Postconditions: // Exit: return; } void fiber_bundle::atp_algebra:: star(const at2_e2_lite& x0, at0_lite& xresult) { // Preconditions: // Body: vd_value_type a123 = x0.component(0); xresult.put_component(0, a123); // Postconditions: ensure(xresult.component(0) == x0.component(0)); // Exit: return; } fiber_bundle::at0_lite* fiber_bundle::atp_algebra:: star(const at2_e2_lite& x0) { // Preconditions: require(precondition_of(star(x0, *result))); // Body: at0_lite* result = new at0_lite(); star(x0, *result); // Postconditions: ///@todo Postconditions. ensure(result != 0); ensure(postcondition_of(star(x0, *result))); // Exit: return result; } void fiber_bundle::atp_algebra:: star(const at0& x0, at2_e2& xresult, bool xauto_access) { require(x0.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); xresult.get_read_write_access(true); } vd_value_type lcomp123 = x0.component(0); xresult.put_component(0, lcomp123); define_old_variable(bool old_xresult_is_p_form = xresult.is_p_form(false)); if(xauto_access) { x0.release_access(); xresult.release_access(); } // Postconditions: ensure(xresult.is_p_form(xauto_access) == old_xresult_is_p_form); // Exit: return; } void fiber_bundle::atp_algebra:: star(const at0_lite& x0, at2_e2_lite& xresult) { // Preconditions: // Body: vd_value_type lcomp123 = x0.component(0); xresult.put_component(0, lcomp123); // Postconditions: ensure(xresult.component(0) == x0.component(0)); // Exit: return; } fiber_bundle::at2_e2_lite* fiber_bundle::atp_algebra:: star(const at0_lite& x0) { // Preconditions: require(precondition_of(star(x0, *result))); // Body: at2_e2_lite* result = new at2_e2_lite(); star(x0, *result); // Postconditions: ///@todo Postconditions. ensure(result != 0); ensure(postcondition_of(star(x0, *result))); // Exit: return result; } void fiber_bundle::atp_algebra:: star(const e2& x0, e2& xresult, bool xauto_access) { require(x0.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); xresult.get_read_write_access(true); } // In 2d the Hodge star operator maps a one-form to a new one-form represented // by orthogonal lines. So here we need to exchange the components and and // change the sign of one of them. We arbitrarily (?) change the sign on // the second component. vd_value_type lcomp0 = x0.component(1); vd_value_type lcomp1 = -x0.component(0); xresult.put_component(0, lcomp0); xresult.put_component(1, lcomp1); // Set the variance of the result. x0.is_p_form(false) ? xresult.put_is_p_form(false) : xresult.put_is_p_vector(false); if(xauto_access) { x0.release_access(); xresult.release_access(); } // Postconditions: ensure(xresult.is_p_form(xauto_access) == x0.is_p_form(xauto_access)); // Exit: return; } void fiber_bundle::atp_algebra:: star(const e2_lite& x0, e2_lite& xresult) { // Preconditions: // Body: // In 2d the Hodge star operator maps a one-form to a new one-form represented by // orthogonal lines. So here we need to exchange the components and and change // the sign of one of them. We arbitrarily (?) change the sign on the second // component. vd_value_type lcomp0 = x0.component(1); vd_value_type lcomp1 = -x0.component(0); xresult.put_component(0, lcomp0); xresult.put_component(1, lcomp1); // Postconditions: ///@todo Postconditions. //ensure(); // Exit: return; } fiber_bundle::e2_lite* fiber_bundle::atp_algebra:: star(const e2_lite& x0) { // Preconditions: // Body: e2_lite* result = new e2_lite(); star(x0, *result); // Postconditions: ensure(result != 0); // Exit: return result; } void fiber_bundle::atp_algebra:: wedge(const e2& x0, const e2& x1, at2_e2& xresult, bool xauto_access) { // Preconditions: require(x0.state_is_auto_read_accessible(xauto_access)); require(x1.state_is_auto_read_accessible(xauto_access)); require(xresult.state_is_auto_read_write_accessible(xauto_access)); require(x0.is_p_form(xauto_access) == x1.is_p_form(xauto_access)); // Body: if(xauto_access) { x0.get_read_access(); x1.get_read_access(); xresult.get_read_write_access(true); } // Access via virtual component required since // some descendants may not store components. vd_value_type a0 = x0.component(0); vd_value_type a1 = x0.component(1); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); vd_value_type lcomp = a0*b1 - a1*b0; xresult.put_component(0, lcomp); // Set the variance of the result. x0.is_p_form(false) ? xresult.put_is_p_form(false) : xresult.put_is_p_vector(false); if(xauto_access) { x0.release_access(); x1.release_access(); xresult.release_access(); } // Postconditions: ensure(xresult.is_p_form(xauto_access) == x0.is_p_form(xauto_access)); // Exit: return; } void fiber_bundle::atp_algebra:: wedge(const e2_lite& x0, const e2_lite& x1, at2_e2_lite& xresult) { // Preconditions: require(x0.is_same_type(x1)); require(x0.dd() == xresult.dd()); // Body: // Access via virtual component required since // some descendants may not store components. vd_value_type a0 = x0.component(0); vd_value_type a1 = x0.component(1); vd_value_type b0 = x1.component(0); vd_value_type b1 = x1.component(1); vd_value_type lcomp = a0*b1 - a1*b0; xresult.put_component(0, lcomp); // Postconditions: ///@todo Postconditions. //ensure(); // Exit: return; }<|fim▁end|>
<|file_name|>test-verifiers.cc<|end_file_name|><|fim▁begin|>// Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // These tests check that Torque-generated verifier functions crash the process // when encountering data that doesn't fit the Torque type definitions. <|fim▁hole|>#include "src/objects/map-inl.h" #include "test/cctest/cctest.h" #include "torque-generated/class-verifiers.h" namespace v8 { namespace internal { // Defines a pair of tests with similar code. The goal is to test that a // specific action causes a failure, but that everything else in the test case // succeeds. The general pattern should be: // // TEST_PAIR(Something) { // do_setup_steps_that_always_succeed(); // if (should_fail) { // do_the_step_that_fails(); // } // do_teardown_steps_that_always_succeed(); // } // // A corresponding entry in cctest.status specifies that all Fail* tests in this // file must fail. #define TEST_PAIR(Name) \ static void Name(bool should_fail); \ TEST(Pass##Name) { Name(false); } \ TEST(Fail##Name) { Name(true); } \ static void Name(bool should_fail) #ifdef VERIFY_HEAP TEST_PAIR(TestWrongTypeInNormalField) { CcTest::InitializeVM(); v8::Isolate* isolate = CcTest::isolate(); i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); v8::HandleScope scope(isolate); v8::Local<v8::Value> v = CompileRun("({a: 3, b: 4})"); Handle<JSObject> o = Handle<JSObject>::cast(v8::Utils::OpenHandle(*v)); Handle<Object> original_elements( TaggedField<Object>::load(*o, JSObject::kElementsOffset), i_isolate); CHECK(original_elements->IsFixedArrayBase()); // There must be no GC (and therefore no verifiers running) until we can // restore the modified data. DisallowHeapAllocation no_gc; // Elements must be FixedArrayBase according to the Torque definition, so a // JSObject should cause a failure. TaggedField<Object>::store(*o, JSObject::kElementsOffset, *o); if (should_fail) { TorqueGeneratedClassVerifiers::JSObjectVerify(*o, i_isolate); } // Put back the original value in case verifiers run on test shutdown. TaggedField<Object>::store(*o, JSObject::kElementsOffset, *original_elements); } TEST_PAIR(TestWrongStrongTypeInIndexedStructField) { CcTest::InitializeVM(); v8::Isolate* isolate = CcTest::isolate(); i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); v8::HandleScope scope(isolate); v8::Local<v8::Value> v = CompileRun("({a: 3, b: 4})"); Handle<Object> o = v8::Utils::OpenHandle(*v); Handle<Map> map(Handle<HeapObject>::cast(o)->map(), i_isolate); Handle<DescriptorArray> descriptors(map->instance_descriptors(kRelaxedLoad), i_isolate); int offset = DescriptorArray::OffsetOfDescriptorAt(1) + DescriptorArray::kEntryKeyOffset; Handle<Object> original_key(TaggedField<Object>::load(*descriptors, offset), i_isolate); CHECK(original_key->IsString()); // There must be no GC (and therefore no verifiers running) until we can // restore the modified data. DisallowHeapAllocation no_gc; // Key must be Name|Undefined according to the Torque definition, so a // JSObject should cause a failure. TaggedField<Object>::store(*descriptors, offset, *o); if (should_fail) { TorqueGeneratedClassVerifiers::DescriptorArrayVerify(*descriptors, i_isolate); } // Put back the original value in case verifiers run on test shutdown. TaggedField<Object>::store(*descriptors, offset, *original_key); } TEST_PAIR(TestWrongWeakTypeInIndexedStructField) { CcTest::InitializeVM(); v8::Isolate* isolate = CcTest::isolate(); i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); v8::HandleScope scope(isolate); v8::Local<v8::Value> v = CompileRun("({a: 3, b: 4})"); Handle<Object> o = v8::Utils::OpenHandle(*v); Handle<Map> map(Handle<HeapObject>::cast(o)->map(), i_isolate); Handle<DescriptorArray> descriptors(map->instance_descriptors(kRelaxedLoad), i_isolate); int offset = DescriptorArray::OffsetOfDescriptorAt(0) + DescriptorArray::kEntryValueOffset; Handle<Object> original_value(TaggedField<Object>::load(*descriptors, offset), i_isolate); // There must be no GC (and therefore no verifiers running) until we can // restore the modified data. DisallowHeapAllocation no_gc; // Value can be JSAny, which includes JSObject, and it can be Weak<Map>, but // it can't be Weak<JSObject>. TaggedField<Object>::store(*descriptors, offset, *o); TorqueGeneratedClassVerifiers::DescriptorArrayVerify(*descriptors, i_isolate); MaybeObject weak = MaybeObject::MakeWeak(MaybeObject::FromObject(*o)); TaggedField<MaybeObject>::store(*descriptors, offset, weak); if (should_fail) { TorqueGeneratedClassVerifiers::DescriptorArrayVerify(*descriptors, i_isolate); } // Put back the original value in case verifiers run on test shutdown. TaggedField<Object>::store(*descriptors, offset, *original_value); } TEST_PAIR(TestWrongOddball) { CcTest::InitializeVM(); v8::Isolate* isolate = CcTest::isolate(); i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); v8::HandleScope scope(isolate); v8::Local<v8::Value> v = CompileRun("new Date()"); Handle<JSDate> date = Handle<JSDate>::cast(v8::Utils::OpenHandle(*v)); Handle<Object> original_hour( TaggedField<Object>::load(*date, JSDate::kHourOffset), i_isolate); // There must be no GC (and therefore no verifiers running) until we can // restore the modified data. DisallowHeapAllocation no_gc; // Hour is Undefined|Smi|NaN. Other oddballs like null should cause a failure. TaggedField<Object>::store(*date, JSDate::kHourOffset, *i_isolate->factory()->null_value()); if (should_fail) { TorqueGeneratedClassVerifiers::JSDateVerify(*date, i_isolate); } // Put back the original value in case verifiers run on test shutdown. TaggedField<Object>::store(*date, JSDate::kHourOffset, *original_hour); } TEST_PAIR(TestWrongNumber) { CcTest::InitializeVM(); v8::Isolate* isolate = CcTest::isolate(); i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate); v8::HandleScope scope(isolate); v8::Local<v8::Value> v = CompileRun("new Date()"); Handle<JSDate> date = Handle<JSDate>::cast(v8::Utils::OpenHandle(*v)); Handle<Object> original_hour( TaggedField<Object>::load(*date, JSDate::kHourOffset), i_isolate); v8::Local<v8::Value> v2 = CompileRun("1.1"); Handle<Object> float_val = v8::Utils::OpenHandle(*v2); // There must be no GC (and therefore no verifiers running) until we can // restore the modified data. DisallowHeapAllocation no_gc; // Hour is Undefined|Smi|NaN. Other doubles like 1.1 should cause a failure. TaggedField<Object>::store(*date, JSDate::kHourOffset, *float_val); if (should_fail) { TorqueGeneratedClassVerifiers::JSDateVerify(*date, i_isolate); } // Put back the original value in case verifiers run on test shutdown. TaggedField<Object>::store(*date, JSDate::kHourOffset, *original_hour); } #endif // VERIFY_HEAP #undef TEST_PAIR } // namespace internal } // namespace v8<|fim▁end|>
#include "src/api/api-inl.h" #include "src/objects/descriptor-array.h"
<|file_name|>evlogger.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python # -*- coding: utf-8 -*- # # This file is part of hopr: https://github.com/hopr/hopr. # # Hopr is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Hopr is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Hopr. If not, see <http://www.gnu.org/licenses/>. from future import standard_library standard_library.install_aliases() from builtins import str from builtins import range from past.builtins import basestring from builtins import object import csv import sys from pickle import dump, load from collections import defaultdict from evdev import ecodes as e from hopr.backend.evdev import find_keyboards, read_events, etype from time import time import os import logging from pprint import pprint, pformat # TODO: Measure time spent pressing any particular key. How much time is spent pressing ctrl vs shift? # TODO: General timing info. How much time is spent typing? class SaveFile(object): def __init__(self, filename): self.filename = filename @property def temp_filename(self): return self.filename + '.tmp' def __enter__(self): self.file = open(self.temp_filename, 'wb') return self def __exit__(self, exc, exc_type, exc_tb): os.fsync(self.file.fileno()) self.file.close() # Rename temp file to filename os.rename(self.temp_filename, self.filename) def key_name(code): if code is None: return 'NONE' else: name = e.keys[code] if not isinstance(name, basestring): name = name[0] return name.replace('KEY_', '') def key_code(name): if name == 'NONE': return None else: return e.ecodes['KEY_' + name] def append(history, code): history[:-1] = history[1:] history[-1] = code def tuplify(x): if isinstance(x, tuple): return x else: return (x,) def save_ngrams(filename, ngrams): n_ngrams = len(ngrams) n_event = sum([n for _,n in list(ngrams.items())]) logging.info('Saving: {filename} n-grams: {n_ngrams} event_count: {n_event}'.format(**locals())) key_header = None with SaveFile(filename) as f: w = csv.writer(f.file) for (keys, values) in list(ngrams.items()): keys = tuplify(keys) values = tuplify(values) if not key_header: key_header = ['key{}'.format(i+1) for i in range(len(keys))] value_header = ['value'] w.writerow(key_header + value_header) w.writerow(keys + values) def save_csv(filename, log): for (tag, sublog) in list(log.items()): save_ngrams(filename + '.' + tag, sublog) def empty_sublog(): return defaultdict(int) def empty_log(): return defaultdict(empty_sublog) def load_ngrams(filename): ngrams = empty_sublog() reader = csv.reader(open(filename, 'rb')) header = next(reader) assert header[-1] == 'value' n = len(header) - 1 for row in reader: key = tuple(int(code) for code in row[:-1]) n = int(row[-1]) ngrams[key] = n return ngrams # def load_csv(filename): # log = empty_log() # for fname in glob(filename + '.*'): # tag = fname.replace('filename.', '') # sublog = load_ngrams(fname) def load_pickle(filename): return load(open(filename, 'rb')) def save_pickle(filename, log): logging.info('Saving log: {}'.format(dict((key, len(value)) for key,value in list(log.items())))) with SaveFile(filename) as f: dump(log, f.file, protocol=2) # def save_csv(filename, log): # save_ngrams(filename + '.bigrams', log['event']) # save_ngrams(filename + '.events', log['press2']) load_log = load_pickle def save_log(filename, log): save_pickle(filename, log) save_csv(filename, log) def start(filename, save_interval): " Log statistics for all keyboard events " if os.path.exists(filename): log = load_log(filename) else: log = empty_log() press = [None]*2 last_save = 0 try: for ev in read_events(find_keyboards()): if time() - last_save > save_interval: save_log(filename, log) last_save = time() if ev.type == e.EV_KEY: logging.debug('{}'.format(ev)) log[etype.name(ev.value)][key_name(ev.code)] += 1 if ev.value == etype.KEY_PRESS: append(press, key_name(ev.code)) log['PRESS2'][tuple(press)] += 1 except KeyboardInterrupt as SystemExit: logging.info('Quitting. Saving log') save_log(filename, log) except Exception as exc: logging.error('Unexpected exception' + str(exc)) raise def view(filename): x = load_log(filename) events = {} for ((code, value), count) in list(x['event'].items()): key = '{}={}'.format(key_name(code), value) events[key] = count<|fim▁hole|> print('Key Count') pprint(events) press = {} for ((code1, code2), count) in list(x['press2'].items()): key = '{},{}'.format(key_name(code1), key_name(code2)) press[key] = count print('Paired event count') pprint(press) # def print_pairs(filename): # x = load_log(filename) # pairs = x['press2'] # codes = sorted(set([c for pair in pairs for c in pair])) # code2idx = dict((c,idx) for (idx, c) in enumerate(codes)) # N = len(codes) # count = [[0]*N for _ in range(N)] # for ((code1, code2), n) in x['press2'].items(): # count[code2idx[code1]][code2idx[code2]] += n # codes = [key_name(code) for code in codes] # w = csv.writer(sys.stdout) # w.writerow([''] + codes) # for code, row in zip(codes, count): # w.writerow([code] + row) def summary(filename, top): x = load_log(filename) press = [] hold = [] for ((code, value), count) in list(x['event'].items()): if value == etype.KEY_PRESS: press.append((count, key_name(code))) elif value == etype.KEY_HOLD: hold.append((count, key_name(code))) print('Key Press') pprint(sorted(press, reverse=True)[:top]) print('Key Hold') pprint(sorted(hold, reverse=True)[:top]) press2 = [] for ((code1, code2), count) in list(x['press2'].items()): # TODO: Option. Ignore repeated key presses. if code1 != code2: key = '{},{}'.format(key_name(code1), key_name(code2)) press2.append((count, key)) print('Paired event count') pprint(sorted(press2, reverse=True)[:top]) def run(cmd, verbose, **kwargs): if verbose: logging.getLogger().setLevel(level=logging.DEBUG) logging.debug('Running {} with args {}'.format(cmd, pformat(kwargs))) f = globals()[cmd] f(**kwargs) def run_parse_args(args): from argparse import ArgumentParser p = ArgumentParser() p.add_argument('-v', '--verbose', action='store_true') sp = p.add_subparsers(dest='cmd') q = sp.add_parser('start') q.add_argument('-i', '--save_interval', default=60.0, type=float) # TODO: Global file name arg. q.add_argument('filename', nargs='?', default='out/evlogger.log') q = sp.add_parser('view') q.add_argument('filename', nargs='?', default='out/evlogger.log') q = sp.add_parser('summary') q.add_argument('filename', nargs='?', default='out/evlogger.log') q.add_argument('-t', '--top', default=15, type=int) # q = sp.add_parser('print_pairs') # q.add_argument('filename', nargs='?', default='out/evlogger.log') x = p.parse_args(args) logging.debug('parse args: {}'.format(x)) run(**vars(x)) if __name__ == "__main__": import sys run_parse_args(sys.argv[1:]) # run_parse_args('-v print_pairs'.split())<|fim▁end|>
<|file_name|>Message.js<|end_file_name|><|fim▁begin|>var _ = require('underscore'), Backbone = require('backbone'), DAL = require('../DAL'); var Message = Backbone.Model.extend( /** @lends Message.prototype */ { defaults: { userId: null, waveId: null, parentId: null, message: '', unread: true, created_at: null }, idAttribute: '_id', /** @constructs */ initialize: function () { if (this.isNew()) {<|fim▁hole|> }, save: function () { return DAL.saveMessage(this); }, validate: function (attrs) { if (0 === attrs.message.trim().length) { return 'Empty message'; } } } ); /** @class */ var MessageCollection = Backbone.Collection.extend( /** @lends MessageCollection.prototype */ { model: Message } ); module.exports = { Model: Message, Collection: MessageCollection };<|fim▁end|>
this.set('created_at', Date.now()); }
<|file_name|>coval.py<|end_file_name|><|fim▁begin|># Atomic covalent radius data # http://www.periodictable.com/Properties/A/CovalentRadius.an.html # Updated Jun. 9th, 2016 class Covalent(object):<|fim▁hole|> "Al": 1.18, "Si": 1.11, "P": 1.06, "S": 1.02, "Cl": 0.99, "Ar": 0.97, "K": 1.96, "Ca": 1.74, "Sc": 1.44, "Ti": 1.36, "V": 1.25, "Cr": 1.27, "Mn": 1.39, "Fe": 1.25, "Co": 1.26, "Ni": 1.21, "Cu": 1.38, "Zn": 1.31, "Ga": 1.26, "Ge": 1.22, "As": 1.19, "Se": 1.16, "Br": 1.14, "Kr": 1.10, "Rb": 2.11, "Sr": 1.92, "Y": 1.62, "Zr": 1.48, "Nb": 1.37, "Mo": 1.45, "Tc": 1.56, "Ru": 1.26, "Rh": 1.35, "Pd": 1.31, "Ag": 1.53, "Cd": 1.48, "In": 1.44, "Sn": 1.41, "Sb": 1.38, "Te": 1.35, "I": 1.33, "Xe": 1.30, "Cs": 2.25, "Ba": 1.98, "La": 1.69, "Ce": 0.00, "Pr": 0.00, "Nd": 0.00, "Pm": 0.00, "Sm": 0.00, "Eu": 0.00, "Gd": 0.00, "Tb": 0.00, "Dy": 0.00, "Ho": 0.00, "Er": 0.00, "Tm": 0.00, "Yb": 0.00, "Lu": 1.60, "Hf": 1.50, "Ta": 1.38, "W": 1.46, "Re": 1.59, "Os": 1.28, "Ir": 1.37, "Pt": 1.28, "Au": 1.44, "Hg": 1.49, "Tl": 1.48, "Pb": 1.47, "Bi": 1.46, "Po": 0.00, "At": 0.00, "Rn": 1.45, "Fr": 0.00, "Ra": 0.00, "Ac": 0.00, "Th": 0.00, "Pa": 0.00, "U": 0.00, "Np": 0.00, "Pu": 0.00, "Am": 0.00, "Cm": 0.00, "Bk": 0.00, "Cf": 0.00, "Es": 0.00, "Fm": 0.00, "Md": 0.00, "No": 0.00, "Lr": 0.00, "Rf": 0.00, "Db": 0.00, "Sg": 0.00, "Bh": 0.00, "Hs": 0.00, "Mt": 0.00, "Ds": 0.00, "Rg": 0.00, "Uub": 0.00, "Uut": 0.00, "Uuq": 0.00, "Uup": 0.00, "Uuh": 0.00, "Uus": 0.00, "Uuo": 0.00 }<|fim▁end|>
x = { "H": 0.37, "He": 0.32, "Li": 1.34, "Be": 0.90, "B": 0.82, "C": 0.77, "N": 0.75, "O": 0.73, "F": 0.71, "Ne": 0.69, "Na": 1.54, "Mg": 1.30,
<|file_name|>Portal.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 from __future__ import print_function import datetime import calendar import logging import time import re import os import os.path from abc import ABCMeta from abc import abstractmethod from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException from PIL import Image import PortalProperties __version__ = "1.0.1" __author__ = "Jose Miguel Colella" __email__ = "[email protected]" __license__ = "MIT" logger = logging.getLogger(__name__) logging.basicConfig( filename="portal.log", format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG) class AbstractPortal(object): """AbstractPortal is an abstract class that encapsulates all the common attributes and methods of the Synthetic Portal such as username, password, login Attributes: driver (selenium.webdriver.phantomjs.webdriver.WebDriver): The webdriver instance """ __metaclass__ = ABCMeta screenshotDebugDir = "screenshotDebug" def __init__(self, username, password): assert type(username) is str, print("username is a string") assert type(password) is str, print("password is a string") # If the operating system is windows or *nix. self._osNull = { "nt": "NUL", "posix": "/dev/null" } self.driver = webdriver.PhantomJS( service_log_path=self._osNull[os.name], service_args=["--ignore-ssl-errors=true"]) self.driver.maximize_window() self.windowSize = self.driver.get_window_size() self._username = username self._password = password self._screenshotDebugDumpDirPath = "{path}/{directory}".format( path=os.getcwd(), directory=AbstractPortal.screenshotDebugDir) self._checkDumpDirIsCreated() @property @abstractmethod def homePage(self): """ str: The url of the portal """ pass @property @abstractmethod def usernameInputIdentifier(self): """ str: The DOM attribute to fetch the username <input> """ pass @property @abstractmethod def passwordInputIdentifier(self): """ str: The DOM attribute to fetch the password <input> """ pass @property @abstractmethod def submitButtonIdentifier(self): """ str: The DOM attribute to fetch the log in button """ pass @property def username(self): """ str: The username used to login. (Read-Only) """ return self._username @property def password(self): """ str: The password used to login.(Read-Only) """ return self._password def _checkDumpDirIsCreated(self): if not os.path.isdir(self.screenshotDebugDir): os.mkdir(self._screenshotDebugDumpDirPath) def _saveDebugScreenshot(self, screenshotName): self.driver.save_screenshot( "{}/{}-{}.png".format(AbstractPortal.screenshotDebugDir, datetime.datetime.today(), screenshotName)) def login(self): """login() inputs the username and password into the corresponding DOM elements of the home page and establishes a session that allows for the interaction """ logging.debug("Fetching Dynatrace Login Page") self.driver.get(self.homePage) logging.debug("Finish fetching page") self._saveDebugScreenshot("Home") usernameInput = self.driver.find_element_by_name( self.usernameInputIdentifier) passwordInput = self.driver.find_element_by_name( self.passwordInputIdentifier) logging.debug("Sending username credentials") usernameInput.send_keys(self.username) logging.debug("Sending password credentials") passwordInput.send_keys(self.password) submitButton = self.driver.find_element_by_id( self.submitButtonIdentifier) logging.debug("Sending button click") submitButton.click() logging.debug("Waiting for page to load") def close(self): """Closes the driver session and the phantomjs process. """ self.driver.quit() class GPNPortal(AbstractPortal): tableId = "ctl00_Content_XFSummaryTable" endOfMonthProjectionIdentifier = "ctl00_Content_XFProjectedUsage" accountsListIdentifier = "identity-btn-name" accountsListDropdownIdentifier = "divIdentityList" def __init__(self, username, password): super(GPNPortal, self).__init__(username, password) self.accountsList = set()<|fim▁hole|> @property def homePage(self): return "https://www.gomeznetworks.com/index.asp?g=1" @property def usernameInputIdentifier(self): return "username" @property def passwordInputIdentifier(self): return "pwd" @property def submitButtonIdentifier(self): return "loginbutton" def _getCurrentAccountName(self): currentAccountName = self.driver.find_element_by_id( "identity-btn-name").text return currentAccountName def login(self): super(GPNPortal, self).login() try: WebDriverWait(self.driver, 30).until( EC.visibility_of_element_located((By.CLASS_NAME, "black-1"))) except Exception: logging.warning("The page could not load") time.sleep(5) self.portalWindow = self.driver.current_window_handle self._saveDebugScreenshot("Login") def getXFMeasurement(self, startDay=1, endDay=calendar.monthrange(datetime.date.today().year, datetime.date.today().month)[1], startMonth=datetime.date.today().month, endMonth=datetime.date.today().month): """getXFMeasurement(startDay, endDay, startMonth, endMonth) returns the XF consumption for the current account calculating the monthly offset, end of month projection, and the sum of the xf measurements from `startDay` to `endDay` Args: startDay (Optional[int]): The initial day to get the XF measurements. Defaults to 1 endDay (Optional[int]): The last day to get the XF measurements. Defaults to the last day of the month startMonth (Optional[int]): The starting month from which to fetch the XF measurements. Defaults to current month endMonth (Optional[int]): The ending month from which to fetch the XF measurem Returns: XFMeasurement: an instance of the XFMeasurement class initialized with the monthly offset, end of month projection, and the sum of the XF measurements from `startDay` to `endDay` Raises: AssertionError: If `startMonth` is not equal to `endMonth`. The GPN Portal will only show XF consumption measurement one month at a time """ assert startMonth == endMonth, "Expected startMonth to be equal to endMonth. {} is not equal to {}".format( startMonth, endMonth) currentYear = datetime.date.today().year xfConsumptionPage = "https://www.gomeznetworks.com/reports/flexReport.aspx?x=&startdate={startYear}/{startMonth}/{startDay}&enddate={endYear}/{endMonth}/{endDay}".format( startYear=currentYear, startMonth=startMonth, startDay=startDay, endYear=currentYear, endMonth=endMonth, endDay=endDay ) self.driver.execute_script( "window.open('{}')" .format(xfConsumptionPage)) self.driver.switch_to_window(self.driver.window_handles[1]) try: WebDriverWait(self.driver, 30).until( EC.visibility_of_element_located((By.ID, "ctl00$Content$Chart"))) except Exception: logging.warning("The page could not load") print("Account: {}".format( self.driver.find_element_by_class_name("black-1").text)) xfConsumption = PortalProperties.XFMeasurement() xfConsumption.setEndOfMonthProjection( self.driver.find_element_by_id(GPNPortal.endOfMonthProjectionIdentifier).text) summaryTable = self.driver.find_element_by_id(GPNPortal.tableId) xfMeasurementHtmlTable = summaryTable.find_elements_by_tag_name("td") xfConsumption.setXFTable(xfMeasurementHtmlTable) xfConsumption.setSumXFMeasurement(startDay, endDay) xfConsumption.setMonthlyOffset(endDay) return xfConsumption def switchAccount(self): if len(self.driver.window_handles) > 1: self.driver.execute_script("window.close()") self.driver.switch_to_window(self.driver.window_handles[0]) cleanAccountName = lambda account: ( re.search(self.accountNameRegex, account).group("accountName")).strip() self.accountsList.add(cleanAccountName(self._getCurrentAccountName())) # Button needs to be clicked in order to see other accounts self.driver.find_element_by_id( GPNPortal.accountsListIdentifier).click() accountList = self.driver.find_element_by_id( GPNPortal.accountsListDropdownIdentifier) # Everything but the first and last element as the first element is the tr -> Switch accounts and the last tr # has an empty name accountListRows = accountList.find_elements_by_tag_name("tr")[1:-1] accounts = [{"name": cleanAccountName(accountListRow.text), "node": accountListRow} for accountListRow in accountListRows if cleanAccountName(accountListRow.text) not in self.accountsList] logging.info(accounts) # Click the first account in the dropdown accounts[0]["node"].click() try: WebDriverWait(self.driver, 30).until( EC.visibility_of_element_located((By.CLASS_NAME, "black-1"))) except Exception: logging.warning("The page could not load") time.sleep(5) logging.info("Current Account: {}".format( cleanAccountName(self._getCurrentAccountName()))) self._saveDebugScreenshot("SwitchAccount.png") logging.info(self.accountsList) class DynatracePortal(AbstractPortal): monitorAnalyzeId = "monitoranalyze" interactiveChartId = "apmInteractiveChart" chartsClass = "apm-btn-link" logoutId = "sign-out" iframeName = "apmframe" chartsUrl = "http://cr02.dynatrace.com/en_US/group/guest/interactive-charts" @property def homePage(self): return "https://www.gomezapm.com" @property def usernameInputIdentifier(self): return "username" @property def passwordInputIdentifier(self): return "pw" @property def submitButtonIdentifier(self): return "signIn" def __init__(self, username, password): super(DynatracePortal, self).__init__(username, password) # Sets the driver to wait 10 seconds to poll the DOM. Very useful for # sites like Dynatrace Portal that take a while to load elements self.driver.implicitly_wait(10) self.chartsCaptured = set() self.currentAccountName = self.username self.croppingChartsDimension = { "left": 675, "up": 270, "right": 675, "down": 150 } self.performanceMapDimension = { "right": 600, "up": 285, "left": 600, "down": 400 } def _cropElement(self, selectorType, selector, sourceFile, destinationFile="output.png"): """Allows for cropping elements from an image given a selectorType, and selector as well as a destination file to save the element to. Args: selectorType (str): The selector type for the DOM element, e.g "id", "class", "name" selector (str): The selector to be extract sourceFile (str): The name of the file to crop destinationFile (str[optional]): The name o """ assert selectorType in {"id", "class", "name", "tag"} try: if selectorType is "id": elements = self.driver.find_elements_by_id(selector) elif selectorType is "class": elements = self.driver.find_elements_by_class_name(selector) elif selectorType is "name": elements = self.driver.find_elements_by_name(selector) elif selectorType is "tag": elements = self.driver.find_elements_by_tag_name(selector) else: pass chartImage = Image.open(sourceFile) for element in elements: if sum(element.location.values()) is not 0 and sum(element.size.values()) is not 0: left = element.location["x"] top = element.location["y"] right = element.location["x"] + element.size["width"] bottom = element.location["y"] + element.size["height"] croppedImage = chartImage.crop((left, top, right, bottom)) croppedImage.save(destinationFile) chartImage.close() except NoSuchElementException: raise NoSuchElementException def login(self): super(DynatracePortal, self).login() try: WebDriverWait(self.driver, 30).until( EC.presence_of_element_located((By.ID, DynatracePortal.monitorAnalyzeId))) logging.info( "Successfully logged in with user: {}".format(self.username)) except Exception: logging.warning("WARNING: The login page could not load") logging.debug("Sleeping for 15 seconds") time.sleep(15) self._saveDebugScreenshot("Login") def getInteractiveCharts(self): logging.debug("navigating to charts URL") self.driver.get(DynatracePortal.chartsUrl) try: WebDriverWait(self.driver, 60).until( EC.invisibility_of_element_located((By.CLASS_NAME, "gwt-Image"))) except Exception: logging.warn( "WARNING: Element could not be found within the time frame") logging.debug("Sleeping for 15 seconds") time.sleep(15) self._saveDebugScreenshot("ChartsAvailable") def getChartPage(self, chartName): self.getInteractiveCharts() chartTimeoutSeconds = 60 availableCharts = self.driver.find_elements_by_class_name( DynatracePortal.chartsClass) try: chartNodes = filter( lambda node: node.text == chartName and node.text != "", availableCharts) chartNode = next(chartNodes) # Click on chart node chartNode.click() try: wait = WebDriverWait(self.driver, chartTimeoutSeconds) wait.until(EC.visibility_of_element_located((By.TAG_NAME, "svg"))) except Exception: raise Exception("No chart element was found during {}".format(chartTimeoutSeconds)) logging.debug("Sleeping for 20 seconds") time.sleep(20) except Exception: raise Exception("Expected valid chart name. Available charts are: {}".format( [elem.text for elem in availableCharts if elem.text != ""])) def saveChartToScreenshot(self, chartName, specificElements=[], saveDir="."): """saveChartToScreenshot saves a screenshot of the `chartName` provided as a parameter. Args: chartName (str): The name of the chart to get the screenshot specificElement(list): The web element to crop cropChart (Optional[bool]): Crop only chart section. Defaults to False saveDir (Optional[str]): The directory to save the screenshot. Defaults to '.' """ self.getChartPage(chartName) imageName = "{}/{}-uncropped.png".format(saveDir, chartName) self.driver.save_screenshot(imageName) if specificElements: typeSelectorList = [(specificElements[element], specificElements[ element + 1]) for element in range(0, len(specificElements), 2)] try: for specificElement in typeSelectorList: saveFileName = "{}/{}-{}.png".format(saveDir, chartName, specificElement[1]) self._cropElement(specificElement[0], specificElement[1], imageName, saveFileName) logging.info("Finished saving {destination} screenshot to {directory} directory".format( destination=saveFileName, directory=saveDir)) if os.path.isfile(imageName): os.remove(imageName) except SystemError: pass<|fim▁end|>
self.accountNameRegex = re.compile(r":(?P<accountName>.+):")
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! Abstracts out the APIs necessary to `Runtime` for integrating the blocking //! pool. When the `blocking` feature flag is **not** enabled, these APIs are //! shells. This isolates the complexity of dealing with conditional //! compilation. mod pool; pub(crate) use pool::{spawn_blocking, BlockingPool, Mandatory, Spawner, Task}; cfg_fs! { pub(crate) use pool::spawn_mandatory_blocking; } mod schedule; mod shutdown; mod task; pub(crate) use schedule::NoopSchedule; pub(crate) use task::BlockingTask; use crate::runtime::Builder; pub(crate) fn create_blocking_pool(builder: &Builder, thread_cap: usize) -> BlockingPool { BlockingPool::new(builder, thread_cap) } /* cfg_not_blocking_impl! { use crate::runtime::Builder; use std::time::Duration; #[derive(Debug, Clone)] pub(crate) struct BlockingPool {} pub(crate) use BlockingPool as Spawner; pub(crate) fn create_blocking_pool(_builder: &Builder, _thread_cap: usize) -> BlockingPool { BlockingPool {} }<|fim▁hole|> } pub(crate) fn shutdown(&mut self, _duration: Option<Duration>) { } } } */<|fim▁end|>
impl BlockingPool { pub(crate) fn spawner(&self) -> &BlockingPool { self
<|file_name|>address.rs<|end_file_name|><|fim▁begin|>extern crate e2d2; use e2d2::utils::*; use std::net::Ipv4Addr; use std::str::FromStr; <|fim▁hole|> let pfx = Ipv4Prefix::new(u32::from(Ipv4Addr::from_str("192.168.0.0").unwrap()), 16); assert!(pfx.in_range(u32::from(Ipv4Addr::from_str("192.168.0.1").unwrap()),)); assert!(pfx.in_range(u32::from_be(16820416))); assert!(pfx.in_range(u32::from(Ipv4Addr::from_str("192.168.100.1").unwrap()),)); assert!(pfx.in_range(u32::from(Ipv4Addr::from_str("192.168.2.1").unwrap()),)); assert!(!pfx.in_range(u32::from(Ipv4Addr::from_str("192.163.0.1").unwrap()),)); assert!(pfx.in_range(u32::from(Ipv4Addr::from_str("192.168.0.0").unwrap()),)); assert!(pfx.in_range(u32::from(Ipv4Addr::from_str("192.168.255.255").unwrap()),)); let pfx = Ipv4Prefix::new(u32::from(Ipv4Addr::from_str("192.168.1.2").unwrap()), 32); assert!(pfx.in_range(u32::from(Ipv4Addr::from_str("192.168.1.2").unwrap()),)); assert!(!pfx.in_range(u32::from(Ipv4Addr::from_str("192.168.1.3").unwrap()),)); let pfx = Ipv4Prefix::new(u32::from(Ipv4Addr::from_str("0.0.0.0").unwrap()), 0); assert!(pfx.in_range(u32::from(Ipv4Addr::from_str("192.168.1.2").unwrap()),)); assert!(pfx.in_range(u32::from(Ipv4Addr::from_str("2.2.2.2").unwrap()),)); let pfx = Ipv4Prefix::new(u32::from(Ipv4Addr::from_str("0.0.0.0").unwrap()), 0); assert!(pfx.in_range(u32::from(Ipv4Addr::from_str("192.168.1.2").unwrap()),)); assert!(pfx.in_range(u32::from(Ipv4Addr::from_str("2.2.2.2").unwrap()),)); }<|fim▁end|>
#[test] fn address_inline() {
<|file_name|>vtysh_utils.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # (C) Copyright 2016 Hewlett Packard Enterprise Development LP # All Rights Reserved. #<|fim▁hole|># not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # ########################################################################## from time import sleep vtysh_cr = "\r\n" route_max_wait_time = 300 class SwitchVtyshUtils(): @staticmethod def vtysh_cfg_cmd(switch, cfg_array, show_running_cfg=False, show_results=False): switch("configure terminal") for cmd in cfg_array: result = switch(cmd) if show_results: print("### Config results: %s ###\n" % result) switch("end") @staticmethod def wait_for_route(switch, network, next_hop, condition=True, print_routes=False): for i in range(route_max_wait_time): attempt = i + 1 found = SwitchVtyshUtils.verify_bgp_route(switch, network, next_hop, attempt, print_routes) if found == condition: if condition: result = "Route was found" else: result = "Route was not found" print("### %s ###\n" % result) return found sleep(1) print("### Condition not met after %s seconds ###\n" % route_max_wait_time) return found @staticmethod def verify_bgp_route(switch, network, next_hop, attempt=1, print_routes=False): print("### Verifying route on switch %s [attempt #%d] - Network: %s, " "Next-Hop: %s ###\n" % (switch.name, attempt, network, next_hop)) routes = switch("show ip bgp") if print_routes: print("### Routes for switch %s ###\n" % switch.name) print("%s\n" % routes) routes = routes.split(vtysh_cr) for rte in routes: if (network in rte) and (next_hop in rte): return True routes = switch("show ipv6 bgp") if print_routes: print("### Routes for switch %s ###\n" % switch.name) print("%s\n" % routes) routes = routes.split(vtysh_cr) for rte in routes: if (network in rte) and (next_hop in rte): return True return False @staticmethod def verify_cfg_exist(switch, cfg_array): return SwitchVtyshUtils.verify_cfg_value(switch, cfg_array, '') @staticmethod def verify_cfg_value(switch, cfg_array, value): running_cfg = SwitchVtyshUtils.vtysh_get_running_cfg(switch) running_cfg = running_cfg.split(vtysh_cr) for rc in running_cfg: for c in cfg_array: if (c in rc) and (str(value) in rc): return True return False @staticmethod def vtysh_get_running_cfg(switch): return switch("show running-config") __all__ = ["SwitchVtyshUtils"]<|fim▁end|>
# Licensed under the Apache License, Version 2.0 (the "License"); you may
<|file_name|>pixied.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import argparse import ipaddress import gevent import gevent.wsgi import hashlib import json import traceback from gevent import monkey from werkzeug.exceptions import (BadRequest, HTTPException, InternalServerError, NotFound) from werkzeug.routing import Map, Rule, RequestRedirect from werkzeug.wrappers import Request, Response from werkzeug.wsgi import responder monkey.patch_all() IMAGE_METHOD = 'tftp' BOOTSCRIPT = """#!ipxe :retry dhcp && isset ${{filename}} || goto retry echo Booting from ${{filename}} kernel {image_method}://${{next-server}}/vmlinuz.img quiet pixie_server=${{next-server}} \ ip=${{ip}}::${{gateway}}:${{netmask}}::eth0:none:${{dns}} {wipe} pixie_root_size={root_size} \ pixie_swap_size={swap_size} pixie_sha224={sha224} {extra_args} || goto error initrd {image_method}://${{next-server}}//initrd.img || goto error boot || goto error error: shell """ CONFIGSCRIPT = """#!ipxe :retry dhcp && isset ${{filename}} || goto retry echo Booting from ${{filename}} kernel {image_method}://${{next-server}}/vmlinuz.img quiet \ ip=${{ip}}::${{gateway}}:${{netmask}}::eth0:none:${{dns}} \ SERVER_IP=${{next-server}}{collector_prefix} || goto error initrd {image_method}://${{next-server}}//doconfig.img || goto error boot || goto error error: shell """ class ScriptHandler(object): def __init__(self, configs, collector_prefix): self.configs = [] self.default_config = dict() self.default_config['image_method'] = IMAGE_METHOD self.default_config['collector_prefix'] = collector_prefix for config in configs: self.configs.append(self.load_config(config)) self.router = Map([ Rule('/', methods=['GET'], endpoint='default'), Rule('/wipe', methods=['GET'], endpoint='wipe') ]) def load_config(self, config): with open(config) as c: cfg = json.load(c) m = hashlib.sha224() m.update(bytes(cfg['subnet'], 'utf-8')) m.update(bytes(cfg['swap_size'])) m.update(bytes(cfg['root_size'])) m.update(bytes(cfg['extra_args'], 'utf-8')) # TODO: check sizes for f in cfg['hashes']: with open(f, 'rb') as fl: for line in fl: m.update(line) cfg['sha224'] = m.hexdigest() cfg['subnet'] = ipaddress.ip_network(cfg['subnet']) cfg['image_method'] = IMAGE_METHOD return cfg @responder def __call__(self, environ, start_response): try: return self.wsgi_app(environ, start_response) except: traceback.print_exc() return InternalServerError() def wsgi_app(self, environ, start_response): route = self.router.bind_to_environ(environ) try: endpoint, args = route.match() except RequestRedirect as e: return e except HTTPException: return NotFound() request = Request(environ) get_args = dict(request.args) if endpoint == 'wipe': get_args['wipe'] = 'pixie_wipe=force' else: get_args['wipe'] = "" response = Response() response.mimetype = 'text/plain' response.status_code = 200 config = None if 'ip' in get_args: ip_addr = ipaddress.ip_address(get_args['ip'][0]) for cfg in self.configs: if ip_addr in cfg['subnet']: config = cfg<|fim▁hole|> if config is None: response.data = CONFIGSCRIPT.format(**self.default_config) else: for (k, v) in config.items(): get_args[k] = v response.data = BOOTSCRIPT.format(**get_args) return response if __name__ == '__main__': parser = argparse.ArgumentParser( description="pixied", formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("configs", action="store", type=str, nargs="+", help="config files to load") parser.add_argument("-a", "--addr", action="store", type=str, default="0.0.0.0", help="address to bind to (default '0.0.0.0')") parser.add_argument("-p", "--port", action="store", type=int, default=8080, help="port to bind to (default 8080)") parser.add_argument("-c", "--collector-prefix", action="store", type=str, default="/pixie_collector", help="prefix on which the collector is served") args = parser.parse_args() server = gevent.wsgi.WSGIServer( (args.addr, args.port), ScriptHandler(args.configs, args.collector_prefix)) gevent.spawn(server.serve_forever).join()<|fim▁end|>
<|file_name|>resolver.js<|end_file_name|><|fim▁begin|>"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ramda_1 = require("ramda"); var render_instance_1 = require("./render-instance"); var types_1 = require("./types"); function deepResolver(mapper, renderer) { return function (comp) { var resolve = deepResolver(mapper, renderer); var mapped = mapper(comp); if (types_1.isShallow(mapped)) { var newComp = renderer(mapped.instance); // note that newComp might be shallow again, so we need to call // deepResolver on it to resolve the whole the tree return resolve(newComp); } if (types_1.isHtml(mapped)) return ramda_1.merge(mapped, { children: mapped.children.map(resolve) }); return mapped;<|fim▁hole|>function shallowResolver(mapper, _) { return function (comp) { var resolve = shallowResolver(mapper, _); var mapped = mapper(comp); if (types_1.isShallow(mapped)) { return render_instance_1.toArtificialHtml(mapped); } if (types_1.isHtml(mapped)) { return ramda_1.merge(mapped, { children: mapped.children.map(resolve) }); } return mapped; }; } exports.shallowResolver = shallowResolver; function interleavedResolver(mapper, renderer, nonRoot) { return function (comp) { var resolve = interleavedResolver(mapper, renderer, true); var mapped = mapper(comp); if (types_1.isShallow(mapped)) { var newComp = renderer(mapped.instance); // note that newComp might be shallow again, so we need to call // interleavedResolver on it to render the whole the tree var renderedComp = resolve(newComp); return render_instance_1.toArtificialHtml(mapped, renderedComp); } if (types_1.isHtml(mapped)) { var mappedWithChildren = ramda_1.merge(mapped, { children: mapped.children.map(resolve) }); return nonRoot ? mappedWithChildren : render_instance_1.toArtificialHtml(mappedWithChildren, mappedWithChildren); } return mapped; }; } exports.interleavedResolver = interleavedResolver;<|fim▁end|>
}; } exports.deepResolver = deepResolver;
<|file_name|>ghostedit-core-1.0.0-pre.js<|end_file_name|><|fim▁begin|>/* Lasso range library Name: Lasso Description: Lightweight, crossbrowser javascript library for creating and modifying ranges. Used by the GhostEdit editor. Licence: Dual licensed under MIT and LGPL licenses. Browser Support: Internet Explorer 6+, Mozilla Firefox 3.5+, Google Chrome, Apple Safari 3+, Opera 10.50+, Any other browser that supports DOMranges or TextRanges Author: Nico Burns <[email protected]> Website: http://ghosted.it/lasso Version: 1.5.0 Release Date: --- Changelog: Changes to the node selection functions. Change to deleteContents() for TextRange browsers (ie) Added clearSelection(); Available methods: Native range: setFromNative(nativerange) getNative() Selection: setToSelection() select() clearSelection() Modify range: reset() setStartToRangeStart(lasso object | range) setStartToRangeEnd(lasso object | range) setEndToRangeStart(lasso object | range) setStartToRangeEnd(lasso object | range) Modify content: deleteContents() pasteText(string) Get content: getText() extractText() getHTML() extractHTML() Node/element: selectNode(node) selectNodeContents(node) [only works on block elements in ie8] setCaretToStart(elem | elemid) setCaretToEnd(elem | elemid) Range information: isCollapsed() compareEndPoints() getStartNode() getEndNode() getParentNode() getStartElement() getEndElement() Save & restore: saveToDOM() restoreFromDOM() isSavedRange() removeDOMmarkers() bookmarkify() [ie <= 8 only] unbookmarkify() [ie <= 8 only] other: clone() inspect() Example usage: 1. Set the caret to the end of an element with ID 'testelem': lasso().setCaretToEnd('testelem').select(); 2. Get the currently selected text lasso().setToSelection().getText(); */ window.lasso = function() { //define local range object to be returned at end var r = { saved: null, endpoint: null, startpoint: null, bookmark: null, textrange: false, domrange: false, isLassoObject: true }, lasso = window.lasso, console = window.console || {}; console.log = console.log || function () {}; r.init = r.reset = r.create = function () { if(document.createRange) { r.textrange = false; r.saved = document.createRange(); } else if (document.selection) { r.textrange = true; r.saved = document.body.createTextRange(); } r.bookmark = false; r.domrange = !r.textrange; return r; }; r.setToEmpty = function () { if (r.domrange) { r.saved = document.createRange(); } else if (r.textrange) { r.saved = document.body.createTextRange(); } return r; }; /* Native Range Functions */ r.setFromNative = function (nativerange) { r.saved = nativerange; return r; }; r.getNative = function () { return r.saved; }; /* Selection Functions */ r.setToSelection = function () { var s; if(r.domrange) { s = window.getSelection(); if(s.rangeCount > 0) { r.saved = s.getRangeAt(0).cloneRange(); } } else if (r.textrange) { r.saved = document.selection.createRange(); } return r; }; r.select = function () { if (r.domrange) { var s = window.getSelection(); if (s.rangeCount > 0) s.removeAllRanges(); s.addRange(r.saved); } else if (r.textrange) { r.saved.select(); } return r; }; r.clearSelection = function () { if (r.domrange) { var s = window.getSelection(); if (s.rangeCount > 0) s.removeAllRanges(); } else if (r.textrange) { document.selection.empty(); } return r; }; /* Modify Range Functions */ r.collapseToStart = function () { r.saved.collapse(true); return r; }; r.collapseToEnd = function () { r.saved.collapse(false); return r; }; r.setStartToRangeStart = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setStart(range.startContainer, range.startOffset); } else if (r.textrange) { r.saved.setEndPoint("StartToStart", range); } return r; }; r.setStartToRangeEnd = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setStart(range.endContainer, range.endOffset); } else if (r.textrange) { r.saved.setEndPoint("StartToEnd", range); } return r; }; r.setEndToRangeStart = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setStart(range.endContainer, range.endOffset); } else if (r.textrange) { r.saved.setEndPoint("EndToStart", range); } return r; }; r.setEndToRangeEnd = function (range) { if (range && range.saved) range = range.getNative(); if (r.domrange) { r.saved.setEnd(range.endContainer, range.endOffset); } else if (r.textrange) { r.saved.setEndPoint("EndToEnd", range); } return r; }; /* Modify Content Functions */ r.deleteContents = function () { if (r.domrange) { r.saved.deleteContents(); } else if (r.textrange) { /* TextRange deleting seems quite buggy - these *should* work, but text = "" has been most successful so far try { r.saved.pasteHTML(""); } catch (e) { r.saved.execCommand("delete"); }*/ r.saved.text = ""; } return r; }; r.pasteText = function (text, collapse) { if(typeof collapse === "undefined") collapse = true; r.deleteContents(); if (r.domrange) { var txt = document.createTextNode(text); r.saved.insertNode(txt); r.reset().selectNodeContents(txt); } else if (r.textrange) { r.saved.pasteHTML(text); } if (collapse) r.collapseToEnd(); r.select(); return r; }; r.insertNode = function (node, collapse) { var div; if(typeof collapse === "undefined") collapse = true; r.deleteContents(); if (r.domrange) { r.saved.insertNode(node); r.setToEmpty().selectNodeContents(node); } else if (r.textrange) { div = document.createNode("div"); div.appendChild(node); r.saved.pasteHTML(div.innerHTML); } if (collapse) r.collapseToEnd(); //r.select(); return r; }; /* Get Content Functions */ r.getText = function () { if (r.domrange) { return r.saved.toString(); } else if (r.textrange) { return r.saved.text; } }; r.extractText = function () { var text = r.getText(); r.deleteContents(); return text; }; r.getHTML = function () { var tempelem, docfrag; if (r.domrange) { docfrag = r.saved.cloneContents(); tempelem = document.createElement("div"); tempelem.appendChild(docfrag); return tempelem.innerHTML; } else if (r.textrange) { return r.saved.htmlText; } }; r.extractHTML = function () { var html = r.getHTML(); r.deleteContents(); return html; }; /* Node/Element Functions */ r.actualSelectNode = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNode(elem); } else if (r.textrange) { r.saved.moveToElementText(elem); } return r; }; <|fim▁hole|> r.saved.selectNodeContents(elem); } else if (r.textrange) { r.saved.moveToElementText(elem); } return r; }; //Only works on block elements in ie8 r.selectNodeContents = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); var r1, r2; if (r.domrange) { r.saved.selectNodeContents(elem); } else if (r.textrange) { r.saved.moveToElementText(elem); r1 = lasso().setCaretToStart(elem).getNative(); r2 = lasso().setCaretToEnd(elem).getNative(); r.saved.setEndPoint("StartToStart", r1); r.saved.setEndPoint("EndToStart", r2); } return r; }; r.setCaretToStart = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(true); } else if (r.textrange) { /*elem.innerHTML = "<span id=\"range_marker\">&#x200b;</span>" + elem.innerHTML; r.selectNode('range_marker');//.deleteContents(); // For some reason .deleteContents() sometimes deletes too much document.getElementById('range_marker').parentNode.removeChild(document.getElementById('range_marker'));*/ r.saved.moveToElementText(elem); r.saved.collapse(true); } return r; }; r.setCaretToBlockStart = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(true); } else if (r.textrange) { r.saved.moveToElementText(elem); r.saved.collapse(false); r.saved.move("character", -(elem.innerText.length + 1)); } return r; }; r.selectInlineStart = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(true).select(); } else if (r.textrange) { elem.innerHTML = "a" + elem.innerHTML; // The 'a' is arbitrary, any single character will work r.saved.moveToElementText(elem); r.saved.collapse(false); r.saved.move("character", -(elem.innerText.length + 1)); r.saved.moveEnd("character", 1); r.saved.select(); r.saved.text = ""; } return r; }; r.setCaretToEnd = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) { r.saved.selectNodeContents(elem); r.saved.collapse(false); } else if (r.textrange) { /*elem.innerHTML = elem.innerHTML + "<span id=\"range_marker\">&#x200b;</span>"; r.selectNode('range_marker');//.deleteContents(); document.getElementById('range_marker').parentNode.removeChild(document.getElementById('range_marker'));*/ r.saved.moveToElementText(elem); r.saved.collapse(false); } return r; }; /* Range Information Functions */ r.isCollapsed = function () { if (r.domrange) { return r.saved.collapsed; } else if (r.textrange) { //return r.saved.compareEndPoints("StartToEnd", r.saved) === 0 ? true : false; return r.saved.isEqual(r.clone().collapseToStart().saved); } }; r.compareEndPoints = function (how, range) { var R; if (range && range.saved) range = range.getNative(); if (r.domrange) { // Note that EndToStart and StartToEnd are reversed (to make compatible with ie order) R = window.Range; var howlookup = {"StartToStart": R.START_TO_START, "StartToEnd": R.END_TO_START, "EndToStart": R.START_TO_END, "EndToEnd": R.END_TO_END}; how = howlookup[how]; return r.saved.compareBoundaryPoints(how, range); } else if (r.textrange) { return r.saved.compareEndPoints(how, range); } }; r.isEqualTo = function (range) { if (range && range.saved) range = range.getNative(); if (r.compareEndPoints("StartToStart", range) !== 0) return false; if (r.compareEndPoints("EndToEnd", range) !== 0) return false; return true; }; r.getStartNode = function () { if (r.domrange) { return r.saved.startContainer; } else if (r.textrange) { var range = r.saved.duplicate(); range.collapse(true); return range.parentElement(); } }; r.getEndNode = function () { if (r.domrange) { return r.saved.endContainer; } else if (r.textrange) { var range = r.saved.duplicate(); range.collapse(false); return range.parentElement(); } }; r.getParentNode = function () { if (r.domrange) { return r.saved.commonAncestorContainer; } else if (r.textrange) { return r.saved.parentElement(); } }; r.getStartElement = function () { return r.util.getParentElement( r.getStartNode() ); }; r.getEndElement = function () { return r.util.getParentElement( r.getEndNode() ); }; r.getParentElement = function () { if (r.domrange) { return r.util.getParentElement( r.saved.commonAncestorContainer); } else if (r.textrange) { return r.saved.parentElement(); } }; /* Clone Function */ r.clone = function () { var r2 = lasso(); if(r.domrange) { r2.saved = r.saved.cloneRange(); } else if (r.textrange) { r2.saved = r.saved.duplicate(); } r2.bookmark = r.cloneBookmark(); return r2; }; /* Save and Restore Functions (save to DOM) */ r.saveToDOM = function (id) { var start, end, smark, emark, collapsed; if (!id) id = "lasso"; r.removeDOMmarkers(id); collapsed = r.isCollapsed(); start = r.clone().collapseToStart().getNative(); if (!collapsed) end = r.clone().collapseToEnd().getNative(); if (r.domrange) { smark = document.createElement("span"); smark.innerHTML = "&#x200b"; smark.id = id + "_range_start"; start.insertNode(smark); if (!collapsed) { emark = document.createElement("span"); emark.innerHTML = "&#x200b"; emark.id = id + "_range_end"; end.insertNode(emark); } } else if (r.textrange) { start.pasteHTML("<span id=\"" + id + "_range_start\">&#x200b;</span>"); if (!collapsed) { end.pasteHTML("<span id=\"" + id + "_range_end\">&#x200b;</span>"); } } // Restore in case selection is lost by changing DOM above r = r.restoreFromDOM(id, false) || r.reset(); return r; }; r.restoreFromDOM = function (id, removemarkers) { var start, end, smark, emark; if (!id || id === "" || id === true || id === false) id = "lasso"; if (id === true) removemarkers = true; smark = document.getElementById(id + "_range_start"); emark = document.getElementById(id + "_range_end"); if (!smark) return false; start = lasso().actualSelectNode(smark).collapseToEnd(); if (removemarkers !== false) smark.parentNode.removeChild(smark); if (emark) { end= lasso().actualSelectNode(emark).collapseToStart(); if (removemarkers !== false) emark.parentNode.removeChild(emark); } else { end = start; } r = lasso().setStartToRangeStart(start).setEndToRangeEnd(end); return r; }; r.isSavedRange = function (id) { if (!id) id = "lasso"; return (document.getElementById(id + "_range_start")) ? true : false; }; r.removeDOMmarkers = function (id) { var smark, emark; if (!id) id = "lasso"; smark = document.getElementById(id + "_range_start"); emark = document.getElementById(id + "_range_end"); if (smark) smark.parentNode.removeChild(smark); if (emark) emark.parentNode.removeChild(emark); }; /* More save and restore functions (save reference from root node) */ r.bookmarkify = function (rootnode) { if (r.domrange) { var node, startnodeoffsets, endnodeoffsets, b = {}; if (!rootnode || !rootnode.nodeType) return r; // Save start and end offset to bookmark b.startoffset = r.saved.startOffset; b.endoffset = r.saved.endOffset; // Get start node offset path relative to rootnode startnodeoffsets = []; node = r.saved.startContainer; while (node !== rootnode) { startnodeoffsets.unshift(r.util.getNodeOffset(node)); node = node.parentNode; if (node === null) return r; } // Get end node offset path relative to rootnode endnodeoffsets = []; node = r.saved.endContainer; while (node !== rootnode) { endnodeoffsets.unshift(r.util.getNodeOffset(node)); node = node.parentNode; if (node === null) return r; } // Save paths to bookmark b.startnodeoffsets = startnodeoffsets.join("-"); b.endnodeoffsets = endnodeoffsets.join("-"); // Save rootnode to bookmark (used to show that bookmark exists) b.rootnode = rootnode; r.bookmark = b; } else if (r.textrange) { r.bookmark = r.saved.getBookmark(); } return r; }; r.unbookmarkify = function (rootnode) { var bookmark = r.bookmark; if (r.domrange) { var node, offset, startnodeoffsets, endnodeoffsets, startcontainer, endcontainer; if (!bookmark.rootnode || !rootnode) return r.setToEmpty(); node = rootnode; startnodeoffsets = bookmark.startnodeoffsets.split("-"); while (startnodeoffsets.length > 0) { offset = startnodeoffsets.shift(); if (!node.childNodes || !node.childNodes[offset]) return r.setToEmpty(); node = node.childNodes[offset]; } startcontainer = node; node = rootnode; endnodeoffsets = bookmark.endnodeoffsets.split("-"); while (endnodeoffsets.length > 0) { offset = endnodeoffsets.shift(); if (!node.childNodes || !node.childNodes[offset]) return r.setToEmpty(); node = node.childNodes[offset]; } endcontainer = node; r.setToEmpty(); r.saved.setStart(startcontainer, bookmark.startoffset); r.saved.setEnd(endcontainer, bookmark.endoffset); } else if (r.textrange) { if (r.bookmark) { r.reset().saved.moveToBookmark(bookmark); r.bookmarkify(); } } return r; }; r.clearBookmark = function () { r.bookmark = false; return r; }; r.cloneBookmark = function (bookmark) { if (!bookmark) bookmark = r.bookmark; if (r.domrange) { return !bookmark ? false : { "rootnode": bookmark.rootnode, "startnodeoffsets": bookmark.startnodeoffsets, "endnodeoffsets": bookmark.endnodeoffsets, "startoffset": bookmark.startoffset, "endoffset": bookmark.endoffset }; } else if (r.textrange) { if (!bookmark) return false; var r2 = lasso().getNative(); return r2.moveToBookmark(bookmark) ? r2.getBookmark() : false; } }; /* Inspection and debugging functions */ r.inspect = function (logid) { console.log({ logid: logid ? logid : "", startelement: r.getStartElement(), startnode: r.getStartNode(), endelement: r.getEndElement(), endnode: r.getEndNode(), text: r.getText(), html: r.getHTML(), parent: r.getParentNode() }); }; /* Utility, 'non-public' functions, used by other functions */ r.util = { //Used only for next two functions (getStartElement and getEndElement) getParentElement: function (node) { if (node.nodeType !== 1) { while (node.nodeType !== 1) { node = node.parentNode; if (node === null) return null; } } return node; }, getNodeOffset: function (node) { if (!node || !node.parentNode) return; var offset = 0; while (node.parentNode.childNodes[offset] !== node) { offset += 1; } return offset; } }; r.init(); return r; }; (function(window, undefined) { // Create ghostedit object and global variables var _ghostedit = { version: "1.0pre", enabledplugins: [], ready: false, active: false, isEditing: true, blockElemId: 0, editorchrome: null, debug: false }; // Empty object for references to any elements which need to be globally accesable to be stored on _ghostedit.el = {}; // Empty api object for plugins and init functions to add to _ghostedit.api = {}; // Empty object for plugins to be stored in _ghostedit.plugins = {}; // Add the ghostedit object to the global namespace window.ghostedit = _ghostedit; })(window); (function(window, undefined) { window.ghostedit.init = function (source, options) { if (typeof source === "string") source = document.getElementById(source); var i, handler, ghostedit = window.ghostedit, rootnode, uilayer, htmlelem; // Set up user options ghostedit.options = {}; ghostedit.options = options || {}; // Check for debug option (but only enable if log module exists) if (ghostedit.options.debug) { ghostedit.debug = true; } // Detect whether we need to add extra br's to work around firefox's bugs (also used for webkit and opera) ghostedit.browserEngine = ghostedit.util.detectEngines(); ghostedit.useMozBr = (ghostedit.browserEngine.gecko !== 0 || ghostedit.browserEngine.webkit !== 0 || ghostedit.browserEngine.opera !== 0); //Hide div containing original content source.style.display = 'none'; ghostedit.el.source = source; // Create contextual ui layer uilayer = document.createElement("div"); uilayer.id = "ghostedit_uilayer"; uilayer.className = "ghostedit_uilayer"; uilayer.innerHTML = "<span style='position: absolute; display: none;left: 0; top: 0;line-height: 0'>ie bug fix</span>"; source.parentNode.insertBefore(uilayer, source); ghostedit.el.uilayer = uilayer; // Run init events for core modules ghostedit.history.init(); ghostedit.inout.init(); ghostedit.clipboard.init(); // Enable plugins ghostedit.options.plugins = ghostedit.options.plugins || []; ghostedit.options.plugins.unshift("container", "textblock"); if (ghostedit.options.plugins) { for (i = 0; i < ghostedit.options.plugins.length; i++) { ghostedit.api.plugin.enable(ghostedit.options.plugins[i]); } } // Send init event to plugins (and core modules) ghostedit.event.trigger("init"); // Import initial content rootnode = ghostedit.inout.importHTML(source); source.parentNode.insertBefore(rootnode, source); ghostedit.el.rootnode = rootnode; // Focus the editor handler = rootnode.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].focus(rootnode); // Make sure that FF uses tags not CSS, and doesn't show resize handles on images try{document.execCommand("styleWithCSS", false, false);} catch(err){}//makes FF use tags for contenteditable try{document.execCommand("enableObjectResizing", false, false);} catch(err){}//stops resize handles being resizeable in FF // Save selection & setup undo ghostedit.selection.save(); ghostedit.history.reset(); ghostedit.history.saveUndoState(); // Attach event handlers to html element htmlelem = document.getElementsByTagName("html")[0]; ghostedit.util.addEvent(htmlelem, "dragenter", ghostedit.util.cancelEvent); ghostedit.util.addEvent(htmlelem, "dragleave", ghostedit.util.cancelEvent); ghostedit.util.addEvent(htmlelem, "dragover", ghostedit.util.cancelEvent); ghostedit.util.addEvent(htmlelem, "drop", ghostedit.util.cancelEvent); // Attach handlers to rootnode ghostedit.util.addEvent(rootnode, "click", ghostedit.selection.save); ghostedit.util.addEvent(rootnode, "mouseup", ghostedit.selection.save); ghostedit.util.addEvent(rootnode, "keyup", ghostedit.selection.save); ghostedit.util.addEvent(rootnode, "keydown", function (event) {ghostedit.event.keydown(this, event); }); ghostedit.util.addEvent(rootnode, "keypress", function (event) {ghostedit.event.keypress(this, event); }); ghostedit.util.addEvent(rootnode, "dragenter", ghostedit.util.cancelEvent); ghostedit.util.addEvent(rootnode, "dragleave", ghostedit.util.cancelEvent); ghostedit.util.addEvent(rootnode, "dragover", ghostedit.util.cancelEvent); ghostedit.util.addEvent(rootnode, "drop", ghostedit.util.cancelEvent); // Focus rootnode rootnode.focus(); ghostedit.plugins.container.focus(rootnode); ghostedit.ready = true; ghostedit.event.trigger("init:after"); }; })(window); (function (window, undefined) { var _plugins = {}, ghostedit = window.ghostedit; _plugins.register = function(name, object) { if (ghostedit.plugins[name]) return false; ghostedit.plugins[name] = object; return true; }; _plugins.enable = function (name) { if (!ghostedit.plugins[name]) return false; if (ghostedit.enabledplugins[name]) _plugins.disable(name); var plugin = ghostedit.plugins[name]; if (typeof(plugin.enable) === "function") { plugin.enable(); } ghostedit.enabledplugins[name] = true; }; _plugins.disable = function (name) { if (!ghostedit.enabledplugins[name] || !ghostedit.plugins[name]) return false; var plugin = ghostedit.plugins[name]; if (typeof(plugin.disable) === "function") { plugin.disable(); } ghostedit.enabledplugins[name] = false; }; window.ghostedit.api.plugin = _plugins; })(window); (function (window, undefined) { var _util = {}; _util.trim = function (string) { return string.replace(/^\s+/, "").replace(/\s+$/, ""); }; // This will call a function using a reference with predefined arguments. //SECOND ARGUMENT = CONTEXT (this) - should usually be false _util.preparefunction = function (func, context /*, 0..n args */) { var args = Array.prototype.slice.call(arguments, 2); return function() { var allArguments = args.concat(Array.prototype.slice.call(arguments)); return func.apply(context ? context : this, allArguments); }; }; _util.isFunction = function (variable) { if (!variable) return false; if (typeof variable !== "function") return false; return true; }; _util.cloneObject = function (obj) { var copy, len, i, attr; // Handle the 3 simple types, and null or undefined if (null === obj || "object" !== typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (i = 0, len = obj.length; i < len; ++i) { copy[i] = _util.cloneObject(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = _util.cloneObject(obj[attr]); } return copy; } }; _util.addClass = function (elem, c) { elem.className = _util.trim(elem.className) + " " + c; }; _util.removeClass = function (elem, c) { var r = new RegExp(c,"g"); elem.className = _util.trim(elem.className.replace(r, "")); }; _util.cancelEvent = function (e) { if (e && e.preventDefault) { e.stopPropagation(); // DOM style (return false doesn't always work in FF) e.preventDefault(); } else if (e) { e.returnValue = false; } return false; // false = IE style }; _util.cancelAllEvents = function (e) { if (e && e.preventDefault) { e.stopPropagation(); // DOM style (return false doesn't always work in FF) e.preventDefault(); } else if (window.event) { window.event.cancelBubble = true; //IE cancel bubble; } return false; // false = IE style }; _util.preventDefault = function (e) { // Standards based browsers if (e && e.preventDefault) { e.preventDefault(); } // ie <= 8 return false; }; _util.preventBubble = function (e) { // Standards based browsers if (e && e.stopPropagation) { e.stopPropagation(); } // ie <= 8 if (window.event) window.event.cancelBubble = true; }; _util.addEvent = function (elem, eventType, handle) { if (elem.addEventListener !== undefined) { elem.addEventListener(eventType, handle, false); } else { elem.attachEvent("on" + eventType, handle); } }; _util.removeEvent = function (elem, eventType, handle) { if (elem.removeEventListener !== undefined) { elem.removeEventListener(eventType, handle, false); } else { elem.detachEvent("on" + eventType, handle); } }; _util.ajax = function (URL, method, params, sHandle, dataType) { var time, connector, xhr; if (!URL || !method) return false; // Get XHR object xhr = false; if(window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject)) { xhr = new window.XMLHttpRequest(); } else { try { xhr = new window.ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { xhr = new window.ActiveXObject("MSXML2.XMLHTTP"); } catch (e2) {} } } if (!xhr) return false; // Prepare variables method = method.toUpperCase(); time = new Date().getTime(); URL = URL.replace(/(\?)+$/, ""); connector = (URL.indexOf('?') === -1) ? "?" : "&"; //connector = (URL.indexOf('?') === URL.length - 1) ? "" : "&"; // Open ajax Request if (method === "GET") { xhr.open(method, URL + connector + time + "&" + params, true); } else { xhr.open(method, URL + connector + time, true); } // Define function to handle response xhr.onreadystatechange = function () { var responseData; if(xhr.readyState === 4) { if(xhr.status === 200) { responseData = (dataType === "xml") ? xhr.responseXML : xhr.responseText; if (sHandle !== null){ sHandle(true, responseData); } return true; } else{ if (sHandle !== null){ sHandle(false, responseData); } return false; } } }; // Set HTTP headers xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //xhr.setRequestHeader("Content-length", params.length); //xhr.setRequestHeader("Connection", "close"); // Send ajax request if (method === "POST" && params !== null) { xhr.send(params); } else { xhr.send(); } }; _util.detectEngines = function() { //rendering engines var engine = {ie: 0, gecko: 0, webkit: 0, khtml: 0, opera: 0, ver: null}; // Detect rendering engines/browsers var ua = navigator.userAgent; if (window.opera){ engine.ver = window.opera.version(); engine.opera = parseFloat(engine.ver); } else if (/AppleWebKit\/(\S+)/.test(ua)){ engine.ver = RegExp.$1; engine.webkit = parseFloat(engine.ver); } else if (/KHTML\/(\S+)/.test(ua) || /Konqueror\/([^;]+)/.test(ua)){ engine.ver = RegExp.$1; engine.khtml = parseFloat(engine.ver); } else if (/rv:([^\)]+)\) Gecko\/\d{8}/.test(ua)){ engine.ver = RegExp.$1; engine.gecko = parseFloat(engine.ver); } else if (/MSIE ([^;]+)/.test(ua)){ engine.ver = RegExp.$1; engine.ie = parseFloat(engine.ver); } //return it return engine; }; window.ghostedit.util = _util; })(window); (function(window, undefined) { var _event = { listeners: [], listenerid: 0, eventtypes: [], cancelKeypress: false //allows onkeypress event to be cancelled from onkeydown event. }, ghostedit = window.ghostedit; // Used to capture non-repeating keyboard event (also, non-printing keys don't fire onkeypress in most browsers) _event.keydown = function (elem, e) { var keycode, ghostblock, handler, handled; ghostedit.selection.save(false); e = !(e && e.istest) && window.event ? window.event : e; keycode = e.keyCode !== null ? e.keyCode : e.charCode; _event.trigger("input:keydown", {"event": e, "keycode": keycode}); // Global shortcuts switch(keycode) { case 8: //backspace case 46: // delete key _event.cancelKeypress = false; if(ghostedit.selection.savedRange.isCollapsed() === false) { ghostedit.history.saveUndoState(); ghostedit.selection.deleteContents( (keycode === 8) ? "collapsetostart" : "collapsetoend" ); ghostedit.history.saveUndoState(); _event.cancelKeypress = true;//otherwise opera fires default backspace event onkeyPRESS (not onkeyDOWN) return ghostedit.util.cancelEvent ( e ); } break; case 83: //ctrl-s if (e.ctrlKey){ ghostedit.api.save(); return ghostedit.util.cancelEvent ( e ); } break; case 66: //ctrl-b if (e.ctrlKey) { ghostedit.plugins.textblock.format.bold (); return ghostedit.util.cancelEvent ( e ); } break; case 73: //ctrl-i if (e.ctrlKey && !e.shiftKey) { ghostedit.plugins.textblock.format.italic (); return ghostedit.util.cancelEvent ( e ); } break; case 85: //ctrl-u if (e.ctrlKey) { ghostedit.plugins.textblock.format.underline (); return ghostedit.util.cancelEvent ( e ); } break; case 90: //ctrl-z if (e.ctrlKey) { ghostedit.history.undo (); return ghostedit.util.cancelEvent ( e ); } break; case 89: //ctrl-y if (e.ctrlKey) { ghostedit.history.redo (); return ghostedit.util.cancelEvent ( e ); } break; } // If not handled by one of above, pass to plugin keydown handlers ghostblock = ghostedit.selection.getContainingGhostBlock(); while (true) { // If plugin for the GhostBlock containing the selection has an 'event.keydown' function, call it handler = ghostblock.getAttribute("data-ghostedit-handler"); if (ghostedit.plugins[handler] && ghostedit.plugins[handler].event && ghostedit.plugins[handler].event.keydown) { handled = ghostedit.plugins[handler].event.keydown(ghostblock, keycode, e); if (handled === true) break; } // If above GhostBlock doesn't handle the keypress, send event to it's parent ghostblock = ghostedit.dom.getParentGhostBlock(ghostblock); if (!ghostblock) break; } ghostedit.selection.save(); return true; }; _event.keypress = function (elem, e) { var keycode, ghostblock, handler, handled, currentDocLen, savedDocLen; ghostedit.selection.save(); currentDocLen = ghostedit.el.rootnode.innerHTML.length; savedDocLen = ghostedit.history.undoData[ghostedit.history.undoPoint] !== undefined ? ghostedit.history.undoData[ghostedit.history.undoPoint].content.string.length : 0; //if (currentDocLen - savedDocLen >= 20 || savedDocLen - currentDocLen >= 20) ghostedit.history.saveUndoState(); e = !(e && e.istest) && window.event ? window.event : e; keycode = e.keyCode !== null ? e.keyCode : e.charCode; _event.trigger("input:keydown", {"event": e, "keycode": keycode}); if (ghostedit.selection.saved.type !== "none" && !ghostedit.selection.savedRange.isCollapsed() && !e.ctrlKey) { ghostedit.selection.deleteContents("collapsetostart"); } // Global keyevents switch(keycode) { case 8: //cancel backspace event in opera if cancelKeypress = true if (_event.cancelKeypress === true) { _event.cancelKeypress = false; return ghostedit.util.cancelEvent ( e ); } break; case 13: // Enter (don't allow default action for enter to happen) ghostedit.util.cancelEvent ( e ); break; } // If not handled by one of above, pass to plugin keypress handlers ghostblock = ghostedit.selection.getContainingGhostBlock(); while (true) { // If plugin for the GhostBlock containing the selection has an 'event.keypress' function, call it handler = ghostblock.getAttribute("data-ghostedit-handler"); if (ghostedit.plugins[handler] && ghostedit.plugins[handler].event && ghostedit.plugins[handler].event.keypress) { handled = ghostedit.plugins[handler].event.keypress(ghostblock, keycode, e); if (handled === true) break; } // If above GhostBlock doesn't handle the keypress, send event to it's parent ghostblock = ghostedit.dom.getParentGhostBlock(ghostblock); if (!ghostblock) break; } ghostedit.selection.save(); return true; }; _event.addListener = function (event, callback, revokekey) { var listeners, eventtypes, isnewevent, i; if (typeof(callback) !== "function") return false; // Check if array for that event needs to be created listeners = _event.listeners; if (!listeners[event] || typeof(listeners[event]) !== "object" || !(listeners[event] instanceof Array)) { listeners[event] = []; } // Add event to list of events eventtypes = _event.eventtypes; isnewevent = true; for (i = 0; i < eventtypes.length; i++) { if (eventtypes[i] === event) { isnewevent = false; break; } } if (isnewevent) eventtypes.push(event); _event.listenerid++; listeners[event].push({"id": _event.listenerid, "callback": callback, "revokekey": revokekey}); return _event.listenerid; }; _event.removeListener = function (event, listenerid) { var listeners = _event.listeners, i, newlist = []; if(!listeners[event]) return; for (i = 0; i < listeners[event].length; i++) { if (listeners[event].id !== listenerid) { newlist.push(listeners[event][i]); } } listeners[event] = newlist; }; _event.removeAllListeners = function (revokekey) { var listeners, eventtypes, event, i, j, newlist = []; if(!revokekey) return; listeners = _event.listeners; eventtypes = _event.eventtypes; for (i = 0; i < eventtypes.length; i++) { event = eventtypes[i]; for (j = 0; j < listeners[event].length; j++) { if(!listeners[event][j].revokekey || listeners[event][j].revokekey !== revokekey) { newlist.push(listeners[event][j]); } } listeners[event] = ghostedit.util.cloneObject(newlist); newlist = []; } }; _event.trigger = function (event, params) { var listeners = _event.listeners, i; if (params === undefined) params = {}; if (!listeners[event] || typeof(listeners[event]) !== "object" || !(listeners[event] instanceof Array)) return; if (ghostedit.debug) { window.console.log(event); window.console.log(params); } for (i = 0; i < listeners[event].length; i++) { listeners[event][i].callback.call(this, params); } }; _event.sendBackwards = function (eventtype, source, params) { var target = false, tracker, result, direction; if (!params) params = {}; if (!ghostedit.dom.isGhostBlock(source)) return false; tracker = source; //tracks currently tried targets while(true) { if ((target = ghostedit.dom.getPreviousSiblingGhostBlock(tracker))) { direction = "ahead"; } else if ((target = ghostedit.dom.getParentGhostBlock(tracker))) { direction = "top"; } result = _event.send (eventtype, target, direction, params); if (!result) return false; else if (result.handled === true) return true; tracker = target; } }; _event.sendForwards = function (eventtype, source, params) { var target = false, tracker, result, direction; if (!params) params = {}; if (!ghostedit.dom.isGhostBlock(source)) return false; tracker = source; //tracks currently tried targets while(true) { if ((target = ghostedit.dom.getNextSiblingGhostBlock(tracker))) { direction = "behind"; } else if ((target = ghostedit.dom.getParentGhostBlock(tracker))) { direction = "bottom"; } result = _event.send (eventtype, target, direction, params); if (!result) return false; else if (result.handled === true) return true; tracker = target; } }; _event.send = function (eventtype, target, fromdirection, params) { var handler, handled; if (!target) return false; // = no previous/next GhostBlock handler = target.getAttribute("data-ghostedit-handler"); if (!ghostedit.plugins[handler] || !ghostedit.plugins[handler].dom || !ghostedit.plugins[handler].dom.deleteevent) { return {"handled": false}; // = no handler for this elemtype } handled = ghostedit.plugins[handler].dom.deleteevent (target, fromdirection, params); return {"handled": handled}; }; window.ghostedit.event = _event; })(window); (function(window, undefined) { var _dom = {}; _dom.getNodeOffset = function (node) { var offset, nodelist; if (!node || !node.parentNode) return; offset = 0; nodelist = node.parentNode.childNodes; while (nodelist[offset] !== node) { offset += 1; } return offset; }; _dom.extractContent = function (node) { var frag = document.createDocumentFragment(), child; while ( (child = node.firstChild) ) { frag.appendChild(child); } return frag; }; _dom.cloneContent = function (node) { var child, i, frag = document.createDocumentFragment(); for (i = 0; i < node.childNodes.length; i++) { child = node.childNodes[i]; frag.appendChild(child.cloneNode(true)); } return frag; }; _dom.parse = function (node, rules) { var parsednode = false, nodes, parsedchild, i, j, value, text, tagname, tagrules, attribute, style; if (!node || !rules || !node.nodeType) return false; rules.textnode = rules.textnode || {}; rules.tags = rules.tags || {}; // Handle textnodes if (node.nodeType === 3) { text = (rules.textnode.clean) ? node.nodeValue.replace(/[\n\r\t]/g,"") : node.nodeValue; return (text.length > 0) ? document.createTextNode(text) : false; } // Handle not-element case (textnodes already handled) if (node.nodeType !== 1) return false; // Get rules for tag, if none default to content only tagname = node.tagName.toLowerCase(); tagrules = {"contentsonly": true}; if (rules.tags[tagname]) { tagrules = rules.tags[tagname]; if (typeof tagrules.template === "string") tagrules = tagrules.template; if (typeof tagrules === "string" && rules.templates[tagrules]) tagrules = rules.templates[tagrules]; if (typeof tagrules === "string") return false; } // If "contentsonly" flag set, create document fragment, else create element of same type as node parsednode = tagrules.contentsonly ? document.createDocumentFragment() : document.createElement(node.tagName.toLowerCase()); // Unless "ignorechildren" flag set, recurse on children if (!tagrules.ignorechildren) { nodes = node.childNodes; for (i = 0; i < nodes.length; i++) { parsedchild = _dom.parse(nodes[i], rules); if (parsedchild) { parsednode.appendChild(parsedchild); } } } // Return here if contents only (no need to copy attributes if no node to copy to) if (tagrules.contentsonly) return (parsednode.childNodes.length > 0) ? parsednode : false; // If attributes specified, copy specified attributes if (tagrules.attributes) { for (i = 0; i < tagrules.attributes.length; i++) { attribute = tagrules.attributes[i]; // Handle simple (no rules) case if (typeof attribute === "string") attribute = {"name": attribute}; // Get value of attribute on source node if (typeof attribute.name !== "string") break; value = attribute.value || (attribute.name === "class") ? node.className : node.getAttribute(attribute.name); if (value === undefined) break; attribute.copy = true; // If allowedvalues are specified, check if value is correct if (attribute.allowedvalues) { attribute.copy = false; for (j = 0; j < attribute.allowedvalues.length; j++) { if (attribute.allowedvalues[i] === value){ attribute.copy = true; break; } } } // If all checks passed, set attribute on new node if (attribute.copy) { if (attribute.name === "class") { parsednode.className = value; } else { parsednode.setAttribute(attribute.name, value); } } } } // If styles specified, copy specified attributes if (tagrules.styles) { for (i = 0; i < tagrules.styles.length; i++) { style = tagrules.styles[i]; // Handle simple (no rules) case if (typeof style === "string") style = {"name": style}; // Get value of style on source node if (typeof style.name !== "string") break; if (style.name === "float") style.name = (node.style.cssFloat) ? "cssFloat" : "styleFloat"; value = style.value || node.style[style.name]; if (value === undefined) break; style.copy = true; // If allowedvalues are specified, check if value is correct if (style.allowedvalues) { style.copy = false; for (j = 0; j < style.allowedvalues.length; j++) { if (style.allowedvalues[j] === value) { style.copy = true; break; } } } // If all checks passed, set style on new node if (style.copy) parsednode.style[style.name] = value; } } return parsednode; }; _dom./*compareNodes = function (node1, node2) { var node; // If node1 is a documentFragment, wrap in an element if (n1.nodeType === 11) { node = document.createElement("div"); node.appendChild(nodeOrFrag); node1 = node; } // If node2 is a documentFragment, wrap in an element if (n2.nodeType === 11) { node = document.createElement("div"); node.appendChild(nodeOrFrag); node2 = node; } function getNextNode (nodelist, current) { } nodes1 = node1.getElementsByTagName(*); },*/ isGhostBlock = function (node) { if (!node || !node.nodeType || node.nodeType !== 1) return false; var ghosttype = node.getAttribute("data-ghostedit-elemtype"); return (ghosttype !== undefined && ghosttype !== false && ghosttype !== null) ? true : false; }; _dom.isChildGhostBlock = function (elem, parent) { var i; if (!elem || !parent || !parent.childNodes) return false; if (elem.nodeType !== 1) return false; if (elem.getAttribute("data-ghostedit-elemtype") === undefined) return false; if (elem.getAttribute("data-ghostedit-elemtype") === false) return false; if (elem.getAttribute("data-ghostedit-elemtype") === null) return false; var childblocks = parent.childNodes; for(i = 0; i < childblocks.length; i += 1) { if (elem === childblocks[i]) { return true; } } return false; }; _dom.isGhostToplevel = function (node) { return (node && node.getAttribute("data-ghostedit-isrootnode") === true) ? true : false; }; _dom.getParentGhostBlock = function (node) { if (!node) return false; do { node = node.parentNode; if (node === null) return false; } while (!_dom.isGhostBlock(node)); return node; }; _dom.getFirstChildGhostBlock = function (node) { var children, i; if (!node || !node.childNodes) return false; // Otherwise, recurse forwards through DOM until first GhostBlock is found. children = node.childNodes; for (i = 0; i < children.length; i += 1) { if (_dom.isGhostBlock(children[i])) { return children[i]; } } return false; }; _dom.getLastChildGhostBlock = function (node) { var children, i; if (!node || !node.childNodes) return false; // Otherwise, recurse backwards through DOM until previous GhostBlock is found. children = node.childNodes; for (i = children.length -1; i >= 0; i -= 1) { if (_dom.isGhostBlock(children[i])) { return children[i]; } } return false; }; _dom.getPreviousSiblingGhostBlock = function (node) { var parent, offset, siblings; if (!node || !node.parentNode) return false; // Otherwise, recurse backwards through DOM until previous GhostBlock is found. parent = node.parentNode; offset = _dom.getNodeOffset (node) - 1; siblings = parent.childNodes; do { if (_dom.isGhostBlock(siblings[offset]) === true) { return siblings[offset]; } offset -= 1; } while (offset >= 0); return false; }; _dom.getNextSiblingGhostBlock = function (node) { var parent, offset, siblings; if (!node || !node.parentNode) return false; // Otherwise, recurse forwards through DOM until next GhostBlock is found. parent = node.parentNode; offset = _dom.getNodeOffset (node) + 1; siblings = parent.childNodes; do { if (_dom.isGhostBlock(siblings[offset]) === true) { return siblings[offset]; } offset += 1; } while (offset < siblings.length); return false; }; _dom.getParentElement = function (node) { if (node.nodeType !== 1) { while (node.nodeType !== 1) { node = node.parentNode; if (node === null) return null; } } return node; }; _dom.isDescendant = function (parent, child) { var node = child.parentNode; while (node !== null) { if (node === parent) { return true; } node = node.parentNode; } return false; }; _dom.getFirstChildElement = function (node) { var children, i; if (!node || !node.childNodes) return false; // Otherwise, recurse forwards through DOM until next element is found. children = node.childNodes; for (i = 0; i < children.length; i += 1) { if (children[i].nodeType === 1) { return children[i]; } } return false; }; _dom.getCertainParent = function (condition, elem) { var args = [].slice.call(arguments); args.shift(); if (!condition.apply(this, args)) { while (!condition.apply(this, args)) { elem = elem.parentNode; args[0] = elem; if (elem === null) return false; } } return elem; }; window.ghostedit.dom = _dom; })(window); (function(window, undefined) { var _selection = { savedRange: null, nodepath: [], saved: {type: "none", data: null}, archived: {type: "none", data: null} }, ghostedit = window.ghostedit, lasso = window.lasso; _selection.save = function (updateui) { var sel; if (updateui !== false) updateui = true; sel = lasso().setToSelection(); if (!_selection.isInEditdiv(sel.getStartNode())) { _selection.saved.type = "none"; return false; } else { //Save current selection to range _selection.saved.type = "textblock"; _selection.saved.data = sel;//.bookmarkify(ghostedit.el.rootnode); // Save to legacy variable _selection.savedRange = _selection.saved.data; ghostedit.event.trigger("selection:change"); _selection.updatePathInfo(); if (updateui) ghostedit.event.trigger("ui:update"); return true; } }; _selection.set = function (type, data, updateui) { if (updateui !== false) updateui = true; if (typeof type !== "string") return; // Update selection variables _selection.saved.type = type; _selection.saved.data = data; // Save to legacy variable _selection.savedRange = _selection.saved.data; // Update path information _selection.updatePathInfo(); // Send events ghostedit.event.trigger("selection:change"); if (updateui) ghostedit.event.trigger("ui:update"); return true; }; _selection.restore = function (type, data, mustbevalid) { if (!type || typeof type !== "string") type = _selection.saved.type; if (!data) data = _selection.saved.data; // if type is none, but cant be, get archived selection if (type === "none" && mustbevalid) { type = _selection.archived.type; data = _selection.archived.data; } // If type is none, clear selection if (type === "none") { _selection.clear(); return true; } // Else, call restore function from appropriate plugin if (ghostedit.plugins[type] && ghostedit.plugins[type].selection.restore) { if (ghostedit.plugins[type].selection.restore(data)) { return true; } else { _selection.clear(); return false; } } }; _selection.restoreValid = function (type, data) { return _selection.restore(type, data, true); }; _selection.deleteContents = function (collapse) { if (collapse !== "collapsetostart" && collapse !== "collapsetoend") collapse = false; var handler, handled, ghostblock; ghostblock = _selection.getContainingGhostBlock(); while (true) { handler = ghostblock.getAttribute("data-ghostedit-handler"); handled = ghostedit.plugins[handler].selection.deleteContents(ghostblock, collapse); if (handled === true) break; ghostblock = ghostedit.dom.getParentGhostBlock(ghostblock); if (!ghostblock) break; } switch (collapse) { case "collapsetostart": lasso().setToSelection().collapseToStart().select(); break; case "collapsetoend": lasso().setToSelection().collapseToEnd().select(); break; } _selection.save(); }; _selection.isSameAs = function (sel) { if (!sel || !sel.type) return false; if (sel.type !== _selection.saved.type) return false; if (sel.type === "none") return true; // Else, call compare function from appropriate plugin if (ghostedit.plugins[sel.type] && ghostedit.plugins[sel.type].selection.compare) { return ghostedit.plugins[sel.type].selection.compare (sel.data, _selection.saved.data); } return false; }; _selection.clear = function () { lasso().clearSelection(); _selection.saved = {"type": "none", "data": null}; }; _selection.isInEditdiv = function (elem) { if (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { while (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { if (elem === null) return false; elem = elem.parentNode; if (elem === null) return false; } } return true; }; _selection.updatePathInfo = function (elem) { if (!elem) elem = _selection.saved.data; if (!elem.nodeType) elem = elem.getParentNode(); // If nodepath is same as before, don't bother calculating it again // below code DOES NOT equal above statement. (dom node can have moved) //if (elem === _selection.nodepath[0]) return true; _selection.nodepath = []; if (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { while (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-isrootnode") !== "true") { if (elem === null) return null; if (elem.nodeType === 1) _selection.nodepath.push(elem); elem = elem.parentNode; if (elem === null) return false; } } // Make sure rootnode is also included in path if (elem && elem.getAttribute("data-ghostedit-isrootnode") === "true") { _selection.nodepath.push(elem); } }; _selection.getContainingGhostBlock = function () { var node = _selection.saved.data; if (!node.nodeType) node = node.getParentNode(); if (!node) return false; while (!ghostedit.dom.isGhostBlock(node)) { node = node.parentNode; if (node === null) return false; } return node; }; window.ghostedit.selection = _selection; })(window); (function(window, undefined) { var _inout = {}, ghostedit = window.ghostedit; _inout.init = function () { // Set initial variables _inout.reset(); // Add listener to check whether the selection has changed since the last undo save ghostedit.event.addListener("selection:change", function () { ghostedit.history.selectionchanged = true; }); // Export undo and redo function to the api ghostedit.api.importHTML = function (source) { return _inout.importHTML(source); }; ghostedit.api.exportHTML = function () { return _inout.exportHTML(); }; }; _inout.reset = function () { _inout.importhandlers = []; }; _inout.importHTML = function (sourcenode) { var /*tagname, handler, result*/ rootnode; if (!sourcenode || sourcenode.childNodes.length < 1) return false; /*var tagname = sourcenode.tagName.toLowerCase(); if (handler = _inout.importhandlers[tagname]) { result = ghostedit.plugins[handler].inout.importHTML(insertedelem, elem) if (result) insertedelem = result; }*/ // Call container import, and set resulting domnode's contenteditable to true rootnode = ghostedit.plugins.container.inout.importHTML(sourcenode); rootnode.className = "ghostedit_rootnode"; rootnode.setAttribute("data-ghostedit-isrootnode", "true"); rootnode.contentEditable = 'true'; // Trigger 'import:after' event ghostedit.event.trigger("import:after", {"rootnode": rootnode}); // Return rootnode container return rootnode; }; _inout.exportHTML = function () { var finalexport, editwrap = ghostedit.el.rootnode; ghostedit.event.trigger("export:before"); //Preparation - contenteditable = false editwrap.contentEditable = false; finalexport = ghostedit.plugins.container.inout.exportHTML(editwrap, false); //Tidy up - contenteditable = true editwrap.contentEditable = true; ghostedit.event.trigger("export:after"); return finalexport; //{snippet: snippet, full: finalCode}; }; _inout.openPreview = function () { window.open(ghostedit.options.previewurl); }; _inout.registerimporthandler = function (importhandler/*, tagnames of elements that can be handled*/) { var i, args, tag; if (typeof importhandler !== "function") return false; if (arguments.length < 2) return false; args = Array.prototype.slice.call(arguments); args.shift(); // Loop through arguments for (i = 0; i < args.length; i++) { tag = args[i]; _inout.importhandlers[tag] = importhandler; } }; window.ghostedit.inout = _inout; })(window); (function(window, undefined) { var _history = {}, ghostedit = window.ghostedit; _history.init = function () { // Set initial variables _history.reset(); // Add listener to check whether the selection has changed since the last undo save ghostedit.event.addListener("selection:change", function () { _history.selectionchanged = true; }); // Export undo and redo function to the api ghostedit.api.undo = function () { return _history.undo(); }; ghostedit.api.redo = function () { return _history.redo(); }; }; _history.reset = function () { _history.undoData = [];//new Array(_history.undolevels); /*_history.undolevels = 4000,*/ _history.undoPoint = 0; _history.selectionchanged = true; }; _history.saveUndoState = function (force) { var undoPoint, undoData, contentchanged, selectionchanged, currentstate, undostate, editwrap = ghostedit.el.rootnode; if (force !== true) force = false; ghostedit.event.trigger("history:save:before"); // Localise undo variables undoPoint = _history.undoPoint; undoData = _history.undoData; // Get latest undopoint into a variable undostate = undoData[undoPoint]; if (!undostate) force = true; // Start capturing current editor state currentstate = { id: "", selection: { "type": ghostedit.selection.saved.type, //"data": ghostedit.selection.saved.type === "textblock" ? ghostedit.selection.saved.data.clone() : ghostedit.selection.saved.data "data": ghostedit.selection.saved.data }, content: { "string": editwrap.innerHTML } }; // Calcuate whether the selection or content have changed if (!force) { contentchanged = (undostate.content.string !== currentstate.content.string) ? true : false; selectionchanged = !(ghostedit.selection.isSameAs(undostate.selection)); } if (force || selectionchanged || contentchanged) { // Clone editor content as documentFragment currentstate.content.dom = ghostedit.dom.extractContent(editwrap.cloneNode(true)); if (force || contentchanged) { // Remove existing redo data if (undoPoint > 0) _history.undoData.splice(0, undoPoint); // Save new data and set undoPoint to point at it _history.undoData.unshift(currentstate); _history.undoPoint = 0; } else { _history.undoData[undoPoint] = currentstate; } } ghostedit.event.trigger("history:save:after"); }; _history.restoreUndoPoint = function (undopoint) { var undoData = _history.undoData, undostate = undoData[undopoint]; if (!undostate || undostate.content.string.length < 1) return false; ghostedit.event.trigger("history:restore:before"); ghostedit.el.rootnode.innerHTML = ""; ghostedit.el.rootnode.appendChild(ghostedit.dom.cloneContent(undostate.content.dom)); ghostedit.selection.restore (undostate.selection.type, undostate.selection.data); //ghostedit.selection.save(); ghostedit.event.trigger("history:restore:after"); }; _history.undo = function () { var undoPoint = _history.undoPoint, undoData = _history.undoData, editwrap = ghostedit.el.rootnode; if (undoData[undoPoint+1] === undefined || undoData[undoPoint+1].content.string.length <= 0) return; // if (undoPoint < _history.undolevels - 1) return; //unlimited undo levels ghostedit.event.trigger("history:undo:before"); // If there are unsaved changes, save current content and revert to last saved undopoint (was 0, but now 1 because current state saved in 0) if (undoData[undoPoint].content.string !== editwrap.innerHTML) { _history.saveUndoState(); undoPoint = 1; } // Else, current state already saved, revert to previous saved one (undoPoint + 1) else { if (undoPoint === 0) { _history.saveUndoState(); } undoPoint = _history.undoPoint; undoPoint += 1; } _history.restoreUndoPoint(undoPoint); _history.undoPoint = undoPoint; _history.undoData = undoData; ghostedit.event.trigger("history:undo:after"); }; _history.redo = function () { var undoPoint = _history.undoPoint, undoData = _history.undoData, editwrap = ghostedit.el.rootnode; if (undoPoint > 0 && undoData[undoPoint-1] !== undefined && undoData[undoPoint-1].content.string.length > 0) { ghostedit.event.trigger("history:redo:before"); // The user has made changes since the last undo/redo, throw away redo data and save undo state if (undoData[undoPoint].content.string !== editwrap.innerHTML) { _history.saveUndoState(true); } // Last action was an undo/redo, move one point forwards if possible else { undoPoint-=1; _history.restoreUndoPoint(undoPoint); _history.undoPoint = undoPoint; _history.undoData = undoData; } ghostedit.event.trigger("history:redo:after"); } }; window.ghostedit.history = _history; })(window); (function (window, undefined) { var _clipboard = {}, _paste, _cut, lasso = window.lasso, ghostedit = window.ghostedit, console = window.console || {}; console.log = console.log || function () {}; _clipboard.init = function () { _clipboard.paste.init(); _clipboard.cut.init(); }; _paste = { savedcontent: null, savedundodata: null, savedundopoint: null, beforerangedata: "", afterrangedata: "", waitlength: 0, postpastetidylist: [] }; _paste.init = function () { ghostedit.event.addListener("init:after", function () { ghostedit.util.addEvent(ghostedit.el.rootnode, "paste", function(event) { _paste.handle(event); }); }, "clipboard"); }; _paste.handle = function (e) {//elem no longer used? // Save editor state, and save undo data in case paste functions mess up undo stack ghostedit.history.saveUndoState(); _paste.savedundodata = ghostedit.history.undoData; _paste.savedundopoint = ghostedit.history.undoPoint; _paste.triedpasteimage = false; // If webkit - get data from clipboard, put into rootnode, cleanup, then cancel event if (e.clipboardData && e.clipboardData.getData) { if (/image/.test(e.clipboardData.types)) { _paste.triedpasteimage = true; } if (/text\/html/.test(e.clipboardData.types)) { ghostedit.el.rootnode.innerHTML = e.clipboardData.getData('text/html'); } else if (/text\/plain/.test(e.clipboardData.types) || ghostedit.browserEngine.opera) { ghostedit.el.rootnode.innerHTML = e.clipboardData.getData('text/plain').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); } else { ghostedit.el.rootnode.innerHTML = ""; } _paste.waitfordata(); return ghostedit.util.cancelEvent(e); } //Else - empty rootnode and allow browser to paste content into it, then cleanup else { ghostedit.el.rootnode.innerHTML = ""; _paste.waitfordata(); return true; } }; _paste.waitfordata = function () { var elem = ghostedit.el.rootnode; if (elem.childNodes && elem.childNodes.length > 0) { _paste.process(); } else { setTimeout(_paste.waitfordata, 20); } }; _paste.process = function () { var pastenode, collapsed, hasmerged, handler, target, result, source, position; // Extract pasted content into a new element pastenode = document.createElement("div"); pastenode = ghostedit.plugins.container.inout.importHTML(ghostedit.el.rootnode); console.log ("processed content"); console.log (pastenode.cloneNode(true)); // Restore undo data, and restore editor content ghostedit.history.undoData = _paste.savedundodata; ghostedit.history.undoPoint = _paste.savedundopoint; ghostedit.history.restoreUndoPoint(ghostedit.history.undoPoint); ghostedit.selection.save(); // Delete selection contents if selection is non-collapsed ghostedit.selection.deleteContents(); ghostedit.selection.save(); // If no content was pasted, return source = ghostedit.dom.getFirstChildGhostBlock(pastenode); if (!source) return; // Save selection to DOM if(ghostedit.selection.saved.data.isCollapsed()){ ghostedit.selection.saved.data.saveToDOM("ghostedit_paste_start"); } else { ghostedit.selection.saved.data.clone().collapseToStart().saveToDOM("ghostedit_paste_start"); ghostedit.selection.saved.data.clone().collapseToEnd().saveToDOM("ghostedit_paste_end"); } // Call handler on first pasted node target = function () { return ghostedit.selection.saved.data.getStartNode(); }; position = {"isfirst": true, "islast": (ghostedit.dom.getLastChildGhostBlock(pastenode) === source) ? true : false}; target = _paste.callHandler (target, source, position); /*ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } ghostedit.selection.saved.data.select().inspect(); return;/* */ // Call handler on last pasted node source = ghostedit.dom.getLastChildGhostBlock(pastenode); if (source) { target = function () { return ghostedit.selection.saved.data.getEndNode(); }; position = {"isfirst": false, "islast": true}; _paste.callHandler (target, source, position); } /*ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } ghostedit.selection.saved.data.select().inspect(); return;/* */ // Loop through and call handler on remaining nodes target = function () { return ghostedit.selection.saved.data.getParentNode(); }; position = {"isfirst": false, "islast": false}; while ((source = ghostedit.dom.getFirstChildGhostBlock(pastenode))) { _paste.callHandler (target, source, position); } // Restore the selection (collapsed to the end) ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", true).select(); if (ghostedit.selection.saved.data.isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_end", true).select(); } ghostedit.selection.save(); // Save undo state ghostedit.history.undoData = _paste.savedundodata; ghostedit.history.undoPoint = _paste.savedundopoint; ghostedit.history.saveUndoState(); if (_paste.triedpasteimage) { ghostedit.event.trigger("ui:message", {message: "You cannot paste images into the editor, please use the add image button instead", time: 2, color: "warn"}); } ghostedit.event.trigger("clipboard:paste:after"); }; _paste.callHandler = function (targetF, source, position) { var target, handler, result; // Restore the selection from DOM markers ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } // Get the target target = targetF(); if (!ghostedit.dom.isGhostBlock(target)) target = ghostedit.dom.getParentGhostBlock(target); // Recursively call handler of target and it's parents while (true) { if (!target) break; // Get handler plugin for specified target handler = target.getAttribute("data-ghostedit-handler"); if (!ghostedit.plugins[handler] || !ghostedit.plugins[handler].paste) break; console.log("Call handler: (" + (position.isfirst?"first":position.islast?"last":"normal") + ")" + handler); console.log(target.cloneNode(true)); console.log(source.cloneNode(true)); // Call handler function for target result = ghostedit.plugins[handler].paste.handle (target, source, position); console.log("result: " + result); // If handler function returns true, then source is handled: remove it and return false to indicate not to continue if (result) { source.parentNode.removeChild(source); break; } // Else, restore the selection from DOM markers ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } // Get the the parent GhostBlock as the next target to try target = ghostedit.dom.getParentGhostBlock(target); } }; _cut = { savedcontent: null, savedundodata: null, savedundopoint: null }; _cut.init = function () { ghostedit.event.addListener("init:after", function () { ghostedit.util.addEvent(ghostedit.el.rootnode, "cut", function(event) { _cut.handle(event); }); }, "clipboard"); }; _cut.handle = function () { // Save editor state, and save undo data in case paste functions mess up undo stack ghostedit.history.saveUndoState(); _cut.savedundodata = ghostedit.history.undoData; _cut.savedundopoint = ghostedit.history.undoPoint; //Else - empty rootnode and allow browser to paste content into it, then cleanup setTimeout(_cut.cleanup, 20); return true; }; _cut.cleanup = function () { // Restore undo data, and restore editor content ghostedit.history.undoData = _cut.savedundodata; ghostedit.history.undoPoint = _cut.savedundopoint; ghostedit.history.restoreUndoPoint(ghostedit.history.undoPoint); ghostedit.selection.save(); // Delete selection contents if selection is non-collapsed ghostedit.selection.deleteContents(); ghostedit.selection.save(); ghostedit.history.saveUndoState(); }; _clipboard.paste = _paste; _clipboard.cut = _cut; window.ghostedit.clipboard = _clipboard; })(window); (function (window, undefined) { var _textblock = {}, lasso = window.lasso, ghostedit = window.ghostedit, console = window.console || {}; console.log = console.log || function () {}; _textblock.enable = function () { _textblock.format.init(); ghostedit.inout.registerimporthandler (_textblock.inout.importHTML, "p", "h1", "h2", "h3", "h4", "h5", "h6"); ghostedit.inout.registerimporthandler (_textblock.inout.importHTML, "#textnode", "b", "strong", "i", "em", "u", "strike", "span"); // Bookmarkify (serialize) the selection, and save the bookmark to the lasso object ghostedit.event.addListener("history:save:after", function () { if (ghostedit.selection.saved.type === "textblock") { ghostedit.selection.saved.data.bookmarkify(ghostedit.el.rootnode); } }); // Clone range object after undo save to avoid accidentally modifying the saved range objects ghostedit.event.addListener("history:save:after", function () { if (ghostedit.selection.saved.type === "textblock") { ghostedit.selection.saved.data = ghostedit.selection.saved.data.clone(); } }); ghostedit.api.insert = ghostedit.api.insert || {}; ghostedit.api.insert.character = function (character) { return _textblock.insert.character(character); }; ghostedit.api.insert.br = function () {return _textblock.insert.br; }; return true; }; _textblock.event = { keydown: function (target, keycode, event) { switch (keycode) { case 8: // backspace return _textblock.event.backspace(target, event); case 46: //delete return _textblock.event.deletekey (target, event); } }, keypress: function (target, keycode, event) { // Enter key if (keycode === 13) return _textblock.event.enterkey (target, event); }, backspace: function (block, e) { if (_textblock.selection.isAtStartOfTextBlock() !== true) { //Caret not at start of textblock: return true to indicate handled return true; } else { //var block = ghostedit.selection.getContainingGhostBlock(); var params = { "merge": { "contenttype": "inlinehtml", "sourcecontent": block.innerHTML, callback: ghostedit.util.preparefunction(function (node) { var parent = node.parentNode; var handler = parent.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].dom.removechild(parent, node);}, false, block) } }; ghostedit.event.sendBackwards("delete", block, params ); ghostedit.event.cancelKeypress = true; ghostedit.util.cancelEvent ( e ); return true; } }, deletekey: function (block, e) { //var block = ghostedit.selection.getContainingGhostBlock(); if (_textblock.selection.isAtEndOfTextBlock() !== true) { //Caret not at end of textblock: return true to indicate handled return true; } else { ghostedit.event.sendForwards("delete", block); //_textblock.remove(_textblock.selection.getStartTextBlockNode()); ghostedit.event.cancelKeypress = true; ghostedit.util.cancelEvent ( e ); return true; } }, enterkey: function (elem, e) { ghostedit.history.saveUndoState(); if (e.shiftKey) { _textblock.insert.br(); _textblock.mozBrs.tidy (elem); } else { _textblock.split(elem); } ghostedit.history.saveUndoState(); ghostedit.util.cancelEvent ( e ); return true; } }; _textblock.dom = { deleteevent: function (target, sourcedirection, params){ var parent, handler, block; switch (sourcedirection) { case "ahead": ghostedit.history.saveUndoState(); if (!_textblock.isEmpty(target)) { target.innerHTML += "<span id='ghostedit_selection_marker'>&#x200b;</span>"; if (params.merge && params.merge.sourcecontent && (params.merge.contenttype === "inlinehtml" || params.merge.contenttype === "text")) { target.innerHTML += params.merge.sourcecontent; } _textblock.mozBrs.tidy(target); params.merge.callback(); //params.sourceblock.parentNode.removeChild(params.sourceblock); lasso().selectNode("ghostedit_selection_marker").select();//.deleteContents(); document.getElementById("ghostedit_selection_marker").parentNode.removeChild(document.getElementById("ghostedit_selection_marker")); ghostedit.selection.save(); } else { parent = ghostedit.dom.getParentGhostBlock(target); handler = parent.getAttribute("data-ghostedit-handler"); //alert(target.id); ghostedit.plugins[handler].dom.removechild(parent, target); } ghostedit.history.saveUndoState(); return true; case "behind": block = ghostedit.selection.getContainingGhostBlock(); params = { "merge": { "contenttype": "inlinehtml", "sourcecontent": target.innerHTML, "callback": ghostedit.util.preparefunction(function (node) { var parent = node.parentNode, handler = parent.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].dom.removechild(parent, node); }, false, target) } }; ghostedit.event.sendBackwards("delete", target, params); //---------------------------------- //_textblock.remove(_textblock.selection.getStartTextBlockNode()); //ghostedit.event.cancelKeypress = true; //return ghostedit.util.cancelEvent ( e ); return true; } } }; _textblock.selection = { compare: function (r1, r2) { if (!r1 || !r1.isEqualTo) return false; return r1.isEqualTo(r2); }, restore: function (savedrange) { if (!savedrange || !savedrange.unbookmarkify) return false; savedrange.unbookmarkify(ghostedit.el.rootnode); savedrange.select(); return true; }, deleteContents: function (textblockelem) { var startofblock, endofblock, selrange; // Temporary selection range to avoid changing actual saved range selrange = ghostedit.selection.savedRange.clone(); // Ranges representing the start and end of the block startofblock = lasso().setCaretToStart(textblockelem); endofblock = lasso().setCaretToEnd(textblockelem); // If selrange starts before block, move start of selrange to start of block if (selrange.compareEndPoints("StartToStart", startofblock) === -1) { selrange.setStartToRangeStart(startofblock); } // If selrange end after block, move end of selrange to end of block if (selrange.compareEndPoints("EndToEnd", endofblock) === 1) { //alert(textblockelem.id); selrange.setEndToRangeEnd(endofblock); } selrange.deleteContents(); return true; }, getTextBlockNode: function (elem) { if (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-elemtype") !== "textblock") { while (elem.nodeType !== 1 || elem.getAttribute("data-ghostedit-elemtype") !== "textblock") { elem = elem.parentNode; if (elem === null) return false; } } return elem; }, getStartTextBlockNode: function () { return _textblock.selection.getTextBlockNode( ghostedit.selection.savedRange.getStartNode() ); }, getEndTextBlockNode: function () { return _textblock.selection.getTextBlockNode( ghostedit.selection.savedRange.getEndNode() ); }, //Assumes selection saved manually isAtStartOfTextBlock: function (point) { var caretIsAtStart = false, range, selrange, i, isequal, firstnode, textblocknode, wholenode, tempnode, useselection; // Check if 'point' parameter was passed and is a lasso object, otherwise get selection useselection = false; if (!point || !point.isLassoObject) { if (ghostedit.selection.saved.type !== "textblock") return false; point = ghostedit.selection.saved.data; useselection = true; } if(document.createRange) { range = point; if(range.isCollapsed() && range.getNative().startOffset === 0) { caretIsAtStart = true; tempnode = ghostedit.selection.savedRange.getStartNode(); } if (!tempnode) return caretIsAtStart; // If tempnode not right at start while (tempnode.nodeType !== 1 || tempnode.getAttribute("data-ghostedit-elemtype") !== "textblock") { if (tempnode !== tempnode.parentNode.childNodes[0]) { isequal = false; if((tempnode.parentNode.childNodes[0].nodeType === 3 && tempnode.parentNode.childNodes[0].length === 0) || (tempnode.parentNode.childNodes[0].nodeType === 1 && tempnode.parentNode.childNodes[0].className === "moz_dirty")) { //Deals with empty text nodes at start of textblock elem for(i = 1; i < tempnode.parentNode.childNodes.length; i += 1) { firstnode = tempnode.parentNode.childNodes[0]; if (tempnode === tempnode.parentNode.childNodes[i]) { isequal = true; break; } else if(!(firstnode.nodeType === 3 && firstnode.length === 0) && !(firstnode.nodeType === 1 && firstnode.className === "moz_dirty")) { break; } } } if(isequal !== true) { caretIsAtStart = false; break; } } tempnode = tempnode.parentNode; } } else if (document.selection) { // Bookmarkify range, so DOM modification doesn't break it selrange = point.clone().bookmarkify(); textblocknode = _textblock.selection.getStartTextBlockNode(); // Get range representing the whole TextBlock contents wholenode = lasso().selectNodeContents( textblocknode ); // Unbookmarkify the range, so it can be used in comparisons again selrange.unbookmarkify(); // Compare html of wholenode with html of node starting from selected point, if eqaul then selection is at the start of the textblock if (wholenode.getHTML() === wholenode.setStartToRangeStart(selrange).getHTML()) { caretIsAtStart = true; } if (useselection) { ghostedit.selection.savedRange = selrange.select(); } } return caretIsAtStart; }, //Assumes selection saved manually isAtEndOfTextBlock: function () { var caretIsAtEnd = false, selrange, range, rangefrag, elemfrag, textblocknode, endpoint; if (!ghostedit.selection.savedRange.isCollapsed()) return false; textblocknode = _textblock.selection.getEndTextBlockNode(); if(document.createRange) { rangefrag = document.createElement("div"); rangefrag.appendChild( ghostedit.selection.savedRange.getNative().cloneContents() ); range = ghostedit.selection.savedRange.getNative(); range.setEnd(textblocknode, textblocknode.childNodes.length); elemfrag = document.createElement("div"); rangefrag.appendChild( range.cloneContents() ); _textblock.mozBrs.clear(rangefrag); _textblock.mozBrs.clear(elemfrag); if(rangefrag.innerHTML === elemfrag.innerHTML) { caretIsAtEnd = true; } } else if (document.selection) { // Bookmarkify range, so DOM modification doesn't break it selrange = ghostedit.selection.savedRange.clone().bookmarkify(); // Get range representing the end of the TextBlock textblocknode.innerHTML += "<span id=\"range_marker\">&#x200b;</span>"; endpoint = lasso().selectNode('range_marker');//.deleteContents(); document.getElementById('range_marker').parentNode.removeChild(document.getElementById('range_marker')); // Unbookmarkify the range, so it can be used in comparisons again selrange.unbookmarkify(); // Compare endpoint to selected point, if equal then selection is at the end of the textblock if (selrange.compareEndPoints("EndToEnd", endpoint) === 0) { caretIsAtEnd = true; } ghostedit.selection.savedRange = selrange.select(); } return caretIsAtEnd; }, extendtoword: function (range, onlyfrommiddle) { var wordstart, wordend; range = range.clone().getNative(); if (document.createRange) { wordstart = _textblock.selection.findwordstart (range.startContainer, range.startOffset); wordend = _textblock.selection.findwordend (range.endContainer, range.endOffset); //If only one end has moved (or neither), then it's not from the middle if (onlyfrommiddle) { if (range.startContainer === wordstart.node && range.startOffset === wordstart.offset) return lasso().setFromNative(range); if (range.endContainer === wordend.node && range.endOffset === wordend.offset) return lasso().setFromNative(range); } range.setStart(wordstart.node, wordstart.offset); range.setEnd(wordend.node, wordend.offset); } else { range.expand("word"); if (range.htmlText.split().reverse()[0] === " ") { range.moveEnd("character", -1); } } return lasso().setFromNative(range); }, findwordstart: function (node, offset) { var leftnodecontent, stroffset, totalstroffset, prevnode, wordendregex = /\s|[\!\?\.\,\:\;\"]/; if (!node || !node.nodeType) return false; // Handle text node if (node.nodeType === 3) { leftnodecontent = node.nodeValue.substring(0, offset); stroffset = leftnodecontent.search(wordendregex); //If there is a space or punctuation mark left of position in current textNode if(stroffset !== -1) { totalstroffset = stroffset + 1; while ((stroffset = leftnodecontent.substring(totalstroffset).search(wordendregex)) !== -1) { totalstroffset += stroffset + 1; } return { node: node, offset: totalstroffset }; } } // Handle Element else if (node.nodeType === 1) { if (offset > 0) { return _textblock.selection.findwordstart(node.childNodes[offset - 1], node.childNodes[offset - 1].length); } } // If no wordend match found in current node and node is a ghostedit_textblock: return current position if (_textblock.isTextBlock(node)){ return {"node": node, "offset": offset}; } // If node is a NOT ghostedit_textblock: check previous node prevnode = node.previousSibling; if (prevnode) { if (prevnode.nodeType === 3) { return _textblock.selection.findwordstart(prevnode, prevnode.nodeValue.length); } else if (prevnode.nodeType === 1) { return _textblock.selection.findwordstart(prevnode, prevnode.childNodes.length); } } // If node is a NOT ghostedit_textblock and no previousSibling: move up tree else { return _textblock.selection.findwordstart(node.parentNode, ghostedit.dom.getNodeOffset(node)); } }, findwordend: function (node, offset) { var rightnodecontent, stroffset, totalstroffset, nextnode, wordendregex = /\s|[\!\?\.\,\:\;\"]/; if (!node || !node.nodeType) return false; // Handle text node if (node.nodeType === 3) { rightnodecontent = node.nodeValue.substring(offset); stroffset = rightnodecontent.search(wordendregex); //If there is a space or punctuation mark left of position in current textNode if (stroffset !== -1) { totalstroffset = offset + stroffset; return { node: node, offset: totalstroffset }; } } // Handle Element else if (node.nodeType === 1) { if (offset < node.childNodes.length) { return _textblock.selection.findwordend(node.childNodes[offset], 0); } } // If no wordend match found in current node and node is a ghostedit_textblock: return current position if (_textblock.isTextBlock(node)){ return {"node": node, "offset": offset}; } // If node is a NOT ghostedit_textblock: check next node nextnode = node.nextSibling; if (nextnode) { return _textblock.selection.findwordend(nextnode, 0); } // If node is a NOT ghostedit_textblock and no nextSibling: move up tree else { return _textblock.selection.findwordend(node.parentNode, ghostedit.dom.getNodeOffset(node) + 1); } } }; _textblock.inout = { handledtags: { "h1": "block", "h2": "block", "h3": "block", "h4": "block", "h5": "block", "h6": "block", "p": "block", "b": "child", "i": "child", "u": "child", "strong": "child", "em": "child", "strike": "child", "br": "child", "a": "contents", "span": "contents" }, parserules: { "textnode": { "clean": true }, "tags": { "h1": "textblock", "h2": "textblock", "h3": "textblock", "h4": "textblock", "h5": "textblock", "h6": "textblock", "p": "textblock", "b": {}, "i": {}, "u": {}, "strong": {}, "em": {}, "strike": {}, "br": { "attributes": [ {"name": "class", "allowedvalues": [ "moz_dirty" ]} ] } }, "templates": { "textblock": { "attributes": [ "class" ], "styles": [ {"name": "textAlign", "allowedvalues": ["left", "right", "center", "justified"] }, {"name": "clear", "allowedvalues": ["left", "right"] } ] } } }, importHTML: function (source) { var newTextBlock, tagname, node, childcount, prevnode, nodetype, parsednode; nodetype = _textblock.inout.isHandleableNode(source); switch (nodetype) { case "block": // Create TextBlock tagname = source.tagName.toLowerCase(); newTextBlock = ghostedit.dom.parse(source, _textblock.inout.parserules); ghostedit.blockElemId += 1; newTextBlock.id = 'ghostedit_textblock_' + ghostedit.blockElemId; // Set GhostEdit handler attributes newTextBlock.setAttribute("data-ghostedit-iselem", "true"); newTextBlock.setAttribute("data-ghostedit-elemtype", "textblock"); newTextBlock.setAttribute("data-ghostedit-handler", "textblock"); // Add event handlers newTextBlock.ondragenter = function(){return false;}; newTextBlock.ondragleave = function(){return false;}; newTextBlock.ondragover = function(){return false;}; newTextBlock.ondrop = function(e){ var elem, elemid; // This function does basic image paragraph changing dnd elemid = e.dataTransfer.getData("Text") || e.srcElement.id; //alert(elemid); TODO drag drop elem = document.getElementById(elemid); elem.parentNode.insertBefore(elem,this); ghostedit.image.focus(elem); }; newTextBlock.onresizestart = function(e) {return ghostedit.util.cancelEvent(e);}; _textblock.mozBrs.tidy (newTextBlock); return newTextBlock; case "child": case "contents": case "text": newTextBlock = _textblock.create("p"); newTextBlock.setAttribute("data-ghostedit-importinfo", "wasinline"); childcount = 0; node = source; do { parsednode = ghostedit.dom.parse(node, _textblock.inout.parserules); if (parsednode) { childcount += 1; newTextBlock.appendChild(parsednode); prevnode = node; node = node.nextSibling; if (childcount > 1) prevnode.parentNode.removeChild(prevnode); } } while (_textblock.inout.isHandleableNode(node) && _textblock.inout.isHandleableNode(node) !== "block"); _textblock.mozBrs.tidy (newTextBlock); return (childcount > 0) ? newTextBlock : false; } return false; }, exportHTML: function (target) { if (!target || !ghostedit.dom.isGhostBlock(target) || target.getAttribute("data-ghostedit-elemtype") !== "textblock") return false; var finalCode = "", stylecode = "", elem; elem = target; _textblock.mozBrs.clear(elem); //if(elem.tagName.toLowerCase() == "p") paracount++; finalCode += "<" + elem.tagName.toLowerCase(); // Extract styles if (elem.style.textAlign !== "") { stylecode += "text-align:" + elem.style.textAlign + ";"; } if (elem.style.clear !== "") stylecode += "clear:" + elem.style.clear + ";"; if (stylecode.length > 0) finalCode += " style='" + stylecode + "'"; // Extract class if (elem.className.length > 0 && !/ghostedit/.test(elem.className)) finalCode += " class='" + elem.className + "'"; finalCode += ">"; // Copy content and end tag finalCode += elem.innerHTML; finalCode += "</" + elem.tagName.toLowerCase() + ">"; _textblock.mozBrs.tidy(elem); return {content: finalCode}; }, isHandleableNode: function (node) { var nodetag; if (!node || !node.nodeType) return false; // Handle textnode case if (node.nodeType === 3) return (node.nodeValue.replace(/[\n\r\t]/g,"").length > 0) ? "text" : false; // Handle not-element case (textnodes already handled) if (node.nodeType !== 1) return false; // Handle textblock case if(node.getAttribute("data-ghostedit-elemtype") === "textblock") return "block"; // Handle other GhostBlock case (don't process other plugins' stuff) if (ghostedit.dom.isGhostBlock(node)) return false; // Else get tagname, and check handleable tag list nodetag = node.tagName.toLowerCase(); if (_textblock.inout.handledtags[nodetag]) { return _textblock.inout.handledtags[nodetag]; } // Else return false return false; } }; _textblock.paste = { handle: function (target, source, position) { if (!ghostedit.dom.isGhostBlock(target) || !ghostedit.dom.isGhostBlock(source)) return; console.log(position); // If source is first pasted element, and was inline content, or is of same type as target, then merge contents into target node if (position.isfirst) { return _textblock.paste.handleFirst(target, source, position); } if (position.islast) { return _textblock.paste.handleLast(target, source, position); } _textblock.paste.split(target); return false; /*if (!position.islast || !(source.tagName.toLowerCase() === "p" || source.tagName === target.tagName) && _textblock.isEmpty(blocks.block2)) { parent = ghostedit.dom.getParentGhostBlock(blocks.block2); handler = parent.getAttribute("data-ghostedit-handler"); marker = document.createElement("span"); marker.id = "ghostedit_paste_end_range_start"; marker.innerHTML = "&#x200b;"; lasso().removeDOMmarkers("ghostedit_paste_end"); ghostedit.plugins[handler].dom.addchild(parent, "after", blocks.block2, marker); ghostedit.plugins[handler].dom.removechild(parent, blocks.block2); return false; }*/ /*PART OF SPLIT FUNCTION lasso().removeDOMmarkers("ghostedit_paste_end"); blocks.block2.innerHTML = "<span id='ghostedit_paste_end_range_start'>&#x200b;</span>" + blocks.block2.innerHTML; _textblock.mozBrs.tidy(blocks.block2);*/ // If source is last pasted element, and was inline content, or is of same type as target, then prepend contents to second node /*if (position.islast && (source.tagName.toLowerCase() === "p" || source.tagName === target.tagName)) { //DEV console.log("paste (last):"); //DEV console.log(blocks.block2); blocks.block2.innerHTML = source.innerHTML + blocks.block2.innerHTML; blocks.block2 = _textblock.format.setTagType({"textblock": blocks.block2, "tagname": source.tagName.toLowerCase()}); return true; }*/ //DEV console.log(blocks.block1.parentNode.cloneNode(true)); }, handleFirst: function (target, source, position) { // No longer needed because is subset of 'p' check: source.getAttribute("data-ghostedit-importinfo") === "wasinline" if (source.tagName.toLowerCase() === "p" || source.tagName === target.tagName) { console.log("paste (first):"); _textblock.mozBrs.clear(source); lasso().removeDOMmarkers("ghostedit_paste_start"); source.innerHTML += "<span id='ghostedit_paste_start_range_start' class='t1'>&#x200b;</span>"; if (document.createRange) { ghostedit.selection.saved.data.collapseToStart().getNative().insertNode( ghostedit.dom.extractContent(source) ); } else { ghostedit.selection.saved.data.collapseToStart().getNative().pasteHTML(source.innerHTML); } return true; } else { return false; } }, handleLast: function (target, source, position) { if (source.tagName.toLowerCase() === "p" || source.tagName === target.tagName) { console.log("paste (last):"); // If selection is collapsed, then create a new paragraph before merging contents if (ghostedit.selection.saved.data.isCollapsed()) { _textblock.paste.split(target); ghostedit.selection.saved.data.restoreFromDOM("ghostedit_paste_start", false); if (lasso().isSavedRange("ghostedit_paste_end")) { ghostedit.selection.saved.data.setEndToRangeEnd(lasso().restoreFromDOM("ghostedit_paste_end", false)); } } _textblock.mozBrs.clear(source); lasso().removeDOMmarkers("ghostedit_paste_end"); source.innerHTML += "<span id='ghostedit_paste_end_range_start'>&#x200b;</span>"; if (document.createRange) { ghostedit.selection.saved.data.collapseToEnd().getNative().insertNode( ghostedit.dom.extractContent(source) ); } else { ghostedit.selection.saved.data.collapseToEnd().getNative().pasteHTML(source.innerHTML); } return true; } else { return false; } }, split: function (target, range) { var blocks, handlestartmarker = false; range = range || ghostedit.selection.saved.data; range = range.clone().collapseToStart(); // Check whether target contains a start marker if (ghostedit.dom.isDescendant(target, document.getElementById("ghostedit_paste_start_range_start"))) { handlestartmarker = true; } if (handlestartmarker) { lasso().removeDOMmarkers("ghostedit_paste_start");//Must be before split or marker is duplicated } blocks = _textblock.split(target, range); if (handlestartmarker) { blocks.block1.innerHTML += "<span id='ghostedit_paste_start_range_start' class='t2'>&#x200b;</span>"; _textblock.mozBrs.tidy(blocks.block1); } // Tidy up end marker lasso().removeDOMmarkers("ghostedit_paste_end"); blocks.block2.innerHTML = "<span id='ghostedit_paste_end_range_start'>&#x200b;</span>" + blocks.block2.innerHTML; _textblock.mozBrs.tidy(blocks.block2); return blocks; } }; _textblock.isTextBlock = function (textblock) { if (!ghostedit.dom.isGhostBlock(textblock)) return false; if (textblock.getAttribute("data-ghostedit-elemtype") !== "textblock") return false; return true; }; _textblock.isEmpty = function (textblock) { var textcontent, imgs, brs, i; // If the node contains textual content then it's not empty //if (ghostedit.util.strip_tags(textblockelem.innerHTML).length > 1) return false; textcontent = textblock.innerText || textblock.textContent; if (textcontent && textcontent.length > 1) return false; // If the node contains no textual content and no <br> or <img> tags then it is empty brs = textblock.getElementsByTagName("br"); imgs = textblock.getElementsByTagName("img"); if (brs.length === 0 && imgs.length === 0) return true; // Otherwise check for non MozDirty <br>'s for(i = 0; i < brs.length; i += 1) { if(brs[i].MozDirty === undefined && !/moz_dirty/.test(brs[i].className)) return false; } // If none are found then it's empty return true; }; _textblock.isFirst = function (textblockelem) { var rootnode, i; rootnode = ghostedit.el.rootnode; for(i = 0; i < rootnode.getElementsByTagName("*").length; i += 1) { if(rootnode.getElementsByTagName("*")[i].getAttribute("data-ghostedit-elemtype") === "textblock") { if(rootnode.getElementsByTagName("*")[i] === textblockelem) { return true; } else { return false; } } } }; _textblock.isLast = function (textblockelem) { var rootnode, i; rootnode = ghostedit.el.rootnode; for(i = rootnode.getElementsByTagName("*").length - 1; i > 0; i -= 1) { if(rootnode.getElementsByTagName("*")[i].getAttribute("data-ghostedit-elemtype") === "textblock") { if(rootnode.getElementsByTagName("*")[i] === textblockelem) { return true; } else { return false; } } } }; _textblock.count = function () { var rootnode, childCount, i; rootnode = ghostedit.el.rootnode; childCount = 0; for(i = 0; i < rootnode.getElementsByTagName("*").length; i += 1) { if(rootnode.getElementsByTagName("*")[i].getAttribute("data-ghostedit-elemtype") === "textblock") { childCount += 1; } } return childCount; }; _textblock.create = function (elemtype, content, id) { var newElem; // If explicit id not passed, get next blockElemId if (!id) { ghostedit.blockElemId += 1; id = 'ghostedit_textblock_' + ghostedit.blockElemId; } // If no content sent, set to default content of "" ---"Edit Here!" content = (content && ((content.length && content.length > 0) || content.nodeType)) ? content : "";//"Edit Here!"; // Create element, and assign id and content newElem = document.createElement(elemtype); newElem.id = id; if (content.nodeType) { content = ghostedit.dom.parse(content, {"textnode": { "clean": true }, "tags": { "b": {}, "i": {}, "u": {}, "strong": {}, "em": {}, "strike": {}, "br": {} } }); if (content) newElem.appendChild(content); } else { newElem.innerHTML = content; } // Set GhostEdit handler attributes newElem.setAttribute("data-ghostedit-iselem", "true"); newElem.setAttribute("data-ghostedit-elemtype", "textblock"); newElem.setAttribute("data-ghostedit-handler", "textblock"); // Add event handlers newElem.ondragenter = function(){return false;}; newElem.ondragleave = function(){return false;}; newElem.ondragover = function(){return false;}; newElem.ondrop = function(e){ var elem, elemid; // This function does basic image paragraph changing dnd elemid = e.dataTransfer.getData("Text") || e.srcElement.id; //alert(elemid); TODO drag drop elem = document.getElementById(elemid); elem.parentNode.insertBefore(elem,this); ghostedit.image.focus(elem); }; newElem.onresizestart = function(e) {return ghostedit.util.cancelEvent(e);}; // Tidy MozBr's in new element _textblock.mozBrs.tidy(newElem); return newElem; }; _textblock.remove = function (textblockelem) { var savedElemContent, rootnode, focuselem, i, thisone, textblockelems; ghostedit.selection.save(); ghostedit.history.saveUndoState(); // If textblock elem still contains content, save to variable for appending to previous textblock elem savedElemContent = ""; savedElemContent = textblockelem.innerHTML; // Cycle through textblock elements backwards to select the one before the current one to focus rootnode = ghostedit.el.rootnode; textblockelems = rootnode.getElementsByTagName("*"); thisone = false; for(i = textblockelems.length - 1; i >= 0; i -= 1) { if (thisone === true && textblockelems[i].getAttribute("data-ghostedit-elemtype") === "textblock") { focuselem = textblockelems[i]; break; } else if (textblockelems[i] === textblockelem) { thisone = true; } } // If focuselem is empty, delete it instead (intuitive behaviour) if (_textblock.isEmpty(focuselem)) { rootnode.removeChild(focuselem); lasso().setCaretToStart(textblockelem).select(); ghostedit.selection.save(); ghostedit.history.saveUndoState(); return; } // Remove textblock elem rootnode.removeChild(textblockelem); // Set caret to end of focuselem lasso().setCaretToEnd(focuselem).select(); ghostedit.selection.save(); // Add saved content focuselem.innerHTML += "<span id='ghostedit_marker'>&#x200b;</span>" + savedElemContent; // Sort out MozBr's (one at very end of elements, that's it) _textblock.mozBrs.tidy(focuselem); // Place caret in correct place lasso().selectNode('ghostedit_marker').deleteContents().select(); if (document.getElementById('ghostedit_marker')) { document.getElementById('ghostedit_marker').parentNode.removeChild(document.getElementById('ghostedit_marker')); } ghostedit.selection.save(); ghostedit.history.saveUndoState(); }; _textblock.focus = function (target) { if (!target || target.nodeType !== 1 || target.getAttribute("data-ghostedit-elemtype") !== "textblock") return false; lasso().setCaretToEnd(target).select(); ghostedit.selection.save(); return true; }; _textblock.merge = function (block1, block2, collapse) { var block1type, block2type, parent, handler; // If collapse === false don't merge if (collapse === false) return block1; // If blocks are same node, return that node if (block1 === block2) return block1; block1type = block1.getAttribute("data-ghostedit-elemtype"); block2type = block2.getAttribute("data-ghostedit-elemtype"); // If one of the blocks isn't a textblock, return false if (block1type !== "textblock" || block2type !== "textblock") return false; // Otherwise, append block2content to block1 and delete block2 block1.innerHTML += "<span id='ghostedit_marker'>&#x200b;</span>" + block2.innerHTML; parent = block2.parentNode; handler = parent.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].dom.removechild(parent, block2); _textblock.mozBrs.tidy(block1); lasso().selectNode("ghostedit_marker").select();//.deleteContents(); document.getElementById("ghostedit_marker").parentNode.removeChild(document.getElementById("ghostedit_marker")); return block1; }; _textblock.split = function (elem, splitpoint) { var wheretoinsert, atstart, atend, elemtype, savedElemContent, range, result, newTextBlock, parent, handler, useselection; useselection = false; if (!splitpoint || !splitpoint.isLassoObject) { ghostedit.selection.save(); if (ghostedit.selection.saved.type !== "textblock") return false; splitpoint = ghostedit.selection.saved.data; useselection = true; } splitpoint = splitpoint.clone().collapseToStart(); atstart = (_textblock.selection.isAtStartOfTextBlock() === true) ? true : false; atend = (_textblock.selection.isAtEndOfTextBlock() === true) ? true : false; wheretoinsert = (atstart && !atend) ? "before" : "after"; elemtype = (wheretoinsert === "before" || atend) ? "p" : _textblock.selection.getStartTextBlockNode().tagName; //console.log("atstart - " + atstart+ "\natend - " + atend + "\nwhere - " + wheretoinsert); // Tidy MozBr's in original element _textblock.mozBrs.tidy(elem); // Save and the delete the content after the caret from the original element if(!atstart && !atend) {//wheretoinsert === "after") { if (document.createRange) { range = lasso().selectNodeContents( elem ).setStartToRangeStart(splitpoint); // Odd bug (at least in chrome) where savedRange is already to the end. savedElemContent = range.getHTML(); range.deleteContents(); } else if (document.selection) { // Bookmark lines allow innerHTML to be modified as long as it is put back to how it was /*savedrange = ghostedit.selection.savedRange.getNative().getBookmark(); range = lasso().selectNodeContents( elem ); ghostedit.selection.savedRange.getNative().moveToBookmark(savedrange); range.getNative().setEndPoint("StartToEnd", ghostedit.selection.savedRange.getNative());*/ range = lasso().selectNode(elem); range.setStartToRangeEnd(splitpoint); savedElemContent = range.getHTML(); range.getNative().text = ""; } } else { savedElemContent = ""; } /*result = _textblock.insert(elem, elemtype, false, wheretoinsert, savedElemContent); */ // Create new element for inserting newTextBlock = _textblock.create(elemtype, savedElemContent); if (!newTextBlock) return false; // Ask (ghost) parent to insert new element into page parent = ghostedit.dom.getParentGhostBlock(elem); handler = parent.getAttribute("data-ghostedit-handler"); result = ghostedit.plugins[handler].dom.addchild (parent, wheretoinsert, elem, newTextBlock, {"contentlength": savedElemContent.length}); if (!result) return false; /* IF !result, replace saved and deleted content after cursor */ // Workaround for ie (6?) bug which doesn't allow an empty element to be selected newTextBlock.innerHTML = "dummy"; lasso().selectNode(newTextBlock).select(); newTextBlock.innerHTML = savedElemContent; // Tidy MozBrs (previous code section often) removes all MozBrs) _textblock.mozBrs.tidy(newTextBlock); // Set caret to start of new element if(wheretoinsert === "before") { range = lasso().setCaretToBlockStart(elem); } else { range = lasso().setCaretToBlockStart(newTextBlock); } // If using selection, set caret to range position if (useselection) { range.select(); ghostedit.selection.save(); } // block1 = first in dom; block2 = second in dom return { "block1": wheretoinsert === "before" ? newTextBlock : elem, "block2": wheretoinsert === "before" ? elem :newTextBlock, "caretposition": range }; }; _textblock.mozBrs = { checkifcontains: function (node) { var elements, i; elements = node.getElementsByTagName("br"); for(i = 0; i < elements.length; i += 1) { if(elements[i].MozDirty !== undefined) return true; } return false; }, insert: function (elem) { var brNode; brNode = document.createElement("br"); brNode.setAttribute("_moz_dirty", ""); brNode.className = "moz_dirty"; elem.appendChild(brNode); }, clear: function (node) { var elements, i; elements = node.getElementsByTagName("br"); for(i = 0; i < elements.length; i += 1) { if(elements[i].MozDirty !== undefined || /moz_dirty/.test(elements[i].className)) { elements[i].parentNode.removeChild(elements[i]); i--; //One less element in live list, so decrease iterator } } }, tidy: function (elem) { _textblock.mozBrs.clear(elem); if(ghostedit.useMozBr) { _textblock.mozBrs.insert(elem); } } }; _textblock.insert = { character: function (character) { if(ghostedit.selection.saved.type === "textblock") { ghostedit.selection.restore(); ghostedit.selection.savedRange.pasteText(character); } }, br: function () { //var isEmpty = false; var s, newBr, r; if (window.getSelection) { s = window.getSelection(); s.getRangeAt(0).collapse(false); newBr = document.createElement("br"); newBr.id = "newBr"; s.getRangeAt(0).insertNode(newBr); s.getRangeAt(0).selectNode(newBr.parentNode); //alert(newBr.nextSibling); r = document.createRange(); r.setStartAfter(newBr); r.setEndAfter(newBr); s.removeAllRanges(); s.addRange(r); document.getElementById("newBr").removeAttribute("id"); } else if (document.selection) { r = document.selection.createRange(); r.collapse(false); r.pasteHTML("<br id='newBr' />"); r.moveToElementText(document.getElementById("newBr")); r.collapse(false); r.select(); document.getElementById("newBr").removeAttribute("id"); } } }; _textblock.format = { init: function () { ghostedit.api.format = ghostedit.api.format || {}; ghostedit.api.format.setStyle = function (tagname, newclass) { _textblock.format.formatSelected(_textblock.format.setTagType, {"tagname": tagname,"newclass": newclass}); }; ghostedit.api.format.alignText = function (alignDirection) { if (!/left|right|center|justify/.test(alignDirection)) return false; _textblock.format.formatSelected(_textblock.format.alignText, {"alignDirection": alignDirection}); }; ghostedit.api.format.bold = function () { _textblock.format.formatSelected(_textblock.format.bold); }; ghostedit.api.format.italic = function () { _textblock.format.formatSelected(_textblock.format.italic); }; ghostedit.api.format.underline = function () { _textblock.format.formatSelected(_textblock.format.underline); }; ghostedit.api.format.strikethrough = function () { _textblock.format.formatSelected(_textblock.format.strikethrough); }; ghostedit.api.format.textColor = function (color) { _textblock.format.formatSelected(_textblock.format.textColor, {"color": color}); }; }, useCommand: function (commandType, param) { //var i, nodes, node, selrange, startofblock, endofblock; //if (typeof param == "undefined") { param = null; } //if (ghostedit.selection.saved.type !== "text") return false; //ghostedit.history.saveUndoState(); document.execCommand(commandType, false, param); //ghostedit.selection.save(); //ghostedit.history.saveUndoState(); }, getNextNode: function (node) { if (node.firstChild) return node.firstChild; while (node) { if (node.nextSibling) return node.nextSibling; node = node.parentNode; } }, getNodesInRange: function (range) { var start = range.getStartNode(), end = range.getEndNode(), commonAncestor = range.getParentNode(), nodes = [], node; // walk parent nodes from start to common ancestor for (node = start.parentNode; node; node = node.parentNode) { nodes.push(node); if (node === commonAncestor) break; } nodes.reverse(); // walk children and siblings from start until end is found for (node = start; node; node = _textblock.format.getNextNode(node)) { nodes.push(node); if (node === end) break; } return nodes; }, useCommandOnWord: function (command) { var range, marker; if (ghostedit.selection.savedRange.isCollapsed() && _textblock.selection.getStartTextBlockNode()) { range = ghostedit.selection.savedRange.clone(); if (document.createRange) { marker = document.createElement("span"); marker.id = "ghostedit_marker"; range.getNative().insertNode(marker); } if (!document.createRange && document.selection) { range.getNative().pasteHTML("<span id='ghostedit_marker'>z</span>"); } range.selectNode("ghostedit_marker"); range = _textblock.selection.extendtoword(range, true); range.select(); } /* Placing cursor inside empty <b> doesn't work in ie <=8 (might work in 6/7) if (range.isCollapsed() && document.selection) { if (document.selection) { range.getNative().pasteHTML("<b><span id='ghostedit_marker'>&#x200b;</span></b>"); alert(lasso().selectNodeContents("ghostedit_marker").getHTML());//.select().deleteContents(); //document.getElementById("ghostedit_newnode").innerHTML = ""; //document.getElementById("ghostedit_newnode").id = ""; } } else {*/ _textblock.format.useCommand(command); if (document.getElementById("ghostedit_marker")) { lasso().selectNode("ghostedit_marker").select(); document.getElementById("ghostedit_marker").parentNode.removeChild(document.getElementById("ghostedit_marker")); } ghostedit.selection.save(); }, bold: function () { _textblock.format.useCommand("bold"); }, italic: function () { _textblock.format.useCommand("italic"); }, underline: function () { _textblock.format.useCommand("underline"); }, strikethrough: function () { _textblock.format.useCommand("strikethrough"); }, textColor: function (color) { _textblock.format.useCommand("foreColor",color); }, formatSelected: function (formatFunc, params) { var elem, startpara, endpara, oldelem, doend, i, descendantblocks; ghostedit.selection.save(); ghostedit.history.saveUndoState(); startpara = _textblock.selection.getStartTextBlockNode(); endpara = _textblock.selection.getEndTextBlockNode(); if (startpara && endpara) { elem = startpara; doend = false; do { if (elem === ghostedit.el.rootnode || elem === null) break; if (_textblock.isTextBlock(elem)) { if (elem === endpara) doend = true; elem = _textblock.format.formatTextBlock(elem, ghostedit.selection.saved.data.clone(), formatFunc, params); if (doend) break; elem = elem.nextSibling ? elem.nextSibling : elem.parentNode; continue; } else if (ghostedit.dom.isDescendant(elem, endpara)) { elem = ghostedit.dom.getFirstChildElement(elem); continue; } else { oldelem = elem; //necessary because setTagType kills list item (and if no list item, then no nextSibling) elem = elem.nextSibling ? elem.nextSibling : elem.parentNode; descendantblocks = oldelem.getElementsByTagName("*"); for(i = 0; i < descendantblocks.length; i += 1) { if (_textblock.isTextBlock(descendantblocks[i])) { _textblock.format.formatTextBlock(descendantblocks[i], ghostedit.selection.saved.data.clone(), formatFunc, params); } } } } while (true); ghostedit.selection.save(); ghostedit.history.saveUndoState(); } ghostedit.history.saveUndoState(); }, formatTextBlock: function (textblock, range, formatFunc, params) { var startofblock, endofblock, newelem; if (!params) params = {}; params.textblock = textblock; // Clone range to avoid reference errors range = range.clone(); // Ranges representing the start and end of the block startofblock = lasso().setCaretToStart(textblock); endofblock = lasso().setCaretToEnd(textblock); // If range doesn't intersect textblock return false //console.log(range.compareEndPoints("EndToStart", startofblock)); //console.log(range.compareEndPoints("StartToEnd", endofblock)); if (range.compareEndPoints("EndToStart", startofblock) === -1 || range.compareEndPoints("StartToEnd", endofblock) === 1) return false; // If range starts before block, move start of selrange to start of block if (range.compareEndPoints("StartToStart", startofblock) === -1) range.setStartToRangeStart(startofblock); // If range end after block, move end of selrange to end of block if (range.compareEndPoints("EndToEnd", endofblock) === 1) range.setEndToRangeEnd(endofblock); ghostedit.selection.saved.data.clone().saveToDOM("ghostedit_format"); //if(textblock.id === "ghostedit_textblock_4") return; range.select(); newelem = formatFunc(params); lasso().restoreFromDOM("ghostedit_format").select(); ghostedit.selection.save(); return newelem && newelem.nodeType !== undefined ? newelem : textblock; }, alignText: function(params) { var elem = lasso().setToSelection().getParentElement(); while (!ghostedit.dom.isGhostBlock(elem)) { elem = elem.parentNode; if (elem === null) return false; } if (!_textblock.isTextBlock(elem)) return false; elem.style.textAlign = params.alignDirection; }, // .tagName is readonly -> need to remove element and add new one setTagType: function (params) { var target, tagtype, newclass, parent, targetid, newTextBlock; target = params.textblock; tagtype = params.tagname; newclass = params.newclass; // Retrieve target node //target = target || ghostedit.selection.nodepath[0]; if (!_textblock.isTextBlock(target)) return false; // Save id of target targetid = 'ghostedit_textblock_' + target.id.replace("ghostedit_textblock_",""); // Create replacement element, and copy over attributes/html newTextBlock = _textblock.create(tagtype); newTextBlock.appendChild(ghostedit.dom.extractContent(target)); _textblock.mozBrs.tidy(newTextBlock); newTextBlock.setAttribute("style", target.getAttribute("style")); if (newclass !== undefined) newTextBlock.className = newclass; // Use naive DOM manipulation because just doing an in place swap parent = target.parentNode; target.id = ""; parent.insertBefore(newTextBlock, target); parent.removeChild(target); // Set id of new TextBlock newTextBlock.id = targetid; return newTextBlock; } }; ghostedit.api.plugin.register("textblock", _textblock); })(window); (function (window, undefined) { var _container = {}, lasso = window.lasso, ghostedit = window.ghostedit; _container.enable = function () { return true; }; _container.dom = { addchild: function (target, wheretoinsert, anchorelem, newElem) { if (wheretoinsert === "before") { target.insertBefore(newElem, anchorelem); } else { if (anchorelem.nextSibling !== null) { target.insertBefore(newElem, anchorelem.nextSibling); } else { target.appendChild(newElem); } } return true; }, removechild: function (target, child) { if (!target || !child) return false; target.removeChild(child); return true; } // Not currently needed, but comments left for easier future implementation /*deleteevent: function (target, sourcedirection, params) { switch (sourcedirection) { case "ahead": // Backspace was pressed at the start of the element after the container break; case "behind": // Delete was pressed at the end of the element before the container break; case "top": // Backspace was pressed at the start of the first child GhostBlock of the container break; case "bottom": // Delete was pressed at the end of the last child GhostBlock the container break; } return false; }*/ }; _container.selection = { deleteContents: function (container, collapse) { var i, firstchildblock, lastchildblock, startofblock, endofblock, atverystart = false, atveryend = false, startblock, endblock, cblock, startcblock, endcblock, childblocks, dodelete, selrange, handler; // Temporary selection range to avoid changing actual saved range if(ghostedit.selection.saved.type !== "textblock") return false; selrange = ghostedit.selection.saved.data; // Get first and last child ghostblock childblocks = container.childNodes; firstchildblock = ghostedit.dom.getFirstChildGhostBlock(container); lastchildblock = ghostedit.dom.getLastChildGhostBlock(container); // Ranges representing the start and end of the block startofblock = lasso().setCaretToStart(firstchildblock); endofblock = lasso().setCaretToEnd(lastchildblock); // If selrange starts before or at block, set startblock to the first child ghostblock if (selrange.compareEndPoints("StartToStart", startofblock) !== 1) { atverystart = true; startblock = firstchildblock; } // Otherwise, set child ghostblock containing the start of the selection else { startblock = selrange.getStartNode(); if (!ghostedit.dom.isGhostBlock(startblock)) startblock = ghostedit.dom.getParentGhostBlock(startblock); } // If selrange ends after or at block, set endblock to the last child ghostblock if (selrange.compareEndPoints("EndToEnd", endofblock) !== -1) { atveryend = true; endblock = lastchildblock; } // Otherwise, set child ghostblock containing the end of the selection else { endblock = selrange.getEndNode(); if (!ghostedit.dom.isGhostBlock(endblock)) endblock = ghostedit.dom.getParentGhostBlock(endblock); } startcblock = startblock; while(!ghostedit.dom.isChildGhostBlock(startcblock, container)) startcblock = ghostedit.dom.getParentGhostBlock(startcblock); endcblock = endblock; while(!ghostedit.dom.isChildGhostBlock(endcblock, container)) endcblock = ghostedit.dom.getParentGhostBlock(endcblock); //alert(startblock.id + endblock.id); /*//Handle selectall case if (isatverystart && isatveryend) { dodelete = false; firsttextblocktype = textblockelems[i].tagName.toLowerCase(); for(i = 0; i < childblocks.length; i += 1) { if (childblocks[i].getAttribute("data-ghostedit-elemtype") !== undefined && childblocks[i].getAttribute("data-ghostedit-elemtype") !== false) { firstchildblock = childblocks[i]; break; } } lasso().setCaretToStart(firstchildblock).select(); return true; }*/ //ghostedit.textblock.selection.deleteContents(lastchildblock); //alert("start - " + startblock.id + "\nend - " + endblock.id); // Cycle through SELECTED child ghostblocks and call delete method dodelete = false; for(i = 0; i < childblocks.length; i += 1) { cblock = childblocks[i]; if ( !ghostedit.dom.isGhostBlock(cblock) ) continue; handler = cblock.getAttribute("data-ghostedit-handler"); if (cblock.id === startcblock.id) { ghostedit.plugins[handler].selection.deleteContents( cblock ); dodelete = true; continue; } else if (cblock.id === endcblock.id) { ghostedit.plugins[handler].selection.deleteContents( cblock ); dodelete = false; break; } if (dodelete) { container.removeChild(childblocks[i]); i--; } } // If the first and last elements in the selection are the same type, then merge if(startcblock.getAttribute("data-ghostedit-elemtype") === endcblock.getAttribute("data-ghostedit-elemtype")) { lasso().setToSelection().saveToDOM("ghostedit_container_deleteselection"); ghostedit.plugins[startcblock.getAttribute("data-ghostedit-elemtype")].merge(startcblock, endcblock, collapse); lasso().restoreFromDOM("ghostedit_container_deleteselection").select(); //if (!ghostedit.dom.getParentGhostBlock(endcblock)) lasso().setToSelection().collapseToStart().select(); //^^tests whether endcblock is still in the document, i.e. whether a merge took place } // If container has no children left, create empty <p> element if (!ghostedit.dom.getFirstChildGhostBlock(container)) { container.appendChild(ghostedit.plugins.textblock.create("p")); } // Place caret where the selection was //lasso().setCaretToStart(endelem).select(); return true; } }; _container.inout = { importHTML: function (sourcenode) { var container, result, i, elemcount, elem, tagname; if (!sourcenode || sourcenode.childNodes.length < 1) return false; container = _container.create(); // For each source child node, check if appropriate import handler exists, if so then call it on the node for (i = 0; i < sourcenode.childNodes.length; i += 1) { elem = sourcenode.childNodes[i]; if (elem.nodeType !== 1 && elem.nodeType !== 3) continue; tagname = (elem.nodeType === 3) ? "#textnode" : elem.tagName.toLowerCase(); /*if (handler = ghostedit.inout.importhandlers[tagname]) { result = ghostedit.plugins[handler].inout.importHTML(elem) if (result && ghostedit.dom.isGhostBlock(result)) { container.appendChild(result); } }*/ if (ghostedit.inout.importhandlers[tagname]) { result = ghostedit.inout.importhandlers[tagname].call(this, elem); if (result && ghostedit.dom.isGhostBlock(result)) { container.appendChild(result); } } else if (elem.childNodes.length > 0) { elemcount = elem.childNodes.length; elem.parentNode.insertBefore(ghostedit.dom.extractContent(elem), elem); elem.parentNode.removeChild(elem); i -= 1; } } // Check any GhostBlock children have been added, else add empty paragraph if (!ghostedit.dom.getFirstChildGhostBlock(container)) { container.appendChild(ghostedit.plugins.textblock.create("p")); } return container; }, exportHTML: function (target/*, includeself*/) { // Shouldn't be used without first using export prepare functions if (!target || !ghostedit.dom.isGhostBlock(target) || target.getAttribute("data-ghostedit-elemtype") !== "container") return false; var i = 0, elem, blockreturn, finalCode = "", blockcount = 0, snippet, handler; //if (target.getAttribute("data-ghostedit-isrootnode") === true) isrootnode = true; // Allows for inclusion of enclosing <div> if wanted in future, may also want to retreieve properties //if (includeself === true) finalCode =+ "<div>"; for (i = 0; i < target.childNodes.length; i += 1) { elem = ghostedit.dom.isGhostBlock( target.childNodes[i] ) ? target.childNodes[i] : false; if (!elem) continue; handler = elem.getAttribute("data-ghostedit-handler"); if (!handler || !ghostedit.plugins[handler]) continue; blockreturn = ghostedit.plugins[handler].inout.exportHTML(elem); if (blockreturn) { finalCode += blockreturn.content; blockcount++; } //Create snippet from first 3 paragraphs if (blockcount <= 3){ snippet = finalCode; } } return {content: finalCode, snippet: snippet}; } }; _container.paste = { handle: function (target, source, position) { var sel, anchor, newnode, dummy; if (!ghostedit.dom.isGhostBlock(target) || !ghostedit.dom.isGhostBlock(source)) return false; //if (position.isfirst || position.islast) return false; sel = ghostedit.selection.saved.data; anchor = sel.clone().collapseToStart().getParentElement(); sel.saveToDOM("ghostedit_paste_start"); if (anchor === target) { /* Just use range marker as dummy elem dummy = document.createElement("span"); dummy.innerHTML = "&#x200b"; dummy.id = "ghostedit_paste_dummy"; sel.clone().collapseToStart().insertNode(dummy);*/ dummy = document.getElementById("ghostedit_paste_start_range_start"); anchor = ghostedit.dom.getPreviousSiblingGhostBlock(dummy) || dummy; } while (anchor.parentNode !== target) { anchor = anchor.parentNode; if (anchor === null || !anchor.parentNode) return true; } newnode = source.cloneNode(true); /*if (position.islast) { sel.removeDOMmarkers("ghostedit_paste"); newnode.innerHTML = "<span id='ghostedit_paste_range_end'>&#x200b;</span>" + newnode.innerHTML; } else { document.getElementById("ghostedit_paste_range_start").parentNode.removeChild(document.getElementById("ghostedit_paste_range_start")); }*/ lasso().removeDOMmarkers("ghostedit_paste_start"); newnode.innerHTML += "<span id='ghostedit_paste_start_range_start' class='t3'>&#x200b;</span>"; _container.dom.addchild(target, "after", anchor, newnode); if (dummy && dummy.parentNode) dummy.parentNode.removeChild(dummy); return true; } }; // TODO remove this function is favour of dom.isChildGhostBlock _container.isChildGhostBlock = function (elem, childblocks) { var i; if (!elem) return false; if (elem.nodeType !== 1) return false; if (elem.getAttribute("data-ghostedit-elemtype") === undefined) return false; if (elem.getAttribute("data-ghostedit-elemtype") === false) return false; if (elem.getAttribute("data-ghostedit-elemtype") === null) return false; for(i = 0; i < childblocks.length; i += 1) { if (elem === childblocks[i]) { return true; } } return false; }; _container.create = function () { var newElem; // Create element, and assign id and content newElem = document.createElement("div"); ghostedit.blockElemId += 1; newElem.id = "ghostedit_container_" + ghostedit.blockElemId; // Set GhostEdit handler attributes newElem.setAttribute("data-ghostedit-iselem", "true"); newElem.setAttribute("data-ghostedit-elemtype", "container"); newElem.setAttribute("data-ghostedit-handler", "container"); return newElem; }; _container.focus = function (target) { var firstchild, handler; if (!target || target.nodeType !== 1 || target.getAttribute("data-ghostedit-elemtype") !== "container") return false; // Get first child of container firstchild = ghostedit.dom.getFirstChildGhostBlock (target); if (!firstchild) return false; handler = firstchild.getAttribute("data-ghostedit-handler"); ghostedit.plugins[handler].focus(firstchild); return true; }; ghostedit.api.plugin.register("container", _container); })(window);<|fim▁end|>
r.selectNode = function (elem) { if(typeof elem === "string") elem = document.getElementById(elem); if (r.domrange) {
<|file_name|>login.go<|end_file_name|><|fim▁begin|>package openshift import ( "io" "io/ioutil" "os" "path/filepath" "strings" "github.com/golang/glog" "github.com/spf13/cobra" kclientcmd "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" kclientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" "github.com/openshift/origin/pkg/cmd/cli/cmd/login" "github.com/openshift/origin/pkg/cmd/cli/config" "github.com/openshift/origin/pkg/cmd/util/clientcmd" ) // Login logs into the specified server using given credentials and CA file<|fim▁hole|> if !os.IsNotExist(err) { return err } existingConfig = *(kclientcmdapi.NewConfig()) } adminConfig, err := kclientcmd.LoadFromFile(filepath.Join(configDir, "master", "admin.kubeconfig")) if err != nil { return err } for k := range adminConfig.AuthInfos { adminConfig.AuthInfos[k].LocationOfOrigin = "" } serverFound := false for k := range adminConfig.Clusters { adminConfig.Clusters[k].LocationOfOrigin = "" if adminConfig.Clusters[k].Server == server { serverFound = true } } if !serverFound { // Create a server entry and admin context for // local cluster for k := range adminConfig.Clusters { localCluster := *adminConfig.Clusters[k] localCluster.Server = server adminConfig.Clusters["local-cluster"] = &localCluster for u := range adminConfig.AuthInfos { if strings.HasPrefix(u, "system:admin") { context := kclientcmdapi.NewContext() context.Cluster = "local-cluster" context.AuthInfo = u context.Namespace = "default" adminConfig.Contexts["default/local-cluster/system:admin"] = context } } break } } newConfig, err := config.MergeConfig(existingConfig, *adminConfig) if err != nil { return err } output := ioutil.Discard if glog.V(1) { output = out } opts := &login.LoginOptions{ Server: server, Username: username, Password: password, Out: output, StartingKubeConfig: newConfig, PathOptions: config.NewPathOptions(c), } return login.RunLogin(nil, opts) }<|fim▁end|>
func Login(username, password, server, configDir string, f *clientcmd.Factory, c *cobra.Command, out io.Writer) error { existingConfig, err := f.OpenShiftClientConfig().RawConfig() if err != nil {
<|file_name|>logger.hpp<|end_file_name|><|fim▁begin|>#pragma once #ifndef UTIL_LOGGER_HPP #define UTIL_LOGGER_HPP #include <gsl/span> #include <string> #include <iterator> #include <vector> #include <cstdlib> /** * @brief A utility which logs a limited amount of entries * @details Logs strings inside a ringbuffer. * * If the buffer is full, the oldest entry will be overwritten. * */ class Logger { public: using Log = gsl::span<char>; public: Logger(Log& log, Log::index_type = 0); /** * @brief Log a string * @details * Write the string to the buffer a zero at the end to indicate end of string. * * If the string overlaps another string, it will clear the remaining string with zeros. * * @param str Message to be logged */ void log(const std::string& str); /** * @brief Retreive all entries from the log * @details Iterates forward over the whole buffer, building strings on the way * * Order old => new * * @return a vector with all the log entries */ std::vector<std::string> entries() const; /** * @brief Retreive entries N from the log * @details * Retrieves N (or less) latest entries from the log, * starting with the oldest. * * * @param n maximum number of entries * @return a vector with entries */ std::vector<std::string> entries(size_t n) const; /** * @brief Clear the log * @details Sets every byte to 0 and set position to start at the beginning. */ void flush(); /** * @brief Size of the log in bytes. * @details Assumes every byte is filled with either data or 0 * @return size in bytes */ auto size() const { return log_.size(); } private: /** The underlaying log */ Log& log_; /** * @brief A "circular" iterator, operating on a Logger::Log * @details Wraps around everytime it reaches the end */ class iterator : public Log::iterator {<|fim▁hole|> // inherit constructors using base::base; constexpr iterator& operator++() noexcept { //Expects(span_ && index_ >= 0); index_ = (index_ < span_->size()-1) ? index_+1 : 0; return *this; } constexpr iterator& operator--() noexcept { //Expects(span_ && index_ < span_->size()); index_ = (index_ > 0) ? index_-1 : span_->size()-1; return *this; } constexpr iterator& operator+=(difference_type n) noexcept { //Expects(span_); index_ = (index_ + n < span_->size()) ? index_ + n : std::abs((n - ((span_->size()) - index_)) % span_->size()); return *this; } constexpr span_iterator& operator-=(difference_type n) noexcept { // No use case for this (yet) return *this += -n; } }; // < class Logger::iterator /** Current position in the log */ iterator pos_; }; // << class Logger #endif<|fim▁end|>
public: using base = Log::iterator;
<|file_name|>energyScalingFunction.H<|end_file_name|><|fim▁begin|>/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2016-2021 hyStrath \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of hyStrath, a derivative work of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::energyScalingFunction Description SourceFiles energyScalingFunction.C newEnergyScalingFunction.C \*---------------------------------------------------------------------------*/ #ifndef energyScalingFunction_H #define energyScalingFunction_H #include "IOdictionary.H" #include "typeInfo.H" #include "runTimeSelectionTables.H" #include "autoPtr.H" #include "pairPotentialModel.H" #include "reducedUnits.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class energyScalingFunction Declaration \*---------------------------------------------------------------------------*/ class energyScalingFunction { protected: // Protected data word name_; dictionary energyScalingFunctionProperties_; const pairPotentialModel& pairPot_; const reducedUnits& rU_; // Private Member Functions //- Disallow copy construct energyScalingFunction(const energyScalingFunction&); //- Disallow default bitwise assignment void operator=(const energyScalingFunction&); public: //- Runtime type information TypeName("energyScalingFunction"); // Declare run-time constructor selection table declareRunTimeSelectionTable ( autoPtr, energyScalingFunction, dictionary, ( const word& name, const dictionary& energyScalingFunctionProperties, const pairPotentialModel& pairPot, const reducedUnits& rU ), (name, energyScalingFunctionProperties, pairPot, rU) ); // Selectors //- Return a reference to the selected viscosity model static autoPtr<energyScalingFunction> New ( const word& name, const dictionary& energyScalingFunctionProperties, const pairPotentialModel& pairPot, const reducedUnits& rU ); // Constructors //- Construct from components energyScalingFunction ( const word& name, const dictionary& energyScalingFunctionProperties, const pairPotentialModel& pairPot, const reducedUnits& rU ); // Destructor virtual ~energyScalingFunction() {} // Member Functions virtual void scaleEnergy(scalar& e, const scalar r) const = 0; const dictionary& energyScalingFunctionProperties() const { return energyScalingFunctionProperties_; } //- Read energyScalingFunction dictionary virtual bool read<|fim▁hole|> ( const dictionary& energyScalingFunctionProperties ) = 0; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //<|fim▁end|>
<|file_name|>macro_inner.rs<|end_file_name|><|fim▁begin|>#![crate_name = "macro_inner"]<|fim▁hole|>pub struct Foo; /// See also [`Foo`] #[macro_export] macro_rules! my_macro { () => {} }<|fim▁end|>
#![deny(broken_intra_doc_links)]
<|file_name|>Icon.tsx<|end_file_name|><|fim▁begin|>import React, { ComponentType } from "react"; import * as styles from "./Icon.module.scss"; type Props = { name: string; icon: ComponentType<any>; }; const Icon = ({ name, icon }: Props) => {<|fim▁hole|>}; export default Icon;<|fim▁end|>
const Icon = icon; return <Icon className={styles.icon} />;
<|file_name|>exception.cpp<|end_file_name|><|fim▁begin|>#include <stdio.h> #include <stdlib.h> static void foo() { throw 123; } <|fim▁hole|>int main(int argc, char *argv[]) { int count = argc == 1 ? 10000 : atoi(argv[ 1 ]); int n = 0; for(int i = 0; i < count; ++i) { try { foo(); } catch(...) { ++n; } } printf("%d\n", n); return 0; }<|fim▁end|>
<|file_name|>admin-user-manage.ts<|end_file_name|><|fim▁begin|>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './admin-user-manage.module';<|fim▁hole|><|fim▁end|>
platformBrowserDynamic().bootstrapModule(AppModule);
<|file_name|>sample_help.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # -*- coding: UTF-8 -*- from __future__ import division,print_function,absolute_import,unicode_literals import sys import os os.chdir(sys.path[0]) sys.path.append('/mnt/sda2/github/TSF1KEV/TSFpy') from TSF_io import * #from TSF_Forth import * from TSF_shuffle import * from TSF_match import * from TSF_calc import * from TSF_time import * TSF_Forth_init(TSF_io_argvs(),[TSF_shuffle_Initwords,TSF_match_Initwords,TSF_calc_Initwords,TSF_time_Initwords]) TSF_Forth_setTSF("TSF_Tab-Separated-Forth:", "\t".join(["UTF-8","#TSF_encoding","replace:","#TSF_this","help:","#TSF_echothe","0","#TSF_fin."]), TSF_style="T") TSF_Forth_setTSF("help:", "\t".join(["usage: ./TSF.py [command|file.tsf] [argv] ...", "commands:", " --help this commands view", " --about about TSF UTF-8 text (Japanese) view\" ", " --python TSF.tsf to Python.py view or save\" ", " --helloworld \"Hello world 1 #TSF_echoN\" sample", " --quine TSF_Forth_viewthey() Quine (self source) sample", " --99beer 99 Bottles of Beer sample", " --fizzbuzz ([0]#3Z1~0)+([0]#5Z2~0) Fizz Buzz Fizz&Buzz sample", " --zundoko Zun Zun Zun Zun Doko VeronCho sample", " --fibonacci Fibonacci number 0,1,1,2,3,5,8,13,21,55... sample", " --prime prime numbers 2,3,5,7,11,13,17,19,23,29... sample", " --calcFX fractions calculator \"1/3-m1|2\"-> p5|6 sample", " --calcDC fractions calculator \"1/3-m1|2\"-> 0.8333... sample", " --calcKN fractions calculator \"1/3-m1|2\"-> 6 bunno 5 sample", " --calender \"@000y@0m@0dm@wdec@0h@0n@0s\"-> TSF_time_getdaytime() sample"]), TSF_style="N") TSF_Forth_setTSF("replace:", "\t".join(["replaceN:","#TSF_carbonthe","#TSF_calender","replaceN:","0","#TSF_pokethe","help:","replaceO:","replaceN:","#TSF_replacestacks"]), TSF_style="T")<|fim▁hole|>TSF_Forth_setTSF("replaceO:", "\t".join(["TSF_time_getdaytime()"]), TSF_style="N") TSF_Forth_setTSF("replaceN:", "\t".join(["@000y@0m@0dm@wdec@0h@0n@0s"]), TSF_style="N") TSF_Forth_addfin(TSF_io_argvs()) TSF_Forth_argvsleftcut(TSF_io_argvs(),1) TSF_Forth_run()<|fim▁end|>
<|file_name|>verify.go<|end_file_name|><|fim▁begin|>package command import ( "fmt" "os" "path/filepath" "time" "github.com/kemokemo/gckdir/lib" "github.com/skratchdot/open-golang/open" "github.com/urfave/cli" ) var ( // UsageVerify is Usage of verify subcommand for cli UsageVerify = "Verifies the structure and each hash value of files." ) // CmdVerify verifies directory information below cases. // Case 1. a json file of hash list with target directory // Case 2. source directory with target directory func CmdVerify(c *cli.Context) error { help := fmt.Sprintf("Please see '%s %s --help'.", c.App.Name, c.Command.FullName()) source := c.Args().Get(0) target := c.Args().Get(1) if source == "" || target == "" { return cli.NewExitError( fmt.Sprintf("Source path or target path is empty. %s", help), ExitCodeInvalidArguments) } source = filepath.Clean(source) target = filepath.Clean(target) <|fim▁hole|> ExitCodeFunctionError) } targetList, err := lib.GetHashList(target) if err != nil { return cli.NewExitError( fmt.Sprintf("Failed to get the hash list. %v\n%s", err, help), ExitCodeFunctionError) } result := lib.VerifyHashList(sourceList, targetList, !c.Bool("no-hv"), !c.Bool("no-uv")) var path string if c.Bool("report") || c.Bool("open") { pathList := lib.PathList{SourcePath: source, TargetPath: target} path, err = createReport(c.String("output"), pathList, result) if err != nil { return cli.NewExitError( fmt.Sprintf("Failed to create a result report. %v\n%s", err, help), ExitCodeFunctionError) } } if c.Bool("open") { err = open.Run(path) if err != nil { return cli.NewExitError( fmt.Sprintf("Failed to open a result report. %v\n%s", err, help), ExitCodeFunctionError) } } if result.VerifyResult == false { fmt.Println("Verification failed.") return cli.NewExitError("", ExitCodeVerificationFailed) } return nil } func createReport(output string, pathList lib.PathList, result lib.HashList) (string, error) { cd, err := os.Getwd() if err != nil { return "", err } if output == "" { output = time.Now().Format("Result_20060102-030405.000000000.html") } path := filepath.Join(cd, output) file, err := os.Create(path) defer func() { err = file.Close() if err != nil { fmt.Println("failed to close file: ", err) } }() err = lib.CreateReport(file, pathList, result) if err != nil { return "", err } path = filepath.Join("file:///", path) return path, nil }<|fim▁end|>
sourceList, err := lib.GetHashList(source) if err != nil { return cli.NewExitError( fmt.Sprintf("Failed to get the hash list. %v\n%s", err, help),
<|file_name|>comment.js<|end_file_name|><|fim▁begin|>function commentPage() { // Open popup $("#comment-popup").dialog({ width : 800, height : 400, modal : true, appendTo: "#mainForm", open : function(event, ui) { $('input[id$="comment-comment"]').focus(); }, close : function(event, ui) { cancelComment(); } }); } /** <|fim▁hole|> */ function cancelComment() { $('textarea[id$="comment-comment"]').val(''); } function saveComment(event) { if (event.status == 'complete') { cancelComment(); $('#comment-popup').dialog('close'); } }<|fim▁end|>
* Clean comment form
<|file_name|>24.d.ts<|end_file_name|><|fim▁begin|>import { MacOption24 } from "../../";<|fim▁hole|> export = MacOption24;<|fim▁end|>
<|file_name|>forecastweather_units.js<|end_file_name|><|fim▁begin|>/* Magic Mirror Test config default weather * * By rejas * MIT Licensed.<|fim▁hole|> modules: [ { module: "weather", position: "bottom_bar", config: { type: "forecast", location: "Munich", mockData: '"#####WEATHERDATA#####"', weatherEndpoint: "/forecast/daily", decimalSymbol: "_" } } ] }; /*************** DO NOT EDIT THE LINE BELOW ***************/ if (typeof module !== "undefined") { module.exports = config; }<|fim▁end|>
*/ let config = { units: "imperial",
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-<|fim▁hole|> The ``scoretools`` package should not import ``instrumenttools`` at top level. ''' from abjad.tools import systemtools systemtools.ImportManager.import_structured_package( __path__[0], globals(), ) _documentation_section = 'core'<|fim▁end|>
'''Dependencies:
<|file_name|>hw5_tests.py<|end_file_name|><|fim▁begin|># -*- coding: utf8 -*- u""" Тесты на ДЗ#5. """ __author__ = "wowkalucky"<|fim▁hole|> import datetime from hw5_solution1 import Person def tests_for_hw5_solution1(): u"""Тесты задачи 1""" petroff = Person("Petrov", "Petro", "1952-01-02") ivanoff = Person("Ivanov", "Ivan", "2000-10-20") sydoroff = Person("Sidorov", "Semen", "1980-12-31", "Senya") assert "first_name" in dir(petroff) assert "get_fullname" in dir(ivanoff) assert "nickname" not in dir(petroff) assert "nickname" in dir(sydoroff) assert petroff.surname == "Petrov" assert petroff.first_name == "Petro" assert petroff.get_fullname() == "Petrov Petro" assert sydoroff.nickname == "Senya" assert petroff.birth_date == datetime.date(1952, 01, 02) assert isinstance(petroff.birth_date, datetime.date) assert petroff.get_age() == "62" print 'All is Ok!'<|fim▁end|>
__email__ = "[email protected]" __date__ = "2014-11-17"
<|file_name|>file_stack.cpp<|end_file_name|><|fim▁begin|>#include <cstdio> #include <string> #include <cerrno> #include <cstring> #include "toi.h" using namespace std; FileStack::FileStack() { tlines = 0; } FileStack::~FileStack() { while(!file_stack.empty()) file_close(); } // returns true if the file is now open // throws an exception upon failure void FileStack::file_open(string name) { Logging(DEBUG) << "opening file \"" << name << "\""; struct file_entry* fe = new struct file_entry; fe->fp = ifstream(name); if(fe->fp.is_open()) { fe->line_no = 1; fe->name = string(name); file_stack.push(fe); } else { Logging(FATAL) << "cannot open input file: \"" << name << "\": " << strerror(errno); } } int FileStack::read_character() { int retv = 0; if(!file_stack.empty()) { retv = file_stack.top()->fp.get(); if(retv == EOF) { // Note that if one reads the stack for a file and and a line // number after this, it's the new file on the tos, not the // one that matches the END_CONTEXT token. I don't think it's // a problem, but I am dropping this comment to mark the // occourance. file_close(); retv = 0x01; } } else { retv = 0x00; } if(retv == '\n') { file_stack.top()->line_no++;<|fim▁hole|> } return retv; } void FileStack::unread_character(int ch) { if(!file_stack.empty()) { if(ch != '\n') file_stack.top()->fp.putback(ch); } } string FileStack::file_name() { if(!file_stack.empty()) return file_stack.top()->name; else return string("no file"); } int FileStack::line_number() { if(!file_stack.empty()) return file_stack.top()->line_no; else return -1; } int FileStack::total_lines() { return tlines; } void FileStack::file_close() { // close the file and pop the stack if(!file_stack.empty()) { Logging(DEBUG) << "closing file \"" << file_stack.top()->name << "\""; struct file_entry* fe = file_stack.top(); fe->fp.close(); file_stack.pop(); delete fe; } else Logging(DEBUG) << "no files to close"; }<|fim▁end|>
tlines++;
<|file_name|>TradeConditionOperator.java<|end_file_name|><|fim▁begin|>package ny2.ats.model.tool;<|fim▁hole|>/** * 取引条件計算の演算子のクラスです */ public enum TradeConditionOperator { EQUAL((d1, d2) -> Double.compare(d1, d2) == 0, null, "="), LESS((d1, d2) -> d1 < d2, null, "<"), LESS_EQUAL((d1, d2) -> d1 <= d2, null, "<="), GRATER((d1, d2) -> d1 > d2, null, ">"), GRATER_EQUAL((d1, d2) -> d1 >= d2, null, ">="), BETWEEN((d1, d2) -> d1 >= d2, (d1, d2) -> d1 <= d2, " between "), WITHOUT((d1, d2) -> d1 < d2, (d1, d2) -> d1 > d2, " without "); // ////////////////////////////////////// // Field // ////////////////////////////////////// private BiPredicate<Double, Double> biPredicate; private BiPredicate<Double, Double> biPredicate2; private String expression; private TradeConditionOperator(BiPredicate<Double, Double> biPredicate, BiPredicate<Double, Double> biPredicate2, String expression) { this.biPredicate = biPredicate; this.expression = expression; } // ////////////////////////////////////// // Method // ////////////////////////////////////// /** * 2種類のBiPredicateを持つかどうかを返します<br> * BETWEEN, WITHOUT のみtrueを返します * @return */ public boolean hasTwoPredicate() { if (biPredicate2 != null) { return true; } else { return false; } } public BiPredicate<Double, Double> getBiPredicate() { return biPredicate; } public BiPredicate<Double, Double> getBiPredicate2() { return biPredicate2; } public String getExpression() { return expression; } }<|fim▁end|>
import java.util.function.BiPredicate;
<|file_name|>dataid.py<|end_file_name|><|fim▁begin|>""" Module defining DataID as enumeration, e.g. concentration, velocity. class Enum allows accessing members by .name and .value FunctionID is deprecated and will be removed """ from enum import IntEnum, auto # Schema for metadata DataSchema = { "type": "object", "properties": { "Type": {"type": "string"}, # Automatically generated from MuPIF, e.g. mupif.field.Field "Type_ID": {"type": "string"}, # Automatically generated from MuPIF, e.g. DataID.FID_Temperature "Name": {"type": "string"}, # e.g. "Density of inclusion" "ID": {"type": ["string", "integer"]}, # Unique ID "Description": {"type": "string"}, # Further description "Units": {"type": "string"}, # Automatically generated from MuPIF, e.g. "kg" "ValueType": {"type": "string"}, # Automatically generated "Origin": {"type": "string", "enum": ["Experiment", "User_input", "Simulated"]}, "Experimental_details": {"type": "string"}, "Experimental_record": {"type": "string"}, # If applies, link to corresponding experimental record "Estimated_std": {"type": "number"}, # Percent of standard deviation "Execution": { "properties": { "ID": {"type": ["string", "integer"]}, # Optional execution ID "Use_case_ID": {"type": ["string", "integer"]}, # If Simulated, give reference to Use_case_ID "Task_ID": {"type": "string"} # If Simulated, give reference to Task_ID }, "required": [] } }, "required": [ "Type", "Type_ID", "Units", "ValueType" ] } class DataID(IntEnum): """ This class represents the supported values of IDs of property, field, etc. Values of members should be stored by .name, .value should not be used. """ # # # # # # # # # # # # # # # # # # # # # # Field FID_Displacement = auto() FID_Strain = auto() FID_Stress = auto() FID_Temperature = auto() FID_Humidity = auto() FID_Concentration = auto() FID_Thermal_absorption_volume = auto() FID_Thermal_absorption_surface = auto() FID_Material_number = auto() FID_BucklingShape = auto() FID_FibreOrientation = auto() FID_DomainNumber = auto() FID_Permeability = auto() FID_Velocity = auto() FID_Pressure = auto() FID_ESI_VPS_Displacement = auto() # # # # # # # # # # # # # # # # # # # # # # GY field IDs FID_Mises_Stress = auto() FID_MaxPrincipal_Stress = auto() FID_MidPrincipal_Stress = auto() FID_MinPrincipal_Stress = auto() FID_MaxPrincipal_Strain = auto() FID_MidPrincipal_Strain = auto() FID_MinPrincipal_Strain = auto() # # # # # # # # # # # # # # # # # # # # # # Particle PSID_ParticlePositions = auto() # # # # # # # # # # # # # # # # # # # # # # Function FuncID_ProbabilityDistribution = auto() # # # # # # # # # # # # # # # # # # # # # # Misc ID_None = auto() ID_GrainState = auto() ID_InputFile = auto() # # # # # # # # # # # # # # # # # # # # # # Property PID_Concentration = auto() PID_CumulativeConcentration = auto() PID_Velocity = auto() PID_transient_simulation_time = auto() PID_effective_conductivity = auto() PID_volume_fraction_red_phosphor = auto() PID_volume_fraction_green_phosphor = auto() PID_conductivity_red_phosphor = auto() PID_conductivity_green_phosphor = auto() PID_mean_radius_red_phosphor = auto() PID_mean_radius_green_phosphor = auto() PID_standard_deviation_red_phosphor = auto() PID_standard_deviation_green_phosphor = auto() PID_RefractiveIndex = auto() PID_NumberOfRays = auto() PID_LEDSpectrum = auto() PID_ChipSpectrum = auto() PID_LEDColor_x = auto() PID_LEDColor_y = auto() PID_LEDCCT = auto() PID_LEDRadiantPower = auto() PID_ParticleNumberDensity = auto() PID_ParticleRefractiveIndex = auto() PID_EmissionSpectrum = auto() PID_ExcitationSpectrum = auto() PID_AsorptionSpectrum = auto() PID_ScatteringCrossSections = auto() PID_InverseCumulativeDist = auto() PID_NumberOfFluorescentParticles = auto() PID_ParticleMu = auto() PID_ParticleSigma = auto() PID_PhosphorEfficiency = auto() PID_Length = auto() PID_Height = auto() PID_Thickness = auto() PID_Deflection = auto() PID_EModulus = auto() # Young's modulus PID_PoissonRatio = auto() # Mul2 properties PID_YoungModulus1 = auto() PID_YoungModulus2 = auto() PID_YoungModulus3 = auto() PID_PoissonRatio23 = auto() PID_PoissonRatio13 = auto() PID_PoissonRatio12 = auto() PID_ShearModulus23 = auto() PID_ShearModulus13 = auto() PID_ShearModulus12 = auto() PID_CriticalLoadLevel = auto() # INSA properties PID_ExtensionalInPlaneStiffness = auto() PID_ExtensionalOutOfPlaneStiffness = auto() PID_ShearInPlaneStiffness = auto() PID_ShearOutOfPlaneStiffness = auto() PID_LocalBendingStiffness = auto() PID_CriticalForce = auto() PID_CriticalMoment = auto() # Digimat Properties PID_MatrixYoung = auto() PID_MatrixPoisson = auto() PID_InclusionYoung = auto() PID_InclusionPoisson = auto() PID_InclusionVolumeFraction = auto() PID_InclusionAspectRatio = auto() PID_MatrixOgdenModulus = auto() PID_MatrixOgdenExponent = auto() PID_InclusionSizeNormalized = auto() PID_CompositeAxialYoung = auto() PID_CompositeInPlaneYoung = auto() PID_CompositeInPlaneShear = auto() PID_CompositeTransverseShear = auto() PID_CompositeInPlanePoisson = auto() PID_CompositeTransversePoisson = auto() PID_CompositeStrain11Tensor = auto() PID_CompositeStrain22Tensor = auto() PID_CompositeStress11Tensor = auto() PID_MatrixDensity = auto() PID_CompositeDensity = auto() PID_InclusionDensity = auto() # CUBA keywords from Jun 6, 2017 - https://github.com/simphony/simphony-common/blob/master/ontology/cuba.yml PID_Position = auto() PID_Direction = auto() PID_Status = auto() PID_Label = auto() PID_Chemical_specie = auto() PID_Material_type = auto() PID_Shape_center = auto() PID_Shape_length = auto() PID_Shape_radius = auto() PID_Shape_side = auto() PID_Crystal_storage = auto() PID_Name_UC = auto() PID_Lattice_vectors = auto() PID_Symmetry_lattice_vectors = auto() PID_Occupancy = auto() PID_Bond_label = auto() PID_Bond_type = auto() # PID_Velocity = auto() Duplicate PID_Dimension = auto() PID_Acceleration = auto() PID_Radius = auto() PID_Size = auto() PID_Mass = auto() PID_Volume = auto() PID_Angular_velocity = auto() PID_Angular_acceleration = auto() PID_Simulation_domain_dimensions = auto() PID_Simulation_domain_origin = auto() PID_Dynamic_viscosity = auto() PID_Kinematic_viscosity = auto() PID_Diffusion_coefficient = auto() PID_Probability_coefficient = auto() PID_Friction_coefficient = auto() PID_Scaling_coefficient = auto() PID_Equation_of_state_coefficient = auto() PID_Contact_angle = auto() PID_Amphiphilicity = auto() PID_Phase_interaction_strength = auto() PID_Hamaker_constant = auto() PID_Zeta_potential = auto() PID_Ion_valence_effect = auto() PID_Debye_length = auto() PID_Smoothing_length = auto() PID_Lattice_spacing = auto() PID_Time_step = auto() PID_Number_of_time_steps = auto() PID_Force = auto() PID_Torque = auto() PID_Density = auto() PID_Pressure = auto() PID_Temperature = auto() PID_Distribution = auto() PID_Order_parameter = auto() PID_Original_position = auto() PID_Current = auto() PID_Final = auto() PID_Delta_displacement = auto() PID_External_applied_force = auto() PID_Euler_angles = auto() PID_Sphericity = auto() PID_Young_modulus = auto() PID_Poisson_ratio = auto() PID_Restitution_coefficient = auto() PID_Rolling_friction = auto() PID_Volume_fraction = auto() PID_Coupling_time = auto() PID_Cutoff_distance = auto() PID_Energy_well_depth = auto() PID_Van_der_Waals_radius = auto() PID_Dielectric_constant = auto() PID_Dynamic_pressure = auto() PID_Flux = auto() PID_Homogenized_stress_tensor = auto() PID_Strain_tensor = auto() PID_Relative_velocity = auto() PID_Diffusion_velocity = auto() PID_Stress_tensor = auto() PID_Volume_fraction_gradient = auto() PID_Cohesion_energy_density = auto()<|fim▁hole|> PID_Charge = auto() PID_Charge_density = auto() PID_Description = auto() PID_Electric_field = auto() PID_Electron_mass = auto() PID_Electrostatic_field = auto() PID_Energy = auto() PID_Heat_conductivity = auto() PID_Initial_viscosity = auto() PID_Linear_constant = auto() PID_Maximum_viscosity = auto() PID_Minimum_viscosity = auto() PID_Momentum = auto() PID_Moment_inertia = auto() PID_Potential_energy = auto() PID_Power_law_index = auto() PID_Relaxation_time = auto() PID_Surface_tension = auto() PID_Time = auto() PID_Viscosity = auto() PID_Collision_operator = auto() PID_Reference_density = auto() PID_External_forcing = auto() PID_Flow_type = auto() PID_Vector = auto() PID_Index = auto() PID_Thermodynamic_ensemble = auto() PID_Variable = auto() PID_None = auto() PID_Lattice_parameter = auto() PID_Steady_state = auto() PID_Maximum_Courant_number = auto() PID_Number_of_cores = auto() PID_Magnitude = auto() PID_Number_of_physics_states = auto() PID_Cohesive_group = auto() PID_FillingTime = auto() # End of CUBA keywords PID_Demo_Min = auto() PID_Demo_Max = auto() PID_Demo_Integral = auto() PID_Demo_Volume = auto() PID_Demo_Value = auto() PID_UserTimeStep = auto() PID_KPI01 = auto() # ESI VPS properties PID_ESI_VPS_TEND = auto() PID_ESI_VPS_PLY1_E0t1 = auto() PID_ESI_VPS_PLY1_E0t2 = auto() PID_ESI_VPS_PLY1_E0t3 = auto() PID_ESI_VPS_PLY1_G012 = auto() PID_ESI_VPS_PLY1_G023 = auto() PID_ESI_VPS_PLY1_G013 = auto() PID_ESI_VPS_PLY1_NU12 = auto() PID_ESI_VPS_PLY1_NU23 = auto() PID_ESI_VPS_PLY1_NU13 = auto() PID_ESI_VPS_PLY1_E0c1 = auto() PID_ESI_VPS_PLY1_RHO = auto() PID_ESI_VPS_hPLY = auto() PID_ESI_VPS_PLY1_XT = auto() PID_ESI_VPS_PLY1_XC = auto() PID_ESI_VPS_PLY1_YT = auto() PID_ESI_VPS_PLY1_YC = auto() PID_ESI_VPS_PLY1_S12 = auto() PID_ESI_VPS_FIRST_FAILURE_VAL = auto() PID_ESI_VPS_FIRST_FAILURE_MOM = auto() PID_ESI_VPS_FIRST_FAILURE_ROT = auto() PID_ESI_VPS_CRIMP_STIFFNESS = auto() PID_ESI_VPS_FIRST_FAILURE_ELE = auto() PID_ESI_VPS_FIRST_FAILURE_PLY = auto() PID_ESI_VPS_TOTAL_MODEL_MASS = auto() PID_ESI_VPS_BUCKL_LOAD = auto() PID_ESI_VPS_MOMENT_CURVE = auto() PID_ESI_VPS_ROTATION_CURVE = auto() PID_ESI_VPS_MOMENT = auto() PID_ESI_VPS_ROTATION = auto() PID_ESI_VPS_THNOD_1 = auto() PID_ESI_VPS_THNOD_2 = auto() PID_ESI_VPS_SECFO_1 = auto() PID_ESI_VPS_SECFO_2 = auto() PID_BoundaryConfiguration = auto() # University of Trieste properties PID_SMILE_MOLECULAR_STRUCTURE = auto() PID_MOLECULAR_WEIGHT = auto() PID_POLYDISPERSITY_INDEX = auto() PID_CROSSLINKER_TYPE = auto() PID_FILLER_DESIGNATION = auto() PID_SMILE_MODIFIER_MOLECULAR_STRUCTURE = auto() PID_SMILE_FILLER_MOLECULAR_STRUCTURE = auto() PID_CROSSLINKONG_DENSITY = auto() PID_FILLER_CONCENTRATION = auto() PID_DENSITY_OF_FUNCTIONALIZATION = auto() PID_TEMPERATURE = auto() PID_PRESSURE = auto() PID_DENSITY = auto() PID_TRANSITION_TEMPERATURE = auto() # GY user-case property IDs PID_HyperelasticPotential = auto() PID_ForceCurve = auto() PID_DisplacementCurve = auto() PID_CorneringAngle = auto() PID_CorneringStiffness = auto() # Demo properties PID_dirichletBC = auto() PID_conventionExternalTemperature = auto() PID_conventionCoefficient = auto() # GY property IDs PID_Footprint = auto() PID_Braking_Force = auto() PID_Stiffness = auto() PID_Hyper1 = auto() PID_maxDisplacement = auto() PID_maxMisesStress = auto() PID_maxPrincipalStress = auto() PID_Hyper2 = auto() # PID_GrainState = auto()<|fim▁end|>
PID_Major = auto() PID_Minor = auto() PID_Patch = auto() PID_Full = auto()
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>use std::io::{ Result, Read };<|fim▁hole|> /// See `read_to_end` for other semantics. fn read_into_vec(&mut self) -> Result<Vec<u8>> { let mut buf = Vec::new(); let res = self.read_to_end(&mut buf); res.map(|_| buf) } /// Read all bytes until EOF in this source, returning them as a new buffer. /// /// See `read_to_string` for other semantics. fn read_into_string(&mut self) -> Result<String> { let mut buf = String::new(); let res = self.read_to_string(&mut buf); res.map(|_| buf) } } impl<T> ReadExt for T where T: Read {}<|fim▁end|>
pub trait ReadExt: Read { /// Read all bytes until EOF in this source, returning them as a new `Vec`. ///
<|file_name|>metadata.py<|end_file_name|><|fim▁begin|>__description__ = "Zookeeper"<|fim▁hole|><|fim▁end|>
__config__ = {}
<|file_name|>pages_test.go<|end_file_name|><|fim▁begin|>package octokit import ( "github.com/stretchr/testify/assert" "testing" ) func TestPagesService_PageInfo(t *testing.T) { setup()<|fim▁hole|> defer tearDown() stubGet(t, "/repos/github/developer.github.com/pages", "pageinfo", nil) page, result := client.Pages().PageInfo(&PagesURL, M{"owner": "github", "repo": "developer.github.com"}) assert.False(t, result.HasError()) assert.Equal(t, "built", page.Status) assert.Equal(t, "developer.github.com", page.Cname) assert.False(t, page.Custom404) } func TestPagesService_PageBuildLatest(t *testing.T) { setup() defer tearDown() stubGet(t, `/repos/github/developer.github.com/pages/builds/latest`, "page_build", nil) build, result := client.Pages().PageBuildLatest(&PagesLatestBuildURL, M{"owner": "github", "repo": "developer.github.com"}) assert.False(t, result.HasError()) assert.Equal(t, "built", build.Status) assert.Equal(t, "351391cdcb88ffae71ec3028c91f375a8036a26b", build.Commit) assert.Equal(t, 1, build.Pusher.ID) assert.Equal(t, 2104, build.Duration) } func TestPagesService_PageBuilds(t *testing.T) { setup() defer tearDown() stubGet(t, "/repos/github/developer.github.com/pages/builds", "page_builds", nil) builds, result := client.Pages().PageBuilds(&PagesBuildsURL, M{"owner": "github", "repo": "developer.github.com"}) assert.False(t, result.HasError()) assert.Equal(t, 1, len(builds)) assert.Equal(t, "built", builds[0].Status) assert.Equal(t, "351391cdcb88ffae71ec3028c91f375a8036a26b", builds[0].Commit) assert.Equal(t, 1, builds[0].Pusher.ID) assert.Equal(t, 2104, builds[0].Duration) } func TestPageService_Failure(t *testing.T) { setup() defer tearDown() url := Hyperlink("}") pageResult, result := client.Pages().PageInfo(&url, nil) assert.True(t, result.HasError()) assert.Equal(t, (*PageInfo)(nil), pageResult) pageBuildResults, result := client.Pages().PageBuilds(&url, nil) assert.True(t, result.HasError()) assert.Equal(t, []PageBuild(nil), pageBuildResults) pageBuildResult, result := client.Pages().PageBuildLatest(&url, nil) assert.True(t, result.HasError()) assert.Equal(t, (*PageBuild)(nil), pageBuildResult) }<|fim▁end|>
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>// 错误使用 // fn main() { // let mut s = String::from("hello"); // let r1 = &s; // 没问题 // let r2 = &s; // 没问题 // let r3 = &mut s; // 大问题 // println!("{}, {}, and {}", r1, r2, r3); //} // 正确使用 fn main() {<|fim▁hole|> let r2 = &s; // 没问题 println!("{} and {}", r1, r2); // 此位置之后 r1 和 r2 不再使用 let r3 = &mut s; // 没问题 println!("{}", r3); }<|fim▁end|>
let mut s = String::from("hello"); let r1 = &s; // 没问题
<|file_name|>construct.py<|end_file_name|><|fim▁begin|>"""Functions to construct sparse matrices """ __docformat__ = "restructuredtext en" __all__ = [ 'spdiags', 'eye', 'identity', 'kron', 'kronsum', 'hstack', 'vstack', 'bmat', 'rand'] from warnings import warn import numpy as np from sputils import upcast from csr import csr_matrix from csc import csc_matrix from bsr import bsr_matrix from coo import coo_matrix from lil import lil_matrix from dia import dia_matrix def spdiags(data, diags, m, n, format=None): """ Return a sparse matrix from diagonals. Parameters ---------- data : array_like matrix diagonals stored row-wise diags : diagonals to set - k = 0 the main diagonal - k > 0 the k-th upper diagonal - k < 0 the k-th lower diagonal m, n : int shape of the result format : format of the result (e.g. "csr") By default (format=None) an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- dia_matrix : the sparse DIAgonal format. Examples -------- >>> data = array([[1,2,3,4],[1,2,3,4],[1,2,3,4]]) >>> diags = array([0,-1,2]) >>> spdiags(data, diags, 4, 4).todense() matrix([[1, 0, 3, 0], [1, 2, 0, 4], [0, 2, 3, 0], [0, 0, 3, 4]]) """ return dia_matrix((data, diags), shape=(m,n)).asformat(format) def identity(n, dtype='d', format=None): """Identity matrix in sparse format Returns an identity matrix with shape (n,n) using a given sparse format and dtype. Parameters ---------- n : integer Shape of the identity matrix. dtype : Data type of the matrix format : string Sparse format of the result, e.g. format="csr", etc. Examples -------- >>> identity(3).todense() matrix([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) >>> identity(3, dtype='int8', format='dia') <3x3 sparse matrix of type '<type 'numpy.int8'>' with 3 stored elements (1 diagonals) in DIAgonal format> """ if format in ['csr','csc']: indptr = np.arange(n+1, dtype=np.intc) indices = np.arange(n, dtype=np.intc) data = np.ones(n, dtype=dtype) cls = eval('%s_matrix' % format) return cls((data,indices,indptr),(n,n)) elif format == 'coo': row = np.arange(n, dtype=np.intc) col = np.arange(n, dtype=np.intc) data = np.ones(n, dtype=dtype) return coo_matrix((data,(row,col)),(n,n)) elif format == 'dia': data = np.ones(n, dtype=dtype) diags = [0] return dia_matrix((data,diags), shape=(n,n)) else: return identity(n, dtype=dtype, format='csr').asformat(format) def eye(m, n, k=0, dtype='d', format=None): """eye(m, n) returns a sparse (m x n) matrix where the k-th diagonal is all ones and everything else is zeros. """ m,n = int(m),int(n) diags = np.ones((1, max(0, min(m + k, n))), dtype=dtype) return spdiags(diags, k, m, n).asformat(format) def kron(A, B, format=None): """kronecker product of sparse matrices A and B Parameters ---------- A : sparse or dense matrix first matrix of the product B : sparse or dense matrix second matrix of the product format : string format of the result (e.g. "csr") Returns ------- kronecker product in a sparse matrix format Examples -------- >>> A = csr_matrix(array([[0,2],[5,0]])) >>> B = csr_matrix(array([[1,2],[3,4]])) >>> kron(A,B).todense() matrix([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) >>> kron(A,[[1,2],[3,4]]).todense() matrix([[ 0, 0, 2, 4], [ 0, 0, 6, 8], [ 5, 10, 0, 0], [15, 20, 0, 0]]) """ B = coo_matrix(B) if (format is None or format == "bsr") and 2*B.nnz >= B.shape[0] * B.shape[1]: #B is fairly dense, use BSR A = csr_matrix(A,copy=True) output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) if A.nnz == 0 or B.nnz == 0: # kronecker product is the zero matrix return coo_matrix( output_shape ) B = B.toarray() data = A.data.repeat(B.size).reshape(-1,B.shape[0],B.shape[1]) data = data * B return bsr_matrix((data,A.indices,A.indptr), shape=output_shape) else: #use COO A = coo_matrix(A) output_shape = (A.shape[0]*B.shape[0], A.shape[1]*B.shape[1]) if A.nnz == 0 or B.nnz == 0: # kronecker product is the zero matrix return coo_matrix( output_shape ) # expand entries of a into blocks row = A.row.repeat(B.nnz) col = A.col.repeat(B.nnz) data = A.data.repeat(B.nnz) row *= B.shape[0] col *= B.shape[1] # increment block indices row,col = row.reshape(-1,B.nnz),col.reshape(-1,B.nnz) row += B.row col += B.col row,col = row.reshape(-1),col.reshape(-1) # compute block entries data = data.reshape(-1,B.nnz) * B.data data = data.reshape(-1) return coo_matrix((data,(row,col)), shape=output_shape).asformat(format) def kronsum(A, B, format=None): """kronecker sum of sparse matrices A and B Kronecker sum of two sparse matrices is a sum of two Kronecker products kron(I_n,A) + kron(B,I_m) where A has shape (m,m) and B has shape (n,n) and I_m and I_n are identity matrices of shape (m,m) and (n,n) respectively. Parameters ---------- A square matrix B square matrix format : string format of the result (e.g. "csr") Returns ------- kronecker sum in a sparse matrix format Examples -------- """ A = coo_matrix(A) B = coo_matrix(B) if A.shape[0] != A.shape[1]: raise ValueError('A is not square') if B.shape[0] != B.shape[1]: raise ValueError('B is not square') dtype = upcast(A.dtype, B.dtype) L = kron(identity(B.shape[0],dtype=dtype), A, format=format) R = kron(B, identity(A.shape[0],dtype=dtype), format=format) return (L+R).asformat(format) #since L + R is not always same format def hstack(blocks, format=None, dtype=None): """ Stack sparse matrices horizontally (column wise) Parameters ---------- blocks sequence of sparse matrices with compatible shapes format : string sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- vstack : stack sparse matrices vertically (row wise) Examples -------- >>> from scipy.sparse import coo_matrix, vstack >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5],[6]]) >>> hstack( [A,B] ).todense() matrix([[1, 2, 5], [3, 4, 6]]) """ return bmat([blocks], format=format, dtype=dtype) def vstack(blocks, format=None, dtype=None): """ Stack sparse matrices vertically (row wise) Parameters ---------- blocks sequence of sparse matrices with compatible shapes format : string sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. See Also -------- hstack : stack sparse matrices horizontally (column wise) Examples -------- >>> from scipy.sparse import coo_matrix, vstack >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5,6]]) >>> vstack( [A,B] ).todense() matrix([[1, 2], [3, 4], [5, 6]]) """ return bmat([ [b] for b in blocks ], format=format, dtype=dtype) def bmat(blocks, format=None, dtype=None): """ Build a sparse matrix from sparse sub-blocks Parameters ---------- blocks grid of sparse matrices with compatible shapes an entry of None implies an all-zero matrix format : sparse format of the result (e.g. "csr") by default an appropriate sparse matrix format is returned. This choice is subject to change. Examples -------- >>> from scipy.sparse import coo_matrix, bmat >>> A = coo_matrix([[1,2],[3,4]]) >>> B = coo_matrix([[5],[6]]) >>> C = coo_matrix([[7]]) >>> bmat( [[A,B],[None,C]] ).todense() matrix([[1, 2, 5], [3, 4, 6], [0, 0, 7]]) >>> bmat( [[A,None],[None,C]] ).todense() matrix([[1, 2, 0], [3, 4, 0], [0, 0, 7]]) """ blocks = np.asarray(blocks, dtype='object') if np.rank(blocks) != 2:<|fim▁hole|> raise ValueError('blocks must have rank 2') M,N = blocks.shape block_mask = np.zeros(blocks.shape, dtype=np.bool) brow_lengths = np.zeros(blocks.shape[0], dtype=np.intc) bcol_lengths = np.zeros(blocks.shape[1], dtype=np.intc) # convert everything to COO format for i in range(M): for j in range(N): if blocks[i,j] is not None: A = coo_matrix(blocks[i,j]) blocks[i,j] = A block_mask[i,j] = True if brow_lengths[i] == 0: brow_lengths[i] = A.shape[0] else: if brow_lengths[i] != A.shape[0]: raise ValueError('blocks[%d,:] has incompatible row dimensions' % i) if bcol_lengths[j] == 0: bcol_lengths[j] = A.shape[1] else: if bcol_lengths[j] != A.shape[1]: raise ValueError('blocks[:,%d] has incompatible column dimensions' % j) # ensure that at least one value in each row and col is not None if brow_lengths.min() == 0: raise ValueError('blocks[%d,:] is all None' % brow_lengths.argmin() ) if bcol_lengths.min() == 0: raise ValueError('blocks[:,%d] is all None' % bcol_lengths.argmin() ) nnz = sum([ A.nnz for A in blocks[block_mask] ]) if dtype is None: dtype = upcast( *tuple([A.dtype for A in blocks[block_mask]]) ) row_offsets = np.concatenate(([0], np.cumsum(brow_lengths))) col_offsets = np.concatenate(([0], np.cumsum(bcol_lengths))) data = np.empty(nnz, dtype=dtype) row = np.empty(nnz, dtype=np.intc) col = np.empty(nnz, dtype=np.intc) nnz = 0 for i in range(M): for j in range(N): if blocks[i,j] is not None: A = blocks[i,j] data[nnz:nnz + A.nnz] = A.data row[nnz:nnz + A.nnz] = A.row col[nnz:nnz + A.nnz] = A.col row[nnz:nnz + A.nnz] += row_offsets[i] col[nnz:nnz + A.nnz] += col_offsets[j] nnz += A.nnz shape = (np.sum(brow_lengths), np.sum(bcol_lengths)) return coo_matrix((data, (row, col)), shape=shape).asformat(format) def rand(m, n, density=0.01, format="coo", dtype=None): """Generate a sparse matrix of the given shape and density with uniformely distributed values. Parameters ---------- m, n: int shape of the matrix density: real density of the generated matrix: density equal to one means a full matrix, density of 0 means a matrix with no non-zero items. format: str sparse matrix format. dtype: dtype type of the returned matrix values. Notes ----- Only float types are supported for now. """ if density < 0 or density > 1: raise ValueError("density expected to be 0 <= density <= 1") if dtype and not dtype in [np.float32, np.float64, np.longdouble]: raise NotImplementedError("type %s not supported" % dtype) mn = m * n # XXX: sparse uses intc instead of intp... tp = np.intp if mn > np.iinfo(tp).max: msg = """\ Trying to generate a random sparse matrix such as the product of dimensions is greater than %d - this is not supported on this machine """ raise ValueError(msg % np.iinfo(tp).max) # Number of non zero values k = long(density * m * n) # Generate a few more values than k so that we can get unique values # afterwards. # XXX: one could be smarter here mlow = 5 fac = 1.02 gk = min(k + mlow, fac * k) def _gen_unique_rand(_gk): id = np.random.rand(_gk) return np.unique(np.floor(id * mn))[:k] id = _gen_unique_rand(gk) while id.size < k: gk *= 1.05 id = _gen_unique_rand(gk) j = np.floor(id * 1. / m).astype(tp) i = (id - j * m).astype(tp) vals = np.random.rand(k).astype(dtype) return coo_matrix((vals, (i, j)), shape=(m, n)).asformat(format)<|fim▁end|>
<|file_name|>fortios_firewall_vip6.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_firewall_vip6 short_description: Configure virtual IP for IPv6 in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify firewall feature and vip6 category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.5 version_added: "2.8" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate IP address. type: str required: false username: description: - FortiOS or FortiGate username. type: str required: false password: description: - FortiOS or FortiGate password. type: str default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol. type: bool default: true ssl_verify: description: - Ensures FortiGate certificate must be verified by a proper CA. type: bool default: true version_added: 2.9 state: description: - Indicates whether to create or remove the object. type: str required: true choices: - present - absent version_added: 2.9 firewall_vip6: description: - Configure virtual IP for IPv6. default: null type: dict suboptions: arp_reply: description: - Enable to respond to ARP requests for this virtual IP address. Enabled by default. type: str choices: - disable - enable color: description: - Color of icon on the GUI. type: int comment: description: - Comment. type: str extip: description: - IP address or address range on the external interface that you want to map to an address or address range on the destination network. type: str extport: description: - Incoming port number range that you want to map to a port number range on the destination network. type: str http_cookie_age: description: - Time in minutes that client web browsers should keep a cookie. Default is 60 seconds. 0 = no time limit. type: int http_cookie_domain: description: - Domain that HTTP cookie persistence should apply to. type: str http_cookie_domain_from_host: description: - Enable/disable use of HTTP cookie domain from host field in HTTP. type: str choices: - disable - enable http_cookie_generation: description: - Generation of HTTP cookie to be accepted. Changing invalidates all existing cookies. type: int http_cookie_path: description: - Limit HTTP cookie persistence to the specified path. type: str http_cookie_share: description: - Control sharing of cookies across virtual servers. same-ip means a cookie from one virtual server can be used by another. Disable stops cookie sharing. type: str choices: - disable - same-ip http_ip_header: description: - For HTTP multiplexing, enable to add the original client IP address in the XForwarded-For HTTP header. type: str choices: - enable - disable http_ip_header_name: description: - For HTTP multiplexing, enter a custom HTTPS header name. The original client IP address is added to this header. If empty, X-Forwarded-For is used. type: str http_multiplex: description: - Enable/disable HTTP multiplexing. type: str choices: - enable - disable https_cookie_secure: description: - Enable/disable verification that inserted HTTPS cookies are secure. type: str choices: - disable - enable id: description: - Custom defined ID. type: int ldb_method: description: - Method used to distribute sessions to real servers. type: str choices: - static - round-robin - weighted - least-session - least-rtt - first-alive - http-host mappedip: description: - Mapped IP address range in the format startIP-endIP. type: str mappedport: description: - Port number range on the destination network to which the external port number range is mapped. type: str max_embryonic_connections: description: - Maximum number of incomplete connections. type: int monitor: description: - Name of the health check monitor to use when polling to determine a virtual server's connectivity status. type: list suboptions: name: description: - Health monitor name. Source firewall.ldb-monitor.name. required: true type: str name: description: - Virtual ip6 name. required: true type: str outlook_web_access: description: - Enable to add the Front-End-Https header for Microsoft Outlook Web Access. type: str choices: - disable - enable persistence: description: - Configure how to make sure that clients connect to the same server every time they make a request that is part of the same session. type: str choices: - none - http-cookie - ssl-session-id portforward: description: - Enable port forwarding. type: str choices: - disable - enable protocol: description: - Protocol to use when forwarding packets. type: str choices: - tcp - udp - sctp realservers: description: - Select the real servers that this server load balancing VIP will distribute traffic to. type: list suboptions: client_ip: description: - Only clients in this IP range can connect to this real server. type: str healthcheck: description: - Enable to check the responsiveness of the real server before forwarding traffic. type: str choices: - disable - enable - vip holddown_interval: description: - Time in seconds that the health check monitor continues to monitor an unresponsive server that should be active. type: int http_host: description: - HTTP server domain name in HTTP header. type: str id: description: - Real server ID. required: true type: int ip: description: - IPv6 address of the real server. type: str max_connections: description: - Max number of active connections that can directed to the real server. When reached, sessions are sent to other real servers. type: int monitor: description: - Name of the health check monitor to use when polling to determine a virtual server's connectivity status. Source firewall .ldb-monitor.name. type: str port: description: - Port for communicating with the real server. Required if port forwarding is enabled. type: int status: description: - Set the status of the real server to active so that it can accept traffic, or on standby or disabled so no traffic is sent. type: str choices: - active - standby - disable weight: description: - Weight of the real server. If weighted load balancing is enabled, the server with the highest weight gets more connections. type: int server_type: description: - Protocol to be load balanced by the virtual server (also called the server load balance virtual IP). type: str choices: - http - https - imaps - pop3s - smtps - ssl - tcp - udp - ip src_filter: description: - "Source IP6 filter (x:x:x:x:x:x:x:x/x). Separate addresses with spaces." type: list suboptions: range: description: - Source-filter range. required: true type: str ssl_algorithm: description: - Permitted encryption algorithms for SSL sessions according to encryption strength. type: str choices: - high - medium - low - custom ssl_certificate: description: - The name of the SSL certificate to use for SSL acceleration. Source vpn.certificate.local.name. type: str ssl_cipher_suites: description: - SSL/TLS cipher suites acceptable from a client, ordered by priority. type: list suboptions: cipher: description: - Cipher suite name. type: str choices: - TLS-RSA-WITH-3DES-EDE-CBC-SHA - TLS-DHE-RSA-WITH-DES-CBC-SHA - TLS-DHE-DSS-WITH-DES-CBC-SHA priority: description: - SSL/TLS cipher suites priority. required: true type: int versions: description: - SSL/TLS versions that the cipher suite can be used with. type: str choices: - ssl-3.0 - tls-1.0 - tls-1.1 - tls-1.2 ssl_client_fallback: description: - Enable/disable support for preventing Downgrade Attacks on client connections (RFC 7507). type: str choices: - disable - enable ssl_client_renegotiation: description: - Allow, deny, or require secure renegotiation of client sessions to comply with RFC 5746. type: str choices: - allow - deny - secure ssl_client_session_state_max: description: - Maximum number of client to FortiGate SSL session states to keep. type: int ssl_client_session_state_timeout: description: - Number of minutes to keep client to FortiGate SSL session state. type: int ssl_client_session_state_type: description: - How to expire SSL sessions for the segment of the SSL connection between the client and the FortiGate. type: str choices: - disable - time - count - both ssl_dh_bits: description: - Number of bits to use in the Diffie-Hellman exchange for RSA encryption of SSL sessions. type: str choices: - 768 - 1024 - 1536 - 2048 - 3072 - 4096 ssl_hpkp: description: - Enable/disable including HPKP header in response. type: str choices: - disable - enable - report-only ssl_hpkp_age: description: - Number of minutes the web browser should keep HPKP. type: int ssl_hpkp_backup: description: - Certificate to generate backup HPKP pin from. Source vpn.certificate.local.name vpn.certificate.ca.name. type: str ssl_hpkp_include_subdomains: description: - Indicate that HPKP header applies to all subdomains. type: str choices: - disable - enable ssl_hpkp_primary: description: - Certificate to generate primary HPKP pin from. Source vpn.certificate.local.name vpn.certificate.ca.name. type: str ssl_hpkp_report_uri: description: - URL to report HPKP violations to. type: str ssl_hsts: description: - Enable/disable including HSTS header in response. type: str choices: - disable - enable ssl_hsts_age: description: - Number of seconds the client should honour the HSTS setting. type: int ssl_hsts_include_subdomains: description: - Indicate that HSTS header applies to all subdomains. type: str choices: - disable - enable ssl_http_location_conversion: description: - Enable to replace HTTP with HTTPS in the reply's Location HTTP header field. type: str choices: - enable - disable ssl_http_match_host: description: - Enable/disable HTTP host matching for location conversion. type: str choices: - enable - disable ssl_max_version: description: - Highest SSL/TLS version acceptable from a client. type: str choices: - ssl-3.0 - tls-1.0 - tls-1.1 - tls-1.2 ssl_min_version: description: - Lowest SSL/TLS version acceptable from a client. type: str choices: - ssl-3.0 - tls-1.0 - tls-1.1 - tls-1.2 ssl_mode: description: - Apply SSL offloading between the client and the FortiGate (half) or from the client to the FortiGate and from the FortiGate to the server (full). type: str choices: - half - full ssl_pfs: description: - Select the cipher suites that can be used for SSL perfect forward secrecy (PFS). Applies to both client and server sessions. type: str choices: - require - deny - allow ssl_send_empty_frags: description: - Enable/disable sending empty fragments to avoid CBC IV attacks (SSL 3.0 & TLS 1.0 only). May need to be disabled for compatibility with older systems. type: str choices: - enable - disable ssl_server_algorithm: description: - Permitted encryption algorithms for the server side of SSL full mode sessions according to encryption strength. type: str choices: - high - medium - low - custom - client ssl_server_cipher_suites: description: - SSL/TLS cipher suites to offer to a server, ordered by priority. type: list suboptions: cipher: description: - Cipher suite name. type: str choices: - TLS-RSA-WITH-3DES-EDE-CBC-SHA - TLS-DHE-RSA-WITH-DES-CBC-SHA - TLS-DHE-DSS-WITH-DES-CBC-SHA priority: description: - SSL/TLS cipher suites priority. required: true type: int versions: description: - SSL/TLS versions that the cipher suite can be used with. type: str choices: - ssl-3.0 - tls-1.0 - tls-1.1 - tls-1.2 ssl_server_max_version: description: - Highest SSL/TLS version acceptable from a server. Use the client setting by default. type: str choices: - ssl-3.0 - tls-1.0 - tls-1.1 - tls-1.2 - client ssl_server_min_version: description: - Lowest SSL/TLS version acceptable from a server. Use the client setting by default. type: str choices: - ssl-3.0 - tls-1.0 - tls-1.1 - tls-1.2 - client ssl_server_session_state_max: description: - Maximum number of FortiGate to Server SSL session states to keep. type: int ssl_server_session_state_timeout: description: - Number of minutes to keep FortiGate to Server SSL session state. type: int ssl_server_session_state_type: description: - How to expire SSL sessions for the segment of the SSL connection between the server and the FortiGate. type: str choices: - disable - time - count - both type: description: - Configure a static NAT or server load balance VIP. type: str choices: - static-nat - server-load-balance uuid: description: - Universally Unique Identifier (UUID; automatically assigned but can be manually reset). type: str weblogic_server: description: - Enable to add an HTTP header to indicate SSL offloading for a WebLogic server. type: str choices: - disable - enable websphere_server: description: - Enable to add an HTTP header to indicate SSL offloading for a WebSphere server. type: str choices: - disable - enable ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" ssl_verify: "False" tasks: - name: Configure virtual IP for IPv6. fortios_firewall_vip6: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" state: "present" firewall_vip6: arp_reply: "disable" color: "4" comment: "Comment." extip: "<your_own_value>" extport: "<your_own_value>" http_cookie_age: "8" http_cookie_domain: "<your_own_value>" http_cookie_domain_from_host: "disable" http_cookie_generation: "11" http_cookie_path: "<your_own_value>" http_cookie_share: "disable" http_ip_header: "enable" http_ip_header_name: "<your_own_value>" http_multiplex: "enable" https_cookie_secure: "disable" id: "18" ldb_method: "static" mappedip: "<your_own_value>" mappedport: "<your_own_value>" max_embryonic_connections: "22" monitor: - name: "default_name_24 (source firewall.ldb-monitor.name)" name: "default_name_25" outlook_web_access: "disable" persistence: "none" portforward: "disable" protocol: "tcp" realservers: - client_ip: "<your_own_value>" healthcheck: "disable" holddown_interval: "33" http_host: "myhostname" id: "35" ip: "<your_own_value>" max_connections: "37" monitor: "<your_own_value> (source firewall.ldb-monitor.name)" port: "39" status: "active" weight: "41" server_type: "http" src_filter: -<|fim▁hole|> ssl_algorithm: "high" ssl_certificate: "<your_own_value> (source vpn.certificate.local.name)" ssl_cipher_suites: - cipher: "TLS-RSA-WITH-3DES-EDE-CBC-SHA" priority: "49" versions: "ssl-3.0" ssl_client_fallback: "disable" ssl_client_renegotiation: "allow" ssl_client_session_state_max: "53" ssl_client_session_state_timeout: "54" ssl_client_session_state_type: "disable" ssl_dh_bits: "768" ssl_hpkp: "disable" ssl_hpkp_age: "58" ssl_hpkp_backup: "<your_own_value> (source vpn.certificate.local.name vpn.certificate.ca.name)" ssl_hpkp_include_subdomains: "disable" ssl_hpkp_primary: "<your_own_value> (source vpn.certificate.local.name vpn.certificate.ca.name)" ssl_hpkp_report_uri: "<your_own_value>" ssl_hsts: "disable" ssl_hsts_age: "64" ssl_hsts_include_subdomains: "disable" ssl_http_location_conversion: "enable" ssl_http_match_host: "enable" ssl_max_version: "ssl-3.0" ssl_min_version: "ssl-3.0" ssl_mode: "half" ssl_pfs: "require" ssl_send_empty_frags: "enable" ssl_server_algorithm: "high" ssl_server_cipher_suites: - cipher: "TLS-RSA-WITH-3DES-EDE-CBC-SHA" priority: "76" versions: "ssl-3.0" ssl_server_max_version: "ssl-3.0" ssl_server_min_version: "ssl-3.0" ssl_server_session_state_max: "80" ssl_server_session_state_timeout: "81" ssl_server_session_state_type: "disable" type: "static-nat" uuid: "<your_own_value>" weblogic_server: "disable" websphere_server: "disable" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.fortios.fortios import FortiOSHandler from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG def login(data, fos): host = data['host'] username = data['username'] password = data['password'] ssl_verify = data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=ssl_verify) def filter_firewall_vip6_data(json): option_list = ['arp_reply', 'color', 'comment', 'extip', 'extport', 'http_cookie_age', 'http_cookie_domain', 'http_cookie_domain_from_host', 'http_cookie_generation', 'http_cookie_path', 'http_cookie_share', 'http_ip_header', 'http_ip_header_name', 'http_multiplex', 'https_cookie_secure', 'id', 'ldb_method', 'mappedip', 'mappedport', 'max_embryonic_connections', 'monitor', 'name', 'outlook_web_access', 'persistence', 'portforward', 'protocol', 'realservers', 'server_type', 'src_filter', 'ssl_algorithm', 'ssl_certificate', 'ssl_cipher_suites', 'ssl_client_fallback', 'ssl_client_renegotiation', 'ssl_client_session_state_max', 'ssl_client_session_state_timeout', 'ssl_client_session_state_type', 'ssl_dh_bits', 'ssl_hpkp', 'ssl_hpkp_age', 'ssl_hpkp_backup', 'ssl_hpkp_include_subdomains', 'ssl_hpkp_primary', 'ssl_hpkp_report_uri', 'ssl_hsts', 'ssl_hsts_age', 'ssl_hsts_include_subdomains', 'ssl_http_location_conversion', 'ssl_http_match_host', 'ssl_max_version', 'ssl_min_version', 'ssl_mode', 'ssl_pfs', 'ssl_send_empty_frags', 'ssl_server_algorithm', 'ssl_server_cipher_suites', 'ssl_server_max_version', 'ssl_server_min_version', 'ssl_server_session_state_max', 'ssl_server_session_state_timeout', 'ssl_server_session_state_type', 'type', 'uuid', 'weblogic_server', 'websphere_server'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for elem in data: elem = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def firewall_vip6(data, fos): vdom = data['vdom'] state = data['state'] firewall_vip6_data = data['firewall_vip6'] filtered_data = underscore_to_hyphen(filter_firewall_vip6_data(firewall_vip6_data)) if state == "present": return fos.set('firewall', 'vip6', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('firewall', 'vip6', mkey=filtered_data['name'], vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_firewall(data, fos): if data['firewall_vip6']: resp = firewall_vip6(data, fos) return not is_successful_status(resp), \ resp['status'] == "success", \ resp def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "default": "", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "ssl_verify": {"required": False, "type": "bool", "default": True}, "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "firewall_vip6": { "required": False, "type": "dict", "default": None, "options": { "arp_reply": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "color": {"required": False, "type": "int"}, "comment": {"required": False, "type": "str"}, "extip": {"required": False, "type": "str"}, "extport": {"required": False, "type": "str"}, "http_cookie_age": {"required": False, "type": "int"}, "http_cookie_domain": {"required": False, "type": "str"}, "http_cookie_domain_from_host": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "http_cookie_generation": {"required": False, "type": "int"}, "http_cookie_path": {"required": False, "type": "str"}, "http_cookie_share": {"required": False, "type": "str", "choices": ["disable", "same-ip"]}, "http_ip_header": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "http_ip_header_name": {"required": False, "type": "str"}, "http_multiplex": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "https_cookie_secure": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "id": {"required": False, "type": "int"}, "ldb_method": {"required": False, "type": "str", "choices": ["static", "round-robin", "weighted", "least-session", "least-rtt", "first-alive", "http-host"]}, "mappedip": {"required": False, "type": "str"}, "mappedport": {"required": False, "type": "str"}, "max_embryonic_connections": {"required": False, "type": "int"}, "monitor": {"required": False, "type": "list", "options": { "name": {"required": True, "type": "str"} }}, "name": {"required": True, "type": "str"}, "outlook_web_access": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "persistence": {"required": False, "type": "str", "choices": ["none", "http-cookie", "ssl-session-id"]}, "portforward": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "protocol": {"required": False, "type": "str", "choices": ["tcp", "udp", "sctp"]}, "realservers": {"required": False, "type": "list", "options": { "client_ip": {"required": False, "type": "str"}, "healthcheck": {"required": False, "type": "str", "choices": ["disable", "enable", "vip"]}, "holddown_interval": {"required": False, "type": "int"}, "http_host": {"required": False, "type": "str"}, "id": {"required": True, "type": "int"}, "ip": {"required": False, "type": "str"}, "max_connections": {"required": False, "type": "int"}, "monitor": {"required": False, "type": "str"}, "port": {"required": False, "type": "int"}, "status": {"required": False, "type": "str", "choices": ["active", "standby", "disable"]}, "weight": {"required": False, "type": "int"} }}, "server_type": {"required": False, "type": "str", "choices": ["http", "https", "imaps", "pop3s", "smtps", "ssl", "tcp", "udp", "ip"]}, "src_filter": {"required": False, "type": "list", "options": { "range": {"required": True, "type": "str"} }}, "ssl_algorithm": {"required": False, "type": "str", "choices": ["high", "medium", "low", "custom"]}, "ssl_certificate": {"required": False, "type": "str"}, "ssl_cipher_suites": {"required": False, "type": "list", "options": { "cipher": {"required": False, "type": "str", "choices": ["TLS-RSA-WITH-3DES-EDE-CBC-SHA", "TLS-DHE-RSA-WITH-DES-CBC-SHA", "TLS-DHE-DSS-WITH-DES-CBC-SHA"]}, "priority": {"required": True, "type": "int"}, "versions": {"required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2"]} }}, "ssl_client_fallback": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "ssl_client_renegotiation": {"required": False, "type": "str", "choices": ["allow", "deny", "secure"]}, "ssl_client_session_state_max": {"required": False, "type": "int"}, "ssl_client_session_state_timeout": {"required": False, "type": "int"}, "ssl_client_session_state_type": {"required": False, "type": "str", "choices": ["disable", "time", "count", "both"]}, "ssl_dh_bits": {"required": False, "type": "str", "choices": ["768", "1024", "1536", "2048", "3072", "4096"]}, "ssl_hpkp": {"required": False, "type": "str", "choices": ["disable", "enable", "report-only"]}, "ssl_hpkp_age": {"required": False, "type": "int"}, "ssl_hpkp_backup": {"required": False, "type": "str"}, "ssl_hpkp_include_subdomains": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "ssl_hpkp_primary": {"required": False, "type": "str"}, "ssl_hpkp_report_uri": {"required": False, "type": "str"}, "ssl_hsts": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "ssl_hsts_age": {"required": False, "type": "int"}, "ssl_hsts_include_subdomains": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "ssl_http_location_conversion": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "ssl_http_match_host": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "ssl_max_version": {"required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2"]}, "ssl_min_version": {"required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2"]}, "ssl_mode": {"required": False, "type": "str", "choices": ["half", "full"]}, "ssl_pfs": {"required": False, "type": "str", "choices": ["require", "deny", "allow"]}, "ssl_send_empty_frags": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "ssl_server_algorithm": {"required": False, "type": "str", "choices": ["high", "medium", "low", "custom", "client"]}, "ssl_server_cipher_suites": {"required": False, "type": "list", "options": { "cipher": {"required": False, "type": "str", "choices": ["TLS-RSA-WITH-3DES-EDE-CBC-SHA", "TLS-DHE-RSA-WITH-DES-CBC-SHA", "TLS-DHE-DSS-WITH-DES-CBC-SHA"]}, "priority": {"required": True, "type": "int"}, "versions": {"required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2"]} }}, "ssl_server_max_version": {"required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2", "client"]}, "ssl_server_min_version": {"required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2", "client"]}, "ssl_server_session_state_max": {"required": False, "type": "int"}, "ssl_server_session_state_timeout": {"required": False, "type": "int"}, "ssl_server_session_state_type": {"required": False, "type": "str", "choices": ["disable", "time", "count", "both"]}, "type": {"required": False, "type": "str", "choices": ["static-nat", "server-load-balance"]}, "uuid": {"required": False, "type": "str"}, "weblogic_server": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "websphere_server": {"required": False, "type": "str", "choices": ["disable", "enable"]} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) # legacy_mode refers to using fortiosapi instead of HTTPAPI legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_firewall(module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_firewall(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()<|fim▁end|>
range: "<your_own_value>"
<|file_name|>Observable.test.ts<|end_file_name|><|fim▁begin|>import {TeardownLogic, Subscription, SubscriptionHandler, Observable, PartialObserver, Subscriber} from 'tabris'; let observable: Observable<string>; let observer: Subscriber<string>; let partialObserver: PartialObserver<string> = {}; let subHandler: SubscriptionHandler<string>; let subscription: Subscription; let teardownObject: TeardownLogic = () => undefined; let str: string = ''; let err: Error; teardownObject = {unsubscribe: () => undefined} observable = new Observable(() => {}); observable = new Observable<string>(() => {}); observable = new Observable(observerArg => { observer = observerArg; bool = observer.closed; }); observable = new Observable(observerArg => { observerArg.next('foo'); observerArg.error(new Error('foo')); observerArg.complete();<|fim▁hole|>observable = new Observable(() => teardownObject); subscription = observable.subscribe(partialObserver); subscription = observable.subscribe(arg => str = arg, (arg: Error) => err = arg, () => undefined); subscription = observable.subscribe(null, null, () => undefined); subscription = observable.subscribe(arg => str = arg, (arg: Error) => err = arg); subscription = observable.subscribe(arg => str = arg); let bool: boolean = subscription.closed; subscription.unsubscribe(); observable[Symbol.observable]().subscribe(partialObserver); subscription = Observable.mutations(new Date()).subscribe(value => str = value.toLocaleDateString());<|fim▁end|>
});
<|file_name|>listener.js<|end_file_name|><|fim▁begin|>'use strict' const { EventEmitter } = require('events') const { Multiaddr } = require('multiaddr') /** * @typedef {import('libp2p-interfaces/src/transport/types').Listener} Listener */ /** * @param {import('../')} libp2p * @returns {Listener} a transport listener */ module.exports = (libp2p) => { const listeningAddrs = new Map() /** * Add swarm handler and listen for incoming connections * * @param {Multiaddr} addr * @returns {Promise<void>} */ async function listen (addr) { const addrString = String(addr).split('/p2p-circuit').find(a => a !== '') const relayConn = await libp2p.dial(new Multiaddr(addrString)) const relayedAddr = relayConn.remoteAddr.encapsulate('/p2p-circuit') listeningAddrs.set(relayConn.remotePeer.toB58String(), relayedAddr) listener.emit('listening') } /** * Get fixed up multiaddrs * * NOTE: This method will grab the peers multiaddrs and expand them such that: * * a) If it's an existing /p2p-circuit address for a specific relay i.e. * `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit` this method will expand the * address to `/ip4/0.0.0.0/tcp/0/ipfs/QmRelay/p2p-circuit/ipfs/QmPeer` where * `QmPeer` is this peers id * b) If it's not a /p2p-circuit address, it will encapsulate the address as a /p2p-circuit * addr, such when dialing over a relay with this address, it will create the circuit using * the encapsulated transport address. This is useful when for example, a peer should only * be dialed over TCP rather than any other transport * * @returns {Multiaddr[]} */ function getAddrs () { const addrs = [] for (const addr of listeningAddrs.values()) { addrs.push(addr) } return addrs } /** @type Listener */ const listener = Object.assign(new EventEmitter(), { close: () => Promise.resolve(), listen, getAddrs<|fim▁hole|> // Remove listeningAddrs when a peer disconnects libp2p.connectionManager.on('peer:disconnect', (connection) => { const deleted = listeningAddrs.delete(connection.remotePeer.toB58String()) if (deleted) { // Announce listen addresses change listener.emit('close') } }) return listener }<|fim▁end|>
})
<|file_name|>rmsprop_op.cc<|end_file_name|><|fim▁begin|>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/optimizers/rmsprop_op.h" namespace paddle { namespace operators { class RmspropOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE_EQ(ctx->HasInput("Param"), true, platform::errors::NotFound( "Input(Param) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ(<|fim▁hole|> platform::errors::NotFound( "Input(MeanSquare) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasInput("LearningRate"), true, platform::errors::NotFound( "Input(LearningRate) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("Grad"), true, platform::errors::NotFound( "Input(Grad) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->HasInput("Moment"), true, platform::errors::NotFound( "Input(Moment) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ(ctx->GetInputsVarType("Param").front(), framework::proto::VarType::LOD_TENSOR, platform::errors::InvalidArgument( "The input var's type in RmspropOp should be " "LoDTensor, but the received is %s", ctx->GetInputsVarType("Param").front())); PADDLE_ENFORCE_EQ( ctx->HasOutput("ParamOut"), true, platform::errors::NotFound( "Output(param_out) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("MomentOut"), true, platform::errors::NotFound( "Output(MomentOut) of RmspropOp should not be null.")); PADDLE_ENFORCE_EQ( ctx->HasOutput("MeanSquareOut"), true, platform::errors::NotFound( "Output(MeanSquareOut) of RmspropOp should not be null.")); if (ctx->Attrs().Get<bool>("centered")) { PADDLE_ENFORCE_EQ( ctx->HasOutput("MeanGradOut"), true, platform::errors::NotFound( "Output(MeanGradOut) of RmspropOp should not be null.")); } auto param_dim = ctx->GetInputDim("Param"); PADDLE_ENFORCE_EQ( param_dim, ctx->GetInputDim("Grad"), platform::errors::InvalidArgument( "Param and grad input of RmspropOp should have the same dimension. " "But received Param's dim [%s] and Grad's dim [%s].", param_dim, ctx->GetInputDim("Grad"))); PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("Moment"), platform::errors::InvalidArgument( "Param and Momentum input of RmspropOp " "should have the same dimension. But received " "Param's dim [%s] and Moment [%s]", param_dim, ctx->GetInputDim("Moment"))); PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("MeanSquare"), platform::errors::InvalidArgument( "Param and Momentum input of RmspropOp " "should have the same dimension. But received " "Param's dim [%s] and MeanSquare [%s]", param_dim, ctx->GetInputDim("MeanSquare"))); auto lr_dim = ctx->GetInputDim("LearningRate"); PADDLE_ENFORCE_EQ(phi::product(lr_dim), 1, platform::errors::InvalidArgument( "Learning Rate of RmspropOp should be a scalar. But " "received LearningRate's dim [%s]", phi::product(lr_dim))); ctx->SetOutputDim("ParamOut", param_dim); ctx->SetOutputDim("MomentOut", param_dim); ctx->SetOutputDim("MeanSquareOut", param_dim); if (ctx->Attrs().Get<bool>("centered")) { ctx->SetOutputDim("MeanGradOut", param_dim); } } }; class RmspropOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("Param", "(Tensor, default Tensor<float>) " "Input parameter value that has to be updated."); AddInput("MeanSquare", "(Tensor, default Tensor<float>)" " The mean square value that gets updated."); AddInput("MeanGrad", "(Tensor, default Tensor<float>)" " The moving average of gradient") .AsDispensable(); AddInput("LearningRate", "(Tensor, default Tensor<float>) " "The learning rate should be a tensor of size 1."); AddInput("Grad", "(Tensor, default Tensor<float>) " "Input gradient of the parameter."); AddInput("Moment", "(Tensor, default Tensor<float>) The moment that gets updated."); AddOutput("ParamOut", "(Tensor) Output updated parameter value."); AddOutput("MomentOut", "(Tensor) Output updated moment."); AddOutput("MeanSquareOut", "(Tensor) Output Mean squared updated value."); AddOutput("MeanGradOut", "(Tensor) Output moving average of gradient updated value."); AddAttr<float>("epsilon", "(float, default 1e-10) Constant " "for numerical stability.") .SetDefault(1.0e-10f); AddAttr<float>("decay", "(float, default 0.9) " "Discounting factor for coming gradient.") .SetDefault(0.9f); AddAttr<float>("momentum", "(float, default 0.0) Constant value.") .SetDefault(0.0f); AddAttr<bool>("centered", "(bool, default false) use centered rmsprop.") .SetDefault(false); AddComment(R"DOC( Rmsprop Optimizer. $$ MeanSquareOut = decay * MeanSquare + (1 - decay) * Grad * Grad \\ MomentOut = momentum * Moment + \frac{LearningRate * Grad}{\sqrt{MeanSquareOut + epsilon}} \\ ParamOut = Param - MomentOut $$ if centered is true: mean_grad = decay * mean_square{t-1} + (1-decay) * gradient mean_square = decay * mean_square{t-1} + (1-decay) * gradient ** 2 mom = momentum * mom{t-1} + learning_rate * g_t / sqrt(mean_square - mean_grad**2 + epsilon) param -= mom The original slides that proposed Rmsprop: Slide 29 of http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf) )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_WITHOUT_GRADIENT(rmsprop, ops::RmspropOp, ops::RmspropOpMaker); REGISTER_OP_CPU_KERNEL( rmsprop, ops::RmspropOpKernel<paddle::platform::CPUDeviceContext, float>, ops::RmspropOpKernel<paddle::platform::CPUDeviceContext, double>);<|fim▁end|>
ctx->HasInput("MeanSquare"), true,
<|file_name|>Mean.java<|end_file_name|><|fim▁begin|>/* * * * Copyright 2015 Skymind,Inc. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package org.nd4j.linalg.api.ops.impl.accum; import org.nd4j.linalg.api.buffer.DataBuffer; import org.nd4j.linalg.api.complex.IComplexNumber; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.ops.Op; /** * Calculate the mean of the vector * * @author Adam Gibson */ public class Mean extends Sum { public Mean() { } public Mean(INDArray x, INDArray y, INDArray z, int n) { super(x, y, z, n); } public Mean(INDArray x, INDArray y, int n) { super(x, y, n); } public Mean(INDArray x) { super(x); } public Mean(INDArray x, INDArray y) { super(x, y); }<|fim▁hole|> @Override public String name() { return "mean"; } @Override public Op opForDimension(int index, int dimension) { INDArray xAlongDimension = x.vectorAlongDimension(index, dimension); if (y() != null) return new Mean(xAlongDimension, y.vectorAlongDimension(index, dimension), xAlongDimension.length()); else return new Mean(x.vectorAlongDimension(index, dimension)); } @Override public Op opForDimension(int index, int... dimension) { INDArray xAlongDimension = x.tensorAlongDimension(index, dimension); if (y() != null) return new Mean(xAlongDimension, y.tensorAlongDimension(index, dimension), xAlongDimension.length()); else return new Mean(x.tensorAlongDimension(index, dimension)); } @Override public double getAndSetFinalResult(double accum){ double d = accum / n(); this.finalResult = d; return d; } @Override public float getAndSetFinalResult(float accum){ float f = accum / n(); this.finalResult = f; return f; } @Override public double calculateFinalResult(double accum, int n) { return accum / n; } @Override public float calculateFinalResult(float accum, int n) { return accum / n; } @Override public IComplexNumber getAndSetFinalResult(IComplexNumber accum){ finalResultComplex = accum.div(n()); return finalResultComplex; } }<|fim▁end|>
<|file_name|>debug.py<|end_file_name|><|fim▁begin|># pylint: disable=C0111,R0903 """Shows that debug is enabled""" import platform import core.module import core.widget import core.decorators class Module(core.module.Module): @core.decorators.every(minutes=60) def __init__(self, config, theme): super().__init__(config, theme, core.widget.Widget(self.full_text)) def full_text(self, widgets): return "debug"<|fim▁hole|> # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4<|fim▁end|>
def state(self, widget): return "warning"
<|file_name|>ZUtils.cpp<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2001-2006 Jacek Sieka, arnetheduck on gmail point com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "stdinc.h" #include "DCPlusPlus.h" #include "ZUtils.h" #include "Exception.h" #include "ResourceManager.h" const double ZFilter::MIN_COMPRESSION_LEVEL = 0.9; ZFilter::ZFilter() : totalIn(0), totalOut(0), compressing(true) { memset(&zs, 0, sizeof(zs)); if(deflateInit(&zs, 3) != Z_OK) { throw Exception(STRING(COMPRESSION_ERROR)); } } ZFilter::~ZFilter() { dcdebug("ZFilter end, %ld/%ld = %.04f\n", zs.total_out, zs.total_in, (float)zs.total_out / max((float)zs.total_in, (float)1)); deflateEnd(&zs); } bool ZFilter::operator()(const void* in, size_t& insize, void* out, size_t& outsize) { if(outsize == 0) return false; zs.next_in = (Bytef*)in; zs.next_out = (Bytef*)out; // Check if there's any use compressing; if not, save some cpu... if(compressing && insize > 0 && outsize > 16 && (totalIn > (64*1024)) && ((static_cast<double>(totalOut) / totalIn) > 0.95)) { zs.avail_in = 0; zs.avail_out = outsize; if(deflateParams(&zs, 0, Z_DEFAULT_STRATEGY) != Z_OK) { throw Exception(STRING(COMPRESSION_ERROR)); } zs.avail_in = insize;<|fim▁hole|> // Check if we ate all space already... if(zs.avail_out == 0) { outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; totalOut += outsize; totalIn += insize; return true; } } else { zs.avail_in = insize; zs.avail_out = outsize; } if(insize == 0) { int err = ::deflate(&zs, Z_FINISH); if(err != Z_OK && err != Z_STREAM_END) throw Exception(STRING(COMPRESSION_ERROR)); outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; totalOut += outsize; totalIn += insize; return err == Z_OK; } else { int err = ::deflate(&zs, Z_NO_FLUSH); if(err != Z_OK) throw Exception(STRING(COMPRESSION_ERROR)); outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; totalOut += outsize; totalIn += insize; return true; } } UnZFilter::UnZFilter() { memset(&zs, 0, sizeof(zs)); if(inflateInit(&zs) != Z_OK) throw Exception(STRING(DECOMPRESSION_ERROR)); } UnZFilter::~UnZFilter() { dcdebug("UnZFilter end, %ld/%ld = %.04f\n", zs.total_out, zs.total_in, (float)zs.total_out / max((float)zs.total_in, (float)1)); inflateEnd(&zs); } bool UnZFilter::operator()(const void* in, size_t& insize, void* out, size_t& outsize) { if(outsize == 0) return 0; zs.avail_in = insize; zs.next_in = (Bytef*)in; zs.avail_out = outsize; zs.next_out = (Bytef*)out; int err = ::inflate(&zs, Z_NO_FLUSH); // see zlib/contrib/minizip/unzip.c, Z_BUF_ERROR means we should have padded // with a dummy byte if at end of stream - since we don't do this it's not a real // error if(!(err == Z_OK || err == Z_STREAM_END || (err == Z_BUF_ERROR && in == NULL))) throw Exception(STRING(DECOMPRESSION_ERROR)); outsize = outsize - zs.avail_out; insize = insize - zs.avail_in; return err == Z_OK; }<|fim▁end|>
compressing = false; dcdebug("Dynamically disabled compression");
<|file_name|>mail_compose_message.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## import base64 import netsvc from osv import osv from osv import fields from tools.translate import _ import tools def _reopen(self, wizard_id, res_model, res_id): return {'type': 'ir.actions.act_window', 'view_mode': 'form', 'view_type': 'form', 'res_id': wizard_id, 'res_model': self._name, 'target': 'new', # save original model in context, otherwise # it will be lost on the action's context switch 'context': {'mail.compose.target.model': res_model, 'mail.compose.target.id': res_id,} } class mail_compose_message(osv.osv_memory): _inherit = 'mail.compose.message' def _get_templates(self, cr, uid, context=None): """ Return Email Template of particular Model. """ if context is None: context = {} record_ids = [] email_template= self.pool.get('email.template') model = False if context.get('message_id'): mail_message = self.pool.get('mail.message') message_data = mail_message.browse(cr, uid, int(context.get('message_id')), context) model = message_data.model elif context.get('mail.compose.target.model') or context.get('active_model'): model = context.get('mail.compose.target.model', context.get('active_model')) if model: record_ids = email_template.search(cr, uid, [('model', '=', model)]) return email_template.name_get(cr, uid, record_ids, context) + [(False,'')] return [] _columns = { 'use_template': fields.boolean('Use Template'), 'template_id': fields.selection(_get_templates, 'Template', size=-1 # means we want an int db column ), } _defaults = { 'template_id' : lambda self, cr, uid, context={} : context.get('mail.compose.template_id', False) } def on_change_template(self, cr, uid, ids, use_template, template_id, email_from=None, email_to=None, context=None): if context is None: context = {} values = {} if template_id:<|fim▁hole|> values = self.pool.get('email.template').read(cr, uid, template_id, self.fields_get_keys(cr, uid), context) report_xml_pool = self.pool.get('ir.actions.report.xml') template = self.pool.get('email.template').get_email_template(cr, uid, template_id, res_id, context) values['attachments'] = False attachments = {} if template.report_template: report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context) report_service = 'report.' + report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name # Ensure report is rendered using template's language ctx = context.copy() if template.lang: ctx['lang'] = self.render_template(cr, uid, template.lang, template.model, res_id, context) service = netsvc.LocalService(report_service) (result, format) = service.create(cr, uid, [res_id], {'model': template.model}, ctx) result = base64.b64encode(result) if not report_name: report_name = report_service ext = "." + format if not report_name.endswith(ext): report_name += ext attachments[report_name] = result # Add document attachments for attach in template.attachment_ids: # keep the bytes as fetched from the db, base64 encoded attachments[attach.datas_fname] = attach.datas values['attachments'] = attachments if values['attachments']: attachment = values.pop('attachments') attachment_obj = self.pool.get('ir.attachment') att_ids = [] for fname, fcontent in attachment.iteritems(): data_attach = { 'name': fname, 'datas': fcontent, 'datas_fname': fname, 'description': fname, 'res_model' : self._name, 'res_id' : ids[0] if ids else False } att_ids.append(attachment_obj.create(cr, uid, data_attach)) values['attachment_ids'] = att_ids else: # render the mail as one-shot values = self.pool.get('email.template').generate_email(cr, uid, template_id, res_id, context=context) # retrofit generated attachments in the expected field format if values['attachments']: attachment = values.pop('attachments') attachment_obj = self.pool.get('ir.attachment') att_ids = [] for fname, fcontent in attachment.iteritems(): data_attach = { 'name': fname, 'datas': fcontent, 'datas_fname': fname, 'description': fname, 'res_model' : self._name, 'res_id' : ids[0] if ids else False } att_ids.append(attachment_obj.create(cr, uid, data_attach)) values['attachment_ids'] = att_ids else: # restore defaults values = self.default_get(cr, uid, self.fields_get_keys(cr, uid), context) values.update(use_template=use_template, template_id=template_id) return {'value': values} def template_toggle(self, cr, uid, ids, context=None): for record in self.browse(cr, uid, ids, context=context): had_template = record.use_template record.write({'use_template': not(had_template)}) if had_template: # equivalent to choosing an empty template onchange_defaults = self.on_change_template(cr, uid, record.id, not(had_template), False, email_from=record.email_from, email_to=record.email_to, context=context) record.write(onchange_defaults['value']) return _reopen(self, record.id, record.model, record.res_id) def save_as_template(self, cr, uid, ids, context=None): if context is None: context = {} email_template = self.pool.get('email.template') model_pool = self.pool.get('ir.model') for record in self.browse(cr, uid, ids, context=context): model = record.model or context.get('active_model') model_ids = model_pool.search(cr, uid, [('model', '=', model)]) model_id = model_ids and model_ids[0] or False model_name = '' if model_id: model_name = model_pool.browse(cr, uid, model_id, context=context).name template_name = "%s: %s" % (model_name, tools.ustr(record.subject)) values = { 'name': template_name, 'email_from': record.email_from or False, 'subject': record.subject or False, 'body_text': record.body_text or False, 'email_to': record.email_to or False, 'email_cc': record.email_cc or False, 'email_bcc': record.email_bcc or False, 'reply_to': record.reply_to or False, 'model_id': model_id or False, 'attachment_ids': [(6, 0, [att.id for att in record.attachment_ids])] } template_id = email_template.create(cr, uid, values, context=context) record.write({'template_id': template_id, 'use_template': True}) # _reopen same wizard screen with new template preselected return _reopen(self, record.id, model, record.res_id) # override the basic implementation def render_template(self, cr, uid, template, model, res_id, context=None): return self.pool.get('email.template').render_template(cr, uid, template, model, res_id, context=context) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<|fim▁end|>
res_id = context.get('mail.compose.target.id') or context.get('active_id') or False if context.get('mail.compose.message.mode') == 'mass_mail': # use the original template values - to be rendered when actually sent # by super.send_mail()
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (c) 2013, Carnegie Mellon University # All rights reserved. # Authors: Michael Koval <[email protected]> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # - Neither the name of Carnegie Mellon University nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF<|fim▁hole|># POSSIBILITY OF SUCH DAMAGE. import base, dependency_manager, logger, ik_ranking, planning, perception, simulation, tsr, viz from named_config import ConfigurationLibrary from clone import Clone, Cloned from bind import bind_subclass import compatibility<|fim▁end|>
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
<|file_name|>connector.js<|end_file_name|><|fim▁begin|>import 'whatwg-fetch'; import { getBaseURL } from 'new-dashboard/utils/base-url'; /* DEV CREDENTIALS: https://connreg.carto-staging.com/api/v4 c96add2d9d67ec784ebec742e2ea4cecdedfdf53 */ async function __createNewConnection (context, payload) { const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections?api_key=${apiKey}`; const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) }); if (!response.ok) { const message = await response.json(); throw new Error(message.errors); } const data = await response.json(); return data; } export async function fetchConnectionsList (context) { if (!context.rootState.user) { return; } context.commit('setLoadingConnections'); const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections?api_key=${apiKey}`; try { const response = await fetch(url); const data = await response.json(); context.commit('setConnections', data || []); } catch (error) { console.error(`ERROR: ${error}`); } } export async function fetchConnectionById (context, id) { if (!context.rootState.user) { return; } const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections/${id}?api_key=${apiKey}`; try { const response = await fetch(url); return await response.json(); } catch (error) { console.error(`ERROR: ${error}`); } } export async function deleteConnection (context, id) { if (!context.rootState.user) { return; } const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections/${id}?api_key=${apiKey}`; try { await fetch(url, { method: 'DELETE' }); context.dispatch('fetchConnectionsList'); } catch (error) { console.error(`ERROR: ${error}`); } } export async function checkOauthConnection (context, connector) { if (!context.rootState.user) { return; } const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections/check_oauth/${connector}?api_key=${apiKey}`; const response = await fetch(url); const data = await response.json(); if (!response.ok) { throw new Error(data.errors); } context.commit('setLoadingConnections'); context.dispatch('fetchConnectionsList'); return data; } export async function fetchOAuthFileList (context, connector) { if (!context.rootState.user) { return; } const baseURL = getBaseURL(context.rootState, 'v1'); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/imports/service/${connector}/list_files?api_key=${apiKey}`; const response = await fetch(url); const data = await response.json(); if (!response.ok) { throw new Error(data.errors); } return data; } export async function createNewOauthConnection (context, connector) { if (!context.rootState.user) { return; } const data = await __createNewConnection(context, { connector: connector, type: 'oauth-service' }); context.dispatch('fetchConnectionsList'); return data && data.auth_url; } export async function createNewConnection (context, { name, connector, ...parameters }) { if (!context.rootState.user) { return; } const data = await __createNewConnection(context, { name, connector, parameters }); context.dispatch('fetchConnectionsList'); return data && data.id; } export async function editExistingConnection (context, { id, name, connector, ...parameters }) { if (!context.rootState.user) { return; } const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections/${id}?api_key=${apiKey}`; const response = await fetch(url, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name, parameters }) }); if (!response.ok) { const message = await response.json(); throw new Error(message.errors); } context.dispatch('fetchConnectionsList'); return id; } export async function connectionDryrun (context, { connector, id, sql_query, import_as }) { if (!context.rootState.user) { return; } const baseURL = getBaseURL(context.rootState, 'v1'); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connectors/${connector}/dryrun?api_key=${apiKey}`; const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ connection_id: id, sql_query, import_as }) }); if (!response.ok) { const message = await response.json(); throw new Error(message.errors); } const data = await response.json(); context.dispatch('fetchConnectionsList'); return data && data.id; } export function requestConnector (context, { user, connector }) { /* Using V3 hubspot API https://api.hsforms.com/submissions/v3/integration/submit/:portalId/:formGuid */ const hubspot_id = '474999'; const form_id = '1644a76c-4876-45ae-aa85-2420cd3fb3ff'; const CONFIG_PATH = [`submissions/v3/integration/submit/${hubspot_id}/${form_id}`]; const data = getFormData(user, connector); const opts = { data, baseUrl: 'https://api.hsforms.com' };<|fim▁hole|> if (err) { resolve(false); } else { resolve(true); } }); }); } function getFormData (user, connector) { return JSON.stringify({ fields: [ { name: 'email', value: user.email }, { name: 'lastname', value: user.last_name || 'no_last_name' }, { name: 'firstname', value: user.name || 'no_firstname' }, { name: 'jobtitle', value: user.job_role || 'no_jobtitle' }, { name: 'company', value: user.company || (user.organization ? user.organization.display_name || user.organization.name : 'no_company') }, { name: 'phone', value: user.phone || 'no_phone' }, { name: 'connector_request_type', value: 'request' }, { name: 'connector_request_name', value: connector } ], context: { pageUri: window.location.href, pageName: document.title } }); } // ------------------------- BIGQUERY ------------------------- export async function createNewBQConnection (context, { name, billing_project, default_project, ...payload }) { if (!context.rootState.user) { return; } const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections?api_key=${apiKey}`; const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name, connector: 'bigquery', parameters: { billing_project, default_project, service_account: JSON.stringify(payload) } }) }); if (!response.ok) { let data; try { data = await response.json(); } catch (e) { // Do nothing } throw new Error(JSON.stringify({ status: response.status, message: data ? data.errors : null })); } const data = await response.json(); return data; } export async function createNewBQConnectionThroughOAuth (context) { if (!context.rootState.user) { return; } const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections?api_key=${apiKey}`; const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ connector: 'bigquery' }) }); if (!response.ok) { let data; try { data = await response.json(); } catch (e) { // Do nothing } throw new Error(JSON.stringify({ status: response.status, message: data ? data.errors : null })); } const data = await response.json(); return data; } export async function checkBQConnectionThroughOAuth (context) { if (!context.rootState.user) { return; } const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections/check_oauth/bigquery?api_key=${apiKey}`; const response = await fetch(url); if (!response.ok) { let data; try { data = await response.json(); } catch (e) { // Do nothing } throw new Error(JSON.stringify({ status: response.status, message: data ? data.errors : null })); } const data = await response.json(); return data; } export async function editBQConnection (context, { bqConnectionId, name, billing_project, default_project, ...payload }) { if (!context.rootState.user) { return; } const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections/${bqConnectionId}?api_key=${apiKey}`; const response = await fetch(url, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name, connector: 'bigquery', parameters: { billing_project, default_project, service_account: JSON.stringify(payload) } }) }); if (!response.ok) { let data; try { data = await response.json(); } catch (e) { // Do nothing } throw new Error(JSON.stringify({ status: response.status, message: data ? data.errors : null })); } return { id: bqConnectionId }; } export async function updateBQConnectionBillingProject (context, { id: bqConnectionId, billing_project }) { if (!context.rootState.user) { return; } const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections/${bqConnectionId}?api_key=${apiKey}`; const response = await fetch(url, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ parameters: { billing_project } }) }); if (!response.ok) { let data; try { data = await response.json(); } catch (e) { // Do nothing } throw new Error(JSON.stringify({ status: response.status, message: data ? data.errors : null })); } return { id: bqConnectionId }; } export async function checkServiceAccount (context, payload) { const baseURL = getBaseURL(context.rootState, 'v1'); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connectors/bigquery/projects?api_key=${apiKey}`; const response = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ service_account: payload }) }); if (!response.ok) { const message = await response.json(); throw new Error(message.errors); } const data = await response.json(); return data; } export async function fetchBQProjectsList (context, connectionId) { if (!context.rootState.user) { return; } context.commit('setLoadingProjects'); const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/connections/${connectionId}/projects?api_key=${apiKey}`; const response = await fetch(url); if (!response.ok) { context.commit('setProjects', []); throw new Error(JSON.stringify({ status: response.status, message: (await response.json()).errors })); } const data = await response.json(); context.commit('setProjects', data || []); return data; } export async function fetchBQDatasetsList (context, { connectionId, projectId }) { if (!context.rootState.user) { return; } context.commit('setLoadingDatasets'); const baseURL = getBaseURL(context.rootState); const apiKey = context.rootState.user.api_key; const url = `${baseURL}/bigquery/datasets?api_key=${apiKey}&connection_id=${connectionId}&project_id=${projectId}`; const response = await fetch(url); if (!response.ok) { context.commit('setBQDatasets', []); throw new Error(JSON.stringify({ status: response.status, message: (await response.json()).errors })); } const data = await response.json(); context.commit('setBQDatasets', data || []); }<|fim▁end|>
return new Promise((resolve, reject) => { context.rootState.client.post([CONFIG_PATH], opts, err => {
<|file_name|>solution_4.cpp<|end_file_name|><|fim▁begin|>#include <iostream> #include <seqan/file.h> #include <seqan/sequence.h><|fim▁hole|>template <typename TText, typename TPattern> int computeLocalScore(TText const & subText, TPattern const & pattern) { int localScore = 0; for (unsigned i = 0; i < length(pattern); ++i) if (subText[i] == pattern[i]) ++localScore; return localScore; } template <typename TText, typename TPattern> String<int> computeScore(TText const & text, TPattern const & pattern) { String<int> score; resize(score, length(text) - length(pattern) + 1, 0); for (unsigned i = 0; i < length(text) - length(pattern) + 1; ++i) score[i] = computeLocalScore(infix(text, i, i + length(pattern)), pattern); return score; } void print(String<int> const & text) { for (unsigned i = 0; i < length(text); ++i) std::cout << text[i] << " "; std::cout << std::endl; } int main() { String<char> text = "This is an awesome tutorial to get to know SeqAn!"; String<char> pattern = "tutorial"; String<int> score = computeScore(text, pattern); print(score); return 0; }<|fim▁end|>
#include <seqan/score.h> using namespace seqan;
<|file_name|>vgg.py<|end_file_name|><|fim▁begin|>import tensorflow as tf import numpy as np import scipy.io vgg_layers = [ 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ] vgg_layer_types = [ 'conv', 'relu', 'conv', 'relu', 'pool', 'conv', 'relu', 'conv', 'relu', 'pool', 'conv', 'relu', 'conv', 'relu', 'conv', 'relu', 'conv', 'relu', 'pool', 'conv', 'relu', 'conv', 'relu', 'conv', 'relu', 'conv', 'relu', 'pool', 'conv', 'relu', 'conv', 'relu', 'conv', 'relu', 'conv', 'relu' ] # Build the vgg convnet # Returns convnet and mean pixel of the convnet def build_net(path_network, input_image): # Load pretrained convnet pretrained_net = scipy.io.loadmat(path_network) # Mean of input pixels - used to normalize input images mean = np.mean(pretrained_net['normalization'][0][0][0], axis = (0, 1)) layers = pretrained_net['layers'][0] convnet = {} current = input_image for i, name in enumerate(vgg_layers): if vgg_layer_types[i] == 'conv': # Convolution layer kernel, bias = layers[i][0][0][0][0] # (width, height, in_channels, out_channels) -> (height, width, in_channels, out_channels) kernels = np.transpose(kernel, (1, 0, 2, 3)) bias = bias.reshape(-1) conv = tf.nn.conv2d(current, tf.constant(kernel), strides = (1, 1, 1, 1), padding = 'SAME') current = tf.nn.bias_add(conv, bias) elif vgg_layer_types[i] == 'relu': # Relu layer current = tf.nn.relu(current) elif vgg_layer_types[i] == 'pool': # Pool layer<|fim▁hole|> def pre_process_image(image, mean_pixel): return image - mean_pixel def restore_image(image, mean_pixel): return image + mean_pixel<|fim▁end|>
current = tf.nn.avg_pool(current, ksize = (1, 2, 2, 1), strides = (1, 2, 2, 1), padding = 'SAME') convnet[name] = current return convnet, mean
<|file_name|>tokenTester.js<|end_file_name|><|fim▁begin|>//currently commented out as TokenTester is causing a OOG error due to the Factory being too big //Not fully needed as factory & separate tests cover token creation. /*contract("TokenTester", function(accounts) { it("creates 10000 initial tokens", function(done) { var tester = TokenTester.at(TokenTester.deployed_address); tester.tokenContractAddress.call() .then(function(tokenContractAddr) { var tokenContract = HumanStandardToken.at(tokenContractAddr); return tokenContract.balanceOf.call(TokenTester.deployed_address); }).then(function (result) { assert.strictEqual(result.toNumber(), 10000); // 10000 as specified in TokenTester.sol done(); }).catch(done); }); //todo:add test on retrieving addresses<|fim▁hole|><|fim▁end|>
});*/
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>#![allow(dead_code)] use std::rc::Rc; use std::ops::{ Add, Sub, }; use chunk::{ChunkOption}; pub struct Vec3f64 { x: f64, y: f64, z: f64, } pub struct Entity { mass: Rc<ChunkOption>, velocity: Vec3f64, location: Vec3f64, rotation: Vec3f64,<|fim▁hole|>impl Add<Vec3f64> for Vec3f64 { type Output = Vec3f64; fn add(self, _rhs: Vec3f64) -> Vec3f64 { Vec3f64 { x: self.x + _rhs.x, y: self.y + _rhs.y, z: self.z + _rhs.z } } } impl Sub<Vec3f64> for Vec3f64 { type Output = Vec3f64; fn sub(self, _rhs: Vec3f64) -> Vec3f64 { Vec3f64 { x: self.x + _rhs.x, y: self.y + _rhs.y, z: self.z + _rhs.z } } }<|fim▁end|>
}
<|file_name|>run-release.js<|end_file_name|><|fim▁begin|>module.exports = function(gulp, plugins, paths){<|fim▁hole|> return plugins.shell.task("node "+paths.build+"/index.js --production"); };<|fim▁end|>
<|file_name|>ringo.cpp<|end_file_name|><|fim▁begin|>#include <iostream> #include "ringo.hpp"<|fim▁hole|>void ringo () { std::cout << "and Ringo" << std::endl; }<|fim▁end|>
<|file_name|>root.rs<|end_file_name|><|fim▁begin|>/* The library provides a simple datastructure to access geolocated labels with an additional elimination time t and a label size factor. The library provides method to query a set of such labels with a bounding box and a minimum elimination time. Copyright (C) {2017} {Filip Krumpe <[email protected]} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ use std::f64; use std::cmp::Ordering; use primitives::label::Label; use primitives::bbox::BBox; /// /// Represent the possible split dimensions. /// #[derive(PartialEq)] enum SplitDimension { X, Y, UNDEF, } <|fim▁hole|>/// in case the node is a leaf node). /// /// The split value indicates the maximum value of the left children in the corresponding /// dimension. The split value is guaranteed to be less than the corresponding coordinate of the /// right children. /// /// Left and right child are some indices, if there is a left or right subtree and none otherwise. pub struct Root { m_t: f64, m_data: Label, m_type: SplitDimension, m_split: f64, m_left_child: Option<usize>, m_right_child: Option<usize>, } impl Root { /// /// Construct a new root from the given label /// /// Note: The function only contains the given label. No subtrees of connenctions to other /// tree nodes are constructed. /// /// To construct a single tree from a forest of root nodes use the Root::init_pst3d(...) /// function. /// pub fn new(l: Label) -> Root { Root { m_t: l.get_t(), m_data: l, m_type: SplitDimension::UNDEF, m_split: f64::NAN, m_left_child: None, m_right_child: None, } } /// /// Initialize a single 3D PST out of a forest of root nodes and return the root node index. /// /// The function will mutate the given root nodes and set the corresponding split type, split /// value and left and right subtree indices. /// /// The function returns the index of the root node in the data array. /// pub fn init_pst3d(mut data: &mut Vec<Root>) -> Option<usize> { let mut refs: Vec<RootRef> = Vec::with_capacity(data.len()); data.sort_by(|first, second| if first.m_t < second.m_t { Ordering::Less } else if first.m_t > second.m_t { Ordering::Greater } else { Ordering::Equal }); data.reverse(); for (idx, d) in data.iter().enumerate() { refs.push(RootRef::new(d, idx)); } let initial_dimension = SplitDimension::X; create_root(refs, &mut data, &initial_dimension) } /// /// Get a vector of references to the elements in the 3d PST with t >= min_t and that are /// contained in bbox. /// pub fn get<'a>(&'a self, bbox: &BBox, min_t: f64, data: &'a Vec<Root>) -> Vec<&'a Label> { let mut r: Vec<&Label> = Vec::new(); if self.m_t <= min_t { return r; } if bbox.is_contained(&self.m_data) { r.push(&self.m_data); } // append the left child if it exists and is cut by the bounding box if let Some(idx) = self.m_left_child { let append = match self.m_type { SplitDimension::X => bbox.get_min_x() <= self.m_split, SplitDimension::Y => bbox.get_min_y() <= self.m_split, SplitDimension::UNDEF => false, }; if append { assert!(idx < data.len()); let mut res = data[idx].get(&bbox, min_t, &data); r.append(&mut res); } } // append the right child if it exists and is cut by the bounding box if let Some(idx) = self.m_right_child { let append = match self.m_type { SplitDimension::X => bbox.get_max_x() > self.m_split, SplitDimension::Y => bbox.get_max_y() > self.m_split, SplitDimension::UNDEF => false, }; if append { assert!(idx < data.len()); let mut res = data[idx].get(&bbox, min_t, &data); r.append(&mut res); } } r } /// /// Get a human readable string representation of the tree rooted at self. /// /// A such string will look like: /// /// ```text /// x-node (split: 4.5): Label [#1]: 'T1' at (1, 2) with prio 1,elim-t: 9 and label factor: \ /// 1.5 /// l y-node (split: 4.5): Label [#2]: 'T2' at (2, 3) with prio 1, elim-t: 8 and label \ /// factor: 1.5 /// l x-node (split: NaN): Label [#3]: 'T3' at (3, 4) with prio 1, elim-t: 7 and \ /// label factor: 1.5 /// ``` /// pub fn to_string(&self, level: i32, data: &Vec<Root>) -> String { // prefix is level x p let p = " "; let mut prefix = String::new(); for _ in 0..level { prefix = format!("{}{}", prefix, p); } let mut result = match self.m_type { SplitDimension::X => { format!("{}x-node (split: {}): {}", prefix, self.m_split, self.m_data.to_string()) } SplitDimension::Y => { format!("{}y-node (split: {}): {}", prefix, self.m_split, self.m_data.to_string()) } SplitDimension::UNDEF => { format!("{}leaf-node (split: {}): {}", prefix, self.m_split, self.m_data.to_string()) } }; // append the left subtree if let Some(idx) = self.m_left_child { assert!(idx < data.len()); result = format!("{}\nl{}", result, data[idx].to_string(level + 1, &data)); } // append the right subtree if let Some(idx) = self.m_right_child { assert!(idx < data.len()); result = format!("{}\nr{}", result, data[idx].to_string(level + 1, &data)); } result } } /// /// The struct represents a reference to a root node and contains all the information required to /// construct the 3D PST. /// #[derive(Debug)] struct RootRef { m_x: f64, m_y: f64, m_t: f64, m_idx: usize, } impl RootRef { /// /// Initialize a new root ref /// fn new(r: &Root, idx: usize) -> RootRef { RootRef { m_t: r.m_data.get_t(), m_x: r.m_data.get_x(), m_y: r.m_data.get_y(), m_idx: idx, } } /// /// Compare two Root refs with respect to the t value. /// fn order_by_t(first: &Self, second: &Self) -> Ordering { if first.m_t < second.m_t { Ordering::Less } else if first.m_t > second.m_t { Ordering::Greater } else { Ordering::Equal } } /// /// Compare two Root refs with respect to the x value. /// fn order_by_x(first: &Self, second: &Self) -> Ordering { if first.m_x < second.m_x { Ordering::Less } else if first.m_x > second.m_x { Ordering::Greater } else { Ordering::Equal } } /// /// Compare two Root refs with respect to the y value. /// fn order_by_y(first: &Self, second: &Self) -> Ordering { if first.m_y < second.m_y { Ordering::Less } else if first.m_y > second.m_y { Ordering::Greater } else { Ordering::Equal } } } /// /// In the RootRef vector find the index of the root with the maximum t value. /// fn find_root_idx(refs: &mut Vec<RootRef>) -> usize { let mut max_t = 0.; let mut max_idx = 0; for (idx, e) in refs.iter().enumerate() { if e.m_t > max_t { max_t = e.m_t; max_idx = idx; } } let r = refs.swap_remove(max_idx); assert!(r.m_t == max_t); r.m_idx } /// /// From the given RootRef vector construct the subtree and update the corresponding root nodes in /// the data vector. /// /// The element with the maximum t value will be set as root with the corresponding split /// dimension. The remaining elements will sorted by the split dimension. The split value is the /// corresponding coordinate of item floor(|root_refs| / 2) and the elements are splitted into <= /// and >. /// /// From the <= elements the left subtree is constructed recursively with swapped split dimension. /// Same for the > elements as the right subtree. /// /// For the nodes in data that are referenced by RootRefs in root_refs the corresponding Roots are /// updated accordingly. /// fn create_root(mut root_refs: Vec<RootRef>, mut data: &mut Vec<Root>, dim: &SplitDimension) -> Option<usize> { if root_refs.is_empty() { return None; } let size1 = root_refs.len(); assert!(*dim != SplitDimension::UNDEF); let is_x = *dim == SplitDimension::X; // find the element with the maximum t value, remove the corresonding RootRef let root_idx = find_root_idx(&mut root_refs); // the sub dimension flips from X to Y or from Y to X let sub_dim = if is_x { SplitDimension::Y } else { SplitDimension::X }; let mut split_value = f64::NAN; let mut left_child_idx: Option<usize> = None; let mut right_child_idx: Option<usize> = None; let order_asc = if is_x { RootRef::order_by_x } else { RootRef::order_by_y }; if root_refs.len() == 1 { split_value = if is_x { root_refs[0].m_x } else { root_refs[0].m_y }; left_child_idx = create_root(root_refs, &mut data, &sub_dim); } else if root_refs.len() > 1 { root_refs.sort_by(order_asc); // take the x value of the median element as the new split value let mut median_idx = root_refs.len() / 2 - 1; split_value = if is_x { root_refs[median_idx].m_x } else { root_refs[median_idx].m_y }; // ensure that the right children realy have a value > m_split if is_x { while median_idx < root_refs.len() && root_refs[median_idx].m_x == split_value { median_idx = median_idx + 1; } } else { while median_idx < root_refs.len() && root_refs[median_idx].m_y == split_value { median_idx = median_idx + 1; } } let size2 = root_refs.len(); assert!(size1 == size2 + 1); // split the data at the median point: let last = root_refs.split_off(median_idx); assert!(size2 == root_refs.len() + last.len()); left_child_idx = create_root(root_refs, &mut data, &sub_dim); right_child_idx = create_root(last, &mut data, &sub_dim); } let r = data.get_mut(root_idx) .expect("Trying to access element at not existing vector position"); r.m_type = if is_x { SplitDimension::X } else { SplitDimension::Y }; r.m_split = split_value; r.m_left_child = left_child_idx; r.m_right_child = right_child_idx; Some(root_idx) } #[test] fn test_root_new() { let r = Root::new(Label::new(1., 2., 9., 1, 1, 1.5, "A".to_string())); assert!(r.m_t == 9.); assert!(*r.m_data.get_label() == "A".to_string()); assert!(r.m_type == SplitDimension::UNDEF); } #[test] fn test_pst_init() { let mut f: Vec<Root> = Vec::new(); f.push(Root::new(Label::new(1., 2., 9., 1, 1, 1.5, "A".to_string()))); f.push(Root::new(Label::new(2., 3., 8., 2, 1, 1.5, "B".to_string()))); f.push(Root::new(Label::new(3., 4., 7., 3, 1, 1.5, "C".to_string()))); let root = Root::init_pst3d(&mut f); let root_idx = root.unwrap(); println!("{}", f[root_idx].to_string(0, &f)); assert!(root_idx == 0); assert!(f[root_idx].m_type == SplitDimension::X); assert!(f[root_idx].m_left_child.is_some()); assert!(f[root_idx].m_right_child.is_some()); assert!(f[root_idx].m_left_child.unwrap() == 1); assert!(f[root_idx].m_right_child.unwrap() == 2); }<|fim▁end|>
/// /// The struct defines a tree node. /// /// The tree nodes members are the labels t value, the label itself, the split type (X, Y or UNDEF
<|file_name|>events.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import, unicode_literals from six import add_metaclass, text_type from .event_encoder import Parameter, EventEncoder @add_metaclass(EventEncoder) class Event(object): hit = Parameter('t', text_type, required=True) category = Parameter('ec', text_type, required=True) action = Parameter('ea', text_type, required=True) label = Parameter('el', text_type) value = Parameter('ev', int) <|fim▁hole|><|fim▁end|>
def __init__(self, **kwargs): self.hit = 'event' for name, value in kwargs.items(): setattr(self, name, value)
<|file_name|>deep_pytorch.py<|end_file_name|><|fim▁begin|>import numpy as np import warnings from .._explainer import Explainer from packaging import version torch = None class PyTorchDeep(Explainer): def __init__(self, model, data): # try and import pytorch global torch if torch is None: import torch if version.parse(torch.__version__) < version.parse("0.4"): warnings.warn("Your PyTorch version is older than 0.4 and not supported.") # check if we have multiple inputs self.multi_input = False if type(data) == list: self.multi_input = True if type(data) != list: data = [data] self.data = data self.layer = None self.input_handle = None self.interim = False self.interim_inputs_shape = None self.expected_value = None # to keep the DeepExplainer base happy if type(model) == tuple: self.interim = True model, layer = model model = model.eval() self.layer = layer self.add_target_handle(self.layer) # if we are taking an interim layer, the 'data' is going to be the input # of the interim layer; we will capture this using a forward hook with torch.no_grad(): _ = model(*data) interim_inputs = self.layer.target_input if type(interim_inputs) is tuple: # this should always be true, but just to be safe self.interim_inputs_shape = [i.shape for i in interim_inputs] else: self.interim_inputs_shape = [interim_inputs.shape] self.target_handle.remove() del self.layer.target_input self.model = model.eval() self.multi_output = False self.num_outputs = 1 with torch.no_grad(): outputs = model(*data) # also get the device everything is running on self.device = outputs.device if outputs.shape[1] > 1: self.multi_output = True self.num_outputs = outputs.shape[1] self.expected_value = outputs.mean(0).cpu().numpy() def add_target_handle(self, layer): input_handle = layer.register_forward_hook(get_target_input) self.target_handle = input_handle def add_handles(self, model, forward_handle, backward_handle): """ Add handles to all non-container layers in the model. Recursively for non-container layers """ handles_list = [] model_children = list(model.children()) if model_children: for child in model_children: handles_list.extend(self.add_handles(child, forward_handle, backward_handle)) else: # leaves handles_list.append(model.register_forward_hook(forward_handle)) handles_list.append(model.register_backward_hook(backward_handle)) return handles_list def remove_attributes(self, model): """ Removes the x and y attributes which were added by the forward handles Recursively searches for non-container layers """ for child in model.children(): if 'nn.modules.container' in str(type(child)): self.remove_attributes(child) else: try: del child.x except AttributeError: pass try: del child.y except AttributeError: pass def gradient(self, idx, inputs): self.model.zero_grad() X = [x.requires_grad_() for x in inputs] outputs = self.model(*X) selected = [val for val in outputs[:, idx]] grads = [] if self.interim: interim_inputs = self.layer.target_input for idx, input in enumerate(interim_inputs): grad = torch.autograd.grad(selected, input, retain_graph=True if idx + 1 < len(interim_inputs) else None, allow_unused=True)[0] if grad is not None: grad = grad.cpu().numpy() else: grad = torch.zeros_like(X[idx]).cpu().numpy() grads.append(grad) del self.layer.target_input return grads, [i.detach().cpu().numpy() for i in interim_inputs] else: for idx, x in enumerate(X): grad = torch.autograd.grad(selected, x, retain_graph=True if idx + 1 < len(X) else None, allow_unused=True)[0] if grad is not None: grad = grad.cpu().numpy() else: grad = torch.zeros_like(X[idx]).cpu().numpy() grads.append(grad) return grads def shap_values(self, X, ranked_outputs=None, output_rank_order="max", check_additivity=False): # X ~ self.model_input # X_data ~ self.data # check if we have multiple inputs if not self.multi_input: assert type(X) != list, "Expected a single tensor model input!" X = [X] else: assert type(X) == list, "Expected a list of model inputs!" X = [x.detach().to(self.device) for x in X] if ranked_outputs is not None and self.multi_output: with torch.no_grad(): model_output_values = self.model(*X) # rank and determine the model outputs that we will explain if output_rank_order == "max": _, model_output_ranks = torch.sort(model_output_values, descending=True) elif output_rank_order == "min": _, model_output_ranks = torch.sort(model_output_values, descending=False) elif output_rank_order == "max_abs": _, model_output_ranks = torch.sort(torch.abs(model_output_values), descending=True) else: assert False, "output_rank_order must be max, min, or max_abs!" model_output_ranks = model_output_ranks[:, :ranked_outputs] else: model_output_ranks = (torch.ones((X[0].shape[0], self.num_outputs)).int() * torch.arange(0, self.num_outputs).int()) # add the gradient handles handles = self.add_handles(self.model, add_interim_values, deeplift_grad) if self.interim: self.add_target_handle(self.layer) # compute the attributions output_phis = [] for i in range(model_output_ranks.shape[1]): phis = [] if self.interim: for k in range(len(self.interim_inputs_shape)): phis.append(np.zeros((X[0].shape[0], ) + self.interim_inputs_shape[k][1: ])) else: for k in range(len(X)): phis.append(np.zeros(X[k].shape)) for j in range(X[0].shape[0]): # tile the inputs to line up with the background data samples tiled_X = [X[l][j:j + 1].repeat( (self.data[l].shape[0],) + tuple([1 for k in range(len(X[l].shape) - 1)])) for l in range(len(X))] joint_x = [torch.cat((tiled_X[l], self.data[l]), dim=0) for l in range(len(X))] # run attribution computation graph feature_ind = model_output_ranks[j, i] sample_phis = self.gradient(feature_ind, joint_x) # assign the attributions to the right part of the output arrays if self.interim: sample_phis, output = sample_phis x, data = [], [] for k in range(len(output)): x_temp, data_temp = np.split(output[k], 2) x.append(x_temp) data.append(data_temp) for l in range(len(self.interim_inputs_shape)): phis[l][j] = (sample_phis[l][self.data[l].shape[0]:] * (x[l] - data[l])).mean(0) else: for l in range(len(X)): phis[l][j] = (torch.from_numpy(sample_phis[l][self.data[l].shape[0]:]).to(self.device) * (X[l][j: j + 1] - self.data[l])).cpu().detach().numpy().mean(0) output_phis.append(phis[0] if not self.multi_input else phis) # cleanup; remove all gradient handles for handle in handles: handle.remove() self.remove_attributes(self.model) if self.interim: self.target_handle.remove() if not self.multi_output: return output_phis[0] elif ranked_outputs is not None: return output_phis, model_output_ranks else: return output_phis # Module hooks def deeplift_grad(module, grad_input, grad_output): """The backward hook which computes the deeplift gradient for an nn.Module """ # first, get the module type module_type = module.__class__.__name__ # first, check the module is supported if module_type in op_handler: if op_handler[module_type].__name__ not in ['passthrough', 'linear_1d']: return op_handler[module_type](module, grad_input, grad_output) else: print('Warning: unrecognized nn.Module: {}'.format(module_type)) return grad_input def add_interim_values(module, input, output): """The forward hook used to save interim tensors, detached from the graph. Used to calculate the multipliers """ try: del module.x except AttributeError: pass try: del module.y except AttributeError: pass module_type = module.__class__.__name__ if module_type in op_handler: func_name = op_handler[module_type].__name__ # First, check for cases where we don't need to save the x and y tensors if func_name == 'passthrough': pass else: # check only the 0th input varies for i in range(len(input)): if i != 0 and type(output) is tuple: assert input[i] == output[i], "Only the 0th input may vary!" # if a new method is added, it must be added here too. This ensures tensors # are only saved if necessary if func_name in ['maxpool', 'nonlinear_1d']: # only save tensors if necessary if type(input) is tuple: setattr(module, 'x', torch.nn.Parameter(input[0].detach())) else: setattr(module, 'x', torch.nn.Parameter(input.detach())) if type(output) is tuple: setattr(module, 'y', torch.nn.Parameter(output[0].detach())) else: setattr(module, 'y', torch.nn.Parameter(output.detach())) if module_type in failure_case_modules: input[0].register_hook(deeplift_tensor_grad) def get_target_input(module, input, output): """A forward hook which saves the tensor - attached to its graph. Used if we want to explain the interim outputs of a model """ try: del module.target_input except AttributeError: pass setattr(module, 'target_input', input) # From the documentation: "The current implementation will not have the presented behavior for # complex Module that perform many operations. In some failure cases, grad_input and grad_output # will only contain the gradients for a subset of the inputs and outputs. # The tensor hook below handles such failure cases (currently, MaxPool1d). In such cases, the deeplift # grad should still be computed, and then appended to the complex_model_gradients list. The tensor hook # will then retrieve the proper gradient from this list. failure_case_modules = ['MaxPool1d'] def deeplift_tensor_grad(grad): return_grad = complex_module_gradients[-1] del complex_module_gradients[-1] return return_grad complex_module_gradients = [] def passthrough(module, grad_input, grad_output): """No change made to gradients""" return None def maxpool(module, grad_input, grad_output): pool_to_unpool = { 'MaxPool1d': torch.nn.functional.max_unpool1d, 'MaxPool2d': torch.nn.functional.max_unpool2d, 'MaxPool3d': torch.nn.functional.max_unpool3d } pool_to_function = { 'MaxPool1d': torch.nn.functional.max_pool1d, 'MaxPool2d': torch.nn.functional.max_pool2d, 'MaxPool3d': torch.nn.functional.max_pool3d } delta_in = module.x[: int(module.x.shape[0] / 2)] - module.x[int(module.x.shape[0] / 2):] dup0 = [2] + [1 for i in delta_in.shape[1:]] # we also need to check if the output is a tuple y, ref_output = torch.chunk(module.y, 2) cross_max = torch.max(y, ref_output) diffs = torch.cat([cross_max - ref_output, y - cross_max], 0) # all of this just to unpool the outputs with torch.no_grad(): _, indices = pool_to_function[module.__class__.__name__]( module.x, module.kernel_size, module.stride, module.padding, module.dilation, module.ceil_mode, True) xmax_pos, rmax_pos = torch.chunk(pool_to_unpool[module.__class__.__name__]( grad_output[0] * diffs, indices, module.kernel_size, module.stride, module.padding, list(module.x.shape)), 2) org_input_shape = grad_input[0].shape # for the maxpool 1d grad_input = [None for _ in grad_input] grad_input[0] = torch.where(torch.abs(delta_in) < 1e-7, torch.zeros_like(delta_in), (xmax_pos + rmax_pos) / delta_in).repeat(dup0) if module.__class__.__name__ == 'MaxPool1d': complex_module_gradients.append(grad_input[0]) # the grad input that is returned doesn't matter, since it will immediately be # be overridden by the grad in the complex_module_gradient grad_input[0] = torch.ones(org_input_shape) return tuple(grad_input)<|fim▁hole|>def linear_1d(module, grad_input, grad_output): """No change made to gradients.""" return None def nonlinear_1d(module, grad_input, grad_output): delta_out = module.y[: int(module.y.shape[0] / 2)] - module.y[int(module.y.shape[0] / 2):] delta_in = module.x[: int(module.x.shape[0] / 2)] - module.x[int(module.x.shape[0] / 2):] dup0 = [2] + [1 for i in delta_in.shape[1:]] # handles numerical instabilities where delta_in is very small by # just taking the gradient in those cases grads = [None for _ in grad_input] grads[0] = torch.where(torch.abs(delta_in.repeat(dup0)) < 1e-6, grad_input[0], grad_output[0] * (delta_out / delta_in).repeat(dup0)) return tuple(grads) op_handler = {} # passthrough ops, where we make no change to the gradient op_handler['Dropout3d'] = passthrough op_handler['Dropout2d'] = passthrough op_handler['Dropout'] = passthrough op_handler['AlphaDropout'] = passthrough op_handler['Conv1d'] = linear_1d op_handler['Conv2d'] = linear_1d op_handler['Conv3d'] = linear_1d op_handler['ConvTranspose1d'] = linear_1d op_handler['ConvTranspose2d'] = linear_1d op_handler['ConvTranspose3d'] = linear_1d op_handler['Linear'] = linear_1d op_handler['AvgPool1d'] = linear_1d op_handler['AvgPool2d'] = linear_1d op_handler['AvgPool3d'] = linear_1d op_handler['AdaptiveAvgPool1d'] = linear_1d op_handler['AdaptiveAvgPool2d'] = linear_1d op_handler['AdaptiveAvgPool3d'] = linear_1d op_handler['BatchNorm1d'] = linear_1d op_handler['BatchNorm2d'] = linear_1d op_handler['BatchNorm3d'] = linear_1d op_handler['LeakyReLU'] = nonlinear_1d op_handler['ReLU'] = nonlinear_1d op_handler['ELU'] = nonlinear_1d op_handler['Sigmoid'] = nonlinear_1d op_handler["Tanh"] = nonlinear_1d op_handler["Softplus"] = nonlinear_1d op_handler['Softmax'] = nonlinear_1d op_handler['MaxPool1d'] = maxpool op_handler['MaxPool2d'] = maxpool op_handler['MaxPool3d'] = maxpool<|fim▁end|>
<|file_name|>coordinator.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import sys sys.path.append(".") from linear.common.coordinator import Coordinator import linear.twopc.config as config if len(sys.argv) != 3: raise RuntimeError("Invalid arguments. Call like this <name> <num_partitions>") coordinator = Coordinator(sys.argv[1], int(sys.argv[2]), config.COORDINATOR_PORT, config.COORDINATOR_PORT_INTERNAL) while coordinator.running: coordinator.update() coordinator.close()<|fim▁end|>
#! /usr/bin/python3
<|file_name|>example.module.ts<|end_file_name|><|fim▁begin|>/** * @file UI Example 页面 * @desc app/page/example/module * @author Surmon <https://github.com/surmon-china> */ import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { ModalModule } from 'ngx-bootstrap/modal'; import { BsDropdownModule } from 'ngx-bootstrap/dropdown'; import { PaginationModule } from 'ngx-bootstrap/pagination'; import { SaBaseModule } from '@app/sa-base.module'; import { RoutingModule } from './example.routing'; import { ExampleComponent } from './example.component'; import { ButtonsComponent } from './components/buttons'; import { GridComponent } from './components/grid'; import { IconsComponent } from './components/icons'; import { ModalsComponent } from './components/modals'; import { TypographyComponent } from './components/typography'; import { OtherComponent } from './components/other'; import { FlatButtonsComponent } from './components/buttons/components/flatButtons'; import { RaisedButtonsComponent } from './components/buttons/components/raisedButtons'; import { SizedButtonsComponent } from './components/buttons/components/sizedButtons'; import { DisabledButtonsComponent } from './components/buttons/components/disabledButtons'; import { IconButtonsComponent } from './components/buttons/components/iconButtons'; import { LargeButtonsComponent } from './components/buttons/components/largeButtons'; import { DropdownButtonsComponent } from './components/buttons/components/dropdownButtons'; import { GroupButtonsComponent } from './components/buttons/components/groupButtons'; import { FormInputsComponent } from './components/forms/inputs'; import { FormLayoutsComponent } from './components/forms/layouts'; import { StandardInputsComponent } from './components/forms/inputs/components/standardInputs'; import { ValidationInputsComponent } from './components/forms/inputs/components/validationInputs'; import { GroupInputsComponent } from './components/forms/inputs/components/groupInputs'; import { CheckboxInputsComponent } from './components/forms/inputs/components/checkboxInputs'; import { SelectInputsComponent } from './components/forms/inputs/components/selectInputs'; import { InlineFormComponent } from './components/forms/layouts/components/inlineForm'; import { BlockFormComponent } from './components/forms/layouts/components/blockForm'; import { HorizontalFormComponent } from './components/forms/layouts/components/horizontalForm'; import { BasicFormComponent } from './components/forms/layouts/components/basicForm'; import { WithoutLabelsFormComponent } from './components/forms/layouts/components/withoutLabelsForm'; import { TableComponent } from './components/table'; import { ResponsiveTableComponent } from './components/table/components/responsiveTable'; import { StripedTableComponent } from './components/table/components/stripedTable';<|fim▁hole|>import { CondensedTableComponent } from './components/table/components/condensedTable'; import { ContextualTableComponent } from './components/table/components/contextualTable'; import { TableService } from './components/table/table.service'; @NgModule({ imports: [ CommonModule, FormsModule, SaBaseModule, RoutingModule, PaginationModule.forRoot(), BsDropdownModule.forRoot(), ModalModule.forRoot(), ], declarations: [ ButtonsComponent, GridComponent, IconsComponent, ModalsComponent, TypographyComponent, ExampleComponent, FlatButtonsComponent, RaisedButtonsComponent, SizedButtonsComponent, DisabledButtonsComponent, IconButtonsComponent, LargeButtonsComponent, DropdownButtonsComponent, GroupButtonsComponent, OtherComponent, FormInputsComponent, FormLayoutsComponent, StandardInputsComponent, ValidationInputsComponent, GroupInputsComponent, CheckboxInputsComponent, SelectInputsComponent, InlineFormComponent, BlockFormComponent, HorizontalFormComponent, BasicFormComponent, WithoutLabelsFormComponent, TableComponent, ResponsiveTableComponent, StripedTableComponent, BorderedTableComponent, HoverTableComponent, CondensedTableComponent, ContextualTableComponent ], providers: [TableService], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class ExampleModule {}<|fim▁end|>
import { BorderedTableComponent } from './components/table/components/borderedTable'; import { HoverTableComponent } from './components/table/components/hoverTable';
<|file_name|>SampleApplication.java<|end_file_name|><|fim▁begin|>package com.sampleapp.base; import android.app.Application; <|fim▁hole|>import io.fabric.sdk.android.Fabric; import timber.log.Timber; /** * Created by saveen_dhiman on 05-November-16. * Initialization of required libraries */ public class SampleApplication extends Application { private AppComponent mAppComponent; @Override public void onCreate() { super.onCreate(); Fabric.with(this, new Crashlytics()); //create component mAppComponent = DaggerAppComponent.builder() .utilsModule(new UtilsModule(this)).build(); //configure timber for logging if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } } public AppComponent getAppComponent() { return mAppComponent; } }<|fim▁end|>
import com.crashlytics.android.Crashlytics; import com.sampleapp.BuildConfig; import com.sampleapp.utils.UtilsModule;
<|file_name|>types.rs<|end_file_name|><|fim▁begin|>use read::Sexp; use std::rc::Rc; use std::cell::{RefCell, Ref}; use std::collections::HashMap; use itertools::*; #[derive(PartialEq, Clone, Debug)] pub struct TRef(Rc<RefCell<Option<Type>>>); impl TRef { fn new() -> Self { TRef(Rc::new(RefCell::new(None))) } fn get(&self) -> Ref<Option<Type>> { self.0.borrow() } fn set(&self, v: Type) { *self.0.borrow_mut() = Some(v); } } #[derive(PartialEq, Clone, Debug)] pub enum Type { Unit, Bool, Int, Sexp, Fun(Vec<Type>, Box<Type>), Var(TRef), } pub fn gentyp() -> Type { Type::Var(TRef::new()) } #[derive(Debug, Clone)] pub enum Ast { Unit, Bool(bool), Int(i64), Quote(Sexp), Let(Vec<(String, Type, Ast)>, Vec<Ast>), Var(String), App(Box<Ast>, Vec<Ast>), IfElse(Box<Ast>, Box<Ast>, Box<Ast>), If(Box<Ast>, Box<Ast>), Add(Vec<Ast>), Fn(Type, Vec<(String, Type)>, Vec<Ast>), } fn deref_typ(t: Type) -> Type { match t { Type::Fun(t1s, t2) => { Type::Fun(t1s.into_iter().map(deref_typ).collect(), Box::new(deref_typ(*t2))) } Type::Var(r) => { let o = (*r.get()).clone(); match o { Some(t) => { let tp = deref_typ(t); r.set(tp.clone()); tp } _ => Type::Var(r), //panic!("Unable to infer type"), } } t => t, } } pub fn deref_term(e: Ast) -> Ast { use self::Ast::*; fn map(e: Box<Ast>) -> Box<Ast> { // could use a map-in-place version Box::new(deref_term(*e)) } match e { Add(es) => Add(es.into_iter().map(deref_term).collect()), IfElse(e1, e2, e3) => IfElse(map(e1), map(e2), map(e3)), Let(params, body) => { let params = params .into_iter() .map(|(sym, ty, e)| (sym, deref_typ(ty), deref_term(e))) .collect(); Let(params, body.into_iter().map(deref_term).collect()) } Fn(ty, params, body) => { Fn(deref_typ(ty), params .into_iter() .map(|(sym, ty)| (sym, deref_typ(ty))) .collect(), body.into_iter().map(deref_term).collect()) } App(e, es) => App(map(e), es.into_iter().map(deref_term).collect()), e => e, } } fn occur(r1: &TRef, t: &Type) -> bool { match *t { Type::Fun(ref t2s, ref t2) => t2s.into_iter().any(|t2| occur(r1, t2)) || occur(r1, &*t2), Type::Var(ref r2) => { if r1.0.borrow().is_some() && r2.0.borrow().is_some() && r1 == r2 { true } else if let None = *r2.get() { false } else if let Some(ref t2) = *r2.get() { occur(r1, t2) } else { unreachable!() } } _ => false, } } fn unify(t1: &Type, t2: &Type) -> Result<(), (Type, Type)> { match (t1, t2) { (&Type::Unit, &Type::Unit) | (&Type::Bool, &Type::Bool) | (&Type::Int, &Type::Int) => Ok(()), (&Type::Fun(ref t1s, ref t1p), &Type::Fun(ref t2s, ref t2p)) => { assert_eq!(t1s.len(), t2s.len()); for (t1, t2) in zip(t1s, t2s) { unify(t1, t2)?; } unify(t1p, t2p) } (&Type::Var(ref r1), &Type::Var(ref r2)) if r1 == r2 => Ok(()), (&Type::Var(ref r1), _) if r1.get().is_some() => { let t1p = r1.get().clone().unwrap(); unify(&t1p, t2) } (_, &Type::Var(ref r2)) if r2.get().is_some() => { let t2p = r2.get().clone().unwrap(); unify(t1, &t2p) } (&Type::Var(ref r1), _) if r1.get().is_none() => { if occur(r1, t2) { return Err((t1.clone(), t2.clone())); } r1.set(t2.clone()); Ok(()) } (_, &Type::Var(ref r2)) if r2.get().is_none() => { if occur(r2, t1) { return Err((t1.clone(), t2.clone())); } r2.set(t1.clone()); Ok(()) } _ => Err((t1.clone(), t2.clone())), } } #[derive(Default)] pub struct InferenceEnv { pub vars: HashMap<String, Type>, } pub fn g(env: &mut InferenceEnv, e: &Ast) -> Type { use self::Ast::*; match *e { Unit => Type::Unit, Bool(_) => Type::Bool, Int(_) => Type::Int,<|fim▁hole|> } Type::Int } Let(ref params, ref e2) => { scope! { env.vars => env.vars.clone(); for &(ref x, ref t, ref e1) in params { unify(t, &g(env, e1)).unwrap(); env.vars.insert(x.clone(), t.clone()); } let (last, rest) = e2.split_last().unwrap(); for e in rest { g(env, e); } g(env, last) } } Var(ref x) => { if let Some(x) = env.vars.get(x).cloned() { x } else { panic!("Unknown sym: {:?}", x); } } App(ref e, ref es) => { let t = gentyp(); let tf = Type::Fun(es.into_iter().map(|e| g(env, e)).collect(), Box::new(t.clone())); unify(&g(env, e), &tf).unwrap(); t } IfElse(ref e1, ref e2, ref e3) => { unify(&g(env, e1), &Type::Bool).unwrap(); let t2 = g(env, e2); let t3 = g(env, e3); unify(&t2, &t3).unwrap(); t2 } If(ref cond, ref then) => { unify(&g(env, cond), &Type::Bool).unwrap(); unify(&g(env, then), &Type::Unit).unwrap(); Type::Unit } Fn(ref ty, ref params, ref body) => { scope! { env.vars => env.vars.clone(); env.vars.extend(params.clone()); let param_types = params.into_iter().map(|&(_, ref ty)| ty.clone()).collect(); let ret_type = { let (last, rest) = body.split_last().unwrap(); for e in rest { g(env, e); } g(env, last) }; let fn_ty = Type::Fun(param_types, Box::new(ret_type)); unify(ty, &fn_ty).unwrap(); fn_ty } } } } pub fn f(env: &mut InferenceEnv, e: Ast) -> Ast { g(env, &e); deref_term(e) }<|fim▁end|>
Quote(ref ast) => Type::Sexp, Add(ref es) => { for e in es { unify(&Type::Int, &g(env, e)).unwrap();
<|file_name|>app.py<|end_file_name|><|fim▁begin|>from database import init_db from flask import Flask from flask_graphql import GraphQLView from schema import schema app = Flask(__name__) app.debug = True default_query = ''' { allEmployees { edges { node { id, name, department { id, name }, role { id,<|fim▁hole|> name } } } } }'''.strip() app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True)) if __name__ == '__main__': init_db() app.run()<|fim▁end|>
<|file_name|>extends-has-child.js<|end_file_name|><|fim▁begin|>'use strict'; var q = require('q'); var announcer = require('pd-api-announcer'); var methodNomen = require('./nomenclt'); var nm = require('./parenthood-nomenclt'); module.exports = function (Parent, Child) { var hasChildName = methodNomen.ifOwns(Child); Parent[hasChildName] = function (parentSid, childSid) { return q.Promise(function (resolve, reject) { var cId = childSid + ''; var redisKey = nm.childOf(Child.modelName(), Parent.modelName(), parentSid); Child.redis.zsetExists(redisKey, cId).then(function (reply) { resolve(reply); }).fail(function (err) { if (announcer.error(err).isSysFor('zsetItem', 'gone')) { throw announcer.error.sys(Child.modelName(), 'gone'); } }).fail(function (err) { reject(err); });<|fim▁hole|> }; };<|fim▁end|>
});
<|file_name|>improv_rnn_create_dataset.py<|end_file_name|><|fim▁begin|># Copyright 2022 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create a dataset of SequenceExamples from NoteSequence protos. This script will extract melodies and chords from NoteSequence protos and save them to TensorFlow's SequenceExample protos for input to the improv RNN models. """ import os from magenta.models.improv_rnn import improv_rnn_config_flags from magenta.models.improv_rnn import improv_rnn_pipeline from magenta.pipelines import pipeline import tensorflow.compat.v1 as tf flags = tf.app.flags FLAGS = tf.app.flags.FLAGS flags.DEFINE_string( 'input', None, 'TFRecord to read NoteSequence protos from.') flags.DEFINE_string( 'output_dir', None, 'Directory to write training and eval TFRecord files. The TFRecord files ' 'are populated with SequenceExample protos.') flags.DEFINE_float( 'eval_ratio', 0.1, 'Fraction of input to set aside for eval set. Partition is randomly ' 'selected.') flags.DEFINE_string(<|fim▁hole|> def main(unused_argv): tf.logging.set_verbosity(FLAGS.log) config = improv_rnn_config_flags.config_from_flags() pipeline_instance = improv_rnn_pipeline.get_pipeline( config, FLAGS.eval_ratio) FLAGS.input = os.path.expanduser(FLAGS.input) FLAGS.output_dir = os.path.expanduser(FLAGS.output_dir) pipeline.run_pipeline_serial( pipeline_instance, pipeline.tf_record_iterator(FLAGS.input, pipeline_instance.input_type), FLAGS.output_dir) def console_entry_point(): tf.disable_v2_behavior() tf.app.run(main) if __name__ == '__main__': console_entry_point()<|fim▁end|>
'log', 'INFO', 'The threshold for what messages will be logged DEBUG, INFO, WARN, ERROR, ' 'or FATAL.')
<|file_name|>test_convert.py<|end_file_name|><|fim▁begin|># # Copyright © 2012–2022 Michal Čihař <[email protected]> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # """File format specific behavior.""" from weblate.formats.convert import ( HTMLFormat, IDMLFormat, OpenDocumentFormat, PlainTextFormat, WindowsRCFormat, ) from weblate.formats.helpers import BytesIOMode from weblate.formats.tests.test_formats import AutoFormatTest from weblate.trans.tests.utils import get_test_file IDML_FILE = get_test_file("en.idml") HTML_FILE = get_test_file("cs.html") OPENDOCUMENT_FILE = get_test_file("cs.odt") TEST_RC = get_test_file("cs-CZ.rc") TEST_TXT = get_test_file("cs.txt") class ConvertFormatTest(AutoFormatTest): NEW_UNIT_MATCH = None EXPECTED_FLAGS = "" def parse_file(self, filename): return self.FORMAT(filename, template_store=self.FORMAT(filename)) class HTMLFormatTest(ConvertFormatTest): FORMAT = HTMLFormat FILE = HTML_FILE MIME = "text/html" EXT = "html" COUNT = 5 MASK = "*/translations.html" EXPECTED_PATH = "cs_CZ/translations.html" FIND_CONTEXT = "+html.body.p:5-1" FIND_MATCH = "Orangutan has five bananas." MATCH = b"<body>" NEW_UNIT_MATCH = None BASE = HTML_FILE EXPECTED_FLAGS = "" EDIT_OFFSET = 1 class OpenDocumentFormatTest(ConvertFormatTest): FORMAT = OpenDocumentFormat FILE = OPENDOCUMENT_FILE MIME = "application/vnd.oasis.opendocument.text" EXT = "odt" COUNT = 4 MASK = "*/translations.odt" EXPECTED_PATH = "cs_CZ/translations.odt" FIND_CONTEXT = ( "odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]" ) FIND_MATCH = "Orangutan has five bananas." MATCH = b"PK" NEW_UNIT_MATCH = None BASE = OPENDOCUMENT_FILE EXPECTED_FLAGS = "" EDIT_OFFSET = 1 @staticmethod def extract_document(content): return bytes( OpenDocumentFormat.convertfile(BytesIOMode("test.odt", content), None) ).decode() def assert_same(self, newdata, testdata): self.assertEqual( self.extract_document(newdata), self.extract_document(testdata), ) class IDMLFormatTest(ConvertFormatTest): FORMAT = IDMLFormat FILE = IDML_FILE MIME = "application/octet-stream" EXT = "idml" COUNT = 6 MASK = "*/translations.idml" EXPECTED_PATH = "cs_CZ/translations.idml" FIND_CONTEXT = (<|fim▁hole|> ) FIND_MATCH = """<g id="0"><g id="1">THE HEADLINE HERE</g></g>""" MATCH = b"PK" NEW_UNIT_MATCH = None BASE = IDML_FILE EXPECTED_FLAGS = "" EDIT_OFFSET = 1 @staticmethod def extract_document(content): return bytes( IDMLFormat.convertfile(BytesIOMode("test.idml", content), None) ).decode() def assert_same(self, newdata, testdata): self.assertEqual( self.extract_document(newdata), self.extract_document(testdata), ) class WindowsRCFormatTest(ConvertFormatTest): FORMAT = WindowsRCFormat FILE = TEST_RC BASE = TEST_RC MIME = "text/plain" EXT = "rc" COUNT = 5 MASK = "rc/*.rc" EXPECTED_PATH = "rc/cs-CZ.rc" MATCH = "STRINGTABLE" FIND_CONTEXT = "STRINGTABLE.IDS_MSG1" FIND_MATCH = "Hello, world!\n" EDIT_OFFSET = 1 class PlainTextFormatTest(ConvertFormatTest): FORMAT = PlainTextFormat FILE = TEST_TXT BASE = TEST_TXT MIME = "text/plain" EXT = "txt" COUNT = 5 MASK = "txt/*.txt" EXPECTED_PATH = "txt/cs_CZ.txt" MATCH = "Hello" FIND_CONTEXT = "cs.txt:2" FIND_MATCH = "Hello, world!" EDIT_OFFSET = 1<|fim▁end|>
"idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]" "Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"
<|file_name|>FileProcessing.py<|end_file_name|><|fim▁begin|># encoding=utf-8 import codecs import sys from src.view.FileProcessingOutput import FileProcessingOutput class FileProcessing(): def __init__(self): self.fileProcessingOutput = FileProcessingOutput() def read_input_file(self, file_path, file_type): ''' Lectura de archivo y procesamiento de archivos :param file_path: :return: file_lines ''' file_lines = [] line_counter = 0 self.fileProcessingOutput.print_reading_file(file_path) try: with codecs.open(file_path, encoding='utf8') as f: for l in f: line_counter += 1 line = l.strip().encode("utf-8") if line != "": if self.check_line_format(line, file_type, line_counter): file_lines.append(line) self.fileProcessingOutput.print_input_file_lines(len(file_lines)) except: self.fileProcessingOutput.print_error_reading_file() sys.exit() if not file_lines:<|fim▁hole|> self.fileProcessingOutput.print_error_reading_file() sys.exit() return file_lines def check_line_format(self, line, file_type, line_counter): ''' Verifica que la linea se ajuste al formato de proceso, y al tipo de archivo ingresado :param line: Linea a procesar :param file_type: Tipo de archivo :param line_counter: Contador de linea, para notificar en caso de error. :return: Retorna si la linea cumple o no con el formato establecido. ''' if file_type == 0: return True elif file_type == 1: if not ':' in line: self.fileProcessingOutput.print_error_delimiter_not_found(line_counter) sys.exit() return True elif file_type == 2: if not ':' in line: self.fileProcessingOutput.print_error_delimiter_not_found(line_counter) sys.exit() _splitted_line = line.split(':') if len(_splitted_line) < 3: self.fileProcessingOutput.print_error_format_not_correct(line_counter) sys.exit() return True<|fim▁end|>
<|file_name|>api-call-wikipedia.js<|end_file_name|><|fim▁begin|>define([ "knockout", // mappoint needs to be here first for addEventListener "../modules/mappoint", ], function (ko) { // create result object var result = { cityname : ko.observable(''), citydata : ko.observableArray([]) }; // subscribe to custom event window.addEventListener("getTitle", getWikipedia, false); // use for jsonp call to wikipedia<|fim▁hole|> // call function function getWikipedia (e) { // listen to custom event city = e.detail.title; // store data object var data = ''; // if city equals old value do nothing if (city === oldValue) { // do something when element is clicked twice console.log("you have allready clicked this " + city + " marker"); } // if city contains new value else { // check if city is in LocalStorage if (localStorage[city]) { // get localstorage item and store it data = JSON.parse(localStorage[city]); // populate observables result.citydata([data]); result.cityname(city); } else { // if no localstorage, sent request sentJSONPRequest(city); } // set city to old value oldValue = city; } } // found jsonp solution for wikipedia after trying it many times with xmlhttprequest and cors function jsonp(url, callback) { var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random()); // create callback and delete it window[callbackName] = function(data) { delete window[callbackName]; document.body.removeChild(script); callback(data); }; // add script var script = document.createElement('script'); script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName; // simple error handling (works in firefox and chrome) window.onerror = function (errorMsg, url, lineNumber) { alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber); }; document.body.appendChild(script); } // set api url var sentJSONPRequest = function (city) { // set url for jsonp request var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=' + city + '&format=json&callback=?'; // call jsonp request jsonp(url, function(data) { // fill result with wikipedia object result.citydata([data[1]]); // use change in city for observable result.cityname(data[0]); // if localstorage support if (window.localStorage) { // store city object with data array localStorage[data[0]] = JSON.stringify(data[1]); } }); }; return result; });<|fim▁end|>
var city ='', // oldValue oldValue = '';
<|file_name|>button.view.js<|end_file_name|><|fim▁begin|>import React, { Component, PropTypes } from 'react' import cx from 'classnames'<|fim▁hole|>import './button.view.styl' export class Button extends Component { static propTypes = { className: PropTypes.string, children: PropTypes.oneOfType([ PropTypes.element, PropTypes.string ]), icon: PropTypes.string, type: PropTypes.oneOf(['primary', 'text', 'danger', 'normal']), htmlType: PropTypes.oneOf(['submit', 'button', 'reset']), size: PropTypes.oneOf(['small', 'normal', 'large']), block: PropTypes.bool, loading: PropTypes.bool, disabled: PropTypes.bool, ghost: PropTypes.bool, onClick: PropTypes.func } static defaultProps = { type: 'primary', size: 'normal', onClick: () => {} } getRootClassNames () { const { className, type, size, block, loading, disabled, ghost } = this.props return cx( 'button', `button${capitalize(type)}`, `size${capitalize(size)}`, { isBlock: block }, { isGhost: ghost }, { isLoading: loading }, { isDisabled: disabled }, className ) } handleClick = (e) => { const { loading, disabled, onClick } = this.props if (loading || disabled) { e.preventDefault() return null } if (onClick) { onClick(e) } } render () { const { icon, htmlType, // loading, children } = this.props const iconName = icon // @OLD: loading ? 'loading' : icon const iconNode = iconName ? <Icon name={iconName} /> : null return ( <button className={this.getRootClassNames()} onClick={this.handleClick} type={htmlType || 'button'} > {iconNode}{children} </button> ) } }<|fim▁end|>
import { Icon } from '../icon' import { capitalize } from 'utils/string'
<|file_name|>skills.js<|end_file_name|><|fim▁begin|>import React from 'react'; import './skills.scss'; export default () => { return ( <section className="skills-section"> <svg className="bigTriangleColor separator-skills" width="100%" height="100" viewBox="0 0 100 102" preserveAspectRatio="none"> <path d="M0 0 L0 100 L70 0 L100 100 L100 0 Z" /> </svg> <h2 className="skills-header">Skills</h2> <p className="skills tlt"><|fim▁hole|> View My <i className="fa fa-github skills-github"></i><a className="skills-btn-a" href="https://www.github.com/musicbender" target="_blank"></a> </button> </section> ); }<|fim▁end|>
Javascript/ES6 React Redux Node Express MongoDB GraphQL REST Next.js Mocha Jest JSS PostCSS SCSS LESS AWS nginx jQuery Webpack Rollup UI/Design </p> <button className="button button--wayra button--inverted skills-btn">
<|file_name|>media_object.py<|end_file_name|><|fim▁begin|>""" TODO: Add docstring """ import re import pexpect class MediaObject(object): """Represents an encodable object""" def __init__(self, input_filename, output_filename): self.input_filename = input_filename self.output_filename = output_filename self.media_duration = self.get_media_duration() # INFO: All other media information could potentially be put here too def get_media_duration(self): """ Spawns an avprobe process to get the media duration. Spawns an avprobe process and saves the output to a list, then uses regex to find the duration of the media and return it as an integer. """ info_process = pexpect.spawn("/usr/bin/avprobe " + self.input_filename) subprocess_output = info_process.readlines() info_process.close # Non-greedy match on characters 'Duration: ' followed by # number in form 00:00:00:00 regex_group = re.compile(".*?Duration: .*?(\\d+):(\\d+):(\\d+).(\\d+)", re.IGNORECASE | re.DOTALL) # Exits as soon as duration is found<|fim▁hole|> for line in subprocess_output: regex_match = regex_group.search(line) if regex_match: # Return the total duration in seconds return ((int(regex_match.group(1)) * 3600) + # Hours (int(regex_match.group(2)) * 60) + # Minutes int(regex_match.group(3)) + # Seconds # Round milliseconds to nearest second 1 if int(regex_match.group(3)) > 50 else 0) # Not found so it's possible the process terminated early or an update # broke the regex. Unlikely but we must return something just in case. return -1<|fim▁end|>
# PERF: Perform some tests to find the min number of lines # certain not to contain the duration, then operate on a slice # not containing those lines
<|file_name|>Portal.js<|end_file_name|><|fim▁begin|>import React from 'react'; import ReactDOM from 'react-dom'; import componentOrElement from 'react-prop-types/lib/componentOrElement'; import ownerDocument from './utils/ownerDocument'; import getContainer from './utils/getContainer';<|fim▁hole|> * The children of `<Portal/>` component will be appended to the `container` specified. */ let Portal = React.createClass({ displayName: 'Portal', propTypes: { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: React.PropTypes.oneOfType([ componentOrElement, React.PropTypes.func ]), /** * Classname to use for the Portal Component */ className: React.PropTypes.string }, componentDidMount() { this._renderOverlay(); }, componentDidUpdate() { this._renderOverlay(); }, componentWillReceiveProps(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this._portalContainerNode.removeChild(this._overlayTarget); this._portalContainerNode = getContainer(nextProps.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); if (this.props.className) { this._overlayTarget.className = this.props.className; } this._portalContainerNode = getContainer(this.props.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, _unmountOverlayTarget() { if (this._overlayTarget) { this._portalContainerNode.removeChild(this._overlayTarget); this._overlayTarget = null; } this._portalContainerNode = null; }, _renderOverlay() { let overlay = !this.props.children ? null : React.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = ReactDOM.unstable_renderSubtreeIntoContainer( this, overlay, this._overlayTarget ); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay() { if (this._overlayTarget) { ReactDOM.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render() { return null; }, getMountNode(){ return this._overlayTarget; }, getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { return ReactDOM.findDOMNode(this._overlayInstance); } return null; } }); export default Portal;<|fim▁end|>
/** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`.
<|file_name|>system.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/system.h> #ifdef ENABLE_EXTERNAL_SIGNER #if defined(WIN32) && !defined(__kernel_entry) // A workaround for boost 1.71 incompatibility with mingw-w64 compiler. // For details see https://github.com/bitcoin/bitcoin/pull/22348. #define __kernel_entry #endif #include <boost/process.hpp> #endif // ENABLE_EXTERNAL_SIGNER #include <chainparamsbase.h> #include <sync.h> #include <util/check.h> #include <util/getuniquepath.h> #include <util/strencodings.h> #include <util/string.h> #include <util/translation.h> #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) #include <pthread.h> #include <pthread_np.h> #endif #ifndef WIN32 // for posix_fallocate, in configure.ac we check if it is present after this #ifdef __linux__ #ifdef _POSIX_C_SOURCE #undef _POSIX_C_SOURCE #endif #define _POSIX_C_SOURCE 200112L #endif // __linux__ #include <algorithm> #include <cassert> #include <fcntl.h> #include <sched.h> #include <sys/resource.h> #include <sys/stat.h> #else #ifdef _MSC_VER #pragma warning(disable:4786) #pragma warning(disable:4804) #pragma warning(disable:4805) #pragma warning(disable:4717) #endif #ifndef NOMINMAX #define NOMINMAX #endif #include <codecvt> #include <io.h> /* for _commit */ #include <shellapi.h> #include <shlobj.h> #endif #ifdef HAVE_MALLOPT_ARENA_MAX #include <malloc.h> #endif #include <boost/algorithm/string/replace.hpp> #include <thread> #include <typeinfo> #include <univalue.h> // Application startup time (used for uptime calculation) const int64_t nStartupTime = GetTime(); const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf"; const char * const BITCOIN_SETTINGS_FILENAME = "settings.json"; ArgsManager gArgs; /** Mutex to protect dir_locks. */ static Mutex cs_dir_locks; /** A map that contains all the currently held directory locks. After * successful locking, these will be held here until the global destructor * cleans them up and thus automatically unlocks them, or ReleaseDirectoryLocks * is called. */ static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks GUARDED_BY(cs_dir_locks); bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only) { LOCK(cs_dir_locks); fs::path pathLockFile = directory / lockfile_name; // If a lock for this directory already exists in the map, don't try to re-lock it if (dir_locks.count(pathLockFile.string())) { return true; } // Create empty lock file if it doesn't exist. FILE* file = fsbridge::fopen(pathLockFile, "a"); if (file) fclose(file); auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile); if (!lock->TryLock()) { return error("Error while attempting to lock directory %s: %s", directory.string(), lock->GetReason()); } if (!probe_only) { // Lock successful and we're not just probing, put it into the map dir_locks.emplace(pathLockFile.string(), std::move(lock)); } return true; } void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name) { LOCK(cs_dir_locks); dir_locks.erase((directory / lockfile_name).string()); } void ReleaseDirectoryLocks() { LOCK(cs_dir_locks); dir_locks.clear(); } bool DirIsWritable(const fs::path& directory) { fs::path tmpFile = GetUniquePath(directory); FILE* file = fsbridge::fopen(tmpFile, "a"); if (!file) return false; fclose(file); remove(tmpFile); return true; } bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes) { constexpr uint64_t min_disk_space = 52428800; // 50 MiB uint64_t free_bytes_available = fs::space(dir).available; return free_bytes_available >= min_disk_space + additional_bytes; } std::streampos GetFileSize(const char* path, std::streamsize max) { std::ifstream file(path, std::ios::binary); file.ignore(max); return file.gcount(); } /** * Interpret a string argument as a boolean. * * The definition of LocaleIndependentAtoi<int>() requires that non-numeric string values * like "foo", return 0. This means that if a user unintentionally supplies a * non-integer argument here, the return value is always false. This means that * -foo=false does what the user probably expects, but -foo=true is well defined * but does not do what they probably expected. * * The return value of LocaleIndependentAtoi<int>(...) is zero when given input not * representable as an int. * * For a more extensive discussion of this topic (and a wide range of opinions * on the Right Way to change this code), see PR12713. */ static bool InterpretBool(const std::string& strValue) { if (strValue.empty()) return true; return (LocaleIndependentAtoi<int>(strValue) != 0); } static std::string SettingName(const std::string& arg) { return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg; } /** * Interpret -nofoo as if the user supplied -foo=0. * * This method also tracks when the -no form was supplied, and if so, * checks whether there was a double-negative (-nofoo=0 -> -foo=1). * * If there was not a double negative, it removes the "no" from the key * and returns false. * * If there was a double negative, it removes "no" from the key, and * returns true. * * If there was no "no", it returns the string value untouched. * * Where an option was negated can be later checked using the * IsArgNegated() method. One use case for this is to have a way to disable * options that are not normally boolean (e.g. using -nodebuglogfile to request * that debug log output is not sent to any file at all). */ static util::SettingsValue InterpretOption(std::string& section, std::string& key, const std::string& value) { // Split section name from key name for keys like "testnet.foo" or "regtest.bar" size_t option_index = key.find('.'); if (option_index != std::string::npos) { section = key.substr(0, option_index); key.erase(0, option_index + 1); } if (key.substr(0, 2) == "no") { key.erase(0, 2); // Double negatives like -nofoo=0 are supported (but discouraged) if (!InterpretBool(value)) { LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key, value); return true; } return false; } return value; } /** * Check settings value validity according to flags. * * TODO: Add more meaningful error checks here in the future * See "here's how the flags are meant to behave" in * https://github.com/bitcoin/bitcoin/pull/16097#issuecomment-514627823 */ static bool CheckValid(const std::string& key, const util::SettingsValue& val, unsigned int flags, std::string& error) { if (val.isBool() && !(flags & ArgsManager::ALLOW_BOOL)) { error = strprintf("Negating of -%s is meaningless and therefore forbidden", key); return false; } return true; } namespace { fs::path StripRedundantLastElementsOfPath(const fs::path& path) { auto result = path; while (result.filename().string() == ".") { result = result.parent_path(); } assert(fs::equivalent(result, path)); return result; } } // namespace // Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to // #include class definitions for all members. // For example, m_settings has an internal dependency on univalue. ArgsManager::ArgsManager() {} ArgsManager::~ArgsManager() {} const std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const { std::set<std::string> unsuitables; LOCK(cs_args); // if there's no section selected, don't worry if (m_network.empty()) return std::set<std::string> {}; // if it's okay to use the default section for this network, don't worry if (m_network == CBaseChainParams::MAIN) return std::set<std::string> {}; for (const auto& arg : m_network_only_args) { if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) { unsuitables.insert(arg); } } return unsuitables; } const std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const { // Section names to be recognized in the config file. static const std::set<std::string> available_sections{ CBaseChainParams::REGTEST, CBaseChainParams::SIGNET, CBaseChainParams::TESTNET, CBaseChainParams::MAIN }; LOCK(cs_args); std::list<SectionInfo> unrecognized = m_config_sections; unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); }); return unrecognized; } void ArgsManager::SelectConfigNetwork(const std::string& network) { LOCK(cs_args); m_network = network; } bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error) { LOCK(cs_args); m_settings.command_line_options.clear(); for (int i = 1; i < argc; i++) { std::string key(argv[i]); #ifdef MAC_OSX // At the first time when a user gets the "App downloaded from the // internet" warning, and clicks the Open button, macOS passes // a unique process serial number (PSN) as -psn_... command-line // argument, which we filter out. if (key.substr(0, 5) == "-psn_") continue; #endif if (key == "-") break; //bitcoin-tx using stdin std::string val; size_t is_index = key.find('='); if (is_index != std::string::npos) { val = key.substr(is_index + 1); key.erase(is_index); } #ifdef WIN32 key = ToLower(key); if (key[0] == '/') key[0] = '-'; #endif if (key[0] != '-') { if (!m_accept_any_command && m_command.empty()) { // The first non-dash arg is a registered command std::optional<unsigned int> flags = GetArgFlags(key); if (!flags || !(*flags & ArgsManager::COMMAND)) { error = strprintf("Invalid command '%s'", argv[i]); return false; } } m_command.push_back(key); while (++i < argc) { // The remaining args are command args m_command.push_back(argv[i]); } break; } // Transform --foo to -foo if (key.length() > 1 && key[1] == '-') key.erase(0, 1); // Transform -foo to foo key.erase(0, 1); std::string section; util::SettingsValue value = InterpretOption(section, key, val); std::optional<unsigned int> flags = GetArgFlags('-' + key); // Unknown command line options and command line options with dot // characters (which are returned from InterpretOption with nonempty // section strings) are not valid. if (!flags || !section.empty()) { error = strprintf("Invalid parameter %s", argv[i]); return false; } if (!CheckValid(key, value, *flags, error)) return false; m_settings.command_line_options[key].push_back(value); } // we do not allow -includeconf from command line, only -noincludeconf if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) { const util::SettingsSpan values{*includes}; // Range may be empty if -noincludeconf was passed if (!values.empty()) { error = "-includeconf cannot be used from commandline; -includeconf=" + values.begin()->write(); return false; // pick first value as example } } return true; } std::optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const { LOCK(cs_args); for (const auto& arg_map : m_available_args) { const auto search = arg_map.second.find(name); if (search != arg_map.second.end()) { return search->second.m_flags; } } return std::nullopt; } const fs::path& ArgsManager::GetBlocksDirPath() const { LOCK(cs_args); fs::path& path = m_cached_blocks_path; // Cache the path to avoid calling fs::create_directories on every call of // this function if (!path.empty()) return path; if (IsArgSet("-blocksdir")) { path = fs::system_complete(GetArg("-blocksdir", "")); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDataDirBase(); } path /= BaseParams().DataDir(); path /= "blocks"; fs::create_directories(path); path = StripRedundantLastElementsOfPath(path); return path; } const fs::path& ArgsManager::GetDataDir(bool net_specific) const { LOCK(cs_args); fs::path& path = net_specific ? m_cached_network_datadir_path : m_cached_datadir_path; // Cache the path to avoid calling fs::create_directories on every call of // this function if (!path.empty()) return path; std::string datadir = GetArg("-datadir", ""); if (!datadir.empty()) { path = fs::system_complete(datadir); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDefaultDataDir(); } if (net_specific) path /= BaseParams().DataDir(); if (fs::create_directories(path)) { // This is the first run, create wallets subdirectory too fs::create_directories(path / "wallets"); } path = StripRedundantLastElementsOfPath(path); return path; } void ArgsManager::ClearPathCache() { LOCK(cs_args); m_cached_datadir_path = fs::path(); m_cached_network_datadir_path = fs::path(); m_cached_blocks_path = fs::path(); } std::optional<const ArgsManager::Command> ArgsManager::GetCommand() const { Command ret; LOCK(cs_args); auto it = m_command.begin(); if (it == m_command.end()) { // No command was passed return std::nullopt; } if (!m_accept_any_command) { // The registered command ret.command = *(it++); } while (it != m_command.end()) { // The unregistered command and args (if any) ret.args.push_back(*(it++)); } return ret; } std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const { std::vector<std::string> result; for (const util::SettingsValue& value : GetSettingsList(strArg)) { result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str()); } return result; } bool ArgsManager::IsArgSet(const std::string& strArg) const { return !GetSetting(strArg).isNull(); } bool ArgsManager::InitSettings(std::string& error) { if (!GetSettingsPath()) { return true; // Do nothing if settings file disabled. } std::vector<std::string> errors; if (!ReadSettingsFile(&errors)) { error = strprintf("Failed loading settings file:\n%s\n", MakeUnorderedList(errors)); return false; } if (!WriteSettingsFile(&errors)) { error = strprintf("Failed saving settings file:\n%s\n", MakeUnorderedList(errors)); return false; } return true; } bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp) const { if (IsArgNegated("-settings")) { return false; } if (filepath) { std::string settings = GetArg("-settings", BITCOIN_SETTINGS_FILENAME); *filepath = fsbridge::AbsPathJoin(GetDataDirNet(), temp ? settings + ".tmp" : settings); } return true; } static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out) { for (const auto& error : errors) { if (error_out) { error_out->emplace_back(error); } else { LogPrintf("%s\n", error); } } } bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors) { fs::path path; if (!GetSettingsPath(&path, /* temp= */ false)) { return true; // Do nothing if settings file disabled. } LOCK(cs_args); m_settings.rw_settings.clear(); std::vector<std::string> read_errors; if (!util::ReadSettings(path, m_settings.rw_settings, read_errors)) { SaveErrors(read_errors, errors); return false; } for (const auto& setting : m_settings.rw_settings) { std::string section; std::string key = setting.first; (void)InterpretOption(section, key, /* value */ {}); // Split setting key into section and argname if (!GetArgFlags('-' + key)) { LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first); } } return true; } bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors) const { fs::path path, path_tmp; if (!GetSettingsPath(&path, /* temp= */ false) || !GetSettingsPath(&path_tmp, /* temp= */ true)) { throw std::logic_error("Attempt to write settings file when dynamic settings are disabled."); } LOCK(cs_args); std::vector<std::string> write_errors; if (!util::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) { SaveErrors(write_errors, errors); return false; } if (!RenameOver(path_tmp, path)) { SaveErrors({strprintf("Failed renaming settings file %s to %s\n", path_tmp.string(), path.string())}, errors); return false; } return true; } bool ArgsManager::IsArgNegated(const std::string& strArg) const { return GetSetting(strArg).isFalse(); } std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const { const util::SettingsValue value = GetSetting(strArg); return value.isNull() ? strDefault : value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str(); } int64_t ArgsManager::GetIntArg(const std::string& strArg, int64_t nDefault) const { const util::SettingsValue value = GetSetting(strArg); return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.get_int64() : LocaleIndependentAtoi<int64_t>(value.get_str()); } bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const { const util::SettingsValue value = GetSetting(strArg); return value.isNull() ? fDefault : value.isBool() ? value.get_bool() : InterpretBool(value.get_str()); } bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue) { LOCK(cs_args); if (IsArgSet(strArg)) return false; ForceSetArg(strArg, strValue); return true; } <|fim▁hole|> else return SoftSetArg(strArg, std::string("0")); } void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue) { LOCK(cs_args); m_settings.forced_settings[SettingName(strArg)] = strValue; } void ArgsManager::AddCommand(const std::string& cmd, const std::string& help) { Assert(cmd.find('=') == std::string::npos); Assert(cmd.at(0) != '-'); LOCK(cs_args); m_accept_any_command = false; // latch to false std::map<std::string, Arg>& arg_map = m_available_args[OptionsCategory::COMMANDS]; auto ret = arg_map.emplace(cmd, Arg{"", help, ArgsManager::COMMAND}); Assert(ret.second); // Fail on duplicate commands } void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat) { Assert((flags & ArgsManager::COMMAND) == 0); // use AddCommand // Split arg name from its help param size_t eq_index = name.find('='); if (eq_index == std::string::npos) { eq_index = name.size(); } std::string arg_name = name.substr(0, eq_index); LOCK(cs_args); std::map<std::string, Arg>& arg_map = m_available_args[cat]; auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags}); assert(ret.second); // Make sure an insertion actually happened if (flags & ArgsManager::NETWORK_ONLY) { m_network_only_args.emplace(arg_name); } } void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names) { for (const std::string& name : names) { AddArg(name, "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN); } } std::string ArgsManager::GetHelpMessage() const { const bool show_debug = GetBoolArg("-help-debug", false); std::string usage = ""; LOCK(cs_args); for (const auto& arg_map : m_available_args) { switch(arg_map.first) { case OptionsCategory::OPTIONS: usage += HelpMessageGroup("Options:"); break; case OptionsCategory::CONNECTION: usage += HelpMessageGroup("Connection options:"); break; case OptionsCategory::ZMQ: usage += HelpMessageGroup("ZeroMQ notification options:"); break; case OptionsCategory::DEBUG_TEST: usage += HelpMessageGroup("Debugging/Testing options:"); break; case OptionsCategory::NODE_RELAY: usage += HelpMessageGroup("Node relay options:"); break; case OptionsCategory::BLOCK_CREATION: usage += HelpMessageGroup("Block creation options:"); break; case OptionsCategory::RPC: usage += HelpMessageGroup("RPC server options:"); break; case OptionsCategory::WALLET: usage += HelpMessageGroup("Wallet options:"); break; case OptionsCategory::WALLET_DEBUG_TEST: if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:"); break; case OptionsCategory::CHAINPARAMS: usage += HelpMessageGroup("Chain selection options:"); break; case OptionsCategory::GUI: usage += HelpMessageGroup("UI Options:"); break; case OptionsCategory::COMMANDS: usage += HelpMessageGroup("Commands:"); break; case OptionsCategory::REGISTER_COMMANDS: usage += HelpMessageGroup("Register Commands:"); break; default: break; } // When we get to the hidden options, stop if (arg_map.first == OptionsCategory::HIDDEN) break; for (const auto& arg : arg_map.second) { if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) { std::string name; if (arg.second.m_help_param.empty()) { name = arg.first; } else { name = arg.first + arg.second.m_help_param; } usage += HelpMessageOpt(name, arg.second.m_help_text); } } } return usage; } bool HelpRequested(const ArgsManager& args) { return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug"); } void SetupHelpOptions(ArgsManager& args) { args.AddArg("-?", "Print this help message and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS); args.AddHiddenArgs({"-h", "-help"}); } static const int screenWidth = 79; static const int optIndent = 2; static const int msgIndent = 7; std::string HelpMessageGroup(const std::string &message) { return std::string(message) + std::string("\n\n"); } std::string HelpMessageOpt(const std::string &option, const std::string &message) { return std::string(optIndent,' ') + std::string(option) + std::string("\n") + std::string(msgIndent,' ') + FormatParagraph(message, screenWidth - msgIndent, msgIndent) + std::string("\n\n"); } static std::string FormatException(const std::exception* pex, const char* pszThread) { #ifdef WIN32 char pszModule[MAX_PATH] = ""; GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule)); #else const char* pszModule = "bitcoin"; #endif if (pex) return strprintf( "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread); else return strprintf( "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread); } void PrintExceptionContinue(const std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); LogPrintf("\n\n************************\n%s\n", message); tfm::format(std::cerr, "\n\n************************\n%s\n", message); } fs::path GetDefaultDataDir() { // Windows: C:\Users\Username\AppData\Roaming\Bitcoin // macOS: ~/Library/Application Support/Bitcoin // Unix-like: ~/.bitcoin #ifdef WIN32 // Windows return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin"; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == nullptr || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // macOS return pathRet / "Library/Application Support/Bitcoin"; #else // Unix-like return pathRet / ".bitcoin"; #endif #endif } bool CheckDataDirOption() { std::string datadir = gArgs.GetArg("-datadir", ""); return datadir.empty() || fs::is_directory(fs::system_complete(datadir)); } fs::path GetConfigFile(const std::string& confPath) { return AbsPathForConfigVal(fs::path(confPath), false); } static bool GetConfigOptions(std::istream& stream, const std::string& filepath, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::list<SectionInfo>& sections) { std::string str, prefix; std::string::size_type pos; int linenr = 1; while (std::getline(stream, str)) { bool used_hash = false; if ((pos = str.find('#')) != std::string::npos) { str = str.substr(0, pos); used_hash = true; } const static std::string pattern = " \t\r\n"; str = TrimString(str, pattern); if (!str.empty()) { if (*str.begin() == '[' && *str.rbegin() == ']') { const std::string section = str.substr(1, str.size() - 2); sections.emplace_back(SectionInfo{section, filepath, linenr}); prefix = section + '.'; } else if (*str.begin() == '-') { error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str); return false; } else if ((pos = str.find('=')) != std::string::npos) { std::string name = prefix + TrimString(str.substr(0, pos), pattern); std::string value = TrimString(str.substr(pos + 1), pattern); if (used_hash && name.find("rpcpassword") != std::string::npos) { error = strprintf("parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr); return false; } options.emplace_back(name, value); if ((pos = name.rfind('.')) != std::string::npos && prefix.length() <= pos) { sections.emplace_back(SectionInfo{name.substr(0, pos), filepath, linenr}); } } else { error = strprintf("parse error on line %i: %s", linenr, str); if (str.size() >= 2 && str.substr(0, 2) == "no") { error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str); } return false; } } ++linenr; } return true; } bool ArgsManager::ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys) { LOCK(cs_args); std::vector<std::pair<std::string, std::string>> options; if (!GetConfigOptions(stream, filepath, error, options, m_config_sections)) { return false; } for (const std::pair<std::string, std::string>& option : options) { std::string section; std::string key = option.first; util::SettingsValue value = InterpretOption(section, key, option.second); std::optional<unsigned int> flags = GetArgFlags('-' + key); if (flags) { if (!CheckValid(key, value, *flags, error)) { return false; } m_settings.ro_config[section][key].push_back(value); } else { if (ignore_invalid_keys) { LogPrintf("Ignoring unknown configuration value %s\n", option.first); } else { error = strprintf("Invalid configuration value %s", option.first); return false; } } } return true; } bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys) { { LOCK(cs_args); m_settings.ro_config.clear(); m_config_sections.clear(); } const std::string confPath = GetArg("-conf", BITCOIN_CONF_FILENAME); fsbridge::ifstream stream(GetConfigFile(confPath)); // not ok to have a config file specified that cannot be opened if (IsArgSet("-conf") && !stream.good()) { error = strprintf("specified config file \"%s\" could not be opened.", confPath); return false; } // ok to not have a config file if (stream.good()) { if (!ReadConfigStream(stream, confPath, error, ignore_invalid_keys)) { return false; } // `-includeconf` cannot be included in the command line arguments except // as `-noincludeconf` (which indicates that no included conf file should be used). bool use_conf_file{true}; { LOCK(cs_args); if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) { // ParseParameters() fails if a non-negated -includeconf is passed on the command-line assert(util::SettingsSpan(*includes).last_negated()); use_conf_file = false; } } if (use_conf_file) { std::string chain_id = GetChainName(); std::vector<std::string> conf_file_names; auto add_includes = [&](const std::string& network, size_t skip = 0) { size_t num_values = 0; LOCK(cs_args); if (auto* section = util::FindKey(m_settings.ro_config, network)) { if (auto* values = util::FindKey(*section, "includeconf")) { for (size_t i = std::max(skip, util::SettingsSpan(*values).negated()); i < values->size(); ++i) { conf_file_names.push_back((*values)[i].get_str()); } num_values = values->size(); } } return num_values; }; // We haven't set m_network yet (that happens in SelectParams()), so manually check // for network.includeconf args. const size_t chain_includes = add_includes(chain_id); const size_t default_includes = add_includes({}); for (const std::string& conf_file_name : conf_file_names) { fsbridge::ifstream conf_file_stream(GetConfigFile(conf_file_name)); if (conf_file_stream.good()) { if (!ReadConfigStream(conf_file_stream, conf_file_name, error, ignore_invalid_keys)) { return false; } LogPrintf("Included configuration file %s\n", conf_file_name); } else { error = "Failed to include configuration file " + conf_file_name; return false; } } // Warn about recursive -includeconf conf_file_names.clear(); add_includes(chain_id, /* skip= */ chain_includes); add_includes({}, /* skip= */ default_includes); std::string chain_id_final = GetChainName(); if (chain_id_final != chain_id) { // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs add_includes(chain_id_final); } for (const std::string& conf_file_name : conf_file_names) { tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", conf_file_name); } } } // If datadir is changed in .conf file: gArgs.ClearPathCache(); if (!CheckDataDirOption()) { error = strprintf("specified data directory \"%s\" does not exist.", GetArg("-datadir", "")); return false; } return true; } std::string ArgsManager::GetChainName() const { auto get_net = [&](const std::string& arg) { LOCK(cs_args); util::SettingsValue value = util::GetSetting(m_settings, /* section= */ "", SettingName(arg), /* ignore_default_section_config= */ false, /* get_chain_name= */ true); return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str()); }; const bool fRegTest = get_net("-regtest"); const bool fSigNet = get_net("-signet"); const bool fTestNet = get_net("-testnet"); const bool is_chain_arg_set = IsArgSet("-chain"); if ((int)is_chain_arg_set + (int)fRegTest + (int)fSigNet + (int)fTestNet > 1) { throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet and -chain. Can use at most one."); } if (fRegTest) return CBaseChainParams::REGTEST; if (fSigNet) { return CBaseChainParams::SIGNET; } if (fTestNet) return CBaseChainParams::TESTNET; return GetArg("-chain", CBaseChainParams::MAIN); } bool ArgsManager::UseDefaultSection(const std::string& arg) const { return m_network == CBaseChainParams::MAIN || m_network_only_args.count(arg) == 0; } util::SettingsValue ArgsManager::GetSetting(const std::string& arg) const { LOCK(cs_args); return util::GetSetting( m_settings, m_network, SettingName(arg), !UseDefaultSection(arg), /* get_chain_name= */ false); } std::vector<util::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const { LOCK(cs_args); return util::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg)); } void ArgsManager::logArgsPrefix( const std::string& prefix, const std::string& section, const std::map<std::string, std::vector<util::SettingsValue>>& args) const { std::string section_str = section.empty() ? "" : "[" + section + "] "; for (const auto& arg : args) { for (const auto& value : arg.second) { std::optional<unsigned int> flags = GetArgFlags('-' + arg.first); if (flags) { std::string value_str = (*flags & SENSITIVE) ? "****" : value.write(); LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str); } } } } void ArgsManager::LogArgs() const { LOCK(cs_args); for (const auto& section : m_settings.ro_config) { logArgsPrefix("Config file arg:", section.first, section.second); } for (const auto& setting : m_settings.rw_settings) { LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write()); } logArgsPrefix("Command-line arg:", "", m_settings.command_line_options); } bool RenameOver(fs::path src, fs::path dest) { #ifdef WIN32 return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(), MOVEFILE_REPLACE_EXISTING) != 0; #else int rc = std::rename(src.string().c_str(), dest.string().c_str()); return (rc == 0); #endif /* WIN32 */ } /** * Ignores exceptions thrown by Boost's create_directories if the requested directory exists. * Specifically handles case where path p exists, but it wasn't possible for the user to * write to the parent directory. */ bool TryCreateDirectories(const fs::path& p) { try { return fs::create_directories(p); } catch (const fs::filesystem_error&) { if (!fs::exists(p) || !fs::is_directory(p)) throw; } // create_directories didn't create the directory, it had to have existed already return false; } bool FileCommit(FILE *file) { if (fflush(file) != 0) { // harmless if redundantly called LogPrintf("%s: fflush failed: %d\n", __func__, errno); return false; } #ifdef WIN32 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file)); if (FlushFileBuffers(hFile) == 0) { LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__, GetLastError()); return false; } #elif defined(MAC_OSX) && defined(F_FULLFSYNC) if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno); return false; } #elif HAVE_FDATASYNC if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync LogPrintf("%s: fdatasync failed: %d\n", __func__, errno); return false; } #else if (fsync(fileno(file)) != 0 && errno != EINVAL) { LogPrintf("%s: fsync failed: %d\n", __func__, errno); return false; } #endif return true; } void DirectoryCommit(const fs::path &dirname) { #ifndef WIN32 FILE* file = fsbridge::fopen(dirname, "r"); if (file) { fsync(fileno(file)); fclose(file); } #endif } bool TruncateFile(FILE *file, unsigned int length) { #if defined(WIN32) return _chsize(_fileno(file), length) == 0; #else return ftruncate(fileno(file), length) == 0; #endif } /** * this function tries to raise the file descriptor limit to the requested number. * It returns the actual file descriptor limit (which may be more or less than nMinFD) */ int RaiseFileDescriptorLimit(int nMinFD) { #if defined(WIN32) return 2048; #else struct rlimit limitFD; if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) { if (limitFD.rlim_cur < (rlim_t)nMinFD) { limitFD.rlim_cur = nMinFD; if (limitFD.rlim_cur > limitFD.rlim_max) limitFD.rlim_cur = limitFD.rlim_max; setrlimit(RLIMIT_NOFILE, &limitFD); getrlimit(RLIMIT_NOFILE, &limitFD); } return limitFD.rlim_cur; } return nMinFD; // getrlimit failed, assume it's fine #endif } /** * this function tries to make a particular range of a file allocated (corresponding to disk space) * it is advisory, and the range specified in the arguments will never contain live data */ void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) { #if defined(WIN32) // Windows-specific version HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file)); LARGE_INTEGER nFileSize; int64_t nEndPos = (int64_t)offset + length; nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF; nFileSize.u.HighPart = nEndPos >> 32; SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN); SetEndOfFile(hFile); #elif defined(MAC_OSX) // OSX specific version // NOTE: Contrary to other OS versions, the OSX version assumes that // NOTE: offset is the size of the file. fstore_t fst; fst.fst_flags = F_ALLOCATECONTIG; fst.fst_posmode = F_PEOFPOSMODE; fst.fst_offset = 0; fst.fst_length = length; // mac os fst_length takes the # of free bytes to allocate, not desired file size fst.fst_bytesalloc = 0; if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) { fst.fst_flags = F_ALLOCATEALL; fcntl(fileno(file), F_PREALLOCATE, &fst); } ftruncate(fileno(file), static_cast<off_t>(offset) + length); #else #if defined(HAVE_POSIX_FALLOCATE) // Version using posix_fallocate off_t nEndPos = (off_t)offset + length; if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return; #endif // Fallback version // TODO: just write one byte per block static const char buf[65536] = {}; if (fseek(file, offset, SEEK_SET)) { return; } while (length > 0) { unsigned int now = 65536; if (length < now) now = length; fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway length -= now; } #endif } #ifdef WIN32 fs::path GetSpecialFolderPath(int nFolder, bool fCreate) { WCHAR pszPath[MAX_PATH] = L""; if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate)) { return fs::path(pszPath); } LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n"); return fs::path(""); } #endif #ifndef WIN32 std::string ShellEscape(const std::string& arg) { std::string escaped = arg; boost::replace_all(escaped, "'", "'\"'\"'"); return "'" + escaped + "'"; } #endif #if HAVE_SYSTEM void runCommand(const std::string& strCommand) { if (strCommand.empty()) return; #ifndef WIN32 int nErr = ::system(strCommand.c_str()); #else int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str()); #endif if (nErr) LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr); } #endif UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in) { #ifdef ENABLE_EXTERNAL_SIGNER namespace bp = boost::process; UniValue result_json; bp::opstream stdin_stream; bp::ipstream stdout_stream; bp::ipstream stderr_stream; if (str_command.empty()) return UniValue::VNULL; bp::child c( str_command, bp::std_out > stdout_stream, bp::std_err > stderr_stream, bp::std_in < stdin_stream ); if (!str_std_in.empty()) { stdin_stream << str_std_in << std::endl; } stdin_stream.pipe().close(); std::string result; std::string error; std::getline(stdout_stream, result); std::getline(stderr_stream, error); c.wait(); const int n_error = c.exit_code(); if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error, error)); if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result); return result_json; #else throw std::runtime_error("Compiled without external signing support (required for external signing)."); #endif // ENABLE_EXTERNAL_SIGNER } void SetupEnvironment() { #ifdef HAVE_MALLOPT_ARENA_MAX // glibc-specific: On 32-bit systems set the number of arenas to 1. // By default, since glibc 2.10, the C library will create up to two heap // arenas per core. This is known to cause excessive virtual address space // usage in our usage. Work around it by setting the maximum number of // arenas to 1. if (sizeof(void*) == 4) { mallopt(M_ARENA_MAX, 1); } #endif // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale // may be invalid, in which case the "C.UTF-8" locale is used as fallback. #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) try { std::locale(""); // Raises a runtime error if current locale is invalid } catch (const std::runtime_error&) { setenv("LC_ALL", "C.UTF-8", 1); } #elif defined(WIN32) // Set the default input/output charset is utf-8 SetConsoleCP(CP_UTF8); SetConsoleOutputCP(CP_UTF8); #endif // The path locale is lazy initialized and to avoid deinitialization errors // in multithreading environments, it is set explicitly by the main thread. // A dummy locale is used to extract the internal default locale, used by // fs::path, which is then used to explicitly imbue the path. std::locale loc = fs::path::imbue(std::locale::classic()); #ifndef WIN32 fs::path::imbue(loc); #else fs::path::imbue(std::locale(loc, new std::codecvt_utf8_utf16<wchar_t>())); #endif } bool SetupNetworking() { #ifdef WIN32 // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2) return false; #endif return true; } int GetNumCores() { return std::thread::hardware_concurrency(); } std::string CopyrightHolders(const std::string& strPrefix) { const auto copyright_devs = strprintf(_(COPYRIGHT_HOLDERS).translated, COPYRIGHT_HOLDERS_SUBSTITUTION); std::string strCopyrightHolders = strPrefix + copyright_devs; // Make sure Bitcoin Core copyright is not removed by accident if (copyright_devs.find("Bitcoin Core") == std::string::npos) { strCopyrightHolders += "\n" + strPrefix + "The Bitcoin Core developers"; } return strCopyrightHolders; } // Obtain the application startup time (used for uptime calculation) int64_t GetStartupTime() { return nStartupTime; } fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific) { if (path.is_absolute()) { return path; } return fsbridge::AbsPathJoin(net_specific ? gArgs.GetDataDirNet() : gArgs.GetDataDirBase(), path); } void ScheduleBatchPriority() { #ifdef SCHED_BATCH const static sched_param param{}; const int rc = pthread_setschedparam(pthread_self(), SCHED_BATCH, &param); if (rc != 0) { LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(rc)); } #endif } namespace util { #ifdef WIN32 WinCmdLineArgs::WinCmdLineArgs() { wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc); std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt; argv = new char*[argc]; args.resize(argc); for (int i = 0; i < argc; i++) { args[i] = utf8_cvt.to_bytes(wargv[i]); argv[i] = &*args[i].begin(); } LocalFree(wargv); } WinCmdLineArgs::~WinCmdLineArgs() { delete[] argv; } std::pair<int, char**> WinCmdLineArgs::get() { return std::make_pair(argc, argv); } #endif } // namespace util<|fim▁end|>
bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue) { if (fValue) return SoftSetArg(strArg, std::string("1"));
<|file_name|>bitcoin_pl.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="pl" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About iadixcoin</source> <translation>O iadixcoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;iadixcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;iadixcoin&lt;/b&gt; wersja</translation> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The iadixcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or &lt;a href=&quot;http://www.opensource.org/licenses/mit-license.php&quot;&gt;http://www.opensource.org/licenses/mit-license.php&lt;/a&gt;. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (&lt;a href=&quot;https://www.openssl.org/&quot;&gt;https://www.openssl.org/&lt;/a&gt;) and cryptographic software written by Eric Young (&lt;a href=&quot;mailto:[email protected]&quot;&gt;[email protected]&lt;/a&gt;) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Książka Adresowa</translation> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Kliknij dwukrotnie, aby edytować adres lub etykietę</translation> </message> <message> <location line="+24"/> <source>Create a new address</source> <translation>Utwórz nowy adres</translation> </message> <message> <location line="+10"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Skopiuj aktualnie wybrany adres do schowka</translation> </message> <message> <location line="-7"/> <source>&amp;New Address</source> <translation>Nowy Adres</translation> </message> <message> <location line="-43"/> <source>These are your iadixcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Tutaj znajdują się twoje adresy do odbierania wpłat. Możesz dodać kolejny adres dla każdego wysyłającego aby określić od kogo pochodzi wpłata.</translation> </message> <message> <location line="+53"/> <source>&amp;Copy Address</source> <translation>&amp;Kopiuj adres</translation> </message> <message> <location line="+7"/> <source>Show &amp;QR Code</source> <translation>Pokaż &amp;Kod QR</translation> </message> <message> <location line="+7"/> <source>Sign a message to prove you own a iadixcoin address</source> <translation>Podpisz wiadomość by udowodnić, że jesteś właścicielem adresu iadixcoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Podpisz &amp;Wiadomość</translation> </message> <message> <location line="+17"/> <source>Delete the currently selected address from the list</source> <translation>Usuń zaznaczony adres z listy</translation> </message> <message> <location line="-10"/> <source>Verify a message to ensure it was signed with a specified iadixcoin address</source> <translation>Zweryfikuj wiadomość, w celu zapewnienia, że została podpisana z określonego adresu iadixcoin</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Zweryfikuj wiadomość</translation> </message> <message> <location line="+10"/> <source>&amp;Delete</source> <translation>&amp;Usuń</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+66"/> <source>Copy &amp;Label</source> <translation>Kopiuj &amp;Etykietę</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Edytuj</translation> </message> <message> <location line="+248"/> <source>Export Address Book Data</source> <translation>Exportuj Książkę Adresową</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Plik *.CSV (rozdzielany przecinkami)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Błąd exportowania</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Nie mogę zapisać do pliku %1</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+145"/> <source>Label</source> <translation>Etykieta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(bez etykiety)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Okienko Hasła</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Wpisz hasło</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nowe hasło</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Powtórz nowe hasło</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+38"/> <source>Encrypt wallet</source> <translation>Zaszyfruj portfel</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ta operacja wymaga hasła do portfela ażeby odblokować portfel.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Odblokuj portfel</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ta operacja wymaga hasła do portfela ażeby odszyfrować portfel.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Odszyfruj portfel</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Zmień hasło</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Podaj stare i nowe hasło do portfela.</translation> </message> <message> <location line="+45"/> <source>Confirm wallet encryption</source> <translation>Potwierdź szyfrowanie portfela</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation>Uwaga: Jeśli zaszyfrujesz swój portfel i zgubisz hasło, wtedy&lt;b&gt;UTRACISZ SWOJE MONETY!&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Jesteś pewien, że chcesz zaszyfrować swój portfel?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>WAŻNE: Wszystkie wykonane wcześniej kopie pliku portfela powinny być zamienione na nowe, szyfrowane pliki. Z powodów bezpieczeństwa, poprzednie kopie nieszyfrowanych plików portfela staną się bezużyteczne jak tylko zaczniesz korzystać z nowego, szyfrowanego portfela.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Uwaga: Klawisz Caps Lock jest włączony</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Portfel zaszyfrowany</translation> </message> <message> <location line="-140"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>iadixcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Szyfrowanie portfela nie powiodło się</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Szyfrowanie portfela nie powiodło się z powodu wewnętrznego błędu. Twój portfel nie został zaszyfrowany.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>Podane hasła nie są takie same.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Odblokowanie portfela nie powiodło się</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Wprowadzone hasło do odszyfrowania portfela jest niepoprawne.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Odszyfrowanie portfela nie powiodło się</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Hasło portfela zostało pomyślnie zmienione.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+297"/> <source>Sign &amp;message...</source> <translation>Podpisz wiado&amp;mość...</translation> </message> <message> <location line="-64"/> <source>Show general overview of wallet</source> <translation>Pokazuje ogólny zarys portfela</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transakcje</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Przeglądaj historię transakcji</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation>&amp;Książka Adresowa</translation> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation>Edytuj listę przechowywanych adresów i etykiet</translation> </message> <message> <location line="-18"/> <source>Show the list of addresses for receiving payments</source> <translation>Pokaż listę adresów do odbierania wpłat</translation> </message> <message> <location line="+34"/> <source>E&amp;xit</source> <translation>&amp;Zakończ</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Zamknij program</translation> </message> <message> <location line="+4"/> <source>Show information about iadixcoin</source> <translation>Pokaż informacje dotyczące iadixcoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>O &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Pokazuje informacje o Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opcje...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>Zaszyfruj Portf&amp;el</translation> </message> <message> <location line="+2"/> <source>&amp;Backup Wallet...</source> <translation>Wykonaj kopię zapasową...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Zmień hasło...</translation> </message> <message> <location line="+9"/> <source>&amp;Export...</source> <translation>&amp;Exportuj</translation> </message> <message> <location line="-55"/> <source>Send coins to a iadixcoin address</source> <translation>Wyślij monety na adres iadixcoin</translation> </message> <message> <location line="+39"/> <source>Modify configuration options for iadixcoin</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Backup wallet to another location</source> <translation>Zapasowy portfel w innej lokalizacji</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Zmień hasło użyte do szyfrowania portfela</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>&amp;Okno debugowania</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Otwórz konsolę debugowania i diagnostyki</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Zweryfikuj wiadomość...</translation> </message> <message> <location line="-214"/> <location line="+555"/> <source>iadixcoin</source> <translation>iadixcoin</translation> </message> <message> <location line="-555"/> <source>Wallet</source> <translation>Portfel</translation> </message> <message> <location line="+193"/> <source>&amp;About iadixcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Pokaż / Ukryj</translation> </message> <message> <location line="+8"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>&amp;File</source> <translation>&amp;Plik</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>P&amp;referencje</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>Pomo&amp;c</translation> </message> <message> <location line="+17"/> <source>Tabs toolbar</source> <translation>Pasek zakładek</translation> </message> <message> <location line="+46"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+58"/> <source>iadixcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to iadixcoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+488"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message> <location line="-812"/> <source>&amp;Dashboard</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+277"/> <source>Up to date</source> <translation>Aktualny</translation> </message> <message> <location line="+43"/> <source>Catching up...</source> <translation>Łapanie bloków...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Transakcja wysłana</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Transakcja przychodząca</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Kwota: %2 Typ: %3 Adres: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid iadixcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Wallet is &lt;b&gt;not encrypted&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portfel jest &lt;b&gt;zaszyfrowany&lt;/b&gt; i obecnie &lt;b&gt;niezablokowany&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portfel jest &lt;b&gt;zaszyfrowany&lt;/b&gt; i obecnie &lt;b&gt;zablokowany&lt;/b&gt;</translation> </message> <message> <location line="+24"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+91"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+433"/> <source>%n hour(s)</source> <translation><numerusform>%n godzina</numerusform><numerusform>%n godzin</numerusform><numerusform>%n godzin</numerusform><numerusform>%n godzin</numerusform></translation> </message> <message> <location line="-456"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+27"/> <location line="+433"/> <source>%n day(s)</source> <translation><numerusform>%n dzień</numerusform><numerusform>%n dni</numerusform><numerusform>%n dni</numerusform><numerusform>%n dni</numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+6"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+0"/> <source>%1 and %2</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+0"/> <source>%n year(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+324"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+104"/> <source>A fatal error occurred. iadixcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+119"/> <source>Network Alert</source> <translation>Sieć Alert</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation>Ilość:</translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Bajtów:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Kwota:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>Opłata:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+493"/> <source>no</source> <translation>nie</translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation>Po opłacie:</translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation>Reszta:</translation> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation>Zaznacz/Odznacz wszystko</translation> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation>Widok drzewa</translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation>Widok listy</translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Kwota</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation>Potwierdzenia</translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Potwierdzony</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation>Priorytet</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-456"/> <source>Copy address</source> <translation>Kopiuj adres</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopiuj etykietę</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Kopiuj kwotę</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Skopiuj ID transakcji</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>Skopiuj ilość</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>Skopiuj opłatę</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Skopiuj ilość po opłacie</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Skopiuj ilość bajtów</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Skopiuj resztę</translation> </message> <message> <location line="+423"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation>tak</translation> </message> <message> <location line="+9"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <location line="+58"/> <source>(no label)</source> <translation>(bez etykiety)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation>reszta z %1 (%2)</translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation>(reszta)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Edytuj adres</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etykieta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adres</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nowy adres odbiorczy</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nowy adres wysyłania</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Edytuj adres odbioru</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Edytuj adres wysyłania</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Wprowadzony adres &quot;%1&quot; już istnieje w książce adresowej.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid iadixcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Nie można było odblokować portfela.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Tworzenie nowego klucza nie powiodło się.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+426"/> <location line="+12"/> <source>iadixcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opcje</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>Główne</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Płać prowizję za transakcje</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start iadixcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start iadixcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Sieć</translation> </message> <message> <location line="+6"/> <source>Automatically open the iadixcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapuj port używając &amp;UPnP</translation> </message> <message> <location line="+19"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP: </translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Port proxy (np. 9050)</translation> </message> <message> <location line="-57"/> <source>Connect to the iadixcoin network through a SOCKS5 proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS5 proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+90"/> <source>&amp;Window</source> <translation>&amp;Okno</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Pokazuj tylko ikonę przy zegarku po zminimalizowaniu okna.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimalizuj do paska przy zegarku zamiast do paska zadań</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimalizuje zamiast zakończyć działanie programu przy zamykaniu okna. Kiedy ta opcja jest włączona, program zakończy działanie po wybieraniu Zamknij w menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimalizuj przy zamknięciu</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Wyświetlanie</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Język &amp;Użytkownika:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting iadixcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Jednostka pokazywana przy kwocie:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Wybierz podział jednostki pokazywany w interfejsie oraz podczas wysyłania monet</translation> </message> <message> <location line="+9"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use black visual theme (requires restart)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Anuluj</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+47"/> <source>default</source> <translation>domyślny</translation> </message> <message> <location line="+147"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting iadixcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Adres podanego proxy jest nieprawidłowy</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formularz</translation> </message> <message> <location line="+46"/> <location line="+247"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the iadixcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-173"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-113"/> <source>Wallet</source> <translation>Portfel</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>Twoje obecne saldo</translation> </message> <message> <location line="+80"/> <source>Immature:</source> <translation>Niedojrzały: </translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Balans wydobycia, który jeszcze nie dojrzał</translation> </message> <message> <location line="+23"/> <source>Total:</source> <translation>Wynosi ogółem:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>Twoje obecne saldo</translation> </message> <message> <location line="+50"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Ostatnie transakcje&lt;/b&gt;</translation> </message> <message> <location line="-118"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-32"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>desynchronizacja</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start iadixcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nazwa klienta</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <source>N/A</source> <translation>NIEDOSTĘPNE</translation> </message> <message> <location line="-194"/> <source>Client version</source> <translation>Wersja klienta</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informacje</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Używana wersja OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Czas uruchomienia</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Sieć</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Liczba połączeń</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Ciąg bloków</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Aktualna liczba bloków</translation> </message> <message> <location line="+197"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <location filename="../rpcconsole.cpp" line="+352"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <location filename="../rpcconsole.cpp" line="+1"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-383"/> <source>Last block time</source> <translation>Czas ostatniego bloku</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Otwórz</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the iadixcoin-Qt help message to get a list with possible iadixcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsola</translation> </message> <message> <location line="-237"/> <source>Build date</source> <translation>Data kompilacji</translation> </message> <message> <location line="-104"/> <source>iadixcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>iadixcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+256"/> <source>Debug log file</source> <translation>Plik logowania debugowania</translation> </message> <message> <location line="+7"/> <source>Open the iadixcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Wyczyść konsolę</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-28"/> <source>Welcome to the iadixcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Użyj strzałek do przewijania historii i &lt;b&gt;Ctrl-L&lt;/b&gt; aby wyczyścić ekran</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Wpisz &lt;b&gt;help&lt;/b&gt; aby uzyskać listę dostępnych komend</translation> </message> <message> <location line="+134"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+179"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Wyślij Monety</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation>Ilość:</translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Bajtów:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Kwota:</translation> </message> <message> <location line="+54"/> <source>Fee:</source> <translation>Opłata:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation>Po opłacie:</translation> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Wyślij do wielu odbiorców na raz</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Dodaj Odbio&amp;rce</translation> </message> <message> <location line="+16"/> <source>Remove all transaction fields</source><|fim▁hole|> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Wyczyść &amp;wszystko</translation> </message> <message> <location line="+24"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+47"/> <source>Confirm the send action</source> <translation>Potwierdź akcję wysyłania</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>Wy&amp;syłka</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-171"/> <source>Enter a iadixcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>Skopiuj ilość</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiuj kwotę</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>Skopiuj opłatę</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Skopiuj ilość po opłacie</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Skopiuj ilość bajtów</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Skopiuj resztę</translation> </message> <message> <location line="+85"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Potwierdź wysyłanie monet</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adres odbiorcy jest nieprawidłowy, proszę poprawić</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Kwota do zapłacenia musi być większa od 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Kwota przekracza twoje saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Suma przekracza twoje saldo, gdy doliczymy %1 prowizji transakcyjnej.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Znaleziono powtórzony adres, można wysłać tylko raz na każdy adres podczas operacji wysyłania.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+241"/> <source>WARNING: Invalid iadixcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(bez etykiety)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Su&amp;ma:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Zapłać &amp;dla:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Wprowadź etykietę dla tego adresu by dodać go do książki adresowej</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etykieta:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Wklej adres ze schowka</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a iadixcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Podpisy - Podpisz / zweryfikuj wiadomość</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>Podpi&amp;sz Wiadomość</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Możesz podpisywać wiadomości swoimi adresami aby udowodnić, że jesteś ich właścicielem. Uważaj, aby nie podpisywać niczego co wzbudza Twoje podejrzenia, ponieważ ktoś może stosować phishing próbując nakłonić Cię do ich podpisania. Akceptuj i podpisuj tylko w pełni zrozumiałe komunikaty i wiadomości.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Wklej adres ze schowka</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Wprowadź wiadomość, którą chcesz podpisać, tutaj</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopiuje aktualny podpis do schowka systemowego</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this iadixcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Zresetuj wszystkie pola podpisanej wiadomości</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Wyczyść &amp;wszystko</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Zweryfikuj wiadomość</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Wpisz adres podpisu, wiadomość (upewnij się, że dokładnie skopiujesz wszystkie zakończenia linii, spacje, tabulacje itp.) oraz podpis poniżej by sprawdzić wiadomość. Uważaj by nie dodać więcej do podpisu niż do samej podpisywanej wiadomości by uniknąć ataku man-in-the-middle (człowiek pośrodku)</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified iadixcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Resetuje wszystkie pola weryfikacji wiadomości</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a iadixcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Kliknij &quot;Podpisz Wiadomość&quot; żeby uzyskać podpis</translation> </message> <message> <location line="+3"/> <source>Enter iadixcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+85"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Podany adres jest nieprawidłowy.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Proszę sprawdzić adres i spróbować ponownie.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Wprowadzony adres nie odnosi się do klucza.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Odblokowanie portfela zostało anulowane.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Klucz prywatny dla podanego adresu nie jest dostępny</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Podpisanie wiadomości nie powiodło się</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Wiadomość podpisana.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Podpis nie może zostać zdekodowany.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Sprawdź podpis i spróbuj ponownie.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Podpis nie odpowiadał streszczeniu wiadomości</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Weryfikacja wiadomości nie powiodła się.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Wiadomość zweryfikowana.</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+75"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+25"/> <source>Open until %1</source> <translation>Otwórz do %1</translation> </message> <message> <location line="+6"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/niezatwierdzone</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 potwierdzeń</translation> </message> <message> <location line="+17"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, emitowany przez %n węzeł</numerusform><numerusform>, emitowany przez %n węzły</numerusform><numerusform>, emitowany przez %n węzłów</numerusform><numerusform>, emitowany przez %n węzłów</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Źródło</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Wygenerowano</translation> </message> <message> <location line="+5"/> <location line="+13"/> <source>From</source> <translation>Od</translation> </message> <message> <location line="+1"/> <location line="+19"/> <location line="+58"/> <source>To</source> <translation>Do</translation> </message> <message> <location line="-74"/> <location line="+2"/> <source>own address</source> <translation>własny adres</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etykieta</translation> </message> <message> <location line="+34"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Przypisy</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>potwierdzona przy %n bloku więcej</numerusform><numerusform>potwierdzona przy %n blokach więcej</numerusform><numerusform>potwierdzona przy %n blokach więcej</numerusform><numerusform>potwierdzona przy %n blokach więcej</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>niezaakceptowane</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debet</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Prowizja transakcji</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Kwota netto</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Wiadomość</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Komentarz</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID transakcji</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informacje debugowania</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transakcja</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Wejścia</translation> </message> <message> <location line="+21"/> <source>Amount</source> <translation>Kwota</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>prawda</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>fałsz</translation> </message> <message> <location line="-202"/> <source>, has not been successfully broadcast yet</source> <translation>, nie został jeszcze pomyślnie wyemitowany</translation> </message> <message numerus="yes"> <location line="-36"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+67"/> <source>unknown</source> <translation>nieznany</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Szczegóły transakcji</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ten panel pokazuje szczegółowy opis transakcji</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+231"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Kwota</translation> </message> <message> <location line="+52"/> <source>Open until %1</source> <translation>Otwórz do %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Zatwierdzony (%1 potwierdzeń)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation>Niepotwierdzone:</translation> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>Potwierdzanie (%1 z %2 rekomendowanych potwierdzeń)</translation> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Ten blok nie został odebrany przez jakikolwiek inny węzeł i prawdopodobnie nie zostanie zaakceptowany!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Wygenerowano ale nie zaakceptowano</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Otrzymane przez</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Odebrano od</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Wysłano do</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Płatność do siebie</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Wydobyto</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(brak)</translation> </message> <message> <location line="+194"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status transakcji. Najedź na pole, aby zobaczyć liczbę potwierdzeń.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data i czas odebrania transakcji.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Rodzaj transakcji.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Adres docelowy transakcji.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Kwota usunięta z lub dodana do konta.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+54"/> <location line="+17"/> <source>All</source> <translation>Wszystko</translation> </message> <message> <location line="-16"/> <source>Today</source> <translation>Dzisiaj</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>W tym tygodniu</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>W tym miesiącu</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>W zeszłym miesiącu</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>W tym roku</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Zakres...</translation> </message> <message> <location line="+12"/> <source>Received with</source> <translation>Otrzymane przez</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Wysłano do</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Do siebie</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Wydobyto</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Inne</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Wprowadź adres albo etykietę żeby wyszukać</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Min suma</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopiuj adres</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopiuj etykietę</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiuj kwotę</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Skopiuj ID transakcji</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Edytuj etykietę</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Pokaż szczegóły transakcji</translation> </message> <message> <location line="+138"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>CSV (rozdzielany przecinkami)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Potwierdzony</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etykieta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Kwota</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Zakres:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>do</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+212"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+8"/> <source>iadixcoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Użycie:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or iadixcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Lista poleceń</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Uzyskaj pomoc do polecenia</translation> </message> <message> <location line="+1"/> <source>Options:</source> <translation>Opcje:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: iadixcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: iadixcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>Określ plik portfela (w obrębie folderu danych)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Wskaż folder danych</translation> </message> <message> <location line="+163"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=iadixcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;iadixcoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="-161"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Ustaw rozmiar w megabajtach cache-u bazy danych (domyślnie: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Listen for connections on &lt;port&gt; (default: 64198 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Utrzymuj maksymalnie &lt;n&gt; połączeń z peerami (domyślnie: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Podłącz się do węzła aby otrzymać adresy peerów i rozłącz</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Podaj swój publiczny adres</translation> </message> <message> <location line="+4"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Always query for peer addresses via DNS lookup (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Próg po którym nastąpi rozłączenie nietrzymających się zasad peerów (domyślnie: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Czas w sekundach, przez jaki nietrzymający się zasad peerzy nie będą mogli ponownie się podłączyć (domyślnie: 86400)</translation> </message> <message> <location line="+153"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Wystąpił błąd podczas ustawiania portu RPC %u w tryb nasłuchu: %s</translation> </message> <message> <location line="-126"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 64199 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Accept command line and JSON-RPC commands</source> <translation>Akceptuj linię poleceń oraz polecenia JSON-RPC</translation> </message> <message> <location line="+1"/> <source>Run in the background as a daemon and accept commands</source> <translation>Uruchom w tle jako daemon i przyjmuj polecenia</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Użyj sieci testowej</translation> </message> <message> <location line="-23"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Akceptuj połączenia z zewnątrz (domyślnie: 1 jeśli nie ustawiono -proxy lub -connect)</translation> </message> <message> <location line="+160"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Wystąpił błąd podczas ustawiania portu RPC %u w tryb nasłuchu dla IPv6, korzystam z IPv4: %s</translation> </message> <message> <location line="-84"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Ostrzeżenie: -paytxfee jest bardzo duży. To jest prowizja za transakcje, którą płacisz, gdy wysyłasz monety.</translation> </message> <message> <location line="+46"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong iadixcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Ostrzeżenie: błąd odczytu wallet.dat! Wszystkie klucze zostały odczytane, ale może brakować pewnych danych transakcji lub wpisów w książce adresowej lub mogą one być nieprawidłowe.</translation> </message> <message> <location line="-16"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Ostrzeżenie: Odtworzono dane z uszkodzonego pliku wallet.dat! Oryginalny wallet.dat został zapisany jako wallet.{timestamp}.bak w %s; jeśli twoje saldo lub transakcje są niepoprawne powinieneś odtworzyć kopię zapasową.</translation> </message> <message> <location line="-31"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Próbuj odzyskać klucze prywatne z uszkodzonego wallet.dat</translation> </message> <message> <location line="+5"/> <source>Block creation options:</source> <translation>Opcje tworzenia bloku:</translation> </message> <message> <location line="-66"/> <source>Connect only to the specified node(s)</source> <translation>Łącz tylko do wskazanego węzła</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Odkryj własny adres IP (domyślnie: 1 kiedy w trybie nasłuchu i brak -externalip )</translation> </message> <message> <location line="+97"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Próba otwarcia jakiegokolwiek portu nie powiodła się. Użyj -listen=0 jeśli tego chcesz.</translation> </message> <message> <location line="-2"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-85"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maksymalny bufor odbioru na połączenie, &lt;n&gt;*1000 bajtów (domyślnie: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maksymalny bufor wysyłu na połączenie, &lt;n&gt;*1000 bajtów (domyślnie: 1000)</translation> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Łącz z węzłami tylko w sieci &lt;net&gt; (IPv4, IPv6 lub Tor)</translation> </message> <message> <location line="+30"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>Opcje SSL: (odwiedź Bitcoin Wiki w celu uzyskania instrukcji)</translation> </message> <message> <location line="-34"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Wyślij informację/raport do konsoli zamiast do pliku debug.log.</translation> </message> <message> <location line="+33"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Ustaw minimalny rozmiar bloku w bajtach (domyślnie: 0)</translation> </message> <message> <location line="-33"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Zmniejsz plik debug.log przy starcie programu (domyślnie: 1 jeśli nie użyto -debug)</translation> </message> <message> <location line="-41"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Wskaż czas oczekiwania bezczynności połączenia w milisekundach (domyślnie: 5000)</translation> </message> <message> <location line="+28"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Używaj UPnP do mapowania portu nasłuchu (domyślnie: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Używaj UPnP do mapowania portu nasłuchu (domyślnie: 1 gdy nasłuchuje)</translation> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Username for JSON-RPC connections</source> <translation>Nazwa użytkownika dla połączeń JSON-RPC</translation> </message> <message> <location line="+50"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Uwaga: Ta wersja jest przestarzała, aktualizacja wymagana!</translation> </message> <message> <location line="-23"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat uszkodzony, odtworzenie się nie powiodło</translation> </message> <message> <location line="-55"/> <source>Password for JSON-RPC connections</source> <translation>Hasło do połączeń JSON-RPC</translation> </message> <message> <location line="-47"/> <source>Connect through SOCKS5 proxy</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Przyjmuj połączenia JSON-RPC ze wskazanego adresu IP</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Wysyłaj polecenia do węzła działającego na &lt;ip&gt; (domyślnie: 127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Wykonaj polecenie kiedy najlepszy blok ulegnie zmianie (%s w komendzie zastanie zastąpione przez hash bloku)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Wykonaj polecenie, kiedy transakcja portfela ulegnie zmianie (%s w poleceniu zostanie zastąpione przez TxID)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Zaktualizuj portfel do najnowszego formatu.</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Ustaw rozmiar puli kluczy na &lt;n&gt; (domyślnie: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Przeskanuj blok łańcuchów żeby znaleźć zaginione transakcje portfela</translation> </message> <message> <location line="+3"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Keep at most &lt;n&gt; MiB of unconnectable blocks in memory (default: %u)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Użyj OpenSSL (https) do połączeń JSON-RPC</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>Plik certyfikatu serwera (domyślnie: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Klucz prywatny serwera (domyślnie: server.pem)</translation> </message> <message> <location line="+5"/> <source>Error: Unsupported argument -socks found. Setting SOCKS version isn&apos;t possible anymore, only SOCKS5 proxies are supported.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Initialization sanity check failed. iadixcoin is shutting down.</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="-135"/> <source>This help message</source> <translation>Ta wiadomość pomocy</translation> </message> <message> <location line="+100"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Nie można przywiązać %s na tym komputerze (bind returned error %d, %s)</translation> </message> <message> <location line="-136"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Zezwól -addnode, -seednode i -connect na łączenie się z serwerem DNS</translation> </message> <message> <location line="+121"/> <source>Loading addresses...</source> <translation>Wczytywanie adresów...</translation> </message> <message> <location line="-10"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Błąd ładowania wallet.dat: Uszkodzony portfel</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of iadixcoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart iadixcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Błąd ładowania wallet.dat</translation> </message> <message> <location line="-15"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Nieprawidłowy adres -proxy: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Nieznana sieć w -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="+3"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Nie można uzyskać adresu -bind: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Nie można uzyskać adresu -externalip: &apos;%s&apos;</translation> </message> <message> <location line="-22"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Nieprawidłowa kwota dla -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+59"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Nieprawidłowa kwota</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Niewystarczające środki</translation> </message> <message> <location line="-41"/> <source>Loading block index...</source> <translation>Ładowanie indeksu bloku...</translation> </message> <message> <location line="-105"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Dodaj węzeł do łączenia się and attempt to keep the connection open</translation> </message> <message> <location line="+131"/> <source>Unable to bind to %s on this computer. iadixcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-108"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>How many blocks to check at startup (default: 500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. iadixcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Loading wallet...</source> <translation>Wczytywanie portfela...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Nie można dezaktualizować portfela</translation> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Nie można zapisać domyślnego adresu</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Ponowne skanowanie...</translation> </message> <message> <location line="+2"/> <source>Done loading</source> <translation>Wczytywanie zakończone</translation> </message> <message> <location line="+33"/> <source>To use the %s option</source> <translation>Aby użyć opcji %s</translation> </message> <message> <location line="-27"/> <source>Error</source> <translation>Błąd</translation> </message> <message> <location line="+22"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Musisz ustawić rpcpassword=&lt;hasło&gt; w pliku configuracyjnym: %s Jeżeli plik nie istnieje, utwórz go z uprawnieniami właściciela-tylko-do-odczytu.</translation> </message> </context> </TS><|fim▁end|>
<translation type="unfinished"/>
<|file_name|>ogr2ogrtabletopostgislist.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ *************************************************************************** ogr2ogrtabletopostgislist.py --------------------- Date : November 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'November 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from qgis.PyQt.QtCore import QSettings from processing.core.parameters import ParameterString from processing.core.parameters import ParameterTable from processing.core.parameters import ParameterSelection from processing.core.parameters import ParameterBoolean from processing.core.parameters import ParameterTableField from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm from processing.algs.gdal.GdalUtils import GdalUtils from processing.tools.system import isWindows from processing.tools.vector import ogrConnectionString, ogrLayerName class Ogr2OgrTableToPostGisList(GdalAlgorithm): DATABASE = 'DATABASE' INPUT_LAYER = 'INPUT_LAYER' HOST = 'HOST' PORT = 'PORT' USER = 'USER' DBNAME = 'DBNAME' PASSWORD = 'PASSWORD' SCHEMA = 'SCHEMA' TABLE = 'TABLE' PK = 'PK' PRIMARY_KEY = 'PRIMARY_KEY' WHERE = 'WHERE' GT = 'GT' OVERWRITE = 'OVERWRITE' APPEND = 'APPEND' ADDFIELDS = 'ADDFIELDS' LAUNDER = 'LAUNDER' SKIPFAILURES = 'SKIPFAILURES' PRECISION = 'PRECISION' OPTIONS = 'OPTIONS' def dbConnectionNames(self): settings = QSettings() settings.beginGroup('/PostgreSQL/connections/') return settings.childGroups() def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Import layer/table as geometryless table into PostgreSQL database') self.group, self.i18n_group = self.trAlgorithm('[OGR] Miscellaneous') self.DB_CONNECTIONS = self.dbConnectionNames() self.addParameter(ParameterSelection(self.DATABASE, self.tr('Database (connection name)'), self.DB_CONNECTIONS)) self.addParameter(ParameterTable(self.INPUT_LAYER, self.tr('Input layer'))) self.addParameter(ParameterString(self.SCHEMA, self.tr('Schema name'), 'public', optional=True)) self.addParameter(ParameterString(self.TABLE, self.tr('Table name, leave blank to use input name'), '', optional=True)) self.addParameter(ParameterString(self.PK, self.tr('Primary key'), 'id', optional=True)) self.addParameter(ParameterTableField(self.PRIMARY_KEY, self.tr('Primary key (existing field, used if the above option is left empty)'), self.INPUT_LAYER, optional=True)) self.addParameter(ParameterString(self.WHERE, self.tr('Select features using a SQL "WHERE" statement (Ex: column=\'value\')'), '', optional=True)) self.addParameter(ParameterString(self.GT, self.tr('Group N features per transaction (Default: 20000)'), '', optional=True)) self.addParameter(ParameterBoolean(self.OVERWRITE, self.tr('Overwrite existing table'), True)) self.addParameter(ParameterBoolean(self.APPEND, self.tr('Append to existing table'), False)) self.addParameter(ParameterBoolean(self.ADDFIELDS, self.tr('Append and add new fields to existing table'), False)) self.addParameter(ParameterBoolean(self.LAUNDER, self.tr('Do not launder columns/table names'), False)) self.addParameter(ParameterBoolean(self.SKIPFAILURES, self.tr('Continue after a failure, skipping the failed record'), False)) self.addParameter(ParameterBoolean(self.PRECISION, self.tr('Keep width and precision of input attributes'), True)) self.addParameter(ParameterString(self.OPTIONS, self.tr('Additional creation options'), '', optional=True)) def getConsoleCommands(self): connection = self.DB_CONNECTIONS[self.getParameterValue(self.DATABASE)] settings = QSettings() mySettings = '/PostgreSQL/connections/' + connection dbname = settings.value(mySettings + '/database') user = settings.value(mySettings + '/username') host = settings.value(mySettings + '/host') port = settings.value(mySettings + '/port') password = settings.value(mySettings + '/password') inLayer = self.getParameterValue(self.INPUT_LAYER) ogrLayer = ogrConnectionString(inLayer)[1:-1] schema = unicode(self.getParameterValue(self.SCHEMA)) table = unicode(self.getParameterValue(self.TABLE)) pk = unicode(self.getParameterValue(self.PK)) pkstring = "-lco FID=" + pk primary_key = self.getParameterValue(self.PRIMARY_KEY) where = unicode(self.getParameterValue(self.WHERE)) wherestring = '-where "' + where + '"' gt = unicode(self.getParameterValue(self.GT)) overwrite = self.getParameterValue(self.OVERWRITE) append = self.getParameterValue(self.APPEND) addfields = self.getParameterValue(self.ADDFIELDS) launder = self.getParameterValue(self.LAUNDER) launderstring = "-lco LAUNDER=NO" skipfailures = self.getParameterValue(self.SKIPFAILURES) precision = self.getParameterValue(self.PRECISION) options = unicode(self.getParameterValue(self.OPTIONS)) arguments = [] arguments.append('-progress') arguments.append('--config PG_USE_COPY YES') arguments.append('-f') arguments.append('PostgreSQL') arguments.append('PG:"host=') arguments.append(host) arguments.append('port=') arguments.append(port) if len(dbname) > 0: arguments.append('dbname=' + dbname) if len(password) > 0: arguments.append('password=' + password) if len(schema) > 0: arguments.append('active_schema=' + schema) else: arguments.append('active_schema=public') arguments.append('user=' + user + '"') arguments.append(ogrLayer) arguments.append('-nlt NONE') arguments.append(ogrLayerName(inLayer)) if launder: arguments.append(launderstring) if append: arguments.append('-append') if addfields: arguments.append('-addfields') if overwrite:<|fim▁hole|> if len(pk) > 0: arguments.append(pkstring) elif primary_key is not None: arguments.append("-lco FID=" + primary_key) if len(table) == 0: table = ogrLayerName(inLayer).lower() if schema: table = '{}.{}'.format(schema, table) arguments.append('-nln') arguments.append(table) if skipfailures: arguments.append('-skipfailures') if where: arguments.append(wherestring) if len(gt) > 0: arguments.append('-gt') arguments.append(gt) if not precision: arguments.append('-lco PRECISION=NO') if len(options) > 0: arguments.append(options) commands = [] if isWindows(): commands = ['cmd.exe', '/C ', 'ogr2ogr.exe', GdalUtils.escapeAndJoin(arguments)] else: commands = ['ogr2ogr', GdalUtils.escapeAndJoin(arguments)] return commands def commandName(self): return "ogr2ogr"<|fim▁end|>
arguments.append('-overwrite')
<|file_name|>mediawiki.py<|end_file_name|><|fim▁begin|>""" Custom Authenticator to use MediaWiki OAuth with JupyterHub Requires `mwoauth` package. """ import json import os from asyncio import wrap_future from concurrent.futures import ThreadPoolExecutor from jupyterhub.handlers import BaseHandler from jupyterhub.utils import url_path_join from mwoauth import ConsumerToken from mwoauth import Handshaker from mwoauth.tokens import RequestToken from traitlets import Any from traitlets import Integer from traitlets import Unicode from oauthenticator import OAuthCallbackHandler from oauthenticator import OAuthenticator # Name of cookie used to pass auth token between the oauth # login and authentication phase AUTH_REQUEST_COOKIE_NAME = 'mw_oauth_request_token_v2' # Helpers to jsonify/de-jsonify request_token # It is a named tuple with bytestrings, json.dumps balks def jsonify(request_token): return json.dumps( [ request_token.key, request_token.secret, ] ) def dejsonify(js): key, secret = json.loads(js) return RequestToken(key, secret) class MWLoginHandler(BaseHandler): async def get(self): consumer_token = ConsumerToken( self.authenticator.client_id, self.authenticator.client_secret, ) handshaker = Handshaker(self.authenticator.mw_index_url, consumer_token) redirect, request_token = await wrap_future( self.authenticator.executor.submit(handshaker.initiate) ) self.set_secure_cookie( AUTH_REQUEST_COOKIE_NAME, jsonify(request_token), expires_days=1, path=url_path_join(self.base_url, 'hub', 'oauth_callback'), httponly=True, ) self.log.info('oauth redirect: %r', redirect) self.redirect(redirect) class MWCallbackHandler(OAuthCallbackHandler): """ Override OAuthCallbackHandler to take out state parameter handling. mwoauth doesn't seem to support it for now! """ def check_arguments(self): pass def get_state_url(self): return None <|fim▁hole|> mw_index_url = Unicode( os.environ.get('MW_INDEX_URL', 'https://meta.wikimedia.org/w/index.php'), config=True, help='Full path to index.php of the MW instance to use to log in', ) executor_threads = Integer( 12, help="""Number of executor threads. MediaWiki OAuth requests happen in this thread, so it is mostly waiting for network replies. """, config=True, ) executor = Any() def normalize_username(self, username): """ Override normalize_username to avoid lowercasing usernames """ return username def _executor_default(self): return ThreadPoolExecutor(self.executor_threads) async def authenticate(self, handler, data=None): consumer_token = ConsumerToken( self.client_id, self.client_secret, ) handshaker = Handshaker(self.mw_index_url, consumer_token) request_token = dejsonify(handler.get_secure_cookie(AUTH_REQUEST_COOKIE_NAME)) handler.clear_cookie(AUTH_REQUEST_COOKIE_NAME) access_token = await wrap_future( self.executor.submit( handshaker.complete, request_token, handler.request.query ) ) identity = await wrap_future( self.executor.submit(handshaker.identify, access_token) ) if identity and 'username' in identity: # this shouldn't be necessary anymore, # but keep for backward-compatibility return { 'name': identity['username'].replace(' ', '_'), 'auth_state': { 'ACCESS_TOKEN_KEY': access_token.key, 'ACCESS_TOKEN_SECRET': access_token.secret, 'MEDIAWIKI_USER_IDENTITY': identity, }, } else: self.log.error("No username found in %s", identity)<|fim▁end|>
class MWOAuthenticator(OAuthenticator): login_service = 'MediaWiki' login_handler = MWLoginHandler callback_handler = MWCallbackHandler
<|file_name|>fitsdiff.py<|end_file_name|><|fim▁begin|>"""fitsdiff is now a part of Astropy. Now this module just provides a wrapper around astropy.io.fits.diff for backwards compatibility with the old interface in case anyone uses it. """ import os import sys from astropy.io.fits.diff import FITSDiff from astropy.io.fits.scripts.fitsdiff import log, main def fitsdiff(input1, input2, comment_excl_list='', value_excl_list='', field_excl_list='', maxdiff=10, delta=0.0, neglect_blanks=True, output=None): if isinstance(comment_excl_list, str): comment_excl_list = list_parse(comment_excl_list) if isinstance(value_excl_list, str):<|fim▁hole|> value_excl_list = list_parse(value_excl_list) if isinstance(field_excl_list, str): field_excl_list = list_parse(field_excl_list) diff = FITSDiff(input1, input2, ignore_keywords=value_excl_list, ignore_comments=comment_excl_list, ignore_fields=field_excl_list, numdiffs=maxdiff, tolerance=delta, ignore_blanks=neglect_blanks) if output is None: output = sys.stdout diff.report(output) return diff.identical def list_parse(name_list): """Parse a comma-separated list of values, or a filename (starting with @) containing a list value on each line. """ if name_list and name_list[0] == '@': value = name_list[1:] if not os.path.exists(value): log.warning('The file %s does not exist' % value) return try: return [v.strip() for v in open(value, 'r').readlines()] except IOError as e: log.warning('reading %s failed: %s; ignoring this file' % (value, e)) else: return [v.strip() for v in name_list.split(',')] if __name__ == "__main__": sys.exit(main())<|fim▁end|>
<|file_name|>test_artificial_32_None_PolyTrend_12_12_20.py<|end_file_name|><|fim▁begin|>import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art <|fim▁hole|> art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 12, transform = "None", sigma = 0.0, exog_count = 20, ar_order = 12);<|fim▁end|>
<|file_name|>timestamp.ts<|end_file_name|><|fim▁begin|>import { OperatorFunction, Timestamp as TimestampInterface, TimestampProvider, Timestamp } from '../types'; import { map } from './map'; /** * Attaches a timestamp to each item emitted by an observable indicating when it was emitted * * The `timestamp` operator maps the *source* observable stream to an object of type * `{value: T, timestamp: R}`. The properties are generically typed. The `value` property contains the value * and type of the *source* observable. The `timestamp` is generated by the schedulers `now` function. By * default it uses the *async* scheduler which simply returns `Date.now()` (milliseconds since 1970/01/01 * 00:00:00:000) and therefore is of type `number`. * * ![](timestamp.png) * * ## Example * * In this example there is a timestamp attached to the documents click event. * * ```ts * import { fromEvent } from 'rxjs'; * import { timestamp } from 'rxjs/operators'; * * const clickWithTimestamp = fromEvent(document, 'click').pipe( * timestamp() * ); * * // Emits data of type {value: MouseEvent, timestamp: number} * clickWithTimestamp.subscribe(data => { * console.log(data); * }); * ``` * * @param timestampProvider An object with a `now()` method used to get the current timestamp. */ export function timestamp<T>(timestampProvider: TimestampProvider = Date): OperatorFunction<T, Timestamp<T>> {<|fim▁hole|>}<|fim▁end|>
return map((value: T) => ({ value, timestamp: timestampProvider.now()}));
<|file_name|>signup.js<|end_file_name|><|fim▁begin|>import { useState } from 'react' import { useRouter } from 'next/router' import Link from 'next/link' import { gql, useMutation } from '@apollo/client' import { getErrorMessage } from '../lib/form' import Field from '../components/field' const SignUpMutation = gql` mutation SignUpMutation($email: String!, $password: String!) { signUp(input: { email: $email, password: $password }) { user { id email } } } ` function SignUp() { const [signUp] = useMutation(SignUpMutation) const [errorMsg, setErrorMsg] = useState() const router = useRouter() async function handleSubmit(event) { event.preventDefault() const emailElement = event.currentTarget.elements.email const passwordElement = event.currentTarget.elements.password try { await signUp({ variables: { email: emailElement.value, password: passwordElement.value, }, }) router.push('/signin') } catch (error) { setErrorMsg(getErrorMessage(error)) } } return ( <> <h1>Sign Up</h1><|fim▁hole|> <Field name="email" type="email" autoComplete="email" required label="Email" /> <Field name="password" type="password" autoComplete="password" required label="Password" /> <button type="submit">Sign up</button> or{' '} <Link href="/signin"> <a>Sign in</a> </Link> </form> </> ) } export default SignUp<|fim▁end|>
<form onSubmit={handleSubmit}> {errorMsg && <p>{errorMsg}</p>}
<|file_name|>syslog_broker.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009-2012: # Gabes Jean, [email protected] # Gerhard Lausser, [email protected] # Gregory Starck, [email protected] # Hartmut Goebel, [email protected] # # This file is part of Shinken. # # Shinken is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by<|fim▁hole|># (at your option) any later version. # # Shinken is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Shinken. If not, see <http://www.gnu.org/licenses/>. # This Class is a plugin for the Shinken Broker. It is in charge # to brok log into the syslog import syslog from shinken.basemodule import BaseModule from shinken.log import logger properties = { 'daemons': ['broker'], 'type': 'syslog', 'external': False, 'phases': ['running'], } # called by the plugin manager to get a broker def get_instance(plugin): logger.info("Get a Syslog broker for plugin %s" % plugin.get_name()) #Catch errors #path = plugin.path instance = Syslog_broker(plugin) return instance # Class for the Merlindb Broker # Get broks and puts them in merlin database class Syslog_broker(BaseModule): def __init__(self, modconf): BaseModule.__init__(self, modconf) # A service check have just arrived, we UPDATE data info with this def manage_log_brok(self, b): data = b.data syslog.syslog(data['log'].encode('UTF-8'))<|fim▁end|>
# the Free Software Foundation, either version 3 of the License, or
<|file_name|>metrics_utils.py<|end_file_name|><|fim▁begin|># Copyright 2021 The Kubeflow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software<|fim▁hole|># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from kfp.deprecated.dsl import artifact_utils from typing import Any, List class ComplexMetricsBase(object): def get_schema(self): """Returns the set YAML schema for the metric class. Returns: YAML schema of the metrics type. """ return self._schema def get_metrics(self): """Returns the stored metrics. The metrics are type checked against the set schema. Returns: Dictionary of metrics data in the format of the set schema. """ artifact_utils.verify_schema_instance(self._schema, self._values) return self._values def __init__(self, schema_file: str): self._schema = artifact_utils.read_schema_file(schema_file) self._type_name, self._metric_fields = artifact_utils.parse_schema( self._schema) self._values = {} class ConfidenceMetrics(ComplexMetricsBase): """Metrics class representing a Confidence Metrics.""" # Initialization flag to support setattr / getattr behavior. _initialized = False def __getattr__(self, name: str) -> Any: """Custom __getattr__ to allow access to metrics schema fields.""" if name not in self._metric_fields: raise AttributeError('No field: {} in metrics.'.format(name)) return self._values[name] def __setattr__(self, name: str, value: Any): """Custom __setattr__ to allow access to metrics schema fields.""" if not self._initialized: object.__setattr__(self, name, value) return if name not in self._metric_fields: raise RuntimeError( 'Field: {} not defined in metirc schema'.format(name)) self._values[name] = value def __init__(self): super().__init__('confidence_metrics.yaml') self._initialized = True class ConfusionMatrix(ComplexMetricsBase): """Metrics class representing a confusion matrix.""" def __init__(self): super().__init__('confusion_matrix.yaml') self._matrix = [[]] self._categories = [] self._initialized = True def set_categories(self, categories: List[str]): """Sets the categories for Confusion Matrix. Args: categories: List of strings specifying the categories. """ self._categories = [] annotation_specs = [] for category in categories: annotation_spec = {'displayName': category} self._categories.append(category) annotation_specs.append(annotation_spec) self._values['annotationSpecs'] = annotation_specs self._matrix = [[0 for i in range(len(self._categories))] for j in range(len(self._categories))] self._values['row'] = self._matrix def log_row(self, row_category: str, row: List[int]): """Logs a confusion matrix row. Args: row_category: Category to which the row belongs. row: List of integers specifying the values for the row. Raises: ValueError: If row_category is not in the list of categories set in set_categories or size of the row does not match the size of categories. """ if row_category not in self._categories: raise ValueError('Invalid category: {} passed. Expected one of: {}'.\ format(row_category, self._categories)) if len(row) != len(self._categories): raise ValueError('Invalid row. Expected size: {} got: {}'.\ format(len(self._categories), len(row))) self._matrix[self._categories.index(row_category)] = row def log_cell(self, row_category: str, col_category: str, value: int): """Logs a cell in the confusion matrix. Args: row_category: String representing the name of the row category. col_category: String representing the name of the column category. value: Int value of the cell. Raises: ValueError: If row_category or col_category is not in the list of categories set in set_categories. """ if row_category not in self._categories: raise ValueError('Invalid category: {} passed. Expected one of: {}'.\ format(row_category, self._categories)) if col_category not in self._categories: raise ValueError('Invalid category: {} passed. Expected one of: {}'.\ format(row_category, self._categories)) self._matrix[self._categories.index(row_category)][ self._categories.index(col_category)] = value def load_matrix(self, categories: List[str], matrix: List[List[int]]): """Supports bulk loading the whole confusion matrix. Args: categories: List of the category names. matrix: Complete confusion matrix. Raises: ValueError: Length of categories does not match number of rows or columns. """ self.set_categories(categories) if len(matrix) != len(categories): raise ValueError('Invalid matrix: {} passed for categories: {}'.\ format(matrix, categories)) for index in range(len(categories)): if len(matrix[index]) != len(categories): raise ValueError('Invalid matrix: {} passed for categories: {}'.\ format(matrix, categories)) self.log_row(categories[index], matrix[index])<|fim▁end|>
# distributed under the License is distributed on an "AS IS" BASIS,
<|file_name|>operand.rs<|end_file_name|><|fim▁begin|>//! //! MOS 6502 operands (adressing modes) //! use std::fmt; use addr::{Address, Masked}; use cpu::Mos6502; use mem::Addressable; /// Instruction operand with different addressing modes #[derive(Debug, PartialEq, Eq)] pub enum Operand { Implied, // OPC Operand implied Immediate(u8), // OPC #$BB Operand is value $BB Accumulator, // OPC A Operand is AC Relative(i8), // OPC $RR Branch target is PC + signed offset $RR (bit 7 signifies negative offset) Absolute(u16), // OPC $HHLL Operand is address $HHLL AbsoluteIndexedWithX(u16), // OPC $HHLL,X Operand is address $HHLL incremented by X AbsoluteIndexedWithY(u16), // OPC $HHLL,Y Operand is address $HHLL incremented by Y Indirect(u16), // OPC ($HHLL) Operand is effective address; effective address is value of address; no page transition (MSB-bug) ZeroPage(u8), // OPC $LL Operand is address $00LL ZeroPageIndexedWithX(u8), // OPC $LL,X Operand is address $00LL incremented by X; no page transition ZeroPageIndexedWithY(u8), // OPC $LL,Y Operand is address $00LL incremented by Y; no page transition ZeroPageIndexedWithXIndirect(u8), // OPC ($LL,X) Operand is effective address; effective address is $00LL incremented by X; no page transition ZeroPageIndirectIndexedWithY(u8), // OPC ($LL),Y Operand is effective address incremented by Y; effective address is word at $00LL } impl Operand { /// Returns the address an operand targets to pub fn addr<M: Addressable> (&self, cpu: &Mos6502<M>) -> u16 { match *self { Operand::Implied => panic!("mos6502: Implied operand does never target an address"), Operand::Immediate(..) => panic!("mos6502: Immediate operand does never target an address"), Operand::Accumulator => panic!("mos6502: Accumulator operand does never target an address"), Operand::Relative(offset) => cpu.pc.offset(offset as i16), Operand::Absolute(addr) => addr, Operand::AbsoluteIndexedWithX(addr) => addr.offset(cpu.x as i16), Operand::AbsoluteIndexedWithY(addr) => addr.offset(cpu.y as i16), Operand::Indirect(addr) => cpu.mem.get_le(Masked(addr, 0xff00)), // simulating MSB-bug Operand::ZeroPage(zp) => zp as u16, Operand::ZeroPageIndexedWithX(zp) => zp.wrapping_add(cpu.x) as u16, // no page transition Operand::ZeroPageIndexedWithY(zp) => zp.wrapping_add(cpu.y) as u16, // no page transition Operand::ZeroPageIndexedWithXIndirect(zp) => cpu.mem.get_le(zp.wrapping_add(cpu.x) as u16), // no page transition Operand::ZeroPageIndirectIndexedWithY(zp) => { let addr: u16 = cpu.mem.get_le(zp as u16); addr.wrapping_add(cpu.y as u16) }, } } /// Returns the value an operand specifies pub fn get<M: Addressable> (&self, cpu: &Mos6502<M>) -> u8 { match *self { Operand::Implied => panic!("mos6502: Implied operand does never have a value"), Operand::Immediate(value) => value, Operand::Accumulator => cpu.ac, Operand::Relative(..) => panic!("mos6502: Relative operand does never have a value"), ref op => cpu.mem.get(op.addr(cpu)), } } /// Sets the value an operand specifies pub fn set<M: Addressable> (&self, cpu: &mut Mos6502<M>, value: u8) { match *self { Operand::Implied => panic!("mos6502: Implied operand does never set a value"), Operand::Immediate(..) => panic!("mos6502: Immediate operand does never set a value"), Operand::Accumulator => cpu.ac = value, Operand::Relative(..) => panic!("mos6502: Relative operand does never set a value"), ref op => { let addr = op.addr(cpu); cpu.mem.set(addr, value); }, } } } impl fmt::Display for Operand { fn fmt (&self, f: &mut fmt::Formatter) -> fmt::Result { let str = match *self { Operand::Implied => format!(""), Operand::Immediate(value) => format!("#${:02X}", value), Operand::Accumulator => format!("A"), Operand::Relative(offset) => format!("{:+}", offset), Operand::Absolute(addr) => format!("{}", addr.display()), Operand::AbsoluteIndexedWithX(addr) => format!("{},X", addr.display()), Operand::AbsoluteIndexedWithY(addr) => format!("{},Y", addr.display()), Operand::Indirect(addr) => format!("({})", addr.display()), Operand::ZeroPage(zp) => format!("${:02X}", zp), Operand::ZeroPageIndexedWithX(zp) => format!("${:02X},X", zp), Operand::ZeroPageIndexedWithY(zp) => format!("${:02X},Y", zp), Operand::ZeroPageIndexedWithXIndirect(zp) => format!("(${:02X},X)", zp), Operand::ZeroPageIndirectIndexedWithY(zp) => format!("(${:02X}),Y", zp), }; str.fmt(f) } } #[cfg(test)] mod tests { use cpu::Mos6502; use mem::test::TestMemory; use super::*; #[test] fn addressing_modes () {<|fim▁hole|> let _ = Operand::Implied; // Immediate assert_eq!(Operand::Immediate(0x55).get(&cpu), 0x55); // Accumulator assert_eq!(Operand::Accumulator.get(&cpu), 0x88); Operand::Accumulator.set(&mut cpu, 0x99); assert_eq!(cpu.ac, 0x99); // Relative assert_eq!(Operand::Relative(0x33).addr(&cpu), 0x136a); assert_eq!(Operand::Relative(-0x33).addr(&cpu), 0x1304); // Absolute assert_eq!(Operand::Absolute(0x0123).addr(&cpu), 0x0123); assert_eq!(Operand::Absolute(0x0123).get(&cpu), 0x24); Operand::Absolute(0x0123).set(&mut cpu, 0x24); // AbsoluteIndexedWithX assert_eq!(Operand::AbsoluteIndexedWithX(0x0123).addr(&cpu), 0x0134); assert_eq!(Operand::AbsoluteIndexedWithX(0x0123).get(&cpu), 0x35); Operand::AbsoluteIndexedWithX(0x0123).set(&mut cpu, 0x35); // AbsoluteIndexedWithY assert_eq!(Operand::AbsoluteIndexedWithY(0x0123).addr(&cpu), 0x0145); assert_eq!(Operand::AbsoluteIndexedWithY(0x0123).get(&cpu), 0x46); Operand::AbsoluteIndexedWithY(0x0123).set(&mut cpu, 0x46); // Indirect assert_eq!(Operand::Indirect(0x0123).addr(&cpu), 0x2524); assert_eq!(Operand::Indirect(0x0123).get(&cpu), 0x49); Operand::Indirect(0x0123).set(&mut cpu, 0x49); // ZeroPage assert_eq!(Operand::ZeroPage(0x12).addr(&cpu), 0x0012); assert_eq!(Operand::ZeroPage(0x12).get(&cpu), 0x12); Operand::ZeroPage(0x12).set(&mut cpu, 0x12); // ZeroPageIndexedWithX assert_eq!(Operand::ZeroPageIndexedWithX(0x12).addr(&cpu), 0x0023); assert_eq!(Operand::ZeroPageIndexedWithX(0x12).get(&cpu), 0x23); Operand::ZeroPageIndexedWithX(0x12).set(&mut cpu, 0x23); // ZeroPageIndexedWithY assert_eq!(Operand::ZeroPageIndexedWithY(0x12).addr(&cpu), 0x0034); assert_eq!(Operand::ZeroPageIndexedWithY(0x12).get(&cpu), 0x34); Operand::ZeroPageIndexedWithY(0x12).set(&mut cpu, 0x34); // ZeroPageIndexedWithXIndirect assert_eq!(Operand::ZeroPageIndexedWithXIndirect(0x12).addr(&cpu), 0x2423); assert_eq!(Operand::ZeroPageIndexedWithXIndirect(0x12).get(&cpu), 0x47); Operand::ZeroPageIndexedWithXIndirect(0x12).set(&mut cpu, 0x47); // ZeroPageIndirectIndexedWithY assert_eq!(Operand::ZeroPageIndirectIndexedWithY(0x12).addr(&cpu), 0x1334); assert_eq!(Operand::ZeroPageIndirectIndexedWithY(0x12).get(&cpu), 0x47); Operand::ZeroPageIndirectIndexedWithY(0x12).set(&mut cpu, 0x47); } #[test] fn indirect_addressing_bug () { let cpu = Mos6502::new(TestMemory); // Indirect($C0FF) must erroneously get address from $C0FF/$C000 instead of $C0FF/$C100 assert_eq!(Operand::Indirect(0xc0ff).addr(&cpu), 0xc0bf); // must be $C0BF, not $C1BF } #[test] fn zero_page_indexed_does_no_page_transition () { let mut cpu = Mos6502::new(TestMemory); cpu.x = 0x11; cpu.y = 0x22; // Zero-page indexed addressing must not transition to the next page assert_eq!(Operand::ZeroPageIndexedWithX(0xff).addr(&cpu), 0x0010); // must be $0010, not $0110 assert_eq!(Operand::ZeroPageIndexedWithY(0xff).addr(&cpu), 0x0021); // must be $0021, not $0121 } #[test] fn zero_page_indexed_indirect_does_no_page_transition () { let mut cpu = Mos6502::new(TestMemory); cpu.x = 0x11; // Zero-page indexed indirect addressing must not transition to the next page when indexing... assert_eq!(Operand::ZeroPageIndexedWithXIndirect(0xff).addr(&cpu), 0x1110); // must be $1110, not $1211 // ...but may transition to the next page when indirecting assert_eq!(Operand::ZeroPageIndexedWithXIndirect(0xee).addr(&cpu), 0x01ff); // must be $01FF, not $00FF } #[test] fn zero_page_indirect_indexed_does_no_page_transition () { let mut cpu = Mos6502::new(TestMemory); cpu.y = 0x22; // Zero-page indirect indexed addressing may transition to the next page when indirecting... assert_eq!(Operand::ZeroPageIndirectIndexedWithY(0xff).addr(&cpu), 0x0221); // must be $0221, not $0121 // ...and may transition to the next page when indexing assert_eq!(Operand::ZeroPageIndirectIndexedWithY(0xf0).addr(&cpu), 0xf212); // must be $F212, not $F112 } }<|fim▁end|>
let mut cpu = Mos6502::new(TestMemory); cpu.pc = 0x1337; cpu.ac = 0x88; cpu.x = 0x11; cpu.y = 0x22; // Implied
<|file_name|>trait.rs<|end_file_name|><|fim▁begin|>// 不可复制的类型。 struct Empty;<|fim▁hole|>trait DoubleDrop<T> { // 定义一个关于调用者的方法,接受一个额外的单一参量 `T`, // 且没有任何操作。 fn double_drop(self, _: T); } // 针对泛型参量 `T` 和调用者 `U` 实现了 `DoubleDrop<T>` 。 impl<T, U> DoubleDrop<T> for U { // 此方法获得了两个传入参数的所有权,并释放这两个参数。 fn double_drop(self, _: T) {} } fn main() { let empty = Empty; let null = Null; // 释放 `empty` 和 `null`。 empty.double_drop(null); //empty; //null; // ^ 试一试:去掉这两行的注释。 }<|fim▁end|>
struct Null; // 用到 `T` 的trait 泛型。
<|file_name|>hooks.py<|end_file_name|><|fim▁begin|>import hexchat import re import sys import twitch.hook, twitch.jtvmsghandler, twitch.user, twitch.channel import twitch.normalize, twitch.commands, twitch.exceptions, twitch.topic import twitch.logger, twitch.settings from twitch import irc log = twitch.logger.get() # regex for extracting time from ban message ban_msg_regex = re.compile(r"for (\d+) more seconds") # Identify ourselves as Twitch IRC client to get user info def endofmotd_cb(word, word_eol, userdata): hexchat.command('CAP REQ :twitch.tv/tags twitch.tv/commands') # Ignore various "unknown command" errors unknowncommands = ('WHO', 'WHOIS') def servererr_cb(word, word_eol, userdata): if word[3] in unknowncommands: return hexchat.EAT_ALL return hexchat.EAT_NONE # PRIVMSG hook to handle various notification messages from Twitch. def privmsg_cb(word, word_eol, msgtype): try: nick = twitch.normalize.nick((word[0][1:].split('!')[0])) chan = word[2] text = word_eol[3] if chan == '#jtv' and nick == 'jtv': hexchat.emit_print('Server Text', text[1:]) return hexchat.EAT_ALL elif nick == 'jtv': if chan[0] != '#': irc.emit_print(None, 'Server Text', text[1:]) return hexchat.EAT_ALL elif "You are banned" in text: chan = twitch.channel.get(chan) if not chan.areWeBanned: chan.areWeBanned = True match = ban_msg_regex.search(text) time = int(match.group(1)) def clear_ban(userdata): chan.areWeBanned = False chan.emit_print('Server Text', "You are (hopefully) no longer banned") hexchat.hook_timer(time * 1000, clear_ban) else: action = word[3][1:] param = word[4:] if action[0] != '_' and hasattr(twitch.jtvmsghandler, action): return getattr(twitch.jtvmsghandler, action)(chan, param) else: #log.warning("Unhandled JTV message: %s" % str(word)) ctxt = twitch.channel.get(chan).getContext() twitch.channel.get(chan).emit_print('Server Text', text[1:]) return hexchat.EAT_ALL elif nick == 'twitchnotify': twitch.channel.get(chan).emit_print('Server Text', text[1:]) return hexchat.EAT_ALL else: twitch.user.get(nick).joinChannel(chan) return hexchat.EAT_NONE except: log.exception("Unhandled exception in twitch.privmsg_cb") return hexchat.EAT_NONE # handle Twitch WHISPER message def whisper_cb(word, word_eol, msgtype): try: nick = twitch.normalize.nick((word[0][1:].split('!')[0])) dest = word[2] msg = word_eol[3][1:] log.debug("Got WHISPER: %s", word) hexchat.emit_print('Notice', nick, msg) except: log.exception("Unhandled exception in twitch.whisper_cb") finally: return hexchat.EAT_ALL # handle Twitch USERSTATE and GLOBALUSERSTATE messages def userstate_cb(word, word_eol, msgtype): try: # log.debug("Got %s msg: %s", msgtype, word) # Nothing to do here (except eat the message) until Hexchat adds a # way to read the message's IRCv3 tags. pass except: log.exception("Unhandled exception in twitch.userstate_cb") finally: return hexchat.EAT_ALL # handle Twitch HOSTTARGET messages # :tmi.twitch.tv HOSTTARGET #renakunisaki :cloakedyoshi - def hosttarget_cb(word, word_eol, msgtype): try: log.debug("%s %s", msgtype, word) chan = word[2] param = word[3:] return twitch.jtvmsghandler.HOSTTARGET(chan, param) except: log.exception("Unhandled exception in twitch.hosttarget_cb") finally: return hexchat.EAT_ALL # handle Twitch CLEARCHAT messages # :tmi.twitch.tv CLEARCHAT #darkspinessonic :ishmon def clearchat_cb(word, word_eol, msgtype): try: log.debug("%s %s", msgtype, word) if len(word) >= 4: param = [word[3][1:]] else: param = [] chan = word[2] # log.debug("Chan = %s, whom = %s", chan, param) return twitch.jtvmsghandler.CLEARCHAT(chan, param) except: log.exception("Unhandled exception in twitch.clearchat_cb") finally: return hexchat.EAT_ALL #def rawmsg_cb(word, word_eol, msgtype, attributes): # try: # log.debug("Got raw msg: %s", word) # except: # log.exception("Unhandled exception in twitch.rawmsg_cb") # finally: # return hexchat.EAT_NONE # message hook to format user messages nicely. message_cb_recurse = False def message_cb(word, word_eol, msgtype): # avoid infinite loop global message_cb_recurse if message_cb_recurse: return message_cb_recurse = True try: #log.debug("message_cb word=%s" % str(word)) #log.debug("message_cb word_eol=%s" % str(word_eol)) if len(word) < 1: return hexchat.EAT_NONE nick = twitch.normalize.nick(word[0]) try: text = word[1] except IndexError: text = '' user = twitch.user.get(nick) chan = twitch.channel.get(hexchat.get_context()) if chan is not None: user.joinChannel(chan) user.printMessage(chan, text, msgtype) else: log.error("Got user message for invalid channel: <%s> %s" % (nick, text)) return hexchat.EAT_ALL except: log.exception("Unhandled exception in twitch.message_cb") return hexchat.EAT_NONE finally: message_cb_recurse = False # MODE hook to track mods def mode_cb(word, word_eol, msgtype): try: chan = word[2] mode = word[3] whom = word[4] user = twitch.user.get(whom) what = '+' for char in mode: if char == '+' or char == '-': what = char elif what == '+': user.setChannelMode(chan, char, True) elif what == '-': user.setChannelMode(chan, char, False) except: log.exception("Unhandled exception in twitch.mode_cb") finally: return hexchat.EAT_NONE # When we join a channel, set up the user info and get stream status def youjoin_cb(word, word_eol, msgtype): try: chan = twitch.channel.get(word[1]) chan.join() hexchat.command("CAP REQ :twitch.tv/membership") # automatically set up some users jtv = twitch.user.get('jtv') jtv.joinChannel(chan) jtv.setAttrs({'admin':True,'bot':True}) twitchnotify = twitch.user.get('twitchnotify') twitchnotify.joinChannel(chan) twitchnotify.setAttrs({'admin':True,'bot':True}) broadcaster = twitch.user.get(chan.name) broadcaster.joinChannel(chan) broadcaster.setChanAttr(chan, 'broadcaster', True) except: log.exception("Unhandled exception in twitch.youjoin_cb") finally: return hexchat.EAT_NONE # When we leave a channel, stop updating it def youpart_cb(word, word_eol, msgtype): try: if msgtype == 'You Kicked': chan = word[1] else: chan = word[2] twitch.channel.get(chan).leave() except: log.exception("Unhandled exception in twitch.youpart_cb") def isCommand(name, obj): return (callable(obj) and (not name.startswith('_')) and hasattr(obj, 'command')) # handler for /twitch command def twitchcmd_cb(word, word_eol, userdata): try: log.debug("/twitch command: %s" % word) if len(word) < 2: print("Available commands:") for name, obj in twitch.commands.__dict__.items(): if isCommand(name, obj): print("%s - %s" % (name, obj.command['desc'])) return hexchat.EAT_ALL cmd = word[1] if not hasattr(twitch.commands, cmd): raise twitch.exceptions.UnknownCommandError(cmd) f = getattr(twitch.commands, cmd) if not hasattr(f, 'command'): raise twitch.exceptions.UnknownCommandError(cmd) f(word[2:], word_eol[2:]) except twitch.exceptions.BadParameterError as ex: print("%s: %s" % (cmd, ex)) except twitch.exceptions.UnknownCommandError as ex: print("%s: Unknown command" % ex) except: log.exception("Unhandled exception in twitch.twitchcmd_cb(%s)" % cmd) finally: return hexchat.EAT_ALL # ignore repeated JOIN events that can happen because we simulate them # (since Twitch doesn't always send them reliably) def join_cb(word, word_eol, msgtype): try: nick = twitch.normalize.nick((word[0][1:].split('!')[0])) user = twitch.user.get(nick) chan = twitch.channel.get(word[2]) if chan.hasUser(user): return hexchat.EAT_ALL else: user.joinChannel(chan) if ".twitch.hexchat.please.stop.being.butts" not in word[0]: # eat JOINs that actually come from Twitch return hexchat.EAT_ALL else: return hexchat.EAT_NONE except: log.exception("Unhandled exception in twitch.join_cb(%s)" % str(word)) return hexchat.EAT_NONE # suppress "gives/removes channel operator status" messages def chanop_cb(word, word_eol, msgtype): if twitch.settings.get('mute.chanop'): return hexchat.EAT_ALL else: return hexchat.EAT_NONE # suppress join/part messages def joinpart_cb(word, word_eol, msgtype): if twitch.settings.get('mute.joinpart'): log.debug("Muted a join/part message: %s" % str(word)) return hexchat.EAT_ALL else: return hexchat.EAT_NONE # suppress "capabilities acknowledged" messages def capack_cb(word, word_eol, msgtype): return hexchat.EAT_ALL # suppress "invalid CAP command" caused by Hexchat doing "CAP LS" at startup def cmd410_cb(word, word_eol, msgtype): return hexchat.EAT_ALL # lowercase channel name before joining, or else we won't get any messages def joincmd_cb(word, word_eol, userdata): try: chan = word[1] orig = chan<|fim▁hole|> chan = chan.lower() # also handle URLs unslashed = re.search('([^/]+)$', chan) if unslashed: chan = unslashed.group(1) # also handle bare username if chan[0] != '#': chan = '#' + chan log.debug("JOIN(%s) => (%s)", orig, chan) if orig == chan: return hexchat.EAT_NONE else: hexchat.command("JOIN " + chan) return hexchat.EAT_ALL except: log.exception("Unhandled exception in twitch.joincmd_cb(%s)" % cmd) return hexchat.EAT_NONE # handle /w command (whisper) def whispercmd_cb(word, word_eol, userdata): try: log.debug("Got /w: %s", word_eol) hexchat.command("PRIVMSG #jtv :/w %s" % word_eol[1]) hexchat.emit_print('Message Send', word[1], word_eol[2]) return hexchat.EAT_ALL except: log.exception("Unhandled exception in twitch.whispercmd_cb") return hexchat.EAT_ALL # Install the hooks def install(): twitch.hook.server ('376', endofmotd_cb) twitch.hook.server ('410', cmd410_cb) twitch.hook.server ('421', servererr_cb) twitch.hook.server ('PRIVMSG', privmsg_cb) twitch.hook.server ('USERSTATE', userstate_cb) twitch.hook.server ('GLOBALUSERSTATE', userstate_cb) twitch.hook.server ('HOSTTARGET', hosttarget_cb) twitch.hook.server ('CLEARCHAT', clearchat_cb) twitch.hook.server ('WHISPER', whisper_cb) #twitch.hook.server_attrs('RAW LINE', rawmsg_cb) twitch.hook.prnt ('Channel Action', message_cb) twitch.hook.prnt ('Channel Action Hilight', message_cb) twitch.hook.prnt ('Channel Message', message_cb) twitch.hook.prnt ('Channel Msg Hilight', message_cb) twitch.hook.prnt ('Your Action', message_cb) twitch.hook.prnt ('Your Message', message_cb) twitch.hook.server ('MODE', mode_cb) twitch.hook.server ('JOIN', join_cb) twitch.hook.prnt ('You Join', youjoin_cb) twitch.hook.prnt ('You Part', youpart_cb) twitch.hook.prnt ('You Part with Reason', youpart_cb) twitch.hook.prnt ('You Kicked', youpart_cb) twitch.hook.command('twitch', twitchcmd_cb) twitch.hook.prnt ('Channel Operator', chanop_cb) twitch.hook.prnt ('Channel DeOp', chanop_cb) twitch.hook.prnt ('Join', joinpart_cb) twitch.hook.prnt ('Part', joinpart_cb) twitch.hook.command('join', joincmd_cb) twitch.hook.prnt ('Capability Acknowledgement', joinpart_cb) twitch.hook.command('w', whispercmd_cb)<|fim▁end|>
<|file_name|>DefaultDialogActionButton.d.ts<|end_file_name|><|fim▁begin|>/// <reference types="react" /> import {DialogAction} from './types' export declare function DefaultDialogActionButton(props: {<|fim▁hole|> index: number onAction?: (action: DialogAction) => void }): JSX.Element<|fim▁end|>
action: DialogAction
<|file_name|>interval_timer.rs<|end_file_name|><|fim▁begin|>//! Timer to keep track of repeating intervals. /// This struct keeps track of passage of repeated intervals (like bars of music). pub struct IntervalTimer { every: u64, next: u64, } impl IntervalTimer { #[allow(missing_docs)] pub fn new(every: u64, next: u64) -> IntervalTimer { IntervalTimer { every: every, next: next, } } #[inline] /// Returns the number of intervals that have elapsed since last `update`. pub fn update(&mut self, current: u64) -> u64 { if current < self.next { 0 } else { let r = 1 + (current - self.next) / self.every; self.next += self.every * r;<|fim▁hole|> r } } } #[test] fn simple() { let mut timer = IntervalTimer::new(3, 3); let mut time = 2; assert_eq!(timer.update(time), 0); time += 2; assert_eq!(timer.update(time), 1); time += 2; assert_eq!(timer.update(time), 1); time += 6; assert_eq!(timer.update(time), 2); time += 3; assert_eq!(timer.update(time), 1); time += 2; assert_eq!(timer.update(time), 0); }<|fim▁end|>
<|file_name|>quest.101.js<|end_file_name|><|fim▁begin|>// // Speak To The Farmers ( 101 ) // var log = require('../class.log'), realmConfig = require('../../config.realm').config, quest = require('../class.quest'), questCondition = require('../class.questCondition').condition; exports.questObject = function( args ) { <|fim▁hole|> this.checkConditions = function( _args ) { var conditionsCompleted = 0; //see if condition is met var _callCondition = function( parameterName ) { self.conditions[parameterName].checkState({ characterId: _args.characterId, after: function() { conditionsCompleted++; if( conditionsCompleted < nrConditions ) { return; } quest.markCompleted({ characterId: _args.characterId, questId: self.id, questServer: args.questServer, after: function(){} }); } }); } var _checkAllConditions = function( ) { for( var i in self.conditions ) { _callCondition(i); } } //if a conditions value is already known, start the check with it if( "parameterName" in _args ) { if( self.conditions[ _args.parameterName ].targetValue > _args.value ) { return; } if( nrConditions == 1 ) { quest.markCompleted({ characterId: _args.characterId, questId: self.id, questServer: args.questServer, after: function(){} }); return; } } _checkAllConditions(); } // // Variables // this.id = 101; var nrConditions = 1; this.conditions['q101_1SpeakToTheFarmers'] = new questCondition({parameterName:'q101_1SpeakToTheFarmers', targetValue:1, quest: self, questServer: args.questServer}); return self; }<|fim▁end|>
var self = this; this.conditions = {};
<|file_name|>ops.py<|end_file_name|><|fim▁begin|>from .. import util from ..util import sqla_compat from . import schemaobj from sqlalchemy.types import NULLTYPE from .base import Operations, BatchOperations import re class MigrateOperation(object): """base class for migration command and organization objects. This system is part of the operation extensibility API. .. versionadded:: 0.8.0 .. seealso:: :ref:`operation_objects` :ref:`operation_plugins` :ref:`customizing_revision` """ @util.memoized_property def info(self): """A dictionary that may be used to store arbitrary information along with this :class:`.MigrateOperation` object. """ return {} class AddConstraintOp(MigrateOperation): """Represent an add constraint operation.""" @property def constraint_type(self): raise NotImplementedError() @classmethod def from_constraint(cls, constraint): funcs = { "unique_constraint": CreateUniqueConstraintOp.from_constraint, "foreign_key_constraint": CreateForeignKeyOp.from_constraint, "primary_key_constraint": CreatePrimaryKeyOp.from_constraint, "check_constraint": CreateCheckConstraintOp.from_constraint, "column_check_constraint": CreateCheckConstraintOp.from_constraint, } return funcs[constraint.__visit_name__](constraint) def reverse(self): return DropConstraintOp.from_constraint(self.to_constraint()) def to_diff_tuple(self): return ("add_constraint", self.to_constraint()) @Operations.register_operation("drop_constraint") @BatchOperations.register_operation("drop_constraint", "batch_drop_constraint") class DropConstraintOp(MigrateOperation): """Represent a drop constraint operation.""" def __init__( self, constraint_name, table_name, type_=None, schema=None, _orig_constraint=None): self.constraint_name = constraint_name self.table_name = table_name self.constraint_type = type_ self.schema = schema self._orig_constraint = _orig_constraint def reverse(self): if self._orig_constraint is None: raise ValueError( "operation is not reversible; " "original constraint is not present") return AddConstraintOp.from_constraint(self._orig_constraint) def to_diff_tuple(self): if self.constraint_type == "foreignkey": return ("remove_fk", self.to_constraint()) else: return ("remove_constraint", self.to_constraint()) @classmethod def from_constraint(cls, constraint): types = { "unique_constraint": "unique", "foreign_key_constraint": "foreignkey", "primary_key_constraint": "primary", "check_constraint": "check", "column_check_constraint": "check", } constraint_table = sqla_compat._table_for_constraint(constraint) return cls( constraint.name, constraint_table.name, schema=constraint_table.schema, type_=types[constraint.__visit_name__], _orig_constraint=constraint ) def to_constraint(self): if self._orig_constraint is not None: return self._orig_constraint else: raise ValueError( "constraint cannot be produced; " "original constraint is not present") @classmethod @util._with_legacy_names([ ("type", "type_"), ("name", "constraint_name"), ]) def drop_constraint( cls, operations, constraint_name, table_name, type_=None, schema=None): """Drop a constraint of the given name, typically via DROP CONSTRAINT. :param constraint_name: name of the constraint. :param table_name: table name. :param ``type_``: optional, required on MySQL. can be 'foreignkey', 'primary', 'unique', or 'check'. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> constraint_name """ op = cls(constraint_name, table_name, type_=type_, schema=schema) return operations.invoke(op) @classmethod def batch_drop_constraint(cls, operations, constraint_name, type_=None): """Issue a "drop constraint" instruction using the current batch migration context. The batch form of this call omits the ``table_name`` and ``schema`` arguments from the call. .. seealso:: :meth:`.Operations.drop_constraint` .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> constraint_name """ op = cls( constraint_name, operations.impl.table_name, type_=type_, schema=operations.impl.schema ) return operations.invoke(op) @Operations.register_operation("create_primary_key") @BatchOperations.register_operation( "create_primary_key", "batch_create_primary_key") class CreatePrimaryKeyOp(AddConstraintOp): """Represent a create primary key operation.""" constraint_type = "primarykey" def __init__( self, constraint_name, table_name, columns, schema=None, _orig_constraint=None, **kw): self.constraint_name = constraint_name self.table_name = table_name self.columns = columns self.schema = schema self._orig_constraint = _orig_constraint self.kw = kw @classmethod def from_constraint(cls, constraint): constraint_table = sqla_compat._table_for_constraint(constraint) return cls( constraint.name, constraint_table.name, constraint.columns, schema=constraint_table.schema, _orig_constraint=constraint ) def to_constraint(self, migration_context=None): if self._orig_constraint is not None: return self._orig_constraint schema_obj = schemaobj.SchemaObjects(migration_context) return schema_obj.primary_key_constraint( self.constraint_name, self.table_name, self.columns, schema=self.schema) @classmethod @util._with_legacy_names([ ('name', 'constraint_name'), ('cols', 'columns') ]) def create_primary_key( cls, operations, constraint_name, table_name, columns, schema=None): """Issue a "create primary key" instruction using the current migration context. e.g.:: from alembic import op op.create_primary_key( "pk_my_table", "my_table", ["id", "version"] ) This internally generates a :class:`~sqlalchemy.schema.Table` object containing the necessary columns, then generates a new :class:`~sqlalchemy.schema.PrimaryKeyConstraint` object which it then associates with the :class:`~sqlalchemy.schema.Table`. Any event listeners associated with this action will be fired off normally. The :class:`~sqlalchemy.schema.AddConstraint` construct is ultimately used to generate the ALTER statement. :param name: Name of the primary key constraint. The name is necessary so that an ALTER statement can be emitted. For setups that use an automated naming scheme such as that described at :ref:`sqla:constraint_naming_conventions` ``name`` here can be ``None``, as the event listener will apply the name to the constraint object when it is associated with the table. :param table_name: String name of the target table. :param columns: a list of string column names to be applied to the primary key constraint. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> constraint_name * cols -> columns """ op = cls(constraint_name, table_name, columns, schema) return operations.invoke(op) @classmethod def batch_create_primary_key(cls, operations, constraint_name, columns): """Issue a "create primary key" instruction using the current batch migration context. The batch form of this call omits the ``table_name`` and ``schema`` arguments from the call. .. seealso:: :meth:`.Operations.create_primary_key` """ op = cls( constraint_name, operations.impl.table_name, columns, schema=operations.impl.schema ) return operations.invoke(op) @Operations.register_operation("create_unique_constraint") @BatchOperations.register_operation( "create_unique_constraint", "batch_create_unique_constraint") class CreateUniqueConstraintOp(AddConstraintOp): """Represent a create unique constraint operation.""" constraint_type = "unique" def __init__( self, constraint_name, table_name, columns, schema=None, _orig_constraint=None, **kw): self.constraint_name = constraint_name self.table_name = table_name self.columns = columns self.schema = schema self._orig_constraint = _orig_constraint self.kw = kw @classmethod def from_constraint(cls, constraint): constraint_table = sqla_compat._table_for_constraint(constraint) kw = {} if constraint.deferrable: kw['deferrable'] = constraint.deferrable if constraint.initially: kw['initially'] = constraint.initially return cls( constraint.name, constraint_table.name, [c.name for c in constraint.columns], schema=constraint_table.schema, _orig_constraint=constraint, **kw ) def to_constraint(self, migration_context=None): if self._orig_constraint is not None: return self._orig_constraint schema_obj = schemaobj.SchemaObjects(migration_context) return schema_obj.unique_constraint( self.constraint_name, self.table_name, self.columns, schema=self.schema, **self.kw) @classmethod @util._with_legacy_names([ ('name', 'constraint_name'), ('source', 'table_name'), ('local_cols', 'columns'), ]) def create_unique_constraint( cls, operations, constraint_name, table_name, columns, schema=None, **kw): """Issue a "create unique constraint" instruction using the current migration context. e.g.:: from alembic import op op.create_unique_constraint("uq_user_name", "user", ["name"]) This internally generates a :class:`~sqlalchemy.schema.Table` object containing the necessary columns, then generates a new :class:`~sqlalchemy.schema.UniqueConstraint` object which it then associates with the :class:`~sqlalchemy.schema.Table`. Any event listeners associated with this action will be fired off normally. The :class:`~sqlalchemy.schema.AddConstraint` construct is ultimately used to generate the ALTER statement. :param name: Name of the unique constraint. The name is necessary so that an ALTER statement can be emitted. For setups that use an automated naming scheme such as that described at :ref:`sqla:constraint_naming_conventions`, ``name`` here can be ``None``, as the event listener will apply the name to the constraint object when it is associated with the table. :param table_name: String name of the source table. :param columns: a list of string column names in the source table. :param deferrable: optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> constraint_name * source -> table_name * local_cols -> columns """ op = cls( constraint_name, table_name, columns, schema=schema, **kw ) return operations.invoke(op) @classmethod @util._with_legacy_names([('name', 'constraint_name')]) def batch_create_unique_constraint( cls, operations, constraint_name, columns, **kw): """Issue a "create unique constraint" instruction using the current batch migration context. The batch form of this call omits the ``source`` and ``schema`` arguments from the call. .. seealso:: :meth:`.Operations.create_unique_constraint` .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> constraint_name """ kw['schema'] = operations.impl.schema op = cls( constraint_name, operations.impl.table_name, columns, **kw ) return operations.invoke(op) @Operations.register_operation("create_foreign_key") @BatchOperations.register_operation( "create_foreign_key", "batch_create_foreign_key") class CreateForeignKeyOp(AddConstraintOp): """Represent a create foreign key constraint operation.""" constraint_type = "foreignkey" def __init__( self, constraint_name, source_table, referent_table, local_cols, remote_cols, _orig_constraint=None, **kw): self.constraint_name = constraint_name self.source_table = source_table self.referent_table = referent_table self.local_cols = local_cols self.remote_cols = remote_cols self._orig_constraint = _orig_constraint self.kw = kw def to_diff_tuple(self): return ("add_fk", self.to_constraint()) @classmethod def from_constraint(cls, constraint): kw = {} if constraint.onupdate: kw['onupdate'] = constraint.onupdate if constraint.ondelete: kw['ondelete'] = constraint.ondelete if constraint.initially: kw['initially'] = constraint.initially if constraint.deferrable: kw['deferrable'] = constraint.deferrable if constraint.use_alter: kw['use_alter'] = constraint.use_alter source_schema, source_table, \ source_columns, target_schema, \ target_table, target_columns = sqla_compat._fk_spec(constraint) kw['source_schema'] = source_schema kw['referent_schema'] = target_schema return cls( constraint.name, source_table, target_table, source_columns, target_columns, _orig_constraint=constraint, **kw ) def to_constraint(self, migration_context=None): if self._orig_constraint is not None: return self._orig_constraint schema_obj = schemaobj.SchemaObjects(migration_context) return schema_obj.foreign_key_constraint( self.constraint_name, self.source_table, self.referent_table, self.local_cols, self.remote_cols, **self.kw) @classmethod @util._with_legacy_names([ ('name', 'constraint_name'), ('source', 'source_table'), ('referent', 'referent_table'), ]) def create_foreign_key(cls, operations, constraint_name, source_table, referent_table, local_cols, remote_cols, onupdate=None, ondelete=None, deferrable=None, initially=None, match=None, source_schema=None, referent_schema=None, **dialect_kw): """Issue a "create foreign key" instruction using the current migration context. e.g.:: from alembic import op op.create_foreign_key( "fk_user_address", "address", "user", ["user_id"], ["id"]) This internally generates a :class:`~sqlalchemy.schema.Table` object containing the necessary columns, then generates a new :class:`~sqlalchemy.schema.ForeignKeyConstraint` object which it then associates with the :class:`~sqlalchemy.schema.Table`. Any event listeners associated with this action will be fired off normally. The :class:`~sqlalchemy.schema.AddConstraint` construct is ultimately used to generate the ALTER statement. :param name: Name of the foreign key constraint. The name is necessary so that an ALTER statement can be emitted. For setups that use an automated naming scheme such as that described at :ref:`sqla:constraint_naming_conventions`, ``name`` here can be ``None``, as the event listener will apply the name to the constraint object when it is associated with the table. :param source_table: String name of the source table. :param referent_table: String name of the destination table. :param local_cols: a list of string column names in the source table. :param remote_cols: a list of string column names in the remote table. :param onupdate: Optional string. If set, emit ON UPDATE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT. :param ondelete: Optional string. If set, emit ON DELETE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT. :param deferrable: optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param source_schema: Optional schema name of the source table. :param referent_schema: Optional schema name of the destination table. .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> constraint_name * source -> source_table * referent -> referent_table """ op = cls( constraint_name, source_table, referent_table, local_cols, remote_cols, onupdate=onupdate, ondelete=ondelete, deferrable=deferrable, source_schema=source_schema, referent_schema=referent_schema, initially=initially, match=match, **dialect_kw ) return operations.invoke(op) @classmethod @util._with_legacy_names([ ('name', 'constraint_name'), ('referent', 'referent_table') ]) def batch_create_foreign_key( cls, operations, constraint_name, referent_table, local_cols, remote_cols,<|fim▁hole|> referent_schema=None, onupdate=None, ondelete=None, deferrable=None, initially=None, match=None, **dialect_kw): """Issue a "create foreign key" instruction using the current batch migration context. The batch form of this call omits the ``source`` and ``source_schema`` arguments from the call. e.g.:: with batch_alter_table("address") as batch_op: batch_op.create_foreign_key( "fk_user_address", "user", ["user_id"], ["id"]) .. seealso:: :meth:`.Operations.create_foreign_key` .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> constraint_name * referent -> referent_table """ op = cls( constraint_name, operations.impl.table_name, referent_table, local_cols, remote_cols, onupdate=onupdate, ondelete=ondelete, deferrable=deferrable, source_schema=operations.impl.schema, referent_schema=referent_schema, initially=initially, match=match, **dialect_kw ) return operations.invoke(op) @Operations.register_operation("create_check_constraint") @BatchOperations.register_operation( "create_check_constraint", "batch_create_check_constraint") class CreateCheckConstraintOp(AddConstraintOp): """Represent a create check constraint operation.""" constraint_type = "check" def __init__( self, constraint_name, table_name, condition, schema=None, _orig_constraint=None, **kw): self.constraint_name = constraint_name self.table_name = table_name self.condition = condition self.schema = schema self._orig_constraint = _orig_constraint self.kw = kw @classmethod def from_constraint(cls, constraint): constraint_table = sqla_compat._table_for_constraint(constraint) return cls( constraint.name, constraint_table.name, constraint.sqltext, schema=constraint_table.schema, _orig_constraint=constraint ) def to_constraint(self, migration_context=None): if self._orig_constraint is not None: return self._orig_constraint schema_obj = schemaobj.SchemaObjects(migration_context) return schema_obj.check_constraint( self.constraint_name, self.table_name, self.condition, schema=self.schema, **self.kw) @classmethod @util._with_legacy_names([ ('name', 'constraint_name'), ('source', 'table_name') ]) def create_check_constraint( cls, operations, constraint_name, table_name, condition, schema=None, **kw): """Issue a "create check constraint" instruction using the current migration context. e.g.:: from alembic import op from sqlalchemy.sql import column, func op.create_check_constraint( "ck_user_name_len", "user", func.len(column('name')) > 5 ) CHECK constraints are usually against a SQL expression, so ad-hoc table metadata is usually needed. The function will convert the given arguments into a :class:`sqlalchemy.schema.CheckConstraint` bound to an anonymous table in order to emit the CREATE statement. :param name: Name of the check constraint. The name is necessary so that an ALTER statement can be emitted. For setups that use an automated naming scheme such as that described at :ref:`sqla:constraint_naming_conventions`, ``name`` here can be ``None``, as the event listener will apply the name to the constraint object when it is associated with the table. :param table_name: String name of the source table. :param condition: SQL expression that's the condition of the constraint. Can be a string or SQLAlchemy expression language structure. :param deferrable: optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> constraint_name * source -> table_name """ op = cls(constraint_name, table_name, condition, schema=schema, **kw) return operations.invoke(op) @classmethod @util._with_legacy_names([('name', 'constraint_name')]) def batch_create_check_constraint( cls, operations, constraint_name, condition, **kw): """Issue a "create check constraint" instruction using the current batch migration context. The batch form of this call omits the ``source`` and ``schema`` arguments from the call. .. seealso:: :meth:`.Operations.create_check_constraint` .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> constraint_name """ op = cls( constraint_name, operations.impl.table_name, condition, schema=operations.impl.schema, **kw) return operations.invoke(op) @Operations.register_operation("create_index") @BatchOperations.register_operation("create_index", "batch_create_index") class CreateIndexOp(MigrateOperation): """Represent a create index operation.""" def __init__( self, index_name, table_name, columns, schema=None, unique=False, _orig_index=None, **kw): self.index_name = index_name self.table_name = table_name self.columns = columns self.schema = schema self.unique = unique self.kw = kw self._orig_index = _orig_index def reverse(self): return DropIndexOp.from_index(self.to_index()) def to_diff_tuple(self): return ("add_index", self.to_index()) @classmethod def from_index(cls, index): return cls( index.name, index.table.name, sqla_compat._get_index_expressions(index), schema=index.table.schema, unique=index.unique, _orig_index=index, **index.kwargs ) def to_index(self, migration_context=None): if self._orig_index: return self._orig_index schema_obj = schemaobj.SchemaObjects(migration_context) return schema_obj.index( self.index_name, self.table_name, self.columns, schema=self.schema, unique=self.unique, **self.kw) @classmethod @util._with_legacy_names([('name', 'index_name')]) def create_index( cls, operations, index_name, table_name, columns, schema=None, unique=False, **kw): """Issue a "create index" instruction using the current migration context. e.g.:: from alembic import op op.create_index('ik_test', 't1', ['foo', 'bar']) Functional indexes can be produced by using the :func:`sqlalchemy.sql.expression.text` construct:: from alembic import op from sqlalchemy import text op.create_index('ik_test', 't1', [text('lower(foo)')]) .. versionadded:: 0.6.7 support for making use of the :func:`~sqlalchemy.sql.expression.text` construct in conjunction with :meth:`.Operations.create_index` in order to produce functional expressions within CREATE INDEX. :param index_name: name of the index. :param table_name: name of the owning table. :param columns: a list consisting of string column names and/or :func:`~sqlalchemy.sql.expression.text` constructs. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. :param unique: If True, create a unique index. :param quote: Force quoting of this column's name on or off, corresponding to ``True`` or ``False``. When left at its default of ``None``, the column identifier will be quoted according to whether the name is case sensitive (identifiers with at least one upper case character are treated as case sensitive), or if it's a reserved word. This flag is only needed to force quoting of a reserved word which is not known by the SQLAlchemy dialect. :param \**kw: Additional keyword arguments not mentioned above are dialect specific, and passed in the form ``<dialectname>_<argname>``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> index_name """ op = cls( index_name, table_name, columns, schema=schema, unique=unique, **kw ) return operations.invoke(op) @classmethod def batch_create_index(cls, operations, index_name, columns, **kw): """Issue a "create index" instruction using the current batch migration context. .. seealso:: :meth:`.Operations.create_index` """ op = cls( index_name, operations.impl.table_name, columns, schema=operations.impl.schema, **kw ) return operations.invoke(op) @Operations.register_operation("drop_index") @BatchOperations.register_operation("drop_index", "batch_drop_index") class DropIndexOp(MigrateOperation): """Represent a drop index operation.""" def __init__( self, index_name, table_name=None, schema=None, _orig_index=None): self.index_name = index_name self.table_name = table_name self.schema = schema self._orig_index = _orig_index def to_diff_tuple(self): return ("remove_index", self.to_index()) def reverse(self): if self._orig_index is None: raise ValueError( "operation is not reversible; " "original index is not present") return CreateIndexOp.from_index(self._orig_index) @classmethod def from_index(cls, index): return cls( index.name, index.table.name, schema=index.table.schema, _orig_index=index ) def to_index(self, migration_context=None): if self._orig_index is not None: return self._orig_index schema_obj = schemaobj.SchemaObjects(migration_context) # need a dummy column name here since SQLAlchemy # 0.7.6 and further raises on Index with no columns return schema_obj.index( self.index_name, self.table_name, ['x'], schema=self.schema) @classmethod @util._with_legacy_names([ ('name', 'index_name'), ('tablename', 'table_name') ]) def drop_index(cls, operations, index_name, table_name=None, schema=None): """Issue a "drop index" instruction using the current migration context. e.g.:: drop_index("accounts") :param index_name: name of the index. :param table_name: name of the owning table. Some backends such as Microsoft SQL Server require this. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> index_name """ op = cls(index_name, table_name=table_name, schema=schema) return operations.invoke(op) @classmethod @util._with_legacy_names([('name', 'index_name')]) def batch_drop_index(cls, operations, index_name, **kw): """Issue a "drop index" instruction using the current batch migration context. .. seealso:: :meth:`.Operations.drop_index` .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> index_name """ op = cls( index_name, table_name=operations.impl.table_name, schema=operations.impl.schema ) return operations.invoke(op) @Operations.register_operation("create_table") class CreateTableOp(MigrateOperation): """Represent a create table operation.""" def __init__( self, table_name, columns, schema=None, _orig_table=None, **kw): self.table_name = table_name self.columns = columns self.schema = schema self.kw = kw self._orig_table = _orig_table def reverse(self): return DropTableOp.from_table(self.to_table()) def to_diff_tuple(self): return ("add_table", self.to_table()) @classmethod def from_table(cls, table): return cls( table.name, list(table.c) + list(table.constraints), schema=table.schema, _orig_table=table, **table.kwargs ) def to_table(self, migration_context=None): if self._orig_table is not None: return self._orig_table schema_obj = schemaobj.SchemaObjects(migration_context) return schema_obj.table( self.table_name, *self.columns, schema=self.schema, **self.kw ) @classmethod @util._with_legacy_names([('name', 'table_name')]) def create_table(cls, operations, table_name, *columns, **kw): """Issue a "create table" instruction using the current migration context. This directive receives an argument list similar to that of the traditional :class:`sqlalchemy.schema.Table` construct, but without the metadata:: from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column from alembic import op op.create_table( 'account', Column('id', INTEGER, primary_key=True), Column('name', VARCHAR(50), nullable=False), Column('description', NVARCHAR(200)), Column('timestamp', TIMESTAMP, server_default=func.now()) ) Note that :meth:`.create_table` accepts :class:`~sqlalchemy.schema.Column` constructs directly from the SQLAlchemy library. In particular, default values to be created on the database side are specified using the ``server_default`` parameter, and not ``default`` which only specifies Python-side defaults:: from alembic import op from sqlalchemy import Column, TIMESTAMP, func # specify "DEFAULT NOW" along with the "timestamp" column op.create_table('account', Column('id', INTEGER, primary_key=True), Column('timestamp', TIMESTAMP, server_default=func.now()) ) The function also returns a newly created :class:`~sqlalchemy.schema.Table` object, corresponding to the table specification given, which is suitable for immediate SQL operations, in particular :meth:`.Operations.bulk_insert`:: from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column from alembic import op account_table = op.create_table( 'account', Column('id', INTEGER, primary_key=True), Column('name', VARCHAR(50), nullable=False), Column('description', NVARCHAR(200)), Column('timestamp', TIMESTAMP, server_default=func.now()) ) op.bulk_insert( account_table, [ {"name": "A1", "description": "account 1"}, {"name": "A2", "description": "account 2"}, ] ) .. versionadded:: 0.7.0 :param table_name: Name of the table :param \*columns: collection of :class:`~sqlalchemy.schema.Column` objects within the table, as well as optional :class:`~sqlalchemy.schema.Constraint` objects and :class:`~.sqlalchemy.schema.Index` objects. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. :param \**kw: Other keyword arguments are passed to the underlying :class:`sqlalchemy.schema.Table` object created for the command. :return: the :class:`~sqlalchemy.schema.Table` object corresponding to the parameters given. .. versionadded:: 0.7.0 - the :class:`~sqlalchemy.schema.Table` object is returned. .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> table_name """ op = cls(table_name, columns, **kw) return operations.invoke(op) @Operations.register_operation("drop_table") class DropTableOp(MigrateOperation): """Represent a drop table operation.""" def __init__( self, table_name, schema=None, table_kw=None, _orig_table=None): self.table_name = table_name self.schema = schema self.table_kw = table_kw or {} self._orig_table = _orig_table def to_diff_tuple(self): return ("remove_table", self.to_table()) def reverse(self): if self._orig_table is None: raise ValueError( "operation is not reversible; " "original table is not present") return CreateTableOp.from_table(self._orig_table) @classmethod def from_table(cls, table): return cls(table.name, schema=table.schema, _orig_table=table) def to_table(self, migration_context=None): if self._orig_table is not None: return self._orig_table schema_obj = schemaobj.SchemaObjects(migration_context) return schema_obj.table( self.table_name, schema=self.schema, **self.table_kw) @classmethod @util._with_legacy_names([('name', 'table_name')]) def drop_table(cls, operations, table_name, schema=None, **kw): """Issue a "drop table" instruction using the current migration context. e.g.:: drop_table("accounts") :param table_name: Name of the table :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. :param \**kw: Other keyword arguments are passed to the underlying :class:`sqlalchemy.schema.Table` object created for the command. .. versionchanged:: 0.8.0 The following positional argument names have been changed: * name -> table_name """ op = cls(table_name, schema=schema, table_kw=kw) operations.invoke(op) class AlterTableOp(MigrateOperation): """Represent an alter table operation.""" def __init__(self, table_name, schema=None): self.table_name = table_name self.schema = schema @Operations.register_operation("rename_table") class RenameTableOp(AlterTableOp): """Represent a rename table operation.""" def __init__(self, old_table_name, new_table_name, schema=None): super(RenameTableOp, self).__init__(old_table_name, schema=schema) self.new_table_name = new_table_name @classmethod def rename_table( cls, operations, old_table_name, new_table_name, schema=None): """Emit an ALTER TABLE to rename a table. :param old_table_name: old name. :param new_table_name: new name. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. """ op = cls(old_table_name, new_table_name, schema=schema) return operations.invoke(op) @Operations.register_operation("alter_column") @BatchOperations.register_operation("alter_column", "batch_alter_column") class AlterColumnOp(AlterTableOp): """Represent an alter column operation.""" def __init__( self, table_name, column_name, schema=None, existing_type=None, existing_server_default=False, existing_nullable=None, modify_nullable=None, modify_server_default=False, modify_name=None, modify_type=None, **kw ): super(AlterColumnOp, self).__init__(table_name, schema=schema) self.column_name = column_name self.existing_type = existing_type self.existing_server_default = existing_server_default self.existing_nullable = existing_nullable self.modify_nullable = modify_nullable self.modify_server_default = modify_server_default self.modify_name = modify_name self.modify_type = modify_type self.kw = kw def to_diff_tuple(self): col_diff = [] schema, tname, cname = self.schema, self.table_name, self.column_name if self.modify_type is not None: col_diff.append( ("modify_type", schema, tname, cname, { "existing_nullable": self.existing_nullable, "existing_server_default": self.existing_server_default, }, self.existing_type, self.modify_type) ) if self.modify_nullable is not None: col_diff.append( ("modify_nullable", schema, tname, cname, { "existing_type": self.existing_type, "existing_server_default": self.existing_server_default }, self.existing_nullable, self.modify_nullable) ) if self.modify_server_default is not False: col_diff.append( ("modify_default", schema, tname, cname, { "existing_nullable": self.existing_nullable, "existing_type": self.existing_type }, self.existing_server_default, self.modify_server_default) ) return col_diff def has_changes(self): hc1 = self.modify_nullable is not None or \ self.modify_server_default is not False or \ self.modify_type is not None if hc1: return True for kw in self.kw: if kw.startswith('modify_'): return True else: return False def reverse(self): kw = self.kw.copy() kw['existing_type'] = self.existing_type kw['existing_nullable'] = self.existing_nullable kw['existing_server_default'] = self.existing_server_default if self.modify_type is not None: kw['modify_type'] = self.modify_type if self.modify_nullable is not None: kw['modify_nullable'] = self.modify_nullable if self.modify_server_default is not False: kw['modify_server_default'] = self.modify_server_default # TODO: make this a little simpler all_keys = set(m.group(1) for m in [ re.match(r'^(?:existing_|modify_)(.+)$', k) for k in kw ] if m) for k in all_keys: if 'modify_%s' % k in kw: swap = kw['existing_%s' % k] kw['existing_%s' % k] = kw['modify_%s' % k] kw['modify_%s' % k] = swap return self.__class__( self.table_name, self.column_name, schema=self.schema, **kw ) @classmethod @util._with_legacy_names([('name', 'new_column_name')]) def alter_column( cls, operations, table_name, column_name, nullable=None, server_default=False, new_column_name=None, type_=None, existing_type=None, existing_server_default=False, existing_nullable=None, schema=None, **kw ): """Issue an "alter column" instruction using the current migration context. Generally, only that aspect of the column which is being changed, i.e. name, type, nullability, default, needs to be specified. Multiple changes can also be specified at once and the backend should "do the right thing", emitting each change either separately or together as the backend allows. MySQL has special requirements here, since MySQL cannot ALTER a column without a full specification. When producing MySQL-compatible migration files, it is recommended that the ``existing_type``, ``existing_server_default``, and ``existing_nullable`` parameters be present, if not being altered. Type changes which are against the SQLAlchemy "schema" types :class:`~sqlalchemy.types.Boolean` and :class:`~sqlalchemy.types.Enum` may also add or drop constraints which accompany those types on backends that don't support them natively. The ``existing_server_default`` argument is used in this case as well to remove a previous constraint. :param table_name: string name of the target table. :param column_name: string name of the target column, as it exists before the operation begins. :param nullable: Optional; specify ``True`` or ``False`` to alter the column's nullability. :param server_default: Optional; specify a string SQL expression, :func:`~sqlalchemy.sql.expression.text`, or :class:`~sqlalchemy.schema.DefaultClause` to indicate an alteration to the column's default value. Set to ``None`` to have the default removed. :param new_column_name: Optional; specify a string name here to indicate the new name within a column rename operation. :param ``type_``: Optional; a :class:`~sqlalchemy.types.TypeEngine` type object to specify a change to the column's type. For SQLAlchemy types that also indicate a constraint (i.e. :class:`~sqlalchemy.types.Boolean`, :class:`~sqlalchemy.types.Enum`), the constraint is also generated. :param autoincrement: set the ``AUTO_INCREMENT`` flag of the column; currently understood by the MySQL dialect. :param existing_type: Optional; a :class:`~sqlalchemy.types.TypeEngine` type object to specify the previous type. This is required for all MySQL column alter operations that don't otherwise specify a new type, as well as for when nullability is being changed on a SQL Server column. It is also used if the type is a so-called SQLlchemy "schema" type which may define a constraint (i.e. :class:`~sqlalchemy.types.Boolean`, :class:`~sqlalchemy.types.Enum`), so that the constraint can be dropped. :param existing_server_default: Optional; The existing default value of the column. Required on MySQL if an existing default is not being changed; else MySQL removes the default. :param existing_nullable: Optional; the existing nullability of the column. Required on MySQL if the existing nullability is not being changed; else MySQL sets this to NULL. :param existing_autoincrement: Optional; the existing autoincrement of the column. Used for MySQL's system of altering a column that specifies ``AUTO_INCREMENT``. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. """ alt = cls( table_name, column_name, schema=schema, existing_type=existing_type, existing_server_default=existing_server_default, existing_nullable=existing_nullable, modify_name=new_column_name, modify_type=type_, modify_server_default=server_default, modify_nullable=nullable, **kw ) return operations.invoke(alt) @classmethod def batch_alter_column( cls, operations, column_name, nullable=None, server_default=False, new_column_name=None, type_=None, existing_type=None, existing_server_default=False, existing_nullable=None, **kw ): """Issue an "alter column" instruction using the current batch migration context. .. seealso:: :meth:`.Operations.add_column` """ alt = cls( operations.impl.table_name, column_name, schema=operations.impl.schema, existing_type=existing_type, existing_server_default=existing_server_default, existing_nullable=existing_nullable, modify_name=new_column_name, modify_type=type_, modify_server_default=server_default, modify_nullable=nullable, **kw ) return operations.invoke(alt) @Operations.register_operation("add_column") @BatchOperations.register_operation("add_column", "batch_add_column") class AddColumnOp(AlterTableOp): """Represent an add column operation.""" def __init__(self, table_name, column, schema=None): super(AddColumnOp, self).__init__(table_name, schema=schema) self.column = column def reverse(self): return DropColumnOp.from_column_and_tablename( self.schema, self.table_name, self.column) def to_diff_tuple(self): return ("add_column", self.schema, self.table_name, self.column) def to_column(self): return self.column @classmethod def from_column(cls, col): return cls(col.table.name, col, schema=col.table.schema) @classmethod def from_column_and_tablename(cls, schema, tname, col): return cls(tname, col, schema=schema) @classmethod def add_column(cls, operations, table_name, column, schema=None): """Issue an "add column" instruction using the current migration context. e.g.:: from alembic import op from sqlalchemy import Column, String op.add_column('organization', Column('name', String()) ) The provided :class:`~sqlalchemy.schema.Column` object can also specify a :class:`~sqlalchemy.schema.ForeignKey`, referencing a remote table name. Alembic will automatically generate a stub "referenced" table and emit a second ALTER statement in order to add the constraint separately:: from alembic import op from sqlalchemy import Column, INTEGER, ForeignKey op.add_column('organization', Column('account_id', INTEGER, ForeignKey('accounts.id')) ) Note that this statement uses the :class:`~sqlalchemy.schema.Column` construct as is from the SQLAlchemy library. In particular, default values to be created on the database side are specified using the ``server_default`` parameter, and not ``default`` which only specifies Python-side defaults:: from alembic import op from sqlalchemy import Column, TIMESTAMP, func # specify "DEFAULT NOW" along with the column add op.add_column('account', Column('timestamp', TIMESTAMP, server_default=func.now()) ) :param table_name: String name of the parent table. :param column: a :class:`sqlalchemy.schema.Column` object representing the new column. :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. """ op = cls(table_name, column, schema=schema) return operations.invoke(op) @classmethod def batch_add_column(cls, operations, column): """Issue an "add column" instruction using the current batch migration context. .. seealso:: :meth:`.Operations.add_column` """ op = cls( operations.impl.table_name, column, schema=operations.impl.schema ) return operations.invoke(op) @Operations.register_operation("drop_column") @BatchOperations.register_operation("drop_column", "batch_drop_column") class DropColumnOp(AlterTableOp): """Represent a drop column operation.""" def __init__( self, table_name, column_name, schema=None, _orig_column=None, **kw): super(DropColumnOp, self).__init__(table_name, schema=schema) self.column_name = column_name self.kw = kw self._orig_column = _orig_column def to_diff_tuple(self): return ( "remove_column", self.schema, self.table_name, self.to_column()) def reverse(self): if self._orig_column is None: raise ValueError( "operation is not reversible; " "original column is not present") return AddColumnOp.from_column_and_tablename( self.schema, self.table_name, self._orig_column) @classmethod def from_column_and_tablename(cls, schema, tname, col): return cls(tname, col.name, schema=schema, _orig_column=col) def to_column(self, migration_context=None): if self._orig_column is not None: return self._orig_column schema_obj = schemaobj.SchemaObjects(migration_context) return schema_obj.column(self.column_name, NULLTYPE) @classmethod def drop_column( cls, operations, table_name, column_name, schema=None, **kw): """Issue a "drop column" instruction using the current migration context. e.g.:: drop_column('organization', 'account_id') :param table_name: name of table :param column_name: name of column :param schema: Optional schema name to operate within. To control quoting of the schema outside of the default behavior, use the SQLAlchemy construct :class:`~sqlalchemy.sql.elements.quoted_name`. .. versionadded:: 0.7.0 'schema' can now accept a :class:`~sqlalchemy.sql.elements.quoted_name` construct. :param mssql_drop_check: Optional boolean. When ``True``, on Microsoft SQL Server only, first drop the CHECK constraint on the column using a SQL-script-compatible block that selects into a @variable from sys.check_constraints, then exec's a separate DROP CONSTRAINT for that constraint. :param mssql_drop_default: Optional boolean. When ``True``, on Microsoft SQL Server only, first drop the DEFAULT constraint on the column using a SQL-script-compatible block that selects into a @variable from sys.default_constraints, then exec's a separate DROP CONSTRAINT for that default. :param mssql_drop_foreign_key: Optional boolean. When ``True``, on Microsoft SQL Server only, first drop a single FOREIGN KEY constraint on the column using a SQL-script-compatible block that selects into a @variable from sys.foreign_keys/sys.foreign_key_columns, then exec's a separate DROP CONSTRAINT for that default. Only works if the column has exactly one FK constraint which refers to it, at the moment. .. versionadded:: 0.6.2 """ op = cls(table_name, column_name, schema=schema, **kw) return operations.invoke(op) @classmethod def batch_drop_column(cls, operations, column_name): """Issue a "drop column" instruction using the current batch migration context. .. seealso:: :meth:`.Operations.drop_column` """ op = cls( operations.impl.table_name, column_name, schema=operations.impl.schema) return operations.invoke(op) @Operations.register_operation("bulk_insert") class BulkInsertOp(MigrateOperation): """Represent a bulk insert operation.""" def __init__(self, table, rows, multiinsert=True): self.table = table self.rows = rows self.multiinsert = multiinsert @classmethod def bulk_insert(cls, operations, table, rows, multiinsert=True): """Issue a "bulk insert" operation using the current migration context. This provides a means of representing an INSERT of multiple rows which works equally well in the context of executing on a live connection as well as that of generating a SQL script. In the case of a SQL script, the values are rendered inline into the statement. e.g.:: from alembic import op from datetime import date from sqlalchemy.sql import table, column from sqlalchemy import String, Integer, Date # Create an ad-hoc table to use for the insert statement. accounts_table = table('account', column('id', Integer), column('name', String), column('create_date', Date) ) op.bulk_insert(accounts_table, [ {'id':1, 'name':'John Smith', 'create_date':date(2010, 10, 5)}, {'id':2, 'name':'Ed Williams', 'create_date':date(2007, 5, 27)}, {'id':3, 'name':'Wendy Jones', 'create_date':date(2008, 8, 15)}, ] ) When using --sql mode, some datatypes may not render inline automatically, such as dates and other special types. When this issue is present, :meth:`.Operations.inline_literal` may be used:: op.bulk_insert(accounts_table, [ {'id':1, 'name':'John Smith', 'create_date':op.inline_literal("2010-10-05")}, {'id':2, 'name':'Ed Williams', 'create_date':op.inline_literal("2007-05-27")}, {'id':3, 'name':'Wendy Jones', 'create_date':op.inline_literal("2008-08-15")}, ], multiinsert=False ) When using :meth:`.Operations.inline_literal` in conjunction with :meth:`.Operations.bulk_insert`, in order for the statement to work in "online" (e.g. non --sql) mode, the :paramref:`~.Operations.bulk_insert.multiinsert` flag should be set to ``False``, which will have the effect of individual INSERT statements being emitted to the database, each with a distinct VALUES clause, so that the "inline" values can still be rendered, rather than attempting to pass the values as bound parameters. .. versionadded:: 0.6.4 :meth:`.Operations.inline_literal` can now be used with :meth:`.Operations.bulk_insert`, and the :paramref:`~.Operations.bulk_insert.multiinsert` flag has been added to assist in this usage when running in "online" mode. :param table: a table object which represents the target of the INSERT. :param rows: a list of dictionaries indicating rows. :param multiinsert: when at its default of True and --sql mode is not enabled, the INSERT statement will be executed using "executemany()" style, where all elements in the list of dictionaries are passed as bound parameters in a single list. Setting this to False results in individual INSERT statements being emitted per parameter set, and is needed in those cases where non-literal values are present in the parameter sets. .. versionadded:: 0.6.4 """ op = cls(table, rows, multiinsert=multiinsert) operations.invoke(op) @Operations.register_operation("execute") class ExecuteSQLOp(MigrateOperation): """Represent an execute SQL operation.""" def __init__(self, sqltext, execution_options=None): self.sqltext = sqltext self.execution_options = execution_options @classmethod def execute(cls, operations, sqltext, execution_options=None): """Execute the given SQL using the current migration context. In a SQL script context, the statement is emitted directly to the output stream. There is *no* return result, however, as this function is oriented towards generating a change script that can run in "offline" mode. For full interaction with a connected database, use the "bind" available from the context:: from alembic import op connection = op.get_bind() Also note that any parameterized statement here *will not work* in offline mode - INSERT, UPDATE and DELETE statements which refer to literal values would need to render inline expressions. For simple use cases, the :meth:`.inline_literal` function can be used for **rudimentary** quoting of string values. For "bulk" inserts, consider using :meth:`.bulk_insert`. For example, to emit an UPDATE statement which is equally compatible with both online and offline mode:: from sqlalchemy.sql import table, column from sqlalchemy import String from alembic import op account = table('account', column('name', String) ) op.execute( account.update().\\ where(account.c.name==op.inline_literal('account 1')).\\ values({'name':op.inline_literal('account 2')}) ) Note above we also used the SQLAlchemy :func:`sqlalchemy.sql.expression.table` and :func:`sqlalchemy.sql.expression.column` constructs to make a brief, ad-hoc table construct just for our UPDATE statement. A full :class:`~sqlalchemy.schema.Table` construct of course works perfectly fine as well, though note it's a recommended practice to at least ensure the definition of a table is self-contained within the migration script, rather than imported from a module that may break compatibility with older migrations. :param sql: Any legal SQLAlchemy expression, including: * a string * a :func:`sqlalchemy.sql.expression.text` construct. * a :func:`sqlalchemy.sql.expression.insert` construct. * a :func:`sqlalchemy.sql.expression.update`, :func:`sqlalchemy.sql.expression.insert`, or :func:`sqlalchemy.sql.expression.delete` construct. * Pretty much anything that's "executable" as described in :ref:`sqlexpression_toplevel`. :param execution_options: Optional dictionary of execution options, will be passed to :meth:`sqlalchemy.engine.Connection.execution_options`. """ op = cls(sqltext, execution_options=execution_options) return operations.invoke(op) class OpContainer(MigrateOperation): """Represent a sequence of operations operation.""" def __init__(self, ops=()): self.ops = ops def is_empty(self): return not self.ops def as_diffs(self): return list(OpContainer._ops_as_diffs(self)) @classmethod def _ops_as_diffs(cls, migrations): for op in migrations.ops: if hasattr(op, 'ops'): for sub_op in cls._ops_as_diffs(op): yield sub_op else: yield op.to_diff_tuple() class ModifyTableOps(OpContainer): """Contains a sequence of operations that all apply to a single Table.""" def __init__(self, table_name, ops, schema=None): super(ModifyTableOps, self).__init__(ops) self.table_name = table_name self.schema = schema def reverse(self): return ModifyTableOps( self.table_name, ops=list(reversed( [op.reverse() for op in self.ops] )), schema=self.schema ) class UpgradeOps(OpContainer): """contains a sequence of operations that would apply to the 'upgrade' stream of a script. .. seealso:: :ref:`customizing_revision` """ def reverse_into(self, downgrade_ops): downgrade_ops.ops[:] = list(reversed( [op.reverse() for op in self.ops] )) return downgrade_ops def reverse(self): return self.reverse_into(DowngradeOps(ops=[])) class DowngradeOps(OpContainer): """contains a sequence of operations that would apply to the 'downgrade' stream of a script. .. seealso:: :ref:`customizing_revision` """ def reverse(self): return UpgradeOps( ops=list(reversed( [op.reverse() for op in self.ops] )) ) class MigrationScript(MigrateOperation): """represents a migration script. E.g. when autogenerate encounters this object, this corresponds to the production of an actual script file. A normal :class:`.MigrationScript` object would contain a single :class:`.UpgradeOps` and a single :class:`.DowngradeOps` directive. .. seealso:: :ref:`customizing_revision` """ def __init__( self, rev_id, upgrade_ops, downgrade_ops, message=None, imports=None, head=None, splice=None, branch_label=None, version_path=None, depends_on=None): self.rev_id = rev_id self.message = message self.imports = imports self.head = head self.splice = splice self.branch_label = branch_label self.version_path = version_path self.depends_on = depends_on self.upgrade_ops = upgrade_ops self.downgrade_ops = downgrade_ops<|fim▁end|>
<|file_name|>aslam_buoys.py<|end_file_name|><|fim▁begin|>from mission.constants.config import PIPE_SEARCH_DEPTH from mission.framework.combinators import * from mission.framework.primitive import * from mission.framework.position import * from mission.framework.movement import * from mission.framework.task import * from mission.framework.timing import * from mission.framework.wiggling import * from mission.constants.config import * from mission.missions.ozer_common import SequentialSuccess, Conditional, Retry from mission.opt_aux.aux import * from mission.missions.buoys import Scuttle import aslam import shm, time, math import numpy as n from auv_math.math_utils import rotate class GoToPipe(Task): """ Move to and align with the pipe after buoys """ def on_first_run(self, *args, **kwargs): pipe_results = shm.buoys_pipe_results.get() self.task = Sequential( Log('Returning to pipe position'), GoToPosition( pipe_results.north, pipe_results.east, depth=pipe_results.depth, optimize=True, ), Log('Aligning with pipe'), Heading(pipe_results.heading), ) def on_run(self, *args, **kwargs): if not self.task.finished: self.task() else: self.finish() class Timeout(Task): def on_first_run(self, time, task, *args, **kwargs): self.timer = Timer(time) def on_run(self, time, task, *args, **kwargs): task() self.timer() if task.finished: self.finish() elif self.timer.finished: self.logw('Task timed out in {} seconds!'.format(time)) self.finish() # Will simply override the desired depth set by a task directly after it is called. class MinDepth(Task): def on_run(self, min_depth, subtask): actual = shm.kalman.depth.get() if actual > min_depth: subtask() else: self.logw('Actual depth {} less than minimum of {}; NOT running task!'.format(actual, min_depth)) desire = shm.desires.depth.get() if desire < min_depth: self.logw('Desired depth {} less than minimum of {}; overriding with minimum!'.format(desire, min_depth)) shm.desires.depth.set(min_depth) if subtask.finished: self.finish() class GrabHeading(Task): def on_run(self): heading = shm.kalman.heading.get() self.logw('Grabbed current sub heading of {}'.format(heading)) shm.buoys_mission.heading.set(heading) self.finish() class GrabPosition(Task): def on_run(self): pos = aslam.sub.position() self.logw('Grabbed position of N {}, E {}, D {}'.format(pos[0], pos[1], pos[2])) shm.buoys_mission.north.set(pos[0]) shm.buoys_mission.east.set(pos[1]) shm.buoys_mission.depth.set(pos[2]) self.finish() class RestoreHeading(Task): def on_first_run(self): self.saved = shm.buoys_mission.heading.get() self.logw('Restoring sub heading of {}'.format(self.saved)) def on_run(self): task = Heading(self.saved) task() if task.finished: self.finish() class RestorePosition(Task): def on_first_run(self): self.saved = [shm.buoys_mission.north.get(), shm.buoys_mission.east.get(), shm.buoys_mission.depth.get()] self.logw('Restoring saved position of N {}, E {}, D {}'.format(*self.saved)) def on_run(self): task = GoToPosition(self.saved[0], self.saved[1], depth = self.saved[2]) task() if task.finished: self.finish() Scan = Sequential( MoveYRough(2.0), MoveYRough(-4.0), MoveYRough(4.0), MoveYRough(-4.0), MoveYRough(2.0) ) boundingBox = lambda pos: (pos - n.array([0.2, 0.2, 0.2]), pos + n.array([0.2, 0.2, 0.2])) tolerance = n.array([0.05, 0.05, 0.05]) class TouchGuarded(Task): def on_run(self, subtask, sensor): subtask() if subtask.finished or not sensor.get(): self.finish() class AvoidYellow(Task): def on_first_run(self): self.heading = shm.kalman.heading.get() self.red_buoy = aslam.world.red_buoy.position()[:2] self.green_buoy = aslam.world.green_buoy.position()[:2] self.yellow_buoy = aslam.world.yellow_buoy.position()[:2] self.all_buoys = [('red', self.red_buoy), ('green', self.green_buoy), ('yellow', self.yellow_buoy)] self.sorted_buoys = sorted(self.all_buoys, key = lambda x: rotate(x[1], -self.heading)[1]) self.logi('Sorted buoys (left-to-right): {}'.format([x[0] for x in self.sorted_buoys])) subtasks = [] subtasks.append(MasterConcurrent(HPRWiggle(), MoveXRough(-1.0))) subtasks.append(Depth(PIPE_SEARCH_DEPTH)) if self.sorted_buoys[0][0] == 'yellow': # yellow buoy far left, go right subtasks.append(MoveYRough(1.0)) elif self.sorted_buoys[1][0] == 'yellow': subtasks.append(MoveYRough(1.0)) else: subtasks.append(MoveYRough(-1.0)) subtasks.append(MoveXRough(1.0)) center_buoy = n.array(self.sorted_buoys[1][1]) center_buoy += n.array(rotate((1, 0), self.heading)) # 1m beyond center buoy subtasks.append(GoToPosition(center_buoy[0], center_buoy[1], depth=PIPE_SEARCH_DEPTH)) self.subtask = Sequential(*subtasks) def on_run(self): self.subtask() if self.subtask.finished: self.finish() class AllBuoys(Task): def desiredModules(self): return [shm.vision_modules.Buoys] def on_first_run(self): self.has_made_progress = False shm.navigation_settings.optimize.set(False) delta_red = aslam.world.red_buoy.position() - aslam.sub.position() delta_red /= n.linalg.norm(delta_red) delta_red *= -1 delta_green = aslam.world.green_buoy.position() - aslam.sub.position() delta_green /= n.linalg.norm(delta_green) delta_green *= -1 delta_yellow = aslam.world.yellow_buoy.position() - aslam.sub.position() delta_yellow /= n.linalg.norm(delta_yellow) delta_yellow *= -1 subtasks = [] # subtasks.append(GoToPipe()) subtasks.append(MoveXRough(PIPE_TO_BUOYS_DIST)) subtasks.append(Depth(BUOY_SEARCH_DEPTH)) subtasks.append(GrabPosition()) subtasks.append(GrabHeading()) subtasks.append(Scan) if 1: subtasks += [ Timeout(20.0, SequentialSuccess( aslam.Target(aslam.world.red_buoy, delta_red, tolerance, boundingBox(delta_red * 2), orient = True)), RelativeToInitialDepth(0.05), Timeout(5.0, TouchGuarded(MoveXRough(1.3), shm.gpio.wall_1)), ), RestorePosition(),<|fim▁hole|> if 1: subtasks += [ Timeout(20.0, SequentialSuccess( aslam.Target(aslam.world.green_buoy, delta_green, tolerance, boundingBox(delta_green * 2), orient = True)), RelativeToInitialDepth(0.1), Timeout(5.0, TouchGuarded(MoveXRough(1.3), shm.gpio.wall_1)), ), RestorePosition(), RestoreHeading() ] if 1: subtasks += [ Timeout(20.0, SequentialSuccess( aslam.Target(aslam.world.yellow_buoy, delta_yellow, tolerance, boundingBox(delta_yellow * 2), orient = True)), RelativeToInitialDepth(0.1), GuardedTimer(10.0, Scuttle(), aslam.SimpleTarget(aslam.world.yellow_buoy, delta_yellow)), ), RestorePosition(), RestoreHeading(), AvoidYellow() ] subtasks.append(RestoreHeading()) self.subtask = MinDepth(0.1, Sequential(*subtasks)) def on_run(self): self.subtask() if self.subtask.finished: self.finish()<|fim▁end|>
RestoreHeading() ]
<|file_name|>ufcs-explicit-self-bad.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. struct Foo { f: int, } impl Foo { fn foo(self: int, x: int) -> int { //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` self.f + x } } struct Bar<T> { f: T, } impl<T> Bar<T> { fn foo(self: Bar<int>, x: int) -> int { //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` x } fn bar(self: &Bar<uint>, x: int) -> int { //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` x } } fn main() {<|fim▁hole|> let bar = box Bar { f: 1, }; println!("{} {}", bar.foo(2), bar.bar(2)); }<|fim▁end|>
let foo = box Foo { f: 1, }; println!("{}", foo.foo(2));
<|file_name|>reverse_lists.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on Jul 1, 2014 @author: anroco I have a list in python and I want to invest the elements, ie the latter is the first, how I can do? <|fim▁hole|>Tengo una lista en python y quiero invertir los elementos de la lista, es decir que el último sea el primero, ¿como puedo hacerlo? ''' #create a list lista = [9, 2, 5, 10, 9, 1, 3] print (lista) #reverses the order of the list lista.reverse() print (lista) #create a list lista = ['abc', 'a', 'bcd', 'c', 'bb', 'abcd'] print (lista) #reverses the order of the list lista.reverse() print (lista)<|fim▁end|>
<|file_name|>bind_rel_test.cpp<|end_file_name|><|fim▁begin|>#include <boost/config.hpp> #if defined(BOOST_MSVC) #pragma warning(disable: 4786) // identifier truncated in debug info #pragma warning(disable: 4710) // function not inlined #pragma warning(disable: 4711) // function selected for automatic inline expansion #pragma warning(disable: 4514) // unreferenced inline removed #endif // // bind_rel_test.cpp - ==, !=, <, <=, >, >= operators // // Copyright (c) 2005 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <boost/bind.hpp> #if defined(BOOST_MSVC) && (BOOST_MSVC < 1300) #pragma warning(push, 3) #endif #include <iostream> #if defined(BOOST_MSVC) && (BOOST_MSVC < 1300) #pragma warning(pop) #endif #include <boost/detail/lightweight_test.hpp> int f( int x ) { return x + x; } int g( int x ) { return 2 * x; } int main() { int x = 4; int y = x + x; // bind op value <|fim▁hole|> BOOST_TEST( ( boost::bind( f, _1 ) < y + 1 )( x ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) > y )( x ) ) ); BOOST_TEST( ( boost::bind( f, _1 ) > y - 1 )( x ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) <= y - 1 )( x ) ) ); BOOST_TEST( ( boost::bind( f, _1 ) <= y )( x ) ); BOOST_TEST( ( boost::bind( f, _1 ) <= y + 1 )( x ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) >= y + 1 )( x ) ) ); BOOST_TEST( ( boost::bind( f, _1 ) >= y )( x ) ); BOOST_TEST( ( boost::bind( f, _1 ) >= y - 1 )( x ) ); // bind op ref BOOST_TEST( ( boost::bind( f, _1 ) == boost::ref( y ) )( x ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) != boost::ref( y ) )( x ) ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) < boost::ref( y ) )( x ) ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) > boost::ref( y ) )( x ) ) ); BOOST_TEST( ( boost::bind( f, _1 ) <= boost::ref( y ) )( x ) ); BOOST_TEST( ( boost::bind( f, _1 ) >= boost::ref( y ) )( x ) ); // bind op placeholder BOOST_TEST( ( boost::bind( f, _1 ) == _2 )( x, y ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) != _2 )( x, y ) ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) < _2 )( x, y ) ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) > _2 )( x, y ) ) ); BOOST_TEST( ( boost::bind( f, _1 ) <= _2 )( x, y ) ); BOOST_TEST( ( boost::bind( f, _1 ) >= _2 )( x, y ) ); // bind op bind // important: bind( f, _1 ) and bind( g, _1 ) have the same type BOOST_TEST( ( boost::bind( f, _1 ) == boost::bind( g, _1 ) )( x ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) != boost::bind( g, _1 ) )( x ) ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) < boost::bind( g, _1 ) )( x ) ) ); BOOST_TEST( ( boost::bind( f, _1 ) <= boost::bind( g, _1 ) )( x ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) > boost::bind( g, _1 ) )( x ) ) ); BOOST_TEST( ( boost::bind( f, _1 ) >= boost::bind( g, _1 ) )( x ) ); return boost::report_errors(); }<|fim▁end|>
BOOST_TEST( ( boost::bind( f, _1 ) == y )( x ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) != y )( x ) ) ); BOOST_TEST( !( ( boost::bind( f, _1 ) < y )( x ) ) );
<|file_name|>test-paths.py<|end_file_name|><|fim▁begin|>from . import common import os import hglib class test_paths(common.basetest): def test_basic(self): f = open('.hg/hgrc', 'a') f.write('[paths]\nfoo = bar\n') f.close() # hgrc isn't watched for changes yet, have to reopen self.client = hglib.open() paths = self.client.paths() self.assertEquals(len(paths), 1) self.assertEquals(paths['foo'], os.path.abspath('bar'))<|fim▁hole|> self.assertEquals(self.client.paths('foo'), os.path.abspath('bar'))<|fim▁end|>
<|file_name|>struct-seq-value-type.ts<|end_file_name|><|fim▁begin|>import { StructProperty } from './struct-property'; /** * REDHAWK StructSeq Property values is a list of Structs<|fim▁hole|><|fim▁end|>
*/ export type StructSeqValueType = Array<StructProperty>;
<|file_name|>antiFloodBot.py<|end_file_name|><|fim▁begin|>import os import time import json import pprint from util import hook def readConfig(): ### Read config json and parse it confJson = None with open(os.getcwd() + '/antiFloodBotConfig.json', 'r') as confFile: confJson = confFile.read() return json.loads(confJson) inputs = {} #store time (unixtimestamp in sec) of every entry sent by user in map where key is user nickname kicked = [] #store nicknames of kicked users conf = readConfig() timeIntervalScope = conf['timeIntervalScope'] # interval when entries are collected [sec] entryThreshold = conf['entryThreshold'] #how many entries are allowed in timeIntervalScope logFile = conf['logFile'] @hook.event('PRIVMSG') def antiFlood(inp, nick=None, msg=None, conn=None, chan=None): if (nick not in inputs): inputs[nick] = [] currentTime = time.time() timeThreshold = currentTime - timeIntervalScope inputs[nick].append(currentTime) inputs[nick] = filter(lambda x: x > timeThreshold, inputs[nick]) #filter out every entry older than 8 sec (threshold) if len(inputs[nick]) >= entryThreshold: #if user has good day, kick one explanationMessage = conf['kickMessage'] file = open(logFile, 'a') file.write('Trying to kick %s on channel %s \n' % (nick, chan)) if nick in kicked: explanationMessage = conf['banMessage'] out = "MODE %s +b %s" % (chan, nick) conn.send(out) file.write('%s is kicked with ban \n' % (nick)) out = "KICK %s %s : %s" % (chan, nick, explanationMessage) conn.send(out) kicked.append(nick) file.close() #todo #if the same user joins again within 24 hour and keeps spamming temp ban in XX time. #step 3) if the same user joins after the removal of the ban and spams, permanent ban. @hook.event('PRIVMSG') def paramDump(inp, nick=None, msg=None, conn=None, chan=None): def saveToFile(file, label, obj): file.write("===== " + label + " ======== \n") file.write("type " + str(type (obj)) + " ========\n") file.write("methods " + str(dir(obj)) + " ========\n") file.write("properties ========\n") pprint.pprint(obj, file) file.write("\n\n\n") file = open(logFile, 'a') <|fim▁hole|> saveToFile(file, "chan", chan) saveToFile(file, "conn", conn) file.close() @hook.event("004") def onConnect(param, conn=None, raw=None): conn.send("Antiflod bot is ready")<|fim▁end|>
saveToFile(file, "inp", inp) saveToFile(file, "nick", nick) saveToFile(file, "msg", msg)
<|file_name|>kernel.go<|end_file_name|><|fim▁begin|>// Copyright 2017 Yanni Coroneos. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "../../embedded" "fmt" "runtime" "syscall" ) /* * This is the entry point of GERT. dont try anything fancy */ //go:nosplit func Entry() { runtime.Armhackmode = 1 runtime.Runtime_main() } //the runtime calls main after it's done setting up func main() { //test things like channels and whatnot fmt.Printf("self tests ...") self_tests() fmt.Printf("done!\n") //print out some warnings for myself so I dont forget possibly sketchy things I have done fmt.Printf("warnings ...") self_warnings() fmt.Printf("done!\n") //init the GIC and turn on interrupts fmt.Printf("pre-init ...") pre_init() syscall.Setenv("TZ", "UTC") runtime.Booted = 1 fmt.Printf("done!\n") //user-provided init code fmt.Printf("user init ...") user_init() fmt.Printf("done!\n") //user main loop<|fim▁hole|> user_loop() } panic("user loop broke out") } //add things here if you think they are critical for functionality func self_tests() { fmt.Println("Hi from fmt") channel := make(chan string, 1) channel <- "channel test pass" val := <-channel fmt.Println(val) go func(resp chan string) { fmt.Println("print from inside goroutine") resp <- "send channel from inside a goroutine" }(channel) val = <-channel fmt.Println(val) } //I never read the git logs. Now I dont have to func self_warnings() { //fmt.Println("REMEMBER THAT SKETCHY THING YOU DID WITH MAPPING AN EXTRA PAGE IN MAP_REGION") } //If a user doesnt want IRQs then they should never enable one. The GIC will just be ON but do nothing func pre_init() { //enable GIC embedded.GIC_init(false) //set IRQ callback function runtime.SetIRQcallback(irq) //Release spinning cpus runtime.Release(3) //unmap the first page runtime.Unmap_region(0x0, 0x0, 0x100000) }<|fim▁end|>
for {
<|file_name|>BLASTing.py<|end_file_name|><|fim▁begin|>####### LICENSE ####### # This code is part of the Recombineering module, written by Gregory # Moyerbrailean at Michigan State University, Department of Microbiology # and Molecular Genetics. # Copyright (C) 2010 Gregory Moyerbrailean # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. '''Handles the local BLAST and the parsing of the results. The BLAST uses the NCBI blast+ command-line tools to run a local BLAST against the organism's genome. In the event that a closed genome is not available for a species, the genome of a closely related strain can be used in its place. When a hit has been found, the parser function will extract and return relevant information regarding the corresponding gene. Alternatively, the user may specify to disable the BLAST function. In this case, the module will use the scaffold files to extract the necessary information. The user therefore does not have to have the blast+ command-line tools. However, the user will also not be able to run organisms such as L. reuteri against a similar genome, as this method requires exact gene matches.''' import subprocess from Bio.Blast.Applications import NcbiblastnCommandline as ncl from Bio.Blast import NCBIXML as nxml def BlastGenome(queryFile,genome,debug,outputFile='Files/extras/temp_blast.xml'): if debug: print "In BLASTing.BlastGenome" # Modify the genome filename to reflect the path to the genome genome = genome.replace(' ','') genomePath = 'Files/genome/' + genome + '/' + genome ## Call blast+ from python cline = ncl(query=queryFile,db=genomePath,out=outputFile,outfmt=5) ret_code = subprocess.call(str(cline),shell=True) if ret_code: print 'BLASTing file "%s" returned error code %s' % (queryFile,ret_code) temp = open(queryFile).read() geneID = temp.split()[0] geneID = geneID.lstrip('>') result = nxml.read(open(outputFile)) # If the blast returns no results, it will be treated as a gene # in the ambiguous region and oligos will be made from both strands if result.alignments: return parseRecord(result,genomePath,debug) else: return 0,0,'Ambiguous','No Match','N/A' def parseRecord(xmlfile,genomePath,debug): if debug: print "In BLASTing.parseRecord" result = nxml.read(open('Files/extras/temp_blast.xml')) hit = result.alignments[0].hit_def e = result.descriptions[0].e if debug: print "Blast match: ",hit print "E-value: ",e hitL = hit.split() hitID = hitL[0] t = [n for n in hitL if '..' in n] hitInfo = t[0] num1,num2 = hitInfo.split('..') num2 = num2[:num2.find('(')] num1,num2 = int(num1),int(num2) strand = hitInfo[hitInfo.find('('):] # Determine the direction, relative location, and position of the gene direction = getDirection(hitInfo) termUpper,termLower = getRelativeLocation(genomePath) pos = getLocation(num1,termUpper,termLower) # TODO # Integrate warning for multiple hits return num1,direction,pos,hit,e,'' def SearchGenome(queryFile,genomeName,debug): from Bio import SeqIO genomePath = 'Files/genome/'+genomeName+'/'+genomeName genome = openGenome(genomePath) high,low = getRelativeLocation(genomePath) gene = SeqIO.read(open(queryFile),'fasta') geneStr = str(gene.seq) geneComp = str(gene.seq.reverse_complement()) count = 0 if geneStr in genome: direction = 'forward' n = genome.find(geneStr) pos = getLocation(n,high,low) count += genome.count(geneStr) elif geneComp in genome: direction = 'reverse' n = genome.find(geneComp) pos = getLocation(n,high,low) count += genome.count(geneComp) else: return 0,0,'Ambiguous','No Match','N/A','' # If the gene sequence is present more than once, issue a warning bWarn = 'Warning: Gene sequence detected multiple times in genome' return n,direction,pos,'No BLAST data','No BLAST data',bWarn def getRelativeLocation(genomePath): l,t = getTermRegion(genomePath+'.txt')<|fim▁hole|> high = t + buff low = t - buff return high,low def getTermRegion(path): fd = open(path) info = fd.read() l,t = info.split('\n') l,t = int(l),int(t) return l,t def getDirection(line): if '(+)' in line: d = 'forward' elif '(-)' in line: d = 'reverse' return d def getLocation(num,high,low): if num < low: p = 'Early' elif num > high: p = 'Late' else: p = 'Ambiguous' return p def openGenome(gpath): fd = open(gpath+'.fasta') g = fd.read() g = g.replace('\n','') return g<|fim▁end|>
buff = 0.05 * l
<|file_name|>Test8570.java<|end_file_name|><|fim▁begin|>package org.gradle.test.performance.mediummonolithicjavaproject.p428; import org.junit.Test; import static org.junit.Assert.*; public class Test8570 { Production8570 objectUnderTest = new Production8570(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() {<|fim▁hole|> String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }<|fim▁end|>