text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
c = get_config() #------------------------------------------------------------------------------ # InteractiveShellApp configuration #------------------------------------------------------------------------------ # A Mixin for applications that start InteractiveShell instances. # # Provides configurables for loading extensions and executing files as part of # configuring a Shell environment. # # The following methods should be called by the :meth:`initialize` method of the # subclass: # # - :meth:`init_path` # - :meth:`init_shell` (to be implemented by the subclass) # - :meth:`init_gui_pylab` # - :meth:`init_extensions` # - :meth:`init_code` # lines of code to run at IPython startup. # c.InteractiveShellApp.exec_lines = [] # Should variables loaded at startup (by startup files, exec_lines, etc.) be # hidden from tools like %who? # c.InteractiveShellApp.hide_initial_ns = True # A list of dotted module names of IPython extensions to load. # c.InteractiveShellApp.extensions = [] # Enable GUI event loop integration with any of ('glut', 'gtk', 'gtk3', 'osx', # 'pyglet', 'qt', 'qt5', 'tk', 'wx'). # c.InteractiveShellApp.gui = None # A file to be run # c.InteractiveShellApp.file_to_run = '' # Configure matplotlib for interactive use with the default matplotlib backend. # c.InteractiveShellApp.matplotlib = None # Reraise exceptions encountered loading IPython extensions? # c.InteractiveShellApp.reraise_ipython_extension_failures = False # Run the file referenced by the PYTHONSTARTUP environment variable at IPython # startup. # c.InteractiveShellApp.exec_PYTHONSTARTUP = True # Pre-load matplotlib and numpy for interactive use, selecting a particular # matplotlib backend and loop integration. # c.InteractiveShellApp.pylab = None # Run the module as a script. # c.InteractiveShellApp.module_to_run = '' # dotted module name of an IPython extension to load. # c.InteractiveShellApp.extra_extension = '' # List of files to run at IPython startup. # c.InteractiveShellApp.exec_files = [] # If true, IPython will populate the user namespace with numpy, pylab, etc. and # an ``import *`` is done from numpy and pylab, when using pylab mode. # # When False, pylab mode should not import any names into the user namespace. # c.InteractiveShellApp.pylab_import_all = True # Execute the given command string. # c.InteractiveShellApp.code_to_run = '' #------------------------------------------------------------------------------ # TerminalIPythonApp configuration #------------------------------------------------------------------------------ # TerminalIPythonApp will inherit config from: BaseIPythonApplication, # Application, InteractiveShellApp # Should variables loaded at startup (by startup files, exec_lines, etc.) be # hidden from tools like %who? # c.TerminalIPythonApp.hide_initial_ns = True # A list of dotted module names of IPython extensions to load. # c.TerminalIPythonApp.extensions = [] # Execute the given command string. # c.TerminalIPythonApp.code_to_run = '' # The date format used by logging formatters for %(asctime)s # c.TerminalIPythonApp.log_datefmt = '%Y-%m-%d %H:%M:%S' # Reraise exceptions encountered loading IPython extensions? # c.TerminalIPythonApp.reraise_ipython_extension_failures = False # Set the log level by value or name. # c.TerminalIPythonApp.log_level = 30 # Run the file referenced by the PYTHONSTARTUP environment variable at IPython # startup. # c.TerminalIPythonApp.exec_PYTHONSTARTUP = True # Pre-load matplotlib and numpy for interactive use, selecting a particular # matplotlib backend and loop integration. # c.TerminalIPythonApp.pylab = None # Run the module as a script. # c.TerminalIPythonApp.module_to_run = '' # Whether to display a banner upon starting IPython. # c.TerminalIPythonApp.display_banner = True # dotted module name of an IPython extension to load. # c.TerminalIPythonApp.extra_extension = '' # Create a massive crash report when IPython encounters what may be an internal # error. The default is to append a short message to the usual traceback # c.TerminalIPythonApp.verbose_crash = False # Whether to overwrite existing config files when copying # c.TerminalIPythonApp.overwrite = False # The IPython profile to use. # c.TerminalIPythonApp.profile = 'default' # If a command or file is given via the command-line, e.g. 'ipython foo.py', # start an interactive shell after executing the file or command. # c.TerminalIPythonApp.force_interact = False # List of files to run at IPython startup. # c.TerminalIPythonApp.exec_files = [] # Start IPython quickly by skipping the loading of config files. # c.TerminalIPythonApp.quick = False # The Logging format template # c.TerminalIPythonApp.log_format = '[%(name)s]%(highlevel)s %(message)s' # Whether to install the default config files into the profile dir. If a new # profile is being created, and IPython contains config files for that profile, # then they will be staged into the new directory. Otherwise, default config # files will be automatically generated. # c.TerminalIPythonApp.copy_config_files = False # Path to an extra config file to load. # # If specified, load this config file in addition to any other IPython config. # c.TerminalIPythonApp.extra_config_file = '' # lines of code to run at IPython startup. # c.TerminalIPythonApp.exec_lines = [] # Enable GUI event loop integration with any of ('glut', 'gtk', 'gtk3', 'osx', # 'pyglet', 'qt', 'qt5', 'tk', 'wx'). # c.TerminalIPythonApp.gui = None # A file to be run # c.TerminalIPythonApp.file_to_run = '' # Configure matplotlib for interactive use with the default matplotlib backend. # c.TerminalIPythonApp.matplotlib = None # Suppress warning messages about legacy config files # c.TerminalIPythonApp.ignore_old_config = False # The name of the IPython directory. This directory is used for logging # configuration (through profiles), history storage, etc. The default is usually # $HOME/.ipython. This option can also be specified through the environment # variable IPYTHONDIR. # c.TerminalIPythonApp.ipython_dir = '' # If true, IPython will populate the user namespace with numpy, pylab, etc. and # an ``import *`` is done from numpy and pylab, when using pylab mode. # # When False, pylab mode should not import any names into the user namespace. # c.TerminalIPythonApp.pylab_import_all = True #------------------------------------------------------------------------------ # TerminalInteractiveShell configuration #------------------------------------------------------------------------------ # TerminalInteractiveShell will inherit config from: InteractiveShell # # c.TerminalInteractiveShell.object_info_string_level = 0 # # c.TerminalInteractiveShell.separate_out = '' # Automatically call the pdb debugger after every exception. # c.TerminalInteractiveShell.pdb = False # # c.TerminalInteractiveShell.ipython_dir = '' # # c.TerminalInteractiveShell.history_length = 10000 # # c.TerminalInteractiveShell.readline_remove_delims = '-/~' # auto editing of files with syntax errors. # c.TerminalInteractiveShell.autoedit_syntax = False # If True, anything that would be passed to the pager will be displayed as # regular output instead. # c.TerminalInteractiveShell.display_page = False # # c.TerminalInteractiveShell.debug = False # # c.TerminalInteractiveShell.separate_in = '\n' # Start logging to the default log file in overwrite mode. Use `logappend` to # specify a log file to **append** logs to. # c.TerminalInteractiveShell.logstart = False # Set the size of the output cache. The default is 1000, you can change it # permanently in your config file. Setting it to 0 completely disables the # caching system, and the minimum value accepted is 20 (if you provide a value # less than 20, it is reset to 0 and a warning is issued). This limit is # defined because otherwise you'll spend more time re-flushing a too small cache # than working # c.TerminalInteractiveShell.cache_size = 1000 # Set to confirm when you try to exit IPython with an EOF (Control-D in Unix, # Control-Z/Enter in Windows). By typing 'exit' or 'quit', you can force a # direct exit without any confirmation. # c.TerminalInteractiveShell.confirm_exit = True # The shell program to be used for paging. # c.TerminalInteractiveShell.pager = 'less' # # c.TerminalInteractiveShell.wildcards_case_sensitive = True # Deprecated, use PromptManager.justify # c.TerminalInteractiveShell.prompts_pad_left = True # The name of the logfile to use. # c.TerminalInteractiveShell.logfile = '' # 'all', 'last', 'last_expr' or 'none', specifying which nodes should be run # interactively (displaying output from expressions). # c.TerminalInteractiveShell.ast_node_interactivity = 'last_expr' # # c.TerminalInteractiveShell.quiet = False # Save multi-line entries as one entry in readline history # c.TerminalInteractiveShell.multiline_history = True # Deprecated, use PromptManager.in_template # c.TerminalInteractiveShell.prompt_in1 = 'In [\\#]: ' # # c.TerminalInteractiveShell.readline_use = True # Enable magic commands to be called without the leading %. # c.TerminalInteractiveShell.automagic = True # The part of the banner to be printed before the profile # c.TerminalInteractiveShell.banner1 = 'Python 3.4.3 |Continuum Analytics, Inc.| (default, Mar 6 2015, 12:07:41) \nType "copyright", "credits" or "license" for more information.\n\nIPython 3.1.0 -- An enhanced Interactive Python.\nAnaconda is brought to you by Continuum Analytics.\nPlease check out: http://continuum.io/thanks and https://binstar.org\n? -> Introduction and overview of IPython\'s features.\n%quickref -> Quick reference.\nhelp -> Python\'s own help system.\nobject? -> Details about \'object\', use \'object??\' for extra details.\n' # Make IPython automatically call any callable object even if you didn't type # explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically. # The value can be '0' to disable the feature, '1' for 'smart' autocall, where # it is not applied if there are no more arguments on the line, and '2' for # 'full' autocall, where all callable objects are automatically called (even if # no arguments are present). # c.TerminalInteractiveShell.autocall = 0 # Autoindent IPython code entered interactively. # c.TerminalInteractiveShell.autoindent = True # Set the color scheme (NoColor, Linux, or LightBG). # c.TerminalInteractiveShell.colors = 'LightBG' # Set the editor used by IPython (default to $EDITOR/vi/notepad). # c.TerminalInteractiveShell.editor = 'mate -w' # Use colors for displaying information about objects. Because this information # is passed through a pager (like 'less'), and some pagers get confused with # color codes, this capability can be turned off. # c.TerminalInteractiveShell.color_info = True # # c.TerminalInteractiveShell.readline_parse_and_bind = ['tab: complete', '"\\C-l": clear-screen', 'set show-all-if-ambiguous on', '"\\C-o": tab-insert', '"\\C-r": reverse-search-history', '"\\C-s": forward-search-history', '"\\C-p": history-search-backward', '"\\C-n": history-search-forward', '"\\e[A": history-search-backward', '"\\e[B": history-search-forward', '"\\C-k": kill-line', '"\\C-u": unix-line-discard'] # Deprecated, use PromptManager.in2_template # c.TerminalInteractiveShell.prompt_in2 = ' .\\D.: ' # # c.TerminalInteractiveShell.separate_out2 = '' # The part of the banner to be printed after the profile # c.TerminalInteractiveShell.banner2 = '' # Start logging to the given file in append mode. Use `logfile` to specify a log # file to **overwrite** logs to. # c.TerminalInteractiveShell.logappend = '' # Don't call post-execute functions that have failed in the past. # c.TerminalInteractiveShell.disable_failing_post_execute = False # Deprecated, use PromptManager.out_template # c.TerminalInteractiveShell.prompt_out = 'Out[\\#]: ' # Enable deep (recursive) reloading by default. IPython can use the deep_reload # module which reloads changes in modules recursively (it replaces the reload() # function, so you don't need to change anything to use it). deep_reload() # forces a full reload of modules whose code may have changed, which the default # reload() function does not. When deep_reload is off, IPython will use the # normal reload(), but deep_reload will still be available as dreload(). # c.TerminalInteractiveShell.deep_reload = False # # c.TerminalInteractiveShell.xmode = 'Context' # Show rewritten input, e.g. for autocall. # c.TerminalInteractiveShell.show_rewritten_input = True # Number of lines of your screen, used to control printing of very long strings. # Strings longer than this number of lines will be sent through a pager instead # of directly printed. The default value for this is 0, which means IPython # will auto-detect your screen size every time it needs to print certain # potentially long strings (this doesn't change the behavior of the 'print' # keyword, it's only triggered internally). If for some reason this isn't # working well (it needs curses support), specify it yourself. Otherwise don't # change the default. # c.TerminalInteractiveShell.screen_length = 0 # A list of ast.NodeTransformer subclass instances, which will be applied to # user input before code is run. # c.TerminalInteractiveShell.ast_transformers = [] # Enable auto setting the terminal title. # c.TerminalInteractiveShell.term_title = False #------------------------------------------------------------------------------ # PromptManager configuration #------------------------------------------------------------------------------ # This is the primary interface for producing IPython's prompts. # # c.PromptManager.color_scheme = 'Linux' # Continuation prompt. # c.PromptManager.in2_template = ' .\\D.: ' # Input prompt. '\#' will be transformed to the prompt number # c.PromptManager.in_template = 'In [\\#]: ' # Output prompt. '\#' will be transformed to the prompt number # c.PromptManager.out_template = 'Out[\\#]: ' # If True (default), each prompt will be right-aligned with the preceding one. # c.PromptManager.justify = True #------------------------------------------------------------------------------ # HistoryManager configuration #------------------------------------------------------------------------------ # A class to organize all history-related functionality in one place. # HistoryManager will inherit config from: HistoryAccessor # Options for configuring the SQLite connection # # These options are passed as keyword args to sqlite3.connect when establishing # database conenctions. # c.HistoryManager.connection_options = {} # Should the history database include output? (default: no) # c.HistoryManager.db_log_output = False # enable the SQLite history # # set enabled=False to disable the SQLite history, in which case there will be # no stored history, no SQLite connection, and no background saving thread. # This may be necessary in some threaded environments where IPython is embedded. # c.HistoryManager.enabled = True # Path to file to use for SQLite history database. # # By default, IPython will put the history database in the IPython profile # directory. If you would rather share one history among profiles, you can set # this value in each, so that they are consistent. # # Due to an issue with fcntl, SQLite is known to misbehave on some NFS mounts. # If you see IPython hanging, try setting this to something on a local disk, # e.g:: # # ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite # c.HistoryManager.hist_file = '' # Write to database every x commands (higher values save disk access & power). # Values of 1 or less effectively disable caching. # c.HistoryManager.db_cache_size = 0 #------------------------------------------------------------------------------ # ProfileDir configuration #------------------------------------------------------------------------------ # An object to manage the profile directory and its resources. # # The profile directory is used by all IPython applications, to manage # configuration, logging and security. # # This object knows how to find, create and manage these directories. This # should be used by any code that wants to handle profiles. # Set the profile location directly. This overrides the logic used by the # `profile` option. # c.ProfileDir.location = '' #------------------------------------------------------------------------------ # PlainTextFormatter configuration #------------------------------------------------------------------------------ # The default pretty-printer. # # This uses :mod:`IPython.lib.pretty` to compute the format data of the object. # If the object cannot be pretty printed, :func:`repr` is used. See the # documentation of :mod:`IPython.lib.pretty` for details on how to write pretty # printers. Here is a simple example:: # # def dtype_pprinter(obj, p, cycle): # if cycle: # return p.text('dtype(...)') # if hasattr(obj, 'fields'): # if obj.fields is None: # p.text(repr(obj)) # else: # p.begin_group(7, 'dtype([') # for i, field in enumerate(obj.descr): # if i > 0: # p.text(',') # p.breakable() # p.pretty(field) # p.end_group(7, '])') # PlainTextFormatter will inherit config from: BaseFormatter # # c.PlainTextFormatter.newline = '\n' # # c.PlainTextFormatter.max_width = 79 # # c.PlainTextFormatter.verbose = False # # c.PlainTextFormatter.pprint = True # # c.PlainTextFormatter.singleton_printers = {} # # c.PlainTextFormatter.type_printers = {} # Truncate large collections (lists, dicts, tuples, sets) to this size. # # Set to 0 to disable truncation. # c.PlainTextFormatter.max_seq_length = 1000 # # c.PlainTextFormatter.deferred_printers = {} # # c.PlainTextFormatter.float_precision = '' #------------------------------------------------------------------------------ # IPCompleter configuration #------------------------------------------------------------------------------ # Extension of the completer class with IPython-specific features # IPCompleter will inherit config from: Completer # Whether to merge completion results into a single list # # If False, only the completion results from the first non-empty completer will # be returned. # c.IPCompleter.merge_completions = True # Activate greedy completion # # This will enable completion on elements of lists, results of function calls, # etc., but can be unsafe because the code is actually evaluated on TAB. # c.IPCompleter.greedy = False # Instruct the completer to use __all__ for the completion # # Specifically, when completing on ``object.<tab>``. # # When True: only those names in obj.__all__ will be included. # # When False [default]: the __all__ attribute is ignored # c.IPCompleter.limit_to__all__ = False # Instruct the completer to omit private method names # # Specifically, when completing on ``object.<tab>``. # # When 2 [default]: all names that start with '_' will be excluded. # # When 1: all 'magic' names (``__foo__``) will be excluded. # # When 0: nothing will be excluded. # c.IPCompleter.omit__names = 2 #------------------------------------------------------------------------------ # ScriptMagics configuration #------------------------------------------------------------------------------ # Magics for talking to scripts # # This defines a base `%%script` cell magic for running a cell with a program in # a subprocess, and registers a few top-level magics that call %%script with # common interpreters. # Extra script cell magics to define # # This generates simple wrappers of `%%script foo` as `%%foo`. # # If you want to add script magics that aren't on your path, specify them in # script_paths # c.ScriptMagics.script_magics = [] # Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby' # # Only necessary for items in script_magics where the default path will not find # the right interpreter. # c.ScriptMagics.script_paths = {} #------------------------------------------------------------------------------ # StoreMagics configuration #------------------------------------------------------------------------------ # Lightweight persistence for python variables. # # Provides the %store magic. # If True, any %store-d variables will be automatically restored when IPython # starts. # c.StoreMagics.autorestore = False
{'content_hash': '823d91cbfc0eb744c44f1fb46ae87ee6', 'timestamp': '', 'source': 'github', 'line_count': 547, 'max_line_length': 567, 'avg_line_length': 37.61608775137112, 'alnum_prop': 0.6815221617418351, 'repo_name': 'bdh1011/wau', 'id': 'd3067791eb8cc738be47ebc4d0588f539b8308aa', 'size': '20611', 'binary': False, 'copies': '24', 'ref': 'refs/heads/master', 'path': 'venv/lib/python2.7/site-packages/jupyter_core/tests/dotipython/profile_default/ipython_config.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1176'}, {'name': 'C', 'bytes': '5022853'}, {'name': 'C++', 'bytes': '43676'}, {'name': 'CSS', 'bytes': '10359'}, {'name': 'D', 'bytes': '1841'}, {'name': 'FORTRAN', 'bytes': '3707'}, {'name': 'GAP', 'bytes': '14120'}, {'name': 'Groff', 'bytes': '7236'}, {'name': 'HTML', 'bytes': '1709320'}, {'name': 'JavaScript', 'bytes': '1200059'}, {'name': 'Jupyter Notebook', 'bytes': '310219'}, {'name': 'Lua', 'bytes': '11887'}, {'name': 'Makefile', 'bytes': '112163'}, {'name': 'Mako', 'bytes': '412'}, {'name': 'Objective-C', 'bytes': '1291'}, {'name': 'Perl', 'bytes': '171375'}, {'name': 'Python', 'bytes': '49407229'}, {'name': 'Ruby', 'bytes': '58403'}, {'name': 'Shell', 'bytes': '47672'}, {'name': 'Smarty', 'bytes': '22599'}, {'name': 'Tcl', 'bytes': '426334'}, {'name': 'XSLT', 'bytes': '153073'}]}
namespace Citicon.Data { public abstract class EntityBase<T> { public T Id { get; set; } public static bool operator ==(EntityBase<T> left, EntityBase<T> right) { return Equals(left, right); } public static bool operator !=(EntityBase<T> left, EntityBase<T> right) { return !(left == right); } public override bool Equals(object obj) { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; if (GetType() != obj.GetType()) return false; if (obj is EntityBase<T> value) { return (Equals(Id, default(T)) || Equals(value.Id, default(T))) ? false : Equals(Id, value.Id); } else { return false; } } public override int GetHashCode() { return Id.GetHashCode(); } } }
{'content_hash': '600d8f4b9cc987f91e4eb9fd30222b7c', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 111, 'avg_line_length': 25.789473684210527, 'alnum_prop': 0.48775510204081635, 'repo_name': 'JohnJosuaPaderon/Citicon', 'id': 'f07e0682eb0e4ed460fbe6a35cec4a066069ef12', 'size': '982', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Citicon/Data/EntityBase.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '2105801'}]}
<div class="fl-container-flex fl-fix information-group"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-identificationInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <span class="label required csc-collection-object-objectNumber-label"></span><span class="required">*</span> </div> <div class="content csc-object-identification-object-number-container clearfix"> <input type="text" class="csc-object-identification-object-number pattern-chooser-input" /> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-numberOfObjects-label"></div> </div> <div class="content"> <input type="text" class="input-numeric-medium csc-object-identification-number-objects"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-otherNumber-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-otherNumber-label"></td> <td class="csc-collection-object-numberType-label"></td> </tr> </thead> <tbody> <tr class="csc-object-identification-otherNumbers"> <td><input type="text" class="csc-object-identification-other-number"/></td> <td><select class="csc-object-identification-other-number-type input-select"><option value="">Options not loaded</option></select></td> </tr> </tbody> </table> </div> </div> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-responsibleDepartments-label"></div> </div> <div class="content"> <select class="csc-object-identification-responsible-department input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-collection-label"></div> </div> <div class="content"> <select class="csc-object-identification-collection input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-recordStatus-label"></div> </div> <div class="content"> <select class="csc-object-identification-record-status input-select"><option value="">Options not loaded</option></select> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-briefDescriptions-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-identification-brief-description"></textarea> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-distinguishingFeatures-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-identification-distinguishing-features"></textarea> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-comments-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-identification-comments"></textarea> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-computedCurrentLocation-label"></div> </div> <div class="content"> <input type="text" disabled="disabled" class="csc-collection-object-computedCurrentLocation"/> </div> </div> </div> </div> <div class="info-column cs-multipleEdit" id="multipleEdit"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-taxonomicIdentGroup-label"></div> </div> <div class="content csc-collection-object-taxonomicIdentGroup determinationHistory oocss"> <div class="info-column"> <table style="margin-bottom: 12px"> <thead> <tr> <td class="csc-collection-object-taxon-label"/> <td class="csc-collection-object-qualifier-label"/> </tr> </thead> <tbody> <tr> <td class="flc-inlineEdit-text taxon size2of3"> <input type="text" class="csc-taxonomic-identification-taxon editableText"/> </td> <td class="flc-inlineEdit-text"> <select class="csc-taxonomic-identification-qualifier"> <option value="">Options not loaded</option> </select> </td> </tr> </tbody> </table> </div> <div class="info-column indent"> <table style="margin-bottom: 12px"> <thead> <tr> <td class="csc-collection-object-identBy-label"/> <td class="csc-collection-object-identDate-label"/> <td class="csc-collection-object-institution-label"/> </tr> </thead> <tbody> <tr> <td class="flc-inlineEdit-text"> <input type="text" class="csc-taxonomic-identification-ident-by editableText"/> </td> <td class="flc-inlineEdit-text"> <input type="text" class="csc-taxonomic-identification-ident-date" /> </td> <td class="flc-inlineEdit-text"> <input type="text" class="csc-taxonomic-identification-institution"/> </td> </tr> </tbody> </table> </div> <div class="info-column indent"> <div class="info-column2-40 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-identKind-label"></div> </div> <div class="content"> <select class="csc-taxonomic-identification-ident-kind input-select-longer"> <option value="">Options not loaded</option> </select> </div> </div> <table> <thead> <tr> <!-- Inadvertently shares label with object reference field --> <td class="csc-collection-object-reference-label"/> <td class="csc-collection-object-refPage-label"/> </tr> </thead> <tbody> <td class="flc-inlineEdit-text"> <input type="text" class="csc-taxonomic-identification-reference editableText"/> </td> <td class="flc-inlineEdit-text"> <input type="text" class="csc-taxonomic-identification-reference-page editableText input-numeric-tiny"/> </td> </tbody> </table> </div> <div class="info-column2-60 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-notes-label"></div> </div> <div class="content"> <textarea rows="4" class="input-textarea csc-taxonomic-identification-notes"></textarea> </div> </div> </div> </div> </div> </div> </div> <div class="info-column cs-multipleEdit" id="multipleEdit"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-titleGroup-label"></div> </div> <div class="content csc-collection-object-titleGroup cs-repeatable-stretched"> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-title-label"></div> </div> <div class="content"> <input type="text" class="csc-object-identification-object-title input-alpha"/> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-titleLanguage-label"></div> </div> <div class="content stretched"> <select class="csc-object-identification-object-title-language input-select"><option value="">Options not loaded</option></select> </div> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-titleGroup-titleTranslationSubGroup-label"></div> </div> <div class="content stretched"> <table> <thead> <tr> <td class="csc-collection-object-titleTranslation-label"></td> <td class="csc-collection-object-titleTranslationLanguage-label"></td> </tr> </thead> <tbody> <tr class="csc-titleGroup-titleTranslationSubGroup"> <td class="flc-inlineEdit-text"><input type="text" class="csc-object-identification-object-title-translation editableText"/></td> <td class="flc-inlineEdit-text"><select class="csc-collection-object-titleTranslationLanguage input-select"><option value="">Options not loaded</option></select></td> </tr> </tbody> </table> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-titleType-label"></div> </div> <div class="content"> <select class="csc-object-identification-object-title-type input-select"><option value="">Options not loaded</option></select> </div> </div> </div> </div> </div> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-objectNameGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-objectName-label"></td> <td class="csc-collection-object-objectNameCurrency-label"></td> <td class="csc-collection-object-objectNameLevel-label"></td> <td class="csc-collection-object-objectNameSystem-label"></td> <td class="csc-collection-object-objectNameType-label"></td> <td class="csc-collection-object-objectNameLanguage-label"></td> <td class="csc-collection-object-objectNameNote-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-objectNameGroup"> <td><input type="text" class="csc-object-identification-object-name"/></td> <td><select class="csc-object-identification-object-currency input-select"><option value="">Options not loaded</option></select></td> <td><select class="csc-object-identification-object-level input-select"><option value="">Options not loaded</option></select></td> <td><select class="csc-object-identification-object-system input-select"><option value="">Options not loaded</option></select></td> <td><select class="csc-object-identification-object-type input-select"><option value="">Options not loaded</option></select></td> <td><select class="csc-object-identification-object-language input-select"><option value="">Options not loaded</option></select></td> <td style="width:25%;"><input type="text" class="csc-object-identification-object-note"/></td> </tr> </tbody> </table> </div> </div> </div> </div> <!-- information-group --> <div class="fl-container-flex fl-fix information-group"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-descriptionInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-copyNumber-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-copy-number"/> </div> </div> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-objectStatus-label"></div> </div> <div class="content"> <select class="csc-object-description-object-status input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-sex-label"></div> </div> <div class="content"> <select class="csc-object-description-sex input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-phase-label"></div> </div> <div class="content"> <select class="csc-object-description-phase input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-forms-label"></div> </div> <div class="content"> <select class="csc-object-description-form input-select"><option value="">Options not loaded</option></select> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-editionNumber-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-edition-number"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-ageGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-age-label"></td> <td class="csc-collection-object-ageQualifier-label"></td> <td class="csc-collection-object-ageUnit-label"></td> </tr> </thead> <tbody> <tr> <td><input type="text" class="csc-object-description-age"/></td> <td><select class="csc-object-description-age-qualifier input-select"><option value="">Options not loaded</option></select></td> <td><select class="csc-object-description-age-unit input-select"><option value="">Options not loaded</option></select></td> </tr> </tbody> </table> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-styles-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-style"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-colors-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-color"/> </div> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-materialGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-material-label"></td> <td class="csc-collection-object-materialComponent-label"></td> <td class="csc-collection-object-materialComponentNote-label"></td> <td class="csc-collection-object-materialName-label"></td> <td class="csc-collection-object-materialSource-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-materialGroup"> <td><input type="text" class="csc-object-description-material"/></td> <td><input type="text" class="csc-object-description-material-component"/></td> <td><input type="text" class="csc-object-description-material-component-note"/></td> <td><input type="text" class="csc-object-description-material-name"/></td> <td><input type="text" class="csc-object-description-material-source"/></td> </tr> </tbody> </table> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-physicalDescription-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-description-physical-description"></textarea> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-objectComponentGroup-label">Object Component</div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-objectComponentName-label"></td> <td class="csc-collection-object-objectComponentInformation-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-objectComponentGroup"> <td><select class="csc-object-description-object-component-name input-select"><option value="">Options not loaded</option></select></td> <td><input type="text" class="csc-object-description-object-component-information" /></td> </tr> </tbody> </table> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-technicalAttributeGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-technicalAttribute-label"></td> <td class="csc-collection-object-technicalAttributeMeasurement-label"></td> <td class="csc-collection-object-technicalAttributeMeasurementUnit-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-technicalAttributeGroup"> <td><select class="csc-object-description-technical-attribute input-select"><option value="">Options not loaded</option></select></td> <td><select class="csc-object-description-technical-attribute-measurement input-select"><option value="">Options not loaded</option></select></td> <td><select class="csc-object-description-technical-attribute-unit input-select"><option value="">Options not loaded</option></select></td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="csc-collection-object-dimension cs-multipleEdit"></div> <div class="fl-container-flex fl-fix information-subgroup"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-contentInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentDescription-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-description-content-description"></textarea> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-contentLanguages-label"></div> </div> <div class="content"> <select class="csc-object-description-content-language input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentActivities-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-content-activity"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentConcepts-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-content-concept"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentDate-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-content-date" /> </div> </div> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-contentPositions-label"></div> </div> <div class="content"> <select class="csc-object-description-content-position input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentObjectGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-contentObject-label"></td> <td class="csc-collection-object-contentObjectType-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-contentObjectGroup"> <td><input type="text" class="csc-object-description-content-object"/></td> <td><select class="csc-object-description-content-object-type"><option value="">Options not loaded</option></select></td> </tr> </tbody> </table> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentPeoples-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-content-people"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentPersons-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-content-person"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentPlaces-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-content-place"/> </div> </div> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-contentScripts-label"></div> </div> <div class="content"> <select class="csc-object-description-content-script input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentOrganizations-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-content-organization"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentEventNameGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-contentEventName-label"></td> <td class="csc-collection-object-contentEventNameType-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-contentEventNameGroup"> <td><input type="text" class="csc-object-description-content-event-name"/></td> <td><input type="text" class="csc-object-description-content-event-name-type"/></td> </tr> </tbody> </table> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentOtherGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-contentOther-label"></td> <td class="csc-collection-object-contentOtherType-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-contentOtherGroup"> <td><input type="text" class="csc-object-description-content-other" /></td> <td><input type="text" class="csc-object-description-content-other-type" /></td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-contentNote-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-description-content-note"></textarea> </div> </div> </div> </div> </div> <!-- information-subgroup --> <div class="fl-container-flex fl-fix information-group infoGroup"> <!--info-group = repeatable container --> <div class="csc-collection-object-textualInscriptionGroup cs-repeatable-stretched"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-textualInscriptionInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionContent-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-description-inscription-content"></textarea> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionContentInscriber-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-inscription-content-inscriber"/> </div> </div> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-inscriptionContentLanguage-label"></div> </div> <div class="content"> <select class="csc-object-description-inscription-content-language input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-textualInscriptionGroup-inscriptionContentDateGroup-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-inscription-content-date" /> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionContentPosition-label"></div> </div> <div class="content"> <select class="csc-object-description-inscription-content-position input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionContentScript-label"></div> </div> <div class="content"> <select class="csc-object-description-inscription-content-script input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionContentType-label"></div> </div> <div class="content"> <select class="csc-object-description-inscription-content-type input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionContentMethod-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-inscription-content-method"/> </div> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionContentInterpretation-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-description-inscription-content-interpretation"></textarea> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionContentTranslation-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-inscription-content-translation"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionContentTransliteration-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-inscription-content-transliteration"/> </div> </div> </div> </div> </div> <!-- /.csc-collection-object-textualInscriptionGroup sub-group --> </div> <!-- /info-group --> <div class="fl-container-flex fl-fix information-group infoGroup"> <!--info-group = repeatable container --> <div class="csc-collection-object-nonTextualInscriptionGroup cs-repeatable-stretched"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-nonTextualInscriptionInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionDescription-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-description-inscription-description"></textarea> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionDescriptionInscriber-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-inscription-description-inscriber"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-nonTextualInscriptionGroup-inscriptionDescriptionDateGroup-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-inscription-description-date" /> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionDescriptionPosition-label"></div> </div> <div class="content"> <select class="csc-object-description-inscription-description-position input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionDescriptionType-label"></div> </div> <div class="content"> <select class="csc-object-description-inscription-description-type input-select"><option value="">Options not loaded</option></select> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionDescriptionMethod-label"></div> </div> <div class="content"> <input type="text" class="csc-object-description-inscription-description-method"/> </div> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-inscriptionDescriptionInterpretation-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-description-inscription-description-interpretation"></textarea> </div> </div> </div> </div> </div> <!-- /.csc-collection-nonTextualInscriptionGroup sub-group --> </div> <!-- / infogroup --> </div> </div> <!-- information-group --> <div class="fl-container-flex fl-fix information-group"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-objectProductionInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-objectProductionDateGroup-label"></div> </div> <div class="content"> <input type="text" class="csc-objectProductionDateGroup-objectProductionDate" /> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-objectProductionPeopleGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-objectProductionPeople-label"></td> <td class="csc-collection-object-objectProductionPeopleRole-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-objectProductionPeopleGroup"> <td><input type="text" class="csc-object-production-people"/></td> <td><input type="text" class="csc-collection-object-objectProductionPeopleRole"/></td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-techniqueGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-technique-label"></td> <td class="csc-collection-object-techniqueType-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-techniqueGroup"> <td><input type="text" class="csc-object-production-technique"/></td> <td><input type="text" class="csc-object-production-technique-type input-select"/></td> </tr> </tbody> </table> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-objectProductionPersonGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-objectProductionPerson-label"></td> <td class="csc-collection-object-objectProductionPersonRole-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-objectProductionPersonGroup"> <td><input type="text" class="csc-object-production-person"/></td> <td><input type="text" class="csc-collection-object-objectProductionPersonRole"/></td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-objectProductionPlaceGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-objectProductionPlace-label"></td> <td class="csc-collection-object-objectProductionPlaceRole-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-objectProductionPlaceGroup"> <td><input type="text" class="csc-object-production-place"/></td> <td><input type="text" class="csc-collection-object-objectProductionPlaceRole"/></td> </tr> </tbody> </table> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-objectProductionOrganizationGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-objectProductionOrganization-label"></td> <td class="csc-collection-object-objectProductionOrganizationRole-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-objectProductionOrganizationGroup"> <td><input type="text" class="csc-object-production-organization"/></td> <td><input type="text" class="csc-collection-object-objectProductionOrganizationRole"/></td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-objectProductionReasons-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-production-reason"></textarea> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-objectProductionNote-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-production-note"></textarea> </div> </div> </div> </div> </div> </div> </div> <!-- information-group --> <div class="fl-container-flex fl-fix information-group"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-objectHistoryAssociationInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <div class="fl-container-flex fl-fix information-subgroup"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-associationInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocActivityGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-assocActivity-label"></td> <td class="csc-collection-object-assocActivityType-label"></td> <td class="csc-collection-object-assocActivityNote-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-assocActivityGroup"> <td><input type="text" class="csc-collection-object-assocActivity"/></td> <td><input type="text" class="csc-collection-object-assocActivityType"/></td> <td><input type="text" class="csc-collection-object-assocActivityNote"/></td> </tr> </tbody> </table> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocObjectGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-assocObject-label"></td> <td class="csc-collection-object-assocObjectType-label"></td> <td class="csc-collection-object-assocObjectNote-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-assocObjectGroup"> <td><input type="text" class="csc-collection-object-assocObject"/></td> <td><input type="text" class="csc-collection-object-assocObjectType"/></td> <td><input type="text" class="csc-collection-object-assocObjectNote"/></td> </tr> </tbody> </table> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocConceptGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-assocConcept-label"></td> <td class="csc-collection-object-assocConceptType-label"></td> <td class="csc-collection-object-assocConceptNote-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-assocConceptGroup"> <td><input type="text" class="csc-collection-object-assocConcept"/></td> <td><input type="text" class="csc-collection-object-assocConceptType"/></td> <td><input type="text" class="csc-collection-object-assocConceptNote"/></td> </tr> </tbody> </table> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocCulturalContextGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-assocCulturalContext-label"></td> <td class="csc-collection-object-assocCulturalContextType-label"></td> <td class="csc-collection-object-assocCulturalContextNote-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-assocCulturalContextGroup"> <td><input type="text" class="csc-collection-object-assocCulturalContext"/></td> <td><input type="text" class="csc-collection-object-assocCulturalContextType"/></td> <td><input type="text" class="csc-collection-object-assocCulturalContextNote"/></td> </tr> </tbody> </table> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocOrganizationGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-assocOrganization-label"></td> <td class="csc-collection-object-assocOrganizationType-label"></td> <td class="csc-collection-object-assocOrganizationNote-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-assocOrganizationGroup"> <td><input type="text" class="csc-collection-object-assocOrganization"/></td> <td><input type="text" class="csc-collection-object-assocOrganizationType"/></td> <td><input type="text" class="csc-collection-object-assocOrganizationNote"/></td> </tr> </tbody> </table> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocPeopleGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-assocPeople-label"></td> <td class="csc-collection-object-assocPeopleType-label"></td> <td class="csc-collection-object-assocPeopleNote-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-assocPeopleGroup"> <td><input type="text" class="csc-collection-object-assocPeople"/></td> <td><input type="text" class="csc-collection-object-assocPeopleType"/></td> <td><input type="text" class="csc-collection-object-assocPeopleNote"/></td> </tr> </tbody> </table> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocPersonGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-assocPerson-label"></td> <td class="csc-collection-object-assocPersonType-label"></td> <td class="csc-collection-object-assocPersonNote-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-assocPersonGroup"> <td><input type="text" class="csc-collection-object-assocPerson"/></td> <td><input type="text" class="csc-collection-object-assocPersonType"/></td> <td><input type="text" class="csc-collection-object-assocPersonNote"/></td> </tr> </tbody> </table> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocPlaceGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-assocPlace-label"></td> <td class="csc-collection-object-assocPlaceType-label"></td> <td class="csc-collection-object-assocPlaceNote-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-assocPlaceGroup"> <td><input type="text" class="csc-collection-object-assocPlace"/></td> <td><input type="text" class="csc-collection-object-assocPlaceType"/></td> <td><input type="text" class="csc-collection-object-assocPlaceNote"/></td> </tr> </tbody> </table> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocEventNameGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-assocEventName-label"></td> <td class="csc-collection-object-assocEventNameType-label"></td> </tr> </thead> <tbody> <tr> <td><input type="text" class="csc-collection-object-assocEventName"/></td> <td><input type="text" class="csc-collection-object-assocEventNameType"/></td> </tr> </tbody> </table> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocEventOrganizations-label"></div> </div> <div class="content"> <input type="text" class="csc-object-history-association-event-organization"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocEventPeoples-label"></div> </div> <div class="content"> <input type="text" class="csc-object-history-association-event-people"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocEventPersons-label"></div> </div> <div class="content"> <input type="text" class="csc-object-history-association-event-person"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocEventPlaces-label"></div> </div> <div class="content"> <input type="text" class="csc-object-history-association-event-place"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocEventNote-label"></div> </div> <div class="content"> <input type="text" class="csc-collection-object-assocEventNote"/> </div> </div> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-assocDateGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-assocDateGroup-assocStructuredDateGroup-label"></td> <td class="csc-collection-object-assocDateType-label"></td> <td class="csc-collection-object-assocDateNote-label"></td> </tr> </thead> <tbody> <tr class="csc-object-history-association-assocDateGroup"> <td><input type="text" class="csc-object-history-association-assocDate"/></td> <td><input type="text" class="csc-collection-object-assocDateType"/></td> <td><input type="text" class="csc-collection-object-assocDateNote"/></td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-objectHistoryNote-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-history-association-object-history-note"></textarea> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-usageGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-usage-label"></td> <td class="csc-collection-object-usageNote-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-usageGroup"> <td><input class="csc-collection-object-usage"/></td> <td><input type="text" class="csc-collection-object-usageNote"/></td> </tr> </tbody> </table> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-owners-label"></div> </div> <div class="content"> <input type="text" class="csc-object-history-association-owner"/> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-column2-50 fl-force-left"> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-ownershipAccess-label"></div> </div> <div class="content"> <select class="csc-object-history-association-access input-select"><option value="">Options not loaded</option></select> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-ownershipCategory-label"></div> </div> <div class="content"> <select class="csc-object-history-association-category input-select"><option value="">Options not loaded</option></select> </div> </div> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-ownershipDateGroup-label"></div> </div> <div class="content"> <input type="text" class="csc-ownershipDateGroup-ownershipDate" /> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-ownershipPlace-label"></div> </div> <div class="content"> <input type="text" class="csc-object-history-association-ownership-place"/> </div> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-ownershipExchangeGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-ownershipExchangeMethod-label"></td> <td class="csc-collection-object-ownershipExchangeNote-label"></td> <td class="csc-collection-object-ownershipExchangePriceCurrency-label"></td> <td class="csc-collection-object-ownershipExchangePriceValue-label"></td> </tr> </thead> <tbody> <tr> <td><select class="csc-object-history-association-exchange-method input-select"><option value="">Options not loaded</option></select></td> <td><input type="text" class="csc-object-history-association-exchange-note"/></td> <td><select class="csc-object-history-association-denomination input-select"><option value="">Options not loaded</option></select></td> <td><input type="text" class="csc-object-history-association-exchange-price-value"/></td> </tr> </tbody> </table> </div> </div> </div> </div> </div> <!-- information-group --> <div class="fl-container-flex fl-fix information-group"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-objectOwnerContributionInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-ownersPersonalExperience-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-owner-experience"></textarea> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-ownersPersonalResponse-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-owner-response"></textarea> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-ownersReferences-label"></div> </div> <div class="content stretched"> <input type="text" class="csc-object-owner-reference"/> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-ownersContributionNote-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-owner-contribution-note"></textarea> </div> </div> </div> </div> </div> <!-- information-group --> <div class="fl-container-flex fl-fix information-group"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-objectViewerContributionInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-viewersRole-label"></div> </div> <div class="content"> <input type="text" class="csc-object-viewer-role"/> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-viewersPersonalExperience-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-viewer-experience"></textarea> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-viewersPersonalResponse-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-viewer-response"></textarea> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-viewersReferences-label"></div> </div> <div class="content stretched"> <input type="text" class="csc-object-viewer-reference"/> </div> </div> </div> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-viewersContributionNote-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-object-viewer-contribution-note"></textarea> </div> </div> </div> </div> </div> <!-- information-group --> <div class="fl-container-flex fl-fix information-group"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-referenceInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <!-- Changed in CSPACE-3501. Reference and Catalog number merged into repeatable group; catalog number renamed reference note --> <div class="info-column"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-referenceGroup-label"></div> </div> <div class="content"> <table> <thead> <tr> <td class="csc-collection-object-reference-label"></td> <td class="csc-collection-object-referenceNote-label"></td> </tr> </thead> <tbody> <tr class="csc-collection-object-referenceGroup"> <td><input type="text" class="csc-collection-object-reference"/></td> <td><input type="text" class="csc-collection-object-referenceNote"/></td> </tr> </tbody> </table> </div> </div> </div> </div> </div> <!-- information-group --> <div class="fl-container-flex fl-fix information-group"> <div class="csc-recordEditor-header fl-container-flex header toggle csc-collection-object-objectCollectionInformation-label"></div> <div class="csc-recordEditor-togglable fl-container-flex fl-fix content main"> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-fieldCollectionDate-label"></div> </div> <div class="content"> <input type="text" class="csc-collection-object-fieldCollectionDate" /> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-fieldCollectionPlace-label"></div> </div> <div class="content"> <input type="text" class="input-alpha csc-collection-object-fieldCollectionPlace" /> </div> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair-select"> <div class="header"> <div class="label csc-collection-object-fieldCollectionMethods-label"></div> </div> <div class="content"> <select class="input-select csc-collection-object-fieldCollectionMethod"><option value="">Options not loaded</option></select> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-fieldCollectionSources-label"></div> </div> <div class="content"> <input type="text" class="input-alpha csc-collection-object-fieldCollectionSource" /> </div> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-fieldCollectionNote-label"></div> </div> <div class="content"> <textarea rows="4" cols="30" class="input-textarea csc-collection-object-fieldCollectionNote"></textarea> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-fieldCollectors-label"></div> </div> <div class="content"> <input type="text" class="input-alpha csc-collection-object-fieldCollector" /> </div> </div> </div> <div class="info-column2-50 fl-force-right"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-fieldColEventNames-label"></div> </div> <div class="content"> <input type="text" class="input-alpha csc-collection-object-fieldColEventName" /> </div> </div> </div> </div> <div class="info-column"> <div class="info-column2-50 fl-force-left"> <div class="info-pair"> <div class="header"> <div class="label csc-collection-object-fieldCollectionNumber-label"></div> </div> <div class="content"> <input type="text" class="input-alpha csc-collection-object-fieldCollectionNumber" /> </div> </div> </div> </div> </div> </div> <!-- information-group --> <div class="csc-record-hierarchy"></div>
{'content_hash': '76f2913afa44f11dacaf7fc1d985ceeb', 'timestamp': '', 'source': 'github', 'line_count': 1727, 'max_line_length': 184, 'avg_line_length': 38.48233931673422, 'alnum_prop': 0.5635203659399028, 'repo_name': 'cspace-deployment/ui', 'id': 'aa9cc4d6bedc20f098c03aea14b27751a57197a6', 'size': '66459', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/webapp/tenants/lifesci/html/pages/CatalogingTemplate.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '335223'}, {'name': 'HTML', 'bytes': '1419347'}, {'name': 'Java', 'bytes': '70381'}, {'name': 'JavaScript', 'bytes': '2256902'}, {'name': 'PHP', 'bytes': '2199'}, {'name': 'Shell', 'bytes': '3701'}]}
require('../../../modules/es7.string.pad-start'); module.exports = require('../../../modules/_entry-virtual')('String').padStart;
{'content_hash': 'fe039f27e0bdfbb83d34e6b6247c2cd9', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 79, 'avg_line_length': 65.0, 'alnum_prop': 0.6461538461538462, 'repo_name': 'Moccine/global-service-plus.com', 'id': 'c9e3942baec1b3678dfc0592095b00814096fa5a', 'size': '130', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'web/libariries/bootstrap/node_modules/core-js/fn/string/virtual/pad-start.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1629941'}, {'name': 'HTML', 'bytes': '967450'}, {'name': 'JavaScript', 'bytes': '390886'}, {'name': 'Makefile', 'bytes': '404'}, {'name': 'PHP', 'bytes': '233061'}]}
![](https://raw.githubusercontent.com/wancy86/wip/master/app/image/wip.png)
{'content_hash': 'ef58b30959576a71743fc750af2a6657', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 75, 'avg_line_length': 75.0, 'alnum_prop': 0.7733333333333333, 'repo_name': 'wancy86/wip', 'id': '9c29d431d05e9c2a49463778e4361fdd26848a2f', 'size': '98', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '72'}, {'name': 'CSS', 'bytes': '716'}, {'name': 'HTML', 'bytes': '38844'}, {'name': 'JavaScript', 'bytes': '36942'}]}
"use strict"; const Constants = require("../../../../Constants"); const Events = Constants.Events; const Endpoints = Constants.Endpoints; const apiRequest = require("../../../../core/ApiRequest"); module.exports = function(channelId, region) { return new Promise((rs, rj) => { var request = apiRequest .patch(this, { url: Endpoints.CALL(channelId), body: {region} }); this._queueManager.put(request, (err, res) => { return (!err && res.ok) ? rs() : rj(err); }); }); };
{'content_hash': '9233587ae6d562d96b984f42f7655db2', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 58, 'avg_line_length': 25.7, 'alnum_prop': 0.5953307392996109, 'repo_name': 'Gamecloud-Solutions/streambot', 'id': 'd4d73fb24d6eef5f00d5428b3ad5d2f2a74689f9', 'size': '514', 'binary': False, 'copies': '4', 'ref': 'refs/heads/dev-3', 'path': 'node_modules/discordie/lib/networking/rest/channels/calls/changeRegion.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '22765'}]}
using System; using System.Collections; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; namespace Aviad.WPF.Controls { /// <summary> /// Follow steps 1a or 1b and then 2 to use this custom control in a XAML file. /// /// Step 1a) Using this custom control in a XAML file that exists in the current project. /// Add this XmlNamespace attribute to the root element of the markup file where it is /// to be used: /// /// xmlns:MyNamespace="clr-namespace:ACTB" /// /// /// Step 1b) Using this custom control in a XAML file that exists in a different project. /// Add this XmlNamespace attribute to the root element of the markup file where it is /// to be used: /// /// xmlns:MyNamespace="clr-namespace:ACTB;assembly=ACTB" /// /// You will also need to add a project reference from the project where the XAML file lives /// to this project and Rebuild to avoid compilation errors: /// /// Right click on the target project in the Solution Explorer and /// "Add Reference"->"Projects"->[Browse to and select this project] /// /// /// Step 2) /// Go ahead and use your control in the XAML file. /// /// <MyNamespace:AutoCompleteTextBox/> /// /// </summary> public class AutoCompleteTextBox : TextBox { private readonly FrameworkElement _dummy = new FrameworkElement(); private Func<object, string, bool> _filter; public ListBox ListBox; private Popup _popup; private bool _suppressEvent; private string _textCache = ""; // Binding hack - not really necessary. //DependencyObject dummy = new DependencyObject(); static AutoCompleteTextBox() { DefaultStyleKeyProperty.OverrideMetadata(typeof (AutoCompleteTextBox), new FrameworkPropertyMetadata(typeof (AutoCompleteTextBox))); } public Func<object, string, bool> Filter { get { return _filter; } set { if (_filter == value) return; _filter = value; if (ListBox == null) return; if (_filter != null) { ListBox.Items.Filter = FilterFunc; } else { ListBox.Items.Filter = null; } } } #region ItemsSource Dependency Property // Using a DependencyProperty as the backing store for ItemsSource. This enables animation, styling, binding, etc... public static readonly DependencyProperty ItemsSourceProperty = ItemsControl.ItemsSourceProperty.AddOwner( typeof (AutoCompleteTextBox), new UIPropertyMetadata(null, OnItemsSourceChanged)); public IEnumerable ItemsSource { get { return (IEnumerable) GetValue(ItemsSourceProperty); } set { SetValue(ItemsSourceProperty, value); } } private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var actb = d as AutoCompleteTextBox; if (actb == null) return; actb.OnItemsSourceChanged(e.NewValue as IEnumerable); } protected void OnItemsSourceChanged(IEnumerable itemsSource) { if (ListBox == null || itemsSource == null) return; Debug.Print("Data: " + itemsSource); if (itemsSource is ListCollectionView) { ListBox.ItemsSource = new LimitedListCollectionView(((ListCollectionView) itemsSource).SourceCollection) {Limit = MaxCompletions}; Debug.Print("Was ListCollectionView"); } else if (itemsSource is CollectionView) { ListBox.ItemsSource = new LimitedListCollectionView(((CollectionView) itemsSource).SourceCollection) {Limit = MaxCompletions}; Debug.Print("Was CollectionView"); } else if (itemsSource is IList) { ListBox.ItemsSource = new LimitedListCollectionView(itemsSource) {Limit = MaxCompletions}; Debug.Print("Was IList"); } else { ListBox.ItemsSource = new LimitedCollectionView(itemsSource) {Limit = MaxCompletions}; Debug.Print("Was IEnumerable"); } if (ListBox.Items.Count == 0) InternalClosePopup(); } #endregion #region Binding Dependency Property // Using a DependencyProperty as the backing store for Binding. This enables animation, styling, binding, etc... public static readonly DependencyProperty BindingProperty = DependencyProperty.Register("Binding", typeof (string), typeof (AutoCompleteTextBox), new UIPropertyMetadata(null)); public string Binding { get { return (string) GetValue(BindingProperty); } set { SetValue(BindingProperty, value); } } #endregion #region ItemTemplate Dependency Property // Using a DependencyProperty as the backing store for ItemTemplate. This enables animation, styling, binding, etc... public static readonly DependencyProperty ItemTemplateProperty = ItemsControl.ItemTemplateProperty.AddOwner( typeof (AutoCompleteTextBox), new UIPropertyMetadata(null, OnItemTemplateChanged)); public DataTemplate ItemTemplate { get { return (DataTemplate) GetValue(ItemTemplateProperty); } set { SetValue(ItemTemplateProperty, value); } } private static void OnItemTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var actb = d as AutoCompleteTextBox; if (actb == null) return; actb.OnItemTemplateChanged(e.NewValue as DataTemplate); } private void OnItemTemplateChanged(DataTemplate p) { if (ListBox == null) return; ListBox.ItemTemplate = p; } #endregion #region ItemContainerStyle Dependency Property // Using a DependencyProperty as the backing store for ItemContainerStyle. This enables animation, styling, binding, etc... public static readonly DependencyProperty ItemContainerStyleProperty = ItemsControl.ItemContainerStyleProperty.AddOwner( typeof (AutoCompleteTextBox), new UIPropertyMetadata(null, OnItemContainerStyleChanged)); public Style ItemContainerStyle { get { return (Style) GetValue(ItemContainerStyleProperty); } set { SetValue(ItemContainerStyleProperty, value); } } private static void OnItemContainerStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var actb = d as AutoCompleteTextBox; if (actb == null) return; actb.OnItemContainerStyleChanged(e.NewValue as Style); } private void OnItemContainerStyleChanged(Style p) { if (ListBox == null) return; ListBox.ItemContainerStyle = p; } #endregion #region MaxCompletions Dependency Property // Using a DependencyProperty as the backing store for MaxCompletions. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxCompletionsProperty = DependencyProperty.Register("MaxCompletions", typeof (int), typeof (AutoCompleteTextBox), new UIPropertyMetadata(int.MaxValue)); public int MaxCompletions { get { return (int) GetValue(MaxCompletionsProperty); } set { SetValue(MaxCompletionsProperty, value); } } #endregion #region ItemTemplateSelector Dependency Property // Using a DependencyProperty as the backing store for ItemTemplateSelector. This enables animation, styling, binding, etc... public static readonly DependencyProperty ItemTemplateSelectorProperty = ItemsControl.ItemTemplateSelectorProperty.AddOwner(typeof (AutoCompleteTextBox), new UIPropertyMetadata(null, OnItemTemplateSelectorChanged)); public DataTemplateSelector ItemTemplateSelector { get { return (DataTemplateSelector) GetValue(ItemTemplateSelectorProperty); } set { SetValue(ItemTemplateSelectorProperty, value); } } private static void OnItemTemplateSelectorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var actb = d as AutoCompleteTextBox; if (actb == null) return; actb.OnItemTemplateSelectorChanged(e.NewValue as DataTemplateSelector); } private void OnItemTemplateSelectorChanged(DataTemplateSelector p) { if (ListBox == null) return; ListBox.ItemTemplateSelector = p; } #endregion private void InternalClosePopup() { if (_popup != null) _popup.IsOpen = false; } private void InternalOpenPopup() { _popup.IsOpen = true; if (ListBox != null) ListBox.SelectedIndex = -1; } public void ShowPopup() { if (ListBox == null || _popup == null) InternalClosePopup(); else if (ListBox.Items.Count == 0) InternalClosePopup(); else InternalOpenPopup(); } private void SetTextValueBySelection(object obj, bool moveFocus) { if (_popup != null) { InternalClosePopup(); Dispatcher.Invoke(new Action(() => { Focus(); if (moveFocus) MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); }), DispatcherPriority.Background); } // Retrieve the Binding object from the control. Binding originalBinding = BindingOperations.GetBinding(this, BindingProperty); if (originalBinding == null) return; // Set the dummy's DataContext to our selected object. _dummy.DataContext = obj; // Apply the binding to the dummy FrameworkElement. BindingOperations.SetBinding(_dummy, TextProperty, originalBinding); _suppressEvent = true; // Get the binding's resulting value. Text = _dummy.GetValue(TextProperty).ToString(); _suppressEvent = false; ListBox.SelectedIndex = -1; SelectAll(); } protected override void OnTextChanged(TextChangedEventArgs e) { base.OnTextChanged(e); if (_suppressEvent) return; _textCache = Text ?? ""; Debug.Print("Text: " + _textCache); if (_popup != null && _textCache == "") { InternalClosePopup(); } else if (ListBox != null) { if (_filter != null) ListBox.Items.Filter = FilterFunc; if (_popup != null) { if (ListBox.Items.Count == 0) InternalClosePopup(); else InternalOpenPopup(); } } } private bool FilterFunc(object obj) { return _filter(obj, _textCache); } public override void OnApplyTemplate() { base.OnApplyTemplate(); _popup = Template.FindName("PART_Popup", this) as Popup; ListBox = Template.FindName("PART_ListBox", this) as ListBox; if (ListBox != null) { ListBox.PreviewMouseDown += listBox_MouseUp; ListBox.KeyDown += listBox_KeyDown; OnItemsSourceChanged(ItemsSource); OnItemTemplateChanged(ItemTemplate); OnItemContainerStyleChanged(ItemContainerStyle); OnItemTemplateSelectorChanged(ItemTemplateSelector); if (_filter != null) ListBox.Items.Filter = FilterFunc; } } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); if (_suppressEvent) return; if (_popup != null) { InternalClosePopup(); } } protected override void OnPreviewKeyDown(KeyEventArgs e) { base.OnPreviewKeyDown(e); DependencyObject fs = FocusManager.GetFocusScope(this); IInputElement o = FocusManager.GetFocusedElement(fs); if (e.Key == Key.Escape) { InternalClosePopup(); Focus(); } else if (e.Key == Key.Down) { if (ListBox != null && o == this) { _suppressEvent = true; ListBox.Focus(); _suppressEvent = false; } } } private void listBox_MouseUp(object sender, MouseButtonEventArgs e) { var dep = (DependencyObject) e.OriginalSource; while ((dep != null) && !(dep is ListBoxItem)) { dep = VisualTreeHelper.GetParent(dep); } if (dep == null) return; object item = ListBox.ItemContainerGenerator.ItemFromContainer(dep); if (item == null) return; SetTextValueBySelection(item, false); } private void listBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter || e.Key == Key.Return) SetTextValueBySelection(ListBox.SelectedItem, false); else if (e.Key == Key.Tab) SetTextValueBySelection(ListBox.SelectedItem, true); } } }
{'content_hash': '18379932a516c466485c79062d251407', 'timestamp': '', 'source': 'github', 'line_count': 398, 'max_line_length': 134, 'avg_line_length': 37.447236180904525, 'alnum_prop': 0.5632716049382716, 'repo_name': 'tltjr/Wish', 'id': '7911470e8d66a308bd0ada1c2315a977ce16856e', 'size': '14906', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ACTB/AutoCompleteTextBox.cs', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C#', 'bytes': '1974442'}, {'name': 'JavaScript', 'bytes': '0'}, {'name': 'PowerShell', 'bytes': '6'}]}
package org.apache.camel.component.rest; import org.apache.camel.CamelContext; import static org.apache.camel.spring.processor.SpringTestHelper.createSpringCamelContext; public class SpringFromRestConfigurationTest extends FromRestConfigurationTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/component/rest/SpringFromRestConfigurationTest.xml"); } }
{'content_hash': '661c303146c8445cfdbf2405092ee1e6', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 117, 'avg_line_length': 30.933333333333334, 'alnum_prop': 0.8146551724137931, 'repo_name': 'adessaigne/camel', 'id': '404e68b68b6d3e44caebaf589e7b114d75797a4d', 'size': '1266', 'binary': False, 'copies': '7', 'ref': 'refs/heads/main', 'path': 'components/camel-spring-xml/src/test/java/org/apache/camel/component/rest/SpringFromRestConfigurationTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Apex', 'bytes': '6695'}, {'name': 'Batchfile', 'bytes': '2353'}, {'name': 'CSS', 'bytes': '5472'}, {'name': 'Dockerfile', 'bytes': '5676'}, {'name': 'Elm', 'bytes': '10852'}, {'name': 'FreeMarker', 'bytes': '16123'}, {'name': 'Groovy', 'bytes': '383919'}, {'name': 'HTML', 'bytes': '209156'}, {'name': 'Java', 'bytes': '109812609'}, {'name': 'JavaScript', 'bytes': '103655'}, {'name': 'Jsonnet', 'bytes': '1734'}, {'name': 'Kotlin', 'bytes': '41869'}, {'name': 'Mustache', 'bytes': '525'}, {'name': 'RobotFramework', 'bytes': '8461'}, {'name': 'Ruby', 'bytes': '88'}, {'name': 'Shell', 'bytes': '19367'}, {'name': 'Tcl', 'bytes': '4974'}, {'name': 'Thrift', 'bytes': '6979'}, {'name': 'XQuery', 'bytes': '699'}, {'name': 'XSLT', 'bytes': '276597'}]}
var Tone = require('tone'); var log = require('./log'); /** * A SoundPlayer stores an audio buffer, and plays it * @constructor */ function SoundPlayer () { this.outputNode = null; this.buffer = new Tone.Buffer(); this.bufferSource = null; this.playbackRate = 1; this.isPlaying = false; } /** * Connect the SoundPlayer to an output node * @param {Tone.Gain} node - an output node to connect to */ SoundPlayer.prototype.connect = function (node) { this.outputNode = node; }; /** * Set an audio buffer * @param {Tone.Buffer} buffer */ SoundPlayer.prototype.setBuffer = function (buffer) { this.buffer = buffer; }; /** * Set the playback rate for the sound * @param {number} playbackRate - a ratio where 1 is normal playback, 0.5 is half speed, 2 is double speed, etc. */ SoundPlayer.prototype.setPlaybackRate = function (playbackRate) { this.playbackRate = playbackRate; if (this.bufferSource && this.bufferSource.playbackRate) { this.bufferSource.playbackRate.value = this.playbackRate; } }; /** * Stop the sound */ SoundPlayer.prototype.stop = function () { if (this.bufferSource) { this.bufferSource.stop(); } this.isPlaying = false; }; /** * Start playing the sound * The web audio framework requires a new audio buffer source node for each playback */ SoundPlayer.prototype.start = function () { if (!this.buffer || !this.buffer.loaded) { log.warn('tried to play a sound that was not loaded yet'); return; } this.bufferSource = new Tone.BufferSource(this.buffer.get()); this.bufferSource.playbackRate.value = this.playbackRate; this.bufferSource.connect(this.outputNode); this.bufferSource.start(); this.isPlaying = true; }; /** * The sound has finished playing. This is called at the correct time even if the playback rate * has been changed * @return {Promise} a Promise that resolves when the sound finishes playing */ SoundPlayer.prototype.finished = function () { var storedContext = this; return new Promise(function (resolve) { storedContext.bufferSource.onended = function () { this.isPlaying = false; resolve(); }.bind(storedContext); }); }; module.exports = SoundPlayer;
{'content_hash': '7971178d8506938d36ea230e8d118c63', 'timestamp': '', 'source': 'github', 'line_count': 86, 'max_line_length': 112, 'avg_line_length': 26.511627906976745, 'alnum_prop': 0.6706140350877193, 'repo_name': 'kesl-scratch/PopconBot', 'id': '2afa3c0eaf82d361f289b2e927153adcdcfe219b', 'size': '2280', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'scratch-audio/src/SoundPlayer.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Arduino', 'bytes': '248137'}, {'name': 'C', 'bytes': '228721'}, {'name': 'C++', 'bytes': '1007800'}, {'name': 'CSS', 'bytes': '56690'}, {'name': 'GLSL', 'bytes': '5418'}, {'name': 'HTML', 'bytes': '483404'}, {'name': 'JavaScript', 'bytes': '7116437'}, {'name': 'Makefile', 'bytes': '1384'}, {'name': 'Processing', 'bytes': '18508'}, {'name': 'Python', 'bytes': '56995'}, {'name': 'Shell', 'bytes': '981'}]}
<?php namespace Kiosk\QuizBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Kiosk\QuestionAnswerBundle\Entity\Answer; use Kiosk\QuestionAnswerBundle\Entity\Question; /** * @ORM\Entity * @ORM\Table(name="quiz") */ class Quiz { /** * @ORM\OneToMany(targetEntity="Kiosk\QuestionAnswerBundle\Entity\Question", mappedBy="quiz") */ protected $questions; public function __construct() { $this->questions = new ArrayCollection(); } /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string", length=100) */ protected $name; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return Quiz */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Add questions * * @param Question $questions * @return Quiz */ public function addQuestion(Question $questions) { $this->questions[] = $questions; return $this; } /** * Remove questions * * @param Question $questions */ public function removeQuestion(Question $questions) { $this->questions->removeElement($questions); } /** * Get questions * * @return \Doctrine\Common\Collections\Collection */ public function getQuestions() { return $this->questions; } }
{'content_hash': 'da3d8eb718c61570a3f2add60ded5069', 'timestamp': '', 'source': 'github', 'line_count': 103, 'max_line_length': 97, 'avg_line_length': 17.038834951456312, 'alnum_prop': 0.5373219373219373, 'repo_name': 'sela/quiz', 'id': 'a4b2de1ce62d58cc66d2bcbaaa7500cd1a0395b0', 'size': '1755', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Kiosk/QuizBundle/Entity/Quiz.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '158726'}, {'name': 'JavaScript', 'bytes': '77213'}, {'name': 'PHP', 'bytes': '87081'}]}
module.exports = function (fileName) { var fs = require('fs'); return JSON.parse(fs.readFileSync(fileName, 'utf8')); };
{'content_hash': 'b515e3316b87b1013921c6fe13209503', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 55, 'avg_line_length': 31.0, 'alnum_prop': 0.6774193548387096, 'repo_name': 'asquelt/allpuppet', 'id': 'eec1e40cc3235a25e18c34238ce190a632dfd2fe', 'size': '124', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/readJSON.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '6118'}]}
<?php /** * RedUNIT_Base_Extassoc * * @file RedUNIT/Base/Extassoc.php * @desc Tests extended associations, associations with additional properties in * @author Gabor de Mooij and the RedBeanPHP Community * @license New BSD/GPLv2 * * (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community. * This source file is subject to the New BSD/GPLv2 License that is bundled * with this source code in the file license.txt. */ class RedUNIT_Base_Extassoc extends RedUNIT_Base { /** * Test extended associations. * * @return void */ public function testExtAssoc() { $toolbox = R::$toolbox; $adapter = $toolbox->getDatabaseAdapter(); $writer = $toolbox->getWriter(); $redbean = $toolbox->getRedBean(); $pdo = $adapter->getDatabase(); R::nuke(); $webpage = $redbean->dispense( "webpage" ); $webpage->title = "page with ads"; $ad = $redbean->dispense( "ad" ); $ad->title = "buy this!"; $top = $redbean->dispense( "placement" ); $top->position = "top"; $bottom = $redbean->dispense( "placement" ); $bottom->position = "bottom"; $ea = new RedBean_AssociationManager_ExtAssociationManager( $toolbox ); $ea->extAssociate( $ad, $webpage, $top ); $ads = $redbean->batch( "ad", $ea->related( $webpage, "ad" ) ); $adsPos = $redbean->batch( "ad_webpage", $ea->related( $webpage, "ad", TRUE ) ); asrt( count( $ads ), 1 ); asrt( count( $adsPos ), 1 ); $theAd = array_pop( $ads ); $theAdPos = array_pop( $adsPos ); asrt( $theAd->title, $ad->title ); asrt( $theAdPos->position, $top->position ); $ad2 = $redbean->dispense( "ad" ); $ad2->title = "buy this too!"; $ea->extAssociate( $ad2, $webpage, $bottom ); $ads = $redbean->batch( "ad", $ea->related( $webpage, "ad", TRUE ) ); asrt( count( $ads ), 2 ); } }
{'content_hash': 'bfbfb3f652c60e1e6f1536514408cf9b', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 83, 'avg_line_length': 24.71232876712329, 'alnum_prop': 0.6197339246119734, 'repo_name': 'monkeycraps/flight-local-picture', 'id': '19a8a4e285963bdc594c04ae1dd47b52d4fa2540', 'size': '1804', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'vendor/gabordemooij/redbean/testing/RedUNIT/Base/Extassoc.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '83752'}]}
package codec import ( "encoding" "errors" "fmt" "io" "reflect" "time" ) // Some tagging information for error messages. const ( msgBadDesc = "Unrecognized descriptor byte" msgDecCannotExpandArr = "cannot expand go array from %v to stream length: %v" ) var ( onlyMapOrArrayCanDecodeIntoStructErr = errors.New("only encoded map or array can be decoded into a struct") cannotDecodeIntoNilErr = errors.New("cannot decode into nil") ) // decReader abstracts the reading source, allowing implementations that can // read from an io.Reader or directly off a byte slice with zero-copying. type decReader interface { unreadn1() // readx will use the implementation scratch buffer if possible i.e. n < len(scratchbuf), OR // just return a view of the []byte being decoded from. // Ensure you call detachZeroCopyBytes later if this needs to be sent outside codec control. readx(n int) []byte readb([]byte) readn1() uint8 readn1eof() (v uint8, eof bool) numread() int // number of bytes read track() stopTrack() []byte } type decReaderByteScanner interface { io.Reader io.ByteScanner } type decDriver interface { // this will check if the next token is a break. CheckBreak() bool TryDecodeAsNil() bool // vt is one of: Bytes, String, Nil, Slice or Map. Return unSet if not known. ContainerType() (vt valueType) IsBuiltinType(rt uintptr) bool DecodeBuiltin(rt uintptr, v interface{}) // DecodeNaked will decode primitives (number, bool, string, []byte) and RawExt. // For maps and arrays, it will not do the decoding in-band, but will signal // the decoder, so that is done later, by setting the decNaked.valueType field. // // Note: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types). // for extensions, DecodeNaked must read the tag and the []byte if it exists. // if the []byte is not read, then kInterfaceNaked will treat it as a Handle // that stores the subsequent value in-band, and complete reading the RawExt. // // extensions should also use readx to decode them, for efficiency. // kInterface will extract the detached byte slice if it has to pass it outside its realm. DecodeNaked() DecodeInt(bitsize uint8) (i int64) DecodeUint(bitsize uint8) (ui uint64) DecodeFloat(chkOverflow32 bool) (f float64) DecodeBool() (b bool) // DecodeString can also decode symbols. // It looks redundant as DecodeBytes is available. // However, some codecs (e.g. binc) support symbols and can // return a pre-stored string value, meaning that it can bypass // the cost of []byte->string conversion. DecodeString() (s string) // DecodeBytes may be called directly, without going through reflection. // Consequently, it must be designed to handle possible nil. DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) // decodeExt will decode into a *RawExt or into an extension. DecodeExt(v interface{}, xtag uint64, ext Ext) (realxtag uint64) // decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte) ReadMapStart() int ReadArrayStart() int reset() uncacheRead() } type decNoSeparator struct { } func (_ decNoSeparator) ReadEnd() {} // func (_ decNoSeparator) uncacheRead() {} type DecodeOptions struct { // MapType specifies type to use during schema-less decoding of a map in the stream. // If nil, we use map[interface{}]interface{} MapType reflect.Type // SliceType specifies type to use during schema-less decoding of an array in the stream. // If nil, we use []interface{} SliceType reflect.Type // MaxInitLen defines the initial length that we "make" a collection (slice, chan or map) with. // If 0 or negative, we default to a sensible value based on the size of an element in the collection. // // For example, when decoding, a stream may say that it has MAX_UINT elements. // We should not auto-matically provision a slice of that length, to prevent Out-Of-Memory crash. // Instead, we provision up to MaxInitLen, fill that up, and start appending after that. MaxInitLen int // If ErrorIfNoField, return an error when decoding a map // from a codec stream into a struct, and no matching struct field is found. ErrorIfNoField bool // If ErrorIfNoArrayExpand, return an error when decoding a slice/array that cannot be expanded. // For example, the stream contains an array of 8 items, but you are decoding into a [4]T array, // or you are decoding into a slice of length 4 which is non-addressable (and so cannot be set). ErrorIfNoArrayExpand bool // If SignedInteger, use the int64 during schema-less decoding of unsigned values (not uint64). SignedInteger bool // MapValueReset controls how we decode into a map value. // // By default, we MAY retrieve the mapping for a key, and then decode into that. // However, especially with big maps, that retrieval may be expensive and unnecessary // if the stream already contains all that is necessary to recreate the value. // // If true, we will never retrieve the previous mapping, // but rather decode into a new value and set that in the map. // // If false, we will retrieve the previous mapping if necessary e.g. // the previous mapping is a pointer, or is a struct or array with pre-set state, // or is an interface. MapValueReset bool // InterfaceReset controls how we decode into an interface. // // By default, when we see a field that is an interface{...}, // or a map with interface{...} value, we will attempt decoding into the // "contained" value. // // However, this prevents us from reading a string into an interface{} // that formerly contained a number. // // If true, we will decode into a new "blank" value, and set that in the interface. // If false, we will decode into whatever is contained in the interface. InterfaceReset bool // InternString controls interning of strings during decoding. // // Some handles, e.g. json, typically will read map keys as strings. // If the set of keys are finite, it may help reduce allocation to // look them up from a map (than to allocate them afresh). // // Note: Handles will be smart when using the intern functionality. // So everything will not be interned. InternString bool } // ------------------------------------ // ioDecByteScanner implements Read(), ReadByte(...), UnreadByte(...) methods // of io.Reader, io.ByteScanner. type ioDecByteScanner struct { r io.Reader l byte // last byte ls byte // last byte status. 0: init-canDoNothing, 1: canRead, 2: canUnread b [1]byte // tiny buffer for reading single bytes } func (z *ioDecByteScanner) Read(p []byte) (n int, err error) { var firstByte bool if z.ls == 1 { z.ls = 2 p[0] = z.l if len(p) == 1 { n = 1 return } firstByte = true p = p[1:] } n, err = z.r.Read(p) if n > 0 { if err == io.EOF && n == len(p) { err = nil // read was successful, so postpone EOF (till next time) } z.l = p[n-1] z.ls = 2 } if firstByte { n++ } return } func (z *ioDecByteScanner) ReadByte() (c byte, err error) { n, err := z.Read(z.b[:]) if n == 1 { c = z.b[0] if err == io.EOF { err = nil // read was successful, so postpone EOF (till next time) } } return } func (z *ioDecByteScanner) UnreadByte() (err error) { x := z.ls if x == 0 { err = errors.New("cannot unread - nothing has been read") } else if x == 1 { err = errors.New("cannot unread - last byte has not been read") } else if x == 2 { z.ls = 1 } return } // ioDecReader is a decReader that reads off an io.Reader type ioDecReader struct { br decReaderByteScanner // temp byte array re-used internally for efficiency during read. // shares buffer with Decoder, so we keep size of struct within 8 words. x *[scratchByteArrayLen]byte bs ioDecByteScanner n int // num read tr []byte // tracking bytes read trb bool } func (z *ioDecReader) numread() int { return z.n } func (z *ioDecReader) readx(n int) (bs []byte) { if n <= 0 { return } if n < len(z.x) { bs = z.x[:n] } else { bs = make([]byte, n) } if _, err := io.ReadAtLeast(z.br, bs, n); err != nil { panic(err) } z.n += len(bs) if z.trb { z.tr = append(z.tr, bs...) } return } func (z *ioDecReader) readb(bs []byte) { if len(bs) == 0 { return } n, err := io.ReadAtLeast(z.br, bs, len(bs)) z.n += n if err != nil { panic(err) } if z.trb { z.tr = append(z.tr, bs...) } } func (z *ioDecReader) readn1() (b uint8) { b, err := z.br.ReadByte() if err != nil { panic(err) } z.n++ if z.trb { z.tr = append(z.tr, b) } return b } func (z *ioDecReader) readn1eof() (b uint8, eof bool) { b, err := z.br.ReadByte() if err == nil { z.n++ if z.trb { z.tr = append(z.tr, b) } } else if err == io.EOF { eof = true } else { panic(err) } return } func (z *ioDecReader) unreadn1() { err := z.br.UnreadByte() if err != nil { panic(err) } z.n-- if z.trb { if l := len(z.tr) - 1; l >= 0 { z.tr = z.tr[:l] } } } func (z *ioDecReader) track() { if z.tr != nil { z.tr = z.tr[:0] } z.trb = true } func (z *ioDecReader) stopTrack() (bs []byte) { z.trb = false return z.tr } // ------------------------------------ var bytesDecReaderCannotUnreadErr = errors.New("cannot unread last byte read") // bytesDecReader is a decReader that reads off a byte slice with zero copying type bytesDecReader struct { b []byte // data c int // cursor a int // available t int // track start } func (z *bytesDecReader) reset(in []byte) { z.b = in z.a = len(in) z.c = 0 z.t = 0 } func (z *bytesDecReader) numread() int { return z.c } func (z *bytesDecReader) unreadn1() { if z.c == 0 || len(z.b) == 0 { panic(bytesDecReaderCannotUnreadErr) } z.c-- z.a++ return } func (z *bytesDecReader) readx(n int) (bs []byte) { // slicing from a non-constant start position is more expensive, // as more computation is required to decipher the pointer start position. // However, we do it only once, and it's better than reslicing both z.b and return value. if n <= 0 { } else if z.a == 0 { panic(io.EOF) } else if n > z.a { panic(io.ErrUnexpectedEOF) } else { c0 := z.c z.c = c0 + n z.a = z.a - n bs = z.b[c0:z.c] } return } func (z *bytesDecReader) readn1() (v uint8) { if z.a == 0 { panic(io.EOF) } v = z.b[z.c] z.c++ z.a-- return } func (z *bytesDecReader) readn1eof() (v uint8, eof bool) { if z.a == 0 { eof = true return } v = z.b[z.c] z.c++ z.a-- return } func (z *bytesDecReader) readb(bs []byte) { copy(bs, z.readx(len(bs))) } func (z *bytesDecReader) track() { z.t = z.c } func (z *bytesDecReader) stopTrack() (bs []byte) { return z.b[z.t:z.c] } // ------------------------------------ type decFnInfo struct { d *Decoder ti *typeInfo xfFn Ext xfTag uint64 seq seqType } // ---------------------------------------- type decFn struct { i decFnInfo f func(*decFnInfo, reflect.Value) } func (f *decFnInfo) builtin(rv reflect.Value) { f.d.d.DecodeBuiltin(f.ti.rtid, rv.Addr().Interface()) } func (f *decFnInfo) rawExt(rv reflect.Value) { f.d.d.DecodeExt(rv.Addr().Interface(), 0, nil) } func (f *decFnInfo) raw(rv reflect.Value) { rv.SetBytes(f.d.raw()) } func (f *decFnInfo) ext(rv reflect.Value) { f.d.d.DecodeExt(rv.Addr().Interface(), f.xfTag, f.xfFn) } func (f *decFnInfo) getValueForUnmarshalInterface(rv reflect.Value, indir int8) (v interface{}) { if indir == -1 { v = rv.Addr().Interface() } else if indir == 0 { v = rv.Interface() } else { for j := int8(0); j < indir; j++ { if rv.IsNil() { rv.Set(reflect.New(rv.Type().Elem())) } rv = rv.Elem() } v = rv.Interface() } return } func (f *decFnInfo) selferUnmarshal(rv reflect.Value) { f.getValueForUnmarshalInterface(rv, f.ti.csIndir).(Selfer).CodecDecodeSelf(f.d) } func (f *decFnInfo) binaryUnmarshal(rv reflect.Value) { bm := f.getValueForUnmarshalInterface(rv, f.ti.bunmIndir).(encoding.BinaryUnmarshaler) xbs := f.d.d.DecodeBytes(nil, false, true) if fnerr := bm.UnmarshalBinary(xbs); fnerr != nil { panic(fnerr) } } func (f *decFnInfo) textUnmarshal(rv reflect.Value) { tm := f.getValueForUnmarshalInterface(rv, f.ti.tunmIndir).(encoding.TextUnmarshaler) fnerr := tm.UnmarshalText(f.d.d.DecodeBytes(f.d.b[:], true, true)) if fnerr != nil { panic(fnerr) } } func (f *decFnInfo) jsonUnmarshal(rv reflect.Value) { tm := f.getValueForUnmarshalInterface(rv, f.ti.junmIndir).(jsonUnmarshaler) // bs := f.d.d.DecodeBytes(f.d.b[:], true, true) // grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself. fnerr := tm.UnmarshalJSON(f.d.nextValueBytes()) if fnerr != nil { panic(fnerr) } } func (f *decFnInfo) kErr(rv reflect.Value) { f.d.errorf("no decoding function defined for kind %v", rv.Kind()) } func (f *decFnInfo) kString(rv reflect.Value) { rv.SetString(f.d.d.DecodeString()) } func (f *decFnInfo) kBool(rv reflect.Value) { rv.SetBool(f.d.d.DecodeBool()) } func (f *decFnInfo) kInt(rv reflect.Value) { rv.SetInt(f.d.d.DecodeInt(intBitsize)) } func (f *decFnInfo) kInt64(rv reflect.Value) { rv.SetInt(f.d.d.DecodeInt(64)) } func (f *decFnInfo) kInt32(rv reflect.Value) { rv.SetInt(f.d.d.DecodeInt(32)) } func (f *decFnInfo) kInt8(rv reflect.Value) { rv.SetInt(f.d.d.DecodeInt(8)) } func (f *decFnInfo) kInt16(rv reflect.Value) { rv.SetInt(f.d.d.DecodeInt(16)) } func (f *decFnInfo) kFloat32(rv reflect.Value) { rv.SetFloat(f.d.d.DecodeFloat(true)) } func (f *decFnInfo) kFloat64(rv reflect.Value) { rv.SetFloat(f.d.d.DecodeFloat(false)) } func (f *decFnInfo) kUint8(rv reflect.Value) { rv.SetUint(f.d.d.DecodeUint(8)) } func (f *decFnInfo) kUint64(rv reflect.Value) { rv.SetUint(f.d.d.DecodeUint(64)) } func (f *decFnInfo) kUint(rv reflect.Value) { rv.SetUint(f.d.d.DecodeUint(uintBitsize)) } func (f *decFnInfo) kUintptr(rv reflect.Value) { rv.SetUint(f.d.d.DecodeUint(uintBitsize)) } func (f *decFnInfo) kUint32(rv reflect.Value) { rv.SetUint(f.d.d.DecodeUint(32)) } func (f *decFnInfo) kUint16(rv reflect.Value) { rv.SetUint(f.d.d.DecodeUint(16)) } // func (f *decFnInfo) kPtr(rv reflect.Value) { // debugf(">>>>>>> ??? decode kPtr called - shouldn't get called") // if rv.IsNil() { // rv.Set(reflect.New(rv.Type().Elem())) // } // f.d.decodeValue(rv.Elem()) // } // var kIntfCtr uint64 func (f *decFnInfo) kInterfaceNaked() (rvn reflect.Value) { // nil interface: // use some hieristics to decode it appropriately // based on the detected next value in the stream. d := f.d d.d.DecodeNaked() n := &d.n if n.v == valueTypeNil { return } // We cannot decode non-nil stream value into nil interface with methods (e.g. io.Reader). // if num := f.ti.rt.NumMethod(); num > 0 { if f.ti.numMeth > 0 { d.errorf("cannot decode non-nil codec value into nil %v (%v methods)", f.ti.rt, f.ti.numMeth) return } // var useRvn bool switch n.v { case valueTypeMap: // if d.h.MapType == nil || d.h.MapType == mapIntfIntfTyp { // } else if d.h.MapType == mapStrIntfTyp { // for json performance // } if d.mtid == 0 || d.mtid == mapIntfIntfTypId { l := len(n.ms) n.ms = append(n.ms, nil) var v2 interface{} = &n.ms[l] d.decode(v2) rvn = reflect.ValueOf(v2).Elem() n.ms = n.ms[:l] } else if d.mtid == mapStrIntfTypId { // for json performance l := len(n.ns) n.ns = append(n.ns, nil) var v2 interface{} = &n.ns[l] d.decode(v2) rvn = reflect.ValueOf(v2).Elem() n.ns = n.ns[:l] } else { rvn = reflect.New(d.h.MapType).Elem() d.decodeValue(rvn, nil) } case valueTypeArray: // if d.h.SliceType == nil || d.h.SliceType == intfSliceTyp { if d.stid == 0 || d.stid == intfSliceTypId { l := len(n.ss) n.ss = append(n.ss, nil) var v2 interface{} = &n.ss[l] d.decode(v2) rvn = reflect.ValueOf(v2).Elem() n.ss = n.ss[:l] } else { rvn = reflect.New(d.h.SliceType).Elem() d.decodeValue(rvn, nil) } case valueTypeExt: var v interface{} tag, bytes := n.u, n.l // calling decode below might taint the values if bytes == nil { l := len(n.is) n.is = append(n.is, nil) v2 := &n.is[l] d.decode(v2) v = *v2 n.is = n.is[:l] } bfn := d.h.getExtForTag(tag) if bfn == nil { var re RawExt re.Tag = tag re.Data = detachZeroCopyBytes(d.bytes, nil, bytes) rvn = reflect.ValueOf(re) } else { rvnA := reflect.New(bfn.rt) rvn = rvnA.Elem() if bytes != nil { bfn.ext.ReadExt(rvnA.Interface(), bytes) } else { bfn.ext.UpdateExt(rvnA.Interface(), v) } } case valueTypeNil: // no-op case valueTypeInt: rvn = reflect.ValueOf(&n.i).Elem() case valueTypeUint: rvn = reflect.ValueOf(&n.u).Elem() case valueTypeFloat: rvn = reflect.ValueOf(&n.f).Elem() case valueTypeBool: rvn = reflect.ValueOf(&n.b).Elem() case valueTypeString, valueTypeSymbol: rvn = reflect.ValueOf(&n.s).Elem() case valueTypeBytes: rvn = reflect.ValueOf(&n.l).Elem() case valueTypeTimestamp: rvn = reflect.ValueOf(&n.t).Elem() default: panic(fmt.Errorf("kInterfaceNaked: unexpected valueType: %d", n.v)) } return } func (f *decFnInfo) kInterface(rv reflect.Value) { // debugf("\t===> kInterface") // Note: // A consequence of how kInterface works, is that // if an interface already contains something, we try // to decode into what was there before. // We do not replace with a generic value (as got from decodeNaked). var rvn reflect.Value if rv.IsNil() { rvn = f.kInterfaceNaked() if rvn.IsValid() { rv.Set(rvn) } } else if f.d.h.InterfaceReset { rvn = f.kInterfaceNaked() if rvn.IsValid() { rv.Set(rvn) } else { // reset to zero value based on current type in there. rv.Set(reflect.Zero(rv.Elem().Type())) } } else { rvn = rv.Elem() // Note: interface{} is settable, but underlying type may not be. // Consequently, we have to set the reflect.Value directly. // if underlying type is settable (e.g. ptr or interface), // we just decode into it. // Else we create a settable value, decode into it, and set on the interface. if rvn.CanSet() { f.d.decodeValue(rvn, nil) } else { rvn2 := reflect.New(rvn.Type()).Elem() rvn2.Set(rvn) f.d.decodeValue(rvn2, nil) rv.Set(rvn2) } } } func (f *decFnInfo) kStruct(rv reflect.Value) { fti := f.ti d := f.d dd := d.d cr := d.cr ctyp := dd.ContainerType() if ctyp == valueTypeMap { containerLen := dd.ReadMapStart() if containerLen == 0 { if cr != nil { cr.sendContainerState(containerMapEnd) } return } tisfi := fti.sfi hasLen := containerLen >= 0 if hasLen { for j := 0; j < containerLen; j++ { // rvkencname := dd.DecodeString() if cr != nil { cr.sendContainerState(containerMapKey) } rvkencname := stringView(dd.DecodeBytes(f.d.b[:], true, true)) // rvksi := ti.getForEncName(rvkencname) if cr != nil { cr.sendContainerState(containerMapValue) } if k := fti.indexForEncName(rvkencname); k > -1 { si := tisfi[k] if dd.TryDecodeAsNil() { si.setToZeroValue(rv) } else { d.decodeValue(si.field(rv, true), nil) } } else { d.structFieldNotFound(-1, rvkencname) } } } else { for j := 0; !dd.CheckBreak(); j++ { // rvkencname := dd.DecodeString() if cr != nil { cr.sendContainerState(containerMapKey) } rvkencname := stringView(dd.DecodeBytes(f.d.b[:], true, true)) // rvksi := ti.getForEncName(rvkencname) if cr != nil { cr.sendContainerState(containerMapValue) } if k := fti.indexForEncName(rvkencname); k > -1 { si := tisfi[k] if dd.TryDecodeAsNil() { si.setToZeroValue(rv) } else { d.decodeValue(si.field(rv, true), nil) } } else { d.structFieldNotFound(-1, rvkencname) } } } if cr != nil { cr.sendContainerState(containerMapEnd) } } else if ctyp == valueTypeArray { containerLen := dd.ReadArrayStart() if containerLen == 0 { if cr != nil { cr.sendContainerState(containerArrayEnd) } return } // Not much gain from doing it two ways for array. // Arrays are not used as much for structs. hasLen := containerLen >= 0 for j, si := range fti.sfip { if hasLen { if j == containerLen { break } } else if dd.CheckBreak() { break } if cr != nil { cr.sendContainerState(containerArrayElem) } if dd.TryDecodeAsNil() { si.setToZeroValue(rv) } else { d.decodeValue(si.field(rv, true), nil) } } if containerLen > len(fti.sfip) { // read remaining values and throw away for j := len(fti.sfip); j < containerLen; j++ { if cr != nil { cr.sendContainerState(containerArrayElem) } d.structFieldNotFound(j, "") } } if cr != nil { cr.sendContainerState(containerArrayEnd) } } else { f.d.error(onlyMapOrArrayCanDecodeIntoStructErr) return } } func (f *decFnInfo) kSlice(rv reflect.Value) { // A slice can be set from a map or array in stream. // This way, the order can be kept (as order is lost with map). ti := f.ti d := f.d dd := d.d rtelem0 := ti.rt.Elem() ctyp := dd.ContainerType() if ctyp == valueTypeBytes || ctyp == valueTypeString { // you can only decode bytes or string in the stream into a slice or array of bytes if !(ti.rtid == uint8SliceTypId || rtelem0.Kind() == reflect.Uint8) { f.d.errorf("bytes or string in the stream must be decoded into a slice or array of bytes, not %v", ti.rt) } if f.seq == seqTypeChan { bs2 := dd.DecodeBytes(nil, false, true) ch := rv.Interface().(chan<- byte) for _, b := range bs2 { ch <- b } } else { rvbs := rv.Bytes() bs2 := dd.DecodeBytes(rvbs, false, false) if rvbs == nil && bs2 != nil || rvbs != nil && bs2 == nil || len(bs2) != len(rvbs) { if rv.CanSet() { rv.SetBytes(bs2) } else { copy(rvbs, bs2) } } } return } // array := f.seq == seqTypeChan slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map) // // an array can never return a nil slice. so no need to check f.array here. if containerLenS == 0 { if f.seq == seqTypeSlice { if rv.IsNil() { rv.Set(reflect.MakeSlice(ti.rt, 0, 0)) } else { rv.SetLen(0) } } else if f.seq == seqTypeChan { if rv.IsNil() { rv.Set(reflect.MakeChan(ti.rt, 0)) } } slh.End() return } rtelem := rtelem0 for rtelem.Kind() == reflect.Ptr { rtelem = rtelem.Elem() } fn := d.getDecFn(rtelem, true, true) var rv0, rv9 reflect.Value rv0 = rv rvChanged := false // for j := 0; j < containerLenS; j++ { var rvlen int if containerLenS > 0 { // hasLen if f.seq == seqTypeChan { if rv.IsNil() { rvlen, _ = decInferLen(containerLenS, f.d.h.MaxInitLen, int(rtelem0.Size())) rv.Set(reflect.MakeChan(ti.rt, rvlen)) } // handle chan specially: for j := 0; j < containerLenS; j++ { rv9 = reflect.New(rtelem0).Elem() slh.ElemContainerState(j) d.decodeValue(rv9, fn) rv.Send(rv9) } } else { // slice or array var truncated bool // says len of sequence is not same as expected number of elements numToRead := containerLenS // if truncated, reset numToRead rvcap := rv.Cap() rvlen = rv.Len() if containerLenS > rvcap { if f.seq == seqTypeArray { d.arrayCannotExpand(rvlen, containerLenS) } else { oldRvlenGtZero := rvlen > 0 rvlen, truncated = decInferLen(containerLenS, f.d.h.MaxInitLen, int(rtelem0.Size())) if truncated { if rvlen <= rvcap { rv.SetLen(rvlen) } else { rv = reflect.MakeSlice(ti.rt, rvlen, rvlen) rvChanged = true } } else { rv = reflect.MakeSlice(ti.rt, rvlen, rvlen) rvChanged = true } if rvChanged && oldRvlenGtZero && !isImmutableKind(rtelem0.Kind()) { reflect.Copy(rv, rv0) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap) } rvcap = rvlen } numToRead = rvlen } else if containerLenS != rvlen { if f.seq == seqTypeSlice { rv.SetLen(containerLenS) rvlen = containerLenS } } j := 0 // we read up to the numToRead for ; j < numToRead; j++ { slh.ElemContainerState(j) d.decodeValue(rv.Index(j), fn) } // if slice, expand and read up to containerLenS (or EOF) iff truncated // if array, swallow all the rest. if f.seq == seqTypeArray { for ; j < containerLenS; j++ { slh.ElemContainerState(j) d.swallow() } } else if truncated { // slice was truncated, as chan NOT in this block for ; j < containerLenS; j++ { rv = expandSliceValue(rv, 1) rv9 = rv.Index(j) if resetSliceElemToZeroValue { rv9.Set(reflect.Zero(rtelem0)) } slh.ElemContainerState(j) d.decodeValue(rv9, fn) } } } } else { rvlen = rv.Len() j := 0 for ; !dd.CheckBreak(); j++ { if f.seq == seqTypeChan { slh.ElemContainerState(j) rv9 = reflect.New(rtelem0).Elem() d.decodeValue(rv9, fn) rv.Send(rv9) } else { // if indefinite, etc, then expand the slice if necessary var decodeIntoBlank bool if j >= rvlen { if f.seq == seqTypeArray { d.arrayCannotExpand(rvlen, j+1) decodeIntoBlank = true } else { // if f.seq == seqTypeSlice // rv = reflect.Append(rv, reflect.Zero(rtelem0)) // uses append logic, plus varargs rv = expandSliceValue(rv, 1) rv9 = rv.Index(j) // rv.Index(rv.Len() - 1).Set(reflect.Zero(rtelem0)) if resetSliceElemToZeroValue { rv9.Set(reflect.Zero(rtelem0)) } rvlen++ rvChanged = true } } else { // slice or array rv9 = rv.Index(j) } slh.ElemContainerState(j) if decodeIntoBlank { d.swallow() } else { // seqTypeSlice d.decodeValue(rv9, fn) } } } if f.seq == seqTypeSlice { if j < rvlen { rv.SetLen(j) } else if j == 0 && rv.IsNil() { rv = reflect.MakeSlice(ti.rt, 0, 0) rvChanged = true } } } slh.End() if rvChanged { rv0.Set(rv) } } func (f *decFnInfo) kArray(rv reflect.Value) { // f.d.decodeValue(rv.Slice(0, rv.Len())) f.kSlice(rv.Slice(0, rv.Len())) } func (f *decFnInfo) kMap(rv reflect.Value) { d := f.d dd := d.d containerLen := dd.ReadMapStart() cr := d.cr ti := f.ti if rv.IsNil() { rv.Set(reflect.MakeMap(ti.rt)) } if containerLen == 0 { if cr != nil { cr.sendContainerState(containerMapEnd) } return } ktype, vtype := ti.rt.Key(), ti.rt.Elem() ktypeId := reflect.ValueOf(ktype).Pointer() vtypeKind := vtype.Kind() var keyFn, valFn *decFn var xtyp reflect.Type for xtyp = ktype; xtyp.Kind() == reflect.Ptr; xtyp = xtyp.Elem() { } keyFn = d.getDecFn(xtyp, true, true) for xtyp = vtype; xtyp.Kind() == reflect.Ptr; xtyp = xtyp.Elem() { } valFn = d.getDecFn(xtyp, true, true) var mapGet, mapSet bool if !f.d.h.MapValueReset { // if pointer, mapGet = true // if interface, mapGet = true if !DecodeNakedAlways (else false) // if builtin, mapGet = false // else mapGet = true if vtypeKind == reflect.Ptr { mapGet = true } else if vtypeKind == reflect.Interface { if !f.d.h.InterfaceReset { mapGet = true } } else if !isImmutableKind(vtypeKind) { mapGet = true } } var rvk, rvv, rvz reflect.Value // for j := 0; j < containerLen; j++ { if containerLen > 0 { for j := 0; j < containerLen; j++ { rvk = reflect.New(ktype).Elem() if cr != nil { cr.sendContainerState(containerMapKey) } d.decodeValue(rvk, keyFn) // special case if a byte array. if ktypeId == intfTypId { rvk = rvk.Elem() if rvk.Type() == uint8SliceTyp { rvk = reflect.ValueOf(d.string(rvk.Bytes())) } } mapSet = true // set to false if u do a get, and its a pointer, and exists if mapGet { rvv = rv.MapIndex(rvk) if rvv.IsValid() { if vtypeKind == reflect.Ptr { mapSet = false } } else { if rvz.IsValid() { rvz.Set(reflect.Zero(vtype)) } else { rvz = reflect.New(vtype).Elem() } rvv = rvz } } else { if rvz.IsValid() { rvz.Set(reflect.Zero(vtype)) } else { rvz = reflect.New(vtype).Elem() } rvv = rvz } if cr != nil { cr.sendContainerState(containerMapValue) } d.decodeValue(rvv, valFn) if mapSet { rv.SetMapIndex(rvk, rvv) } } } else { for j := 0; !dd.CheckBreak(); j++ { rvk = reflect.New(ktype).Elem() if cr != nil { cr.sendContainerState(containerMapKey) } d.decodeValue(rvk, keyFn) // special case if a byte array. if ktypeId == intfTypId { rvk = rvk.Elem() if rvk.Type() == uint8SliceTyp { rvk = reflect.ValueOf(d.string(rvk.Bytes())) } } mapSet = true // set to false if u do a get, and its a pointer, and exists if mapGet { rvv = rv.MapIndex(rvk) if rvv.IsValid() { if vtypeKind == reflect.Ptr { mapSet = false } } else { if rvz.IsValid() { rvz.Set(reflect.Zero(vtype)) } else { rvz = reflect.New(vtype).Elem() } rvv = rvz } } else { if rvz.IsValid() { rvz.Set(reflect.Zero(vtype)) } else { rvz = reflect.New(vtype).Elem() } rvv = rvz } if cr != nil { cr.sendContainerState(containerMapValue) } d.decodeValue(rvv, valFn) if mapSet { rv.SetMapIndex(rvk, rvv) } } } if cr != nil { cr.sendContainerState(containerMapEnd) } } type decRtidFn struct { rtid uintptr fn decFn } // decNaked is used to keep track of the primitives decoded. // Without it, we would have to decode each primitive and wrap it // in an interface{}, causing an allocation. // In this model, the primitives are decoded in a "pseudo-atomic" fashion, // so we can rest assured that no other decoding happens while these // primitives are being decoded. // // maps and arrays are not handled by this mechanism. // However, RawExt is, and we accommodate for extensions that decode // RawExt from DecodeNaked, but need to decode the value subsequently. // kInterfaceNaked and swallow, which call DecodeNaked, handle this caveat. // // However, decNaked also keeps some arrays of default maps and slices // used in DecodeNaked. This way, we can get a pointer to it // without causing a new heap allocation. // // kInterfaceNaked will ensure that there is no allocation for the common // uses. type decNaked struct { // r RawExt // used for RawExt, uint, []byte. u uint64 i int64 f float64 l []byte s string t time.Time b bool v valueType // stacks for reducing allocation is []interface{} ms []map[interface{}]interface{} ns []map[string]interface{} ss [][]interface{} // rs []RawExt // keep arrays at the bottom? Chance is that they are not used much. ia [4]interface{} ma [4]map[interface{}]interface{} na [4]map[string]interface{} sa [4][]interface{} // ra [2]RawExt } func (n *decNaked) reset() { if n.ss != nil { n.ss = n.ss[:0] } if n.is != nil { n.is = n.is[:0] } if n.ms != nil { n.ms = n.ms[:0] } if n.ns != nil { n.ns = n.ns[:0] } } // A Decoder reads and decodes an object from an input stream in the codec format. type Decoder struct { // hopefully, reduce derefencing cost by laying the decReader inside the Decoder. // Try to put things that go together to fit within a cache line (8 words). d decDriver // NOTE: Decoder shouldn't call it's read methods, // as the handler MAY need to do some coordination. r decReader // sa [initCollectionCap]decRtidFn h *BasicHandle hh Handle be bool // is binary encoding bytes bool // is bytes reader js bool // is json handle rb bytesDecReader ri ioDecReader cr containerStateRecv s []decRtidFn f map[uintptr]*decFn // _ uintptr // for alignment purposes, so next one starts from a cache line // cache the mapTypeId and sliceTypeId for faster comparisons mtid uintptr stid uintptr n decNaked b [scratchByteArrayLen]byte is map[string]string // used for interning strings } // NewDecoder returns a Decoder for decoding a stream of bytes from an io.Reader. // // For efficiency, Users are encouraged to pass in a memory buffered reader // (eg bufio.Reader, bytes.Buffer). func NewDecoder(r io.Reader, h Handle) *Decoder { d := newDecoder(h) d.Reset(r) return d } // NewDecoderBytes returns a Decoder which efficiently decodes directly // from a byte slice with zero copying. func NewDecoderBytes(in []byte, h Handle) *Decoder { d := newDecoder(h) d.ResetBytes(in) return d } func newDecoder(h Handle) *Decoder { d := &Decoder{hh: h, h: h.getBasicHandle(), be: h.isBinary()} n := &d.n // n.rs = n.ra[:0] n.ms = n.ma[:0] n.is = n.ia[:0] n.ns = n.na[:0] n.ss = n.sa[:0] _, d.js = h.(*JsonHandle) if d.h.InternString { d.is = make(map[string]string, 32) } d.d = h.newDecDriver(d) d.cr, _ = d.d.(containerStateRecv) // d.d = h.newDecDriver(decReaderT{true, &d.rb, &d.ri}) return d } func (d *Decoder) resetCommon() { d.n.reset() d.d.reset() // reset all things which were cached from the Handle, // but could be changed. d.mtid, d.stid = 0, 0 if d.h.MapType != nil { d.mtid = reflect.ValueOf(d.h.MapType).Pointer() } if d.h.SliceType != nil { d.stid = reflect.ValueOf(d.h.SliceType).Pointer() } } func (d *Decoder) Reset(r io.Reader) { d.ri.x = &d.b // d.s = d.sa[:0] d.ri.bs.r = r var ok bool d.ri.br, ok = r.(decReaderByteScanner) if !ok { d.ri.br = &d.ri.bs } d.r = &d.ri d.resetCommon() } func (d *Decoder) ResetBytes(in []byte) { // d.s = d.sa[:0] d.rb.reset(in) d.r = &d.rb d.resetCommon() } // func (d *Decoder) sendContainerState(c containerState) { // if d.cr != nil { // d.cr.sendContainerState(c) // } // } // Decode decodes the stream from reader and stores the result in the // value pointed to by v. v cannot be a nil pointer. v can also be // a reflect.Value of a pointer. // // Note that a pointer to a nil interface is not a nil pointer. // If you do not know what type of stream it is, pass in a pointer to a nil interface. // We will decode and store a value in that nil interface. // // Sample usages: // // Decoding into a non-nil typed value // var f float32 // err = codec.NewDecoder(r, handle).Decode(&f) // // // Decoding into nil interface // var v interface{} // dec := codec.NewDecoder(r, handle) // err = dec.Decode(&v) // // When decoding into a nil interface{}, we will decode into an appropriate value based // on the contents of the stream: // - Numbers are decoded as float64, int64 or uint64. // - Other values are decoded appropriately depending on the type: // bool, string, []byte, time.Time, etc // - Extensions are decoded as RawExt (if no ext function registered for the tag) // Configurations exist on the Handle to override defaults // (e.g. for MapType, SliceType and how to decode raw bytes). // // When decoding into a non-nil interface{} value, the mode of encoding is based on the // type of the value. When a value is seen: // - If an extension is registered for it, call that extension function // - If it implements BinaryUnmarshaler, call its UnmarshalBinary(data []byte) error // - Else decode it based on its reflect.Kind // // There are some special rules when decoding into containers (slice/array/map/struct). // Decode will typically use the stream contents to UPDATE the container. // - A map can be decoded from a stream map, by updating matching keys. // - A slice can be decoded from a stream array, // by updating the first n elements, where n is length of the stream. // - A slice can be decoded from a stream map, by decoding as if // it contains a sequence of key-value pairs. // - A struct can be decoded from a stream map, by updating matching fields. // - A struct can be decoded from a stream array, // by updating fields as they occur in the struct (by index). // // When decoding a stream map or array with length of 0 into a nil map or slice, // we reset the destination map or slice to a zero-length value. // // However, when decoding a stream nil, we reset the destination container // to its "zero" value (e.g. nil for slice/map, etc). // func (d *Decoder) Decode(v interface{}) (err error) { defer panicToErr(&err) d.decode(v) return } // this is not a smart swallow, as it allocates objects and does unnecessary work. func (d *Decoder) swallowViaHammer() { var blank interface{} d.decodeValue(reflect.ValueOf(&blank).Elem(), nil) } func (d *Decoder) swallow() { // smarter decode that just swallows the content dd := d.d if dd.TryDecodeAsNil() { return } cr := d.cr switch dd.ContainerType() { case valueTypeMap: containerLen := dd.ReadMapStart() clenGtEqualZero := containerLen >= 0 for j := 0; ; j++ { if clenGtEqualZero { if j >= containerLen { break } } else if dd.CheckBreak() { break } if cr != nil { cr.sendContainerState(containerMapKey) } d.swallow() if cr != nil { cr.sendContainerState(containerMapValue) } d.swallow() } if cr != nil { cr.sendContainerState(containerMapEnd) } case valueTypeArray: containerLenS := dd.ReadArrayStart() clenGtEqualZero := containerLenS >= 0 for j := 0; ; j++ { if clenGtEqualZero { if j >= containerLenS { break } } else if dd.CheckBreak() { break } if cr != nil { cr.sendContainerState(containerArrayElem) } d.swallow() } if cr != nil { cr.sendContainerState(containerArrayEnd) } case valueTypeBytes: dd.DecodeBytes(d.b[:], false, true) case valueTypeString: dd.DecodeBytes(d.b[:], true, true) // dd.DecodeStringAsBytes(d.b[:]) default: // these are all primitives, which we can get from decodeNaked // if RawExt using Value, complete the processing. dd.DecodeNaked() if n := &d.n; n.v == valueTypeExt && n.l == nil { l := len(n.is) n.is = append(n.is, nil) v2 := &n.is[l] d.decode(v2) n.is = n.is[:l] } } } // MustDecode is like Decode, but panics if unable to Decode. // This provides insight to the code location that triggered the error. func (d *Decoder) MustDecode(v interface{}) { d.decode(v) } func (d *Decoder) decode(iv interface{}) { // if ics, ok := iv.(Selfer); ok { // ics.CodecDecodeSelf(d) // return // } if d.d.TryDecodeAsNil() { switch v := iv.(type) { case nil: case *string: *v = "" case *bool: *v = false case *int: *v = 0 case *int8: *v = 0 case *int16: *v = 0 case *int32: *v = 0 case *int64: *v = 0 case *uint: *v = 0 case *uint8: *v = 0 case *uint16: *v = 0 case *uint32: *v = 0 case *uint64: *v = 0 case *float32: *v = 0 case *float64: *v = 0 case *[]uint8: *v = nil case *Raw: *v = nil case reflect.Value: if v.Kind() != reflect.Ptr || v.IsNil() { d.errNotValidPtrValue(v) } // d.chkPtrValue(v) v = v.Elem() if v.IsValid() { v.Set(reflect.Zero(v.Type())) } default: rv := reflect.ValueOf(iv) if rv.Kind() != reflect.Ptr || rv.IsNil() { d.errNotValidPtrValue(rv) } // d.chkPtrValue(rv) rv = rv.Elem() if rv.IsValid() { rv.Set(reflect.Zero(rv.Type())) } } return } switch v := iv.(type) { case nil: d.error(cannotDecodeIntoNilErr) return case Selfer: v.CodecDecodeSelf(d) case reflect.Value: if v.Kind() != reflect.Ptr || v.IsNil() { d.errNotValidPtrValue(v) } // d.chkPtrValue(v) d.decodeValueNotNil(v.Elem(), nil) case *string: *v = d.d.DecodeString() case *bool: *v = d.d.DecodeBool() case *int: *v = int(d.d.DecodeInt(intBitsize)) case *int8: *v = int8(d.d.DecodeInt(8)) case *int16: *v = int16(d.d.DecodeInt(16)) case *int32: *v = int32(d.d.DecodeInt(32)) case *int64: *v = d.d.DecodeInt(64) case *uint: *v = uint(d.d.DecodeUint(uintBitsize)) case *uint8: *v = uint8(d.d.DecodeUint(8)) case *uint16: *v = uint16(d.d.DecodeUint(16)) case *uint32: *v = uint32(d.d.DecodeUint(32)) case *uint64: *v = d.d.DecodeUint(64) case *float32: *v = float32(d.d.DecodeFloat(true)) case *float64: *v = d.d.DecodeFloat(false) case *[]uint8: *v = d.d.DecodeBytes(*v, false, false) case *Raw: *v = d.raw() case *interface{}: d.decodeValueNotNil(reflect.ValueOf(iv).Elem(), nil) default: if !fastpathDecodeTypeSwitch(iv, d) { d.decodeI(iv, true, false, false, false) } } } func (d *Decoder) preDecodeValue(rv reflect.Value, tryNil bool) (rv2 reflect.Value, proceed bool) { if tryNil && d.d.TryDecodeAsNil() { // No need to check if a ptr, recursively, to determine // whether to set value to nil. // Just always set value to its zero type. if rv.IsValid() { // rv.CanSet() // always settable, except it's invalid rv.Set(reflect.Zero(rv.Type())) } return } // If stream is not containing a nil value, then we can deref to the base // non-pointer value, and decode into that. for rv.Kind() == reflect.Ptr { if rv.IsNil() { rv.Set(reflect.New(rv.Type().Elem())) } rv = rv.Elem() } return rv, true } func (d *Decoder) decodeI(iv interface{}, checkPtr, tryNil, checkFastpath, checkCodecSelfer bool) { rv := reflect.ValueOf(iv) if checkPtr { if rv.Kind() != reflect.Ptr || rv.IsNil() { d.errNotValidPtrValue(rv) } // d.chkPtrValue(rv) } rv, proceed := d.preDecodeValue(rv, tryNil) if proceed { fn := d.getDecFn(rv.Type(), checkFastpath, checkCodecSelfer) fn.f(&fn.i, rv) } } func (d *Decoder) decodeValue(rv reflect.Value, fn *decFn) { if rv, proceed := d.preDecodeValue(rv, true); proceed { if fn == nil { fn = d.getDecFn(rv.Type(), true, true) } fn.f(&fn.i, rv) } } func (d *Decoder) decodeValueNotNil(rv reflect.Value, fn *decFn) { if rv, proceed := d.preDecodeValue(rv, false); proceed { if fn == nil { fn = d.getDecFn(rv.Type(), true, true) } fn.f(&fn.i, rv) } } func (d *Decoder) getDecFn(rt reflect.Type, checkFastpath, checkCodecSelfer bool) (fn *decFn) { rtid := reflect.ValueOf(rt).Pointer() // retrieve or register a focus'ed function for this type // to eliminate need to do the retrieval multiple times // if d.f == nil && d.s == nil { debugf("---->Creating new dec f map for type: %v\n", rt) } var ok bool if useMapForCodecCache { fn, ok = d.f[rtid] } else { for i := range d.s { v := &(d.s[i]) if v.rtid == rtid { fn, ok = &(v.fn), true break } } } if ok { return } if useMapForCodecCache { if d.f == nil { d.f = make(map[uintptr]*decFn, initCollectionCap) } fn = new(decFn) d.f[rtid] = fn } else { if d.s == nil { d.s = make([]decRtidFn, 0, initCollectionCap) } d.s = append(d.s, decRtidFn{rtid: rtid}) fn = &(d.s[len(d.s)-1]).fn } // debugf("\tCreating new dec fn for type: %v\n", rt) ti := d.h.getTypeInfo(rtid, rt) fi := &(fn.i) fi.d = d fi.ti = ti // An extension can be registered for any type, regardless of the Kind // (e.g. type BitSet int64, type MyStruct { / * unexported fields * / }, type X []int, etc. // // We can't check if it's an extension byte here first, because the user may have // registered a pointer or non-pointer type, meaning we may have to recurse first // before matching a mapped type, even though the extension byte is already detected. // // NOTE: if decoding into a nil interface{}, we return a non-nil // value except even if the container registers a length of 0. if checkCodecSelfer && ti.cs { fn.f = (*decFnInfo).selferUnmarshal } else if rtid == rawExtTypId { fn.f = (*decFnInfo).rawExt } else if rtid == rawTypId { fn.f = (*decFnInfo).raw } else if d.d.IsBuiltinType(rtid) { fn.f = (*decFnInfo).builtin } else if xfFn := d.h.getExt(rtid); xfFn != nil { fi.xfTag, fi.xfFn = xfFn.tag, xfFn.ext fn.f = (*decFnInfo).ext } else if supportMarshalInterfaces && d.be && ti.bunm { fn.f = (*decFnInfo).binaryUnmarshal } else if supportMarshalInterfaces && !d.be && d.js && ti.junm { //If JSON, we should check JSONUnmarshal before textUnmarshal fn.f = (*decFnInfo).jsonUnmarshal } else if supportMarshalInterfaces && !d.be && ti.tunm { fn.f = (*decFnInfo).textUnmarshal } else { rk := rt.Kind() if fastpathEnabled && checkFastpath && (rk == reflect.Map || rk == reflect.Slice) { if rt.PkgPath() == "" { if idx := fastpathAV.index(rtid); idx != -1 { fn.f = fastpathAV[idx].decfn } } else { // use mapping for underlying type if there ok = false var rtu reflect.Type if rk == reflect.Map { rtu = reflect.MapOf(rt.Key(), rt.Elem()) } else { rtu = reflect.SliceOf(rt.Elem()) } rtuid := reflect.ValueOf(rtu).Pointer() if idx := fastpathAV.index(rtuid); idx != -1 { xfnf := fastpathAV[idx].decfn xrt := fastpathAV[idx].rt fn.f = func(xf *decFnInfo, xrv reflect.Value) { // xfnf(xf, xrv.Convert(xrt)) xfnf(xf, xrv.Addr().Convert(reflect.PtrTo(xrt)).Elem()) } } } } if fn.f == nil { switch rk { case reflect.String: fn.f = (*decFnInfo).kString case reflect.Bool: fn.f = (*decFnInfo).kBool case reflect.Int: fn.f = (*decFnInfo).kInt case reflect.Int64: fn.f = (*decFnInfo).kInt64 case reflect.Int32: fn.f = (*decFnInfo).kInt32 case reflect.Int8: fn.f = (*decFnInfo).kInt8 case reflect.Int16: fn.f = (*decFnInfo).kInt16 case reflect.Float32: fn.f = (*decFnInfo).kFloat32 case reflect.Float64: fn.f = (*decFnInfo).kFloat64 case reflect.Uint8: fn.f = (*decFnInfo).kUint8 case reflect.Uint64: fn.f = (*decFnInfo).kUint64 case reflect.Uint: fn.f = (*decFnInfo).kUint case reflect.Uint32: fn.f = (*decFnInfo).kUint32 case reflect.Uint16: fn.f = (*decFnInfo).kUint16 // case reflect.Ptr: // fn.f = (*decFnInfo).kPtr case reflect.Uintptr: fn.f = (*decFnInfo).kUintptr case reflect.Interface: fn.f = (*decFnInfo).kInterface case reflect.Struct: fn.f = (*decFnInfo).kStruct case reflect.Chan: fi.seq = seqTypeChan fn.f = (*decFnInfo).kSlice case reflect.Slice: fi.seq = seqTypeSlice fn.f = (*decFnInfo).kSlice case reflect.Array: fi.seq = seqTypeArray fn.f = (*decFnInfo).kArray case reflect.Map: fn.f = (*decFnInfo).kMap default: fn.f = (*decFnInfo).kErr } } } return } func (d *Decoder) structFieldNotFound(index int, rvkencname string) { // NOTE: rvkencname may be a stringView, so don't pass it to another function. if d.h.ErrorIfNoField { if index >= 0 { d.errorf("no matching struct field found when decoding stream array at index %v", index) return } else if rvkencname != "" { d.errorf("no matching struct field found when decoding stream map with key " + rvkencname) return } } d.swallow() } func (d *Decoder) arrayCannotExpand(sliceLen, streamLen int) { if d.h.ErrorIfNoArrayExpand { d.errorf("cannot expand array len during decode from %v to %v", sliceLen, streamLen) } } func (d *Decoder) chkPtrValue(rv reflect.Value) { // We can only decode into a non-nil pointer if rv.Kind() == reflect.Ptr && !rv.IsNil() { return } d.errNotValidPtrValue(rv) } func (d *Decoder) errNotValidPtrValue(rv reflect.Value) { if !rv.IsValid() { d.error(cannotDecodeIntoNilErr) return } if !rv.CanInterface() { d.errorf("cannot decode into a value without an interface: %v", rv) return } rvi := rv.Interface() d.errorf("cannot decode into non-pointer or nil pointer. Got: %v, %T, %v", rv.Kind(), rvi, rvi) } func (d *Decoder) error(err error) { panic(err) } func (d *Decoder) errorf(format string, params ...interface{}) { params2 := make([]interface{}, len(params)+1) params2[0] = d.r.numread() copy(params2[1:], params) err := fmt.Errorf("[pos %d]: "+format, params2...) panic(err) } func (d *Decoder) string(v []byte) (s string) { if d.is != nil { s, ok := d.is[string(v)] // no allocation here. if !ok { s = string(v) d.is[s] = s } return s } return string(v) // don't return stringView, as we need a real string here. } func (d *Decoder) intern(s string) { if d.is != nil { d.is[s] = s } } // nextValueBytes returns the next value in the stream as a set of bytes. func (d *Decoder) nextValueBytes() []byte { d.d.uncacheRead() d.r.track() d.swallow() return d.r.stopTrack() } func (d *Decoder) raw() []byte { // ensure that this is not a view into the bytes // i.e. make new copy always. bs := d.nextValueBytes() bs2 := make([]byte, len(bs)) copy(bs2, bs) return bs2 } // -------------------------------------------------- // decSliceHelper assists when decoding into a slice, from a map or an array in the stream. // A slice can be set from a map or array in stream. This supports the MapBySlice interface. type decSliceHelper struct { d *Decoder // ct valueType array bool } func (d *Decoder) decSliceHelperStart() (x decSliceHelper, clen int) { dd := d.d ctyp := dd.ContainerType() if ctyp == valueTypeArray { x.array = true clen = dd.ReadArrayStart() } else if ctyp == valueTypeMap { clen = dd.ReadMapStart() * 2 } else { d.errorf("only encoded map or array can be decoded into a slice (%d)", ctyp) } // x.ct = ctyp x.d = d return } func (x decSliceHelper) End() { cr := x.d.cr if cr == nil { return } if x.array { cr.sendContainerState(containerArrayEnd) } else { cr.sendContainerState(containerMapEnd) } } func (x decSliceHelper) ElemContainerState(index int) { cr := x.d.cr if cr == nil { return } if x.array { cr.sendContainerState(containerArrayElem) } else { if index%2 == 0 { cr.sendContainerState(containerMapKey) } else { cr.sendContainerState(containerMapValue) } } } func decByteSlice(r decReader, clen int, bs []byte) (bsOut []byte) { if clen == 0 { return zeroByteSlice } if len(bs) == clen { bsOut = bs } else if cap(bs) >= clen { bsOut = bs[:clen] } else { bsOut = make([]byte, clen) } r.readb(bsOut) return } func detachZeroCopyBytes(isBytesReader bool, dest []byte, in []byte) (out []byte) { if xlen := len(in); xlen > 0 { if isBytesReader || xlen <= scratchByteArrayLen { if cap(dest) >= xlen { out = dest[:xlen] } else { out = make([]byte, xlen) } copy(out, in) return } } return in } // decInferLen will infer a sensible length, given the following: // - clen: length wanted. // - maxlen: max length to be returned. // if <= 0, it is unset, and we infer it based on the unit size // - unit: number of bytes for each element of the collection func decInferLen(clen, maxlen, unit int) (rvlen int, truncated bool) { // handle when maxlen is not set i.e. <= 0 if clen <= 0 { return } if maxlen <= 0 { // no maxlen defined. Use maximum of 256K memory, with a floor of 4K items. // maxlen = 256 * 1024 / unit // if maxlen < (4 * 1024) { // maxlen = 4 * 1024 // } if unit < (256 / 4) { maxlen = 256 * 1024 / unit } else { maxlen = 4 * 1024 } } if clen > maxlen { rvlen = maxlen truncated = true } else { rvlen = clen } return // if clen <= 0 { // rvlen = 0 // } else if maxlen > 0 && clen > maxlen { // rvlen = maxlen // truncated = true // } else { // rvlen = clen // } // return } // // implement overall decReader wrapping both, for possible use inline: // type decReaderT struct { // bytes bool // rb *bytesDecReader // ri *ioDecReader // } // // // implement *Decoder as a decReader. // // Using decReaderT (defined just above) caused performance degradation // // possibly because of constant copying the value, // // and some value->interface conversion causing allocation. // func (d *Decoder) unreadn1() { // if d.bytes { // d.rb.unreadn1() // } else { // d.ri.unreadn1() // } // } // ... for other methods of decReader. // Testing showed that performance improvement was negligible.
{'content_hash': 'eeab8d5e5b26279324a036ecc92a5746', 'timestamp': '', 'source': 'github', 'line_count': 2038, 'max_line_length': 108, 'avg_line_length': 25.355250245338567, 'alnum_prop': 0.6382706970623524, 'repo_name': 'timoreimann/kubernetes-goclient-example', 'id': '8b7a1b0d3fc61d89791be11e5674f43670d09746', 'size': '51820', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/ugorji/go/codec/decode.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '8309'}, {'name': 'Shell', 'bytes': '1320'}]}
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInit6de589382832223dfa71adf9fb03f62e { public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { }, null, ClassLoader::class); } }
{'content_hash': 'fa0f1d974fea6909fc87c225a1ebc3fe', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 62, 'avg_line_length': 21.133333333333333, 'alnum_prop': 0.7066246056782335, 'repo_name': 'Sonic23X/upp', 'id': '2d9a4c8821ca19d2e4170d9509df98413a61ebe3', 'size': '317', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/composer/autoload_static.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '352144'}, {'name': 'HTML', 'bytes': '6200'}, {'name': 'JavaScript', 'bytes': '143170'}, {'name': 'PHP', 'bytes': '16820'}]}
package org.apache.ignite.internal.processors.platform.client.cache; import org.apache.ignite.internal.binary.BinaryRawReaderEx; import org.apache.ignite.internal.processors.platform.client.ClientConnectionContext; import org.apache.ignite.internal.processors.platform.client.ClientResponse; /** * Cache put request. */ public class ClientCachePutRequest extends ClientCacheKeyValueRequest { /** * Ctor. * * @param reader Reader. */ public ClientCachePutRequest(BinaryRawReaderEx reader) { super(reader); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public ClientResponse process(ClientConnectionContext ctx) { cache(ctx).put(key(), val()); return super.process(ctx); } }
{'content_hash': 'b73ccc5d9ead438ee03c6c94de70506b', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 85, 'avg_line_length': 26.586206896551722, 'alnum_prop': 0.7133592736705577, 'repo_name': 'ntikhonov/ignite', 'id': '94c2b25ad5ca0596cf88dad3e5a39cd78fd2fb9b', 'size': '1573', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'modules/core/src/main/java/org/apache/ignite/internal/processors/platform/client/cache/ClientCachePutRequest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '48727'}, {'name': 'C', 'bytes': '5286'}, {'name': 'C#', 'bytes': '5368172'}, {'name': 'C++', 'bytes': '2902467'}, {'name': 'CSS', 'bytes': '196133'}, {'name': 'Groovy', 'bytes': '15092'}, {'name': 'HTML', 'bytes': '638057'}, {'name': 'Java', 'bytes': '30814747'}, {'name': 'JavaScript', 'bytes': '1321793'}, {'name': 'M4', 'bytes': '12456'}, {'name': 'Makefile', 'bytes': '106017'}, {'name': 'PHP', 'bytes': '11079'}, {'name': 'PowerShell', 'bytes': '14438'}, {'name': 'SQLPL', 'bytes': '307'}, {'name': 'Scala', 'bytes': '686721'}, {'name': 'Shell', 'bytes': '600296'}, {'name': 'Smalltalk', 'bytes': '1908'}]}
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AgeCalculation")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AgeCalculation")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("630e9c13-caa5-4317-b843-496b7b51654c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{'content_hash': 'bae5a66b39f6c6ac653d102810f303a8', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 84, 'avg_line_length': 38.916666666666664, 'alnum_prop': 0.7458957887223412, 'repo_name': 'PetarTilevRusev/Introduction-to-Programming-Homework', 'id': '49388209d6f8629991164bce08a2fffe296e52ed', 'size': '1404', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'AgeCalculation/Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '23206'}]}
// flow-typed signature: 68647205d5dabaccce652d5559bfd35c // flow-typed version: <<STUB>>/sinon_v^1.17.7/flow_v0.37.4 /** * This is an autogenerated libdef stub for: * * 'sinon' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'sinon' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'sinon/lib/sinon' { declare module.exports: any; } declare module 'sinon/lib/sinon/assert' { declare module.exports: any; } declare module 'sinon/lib/sinon/behavior' { declare module.exports: any; } declare module 'sinon/lib/sinon/call' { declare module.exports: any; } declare module 'sinon/lib/sinon/collection' { declare module.exports: any; } declare module 'sinon/lib/sinon/extend' { declare module.exports: any; } declare module 'sinon/lib/sinon/format' { declare module.exports: any; } declare module 'sinon/lib/sinon/log_error' { declare module.exports: any; } declare module 'sinon/lib/sinon/match' { declare module.exports: any; } declare module 'sinon/lib/sinon/mock' { declare module.exports: any; } declare module 'sinon/lib/sinon/sandbox' { declare module.exports: any; } declare module 'sinon/lib/sinon/spy' { declare module.exports: any; } declare module 'sinon/lib/sinon/stub' { declare module.exports: any; } declare module 'sinon/lib/sinon/test_case' { declare module.exports: any; } declare module 'sinon/lib/sinon/test' { declare module.exports: any; } declare module 'sinon/lib/sinon/times_in_words' { declare module.exports: any; } declare module 'sinon/lib/sinon/typeOf' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/core' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/event' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/fake_server_with_clock' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/fake_server' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/fake_timers' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/fake_xdomain_request' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/fake_xml_http_request' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/timers_ie' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/xdr_ie' { declare module.exports: any; } declare module 'sinon/lib/sinon/util/xhr_ie' { declare module.exports: any; } declare module 'sinon/lib/sinon/walk' { declare module.exports: any; } declare module 'sinon/pkg/sinon-1.17.7' { declare module.exports: any; } declare module 'sinon/pkg/sinon-ie-1.17.7' { declare module.exports: any; } declare module 'sinon/pkg/sinon-ie' { declare module.exports: any; } declare module 'sinon/pkg/sinon-server-1.17.7' { declare module.exports: any; } declare module 'sinon/pkg/sinon-server' { declare module.exports: any; } declare module 'sinon/pkg/sinon' { declare module.exports: any; } // Filename aliases declare module 'sinon/lib/sinon.js' { declare module.exports: $Exports<'sinon/lib/sinon'>; } declare module 'sinon/lib/sinon/assert.js' { declare module.exports: $Exports<'sinon/lib/sinon/assert'>; } declare module 'sinon/lib/sinon/behavior.js' { declare module.exports: $Exports<'sinon/lib/sinon/behavior'>; } declare module 'sinon/lib/sinon/call.js' { declare module.exports: $Exports<'sinon/lib/sinon/call'>; } declare module 'sinon/lib/sinon/collection.js' { declare module.exports: $Exports<'sinon/lib/sinon/collection'>; } declare module 'sinon/lib/sinon/extend.js' { declare module.exports: $Exports<'sinon/lib/sinon/extend'>; } declare module 'sinon/lib/sinon/format.js' { declare module.exports: $Exports<'sinon/lib/sinon/format'>; } declare module 'sinon/lib/sinon/log_error.js' { declare module.exports: $Exports<'sinon/lib/sinon/log_error'>; } declare module 'sinon/lib/sinon/match.js' { declare module.exports: $Exports<'sinon/lib/sinon/match'>; } declare module 'sinon/lib/sinon/mock.js' { declare module.exports: $Exports<'sinon/lib/sinon/mock'>; } declare module 'sinon/lib/sinon/sandbox.js' { declare module.exports: $Exports<'sinon/lib/sinon/sandbox'>; } declare module 'sinon/lib/sinon/spy.js' { declare module.exports: $Exports<'sinon/lib/sinon/spy'>; } declare module 'sinon/lib/sinon/stub.js' { declare module.exports: $Exports<'sinon/lib/sinon/stub'>; } declare module 'sinon/lib/sinon/test_case.js' { declare module.exports: $Exports<'sinon/lib/sinon/test_case'>; } declare module 'sinon/lib/sinon/test.js' { declare module.exports: $Exports<'sinon/lib/sinon/test'>; } declare module 'sinon/lib/sinon/times_in_words.js' { declare module.exports: $Exports<'sinon/lib/sinon/times_in_words'>; } declare module 'sinon/lib/sinon/typeOf.js' { declare module.exports: $Exports<'sinon/lib/sinon/typeOf'>; } declare module 'sinon/lib/sinon/util/core.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/core'>; } declare module 'sinon/lib/sinon/util/event.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/event'>; } declare module 'sinon/lib/sinon/util/fake_server_with_clock.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/fake_server_with_clock'>; } declare module 'sinon/lib/sinon/util/fake_server.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/fake_server'>; } declare module 'sinon/lib/sinon/util/fake_timers.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/fake_timers'>; } declare module 'sinon/lib/sinon/util/fake_xdomain_request.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/fake_xdomain_request'>; } declare module 'sinon/lib/sinon/util/fake_xml_http_request.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/fake_xml_http_request'>; } declare module 'sinon/lib/sinon/util/timers_ie.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/timers_ie'>; } declare module 'sinon/lib/sinon/util/xdr_ie.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/xdr_ie'>; } declare module 'sinon/lib/sinon/util/xhr_ie.js' { declare module.exports: $Exports<'sinon/lib/sinon/util/xhr_ie'>; } declare module 'sinon/lib/sinon/walk.js' { declare module.exports: $Exports<'sinon/lib/sinon/walk'>; } declare module 'sinon/pkg/sinon-1.17.7.js' { declare module.exports: $Exports<'sinon/pkg/sinon-1.17.7'>; } declare module 'sinon/pkg/sinon-ie-1.17.7.js' { declare module.exports: $Exports<'sinon/pkg/sinon-ie-1.17.7'>; } declare module 'sinon/pkg/sinon-ie.js' { declare module.exports: $Exports<'sinon/pkg/sinon-ie'>; } declare module 'sinon/pkg/sinon-server-1.17.7.js' { declare module.exports: $Exports<'sinon/pkg/sinon-server-1.17.7'>; } declare module 'sinon/pkg/sinon-server.js' { declare module.exports: $Exports<'sinon/pkg/sinon-server'>; } declare module 'sinon/pkg/sinon.js' { declare module.exports: $Exports<'sinon/pkg/sinon'>; }
{'content_hash': '7423c8a15b1640b90995eac9e6d4507a', 'timestamp': '', 'source': 'github', 'line_count': 263, 'max_line_length': 82, 'avg_line_length': 27.5893536121673, 'alnum_prop': 0.7253307607497244, 'repo_name': 'SiDevesh/Bootleg', 'id': '94d355856cefcc11025bc3f8fd65004ff45ed2a3', 'size': '7256', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'flow-typed/npm/sinon_vx.x.x.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '391'}, {'name': 'HTML', 'bytes': '912'}, {'name': 'JavaScript', 'bytes': '505970'}]}
<?php namespace backend\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use backend\models\Publics; /** * PublicsSearch represents the model behind the search form about `backend\models\Publics`. */ class PublicsSearch extends Publics { /** * @inheritdoc */ public function rules() { return [ [['id'], 'integer'], [['public_name'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Publics::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, ]); $query->andFilterWhere(['like', 'public_name', $this->public_name]); return $dataProvider; } }
{'content_hash': 'd54631c5819533e238cdd76cc63a335e', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 106, 'avg_line_length': 21.106060606060606, 'alnum_prop': 0.5455850681981336, 'repo_name': 'foyplvowlp/rm', 'id': '5900827a4d38cf8dabdc9a9d80593b4457412919', 'size': '1393', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'backend/models/PublicsSearch.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '1541'}, {'name': 'CSS', 'bytes': '69096'}, {'name': 'JavaScript', 'bytes': '9591'}, {'name': 'PHP', 'bytes': '2021021'}]}
set (PLIBSYS_THREAD_MODEL posix) set (PLIBSYS_IPC_MODEL posix) set (PLIBSYS_TIME_PROFILER_MODEL posix) set (PLIBSYS_DIR_MODEL posix) set (PLIBSYS_LIBRARYLOADER_MODEL posix) set (PLIBSYS_PLATFORM_LINK_LIBRARIES socket) set (PLIBSYS_PLATFORM_DEFINES -D_REENTRANT -D_POSIX_THREAD_SAFE_FUNCTIONS )
{'content_hash': 'a55c4344d09038da924b905f7bd920a2', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 44, 'avg_line_length': 26.0, 'alnum_prop': 0.75, 'repo_name': 'saprykin/plibsys', 'id': 'de75bc2432abe1ffd8a25cd15aff011b93430138', 'size': '312', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'platforms/qnx-qcc/platform.cmake', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '901693'}, {'name': 'C++', 'bytes': '295379'}, {'name': 'CMake', 'bytes': '106481'}, {'name': 'DIGITAL Command Language', 'bytes': '19549'}, {'name': 'Objective-C', 'bytes': '7886'}, {'name': 'Shell', 'bytes': '2276'}]}
/** @file ColladaParser.cpp * @brief Implementation of the Collada parser helper */ #ifndef ASSIMP_BUILD_NO_COLLADA_IMPORTER #include <sstream> #include <stdarg.h> #include "ColladaParser.h" #include "fast_atof.h" #include "ParsingUtils.h" #include <boost/scoped_ptr.hpp> #include <boost/foreach.hpp> #include "../include/assimp/DefaultLogger.hpp" #include "../include/assimp/IOSystem.hpp" #include "../include/assimp/light.h" using namespace Assimp; using namespace Assimp::Collada; // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer ColladaParser::ColladaParser( IOSystem* pIOHandler, const std::string& pFile) : mFileName( pFile) { mRootNode = NULL; mUnitSize = 1.0f; mUpDirection = UP_Y; // We assume the newest file format by default mFormat = FV_1_5_n; // open the file boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile)); if( file.get() == NULL) throw DeadlyImportError( "Failed to open file " + pFile + "."); // generate a XML reader for it boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper( new CIrrXML_IOStreamReader( file.get())); mReader = irr::io::createIrrXMLReader( mIOWrapper.get()); if( !mReader) ThrowException( "Collada: Unable to open file."); // start reading ReadContents(); } // ------------------------------------------------------------------------------------------------ // Destructor, private as well ColladaParser::~ColladaParser() { delete mReader; for( NodeLibrary::iterator it = mNodeLibrary.begin(); it != mNodeLibrary.end(); ++it) delete it->second; for( MeshLibrary::iterator it = mMeshLibrary.begin(); it != mMeshLibrary.end(); ++it) delete it->second; } // ------------------------------------------------------------------------------------------------ // Read bool from text contents of current element bool ColladaParser::ReadBoolFromTextContent() { const char* cur = GetTextContent(); return (!ASSIMP_strincmp(cur,"true",4) || '0' != *cur); } // ------------------------------------------------------------------------------------------------ // Read float from text contents of current element float ColladaParser::ReadFloatFromTextContent() { const char* cur = GetTextContent(); return fast_atof(cur); } // ------------------------------------------------------------------------------------------------ // Reads the contents of the file void ColladaParser::ReadContents() { while( mReader->read()) { // handle the root element "COLLADA" if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "COLLADA")) { // check for 'version' attribute const int attrib = TestAttribute("version"); if (attrib != -1) { const char* version = mReader->getAttributeValue(attrib); if (!::strncmp(version,"1.5",3)) { mFormat = FV_1_5_n; DefaultLogger::get()->debug("Collada schema version is 1.5.n"); } else if (!::strncmp(version,"1.4",3)) { mFormat = FV_1_4_n; DefaultLogger::get()->debug("Collada schema version is 1.4.n"); } else if (!::strncmp(version,"1.3",3)) { mFormat = FV_1_3_n; DefaultLogger::get()->debug("Collada schema version is 1.3.n"); } } ReadStructure(); } else { DefaultLogger::get()->debug( boost::str( boost::format( "Ignoring global element <%s>.") % mReader->getNodeName())); SkipElement(); } } else { // skip everything else silently } } } // ------------------------------------------------------------------------------------------------ // Reads the structure of the file void ColladaParser::ReadStructure() { while( mReader->read()) { // beginning of elements if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "asset")) ReadAssetInfo(); else if( IsElement( "library_animations")) ReadAnimationLibrary(); else if( IsElement( "library_controllers")) ReadControllerLibrary(); else if( IsElement( "library_images")) ReadImageLibrary(); else if( IsElement( "library_materials")) ReadMaterialLibrary(); else if( IsElement( "library_effects")) ReadEffectLibrary(); else if( IsElement( "library_geometries")) ReadGeometryLibrary(); else if( IsElement( "library_visual_scenes")) ReadSceneLibrary(); else if( IsElement( "library_lights")) ReadLightLibrary(); else if( IsElement( "library_cameras")) ReadCameraLibrary(); else if( IsElement( "library_nodes")) ReadSceneNode(NULL); /* some hacking to reuse this piece of code */ else if( IsElement( "scene")) ReadScene(); else SkipElement(); } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { break; } } } // ------------------------------------------------------------------------------------------------ // Reads asset informations such as coordinate system informations and legal blah void ColladaParser::ReadAssetInfo() { if( mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "unit")) { // read unit data from the element's attributes const int attrIndex = TestAttribute( "meter"); if (attrIndex == -1) { mUnitSize = 1.f; } else { mUnitSize = mReader->getAttributeValueAsFloat( attrIndex); } // consume the trailing stuff if( !mReader->isEmptyElement()) SkipElement(); } else if( IsElement( "up_axis")) { // read content, strip whitespace, compare const char* content = GetTextContent(); if( strncmp( content, "X_UP", 4) == 0) mUpDirection = UP_X; else if( strncmp( content, "Z_UP", 4) == 0) mUpDirection = UP_Z; else mUpDirection = UP_Y; // check element end TestClosing( "up_axis"); } else { SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "asset") != 0) ThrowException( "Expected end of <asset> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads the animation library void ColladaParser::ReadAnimationLibrary() { if (mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "animation")) { // delegate the reading. Depending on the inner elements it will be a container or a anim channel ReadAnimation( &mAnims); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "library_animations") != 0) ThrowException( "Expected end of <library_animations> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads an animation into the given parent structure void ColladaParser::ReadAnimation( Collada::Animation* pParent) { if( mReader->isEmptyElement()) return; // an <animation> element may be a container for grouping sub-elements or an animation channel // this is the channel collection by ID, in case it has channels typedef std::map<std::string, AnimationChannel> ChannelMap; ChannelMap channels; // this is the anim container in case we're a container Animation* anim = NULL; // optional name given as an attribute std::string animName; int indexName = TestAttribute( "name"); int indexID = TestAttribute( "id"); if( indexName >= 0) animName = mReader->getAttributeValue( indexName); else if( indexID >= 0) animName = mReader->getAttributeValue( indexID); else animName = "animation"; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { // we have subanimations if( IsElement( "animation")) { // create container from our element if( !anim) { anim = new Animation; anim->mName = animName; pParent->mSubAnims.push_back( anim); } // recurse into the subelement ReadAnimation( anim); } else if( IsElement( "source")) { // possible animation data - we'll never know. Better store it ReadSource(); } else if( IsElement( "sampler")) { // read the ID to assign the corresponding collada channel afterwards. int indexID = GetAttribute( "id"); std::string id = mReader->getAttributeValue( indexID); ChannelMap::iterator newChannel = channels.insert( std::make_pair( id, AnimationChannel())).first; // have it read into a channel ReadAnimationSampler( newChannel->second); } else if( IsElement( "channel")) { // the binding element whose whole purpose is to provide the target to animate // Thanks, Collada! A directly posted information would have been too simple, I guess. // Better add another indirection to that! Can't have enough of those. int indexTarget = GetAttribute( "target"); int indexSource = GetAttribute( "source"); const char* sourceId = mReader->getAttributeValue( indexSource); if( sourceId[0] == '#') sourceId++; ChannelMap::iterator cit = channels.find( sourceId); if( cit != channels.end()) cit->second.mTarget = mReader->getAttributeValue( indexTarget); if( !mReader->isEmptyElement()) SkipElement(); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "animation") != 0) ThrowException( "Expected end of <animation> element."); break; } } // it turned out to have channels - add them if( !channels.empty()) { // special filtering for stupid exporters packing each channel into a separate animation if( channels.size() == 1) { pParent->mChannels.push_back( channels.begin()->second); } else { // else create the animation, if not done yet, and store the channels if( !anim) { anim = new Animation; anim->mName = animName; pParent->mSubAnims.push_back( anim); } for( ChannelMap::const_iterator it = channels.begin(); it != channels.end(); ++it) anim->mChannels.push_back( it->second); } } } // ------------------------------------------------------------------------------------------------ // Reads an animation sampler into the given anim channel void ColladaParser::ReadAnimationSampler( Collada::AnimationChannel& pChannel) { while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "input")) { int indexSemantic = GetAttribute( "semantic"); const char* semantic = mReader->getAttributeValue( indexSemantic); int indexSource = GetAttribute( "source"); const char* source = mReader->getAttributeValue( indexSource); if( source[0] != '#') ThrowException( "Unsupported URL format"); source++; if( strcmp( semantic, "INPUT") == 0) pChannel.mSourceTimes = source; else if( strcmp( semantic, "OUTPUT") == 0) pChannel.mSourceValues = source; if( !mReader->isEmptyElement()) SkipElement(); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "sampler") != 0) ThrowException( "Expected end of <sampler> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads the skeleton controller library void ColladaParser::ReadControllerLibrary() { if (mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "controller")) { // read ID. Ask the spec if it's neccessary or optional... you might be surprised. int attrID = GetAttribute( "id"); std::string id = mReader->getAttributeValue( attrID); // create an entry and store it in the library under its ID mControllerLibrary[id] = Controller(); // read on from there ReadController( mControllerLibrary[id]); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "library_controllers") != 0) ThrowException( "Expected end of <library_controllers> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads a controller into the given mesh structure void ColladaParser::ReadController( Collada::Controller& pController) { while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { // two types of controllers: "skin" and "morph". Only the first one is relevant, we skip the other if( IsElement( "morph")) { // should skip everything inside, so there's no danger of catching elements inbetween SkipElement(); } else if( IsElement( "skin")) { // read the mesh it refers to. According to the spec this could also be another // controller, but I refuse to implement every single idea they've come up with int sourceIndex = GetAttribute( "source"); pController.mMeshId = mReader->getAttributeValue( sourceIndex) + 1; } else if( IsElement( "bind_shape_matrix")) { // content is 16 floats to define a matrix... it seems to be important for some models const char* content = GetTextContent(); // read the 16 floats for( unsigned int a = 0; a < 16; a++) { // read a number content = fast_atoreal_move<float>( content, pController.mBindShapeMatrix[a]); // skip whitespace after it SkipSpacesAndLineEnd( &content); } TestClosing( "bind_shape_matrix"); } else if( IsElement( "source")) { // data array - we have specialists to handle this ReadSource(); } else if( IsElement( "joints")) { ReadControllerJoints( pController); } else if( IsElement( "vertex_weights")) { ReadControllerWeights( pController); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "controller") == 0) break; else if( strcmp( mReader->getNodeName(), "skin") != 0) ThrowException( "Expected end of <controller> element."); } } } // ------------------------------------------------------------------------------------------------ // Reads the joint definitions for the given controller void ColladaParser::ReadControllerJoints( Collada::Controller& pController) { while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { // Input channels for joint data. Two possible semantics: "JOINT" and "INV_BIND_MATRIX" if( IsElement( "input")) { int indexSemantic = GetAttribute( "semantic"); const char* attrSemantic = mReader->getAttributeValue( indexSemantic); int indexSource = GetAttribute( "source"); const char* attrSource = mReader->getAttributeValue( indexSource); // local URLS always start with a '#'. We don't support global URLs if( attrSource[0] != '#') ThrowException( boost::str( boost::format( "Unsupported URL format in \"%s\" in source attribute of <joints> data <input> element") % attrSource)); attrSource++; // parse source URL to corresponding source if( strcmp( attrSemantic, "JOINT") == 0) pController.mJointNameSource = attrSource; else if( strcmp( attrSemantic, "INV_BIND_MATRIX") == 0) pController.mJointOffsetMatrixSource = attrSource; else ThrowException( boost::str( boost::format( "Unknown semantic \"%s\" in <joints> data <input> element") % attrSemantic)); // skip inner data, if present if( !mReader->isEmptyElement()) SkipElement(); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "joints") != 0) ThrowException( "Expected end of <joints> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads the joint weights for the given controller void ColladaParser::ReadControllerWeights( Collada::Controller& pController) { // read vertex count from attributes and resize the array accordingly int indexCount = GetAttribute( "count"); size_t vertexCount = (size_t) mReader->getAttributeValueAsInt( indexCount); pController.mWeightCounts.resize( vertexCount); while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { // Input channels for weight data. Two possible semantics: "JOINT" and "WEIGHT" if( IsElement( "input") && vertexCount > 0 ) { InputChannel channel; int indexSemantic = GetAttribute( "semantic"); const char* attrSemantic = mReader->getAttributeValue( indexSemantic); int indexSource = GetAttribute( "source"); const char* attrSource = mReader->getAttributeValue( indexSource); int indexOffset = TestAttribute( "offset"); if( indexOffset >= 0) channel.mOffset = mReader->getAttributeValueAsInt( indexOffset); // local URLS always start with a '#'. We don't support global URLs if( attrSource[0] != '#') ThrowException( boost::str( boost::format( "Unsupported URL format in \"%s\" in source attribute of <vertex_weights> data <input> element") % attrSource)); channel.mAccessor = attrSource + 1; // parse source URL to corresponding source if( strcmp( attrSemantic, "JOINT") == 0) pController.mWeightInputJoints = channel; else if( strcmp( attrSemantic, "WEIGHT") == 0) pController.mWeightInputWeights = channel; else ThrowException( boost::str( boost::format( "Unknown semantic \"%s\" in <vertex_weights> data <input> element") % attrSemantic)); // skip inner data, if present if( !mReader->isEmptyElement()) SkipElement(); } else if( IsElement( "vcount") && vertexCount > 0 ) { // read weight count per vertex const char* text = GetTextContent(); size_t numWeights = 0; for( std::vector<size_t>::iterator it = pController.mWeightCounts.begin(); it != pController.mWeightCounts.end(); ++it) { if( *text == 0) ThrowException( "Out of data while reading <vcount>"); *it = strtoul10( text, &text); numWeights += *it; SkipSpacesAndLineEnd( &text); } TestClosing( "vcount"); // reserve weight count pController.mWeights.resize( numWeights); } else if( IsElement( "v") && vertexCount > 0 ) { // read JointIndex - WeightIndex pairs const char* text = GetTextContent(); for( std::vector< std::pair<size_t, size_t> >::iterator it = pController.mWeights.begin(); it != pController.mWeights.end(); ++it) { if( *text == 0) ThrowException( "Out of data while reading <vertex_weights>"); it->first = strtoul10( text, &text); SkipSpacesAndLineEnd( &text); if( *text == 0) ThrowException( "Out of data while reading <vertex_weights>"); it->second = strtoul10( text, &text); SkipSpacesAndLineEnd( &text); } TestClosing( "v"); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "vertex_weights") != 0) ThrowException( "Expected end of <vertex_weights> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads the image library contents void ColladaParser::ReadImageLibrary() { if( mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "image")) { // read ID. Another entry which is "optional" by design but obligatory in reality int attrID = GetAttribute( "id"); std::string id = mReader->getAttributeValue( attrID); // create an entry and store it in the library under its ID mImageLibrary[id] = Image(); // read on from there ReadImage( mImageLibrary[id]); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "library_images") != 0) ThrowException( "Expected end of <library_images> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads an image entry into the given image void ColladaParser::ReadImage( Collada::Image& pImage) { while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT){ // Need to run different code paths here, depending on the Collada XSD version if (IsElement("image")) { SkipElement(); } else if( IsElement( "init_from")) { if (mFormat == FV_1_4_n) { // FIX: C4D exporter writes empty <init_from/> tags if (!mReader->isEmptyElement()) { // element content is filename - hopefully const char* sz = TestTextContent(); if (sz)pImage.mFileName = sz; TestClosing( "init_from"); } if (!pImage.mFileName.length()) { pImage.mFileName = "unknown_texture"; } } else if (mFormat == FV_1_5_n) { // make sure we skip over mip and array initializations, which // we don't support, but which could confuse the loader if // they're not skipped. int attrib = TestAttribute("array_index"); if (attrib != -1 && mReader->getAttributeValueAsInt(attrib) > 0) { DefaultLogger::get()->warn("Collada: Ignoring texture array index"); continue; } attrib = TestAttribute("mip_index"); if (attrib != -1 && mReader->getAttributeValueAsInt(attrib) > 0) { DefaultLogger::get()->warn("Collada: Ignoring MIP map layer"); continue; } // TODO: correctly jump over cube and volume maps? } } else if (mFormat == FV_1_5_n) { if( IsElement( "ref")) { // element content is filename - hopefully const char* sz = TestTextContent(); if (sz)pImage.mFileName = sz; TestClosing( "ref"); } else if( IsElement( "hex") && !pImage.mFileName.length()) { // embedded image. get format const int attrib = TestAttribute("format"); if (-1 == attrib) DefaultLogger::get()->warn("Collada: Unknown image file format"); else pImage.mEmbeddedFormat = mReader->getAttributeValue(attrib); const char* data = GetTextContent(); // hexadecimal-encoded binary octets. First of all, find the // required buffer size to reserve enough storage. const char* cur = data; while (!IsSpaceOrNewLine(*cur)) cur++; const unsigned int size = (unsigned int)(cur-data) * 2; pImage.mImageData.resize(size); for (unsigned int i = 0; i < size;++i) pImage.mImageData[i] = HexOctetToDecimal(data+(i<<1)); TestClosing( "hex"); } } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "image") == 0) break; } } } // ------------------------------------------------------------------------------------------------ // Reads the material library void ColladaParser::ReadMaterialLibrary() { if( mReader->isEmptyElement()) return; std::map<std::string, int> names; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "material")) { // read ID. By now you propably know my opinion about this "specification" int attrID = GetAttribute( "id"); std::string id = mReader->getAttributeValue( attrID); std::string name; int attrName = TestAttribute("name"); if (attrName >= 0) name = mReader->getAttributeValue( attrName); // create an entry and store it in the library under its ID mMaterialLibrary[id] = Material(); if( !name.empty()) { std::map<std::string, int>::iterator it = names.find( name); if( it != names.end()) { std::ostringstream strStream; strStream << ++it->second; name.append( " " + strStream.str()); } else { names[name] = 0; } mMaterialLibrary[id].mName = name; } ReadMaterial( mMaterialLibrary[id]); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "library_materials") != 0) ThrowException( "Expected end of <library_materials> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads the light library void ColladaParser::ReadLightLibrary() { if( mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "light")) { // read ID. By now you propably know my opinion about this "specification" int attrID = GetAttribute( "id"); std::string id = mReader->getAttributeValue( attrID); // create an entry and store it in the library under its ID ReadLight(mLightLibrary[id] = Light()); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "library_lights") != 0) ThrowException( "Expected end of <library_lights> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads the camera library void ColladaParser::ReadCameraLibrary() { if( mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "camera")) { // read ID. By now you propably know my opinion about this "specification" int attrID = GetAttribute( "id"); std::string id = mReader->getAttributeValue( attrID); // create an entry and store it in the library under its ID Camera& cam = mCameraLibrary[id]; attrID = TestAttribute( "name"); if (attrID != -1) cam.mName = mReader->getAttributeValue( attrID); ReadCamera(cam); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "library_cameras") != 0) ThrowException( "Expected end of <library_cameras> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads a material entry into the given material void ColladaParser::ReadMaterial( Collada::Material& pMaterial) { while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if (IsElement("material")) { SkipElement(); } else if( IsElement( "instance_effect")) { // referred effect by URL int attrUrl = GetAttribute( "url"); const char* url = mReader->getAttributeValue( attrUrl); if( url[0] != '#') ThrowException( "Unknown reference format"); pMaterial.mEffect = url+1; SkipElement(); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "material") != 0) ThrowException( "Expected end of <material> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads a light entry into the given light void ColladaParser::ReadLight( Collada::Light& pLight) { while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if (IsElement("light")) { SkipElement(); } else if (IsElement("spot")) { pLight.mType = aiLightSource_SPOT; } else if (IsElement("ambient")) { pLight.mType = aiLightSource_AMBIENT; } else if (IsElement("directional")) { pLight.mType = aiLightSource_DIRECTIONAL; } else if (IsElement("point")) { pLight.mType = aiLightSource_POINT; } else if (IsElement("color")) { // text content contains 3 floats const char* content = GetTextContent(); content = fast_atoreal_move<float>( content, (float&)pLight.mColor.r); SkipSpacesAndLineEnd( &content); content = fast_atoreal_move<float>( content, (float&)pLight.mColor.g); SkipSpacesAndLineEnd( &content); content = fast_atoreal_move<float>( content, (float&)pLight.mColor.b); SkipSpacesAndLineEnd( &content); TestClosing( "color"); } else if (IsElement("constant_attenuation")) { pLight.mAttConstant = ReadFloatFromTextContent(); TestClosing("constant_attenuation"); } else if (IsElement("linear_attenuation")) { pLight.mAttLinear = ReadFloatFromTextContent(); TestClosing("linear_attenuation"); } else if (IsElement("quadratic_attenuation")) { pLight.mAttQuadratic = ReadFloatFromTextContent(); TestClosing("quadratic_attenuation"); } else if (IsElement("falloff_angle")) { pLight.mFalloffAngle = ReadFloatFromTextContent(); TestClosing("falloff_angle"); } else if (IsElement("falloff_exponent")) { pLight.mFalloffExponent = ReadFloatFromTextContent(); TestClosing("falloff_exponent"); } // FCOLLADA extensions // ------------------------------------------------------- else if (IsElement("outer_cone")) { pLight.mOuterAngle = ReadFloatFromTextContent(); TestClosing("outer_cone"); } // ... and this one is even deprecated else if (IsElement("penumbra_angle")) { pLight.mPenumbraAngle = ReadFloatFromTextContent(); TestClosing("penumbra_angle"); } else if (IsElement("intensity")) { pLight.mIntensity = ReadFloatFromTextContent(); TestClosing("intensity"); } else if (IsElement("falloff")) { pLight.mOuterAngle = ReadFloatFromTextContent(); TestClosing("falloff"); } else if (IsElement("hotspot_beam")) { pLight.mFalloffAngle = ReadFloatFromTextContent(); TestClosing("hotspot_beam"); } // OpenCOLLADA extensions // ------------------------------------------------------- else if (IsElement("decay_falloff")) { pLight.mOuterAngle = ReadFloatFromTextContent(); TestClosing("decay_falloff"); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "light") == 0) break; } } } // ------------------------------------------------------------------------------------------------ // Reads a camera entry into the given light void ColladaParser::ReadCamera( Collada::Camera& pCamera) { while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if (IsElement("camera")) { SkipElement(); } else if (IsElement("orthographic")) { pCamera.mOrtho = true; } else if (IsElement("xfov") || IsElement("xmag")) { pCamera.mHorFov = ReadFloatFromTextContent(); TestClosing((pCamera.mOrtho ? "xmag" : "xfov")); } else if (IsElement("yfov") || IsElement("ymag")) { pCamera.mVerFov = ReadFloatFromTextContent(); TestClosing((pCamera.mOrtho ? "ymag" : "yfov")); } else if (IsElement("aspect_ratio")) { pCamera.mAspect = ReadFloatFromTextContent(); TestClosing("aspect_ratio"); } else if (IsElement("znear")) { pCamera.mZNear = ReadFloatFromTextContent(); TestClosing("znear"); } else if (IsElement("zfar")) { pCamera.mZFar = ReadFloatFromTextContent(); TestClosing("zfar"); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "camera") == 0) break; } } } // ------------------------------------------------------------------------------------------------ // Reads the effect library void ColladaParser::ReadEffectLibrary() { if (mReader->isEmptyElement()) { return; } while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "effect")) { // read ID. Do I have to repeat my ranting about "optional" attributes? int attrID = GetAttribute( "id"); std::string id = mReader->getAttributeValue( attrID); // create an entry and store it in the library under its ID mEffectLibrary[id] = Effect(); // read on from there ReadEffect( mEffectLibrary[id]); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "library_effects") != 0) ThrowException( "Expected end of <library_effects> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads an effect entry into the given effect void ColladaParser::ReadEffect( Collada::Effect& pEffect) { // for the moment we don't support any other type of effect. while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "profile_COMMON")) ReadEffectProfileCommon( pEffect); else SkipElement(); } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "effect") != 0) ThrowException( "Expected end of <effect> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads an COMMON effect profile void ColladaParser::ReadEffectProfileCommon( Collada::Effect& pEffect) { while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "newparam")) { // save ID int attrSID = GetAttribute( "sid"); std::string sid = mReader->getAttributeValue( attrSID); pEffect.mParams[sid] = EffectParam(); ReadEffectParam( pEffect.mParams[sid]); } else if( IsElement( "technique") || IsElement( "extra")) { // just syntactic sugar } else if( mFormat == FV_1_4_n && IsElement( "image")) { // read ID. Another entry which is "optional" by design but obligatory in reality int attrID = GetAttribute( "id"); std::string id = mReader->getAttributeValue( attrID); // create an entry and store it in the library under its ID mImageLibrary[id] = Image(); // read on from there ReadImage( mImageLibrary[id]); } /* Shading modes */ else if( IsElement( "phong")) pEffect.mShadeType = Shade_Phong; else if( IsElement( "constant")) pEffect.mShadeType = Shade_Constant; else if( IsElement( "lambert")) pEffect.mShadeType = Shade_Lambert; else if( IsElement( "blinn")) pEffect.mShadeType = Shade_Blinn; /* Color + texture properties */ else if( IsElement( "emission")) ReadEffectColor( pEffect.mEmissive, pEffect.mTexEmissive); else if( IsElement( "ambient")) ReadEffectColor( pEffect.mAmbient, pEffect.mTexAmbient); else if( IsElement( "diffuse")) ReadEffectColor( pEffect.mDiffuse, pEffect.mTexDiffuse); else if( IsElement( "specular")) ReadEffectColor( pEffect.mSpecular, pEffect.mTexSpecular); else if( IsElement( "reflective")) { ReadEffectColor( pEffect.mReflective, pEffect.mTexReflective); } else if( IsElement( "transparent")) { pEffect.mHasTransparency = true; // In RGB_ZERO mode, the transparency is interpreted in reverse, go figure... if(::strcmp(mReader->getAttributeValueSafe("opaque"), "RGB_ZERO") == 0) { // TODO: handle RGB_ZERO mode completely pEffect.mRGBTransparency = true; } ReadEffectColor( pEffect.mTransparent,pEffect.mTexTransparent); } else if( IsElement( "shininess")) ReadEffectFloat( pEffect.mShininess); else if( IsElement( "reflectivity")) ReadEffectFloat( pEffect.mReflectivity); /* Single scalar properties */ else if( IsElement( "transparency")) ReadEffectFloat( pEffect.mTransparency); else if( IsElement( "index_of_refraction")) ReadEffectFloat( pEffect.mRefractIndex); // GOOGLEEARTH/OKINO extensions // ------------------------------------------------------- else if( IsElement( "double_sided")) pEffect.mDoubleSided = ReadBoolFromTextContent(); // FCOLLADA extensions // ------------------------------------------------------- else if( IsElement( "bump")) { aiColor4D dummy; ReadEffectColor( dummy,pEffect.mTexBump); } // MAX3D extensions // ------------------------------------------------------- else if( IsElement( "wireframe")) { pEffect.mWireframe = ReadBoolFromTextContent(); TestClosing( "wireframe"); } else if( IsElement( "faceted")) { pEffect.mFaceted = ReadBoolFromTextContent(); TestClosing( "faceted"); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "profile_COMMON") == 0) { break; } } } } // ------------------------------------------------------------------------------------------------ // Read texture wrapping + UV transform settings from a profile==Maya chunk void ColladaParser::ReadSamplerProperties( Sampler& out ) { if (mReader->isEmptyElement()) { return; } while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { // MAYA extensions // ------------------------------------------------------- if( IsElement( "wrapU")) { out.mWrapU = ReadBoolFromTextContent(); TestClosing( "wrapU"); } else if( IsElement( "wrapV")) { out.mWrapV = ReadBoolFromTextContent(); TestClosing( "wrapV"); } else if( IsElement( "mirrorU")) { out.mMirrorU = ReadBoolFromTextContent(); TestClosing( "mirrorU"); } else if( IsElement( "mirrorV")) { out.mMirrorV = ReadBoolFromTextContent(); TestClosing( "mirrorV"); } else if( IsElement( "repeatU")) { out.mTransform.mScaling.x = ReadFloatFromTextContent(); TestClosing( "repeatU"); } else if( IsElement( "repeatV")) { out.mTransform.mScaling.y = ReadFloatFromTextContent(); TestClosing( "repeatV"); } else if( IsElement( "offsetU")) { out.mTransform.mTranslation.x = ReadFloatFromTextContent(); TestClosing( "offsetU"); } else if( IsElement( "offsetV")) { out.mTransform.mTranslation.y = ReadFloatFromTextContent(); TestClosing( "offsetV"); } else if( IsElement( "rotateUV")) { out.mTransform.mRotation = ReadFloatFromTextContent(); TestClosing( "rotateUV"); } else if( IsElement( "blend_mode")) { const char* sz = GetTextContent(); // http://www.feelingsoftware.com/content/view/55/72/lang,en/ // NONE, OVER, IN, OUT, ADD, SUBTRACT, MULTIPLY, DIFFERENCE, LIGHTEN, DARKEN, SATURATE, DESATURATE and ILLUMINATE if (0 == ASSIMP_strincmp(sz,"ADD",3)) out.mOp = aiTextureOp_Add; else if (0 == ASSIMP_strincmp(sz,"SUBTRACT",8)) out.mOp = aiTextureOp_Subtract; else if (0 == ASSIMP_strincmp(sz,"MULTIPLY",8)) out.mOp = aiTextureOp_Multiply; else { DefaultLogger::get()->warn("Collada: Unsupported MAYA texture blend mode"); } TestClosing( "blend_mode"); } // OKINO extensions // ------------------------------------------------------- else if( IsElement( "weighting")) { out.mWeighting = ReadFloatFromTextContent(); TestClosing( "weighting"); } else if( IsElement( "mix_with_previous_layer")) { out.mMixWithPrevious = ReadFloatFromTextContent(); TestClosing( "mix_with_previous_layer"); } // MAX3D extensions // ------------------------------------------------------- else if( IsElement( "amount")) { out.mWeighting = ReadFloatFromTextContent(); TestClosing( "amount"); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "technique") == 0) break; } } } // ------------------------------------------------------------------------------------------------ // Reads an effect entry containing a color or a texture defining that color void ColladaParser::ReadEffectColor( aiColor4D& pColor, Sampler& pSampler) { if (mReader->isEmptyElement()) return; // Save current element name const std::string curElem = mReader->getNodeName(); while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "color")) { // text content contains 4 floats const char* content = GetTextContent(); content = fast_atoreal_move<float>( content, (float&)pColor.r); SkipSpacesAndLineEnd( &content); content = fast_atoreal_move<float>( content, (float&)pColor.g); SkipSpacesAndLineEnd( &content); content = fast_atoreal_move<float>( content, (float&)pColor.b); SkipSpacesAndLineEnd( &content); content = fast_atoreal_move<float>( content, (float&)pColor.a); SkipSpacesAndLineEnd( &content); TestClosing( "color"); } else if( IsElement( "texture")) { // get name of source textur/sampler int attrTex = GetAttribute( "texture"); pSampler.mName = mReader->getAttributeValue( attrTex); // get name of UV source channel. Specification demands it to be there, but some exporters // don't write it. It will be the default UV channel in case it's missing. attrTex = TestAttribute( "texcoord"); if( attrTex >= 0 ) pSampler.mUVChannel = mReader->getAttributeValue( attrTex); //SkipElement(); // as we've read texture, the color needs to be 1,1,1,1 pColor = aiColor4D(1.f, 1.f, 1.f, 1.f); } else if( IsElement( "technique")) { const int _profile = GetAttribute( "profile"); const char* profile = mReader->getAttributeValue( _profile ); // Some extensions are quite useful ... ReadSamplerProperties processes // several extensions in MAYA, OKINO and MAX3D profiles. if (!::strcmp(profile,"MAYA") || !::strcmp(profile,"MAX3D") || !::strcmp(profile,"OKINO")) { // get more information on this sampler ReadSamplerProperties(pSampler); } else SkipElement(); } else if( !IsElement( "extra")) { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){ if (mReader->getNodeName() == curElem) break; } } } // ------------------------------------------------------------------------------------------------ // Reads an effect entry containing a float void ColladaParser::ReadEffectFloat( float& pFloat) { while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT){ if( IsElement( "float")) { // text content contains a single floats const char* content = GetTextContent(); content = fast_atoreal_move<float>( content, pFloat); SkipSpacesAndLineEnd( &content); TestClosing( "float"); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){ break; } } } // ------------------------------------------------------------------------------------------------ // Reads an effect parameter specification of any kind void ColladaParser::ReadEffectParam( Collada::EffectParam& pParam) { while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "surface")) { // image ID given inside <init_from> tags TestOpening( "init_from"); const char* content = GetTextContent(); pParam.mType = Param_Surface; pParam.mReference = content; TestClosing( "init_from"); // don't care for remaining stuff SkipElement( "surface"); } else if( IsElement( "sampler2D")) { // surface ID is given inside <source> tags TestOpening( "source"); const char* content = GetTextContent(); pParam.mType = Param_Sampler; pParam.mReference = content; TestClosing( "source"); // don't care for remaining stuff SkipElement( "sampler2D"); } else { // ignore unknown element SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { break; } } } // ------------------------------------------------------------------------------------------------ // Reads the geometry library contents void ColladaParser::ReadGeometryLibrary() { if( mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "geometry")) { // read ID. Another entry which is "optional" by design but obligatory in reality int indexID = GetAttribute( "id"); std::string id = mReader->getAttributeValue( indexID); // TODO: (thom) support SIDs // ai_assert( TestAttribute( "sid") == -1); // create a mesh and store it in the library under its ID Mesh* mesh = new Mesh; mMeshLibrary[id] = mesh; // read the mesh name if it exists const int nameIndex = TestAttribute("name"); if(nameIndex != -1) { mesh->mName = mReader->getAttributeValue(nameIndex); } // read on from there ReadGeometry( mesh); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "library_geometries") != 0) ThrowException( "Expected end of <library_geometries> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads a geometry from the geometry library. void ColladaParser::ReadGeometry( Collada::Mesh* pMesh) { if( mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "mesh")) { // read on from there ReadMesh( pMesh); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "geometry") != 0) ThrowException( "Expected end of <geometry> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads a mesh from the geometry library void ColladaParser::ReadMesh( Mesh* pMesh) { if( mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "source")) { // we have professionals dealing with this ReadSource(); } else if( IsElement( "vertices")) { // read per-vertex mesh data ReadVertexData( pMesh); } else if( IsElement( "triangles") || IsElement( "lines") || IsElement( "linestrips") || IsElement( "polygons") || IsElement( "polylist") || IsElement( "trifans") || IsElement( "tristrips")) { // read per-index mesh data and faces setup ReadIndexData( pMesh); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "technique_common") == 0) { // end of another meaningless element - read over it } else if( strcmp( mReader->getNodeName(), "mesh") == 0) { // end of <mesh> element - we're done here break; } else { // everything else should be punished ThrowException( "Expected end of <mesh> element."); } } } } // ------------------------------------------------------------------------------------------------ // Reads a source element void ColladaParser::ReadSource() { int indexID = GetAttribute( "id"); std::string sourceID = mReader->getAttributeValue( indexID); while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "float_array") || IsElement( "IDREF_array") || IsElement( "Name_array")) { ReadDataArray(); } else if( IsElement( "technique_common")) { // I don't care for your profiles } else if( IsElement( "accessor")) { ReadAccessor( sourceID); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "source") == 0) { // end of <source> - we're done break; } else if( strcmp( mReader->getNodeName(), "technique_common") == 0) { // end of another meaningless element - read over it } else { // everything else should be punished ThrowException( "Expected end of <source> element."); } } } } // ------------------------------------------------------------------------------------------------ // Reads a data array holding a number of floats, and stores it in the global library void ColladaParser::ReadDataArray() { std::string elmName = mReader->getNodeName(); bool isStringArray = (elmName == "IDREF_array" || elmName == "Name_array"); bool isEmptyElement = mReader->isEmptyElement(); // read attributes int indexID = GetAttribute( "id"); std::string id = mReader->getAttributeValue( indexID); int indexCount = GetAttribute( "count"); unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( indexCount); const char* content = TestTextContent(); // read values and store inside an array in the data library mDataLibrary[id] = Data(); Data& data = mDataLibrary[id]; data.mIsStringArray = isStringArray; // some exporters write empty data arrays, but we need to conserve them anyways because others might reference them if (content) { if( isStringArray) { data.mStrings.reserve( count); std::string s; for( unsigned int a = 0; a < count; a++) { if( *content == 0) ThrowException( "Expected more values while reading IDREF_array contents."); s.clear(); while( !IsSpaceOrNewLine( *content)) s += *content++; data.mStrings.push_back( s); SkipSpacesAndLineEnd( &content); } } else { data.mValues.reserve( count); for( unsigned int a = 0; a < count; a++) { if( *content == 0) ThrowException( "Expected more values while reading float_array contents."); float value; // read a number content = fast_atoreal_move<float>( content, value); data.mValues.push_back( value); // skip whitespace after it SkipSpacesAndLineEnd( &content); } } } // test for closing tag if( !isEmptyElement ) TestClosing( elmName.c_str()); } // ------------------------------------------------------------------------------------------------ // Reads an accessor and stores it in the global library void ColladaParser::ReadAccessor( const std::string& pID) { // read accessor attributes int attrSource = GetAttribute( "source"); const char* source = mReader->getAttributeValue( attrSource); if( source[0] != '#') ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\" in source attribute of <accessor> element.") % source)); int attrCount = GetAttribute( "count"); unsigned int count = (unsigned int) mReader->getAttributeValueAsInt( attrCount); int attrOffset = TestAttribute( "offset"); unsigned int offset = 0; if( attrOffset > -1) offset = (unsigned int) mReader->getAttributeValueAsInt( attrOffset); int attrStride = TestAttribute( "stride"); unsigned int stride = 1; if( attrStride > -1) stride = (unsigned int) mReader->getAttributeValueAsInt( attrStride); // store in the library under the given ID mAccessorLibrary[pID] = Accessor(); Accessor& acc = mAccessorLibrary[pID]; acc.mCount = count; acc.mOffset = offset; acc.mStride = stride; acc.mSource = source+1; // ignore the leading '#' acc.mSize = 0; // gets incremented with every param // and read the components while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "param")) { // read data param int attrName = TestAttribute( "name"); std::string name; if( attrName > -1) { name = mReader->getAttributeValue( attrName); // analyse for common type components and store it's sub-offset in the corresponding field /* Cartesian coordinates */ if( name == "X") acc.mSubOffset[0] = acc.mParams.size(); else if( name == "Y") acc.mSubOffset[1] = acc.mParams.size(); else if( name == "Z") acc.mSubOffset[2] = acc.mParams.size(); /* RGBA colors */ else if( name == "R") acc.mSubOffset[0] = acc.mParams.size(); else if( name == "G") acc.mSubOffset[1] = acc.mParams.size(); else if( name == "B") acc.mSubOffset[2] = acc.mParams.size(); else if( name == "A") acc.mSubOffset[3] = acc.mParams.size(); /* UVWQ (STPQ) texture coordinates */ else if( name == "S") acc.mSubOffset[0] = acc.mParams.size(); else if( name == "T") acc.mSubOffset[1] = acc.mParams.size(); else if( name == "P") acc.mSubOffset[2] = acc.mParams.size(); // else if( name == "Q") acc.mSubOffset[3] = acc.mParams.size(); /* 4D uv coordinates are not supported in Assimp */ /* Generic extra data, interpreted as UV data, too*/ else if( name == "U") acc.mSubOffset[0] = acc.mParams.size(); else if( name == "V") acc.mSubOffset[1] = acc.mParams.size(); //else // DefaultLogger::get()->warn( boost::str( boost::format( "Unknown accessor parameter \"%s\". Ignoring data channel.") % name)); } // read data type int attrType = TestAttribute( "type"); if( attrType > -1) { // for the moment we only distinguish between a 4x4 matrix and anything else. // TODO: (thom) I don't have a spec here at work. Check if there are other multi-value types // which should be tested for here. std::string type = mReader->getAttributeValue( attrType); if( type == "float4x4") acc.mSize += 16; else acc.mSize += 1; } acc.mParams.push_back( name); // skip remaining stuff of this element, if any SkipElement(); } else { ThrowException( boost::str( boost::format( "Unexpected sub element <%s> in tag <accessor>") % mReader->getNodeName())); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "accessor") != 0) ThrowException( "Expected end of <accessor> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads input declarations of per-vertex mesh data into the given mesh void ColladaParser::ReadVertexData( Mesh* pMesh) { // extract the ID of the <vertices> element. Not that we care, but to catch strange referencing schemes we should warn about int attrID= GetAttribute( "id"); pMesh->mVertexID = mReader->getAttributeValue( attrID); // a number of <input> elements while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "input")) { ReadInputChannel( pMesh->mPerVertexData); } else { ThrowException( boost::str( boost::format( "Unexpected sub element <%s> in tag <vertices>") % mReader->getNodeName())); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "vertices") != 0) ThrowException( "Expected end of <vertices> element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads input declarations of per-index mesh data into the given mesh void ColladaParser::ReadIndexData( Mesh* pMesh) { std::vector<size_t> vcount; std::vector<InputChannel> perIndexData; // read primitive count from the attribute int attrCount = GetAttribute( "count"); size_t numPrimitives = (size_t) mReader->getAttributeValueAsInt( attrCount); // some mesh types (e.g. tristrips) don't specify primitive count upfront, // so we need to sum up the actual number of primitives while we read the <p>-tags size_t actualPrimitives = 0; // material subgroup int attrMaterial = TestAttribute( "material"); SubMesh subgroup; if( attrMaterial > -1) subgroup.mMaterial = mReader->getAttributeValue( attrMaterial); // distinguish between polys and triangles std::string elementName = mReader->getNodeName(); PrimitiveType primType = Prim_Invalid; if( IsElement( "lines")) primType = Prim_Lines; else if( IsElement( "linestrips")) primType = Prim_LineStrip; else if( IsElement( "polygons")) primType = Prim_Polygon; else if( IsElement( "polylist")) primType = Prim_Polylist; else if( IsElement( "triangles")) primType = Prim_Triangles; else if( IsElement( "trifans")) primType = Prim_TriFans; else if( IsElement( "tristrips")) primType = Prim_TriStrips; ai_assert( primType != Prim_Invalid); // also a number of <input> elements, but in addition a <p> primitive collection and propably index counts for all primitives while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "input")) { ReadInputChannel( perIndexData); } else if( IsElement( "vcount")) { if( !mReader->isEmptyElement()) { if (numPrimitives) // It is possible to define a mesh without any primitives { // case <polylist> - specifies the number of indices for each polygon const char* content = GetTextContent(); vcount.reserve( numPrimitives); for( unsigned int a = 0; a < numPrimitives; a++) { if( *content == 0) ThrowException( "Expected more values while reading <vcount> contents."); // read a number vcount.push_back( (size_t) strtoul10( content, &content)); // skip whitespace after it SkipSpacesAndLineEnd( &content); } } TestClosing( "vcount"); } } else if( IsElement( "p")) { if( !mReader->isEmptyElement()) { // now here the actual fun starts - these are the indices to construct the mesh data from actualPrimitives += ReadPrimitives(pMesh, perIndexData, numPrimitives, vcount, primType); } } else if (IsElement("extra")) { SkipElement("extra"); } else { ThrowException( boost::str( boost::format( "Unexpected sub element <%s> in tag <%s>") % mReader->getNodeName() % elementName)); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( mReader->getNodeName() != elementName) ThrowException( boost::str( boost::format( "Expected end of <%s> element.") % elementName)); break; } } #ifdef ASSIMP_BUILD_DEBUG if (primType != Prim_TriFans && primType != Prim_TriStrips && primType != Prim_Lines) { // this is ONLY to workaround a bug in SketchUp 15.3.331 where it writes the wrong 'count' when it writes out the 'lines'. ai_assert(actualPrimitives == numPrimitives); } #endif // only when we're done reading all <p> tags (and thus know the final vertex count) can we commit the submesh subgroup.mNumFaces = actualPrimitives; pMesh->mSubMeshes.push_back(subgroup); } // ------------------------------------------------------------------------------------------------ // Reads a single input channel element and stores it in the given array, if valid void ColladaParser::ReadInputChannel( std::vector<InputChannel>& poChannels) { InputChannel channel; // read semantic int attrSemantic = GetAttribute( "semantic"); std::string semantic = mReader->getAttributeValue( attrSemantic); channel.mType = GetTypeForSemantic( semantic); // read source int attrSource = GetAttribute( "source"); const char* source = mReader->getAttributeValue( attrSource); if( source[0] != '#') ThrowException( boost::str( boost::format( "Unknown reference format in url \"%s\" in source attribute of <input> element.") % source)); channel.mAccessor = source+1; // skipping the leading #, hopefully the remaining text is the accessor ID only // read index offset, if per-index <input> int attrOffset = TestAttribute( "offset"); if( attrOffset > -1) channel.mOffset = mReader->getAttributeValueAsInt( attrOffset); // read set if texture coordinates if(channel.mType == IT_Texcoord || channel.mType == IT_Color){ int attrSet = TestAttribute("set"); if(attrSet > -1){ attrSet = mReader->getAttributeValueAsInt( attrSet); if(attrSet < 0) ThrowException( boost::str( boost::format( "Invalid index \"%i\" in set attribute of <input> element") % (attrSet))); channel.mIndex = attrSet; } } // store, if valid type if( channel.mType != IT_Invalid) poChannels.push_back( channel); // skip remaining stuff of this element, if any SkipElement(); } // ------------------------------------------------------------------------------------------------ // Reads a <p> primitive index list and assembles the mesh data into the given mesh size_t ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pPerIndexChannels, size_t pNumPrimitives, const std::vector<size_t>& pVCount, PrimitiveType pPrimType) { // determine number of indices coming per vertex // find the offset index for all per-vertex channels size_t numOffsets = 1; size_t perVertexOffset = SIZE_MAX; // invalid value BOOST_FOREACH( const InputChannel& channel, pPerIndexChannels) { numOffsets = std::max( numOffsets, channel.mOffset+1); if( channel.mType == IT_Vertex) perVertexOffset = channel.mOffset; } // determine the expected number of indices size_t expectedPointCount = 0; switch( pPrimType) { case Prim_Polylist: { BOOST_FOREACH( size_t i, pVCount) expectedPointCount += i; break; } case Prim_Lines: expectedPointCount = 2 * pNumPrimitives; break; case Prim_Triangles: expectedPointCount = 3 * pNumPrimitives; break; default: // other primitive types don't state the index count upfront... we need to guess break; } // and read all indices into a temporary array std::vector<size_t> indices; if( expectedPointCount > 0) indices.reserve( expectedPointCount * numOffsets); if (pNumPrimitives > 0) // It is possible to not contain any indicies { const char* content = GetTextContent(); while( *content != 0) { // read a value. // Hack: (thom) Some exporters put negative indices sometimes. We just try to carry on anyways. int value = std::max( 0, strtol10( content, &content)); indices.push_back( size_t( value)); // skip whitespace after it SkipSpacesAndLineEnd( &content); } } // complain if the index count doesn't fit if( expectedPointCount > 0 && indices.size() != expectedPointCount * numOffsets) { if (pPrimType == Prim_Lines) { // HACK: We just fix this number since SketchUp 15.3.331 writes the wrong 'count' for 'lines' ReportWarning( "Expected different index count in <p> element, %d instead of %d.", indices.size(), expectedPointCount * numOffsets); pNumPrimitives = (indices.size() / numOffsets) / 2; } else ThrowException( "Expected different index count in <p> element."); } else if( expectedPointCount == 0 && (indices.size() % numOffsets) != 0) ThrowException( "Expected different index count in <p> element."); // find the data for all sources for( std::vector<InputChannel>::iterator it = pMesh->mPerVertexData.begin(); it != pMesh->mPerVertexData.end(); ++it) { InputChannel& input = *it; if( input.mResolved) continue; // find accessor input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor); // resolve accessor's data pointer as well, if neccessary const Accessor* acc = input.mResolved; if( !acc->mData) acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource); } // and the same for the per-index channels for( std::vector<InputChannel>::iterator it = pPerIndexChannels.begin(); it != pPerIndexChannels.end(); ++it) { InputChannel& input = *it; if( input.mResolved) continue; // ignore vertex pointer, it doesn't refer to an accessor if( input.mType == IT_Vertex) { // warn if the vertex channel does not refer to the <vertices> element in the same mesh if( input.mAccessor != pMesh->mVertexID) ThrowException( "Unsupported vertex referencing scheme."); continue; } // find accessor input.mResolved = &ResolveLibraryReference( mAccessorLibrary, input.mAccessor); // resolve accessor's data pointer as well, if neccessary const Accessor* acc = input.mResolved; if( !acc->mData) acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource); } // For continued primitives, the given count does not come all in one <p>, but only one primitive per <p> size_t numPrimitives = pNumPrimitives; if( pPrimType == Prim_TriFans || pPrimType == Prim_Polygon) numPrimitives = 1; // For continued primitives, the given count is actually the number of <p>'s inside the parent tag if ( pPrimType == Prim_TriStrips){ size_t numberOfVertices = indices.size() / numOffsets; numPrimitives = numberOfVertices - 2; } pMesh->mFaceSize.reserve( numPrimitives); pMesh->mFacePosIndices.reserve( indices.size() / numOffsets); size_t polylistStartVertex = 0; for (size_t currentPrimitive = 0; currentPrimitive < numPrimitives; currentPrimitive++) { // determine number of points for this primitive size_t numPoints = 0; switch( pPrimType) { case Prim_Lines: numPoints = 2; for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); break; case Prim_Triangles: numPoints = 3; for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); break; case Prim_TriStrips: numPoints = 3; ReadPrimTriStrips(numOffsets, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); break; case Prim_Polylist: numPoints = pVCount[currentPrimitive]; for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) CopyVertex(polylistStartVertex + currentVertex, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, 0, indices); polylistStartVertex += numPoints; break; case Prim_TriFans: case Prim_Polygon: numPoints = indices.size() / numOffsets; for (size_t currentVertex = 0; currentVertex < numPoints; currentVertex++) CopyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); break; default: // LineStrip is not supported due to expected index unmangling ThrowException( "Unsupported primitive type."); break; } // store the face size to later reconstruct the face from pMesh->mFaceSize.push_back( numPoints); } // if I ever get my hands on that guy who invented this steaming pile of indirection... TestClosing( "p"); return numPrimitives; } void ColladaParser::CopyVertex(size_t currentVertex, size_t numOffsets, size_t numPoints, size_t perVertexOffset, Mesh* pMesh, std::vector<InputChannel>& pPerIndexChannels, size_t currentPrimitive, const std::vector<size_t>& indices){ // calculate the base offset of the vertex whose attributes we ant to copy size_t baseOffset = currentPrimitive * numOffsets * numPoints + currentVertex * numOffsets; // don't overrun the boundaries of the index list size_t maxIndexRequested = baseOffset + numOffsets - 1; ai_assert(maxIndexRequested < indices.size()); // extract per-vertex channels using the global per-vertex offset for (std::vector<InputChannel>::iterator it = pMesh->mPerVertexData.begin(); it != pMesh->mPerVertexData.end(); ++it) ExtractDataObjectFromChannel(*it, indices[baseOffset + perVertexOffset], pMesh); // and extract per-index channels using there specified offset for (std::vector<InputChannel>::iterator it = pPerIndexChannels.begin(); it != pPerIndexChannels.end(); ++it) ExtractDataObjectFromChannel(*it, indices[baseOffset + it->mOffset], pMesh); // store the vertex-data index for later assignment of bone vertex weights pMesh->mFacePosIndices.push_back(indices[baseOffset + perVertexOffset]); } void ColladaParser::ReadPrimTriStrips(size_t numOffsets, size_t perVertexOffset, Mesh* pMesh, std::vector<InputChannel>& pPerIndexChannels, size_t currentPrimitive, const std::vector<size_t>& indices){ if (currentPrimitive % 2 != 0){ //odd tristrip triangles need their indices mangled, to preserve winding direction CopyVertex(1, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); CopyVertex(0, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); CopyVertex(2, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); } else {//for non tristrips or even tristrip triangles CopyVertex(0, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); CopyVertex(1, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); CopyVertex(2, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices); } } // ------------------------------------------------------------------------------------------------ // Extracts a single object from an input channel and stores it in the appropriate mesh data array void ColladaParser::ExtractDataObjectFromChannel( const InputChannel& pInput, size_t pLocalIndex, Mesh* pMesh) { // ignore vertex referrer - we handle them that separate if( pInput.mType == IT_Vertex) return; const Accessor& acc = *pInput.mResolved; if( pLocalIndex >= acc.mCount) ThrowException( boost::str( boost::format( "Invalid data index (%d/%d) in primitive specification") % pLocalIndex % acc.mCount)); // get a pointer to the start of the data object referred to by the accessor and the local index const float* dataObject = &(acc.mData->mValues[0]) + acc.mOffset + pLocalIndex* acc.mStride; // assemble according to the accessors component sub-offset list. We don't care, yet, // what kind of object exactly we're extracting here float obj[4]; for( size_t c = 0; c < 4; ++c) obj[c] = dataObject[acc.mSubOffset[c]]; // now we reinterpret it according to the type we're reading here switch( pInput.mType) { case IT_Position: // ignore all position streams except 0 - there can be only one position if( pInput.mIndex == 0) pMesh->mPositions.push_back( aiVector3D( obj[0], obj[1], obj[2])); else DefaultLogger::get()->error("Collada: just one vertex position stream supported"); break; case IT_Normal: // pad to current vertex count if necessary if( pMesh->mNormals.size() < pMesh->mPositions.size()-1) pMesh->mNormals.insert( pMesh->mNormals.end(), pMesh->mPositions.size() - pMesh->mNormals.size() - 1, aiVector3D( 0, 1, 0)); // ignore all normal streams except 0 - there can be only one normal if( pInput.mIndex == 0) pMesh->mNormals.push_back( aiVector3D( obj[0], obj[1], obj[2])); else DefaultLogger::get()->error("Collada: just one vertex normal stream supported"); break; case IT_Tangent: // pad to current vertex count if necessary if( pMesh->mTangents.size() < pMesh->mPositions.size()-1) pMesh->mTangents.insert( pMesh->mTangents.end(), pMesh->mPositions.size() - pMesh->mTangents.size() - 1, aiVector3D( 1, 0, 0)); // ignore all tangent streams except 0 - there can be only one tangent if( pInput.mIndex == 0) pMesh->mTangents.push_back( aiVector3D( obj[0], obj[1], obj[2])); else DefaultLogger::get()->error("Collada: just one vertex tangent stream supported"); break; case IT_Bitangent: // pad to current vertex count if necessary if( pMesh->mBitangents.size() < pMesh->mPositions.size()-1) pMesh->mBitangents.insert( pMesh->mBitangents.end(), pMesh->mPositions.size() - pMesh->mBitangents.size() - 1, aiVector3D( 0, 0, 1)); // ignore all bitangent streams except 0 - there can be only one bitangent if( pInput.mIndex == 0) pMesh->mBitangents.push_back( aiVector3D( obj[0], obj[1], obj[2])); else DefaultLogger::get()->error("Collada: just one vertex bitangent stream supported"); break; case IT_Texcoord: // up to 4 texture coord sets are fine, ignore the others if( pInput.mIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS) { // pad to current vertex count if necessary if( pMesh->mTexCoords[pInput.mIndex].size() < pMesh->mPositions.size()-1) pMesh->mTexCoords[pInput.mIndex].insert( pMesh->mTexCoords[pInput.mIndex].end(), pMesh->mPositions.size() - pMesh->mTexCoords[pInput.mIndex].size() - 1, aiVector3D( 0, 0, 0)); pMesh->mTexCoords[pInput.mIndex].push_back( aiVector3D( obj[0], obj[1], obj[2])); if (0 != acc.mSubOffset[2] || 0 != acc.mSubOffset[3]) /* hack ... consider cleaner solution */ pMesh->mNumUVComponents[pInput.mIndex]=3; } else { DefaultLogger::get()->error("Collada: too many texture coordinate sets. Skipping."); } break; case IT_Color: // up to 4 color sets are fine, ignore the others if( pInput.mIndex < AI_MAX_NUMBER_OF_COLOR_SETS) { // pad to current vertex count if necessary if( pMesh->mColors[pInput.mIndex].size() < pMesh->mPositions.size()-1) pMesh->mColors[pInput.mIndex].insert( pMesh->mColors[pInput.mIndex].end(), pMesh->mPositions.size() - pMesh->mColors[pInput.mIndex].size() - 1, aiColor4D( 0, 0, 0, 1)); aiColor4D result(0, 0, 0, 1); for (size_t i = 0; i < pInput.mResolved->mSize; ++i) { result[i] = obj[pInput.mResolved->mSubOffset[i]]; } pMesh->mColors[pInput.mIndex].push_back(result); } else { DefaultLogger::get()->error("Collada: too many vertex color sets. Skipping."); } break; default: // IT_Invalid and IT_Vertex ai_assert(false && "shouldn't ever get here"); } } // ------------------------------------------------------------------------------------------------ // Reads the library of node hierarchies and scene parts void ColladaParser::ReadSceneLibrary() { if( mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { // a visual scene - generate root node under its ID and let ReadNode() do the recursive work if( IsElement( "visual_scene")) { // read ID. Is optional according to the spec, but how on earth should a scene_instance refer to it then? int indexID = GetAttribute( "id"); const char* attrID = mReader->getAttributeValue( indexID); // read name if given. int indexName = TestAttribute( "name"); const char* attrName = "unnamed"; if( indexName > -1) attrName = mReader->getAttributeValue( indexName); // create a node and store it in the library under its ID Node* node = new Node; node->mID = attrID; node->mName = attrName; mNodeLibrary[node->mID] = node; ReadSceneNode( node); } else { // ignore the rest SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "library_visual_scenes") == 0) //ThrowException( "Expected end of \"library_visual_scenes\" element."); break; } } } // ------------------------------------------------------------------------------------------------ // Reads a scene node's contents including children and stores it in the given node void ColladaParser::ReadSceneNode( Node* pNode) { // quit immediately on <bla/> elements if( mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "node")) { Node* child = new Node; int attrID = TestAttribute( "id"); if( attrID > -1) child->mID = mReader->getAttributeValue( attrID); int attrSID = TestAttribute( "sid"); if( attrSID > -1) child->mSID = mReader->getAttributeValue( attrSID); int attrName = TestAttribute( "name"); if( attrName > -1) child->mName = mReader->getAttributeValue( attrName); // TODO: (thom) support SIDs // ai_assert( TestAttribute( "sid") == -1); if (pNode) { pNode->mChildren.push_back( child); child->mParent = pNode; } else { // no parent node given, probably called from <library_nodes> element. // create new node in node library mNodeLibrary[child->mID] = child; } // read on recursively from there ReadSceneNode( child); continue; } // For any further stuff we need a valid node to work on else if (!pNode) continue; if( IsElement( "lookat")) ReadNodeTransformation( pNode, TF_LOOKAT); else if( IsElement( "matrix")) ReadNodeTransformation( pNode, TF_MATRIX); else if( IsElement( "rotate")) ReadNodeTransformation( pNode, TF_ROTATE); else if( IsElement( "scale")) ReadNodeTransformation( pNode, TF_SCALE); else if( IsElement( "skew")) ReadNodeTransformation( pNode, TF_SKEW); else if( IsElement( "translate")) ReadNodeTransformation( pNode, TF_TRANSLATE); else if( IsElement( "render") && pNode->mParent == NULL && 0 == pNode->mPrimaryCamera.length()) { // ... scene evaluation or, in other words, postprocessing pipeline, // or, again in other words, a turing-complete description how to // render a Collada scene. The only thing that is interesting for // us is the primary camera. int attrId = TestAttribute("camera_node"); if (-1 != attrId) { const char* s = mReader->getAttributeValue(attrId); if (s[0] != '#') DefaultLogger::get()->error("Collada: Unresolved reference format of camera"); else pNode->mPrimaryCamera = s+1; } } else if( IsElement( "instance_node")) { // find the node in the library int attrID = TestAttribute( "url"); if( attrID != -1) { const char* s = mReader->getAttributeValue(attrID); if (s[0] != '#') DefaultLogger::get()->error("Collada: Unresolved reference format of node"); else { pNode->mNodeInstances.push_back(NodeInstance()); pNode->mNodeInstances.back().mNode = s+1; } } } else if( IsElement( "instance_geometry") || IsElement( "instance_controller")) { // Reference to a mesh or controller, with possible material associations ReadNodeGeometry( pNode); } else if( IsElement( "instance_light")) { // Reference to a light, name given in 'url' attribute int attrID = TestAttribute("url"); if (-1 == attrID) DefaultLogger::get()->warn("Collada: Expected url attribute in <instance_light> element"); else { const char* url = mReader->getAttributeValue( attrID); if( url[0] != '#') ThrowException( "Unknown reference format in <instance_light> element"); pNode->mLights.push_back(LightInstance()); pNode->mLights.back().mLight = url+1; } } else if( IsElement( "instance_camera")) { // Reference to a camera, name given in 'url' attribute int attrID = TestAttribute("url"); if (-1 == attrID) DefaultLogger::get()->warn("Collada: Expected url attribute in <instance_camera> element"); else { const char* url = mReader->getAttributeValue( attrID); if( url[0] != '#') ThrowException( "Unknown reference format in <instance_camera> element"); pNode->mCameras.push_back(CameraInstance()); pNode->mCameras.back().mCamera = url+1; } } else { // skip everything else for the moment SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { break; } } } // ------------------------------------------------------------------------------------------------ // Reads a node transformation entry of the given type and adds it to the given node's transformation list. void ColladaParser::ReadNodeTransformation( Node* pNode, TransformType pType) { if( mReader->isEmptyElement()) return; std::string tagName = mReader->getNodeName(); Transform tf; tf.mType = pType; // read SID int indexSID = TestAttribute( "sid"); if( indexSID >= 0) tf.mID = mReader->getAttributeValue( indexSID); // how many parameters to read per transformation type static const unsigned int sNumParameters[] = { 9, 4, 3, 3, 7, 16 }; const char* content = GetTextContent(); // read as many parameters and store in the transformation for( unsigned int a = 0; a < sNumParameters[pType]; a++) { // read a number content = fast_atoreal_move<float>( content, tf.f[a]); // skip whitespace after it SkipSpacesAndLineEnd( &content); } // place the transformation at the queue of the node pNode->mTransforms.push_back( tf); // and consume the closing tag TestClosing( tagName.c_str()); } // ------------------------------------------------------------------------------------------------ // Processes bind_vertex_input and bind elements void ColladaParser::ReadMaterialVertexInputBinding( Collada::SemanticMappingTable& tbl) { while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "bind_vertex_input")) { Collada::InputSemanticMapEntry vn; // effect semantic int n = GetAttribute("semantic"); std::string s = mReader->getAttributeValue(n); // input semantic n = GetAttribute("input_semantic"); vn.mType = GetTypeForSemantic( mReader->getAttributeValue(n) ); // index of input set n = TestAttribute("input_set"); if (-1 != n) vn.mSet = mReader->getAttributeValueAsInt(n); tbl.mMap[s] = vn; } else if( IsElement( "bind")) { DefaultLogger::get()->warn("Collada: Found unsupported <bind> element"); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "instance_material") == 0) break; } } } // ------------------------------------------------------------------------------------------------ // Reads a mesh reference in a node and adds it to the node's mesh list void ColladaParser::ReadNodeGeometry( Node* pNode) { // referred mesh is given as an attribute of the <instance_geometry> element int attrUrl = GetAttribute( "url"); const char* url = mReader->getAttributeValue( attrUrl); if( url[0] != '#') ThrowException( "Unknown reference format"); Collada::MeshInstance instance; instance.mMeshOrController = url+1; // skipping the leading # if( !mReader->isEmptyElement()) { // read material associations. Ignore additional elements inbetween while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "instance_material")) { // read ID of the geometry subgroup and the target material int attrGroup = GetAttribute( "symbol"); std::string group = mReader->getAttributeValue( attrGroup); int attrMaterial = GetAttribute( "target"); const char* urlMat = mReader->getAttributeValue( attrMaterial); Collada::SemanticMappingTable s; if( urlMat[0] == '#') urlMat++; s.mMatName = urlMat; // resolve further material details + THIS UGLY AND NASTY semantic mapping stuff if( !mReader->isEmptyElement()) ReadMaterialVertexInputBinding(s); // store the association instance.mMaterials[group] = s; } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) { if( strcmp( mReader->getNodeName(), "instance_geometry") == 0 || strcmp( mReader->getNodeName(), "instance_controller") == 0) break; } } } // store it pNode->mMeshes.push_back( instance); } // ------------------------------------------------------------------------------------------------ // Reads the collada scene void ColladaParser::ReadScene() { if( mReader->isEmptyElement()) return; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT) { if( IsElement( "instance_visual_scene")) { // should be the first and only occurence if( mRootNode) ThrowException( "Invalid scene containing multiple root nodes in <instance_visual_scene> element"); // read the url of the scene to instance. Should be of format "#some_name" int urlIndex = GetAttribute( "url"); const char* url = mReader->getAttributeValue( urlIndex); if( url[0] != '#') ThrowException( "Unknown reference format in <instance_visual_scene> element"); // find the referred scene, skip the leading # NodeLibrary::const_iterator sit = mNodeLibrary.find( url+1); if( sit == mNodeLibrary.end()) ThrowException( "Unable to resolve visual_scene reference \"" + std::string(url) + "\" in <instance_visual_scene> element."); mRootNode = sit->second; } else { SkipElement(); } } else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END){ break; } } } // ------------------------------------------------------------------------------------------------ // Aborts the file reading with an exception AI_WONT_RETURN void ColladaParser::ThrowException( const std::string& pError) const { throw DeadlyImportError( boost::str( boost::format( "Collada: %s - %s") % mFileName % pError)); } void ColladaParser::ReportWarning(const char* msg,...) { ai_assert(NULL != msg); va_list args; va_start(args,msg); char szBuffer[3000]; const int iLen = vsprintf(szBuffer,msg,args); ai_assert(iLen > 0); va_end(args); DefaultLogger::get()->warn("Validation warning: " + std::string(szBuffer,iLen)); } // ------------------------------------------------------------------------------------------------ // Skips all data until the end node of the current element void ColladaParser::SkipElement() { // nothing to skip if it's an <element /> if( mReader->isEmptyElement()) return; // reroute SkipElement( mReader->getNodeName()); } // ------------------------------------------------------------------------------------------------ // Skips all data until the end node of the given element void ColladaParser::SkipElement( const char* pElement) { // copy the current node's name because it'a pointer to the reader's internal buffer, // which is going to change with the upcoming parsing std::string element = pElement; while( mReader->read()) { if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) if( mReader->getNodeName() == element) break; } } // ------------------------------------------------------------------------------------------------ // Tests for an opening element of the given name, throws an exception if not found void ColladaParser::TestOpening( const char* pName) { // read element start if( !mReader->read()) ThrowException( boost::str( boost::format( "Unexpected end of file while beginning of <%s> element.") % pName)); // whitespace in front is ok, just read again if found if( mReader->getNodeType() == irr::io::EXN_TEXT) if( !mReader->read()) ThrowException( boost::str( boost::format( "Unexpected end of file while reading beginning of <%s> element.") % pName)); if( mReader->getNodeType() != irr::io::EXN_ELEMENT || strcmp( mReader->getNodeName(), pName) != 0) ThrowException( boost::str( boost::format( "Expected start of <%s> element.") % pName)); } // ------------------------------------------------------------------------------------------------ // Tests for the closing tag of the given element, throws an exception if not found void ColladaParser::TestClosing( const char* pName) { // check if we're already on the closing tag and return right away if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END && strcmp( mReader->getNodeName(), pName) == 0) return; // if not, read some more if( !mReader->read()) ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of <%s> element.") % pName)); // whitespace in front is ok, just read again if found if( mReader->getNodeType() == irr::io::EXN_TEXT) if( !mReader->read()) ThrowException( boost::str( boost::format( "Unexpected end of file while reading end of <%s> element.") % pName)); // but this has the be the closing tag, or we're lost if( mReader->getNodeType() != irr::io::EXN_ELEMENT_END || strcmp( mReader->getNodeName(), pName) != 0) ThrowException( boost::str( boost::format( "Expected end of <%s> element.") % pName)); } // ------------------------------------------------------------------------------------------------ // Returns the index of the named attribute or -1 if not found. Does not throw, therefore useful for optional attributes int ColladaParser::GetAttribute( const char* pAttr) const { int index = TestAttribute( pAttr); if( index != -1) return index; // attribute not found -> throw an exception ThrowException( boost::str( boost::format( "Expected attribute \"%s\" for element <%s>.") % pAttr % mReader->getNodeName())); return -1; } // ------------------------------------------------------------------------------------------------ // Tests the present element for the presence of one attribute, returns its index or throws an exception if not found int ColladaParser::TestAttribute( const char* pAttr) const { for( int a = 0; a < mReader->getAttributeCount(); a++) if( strcmp( mReader->getAttributeName( a), pAttr) == 0) return a; return -1; } // ------------------------------------------------------------------------------------------------ // Reads the text contents of an element, throws an exception if not given. Skips leading whitespace. const char* ColladaParser::GetTextContent() { const char* sz = TestTextContent(); if(!sz) { ThrowException( "Invalid contents in element \"n\"."); } return sz; } // ------------------------------------------------------------------------------------------------ // Reads the text contents of an element, returns NULL if not given. Skips leading whitespace. const char* ColladaParser::TestTextContent() { // present node should be the beginning of an element if( mReader->getNodeType() != irr::io::EXN_ELEMENT || mReader->isEmptyElement()) return NULL; // read contents of the element if( !mReader->read() ) return NULL; if( mReader->getNodeType() != irr::io::EXN_TEXT) return NULL; // skip leading whitespace const char* text = mReader->getNodeData(); SkipSpacesAndLineEnd( &text); return text; } // ------------------------------------------------------------------------------------------------ // Calculates the resulting transformation fromm all the given transform steps aiMatrix4x4 ColladaParser::CalculateResultTransform( const std::vector<Transform>& pTransforms) const { aiMatrix4x4 res; for( std::vector<Transform>::const_iterator it = pTransforms.begin(); it != pTransforms.end(); ++it) { const Transform& tf = *it; switch( tf.mType) { case TF_LOOKAT: { aiVector3D pos( tf.f[0], tf.f[1], tf.f[2]); aiVector3D dstPos( tf.f[3], tf.f[4], tf.f[5]); aiVector3D up = aiVector3D( tf.f[6], tf.f[7], tf.f[8]).Normalize(); aiVector3D dir = aiVector3D( dstPos - pos).Normalize(); aiVector3D right = (dir ^ up).Normalize(); res *= aiMatrix4x4( right.x, up.x, -dir.x, pos.x, right.y, up.y, -dir.y, pos.y, right.z, up.z, -dir.z, pos.z, 0, 0, 0, 1); break; } case TF_ROTATE: { aiMatrix4x4 rot; float angle = tf.f[3] * float( AI_MATH_PI) / 180.0f; aiVector3D axis( tf.f[0], tf.f[1], tf.f[2]); aiMatrix4x4::Rotation( angle, axis, rot); res *= rot; break; } case TF_TRANSLATE: { aiMatrix4x4 trans; aiMatrix4x4::Translation( aiVector3D( tf.f[0], tf.f[1], tf.f[2]), trans); res *= trans; break; } case TF_SCALE: { aiMatrix4x4 scale( tf.f[0], 0.0f, 0.0f, 0.0f, 0.0f, tf.f[1], 0.0f, 0.0f, 0.0f, 0.0f, tf.f[2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); res *= scale; break; } case TF_SKEW: // TODO: (thom) ai_assert( false); break; case TF_MATRIX: { aiMatrix4x4 mat( tf.f[0], tf.f[1], tf.f[2], tf.f[3], tf.f[4], tf.f[5], tf.f[6], tf.f[7], tf.f[8], tf.f[9], tf.f[10], tf.f[11], tf.f[12], tf.f[13], tf.f[14], tf.f[15]); res *= mat; break; } default: ai_assert( false); break; } } return res; } // ------------------------------------------------------------------------------------------------ // Determines the input data type for the given semantic string Collada::InputType ColladaParser::GetTypeForSemantic( const std::string& pSemantic) { if( pSemantic == "POSITION") return IT_Position; else if( pSemantic == "TEXCOORD") return IT_Texcoord; else if( pSemantic == "NORMAL") return IT_Normal; else if( pSemantic == "COLOR") return IT_Color; else if( pSemantic == "VERTEX") return IT_Vertex; else if( pSemantic == "BINORMAL" || pSemantic == "TEXBINORMAL") return IT_Bitangent; else if( pSemantic == "TANGENT" || pSemantic == "TEXTANGENT") return IT_Tangent; DefaultLogger::get()->warn( boost::str( boost::format( "Unknown vertex input type \"%s\". Ignoring.") % pSemantic)); return IT_Invalid; } #endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER
{'content_hash': 'a5c61bd5b81ab067892d8f004dd03504', 'timestamp': '', 'source': 'github', 'line_count': 2918, 'max_line_length': 234, 'avg_line_length': 38.937628512679915, 'alnum_prop': 0.5047614856539342, 'repo_name': 'helingping/Urho3D', 'id': 'cdc3cedeb55a525b5ddabd0982dd47a100217ca6', 'size': '115405', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'Source/ThirdParty/Assimp/code/ColladaParser.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '1270325'}, {'name': 'Batchfile', 'bytes': '19782'}, {'name': 'C++', 'bytes': '7786867'}, {'name': 'CMake', 'bytes': '464850'}, {'name': 'GLSL', 'bytes': '161387'}, {'name': 'HLSL', 'bytes': '185428'}, {'name': 'HTML', 'bytes': '1375'}, {'name': 'Java', 'bytes': '77949'}, {'name': 'Lua', 'bytes': '475026'}, {'name': 'MAXScript', 'bytes': '94704'}, {'name': 'Objective-C', 'bytes': '6539'}, {'name': 'Ruby', 'bytes': '62537'}, {'name': 'Shell', 'bytes': '26427'}]}
<?php /** * CActiveFinder implements eager loading and lazy loading of related active records. * * When used in eager loading, this class provides the same set of find methods as * {@link CActiveRecord}. * * @author Qiang Xue <[email protected]> * @package system.db.ar * @since 1.0 */ class CActiveFinder extends CComponent { /** * @var boolean join all tables all at once. Defaults to false. * This property is internally used. */ public $joinAll=false; /** * @var boolean whether the base model has limit or offset. * This property is internally used. */ public $baseLimited=false; private $_joinCount=0; private $_joinTree; private $_builder; /** * Constructor. * A join tree is built up based on the declared relationships between active record classes. * @param CActiveRecord $model the model that initiates the active finding process * @param mixed $with the relation names to be actively looked for */ public function __construct($model,$with) { $this->_builder=$model->getCommandBuilder(); $this->_joinTree=new CJoinElement($this,$model); $this->buildJoinTree($this->_joinTree,$with); } /** * Do not call this method. This method is used internally to perform the relational query * based on the given DB criteria. * @param CDbCriteria $criteria the DB criteria * @param boolean $all whether to bring back all records * @return mixed the query result */ public function query($criteria,$all=false) { $this->joinAll=$criteria->together===true; if($criteria->alias!='') { $this->_joinTree->tableAlias=$criteria->alias; $this->_joinTree->rawTableAlias=$this->_builder->getSchema()->quoteTableName($criteria->alias); } $this->_joinTree->find($criteria); $this->_joinTree->afterFind(); if($all) { $result = array_values($this->_joinTree->records); if ($criteria->index!==null) { $index=$criteria->index; $array=array(); foreach($result as $object) $array[$object->$index]=$object; $result=$array; } } elseif(count($this->_joinTree->records)) $result = reset($this->_joinTree->records); else $result = null; $this->destroyJoinTree(); return $result; } /** * This method is internally called. * @param string $sql the SQL statement * @param array $params parameters to be bound to the SQL statement * @return CActiveRecord */ public function findBySql($sql,$params=array()) { Yii::trace(get_class($this->_joinTree->model).'.findBySql() eagerly','system.db.ar.CActiveRecord'); if(($row=$this->_builder->createSqlCommand($sql,$params)->queryRow())!==false) { $baseRecord=$this->_joinTree->model->populateRecord($row,false); $this->_joinTree->findWithBase($baseRecord); $this->_joinTree->afterFind(); $this->destroyJoinTree(); return $baseRecord; } else $this->destroyJoinTree(); } /** * This method is internally called. * @param string $sql the SQL statement * @param array $params parameters to be bound to the SQL statement * @return CActiveRecord[] */ public function findAllBySql($sql,$params=array()) { Yii::trace(get_class($this->_joinTree->model).'.findAllBySql() eagerly','system.db.ar.CActiveRecord'); if(($rows=$this->_builder->createSqlCommand($sql,$params)->queryAll())!==array()) { $baseRecords=$this->_joinTree->model->populateRecords($rows,false); $this->_joinTree->findWithBase($baseRecords); $this->_joinTree->afterFind(); $this->destroyJoinTree(); return $baseRecords; } else { $this->destroyJoinTree(); return array(); } } /** * This method is internally called. * @param CDbCriteria $criteria the query criteria * @return string */ public function count($criteria) { Yii::trace(get_class($this->_joinTree->model).'.count() eagerly','system.db.ar.CActiveRecord'); $this->joinAll=$criteria->together!==true; $alias=$criteria->alias===null ? 't' : $criteria->alias; $this->_joinTree->tableAlias=$alias; $this->_joinTree->rawTableAlias=$this->_builder->getSchema()->quoteTableName($alias); $n=$this->_joinTree->count($criteria); $this->destroyJoinTree(); return $n; } /** * Finds the related objects for the specified active record. * This method is internally invoked by {@link CActiveRecord} to support lazy loading. * @param CActiveRecord $baseRecord the base record whose related objects are to be loaded */ public function lazyFind($baseRecord) { $this->_joinTree->lazyFind($baseRecord); if(!empty($this->_joinTree->children)) { foreach($this->_joinTree->children as $child) $child->afterFind(); } $this->destroyJoinTree(); } /** * Given active record class name returns new model instance. * * @param string $className active record class name * @return CActiveRecord active record model instance * * @since 1.1.14 */ public function getModel($className) { return CActiveRecord::model($className); } private function destroyJoinTree() { if($this->_joinTree!==null) $this->_joinTree->destroy(); $this->_joinTree=null; } /** * Builds up the join tree representing the relationships involved in this query. * @param CJoinElement $parent the parent tree node * @param mixed $with the names of the related objects relative to the parent tree node * @param array $options additional query options to be merged with the relation * @throws CDbException if given parent tree node is an instance of {@link CStatElement} * or relation is not defined in the given parent's tree node model class */ private function buildJoinTree($parent,$with,$options=null) { if($parent instanceof CStatElement) throw new CDbException(Yii::t('yii','The STAT relation "{name}" cannot have child relations.', array('{name}'=>$parent->relation->name))); if(is_string($with)) { if(($pos=strrpos($with,'.'))!==false) { $parent=$this->buildJoinTree($parent,substr($with,0,$pos)); $with=substr($with,$pos+1); } // named scope $scopes=array(); if(($pos=strpos($with,':'))!==false) { $scopes=explode(':',substr($with,$pos+1)); $with=substr($with,0,$pos); } if(isset($parent->children[$with]) && $parent->children[$with]->master===null) return $parent->children[$with]; if(($relation=$parent->model->getActiveRelation($with))===null) throw new CDbException(Yii::t('yii','Relation "{name}" is not defined in active record class "{class}".', array('{class}'=>get_class($parent->model), '{name}'=>$with))); $relation=clone $relation; $model=$this->getModel($relation->className); if($relation instanceof CActiveRelation) { $oldAlias=$model->getTableAlias(false,false); if(isset($options['alias'])) $model->setTableAlias($options['alias']); elseif($relation->alias===null) $model->setTableAlias($relation->name); else $model->setTableAlias($relation->alias); } if(!empty($relation->scopes)) $scopes=array_merge($scopes,(array)$relation->scopes); // no need for complex merging if(!empty($options['scopes'])) $scopes=array_merge($scopes,(array)$options['scopes']); // no need for complex merging if(!empty($options['joinOptions'])) $relation->joinOptions=$options['joinOptions']; $model->resetScope(false); $criteria=$model->getDbCriteria(); $criteria->scopes=$scopes; $model->beforeFindInternal(); $model->applyScopes($criteria); // select has a special meaning in stat relation, so we need to ignore select from scope or model criteria if($relation instanceof CStatRelation) $criteria->select='*'; $relation->mergeWith($criteria,true); // dynamic options if($options!==null) $relation->mergeWith($options); if($relation instanceof CActiveRelation) $model->setTableAlias($oldAlias); if($relation instanceof CStatRelation) return new CStatElement($this,$relation,$parent); else { if(isset($parent->children[$with])) { $element=$parent->children[$with]; $element->relation=$relation; } else $element=new CJoinElement($this,$relation,$parent,++$this->_joinCount); if(!empty($relation->through)) { $slave=$this->buildJoinTree($parent,$relation->through,array('select'=>'')); $slave->master=$element; $element->slave=$slave; } $parent->children[$with]=$element; if(!empty($relation->with)) $this->buildJoinTree($element,$relation->with); return $element; } } // $with is an array, keys are relation name, values are relation spec foreach($with as $key=>$value) { if(is_string($value)) // the value is a relation name $this->buildJoinTree($parent,$value); elseif(is_string($key) && is_array($value)) $this->buildJoinTree($parent,$key,$value); } } } /** * CJoinElement represents a tree node in the join tree created by {@link CActiveFinder}. * * @author Qiang Xue <[email protected]> * @package system.db.ar * @since 1.0 */ class CJoinElement { /** * @var integer the unique ID of this tree node */ public $id; /** * @var CActiveRelation the relation represented by this tree node */ public $relation; /** * @var CActiveRelation the master relation */ public $master; /** * @var CActiveRelation the slave relation */ public $slave; /** * @var CActiveRecord the model associated with this tree node */ public $model; /** * @var array list of active records found by the queries. They are indexed by primary key values. */ public $records=array(); /** * @var array list of child join elements */ public $children=array(); /** * @var array list of stat elements */ public $stats=array(); /** * @var string table alias for this join element */ public $tableAlias; /** * @var string the quoted table alias for this element */ public $rawTableAlias; private $_finder; private $_builder; private $_parent; private $_pkAlias; // string or name=>alias private $_columnAliases=array(); // name=>alias private $_joined=false; private $_table; private $_related=array(); // PK, relation name, related PK => true /** * Constructor. * @param CActiveFinder $finder the finder * @param mixed $relation the relation (if the third parameter is not null) * or the model (if the third parameter is null) associated with this tree node. * @param CJoinElement $parent the parent tree node * @param integer $id the ID of this tree node that is unique among all the tree nodes */ public function __construct($finder,$relation,$parent=null,$id=0) { $this->_finder=$finder; $this->id=$id; if($parent!==null) { $this->relation=$relation; $this->_parent=$parent; $this->model=$this->_finder->getModel($relation->className); $this->_builder=$this->model->getCommandBuilder(); $this->tableAlias=$relation->alias===null?$relation->name:$relation->alias; $this->rawTableAlias=$this->_builder->getSchema()->quoteTableName($this->tableAlias); $this->_table=$this->model->getTableSchema(); } else // root element, the first parameter is the model. { $this->model=$relation; $this->_builder=$relation->getCommandBuilder(); $this->_table=$relation->getTableSchema(); $this->tableAlias=$this->model->getTableAlias(); $this->rawTableAlias=$this->_builder->getSchema()->quoteTableName($this->tableAlias); } // set up column aliases, such as t1_c2 $table=$this->_table; if($this->model->getDbConnection()->getDriverName()==='oci') // Issue 482 $prefix='T'.$id.'_C'; else $prefix='t'.$id.'_c'; foreach($table->getColumnNames() as $key=>$name) { $alias=$prefix.$key; $this->_columnAliases[$name]=$alias; if($table->primaryKey===$name) $this->_pkAlias=$alias; elseif(is_array($table->primaryKey) && in_array($name,$table->primaryKey)) $this->_pkAlias[$name]=$alias; } } /** * Removes references to child elements and finder to avoid circular references. * This is internally used. */ public function destroy() { if(!empty($this->children)) { foreach($this->children as $child) $child->destroy(); } unset($this->_finder, $this->_parent, $this->model, $this->relation, $this->master, $this->slave, $this->records, $this->children, $this->stats); } /** * Performs the recursive finding with the criteria. * @param CDbCriteria $criteria the query criteria */ public function find($criteria=null) { if($this->_parent===null) // root element { $query=new CJoinQuery($this,$criteria); $this->_finder->baseLimited=($criteria->offset>=0 || $criteria->limit>=0); $this->buildQuery($query); $this->_finder->baseLimited=false; $this->runQuery($query); } elseif(!$this->_joined && !empty($this->_parent->records)) // not joined before { $query=new CJoinQuery($this->_parent); $this->_joined=true; $query->join($this); $this->buildQuery($query); $this->_parent->runQuery($query); } foreach($this->children as $child) // find recursively $child->find(); foreach($this->stats as $stat) $stat->query(); } /** * Performs lazy find with the specified base record. * @param CActiveRecord $baseRecord the active record whose related object is to be fetched. */ public function lazyFind($baseRecord) { if(is_string($this->_table->primaryKey)) $this->records[$baseRecord->{$this->_table->primaryKey}]=$baseRecord; else { $pk=array(); foreach($this->_table->primaryKey as $name) $pk[$name]=$baseRecord->$name; $this->records[serialize($pk)]=$baseRecord; } foreach($this->stats as $stat) $stat->query(); if(!$this->children) return; $params=array(); foreach($this->children as $child) if(is_array($child->relation->params)) $params=array_merge($params,$child->relation->params); $query=new CJoinQuery($child); $query->selects=array($child->getColumnSelect($child->relation->select)); $query->conditions=array( $child->relation->on, ); $query->groups[]=$child->relation->group; $query->joins[]=$child->relation->join; $query->havings[]=$child->relation->having; $query->orders[]=$child->relation->order; $query->params=$params; $query->elements[$child->id]=true; if($child->relation instanceof CHasManyRelation) { $query->limit=$child->relation->limit; $query->offset=$child->relation->offset; } $child->applyLazyCondition($query,$baseRecord); $this->_joined=true; $child->_joined=true; $this->_finder->baseLimited=false; $child->buildQuery($query); $child->runQuery($query); foreach($child->children as $c) $c->find(); if(empty($child->records)) return; if($child->relation instanceof CHasOneRelation || $child->relation instanceof CBelongsToRelation) $baseRecord->addRelatedRecord($child->relation->name,reset($child->records),false); else // has_many and many_many { foreach($child->records as $record) { if($child->relation->index!==null) $index=$record->{$child->relation->index}; else $index=true; $baseRecord->addRelatedRecord($child->relation->name,$record,$index); } } } /** * Apply Lazy Condition * @param CJoinQuery $query represents a JOIN SQL statements * @param CActiveRecord $record the active record whose related object is to be fetched. * @throws CDbException if relation in active record class is not specified correctly */ private function applyLazyCondition($query,$record) { $schema=$this->_builder->getSchema(); $parent=$this->_parent; if($this->relation instanceof CManyManyRelation) { $query->conditions=array( $this->relation->condition, ); $joinTableName=$this->relation->getJunctionTableName(); if(($joinTable=$schema->getTable($joinTableName))===null) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is not specified correctly: the join table "{joinTable}" given in the foreign key cannot be found in the database.', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{joinTable}'=>$joinTableName))); $fks=$this->relation->getJunctionForeignKeys(); $joinAlias=$schema->quoteTableName($this->relation->name.'_'.$this->tableAlias); $parentCondition=array(); $childCondition=array(); $count=0; $params=array(); $fkDefined=true; foreach($fks as $i=>$fk) { if(isset($joinTable->foreignKeys[$fk])) // FK defined { list($tableName,$pk)=$joinTable->foreignKeys[$fk]; if(!isset($parentCondition[$pk]) && $schema->compareTableNames($parent->_table->rawName,$tableName)) { $parentCondition[$pk]=$joinAlias.'.'.$schema->quoteColumnName($fk).'=:ypl'.$count; $params[':ypl'.$count]=$record->$pk; $count++; } elseif(!isset($childCondition[$pk]) && $schema->compareTableNames($this->_table->rawName,$tableName)) $childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); else { $fkDefined=false; break; } } else { $fkDefined=false; break; } } if(!$fkDefined) { $parentCondition=array(); $childCondition=array(); $count=0; $params=array(); foreach($fks as $i=>$fk) { if($i<count($parent->_table->primaryKey)) { $pk=is_array($parent->_table->primaryKey) ? $parent->_table->primaryKey[$i] : $parent->_table->primaryKey; $parentCondition[$pk]=$joinAlias.'.'.$schema->quoteColumnName($fk).'=:ypl'.$count; $params[':ypl'.$count]=$record->$pk; $count++; } else { $j=$i-count($parent->_table->primaryKey); $pk=is_array($this->_table->primaryKey) ? $this->_table->primaryKey[$j] : $this->_table->primaryKey; $childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); } } } if($parentCondition!==array() && $childCondition!==array()) { $join='INNER JOIN '.$joinTable->rawName.' '.$joinAlias.' ON '; $join.='('.implode(') AND (',$parentCondition).') AND ('.implode(') AND (',$childCondition).')'; if(!empty($this->relation->on)) $join.=' AND ('.$this->relation->on.')'; $query->joins[]=$join; foreach($params as $name=>$value) $query->params[$name]=$value; } else throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name))); } else { $element=$this; while(true) { $condition=$element->relation->condition; if(!empty($condition)) $query->conditions[]=$condition; $query->params=array_merge($query->params,$element->relation->params); if($element->slave!==null) { $query->joins[]=$element->slave->joinOneMany($element->slave,$element->relation->foreignKey,$element,$parent); $element=$element->slave; } else break; } $fks=is_array($element->relation->foreignKey) ? $element->relation->foreignKey : preg_split('/\s*,\s*/',$element->relation->foreignKey,-1,PREG_SPLIT_NO_EMPTY); $prefix=$element->getColumnPrefix(); $params=array(); foreach($fks as $i=>$fk) { if(!is_int($i)) { $pk=$fk; $fk=$i; } if($element->relation instanceof CBelongsToRelation) { if(is_int($i)) { if(isset($parent->_table->foreignKeys[$fk])) // FK defined $pk=$parent->_table->foreignKeys[$fk][1]; elseif(is_array($element->_table->primaryKey)) // composite PK $pk=$element->_table->primaryKey[$i]; else $pk=$element->_table->primaryKey; } $params[$pk]=$record->$fk; } else { if(is_int($i)) { if(isset($element->_table->foreignKeys[$fk])) // FK defined $pk=$element->_table->foreignKeys[$fk][1]; elseif(is_array($parent->_table->primaryKey)) // composite PK $pk=$parent->_table->primaryKey[$i]; else $pk=$parent->_table->primaryKey; } $params[$fk]=$record->$pk; } } $count=0; foreach($params as $name=>$value) { $query->conditions[]=$prefix.$schema->quoteColumnName($name).'=:ypl'.$count; $query->params[':ypl'.$count]=$value; $count++; } } } /** * Performs the eager loading with the base records ready. * @param mixed $baseRecords the available base record(s). */ public function findWithBase($baseRecords) { if(!is_array($baseRecords)) $baseRecords=array($baseRecords); if(is_string($this->_table->primaryKey)) { foreach($baseRecords as $baseRecord) $this->records[$baseRecord->{$this->_table->primaryKey}]=$baseRecord; } else { foreach($baseRecords as $baseRecord) { $pk=array(); foreach($this->_table->primaryKey as $name) $pk[$name]=$baseRecord->$name; $this->records[serialize($pk)]=$baseRecord; } } $query=new CJoinQuery($this); $this->buildQuery($query); if(count($query->joins)>1) $this->runQuery($query); foreach($this->children as $child) $child->find(); foreach($this->stats as $stat) $stat->query(); } /** * Count the number of primary records returned by the join statement. * @param CDbCriteria $criteria the query criteria * @return string number of primary records. Note: type is string to keep max. precision. */ public function count($criteria=null) { $query=new CJoinQuery($this,$criteria); // ensure only one big join statement is used $this->_finder->baseLimited=false; $this->_finder->joinAll=true; $this->buildQuery($query); $query->limit=$query->offset=-1; if(!empty($criteria->group) || !empty($criteria->having)) { $query->orders = array(); $command=$query->createCommand($this->_builder); $sql=$command->getText(); $sql="SELECT COUNT(*) FROM ({$sql}) sq"; $command->setText($sql); $command->params=$query->params; return $command->queryScalar(); } else { $select=is_array($criteria->select) ? implode(',',$criteria->select) : $criteria->select; if($select!=='*' && preg_match('/^count\s*\(/i',trim($select))) $query->selects=array($select); elseif(is_string($this->_table->primaryKey)) { $prefix=$this->getColumnPrefix(); $schema=$this->_builder->getSchema(); $column=$prefix.$schema->quoteColumnName($this->_table->primaryKey); $query->selects=array("COUNT(DISTINCT $column)"); } else $query->selects=array("COUNT(*)"); $query->orders=$query->groups=$query->havings=array(); $command=$query->createCommand($this->_builder); return $command->queryScalar(); } } /** * Calls {@link CActiveRecord::afterFind} of all the records. */ public function afterFind() { foreach($this->records as $record) $record->afterFindInternal(); foreach($this->children as $child) $child->afterFind(); $this->children = null; } /** * Builds the join query with all descendant HAS_ONE and BELONGS_TO nodes. * @param CJoinQuery $query the query being built up */ public function buildQuery($query) { foreach($this->children as $child) { if($child->master!==null) $child->_joined=true; elseif($child->relation instanceof CHasOneRelation || $child->relation instanceof CBelongsToRelation || $this->_finder->joinAll || $child->relation->together || (!$this->_finder->baseLimited && $child->relation->together===null)) { $child->_joined=true; $query->join($child); $child->buildQuery($query); } } } /** * Executes the join query and populates the query results. * @param CJoinQuery $query the query to be executed. */ public function runQuery($query) { $command=$query->createCommand($this->_builder); foreach($command->queryAll() as $row) $this->populateRecord($query,$row); } /** * Populates the active records with the query data. * @param CJoinQuery $query the query executed * @param array $row a row of data * @return CActiveRecord the populated record */ private function populateRecord($query,$row) { // determine the primary key value if(is_string($this->_pkAlias)) // single key { if(isset($row[$this->_pkAlias])) $pk=$row[$this->_pkAlias]; else // no matching related objects return null; } else // is_array, composite key { $pk=array(); foreach($this->_pkAlias as $name=>$alias) { if(isset($row[$alias])) $pk[$name]=$row[$alias]; else // no matching related objects return null; } $pk=serialize($pk); } // retrieve or populate the record according to the primary key value if(isset($this->records[$pk])) $record=$this->records[$pk]; else { $attributes=array(); $aliases=array_flip($this->_columnAliases); foreach($row as $alias=>$value) { if(isset($aliases[$alias])) $attributes[$aliases[$alias]]=$value; } $record=$this->model->populateRecord($attributes,false); foreach($this->children as $child) { if(!empty($child->relation->select)) $record->addRelatedRecord($child->relation->name,null,$child->relation instanceof CHasManyRelation); } $this->records[$pk]=$record; } // populate child records recursively foreach($this->children as $child) { if(!isset($query->elements[$child->id]) || empty($child->relation->select)) continue; $childRecord=$child->populateRecord($query,$row); if($child->relation instanceof CHasOneRelation || $child->relation instanceof CBelongsToRelation) $record->addRelatedRecord($child->relation->name,$childRecord,false); else // has_many and many_many { // need to double check to avoid adding duplicated related objects if($childRecord instanceof CActiveRecord) $fpk=serialize($childRecord->getPrimaryKey()); else $fpk=0; if(!isset($this->_related[$pk][$child->relation->name][$fpk])) { if($childRecord instanceof CActiveRecord && $child->relation->index!==null) $index=$childRecord->{$child->relation->index}; else $index=true; $record->addRelatedRecord($child->relation->name,$childRecord,$index); $this->_related[$pk][$child->relation->name][$fpk]=true; } } } return $record; } /** * @return string the table name and the table alias (if any). This can be used directly in SQL query without escaping. */ public function getTableNameWithAlias() { if($this->tableAlias!==null) return $this->_table->rawName . ' ' . $this->rawTableAlias; else return $this->_table->rawName; } /** * Generates the list of columns to be selected. * Columns will be properly aliased and primary keys will be added to selection if they are not specified. * @param mixed $select columns to be selected. Defaults to '*', indicating all columns. * @throws CDbException if active record class is trying to select an invalid column * @return string the column selection */ public function getColumnSelect($select='*') { $schema=$this->_builder->getSchema(); $prefix=$this->getColumnPrefix(); $columns=array(); if($select==='*') { foreach($this->_table->getColumnNames() as $name) $columns[]=$prefix.$schema->quoteColumnName($name).' AS '.$schema->quoteColumnName($this->_columnAliases[$name]); } else { if(is_string($select)) $select=explode(',',$select); $selected=array(); foreach($select as $name) { $name=trim($name); $matches=array(); if(($pos=strrpos($name,'.'))!==false) $key=substr($name,$pos+1); else $key=$name; $key=trim($key,'\'"`'); if($key==='*') { foreach($this->_table->columns as $name=>$column) { $alias=$this->_columnAliases[$name]; if(!isset($selected[$alias])) { $columns[]=$prefix.$column->rawName.' AS '.$schema->quoteColumnName($alias); $selected[$alias]=1; } } continue; } if(isset($this->_columnAliases[$key])) // simple column names { $columns[]=$prefix.$schema->quoteColumnName($key).' AS '.$schema->quoteColumnName($this->_columnAliases[$key]); $selected[$this->_columnAliases[$key]]=1; } elseif(preg_match('/^(.*?)\s+AS\s+(\w+)$/im',$name,$matches)) // if the column is already aliased { $alias=$matches[2]; if(!isset($this->_columnAliases[$alias]) || $this->_columnAliases[$alias]!==$alias) { $this->_columnAliases[$alias]=$alias; $columns[]=$name; $selected[$alias]=1; } } else throw new CDbException(Yii::t('yii','Active record "{class}" is trying to select an invalid column "{column}". Note, the column must exist in the table or be an expression with alias.', array('{class}'=>get_class($this->model), '{column}'=>$name))); } // add primary key selection if they are not selected if(is_string($this->_pkAlias) && !isset($selected[$this->_pkAlias])) $columns[]=$prefix.$schema->quoteColumnName($this->_table->primaryKey).' AS '.$schema->quoteColumnName($this->_pkAlias); elseif(is_array($this->_pkAlias)) { foreach($this->_pkAlias as $name=>$alias) if(!isset($selected[$alias])) $columns[]=$prefix.$schema->quoteColumnName($name).' AS '.$schema->quoteColumnName($alias); } } return implode(', ',$columns); } /** * @return string the primary key selection */ public function getPrimaryKeySelect() { $schema=$this->_builder->getSchema(); $prefix=$this->getColumnPrefix(); $columns=array(); if(is_string($this->_pkAlias)) $columns[]=$prefix.$schema->quoteColumnName($this->_table->primaryKey).' AS '.$schema->quoteColumnName($this->_pkAlias); elseif(is_array($this->_pkAlias)) { foreach($this->_pkAlias as $name=>$alias) $columns[]=$prefix.$schema->quoteColumnName($name).' AS '.$schema->quoteColumnName($alias); } return implode(', ',$columns); } /** * @return string the condition that specifies only the rows with the selected primary key values. */ public function getPrimaryKeyRange() { if(empty($this->records)) return ''; $values=array_keys($this->records); if(is_array($this->_table->primaryKey)) { foreach($values as &$value) $value=unserialize($value); } return $this->_builder->createInCondition($this->_table,$this->_table->primaryKey,$values,$this->getColumnPrefix()); } /** * @return string the column prefix for column reference disambiguation */ public function getColumnPrefix() { if($this->tableAlias!==null) return $this->rawTableAlias.'.'; else return $this->_table->rawName.'.'; } /** * @throws CDbException if relation in active record class is not specified correctly * @return string the join statement (this node joins with its parent) */ public function getJoinCondition() { $parent=$this->_parent; if($this->relation instanceof CManyManyRelation) { $schema=$this->_builder->getSchema(); $joinTableName=$this->relation->getJunctionTableName(); if(($joinTable=$schema->getTable($joinTableName))===null) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is not specified correctly: the join table "{joinTable}" given in the foreign key cannot be found in the database.', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{joinTable}'=>$joinTableName))); $fks=$this->relation->getJunctionForeignKeys(); return $this->joinManyMany($joinTable,$fks,$parent); } else { $fks=is_array($this->relation->foreignKey) ? $this->relation->foreignKey : preg_split('/\s*,\s*/',$this->relation->foreignKey,-1,PREG_SPLIT_NO_EMPTY); if($this->slave!==null) { if($this->relation instanceof CBelongsToRelation) { $fks=array_flip($fks); $pke=$this->slave; $fke=$this; } else { $pke=$this; $fke=$this->slave; } } elseif($this->relation instanceof CBelongsToRelation) { $pke=$this; $fke=$parent; } else { $pke=$parent; $fke=$this; } return $this->joinOneMany($fke,$fks,$pke,$parent); } } /** * Generates the join statement for one-many relationship. * This works for HAS_ONE, HAS_MANY and BELONGS_TO. * @param CJoinElement $fke the join element containing foreign keys * @param array $fks the foreign keys * @param CJoinElement $pke the join element contains primary keys * @param CJoinElement $parent the parent join element * @return string the join statement * @throws CDbException if a foreign key is invalid */ private function joinOneMany($fke,$fks,$pke,$parent) { $schema=$this->_builder->getSchema(); $joins=array(); if(is_string($fks)) $fks=preg_split('/\s*,\s*/',$fks,-1,PREG_SPLIT_NO_EMPTY); foreach($fks as $i=>$fk) { if(!is_int($i)) { $pk=$fk; $fk=$i; } if(!isset($fke->_table->columns[$fk])) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{key}'=>$fk, '{table}'=>$fke->_table->name))); if(is_int($i)) { if(isset($fke->_table->foreignKeys[$fk]) && $schema->compareTableNames($pke->_table->rawName, $fke->_table->foreignKeys[$fk][0])) $pk=$fke->_table->foreignKeys[$fk][1]; else // FK constraints undefined { if(is_array($pke->_table->primaryKey)) // composite PK $pk=$pke->_table->primaryKey[$i]; else $pk=$pke->_table->primaryKey; } } $joins[]=$fke->getColumnPrefix().$schema->quoteColumnName($fk) . '=' . $pke->getColumnPrefix().$schema->quoteColumnName($pk); } if(!empty($this->relation->on)) $joins[]=$this->relation->on; if(!empty($this->relation->joinOptions) && is_string($this->relation->joinOptions)) return $this->relation->joinType.' '.$this->getTableNameWithAlias().' '.$this->relation->joinOptions. ' ON ('.implode(') AND (',$joins).')'; else return $this->relation->joinType.' '.$this->getTableNameWithAlias().' ON ('.implode(') AND (',$joins).')'; } /** * Generates the join statement for many-many relationship. * @param CDbTableSchema $joinTable the join table * @param array $fks the foreign keys * @param CJoinElement $parent the parent join element * @return string the join statement * @throws CDbException if a foreign key is invalid */ private function joinManyMany($joinTable,$fks,$parent) { $schema=$this->_builder->getSchema(); $joinAlias=$schema->quoteTableName($this->relation->name.'_'.$this->tableAlias); $parentCondition=array(); $childCondition=array(); $fkDefined=true; foreach($fks as $i=>$fk) { if(!isset($joinTable->columns[$fk])) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{key}'=>$fk, '{table}'=>$joinTable->name))); if(isset($joinTable->foreignKeys[$fk])) { list($tableName,$pk)=$joinTable->foreignKeys[$fk]; if(!isset($parentCondition[$pk]) && $schema->compareTableNames($parent->_table->rawName,$tableName)) $parentCondition[$pk]=$parent->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); elseif(!isset($childCondition[$pk]) && $schema->compareTableNames($this->_table->rawName,$tableName)) $childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); else { $fkDefined=false; break; } } else { $fkDefined=false; break; } } if(!$fkDefined) { $parentCondition=array(); $childCondition=array(); foreach($fks as $i=>$fk) { if($i<count($parent->_table->primaryKey)) { $pk=is_array($parent->_table->primaryKey) ? $parent->_table->primaryKey[$i] : $parent->_table->primaryKey; $parentCondition[$pk]=$parent->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); } else { $j=$i-count($parent->_table->primaryKey); $pk=is_array($this->_table->primaryKey) ? $this->_table->primaryKey[$j] : $this->_table->primaryKey; $childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); } } } if($parentCondition!==array() && $childCondition!==array()) { $join=$this->relation->joinType.' '.$joinTable->rawName.' '.$joinAlias; if(is_array($this->relation->joinOptions) && isset($this->relation->joinOptions[0]) && is_string($this->relation->joinOptions[0])) $join.=' '.$this->relation->joinOptions[0]; elseif(!empty($this->relation->joinOptions) && is_string($this->relation->joinOptions)) $join.=' '.$this->relation->joinOptions; $join.=' ON ('.implode(') AND (',$parentCondition).')'; $join.=' '.$this->relation->joinType.' '.$this->getTableNameWithAlias(); if(is_array($this->relation->joinOptions) && isset($this->relation->joinOptions[1]) && is_string($this->relation->joinOptions[1])) $join.=' '.$this->relation->joinOptions[1]; $join.=' ON ('.implode(') AND (',$childCondition).')'; if(!empty($this->relation->on)) $join.=' AND ('.$this->relation->on.')'; return $join; } else throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name))); } } /** * CJoinQuery represents a JOIN SQL statement. * * @author Qiang Xue <[email protected]> * @package system.db.ar * @since 1.0 */ class CJoinQuery { /** * @var array list of column selections */ public $selects=array(); /** * @var boolean whether to select distinct result set */ public $distinct=false; /** * @var array list of join statement */ public $joins=array(); /** * @var array list of WHERE clauses */ public $conditions=array(); /** * @var array list of ORDER BY clauses */ public $orders=array(); /** * @var array list of GROUP BY clauses */ public $groups=array(); /** * @var array list of HAVING clauses */ public $havings=array(); /** * @var integer row limit */ public $limit=-1; /** * @var integer row offset */ public $offset=-1; /** * @var array list of query parameters */ public $params=array(); /** * @var array list of join element IDs (id=>true) */ public $elements=array(); /** * Constructor. * @param CJoinElement $joinElement The root join tree. * @param CDbCriteria $criteria the query criteria */ public function __construct($joinElement,$criteria=null) { if($criteria!==null) { $this->selects[]=$joinElement->getColumnSelect($criteria->select); $this->joins[]=$joinElement->getTableNameWithAlias(); $this->joins[]=$criteria->join; $this->conditions[]=$criteria->condition; $this->orders[]=$criteria->order; $this->groups[]=$criteria->group; $this->havings[]=$criteria->having; $this->limit=$criteria->limit; $this->offset=$criteria->offset; $this->params=$criteria->params; if(!$this->distinct && $criteria->distinct) $this->distinct=true; } else { $this->selects[]=$joinElement->getPrimaryKeySelect(); $this->joins[]=$joinElement->getTableNameWithAlias(); $this->conditions[]=$joinElement->getPrimaryKeyRange(); } $this->elements[$joinElement->id]=true; } /** * Joins with another join element * @param CJoinElement $element the element to be joined */ public function join($element) { if($element->slave!==null) $this->join($element->slave); if(!empty($element->relation->select)) $this->selects[]=$element->getColumnSelect($element->relation->select); $this->conditions[]=$element->relation->condition; $this->orders[]=$element->relation->order; $this->joins[]=$element->getJoinCondition(); $this->joins[]=$element->relation->join; $this->groups[]=$element->relation->group; $this->havings[]=$element->relation->having; if(is_array($element->relation->params)) { if(is_array($this->params)) $this->params=array_merge($this->params,$element->relation->params); else $this->params=$element->relation->params; } $this->elements[$element->id]=true; } /** * Creates the SQL statement. * @param CDbCommandBuilder $builder the command builder * @return CDbCommand DB command instance representing the SQL statement */ public function createCommand($builder) { $sql=($this->distinct ? 'SELECT DISTINCT ':'SELECT ') . implode(', ',$this->selects); $sql.=' FROM ' . implode(' ',array_unique($this->joins)); $conditions=array(); foreach($this->conditions as $condition) if($condition!=='') $conditions[]=$condition; if($conditions!==array()) $sql.=' WHERE (' . implode(') AND (',$conditions).')'; $groups=array(); foreach($this->groups as $group) if($group!=='') $groups[]=$group; if($groups!==array()) $sql.=' GROUP BY ' . implode(', ',$groups); $havings=array(); foreach($this->havings as $having) if($having!=='') $havings[]=$having; if($havings!==array()) $sql.=' HAVING (' . implode(') AND (',$havings).')'; $orders=array(); foreach($this->orders as $order) if($order!=='') $orders[]=$order; if($orders!==array()) $sql.=' ORDER BY ' . implode(', ',$orders); $sql=$builder->applyLimit($sql,$this->limit,$this->offset); $command=$builder->getDbConnection()->createCommand($sql); $builder->bindValues($command,$this->params); return $command; } } /** * CStatElement represents STAT join element for {@link CActiveFinder}. * * @author Qiang Xue <[email protected]> * @package system.db.ar */ class CStatElement { /** * @var CActiveRelation the relation represented by this tree node */ public $relation; private $_finder; private $_parent; /** * Constructor. * @param CActiveFinder $finder the finder * @param CStatRelation $relation the STAT relation * @param CJoinElement $parent the join element owning this STAT element */ public function __construct($finder,$relation,$parent) { $this->_finder=$finder; $this->_parent=$parent; $this->relation=$relation; $parent->stats[]=$this; } /** * Performs the STAT query. */ public function query() { if(preg_match('/^\s*(.*?)\((.*)\)\s*$/',$this->relation->foreignKey,$matches)) $this->queryManyMany($matches[1],$matches[2]); else $this->queryOneMany(); } private function queryOneMany() { $relation=$this->relation; $model=$this->_finder->getModel($relation->className); $builder=$model->getCommandBuilder(); $schema=$builder->getSchema(); $table=$model->getTableSchema(); $parent=$this->_parent; $pkTable=$parent->model->getTableSchema(); $fks=preg_split('/\s*,\s*/',$relation->foreignKey,-1,PREG_SPLIT_NO_EMPTY); if(count($fks)!==count($pkTable->primaryKey)) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key. The columns in the key must match the primary keys of the table "{table}".', array('{class}'=>get_class($parent->model), '{relation}'=>$relation->name, '{table}'=>$pkTable->name))); // set up mapping between fk and pk columns $map=array(); // pk=>fk foreach($fks as $i=>$fk) { if(!isset($table->columns[$fk])) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".', array('{class}'=>get_class($parent->model), '{relation}'=>$relation->name, '{key}'=>$fk, '{table}'=>$table->name))); if(isset($table->foreignKeys[$fk])) { list($tableName,$pk)=$table->foreignKeys[$fk]; if($schema->compareTableNames($pkTable->rawName,$tableName)) $map[$pk]=$fk; else throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with a foreign key "{key}" that does not point to the parent table "{table}".', array('{class}'=>get_class($parent->model), '{relation}'=>$relation->name, '{key}'=>$fk, '{table}'=>$pkTable->name))); } else // FK constraints undefined { if(is_array($pkTable->primaryKey)) // composite PK $map[$pkTable->primaryKey[$i]]=$fk; else $map[$pkTable->primaryKey]=$fk; } } $records=$this->_parent->records; $join=empty($relation->join)?'' : ' '.$relation->join; $where=empty($relation->condition)?' WHERE ' : ' WHERE ('.$relation->condition.') AND '; $group=empty($relation->group)?'' : ', '.$relation->group; $having=empty($relation->having)?'' : ' HAVING ('.$relation->having.')'; $order=empty($relation->order)?'' : ' ORDER BY '.$relation->order; $c=$schema->quoteColumnName('c'); $s=$schema->quoteColumnName('s'); $tableAlias=$model->getTableAlias(true); // generate and perform query if(count($fks)===1) // single column FK { $col=$tableAlias.'.'.$table->columns[$fks[0]]->rawName; $sql="SELECT $col AS $c, {$relation->select} AS $s FROM {$table->rawName} ".$tableAlias.$join .$where.'('.$builder->createInCondition($table,$fks[0],array_keys($records),$tableAlias.'.').')' ." GROUP BY $col".$group .$having.$order; $command=$builder->getDbConnection()->createCommand($sql); if(is_array($relation->params)) $builder->bindValues($command,$relation->params); $stats=array(); foreach($command->queryAll() as $row) $stats[$row['c']]=$row['s']; } else // composite FK { $keys=array_keys($records); foreach($keys as &$key) { $key2=unserialize($key); $key=array(); foreach($pkTable->primaryKey as $pk) $key[$map[$pk]]=$key2[$pk]; } $cols=array(); foreach($pkTable->primaryKey as $n=>$pk) { $name=$tableAlias.'.'.$table->columns[$map[$pk]]->rawName; $cols[$name]=$name.' AS '.$schema->quoteColumnName('c'.$n); } $sql='SELECT '.implode(', ',$cols).", {$relation->select} AS $s FROM {$table->rawName} ".$tableAlias.$join .$where.'('.$builder->createInCondition($table,$fks,$keys,$tableAlias.'.').')' .' GROUP BY '.implode(', ',array_keys($cols)).$group .$having.$order; $command=$builder->getDbConnection()->createCommand($sql); if(is_array($relation->params)) $builder->bindValues($command,$relation->params); $stats=array(); foreach($command->queryAll() as $row) { $key=array(); foreach($pkTable->primaryKey as $n=>$pk) $key[$pk]=$row['c'.$n]; $stats[serialize($key)]=$row['s']; } } // populate the results into existing records foreach($records as $pk=>$record) $record->addRelatedRecord($relation->name,isset($stats[$pk])?$stats[$pk]:$relation->defaultValue,false); } /** * @param string $joinTableName jointablename * @param string $keys keys * @throws CDbException */ private function queryManyMany($joinTableName,$keys) { $relation=$this->relation; $model=$this->_finder->getModel($relation->className); $table=$model->getTableSchema(); $builder=$model->getCommandBuilder(); $schema=$builder->getSchema(); $pkTable=$this->_parent->model->getTableSchema(); $tableAlias=$model->getTableAlias(true); if(($joinTable=$builder->getSchema()->getTable($joinTableName))===null) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is not specified correctly: the join table "{joinTable}" given in the foreign key cannot be found in the database.', array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name, '{joinTable}'=>$joinTableName))); $fks=preg_split('/\s*,\s*/',$keys,-1,PREG_SPLIT_NO_EMPTY); if(count($fks)!==count($table->primaryKey)+count($pkTable->primaryKey)) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.', array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name))); $joinCondition=array(); $map=array(); $fkDefined=true; foreach($fks as $i=>$fk) { if(!isset($joinTable->columns[$fk])) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".', array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name, '{key}'=>$fk, '{table}'=>$joinTable->name))); if(isset($joinTable->foreignKeys[$fk])) { list($tableName,$pk)=$joinTable->foreignKeys[$fk]; if(!isset($joinCondition[$pk]) && $schema->compareTableNames($table->rawName,$tableName)) $joinCondition[$pk]=$tableAlias.'.'.$schema->quoteColumnName($pk).'='.$joinTable->rawName.'.'.$schema->quoteColumnName($fk); elseif(!isset($map[$pk]) && $schema->compareTableNames($pkTable->rawName,$tableName)) $map[$pk]=$fk; else { $fkDefined=false; break; } } else { $fkDefined=false; break; } } if(!$fkDefined) { $joinCondition=array(); $map=array(); foreach($fks as $i=>$fk) { if($i<count($pkTable->primaryKey)) { $pk=is_array($pkTable->primaryKey) ? $pkTable->primaryKey[$i] : $pkTable->primaryKey; $map[$pk]=$fk; } else { $j=$i-count($pkTable->primaryKey); $pk=is_array($table->primaryKey) ? $table->primaryKey[$j] : $table->primaryKey; $joinCondition[$pk]=$tableAlias.'.'.$schema->quoteColumnName($pk).'='.$joinTable->rawName.'.'.$schema->quoteColumnName($fk); } } } if($joinCondition===array() || $map===array()) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.', array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name))); $records=$this->_parent->records; $cols=array(); foreach(is_string($pkTable->primaryKey)?array($pkTable->primaryKey):$pkTable->primaryKey as $n=>$pk) { $name=$joinTable->rawName.'.'.$schema->quoteColumnName($map[$pk]); $cols[$name]=$name.' AS '.$schema->quoteColumnName('c'.$n); } $keys=array_keys($records); if(is_array($pkTable->primaryKey)) { foreach($keys as &$key) { $key2=unserialize($key); $key=array(); foreach($pkTable->primaryKey as $pk) $key[$map[$pk]]=$key2[$pk]; } } $join=empty($relation->join)?'' : ' '.$relation->join; $where=empty($relation->condition)?'' : ' WHERE ('.$relation->condition.')'; $group=empty($relation->group)?'' : ', '.$relation->group; $having=empty($relation->having)?'' : ' AND ('.$relation->having.')'; $order=empty($relation->order)?'' : ' ORDER BY '.$relation->order; $sql='SELECT '.$this->relation->select.' AS '.$schema->quoteColumnName('s').', '.implode(', ',$cols) .' FROM '.$table->rawName.' '.$tableAlias.' INNER JOIN '.$joinTable->rawName .' ON ('.implode(') AND (',$joinCondition).')'.$join .$where .' GROUP BY '.implode(', ',array_keys($cols)).$group .' HAVING ('.$builder->createInCondition($joinTable,$map,$keys).')' .$having.$order; $command=$builder->getDbConnection()->createCommand($sql); if(is_array($relation->params)) $builder->bindValues($command,$relation->params); $stats=array(); foreach($command->queryAll() as $row) { if(is_array($pkTable->primaryKey)) { $key=array(); foreach($pkTable->primaryKey as $n=>$k) $key[$k]=$row['c'.$n]; $stats[serialize($key)]=$row['s']; } else $stats[$row['c0']]=$row['s']; } foreach($records as $pk=>$record) $record->addRelatedRecord($relation->name,isset($stats[$pk])?$stats[$pk]:$this->relation->defaultValue,false); } }
{'content_hash': '94ce59366de6d37ee1d848018dfe92df', 'timestamp': '', 'source': 'github', 'line_count': 1654, 'max_line_length': 219, 'avg_line_length': 31.611850060459492, 'alnum_prop': 0.6433462112228895, 'repo_name': 'hellorich/go-craft', 'id': '36eb86c857ff449e17ec37ec742bd069bcf2aa81', 'size': '52496', 'binary': False, 'copies': '61', 'ref': 'refs/heads/master', 'path': 'craft/app/framework/db/ar/CActiveFinder.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Shell', 'bytes': '1763'}]}
package org.maera.plugin.servlet.filter; /** * The dispatching conditions that are taken into account when deciding to match a filter. These match to the dispatcher * values allowed in the Servlet API version 2.4. * * @since 2.5.0 */ public enum FilterDispatcherCondition { REQUEST, INCLUDE, FORWARD, ERROR; /** * Determines if a dispatcher value is a valid condition * * @param dispatcher The dispatcher value. Null allowed. * @return True if valid, false otherwise */ public static boolean contains(String dispatcher) { for (FilterDispatcherCondition cond : values()) { if (cond.toString().equals(dispatcher)) { return true; } } return false; } }
{'content_hash': '9833f14ba0e1822c2f50fadbdb0f0986', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 121, 'avg_line_length': 26.724137931034484, 'alnum_prop': 0.632258064516129, 'repo_name': 'katasource/maera', 'id': '245186890a658c7ae85dfd4f831f910b416870ca', 'size': '775', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'servlet/src/main/java/org/maera/plugin/servlet/filter/FilterDispatcherCondition.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '2332713'}]}
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/questionMain" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:layout_alignParentLeft="true"> </TextView> <TextView android:id="@+id/authorMain" android:layout_width="wrap_content" android:layout_height="30sp" android:paddingTop="10sp" android:textSize="15sp" android:textColor="@color/grey" android:layout_below="@id/questionMain" android:layout_alignParentRight="true"> </TextView> <TextView android:id="@+id/numOfPoints" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="10sp" android:textSize="12sp" android:layout_below="@id/locMain" android:layout_alignParentLeft="true"> </TextView> <TextView android:id="@+id/numOfAnswers" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="10sp" android:layout_below="@id/locMain" android:layout_alignParentRight="true" android:textSize="12sp"> </TextView> <TextView android:id="@+id/locMain" android:layout_width="wrap_content" android:layout_height="30sp" android:paddingTop="10sp" android:textSize="12sp" android:textColor="@color/grey" android:layout_below="@id/authorMain" android:layout_alignParentRight="true"> </TextView> </RelativeLayout>
{'content_hash': 'f2593c013f88c090309126e41f1aa44f', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 74, 'avg_line_length': 30.0, 'alnum_prop': 0.6619883040935672, 'repo_name': 'CMPUT301F14T09/Team09Project', 'id': 'a276ff1c93dfc69bf52428109e1547d2d87250f3', 'size': '1710', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': "Team09_Q'sAndA's/res/layout/user_row_layout.xml", 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '13382'}, {'name': 'Java', 'bytes': '172984'}, {'name': 'JavaScript', 'bytes': '857'}]}
# coding: utf8 """ Data structures for the CSS abstract syntax tree. """ from __future__ import unicode_literals from ..webencodings import ascii_lower from .serializer import (serialize_identifier, serialize_name, serialize_string_value, _serialize_to) class Node(object): """Every node type inherits from this class, which is never instantiated directly. .. attribute:: type Each child class has a :attr:`type` class attribute with an unique string value. This allows checking for the node type with code like: .. code-block:: python if node.type == 'whitespace': instead of the more verbose: .. code-block:: python from tinycss2.ast import WhitespaceToken if isinstance(node, WhitespaceToken): Every node also has these attributes and methods, which are not repeated for brevity: .. attribute:: source_line The line number of the start of the node in the CSS source. Starts at 1. .. attribute:: source_column The column number within :attr:`source_line` of the start of the node in the CSS source. Starts at 1. .. automethod:: serialize """ __slots__ = ['source_line', 'source_column'] def __init__(self, source_line, source_column): self.source_line = source_line self.source_column = source_column if str is bytes: def __repr__(self): return self.repr_format.format(self=self).encode('utf8') else: def __repr__(self): return self.repr_format.format(self=self) def serialize(self): """Serialize this node to CSS syntax and return an Unicode string.""" chuncks = [] self._serialize_to(chuncks.append) return ''.join(chuncks) def _serialize_to(self, write): """Serialize this node to CSS syntax, writing chuncks as Unicode string by calling the provided :obj:`write` callback. """ raise NotImplementedError class ParseError(Node): """A syntax error of some sort. May occur anywhere in the tree. Syntax errors are not fatal in the parser to allow for different error handling behaviors. For example, an error in a Selector list makes the whole rule invalid, but an error in a Media Query list only replaces one comma-separated query with ``not all``. .. autoattribute:: type .. attribute:: kind Machine-readable string indicating the type of error. Example: ``'bad-url'``. .. attribute:: message Human-readable explanation of the error, as a string. Could be translated, expanded to include details, etc. """ __slots__ = ['kind', 'message'] type = 'error' repr_format = '<{self.__class__.__name__} {self.kind}>' def __init__(self, line, column, kind, message): Node.__init__(self, line, column) self.kind = kind self.message = message def _serialize_to(self, write): if self.kind == 'bad-string': write('"[bad string]\n') elif self.kind == 'bad-url': write('url([bad url])') elif self.kind in ')]}': write(self.kind) else: raise TypeError('Can not serialize %r' % self) class Comment(Node): """A CSS comment. By default, comments are ignored and :class:`Comment` objects are not created. This can be changed by passing ``preserve_comments=True`` to :func:`~tinycss2.parse_component_value_list` .. autoattribute:: type .. attribute:: value The content of the comment, between ``/*`` and ``*/``. """ __slots__ = ['value'] type = 'comment' repr_format = '<{self.__class__.__name__} {self.value}>' def __init__(self, line, column, value): Node.__init__(self, line, column) self.value = value def _serialize_to(self, write): write('/*') write(self.value) write('*/') class WhitespaceToken(Node): """A :diagram:`whitespace-token`. .. autoattribute:: type """ __slots__ = [] type = 'whitespace' repr_format = '<{self.__class__.__name__}>' def _serialize_to(self, write): write(' ') class LiteralToken(Node): r"""Token that represents one or more characters as in the CSS source. .. autoattribute:: type .. attribute:: value A string of one to four characters. Instances compare equal to their :attr:`value`, so that these are equivalent: .. code-block:: python if node == ';': if node.type == 'literal' and node.value == ';': This regroups what `the specification`_ defines as separate token types: .. _the specification: http://dev.w3.org/csswg/css-syntax-3/ * *<colon-token>* ``:`` * *<semicolon-token>* ``;`` * *<comma-token>* ``,`` * *<cdc-token>* ``-->`` * *<cdo-token>* ``<!--`` * *<include-match-token>* ``~=`` * *<dash-match-token>* ``|=`` * *<prefix-match-token>* ``^=`` * *<suffix-match-token>* ``$=`` * *<substring-match-token>* ``*=`` * *<column-token>* ``||`` * *<delim-token>* (a single ASCII character not part of any another token) """ __slots__ = ['value'] type = 'literal' repr_format = '<{self.__class__.__name__} {self.value}>' def __init__(self, line, column, value): Node.__init__(self, line, column) self.value = value def __eq__(self, other): return self.value == other or self is other def __ne__(self, other): return not self == other def _serialize_to(self, write): write(self.value) class IdentToken(Node): """An :diagram:`ident-token`. .. autoattribute:: type .. attribute:: value The unescaped value, as an Unicode string. .. attribute:: lower_value Same as :attr:`value` but normalized to *ASCII lower case*, see :func:`~webencodings.ascii_lower`. This is the value to use when comparing to a CSS keyword. """ __slots__ = ['value', 'lower_value'] type = 'ident' repr_format = '<{self.__class__.__name__} {self.value}>' def __init__(self, line, column, value): Node.__init__(self, line, column) self.value = value self.lower_value = ascii_lower(value) def _serialize_to(self, write): write(serialize_identifier(self.value)) class AtKeywordToken(Node): """An :diagram:`at-keyword-token`. .. autoattribute:: type .. attribute:: value The unescaped value, as an Unicode string, without the preceding ``@``. .. attribute:: lower_value Same as :attr:`value` but normalized to *ASCII lower case*, see :func:`~webencodings.ascii_lower`. This is the value to use when comparing to a CSS at-keyword. .. code-block:: python if node.type == 'at-keyword' and node.lower_value == 'import': ... """ __slots__ = ['value', 'lower_value'] type = 'at-keyword' repr_format = '<{self.__class__.__name__} @{self.value}>' def __init__(self, line, column, value): Node.__init__(self, line, column) self.value = value self.lower_value = ascii_lower(value) def _serialize_to(self, write): write('@') write(serialize_identifier(self.value)) class HashToken(Node): r"""A :diagram:`hash-token`. .. autoattribute:: type .. attribute:: value The unescaped value, as an Unicode string, without the preceding ``#``. .. attribute:: is_identifier A boolean, true if the CSS source for this token was ``#`` followed by a valid identifier. (Only such hash tokens are valid ID selectors.) """ __slots__ = ['value', 'is_identifier'] type = 'hash' repr_format = '<{self.__class__.__name__} #{self.value}>' def __init__(self, line, column, value, is_identifier): Node.__init__(self, line, column) self.value = value self.is_identifier = is_identifier def _serialize_to(self, write): write('#') if self.is_identifier: write(serialize_identifier(self.value)) else: write(serialize_name(self.value)) class StringToken(Node): """A :diagram:`string-token`. .. autoattribute:: type .. attribute:: value The unescaped value, as an Unicode string, without the quotes. """ __slots__ = ['value'] type = 'string' repr_format = '<{self.__class__.__name__} "{self.value}">' def __init__(self, line, column, value): Node.__init__(self, line, column) self.value = value def _serialize_to(self, write): write('"') write(serialize_string_value(self.value)) write('"') class URLToken(Node): """An :diagram:`url-token`. .. autoattribute:: type .. attribute:: value The unescaped URL, as an Unicode string, without the ``url(`` and ``)`` markers or the optional quotes. """ __slots__ = ['value'] type = 'url' repr_format = '<{self.__class__.__name__} url({self.value})>' def __init__(self, line, column, value): Node.__init__(self, line, column) self.value = value def _serialize_to(self, write): write('url("') write(serialize_string_value(self.value)) write('")') class UnicodeRangeToken(Node): """An :diagram:`unicode-range-token`. .. autoattribute:: type .. attribute:: start The start of the range, as an integer between 0 and 1114111. .. attribute:: end The end of the range, as an integer between 0 and 1114111. Same as :attr:`start` if the source only specified one value. """ __slots__ = ['start', 'end'] type = 'unicode-range' repr_format = '<{self.__class__.__name__} {self.start} {self.end}>' def __init__(self, line, column, start, end): Node.__init__(self, line, column) self.start = start self.end = end def _serialize_to(self, write): if self.end == self.start: write('U+%X' % self.start) else: write('U+%X-%X' % (self.start, self.end)) class NumberToken(Node): """A :diagram:`numer-token`. .. autoattribute:: type .. attribute:: value The numeric value as a :class:`float`. .. attribute:: int_value The numeric value as an :class:`int` if :attr:`is_integer` is true, :obj:`None` otherwise. .. attribute:: is_integer Whether the token was syntactically an integer, as a boolean. .. attribute:: representation The CSS representation of the value, as an Unicode string. """ __slots__ = ['value', 'int_value', 'is_integer', 'representation'] type = 'number' repr_format = '<{self.__class__.__name__} {self.representation}>' def __init__(self, line, column, value, int_value, representation): Node.__init__(self, line, column) self.value = value self.int_value = int_value self.is_integer = int_value is not None self.representation = representation def _serialize_to(self, write): write(self.representation) class PercentageToken(Node): """A :diagram:`percentage-token`. .. autoattribute:: type .. attribute:: value The value numeric as a :class:`float`. .. attribute:: int_value The numeric value as an :class:`int` if the token was syntactically an integer, or :obj:`None`. .. attribute:: is_integer Whether the token’s value was syntactically an integer, as a boolean. .. attribute:: representation The CSS representation of the value without the unit, as an Unicode string. """ __slots__ = ['value', 'int_value', 'is_integer', 'representation'] type = 'percentage' repr_format = '<{self.__class__.__name__} {self.representation}%>' def __init__(self, line, column, value, int_value, representation): Node.__init__(self, line, column) self.value = value self.int_value = int_value self.is_integer = int_value is not None self.representation = representation def _serialize_to(self, write): write(self.representation) write('%') class DimensionToken(Node): """A :diagram:`dimension-token`. .. autoattribute:: type .. attribute:: value The value numeric as a :class:`float`. .. attribute:: int_value The numeric value as an :class:`int` if the token was syntactically an integer, or :obj:`None`. .. attribute:: is_integer Whether the token’s value was syntactically an integer, as a boolean. .. attribute:: representation The CSS representation of the value without the unit, as an Unicode string. .. attribute:: unit The unescaped unit, as an Unicode string. .. attribute:: lower_unit Same as :attr:`unit` but normalized to *ASCII lower case*, see :func:`~webencodings.ascii_lower`. This is the value to use when comparing to a CSS unit. .. code-block:: python if node.type == 'dimension' and node.lower_unit == 'px': ... """ __slots__ = ['value', 'int_value', 'is_integer', 'representation', 'unit', 'lower_unit'] type = 'dimension' repr_format = ('<{self.__class__.__name__} ' '{self.representation}{self.unit}>') def __init__(self, line, column, value, int_value, representation, unit): Node.__init__(self, line, column) self.value = value self.int_value = int_value self.is_integer = int_value is not None self.representation = representation self.unit = unit self.lower_unit = ascii_lower(unit) def _serialize_to(self, write): write(self.representation) # Disambiguate with scientific notation unit = self.unit if unit in ('e', 'E') or unit.startswith(('e-', 'E-')): write('\\65 ') write(serialize_name(unit[1:])) else: write(serialize_identifier(unit)) class ParenthesesBlock(Node): """A :diagram:`()-block`. .. autoattribute:: type .. attribute:: content The content of the block, as list of :term:`component values`. The ``(`` and ``)`` markers themselves are not represented in the list. """ __slots__ = ['content'] type = '() block' repr_format = '<{self.__class__.__name__} ( … )>' def __init__(self, line, column, content): Node.__init__(self, line, column) self.content = content def _serialize_to(self, write): write('(') _serialize_to(self.content, write) write(')') class SquareBracketsBlock(Node): """A :diagram:`[]-block`. .. autoattribute:: type .. attribute:: content The content of the block, as list of :term:`component values`. The ``[`` and ``]`` markers themselves are not represented in the list. """ __slots__ = ['content'] type = '[] block' repr_format = '<{self.__class__.__name__} [ … ]>' def __init__(self, line, column, content): Node.__init__(self, line, column) self.content = content def _serialize_to(self, write): write('[') _serialize_to(self.content, write) write(']') class CurlyBracketsBlock(Node): """A :diagram:`{}-block`. .. autoattribute:: type .. attribute:: content The content of the block, as list of :term:`component values`. The ``[`` and ``]`` markers themselves are not represented in the list. """ __slots__ = ['content'] type = '{} block' repr_format = '<{self.__class__.__name__} {{ … }}>' def __init__(self, line, column, content): Node.__init__(self, line, column) self.content = content def _serialize_to(self, write): write('{') _serialize_to(self.content, write) write('}') class FunctionBlock(Node): """A :diagram:`function-block`. .. autoattribute:: type .. attribute:: name The unescaped name of the function, as an Unicode string. .. attribute:: lower_name Same as :attr:`name` but normalized to *ASCII lower case*, see :func:`~webencodings.ascii_lower`. This is the value to use when comparing to a CSS function name. .. attribute:: arguments The arguments of the function, as list of :term:`component values`. The ``(`` and ``)`` markers themselves are not represented in the list. Commas are not special, but represented as :obj:`LiteralToken` objects in the list. """ __slots__ = ['name', 'lower_name', 'arguments'] type = 'function' repr_format = '<{self.__class__.__name__} {self.name}( … )>' def __init__(self, line, column, name, arguments): Node.__init__(self, line, column) self.name = name self.lower_name = ascii_lower(name) self.arguments = arguments def _serialize_to(self, write): write(serialize_identifier(self.name)) write('(') _serialize_to(self.arguments, write) write(')') class Declaration(Node): """A (property or descriptor) :diagram:`declaration`. .. autoattribute:: type .. attribute:: name The unescaped name, as an Unicode string. .. autoattribute:: type .. attribute:: lower_name Same as :attr:`name` but normalized to *ASCII lower case*, see :func:`~webencodings.ascii_lower`. This is the value to use when comparing to a CSS property or descriptor name. .. code-block:: python if node.type == 'declaration' and node.lower_name == 'color': ... .. attribute:: value The declaration value as a list of :term:`component values`: anything between ``:`` and the end of the declaration, or ``!important``. .. attribute:: important A boolean, true if the declaration had an ``!important`` marker. It is up to the consumer to reject declarations that do not accept this flag, such as non-property descriptor declarations. """ __slots__ = ['name', 'lower_name', 'value', 'important'] type = 'declaration' repr_format = '<{self.__class__.__name__} {self.name}: …>' def __init__(self, line, column, name, lower_name, value, important): Node.__init__(self, line, column) self.name = name self.lower_name = lower_name self.value = value self.important = important def _serialize_to(self, write): write(serialize_identifier(self.name)) write(':') _serialize_to(self.value, write) write(';') class QualifiedRule(Node): """A :diagram:`qualified rule`. The interpretation of style rules depend on their context. At the top-level of a stylesheet or in a conditional rule such as ``@media``, they are style rules where the :attr:`prelude` is a list of Selectors and the :attr:`body` is a list of property declarations. .. autoattribute:: type .. attribute:: prelude The rule’s prelude, the part before the {} block, as a list of :term:`component values`. .. attribute:: content The rule’s content, the part inside the {} block, as a list of :term:`component values`. """ __slots__ = ['prelude', 'content'] type = 'qualified-rule' repr_format = ('<{self.__class__.__name__} ' '… {{ … }}>') def __init__(self, line, column, prelude, content): Node.__init__(self, line, column) self.prelude = prelude self.content = content def _serialize_to(self, write): _serialize_to(self.prelude, write) write('{') _serialize_to(self.content, write) write('}') class AtRule(Node): """An :diagram:`at-rule`. The interpretation of at-rules depend on their at-keyword as well as their context. Most types of at-rules (ie. at-keyword values) are only allowed in some context, and must either end with a {} block or a semicolon. .. autoattribute:: type .. attribute:: at_keyword The unescaped value of the rule’s at-keyword, without the ``@`` symbol, as an Unicode string. .. attribute:: lower_at_keyword Same as :attr:`at_keyword` but normalized to *ASCII lower case*, see :func:`~webencodings.ascii_lower`. This is the value to use when comparing to a CSS at-keyword. .. code-block:: python if node.type == 'at-rule' and node.lower_at_keyword == 'import': ... .. attribute:: prelude The rule’s prelude, the part before the {} block or semicolon, as a list of :term:`component values`. .. attribute:: content The rule’s content, if any. The block’s content as a list of :term:`component values` for at-rules with a {} block, or :obj:`None` for at-rules ending with a semicolon. """ __slots__ = ['at_keyword', 'lower_at_keyword', 'prelude', 'content'] type = 'at-rule' repr_format = ('<{self.__class__.__name__} ' '@{self.at_keyword} … {{ … }}>') def __init__(self, line, column, at_keyword, lower_at_keyword, prelude, content): Node.__init__(self, line, column) self.at_keyword = at_keyword self.lower_at_keyword = lower_at_keyword self.prelude = prelude self.content = content def _serialize_to(self, write): write('@') write(serialize_identifier(self.at_keyword)) _serialize_to(self.prelude, write) if self.content is None: write(';') else: write('{') _serialize_to(self.content, write) write('}')
{'content_hash': '4f2bae9877cf420f1d6c8afb76556044', 'timestamp': '', 'source': 'github', 'line_count': 806, 'max_line_length': 80, 'avg_line_length': 27.325062034739453, 'alnum_prop': 0.581683617871413, 'repo_name': 'aeroaks/httpProfiler', 'id': '750389a26936dc9683b57f59a796a9080e365d8e', 'size': '22058', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'methods/tinycss2/ast.py', 'mode': '33188', 'license': 'mit', 'language': []}
package fm.liu.timo.manager.handler; import fm.liu.timo.manager.ManagerConnection; import fm.liu.timo.manager.parser.ManagerParseStop; import fm.liu.timo.manager.response.ResponseUtil; import fm.liu.timo.manager.response.StopHeartbeat; /** * @author xianmao.hexm */ public final class StopHandler { public static void handle(String stmt, ManagerConnection c, int offset) { switch (ManagerParseStop.parse(stmt, offset)) { case ManagerParseStop.HEARTBEAT: StopHeartbeat.execute(stmt, c); break; default: ResponseUtil.error(c); } } }
{'content_hash': 'caa44129fd3b89eaeb2f90966aa3fd51', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 77, 'avg_line_length': 26.416666666666668, 'alnum_prop': 0.6656151419558359, 'repo_name': 'ronghuaxiang/Timo', 'id': '17b40258be6c3a0294a82f241ea16c1af464f460', 'size': '1229', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/main/java/fm/liu/timo/manager/handler/StopHandler.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '138'}, {'name': 'Java', 'bytes': '2636150'}, {'name': 'Shell', 'bytes': '2138'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Ristorante Con Fusion: About Us</title> <!-- Bootstrap --> <link href="bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet"> <link href="bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet"> <link href="css/bootstrap-social.css" rel="stylesheet"> <link href="css/mystyles.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body data-spy="scroll" data-target="#myScrollspy" data-offset="200"> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.html"><img src="img/logo.png" height=30 width=41></a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="index.html"><span class="glyphicon glyphicon-home" aria-hidden="true"></span> Home</a></li> <li class="active"><a href="aboutus.html"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span> About</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> Menu<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Appetizers</a></li> <li><a href="#">Main Courses</a></li> <li><a href="#">Desserts</a></li> <li><a href="#">Drinks</a></li> <li role="separator" class="divider"></li> <li class="dropdown-header">Specials</li> <li><a href="#">Lunch Buffet</a></li> <li><a href="#">Weekend Brunch</a></li> </ul> </li> <li><a href="contactus.html"><span class="fa fa-envelope-o" aria-hidden="true"></span> Contact</a></li> </ul> </div> </div> </nav> <header class="jumbotron"> <!-- Main component for a primary marketing message or call to action --> <div class="container"> <div class="row row-header"> <div class="col-xs-12 col-sm-8"> <h1>Ristorante con Fusion</h1> <p style="padding:40px;"></p> <p>We take inspiration from the World's best cuisines, and create a unique fusion experience. Our lipsmacking creations will tickle your culinary senses!</p> </div> <div class="col-xs-12 col-sm-2"> <p style="padding:20px;"></p> <img src="img/logo.png" class="img-responsive"> </div> </div> </div> </header> <div class="row"> <div class="col-xs-12 col-sm-10"> <div class="container"> <div> <div> <ol class="breadcrumb"> <li><a href="index.html">Home</a></li> <li class="active">About</li> </ol> </div> <div> <h3>About Us</h3> <hr> </div> </div> <div class="row row-content" id="history"> <div class="col-xs-12 col-sm-6 col-lg-8"> <h2>Our History</h2> <p>Started in 2010, Ristorante con Fusion quickly established itself as a culinary icon par excellence in Hong Kong. With its unique brand of world fusion cuisine that can be found nowhere else, it enjoys patronage from the A-list clientele in Hong Kong. Featuring four of the best three-star Michelin chefs in the world, you never know what will arrive on your plate the next time you visit us.</p> <p>The restaurant traces its humble beginnings to <em>The Frying Pan</em>, a successful chain started by our CEO, Mr. Peter Pan, that featured for the first time the world's best cuisines in a pan.</p> <div class="well"> <blockquote> <p>You better cut the pizza in four pieces because I'm not hungry enough to eat six.</p> <footer>Yogi Berra, <cite>The Wit and Wisdom of Yogi Berra, P. Pepe, Diversion Books, 2014</cite> </footer> </blockquote> </div> </div> <div class="col-xs-12 col-sm-6 col-lg-4"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Facts At a Glance</h3> </div> <div class="panel-body"> <dl class="dl-horizontal"> <dt>Started</dt> <dd>3 Feb. 2013</dd> <dt>Major Stake Holder</dt> <dd>HK Fine Foods Inc.</dd> <dt>Last Year's Turnover</dt> <dd>$1,250,375</dd> <dt>Employees</dt> <dd>40</dd> </dl> </div> </div> </div> </div> <div class="row row-content" id="corporate"> <div class="col-xs-12"> <h2>Corporate Leadership</h2> <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingPeter"> <h3 class="panel-title"> <a role="button" data-toggle="collapse" data-parent="#accordion" href="#peter" aria-expanded="true" aria-controls="peter"> Peter Pan <small>Chief Epicurious Officer</small></a> </h3> </div> <div role="tabpanel" class="panel-collapse collapse in" id="peter" aria-labelledby="headingPeter"> <div class="panel-body"> <p>Our CEO, Peter, credits his hardworking East Asian immigrant parents who undertook the arduous journey to the shores of America with the intention of giving their children the best future. His mother's wizardy in the kitchen whipping up the tastiest dishes with whatever is available inexpensively at the supermarket, was his first inspiration to create the fusion cuisines for which <em>The Frying Pan</em> became well known. He brings his zeal for fusion cuisines to this restaurant, pioneering cross-cultural culinary connections.</p> </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingDanny"> <h3 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#danny" aria-expanded="false" aria-controls="danny"> Dhanasekaran Witherspoon <small>Chief Food Officer</small></a> </h3> </div> <div role="tabpanel" class="panel-collapse collapse" id="danny" aria-labelledby="headingDanny"> <div class="panel-body"> <p>Our CFO, Danny, as he is affectionately referred to by his colleagues, comes from a long established family tradition in farming and produce. His experiences growing up on a farm in the Australian outback gave him great appreciation for varieties of food sources. As he puts it in his own words, <em>Everything that runs, wins, and everything that stays, pays!</em></p> </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingAgumbe"> <h3 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#agumbe" aria-expanded="false" aria-controls="agumbe"> Agumbe Tang <small>Chief Taste Officer</small></a> </h3> </div> <div role="tabpanel" class="panel-collapse collapse" id="agumbe" aria-labelledby="headingAgumbe"> <div class="panel-body"> <p>Blessed with the most discerning gustatory sense, Agumbe, our CFO, personally ensures that every dish that we serve meets his exacting tastes. Our chefs dread the tongue lashing that ensues if their dish does not meet his exacting standards. He lives by his motto, <em>You click only if you survive my lick.</em></p> </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingAlberto"> <h3 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#alberto" aria-expanded="false" aria-controls="alberto"> Alberto Somayya <small>Executive Chef</small></a> </h3> </div> <div role="tabpanel" class="panel-collapse collapse" id="alberto" aria-labelledby="headingAlberto"> <div class="panel-body"> <p>Award winning three-star Michelin chef with wide International experience having worked closely with whos-who in the culinary world, he specializes in creating mouthwatering Indo-Italian fusion experiences. He says, <em>Put together the cuisines from the two craziest cultures, and you get a winning hit! Amma Mia!</em></p> </div> </div> </div> </div> </div> <div> <p style="padding:20px;"></p> </div> </div> <div class="row row-content" id="facts"> <div class="col-xs-12"> <h2>Facts &amp; Figures</h2> <div class="table-responsive"> <table class="table table-striped"> <tr> <td>&nbsp;</td> <th>2013</th> <th>2014</th> <th>2015</th> </tr> <tr> <th>Employees</th> <td>15</td> <td>30</td> <td>40</td> </tr> <tr> <th>Guests Served</th> <td>15000</td> <td>45000</td> <td>100,000</td> </tr> <tr> <th>Special Events</th> <td>3</td> <td>20</td> <td>45</td> </tr> <tr> <th>Annual Turnover</th> <td>$251,325</td> <td>$1,250,375</td> <td>~$3,000,000</td> </tr> </table> </div> </div> <div class="col-xs-12 col-sm-3"> <p style="padding:20px;"></p> </div> </div> </div> <footer class="row-footer"> <div class="container"> <div class="row"> <div class="col-xs-5 col-xs-offset-1 col-sm-2 col-sm-offset-1"> <h5>Links</h5> <ul class="list-unstyled"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Menu</a></li> <li><a href="#">Contact</a></li> </ul> </div> <div class="col-xs-6 col-sm-5"> <h5>Our Address</h5> <address> 121, Clear Water Bay Road<br> Clear Water Bay, Kowloon<br> HONG KONG<br> <i class="fa fa-phone"></i>: +852 1234 5678<br> <i class="fa fa-fax"></i>: +852 8765 4321<br> <i class="fa fa-envelope"></i>: <a href="mailto:[email protected]">[email protected]</a> </address> </div> <div class="col-xs-12 col-sm-4"> <div class="nav navbar-nav" style="padding: 40px 10px;"> <a class="btn btn-social-icon btn-google-plus" href="http://google.com/+"><i class="fa fa-google-plus"></i></a> <a class="btn btn-social-icon btn-facebook" href="http://www.facebook.com/profile.php?id="><i class="fa fa-facebook"></i></a> <a class="btn btn-social-icon btn-linkedin" href="http://www.linkedin.com/in/"><i class="fa fa-linkedin"></i></a> <a class="btn btn-social-icon btn-twitter" href="http://twitter.com/"><i class="fa fa-twitter"></i></a> <a class="btn btn-social-icon btn-youtube" href="http://youtube.com/"><i class="fa fa-youtube"></i></a> <a class="btn btn-social-icon" href="mailto:"><i class="fa fa-envelope-o"></i></a> </div> </div> <div class="col-xs-12"> <p style="padding:10px;"></p> <p align=center>© Copyright 2015 Ristorante Con Fusion</p> </div> </div> </div> </footer> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="bower_components/jquery/dist/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script> </div> <nav class="hidden-xs col-sm-2" id="myScrollspy"> <ul class="nav nav-pills nav-stacked" data-spy="affix" data-offset-top="400"> <li><a href="#history">Our History</a></li> <li><a href="#corporate">Corporate</a></li> <li><a href="#facts">Facts</a></li> </ul> </nav> </div> </body> </html>
{'content_hash': '5fc14e4e177bac0a424d6998db2ef459', 'timestamp': '', 'source': 'github', 'line_count': 313, 'max_line_length': 549, 'avg_line_length': 42.2555910543131, 'alnum_prop': 0.600635112656888, 'repo_name': 'djhvscf/Coursera', 'id': '872ef4097fec8809570c69e57de74b2b63452c87', 'size': '13227', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Front-End Web UI Frameworks and Tools/conFusion/aboutus.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '582738'}, {'name': 'HTML', 'bytes': '262096'}, {'name': 'JavaScript', 'bytes': '3232487'}]}
<?xml version="1.0" encoding="UTF-8"?> <Paragraph_ListItem xmlns="http://www.opentravel.org/OTM/Common/v2" formattedText="Formatted text example." language="en" listItem="1234" textFormat="PlainText"/>
{'content_hash': '7e4e82ef16e2134b4ef823ea5f81d380', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 67, 'avg_line_length': 52.5, 'alnum_prop': 0.719047619047619, 'repo_name': 'OpenTravel-Forum-2016/otaforum-mock-content', 'id': '9b9a870f0557d74a3ca36888e64afaa408ae00e3', 'size': '210', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'untitled folder/jljandrew_CompilerOutput/schemas/examples/Common_2_0_0/ParagraphListItem.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1143'}]}
package com.google.javascript.jscomp; import com.google.javascript.rhino.Node; /** * This interface defines how objects capable of creating scopes from the parse * tree behave. * * */ interface ScopeCreator { /** * Creates a {@link Scope} object. * * @param n the root node (either a FUNCTION node, a SCRIPT node, or a * synthetic block node whose children are all SCRIPT nodes) * @param parent the parent Scope object (may be null) */ Scope createScope(Node n, Scope parent); }
{'content_hash': 'e7e23c05d245c8cc0638ced313f0e87b', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 79, 'avg_line_length': 23.318181818181817, 'alnum_prop': 0.6920077972709552, 'repo_name': 'kencheung/js-symbolic-executor', 'id': 'a4d53379819a391cace20307d0b68e2201e49007', 'size': '1107', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'closure-compiler/src/com/google/javascript/jscomp/ScopeCreator.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '21321'}, {'name': 'C++', 'bytes': '4405546'}, {'name': 'Emacs Lisp', 'bytes': '27569'}, {'name': 'HTML', 'bytes': '1571'}, {'name': 'Java', 'bytes': '6917520'}, {'name': 'JavaScript', 'bytes': '726362'}, {'name': 'Lex', 'bytes': '28595'}, {'name': 'Makefile', 'bytes': '37617'}, {'name': 'OCaml', 'bytes': '7126'}, {'name': 'Protocol Buffer', 'bytes': '2100'}, {'name': 'Python', 'bytes': '46416'}, {'name': 'Shell', 'bytes': '13620'}, {'name': 'Standard ML', 'bytes': '2115'}, {'name': 'Yacc', 'bytes': '131032'}]}
<?xml version="1.0" ?><!DOCTYPE TS><TS language="id_ID" version="2.0"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Freshcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;Freshcoin Core&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../utilitydialog.cpp" line="+29"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The Freshcoin Core developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+30"/> <source>Double-click to edit address or label</source> <translation>Klik-ganda untuk mengubah alamat atau label</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Buat alamat baru</translation> </message> <message> <location line="+3"/> <source>&amp;New</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Salin alamat yang dipilih ke clipboard</translation> </message> <message> <location line="+3"/> <source>&amp;Copy</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>C&amp;lose</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+74"/> <source>&amp;Copy Address</source> <translation>&amp;Salin Alamat</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="-41"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-27"/> <source>&amp;Delete</source> <translation>&amp;Hapus</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-30"/> <source>Choose the address to send coins to</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Choose the address to receive coins with</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>C&amp;hoose</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Sending addresses</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Receiving addresses</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>These are your Freshcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>These are your Freshcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Label</source> <translation>Salin &amp;Label</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Ubah</translation> </message> <message> <location line="+194"/> <source>Export Address List</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>File CSV (*.csv)</translation> </message> <message> <location line="+13"/> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>There was an error trying to save the address list to %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+168"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Alamat</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(tidak ada label)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Dialog Kata kunci</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Masukkan kata kunci</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Kata kunci baru</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ulangi kata kunci baru</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+40"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Masukkan kata kunci baru ke dompet.&lt;br/&gt;Mohon gunakan kata kunci dengan &lt;b&gt;10 karakter atau lebih dengan acak&lt;/b&gt;, atau &lt;b&gt;delapan kata atau lebih&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Enkripsi dompet</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Operasi ini memerlukan kata kunci dompet Anda untuk membuka dompet ini.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Buka dompet</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Operasi ini memerlukan kata kunci dompet Anda untuk mendekripsi dompet ini.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dekripsi dompet</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Ubah kata kunci</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Masukkan kata kunci lama dan baru ke dompet ini.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Konfirmasi enkripsi dompet</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 FRSHCOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </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 type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Dompet terenkripsi</translation> </message> <message> <location line="-56"/> <source>Freshcoin Core will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Freshcoins from being stolen by malware infecting your computer.</source> <translation>Freshcoin akan menutup untuk menyelesaikan proses enkripsi. Ingat bahwa dengan mengenkripsi dompet Anda tidak sepenuhnya melindungi freshcoin Anda dari perangkat lunak berbahaya yang menginfeksi komputer Anda.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Enkripsi dompet gagal</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Enkripsi dompet gagal karena kesalahan internal. Dompet Anda tidak dienkripsi.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Kata kunci yang dimasukkan tidak cocok.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Gagal buka dompet</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Kata kunci yang dimasukkan untuk dekripsi dompet tidak cocok.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Dekripsi dompet gagal</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+295"/> <source>Sign &amp;message...</source> <translation>Pesan &amp;penanda...</translation> </message> <message> <location line="+335"/> <source>Synchronizing with network...</source> <translation>Sinkronisasi dengan jaringan...</translation> </message> <message> <location line="-407"/> <source>&amp;Overview</source> <translation>&amp;Kilasan</translation> </message> <message> <location line="-137"/> <source>Node</source> <translation type="unfinished"/> </message> <message> <location line="+138"/> <source>Show general overview of wallet</source> <translation>Tampilkan kilasan umum dari dompet</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transaksi</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Jelajah sejarah transaksi</translation> </message> <message> <location line="+17"/> <source>E&amp;xit</source> <translation>K&amp;eluar</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Keluar dari aplikasi</translation> </message> <message> <location line="+7"/> <source>Show information about Freshcoin Core</source> <translation>Tampilkan informasi mengenai Freshcoin</translation> </message> <message> <location line="+3"/> <location line="+2"/> <source>About &amp;Qt</source> <translation>Mengenai &amp;Qt</translation> </message> <message> <location line="+2"/> <source>Show information about Qt</source> <translation>Tampilkan informasi mengenai Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Pilihan...</translation> </message> <message> <location line="+9"/> <source>&amp;Encrypt Wallet...</source> <translation>%Enkripsi Dompet...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Cadangkan Dompet...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Ubah Kata Kunci...</translation> </message> <message> <location line="+10"/> <source>&amp;sending addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;receiving addresses...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Open &amp;URI...</source> <translation type="unfinished"/> </message> <message> <location line="+325"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Mengindex ulang block di harddisk...</translation> </message> <message> <location line="-405"/> <source>Send coins to a Freshcoin address</source> <translation>Kirim koin ke alamat Freshcoin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Freshcoin Core</source> <translation>Ubah pilihan konfigurasi untuk Freshcoin</translation> </message> <message> <location line="+12"/> <source>Backup wallet to another location</source> <translation>Cadangkan dompet ke lokasi lain</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Ubah kata kunci yang digunakan untuk enkripsi dompet</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Jendela Debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Buka konsol debug dan diagnosa</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verifikasi pesan...</translation> </message> <message> <location line="+430"/> <source>Freshcoin</source> <translation type="unfinished"/> </message> <message> <location line="-643"/> <source>Wallet</source> <translation>Dompet</translation> </message> <message> <location line="+146"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <location line="+2"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Freshcoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Freshcoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>&amp;File</source> <translation>&amp;Berkas</translation> </message> <message> <location line="+14"/> <source>&amp;Settings</source> <translation>&amp;Pengaturan</translation> </message> <message> <location line="+9"/> <source>&amp;Help</source> <translation>&amp;Bantuan</translation> </message> <message> <location line="+15"/> <source>Tabs toolbar</source> <translation>Baris tab</translation> </message> <message> <location line="-284"/> <location line="+376"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="-401"/> <source>Freshcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+163"/> <source>Request payments (generates QR codes and freshcoin: URIs)</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <location line="+2"/> <source>&amp;About Freshcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Show the list of used sending addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Show the list of used receiving addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Open a freshcoin: URI or payment request</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the Freshcoin Core help message to get a list with possible Freshcoin Core command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+159"/> <location line="+5"/> <source>Freshcoin client</source> <translation>Klien Freshcoin</translation> </message> <message numerus="yes"> <location line="+142"/> <source>%n active connection(s) to Freshcoin network</source> <translation><numerusform>%n hubungan aktif ke jaringan Freshcoin</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+23"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <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="+27"/> <source>Error</source> <translation>Gagal</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Peringatan</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informasi</translation> </message> <message> <location line="-85"/> <source>Up to date</source> <translation>Terbaru</translation> </message> <message> <location line="+34"/> <source>Catching up...</source> <translation>Menyusul...</translation> </message> <message> <location line="+130"/> <source>Sent transaction</source> <translation>Transaksi terkirim</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Transaksi diterima</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Tanggal: %1 Jumlah: %2 Jenis: %3 Alamat: %4 </translation> </message> <message> <location line="+69"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Dompet saat ini &lt;b&gt;terenkripsi&lt;/b&gt; dan &lt;b&gt;terbuka&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>Dompet saat ini &lt;b&gt;terenkripsi&lt;/b&gt; dan &lt;b&gt;terkunci&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+438"/> <source>A fatal error occurred. Freshcoin Core 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>Notifikasi Jaringan</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control Address Selection</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount:</source> <translation>Jumlah:</translation> </message> <message> <location line="+29"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+63"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>Amount</source> <translation>Jumlah</translation> </message> <message> <location line="+10"/> <source>Address</source> <translation>Alamat</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Tanggal</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Terkonfirmasi</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+42"/> <source>Copy address</source> <translation>Salin alamat</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Salin label</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Salin jumlah</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock unspent</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Unlock unspent</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+323"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>higher</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lower</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>(%1 locked)</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>none</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Dust</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is greater than 1000 bytes.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+5"/> <source>This means a fee of at least %1 per kB is required.</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>Can vary +/- 1 byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions with higher priority are more likely to get included into a block.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the priority is smaller than &quot;medium&quot;.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This label turns red, if any recipient receives an amount smaller than %1.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+4"/> <source>This means a fee of at least %1 is required.</source> <translation type="unfinished"/> </message> <message> <location line="-3"/> <source>Amounts below 0.546 times the minimum relay fee are shown as dust.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>This label turns red, if the change is smaller than %1.</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <location line="+66"/> <source>(no label)</source> <translation>(tidak ada label)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Ubah Alamat</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Label</translation> </message> <message> <location line="+10"/> <source>The label associated with this address list entry</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>&amp;Address</source> <translation>&amp;Alamat</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+28"/> <source>New receiving address</source> <translation>Alamat menerima baru</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Alamat mengirim baru</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Ubah alamat menerima</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Ubah alamat mengirim</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Alamat yang dimasukkan &quot;%1&quot; sudah ada di dalam buku alamat.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Freshcoin address.</source> <translation>Alamat yang dimasukkan &quot;%1&quot; bukan alamat Freshcoin yang benar.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Tidak dapat membuka dompet.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Pembuatan kunci baru gagal.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <location filename="../intro.cpp" line="+65"/> <source>A new data directory will be created.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>name</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Path already exists, and is not a directory.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Cannot create data directory here.</source> <translation type="unfinished"/> </message> </context> <context> <name>HelpMessageDialog</name> <message> <location filename="../forms/helpmessagedialog.ui" line="+19"/> <source>Freshcoin Core - Command-line options</source> <translation type="unfinished"/> </message> <message> <location filename="../utilitydialog.cpp" line="+38"/> <source>Freshcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>version</source> <translation>versi</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Penggunaan:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>pilihan perintah-baris</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>pilihan UI</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Atur bahasa, sebagai contoh &quot;id_ID&quot; (standar: system locale)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Memulai terminimalisi</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Tampilkan layar pembuka saat nyala (standar: 1)</translation> </message> <message> <location line="+1"/> <source>Choose data directory on startup (default: 0)</source> <translation type="unfinished"/> </message> </context> <context> <name>Intro</name> <message> <location filename="../forms/intro.ui" line="+14"/> <source>Welcome</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Welcome to Freshcoin Core.</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>As this is the first time the program is launched, you can choose where Freshcoin Core will store its data.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Freshcoin Core will download and store a copy of the Freshcoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Use the default data directory</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use a custom data directory:</source> <translation type="unfinished"/> </message> <message> <location filename="../intro.cpp" line="+85"/> <source>Freshcoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Error</source> <translation>Gagal</translation> </message> <message> <location line="+9"/> <source>GB of free space available</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>(of %1GB needed)</source> <translation type="unfinished"/> </message> </context> <context> <name>OpenURIDialog</name> <message> <location filename="../forms/openuridialog.ui" line="+14"/> <source>Open URI</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Open payment request from URI or file</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>URI:</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Select payment request file</source> <translation type="unfinished"/> </message> <message> <location filename="../openuridialog.cpp" line="+47"/> <source>Select payment request file to open</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Pilihan</translation> </message> <message> <location line="+13"/> <source>&amp;Main</source> <translation>&amp;Utama</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.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Bayar &amp;biaya transaksi</translation> </message> <message> <location line="+31"/> <source>Automatically start Freshcoin Core after logging in to the system.</source> <translation>Menyalakan Freshcoin secara otomatis setelah masuk ke dalam sistem.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Freshcoin Core on system login</source> <translation>&amp;Menyalakan Freshcoin pada login sistem</translation> </message> <message> <location line="+9"/> <source>Size of &amp;database cache</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Atur ukuran tembolok dalam megabyte (standar: 25)</translation> </message> <message> <location line="+13"/> <source>MB</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Number of script &amp;verification threads</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+58"/> <source>Connect to the Freshcoin network through a SOCKS proxy.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy (default proxy):</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation type="unfinished"/> </message> <message> <location line="+224"/> <source>Active command-line options that override above options:</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="-323"/> <source>&amp;Network</source> <translation>&amp;Jaringan</translation> </message> <message> <location line="+6"/> <source>Automatically open the Freshcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Otomatis membuka port client Freshcoin di router. Hanya berjalan apabila router anda mendukung UPnP dan di-enable.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Petakan port dengan &amp;UPnP</translation> </message> <message> <location line="+19"/> <source>Proxy &amp;IP:</source> <translation>IP Proxy:</translation> </message> <message> <location line="+32"/> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <location line="+25"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Port proxy (cth. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>Versi &amp;SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versi SOCKS proxy (cth. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Jendela</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Hanya tampilkan ikon tray setelah meminilisasi jendela</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Meminilisasi ke tray daripada taskbar</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 type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;eminilisasi saat tutup</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Tampilan</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Bahasa Antarmuka Pengguna:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Freshcoin Core.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unit untuk menunjukkan jumlah:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Freshcoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Tampilkan alamat dalam daftar transaksi</translation> </message> <message> <location line="+7"/> <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="+136"/> <source>&amp;OK</source> <translation>&amp;YA</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Batal</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+67"/> <source>default</source> <translation>standar</translation> </message> <message> <location line="+57"/> <source>none</source> <translation type="unfinished"/> </message> <message> <location line="+75"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+29"/> <source>Client restart required to activate changes.</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Client will be shutdown, do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>This change would require a client restart.</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The supplied proxy address is invalid.</source> <translation>Alamat proxy yang diisi tidak valid.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formulir</translation> </message> <message> <location line="+50"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Freshcoin network after a connection is established, but this process has not completed yet.</source> <translation>Informasi terlampir mungkin sudah kedaluwarsa. Dompet Anda secara otomatis mensinkronisasi dengan jaringan Freshcoin ketika sebuah hubungan terbentuk, namun proses ini belum selesai.</translation> </message> <message> <location line="-155"/> <source>Unconfirmed:</source> <translation>Tidak terkonfirmasi:</translation> </message> <message> <location line="-83"/> <source>Wallet</source> <translation>Dompet</translation> </message> <message> <location line="+51"/> <source>Confirmed:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transaksi sebelumnya&lt;/b&gt;</translation> </message> <message> <location filename="../overviewpage.cpp" line="+120"/> <location line="+1"/> <source>out of sync</source> <translation>tidak tersinkron</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+403"/> <location line="+13"/> <source>URI handling</source> <translation>Penanganan URI</translation> </message> <message> <location line="+1"/> <source>URI can not be parsed! This can be caused by an invalid Freshcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+96"/> <source>Requested payment amount of %1 is too small (considered dust).</source> <translation type="unfinished"/> </message> <message> <location line="-221"/> <location line="+212"/> <location line="+13"/> <location line="+95"/> <location line="+18"/> <location line="+16"/> <source>Payment request error</source> <translation type="unfinished"/> </message> <message> <location line="-353"/> <source>Cannot start freshcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> <message> <location line="+58"/> <source>Net manager warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Your active proxy doesn&apos;t support SOCKS5, which is required for payment requests via proxy.</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>Payment request fetch URL is invalid: %1</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Payment request file handling</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Payment request file can not be read or processed! This can be caused by an invalid payment request file.</source> <translation type="unfinished"/> </message> <message> <location line="+73"/> <source>Unverified payment requests to custom payment scripts are unsupported.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Refund from %1</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Error communicating with %1: %2</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Payment request can not be parsed or processed!</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Bad response from server %1</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Payment acknowledged</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Network request error</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <location filename="../bitcoin.cpp" line="+71"/> <location line="+11"/> <source>Freshcoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Error: Invalid combination of -regtest and -testnet.</source> <translation type="unfinished"/> </message> </context> <context> <name>QRImageWidget</name> <message> <location filename="../receiverequestdialog.cpp" line="+36"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Copy Image</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Save QR Code</source> <translation>Simpan Kode QR</translation> </message> <message> <location line="+0"/> <source>PNG Image (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nama Klien</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+23"/> <location line="+36"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+359"/> <source>N/A</source> <translation>T/S</translation> </message> <message> <location line="-223"/> <source>Client version</source> <translation>Versi Klien</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informasi</translation> </message> <message> <location line="-10"/> <source>Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>General</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Waktu nyala</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Jaringan</translation> </message> <message> <location line="+7"/> <source>Name</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Number of connections</source> <translation>Jumlah hubungan</translation> </message> <message> <location line="+29"/> <source>Block chain</source> <translation>Rantai blok</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Jumlah blok terkini</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Perkiraan blok total</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Waktu blok terakhir</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Buka</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsol</translation> </message> <message> <location line="+72"/> <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"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-521"/> <source>Build date</source> <translation>Tanggal pembuatan</translation> </message> <message> <location line="+206"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Freshcoin Core 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="+76"/> <source>Clear console</source> <translation>Bersihkan konsol</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Freshcoin Core RPC console.</source> <translation>Selamat datang ke konsol RPC Freshcoin.</translation> </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>Gunakan panah keatas dan kebawah untuk menampilkan sejarah, dan &lt;b&gt;Ctrl-L&lt;/b&gt; untuk bersihkan layar.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Ketik &lt;b&gt;help&lt;/b&gt; untuk menampilkan perintah tersedia.</translation> </message> <message> <location line="+122"/> <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>ReceiveCoinsDialog</name> <message> <location filename="../forms/receivecoinsdialog.ui" line="+83"/> <source>&amp;Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Label:</source> <translation>&amp;Label:</translation> </message> <message> <location line="-34"/> <source>&amp;Message:</source> <translation type="unfinished"/> </message> <message> <location line="-17"/> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>An optional label to associate with the new receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Freshcoin network.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Request payment</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Requested payments</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Show the selected request (does the same as double clicking an entry)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Show</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Remove the selected entries from the list</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Remove</source> <translation type="unfinished"/> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <location filename="../forms/receiverequestdialog.ui" line="+29"/> <source>QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Copy &amp;URI</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Copy &amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Save Image...</source> <translation type="unfinished"/> </message> <message> <location filename="../receiverequestdialog.cpp" line="+56"/> <source>Request payment to %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Payment information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>URI</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Address</source> <translation>Alamat</translation> </message> <message> <location line="+2"/> <source>Amount</source> <translation>Jumlah</translation> </message> <message> <location line="+2"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+2"/> <source>Message</source> <translation>Pesan</translation> </message> <message> <location line="+10"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Hasil URI terlalu panjang, coba kurangi label / pesan.</translation> </message> <message> <location line="+5"/> <source>Error encoding URI into QR Code.</source> <translation>Gagal mengubah URI ke kode QR.</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <location filename="../recentrequeststablemodel.cpp" line="+24"/> <source>Date</source> <translation>Tanggal</translation> </message> <message> <location line="+0"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+0"/> <source>Message</source> <translation>Pesan:</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Jumlah</translation> </message> <message> <location line="+38"/> <source>(no label)</source> <translation>(tidak ada label)</translation> </message> <message> <location line="+9"/> <source>(no message)</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+381"/> <location line="+80"/> <source>Send Coins</source> <translation>Kirim Koin</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="+89"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Jumlah:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+115"/> <source>Send to multiple recipients at once</source> <translation>Kirim ke beberapa penerima sekaligus</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Clear all fields of the form.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Hapus %Semua</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+41"/> <source>Confirm the send action</source> <translation>Konfirmasi aksi pengiriman</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-228"/> <source>Confirm send coins</source> <translation>Konfirmasi pengiriman koin</translation> </message> <message> <location line="-74"/> <location line="+5"/> <location line="+5"/> <location line="+4"/> <source>%1 to %2</source> <translation>%1 ke %2</translation> </message> <message> <location line="-136"/> <source>Enter a Freshcoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Masukkan alamat Freshcoin (cth. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Salin jumlah</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+170"/> <source>Total Amount %1 (= %2)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>or</source> <translation type="unfinished"/> </message> <message> <location line="+202"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>The amount to pay must be larger than 0.</source> <translation>Jumlah yang dibayar harus lebih besar dari 0.</translation> </message> <message> <location line="+3"/> <source>The amount exceeds your balance.</source> <translation>Jumlah melebihi saldo Anda.</translation> </message> <message> <location line="+3"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Kelebihan total saldo Anda ketika biaya transaksi %1 ditambahkan.</translation> </message> <message> <location line="+3"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Ditemukan alamat ganda, hanya dapat mengirim ke tiap alamat sekali per operasi pengiriman.</translation> </message> <message> <location line="+3"/> <source>Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>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="+112"/> <source>Warning: Invalid Freshcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>(no label)</source> <translation>(tidak ada label)</translation> </message> <message> <location line="-11"/> <source>Warning: Unknown change address</source> <translation type="unfinished"/> </message> <message> <location line="-366"/> <source>Are you sure you want to send?</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>added as transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+170"/> <source>Payment request expired</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Invalid payment address %1</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+131"/> <location line="+521"/> <location line="+536"/> <source>A&amp;mount:</source> <translation>J&amp;umlah:</translation> </message> <message> <location line="-1152"/> <source>Pay &amp;To:</source> <translation>Kirim &amp;Ke:</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+30"/> <source>Enter a label for this address to add it to your address book</source> <translation>Masukkan label bagi alamat ini untuk menambahkannya ke buku alamat Anda</translation> </message> <message> <location filename="../forms/sendcoinsentry.ui" line="+57"/> <source>&amp;Label:</source> <translation>&amp;Label:</translation> </message> <message> <location line="-50"/> <source>Choose previously used address</source> <translation>Pilih alamat yang telah digunakan sebelumnya</translation> </message> <message> <location line="-40"/> <source>This is a normal payment.</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Alt+A</source> <translation>Alt+J</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Tempel alamat dari salinan</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+B</translation> </message> <message> <location line="+7"/> <location line="+524"/> <location line="+536"/> <source>Remove this entry</source> <translation type="unfinished"/> </message> <message> <location line="-1008"/> <source>Message:</source> <translation>Pesan:</translation> </message> <message> <location line="+10"/> <source>A message that was attached to the Freshcoin URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Freshcoin network.</source> <translation type="unfinished"/> </message> <message> <location line="+958"/> <source>This is a verified payment request.</source> <translation type="unfinished"/> </message> <message> <location line="-991"/> <source>Enter a label for this address to add it to the list of used addresses</source> <translation type="unfinished"/> </message> <message> <location line="+459"/> <source>This is an unverified payment request.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <location line="+532"/> <source>Pay To:</source> <translation type="unfinished"/> </message> <message> <location line="-498"/> <location line="+536"/> <source>Memo:</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Freshcoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Masukkan alamat Freshcoin (cth. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <location filename="../utilitydialog.cpp" line="+48"/> <source>Freshcoin Core is shutting down...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do not shut down the computer until this window disappears.</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 type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <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 type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose previously used address</source> <translation>Pilih alamat yang telah digunakan sebelumnya</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+J</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Tempel alamat dari salinan</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+B</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Freshcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Hapus %Semua</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <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 type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Freshcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+29"/> <location line="+3"/> <source>Enter a Freshcoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source> <translation>Masukkan alamat Freshcoin (cth. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Freshcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+84"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Alamat yang dimasukkan tidak sesuai.</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>Silahkan periksa alamat dan coba lagi.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+28"/> <source>Freshcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>The Freshcoin Core developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+79"/> <source>KB/s</source> <translation>KB/s</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+28"/> <source>Open until %1</source> <translation>Buka hingga %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/tidak terkonfirmasi</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 konfirmasi</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Tanggal</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Dari</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Untuk</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+53"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-125"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+53"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <location line="+9"/> <source>Message</source> <translation>Pesan:</translation> </message> <message> <location line="-7"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Merchant</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Generated coins must mature %1 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="+8"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transaksi</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Jumlah</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-232"/> <source>, has not been successfully broadcast yet</source> <translation>, belum berhasil disiarkan</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>tidak diketahui</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Rincian transaksi</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Jendela ini menampilkan deskripsi rinci dari transaksi tersebut</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+234"/> <source>Date</source> <translation>Tanggal</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Jenis</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Alamat</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Jumlah</translation> </message> <message> <location line="+59"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+16"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Buka hingga %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 konfirmasi)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Tidak terkonfirmasi (%1 dari %2 konfirmasi)</translation> </message> <message> <location line="-22"/> <location line="+25"/> <source>Confirmed (%1 confirmations)</source> <translation>Terkonfirmasi (%1 konfirmasi)</translation> </message> <message> <location line="-22"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Blok ini tidak diterima oleh node lainnya dan kemungkinan tidak akan diterima!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Terbuat tetapi tidak diterima</translation> </message> <message> <location line="+62"/> <source>Received with</source> <translation>Diterima dengan</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Diterima dari</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Terkirim ke</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pembayaran ke Anda sendiri</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Tertambang</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(t/s)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Status transaksi. Arahkan ke bagian ini untuk menampilkan jumlah konfrimasi.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Tanggal dan waktu transaksi tersebut diterima.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Jenis transaksi.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Alamat tujuan dari transaksi.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Jumlah terbuang dari atau ditambahkan ke saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+57"/> <location line="+16"/> <source>All</source> <translation>Semua</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Hari ini</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Minggu ini</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Bulan ini</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Bulan kemarin</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Tahun ini</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Jarak...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>DIterima dengan</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Terkirim ke</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Ke Anda sendiri</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Ditambang</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Lainnya</translation> </message> <message> <location line="+6"/> <source>Enter address or label to search</source> <translation>Masukkan alamat atau label untuk mencari</translation> </message> <message> <location line="+6"/> <source>Min amount</source> <translation>Jumlah min</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Salin alamat</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Salin label</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Salin jumlah</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Ubah label</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Tampilkan rincian transaksi</translation> </message> <message> <location line="+142"/> <source>Export Transaction History</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Exporting Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the transaction history to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Exporting Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The transaction history was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <location line="-22"/> <source>Comma separated file (*.csv)</source> <translation>Berkas CSV (*.csv)</translation> </message> <message> <location line="+9"/> <source>Confirmed</source> <translation>Terkonfirmasi</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Tanggal</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Jenis</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Label</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Alamat</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Jumlah</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+107"/> <source>Range:</source> <translation>Jarak:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>ke</translation> </message> </context> <context> <name>WalletFrame</name> <message> <location filename="../walletframe.cpp" line="+26"/> <source>No wallet has been loaded.</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+245"/> <source>Send Coins</source> <translation>Kirim Koin</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+43"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+181"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>The wallet data was successfully saved to %1.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> </context> <context> <name>freshcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+221"/> <source>Usage:</source> <translation>Penggunaan:</translation> </message> <message> <location line="-54"/> <source>List commands</source> <translation>Daftar perintah</translation> </message> <message> <location line="-14"/> <source>Get help for a command</source> <translation>Dapatkan bantuan untuk perintah</translation> </message> <message> <location line="+26"/> <source>Options:</source> <translation>Pilihan:</translation> </message> <message> <location line="+22"/> <source>Specify configuration file (default: freshcoin.conf)</source> <translation>Tentukan berkas konfigurasi (standar: freshcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: freshcoind.pid)</source> <translation>Tentukan berkas pid (standar: freshcoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Tentukan direktori data</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Atur ukuran tembolok dalam megabyte (standar: 25)</translation> </message> <message> <location line="-26"/> <source>Listen for connections on &lt;port&gt; (default: 22556 or testnet: 44556)</source> <translation>Menerima hubungan pada &lt;port&gt; (standar: 22556 atau testnet: 44556)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Mengatur hubungan paling banyak &lt;n&gt; ke peer (standar: 125)</translation> </message> <message> <location line="-51"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Hubungkan ke node untuk menerima alamat peer, dan putuskan</translation> </message> <message> <location line="+84"/> <source>Specify your own public address</source> <translation>Tentukan alamat publik Anda sendiri</translation> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Batas untuk memutuskan peer buruk (standar: 100)</translation> </message> <message> <location line="-148"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Jumlah kedua untuk menjaga peer buruk dari hubung-ulang (standar: 86400)</translation> </message> <message> <location line="-36"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 22555 or testnet: 44555)</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Accept command line and JSON-RPC commands</source> <translation>Menerima perintah baris perintah dan JSON-RPC</translation> </message> <message> <location line="+80"/> <source>Run in the background as a daemon and accept commands</source> <translation>Berjalan dibelakang sebagai daemin dan menerima perintah</translation> </message> <message> <location line="+39"/> <source>Use the test network</source> <translation>Gunakan jaringan uji</translation> </message> <message> <location line="-118"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=freshcoinrpc 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;Freshcoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Freshcoin Core is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <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="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <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="+4"/> <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="+6"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <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="+5"/> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Freshcoin Core will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <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 type="unfinished"/> </message> <message> <location line="+9"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Freshcoin Core Daemon</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Freshcoin Core RPC client version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Connect through SOCKS proxy</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Connect to JSON-RPC on &lt;port&gt; (default: 22555 or testnet: 44555)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do not load the wallet and disable wallet RPC calls</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Error: system error:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Fee per kB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -onion address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Prepend debug output with timestamp (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>RPC client options:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Select SOCKS version for -proxy (4 or 5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to Freshcoin Core server</source> <translation>Kirim perintah ke Freshcoin server</translation> </message> <message> <location line="+7"/> <source>Set maximum block size in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Start Freshcoin Core server</source> <translation>Mulai Freshcoin server</translation> </message> <message> <location line="+3"/> <source>This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Usage (deprecated, use freshcoin-cli):</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet %s resides outside data directory %s</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Wallet options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="-79"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-105"/> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+89"/> <source>Information</source> <translation>Informasi</translation> </message> <message> <location line="+4"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Kirim info lacak/debug ke konsol sebaliknya dari berkas debug.log</translation> </message> <message> <location line="+6"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Nama pengguna untuk hubungan JSON-RPC</translation> </message> <message> <location line="+7"/> <source>Warning</source> <translation>Peringatan</translation> </message> <message> <location line="+2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>version</source> <translation>versi</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>Password for JSON-RPC connections</source> <translation>Kata sandi untuk hubungan JSON-RPC</translation> </message> <message> <location line="-70"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Izinkan hubungan JSON-RPC dari alamat IP yang ditentukan</translation> </message> <message> <location line="+80"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Kirim perintah ke node berjalan pada &lt;ip&gt; (standar: 127.0.0.1)</translation> </message> <message> <location line="-132"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Menjalankan perintah ketika perubahan blok terbaik (%s dalam cmd digantikan oleh hash blok)</translation> </message> <message> <location line="+161"/> <source>Upgrade wallet to latest format</source> <translation>Perbarui dompet ke format terbaru</translation> </message> <message> <location line="-24"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Kirim ukuran kolam kunci ke &lt;n&gt; (standar: 100)</translation> </message> <message> <location line="-11"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Pindai ulang rantai-blok untuk transaksi dompet yang hilang</translation> </message> <message> <location line="+38"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Gunakan OpenSSL (https) untuk hubungan JSON-RPC</translation> </message> <message> <location line="-30"/> <source>Server certificate file (default: server.cert)</source> <translation>Berkas sertifikat server (standar: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Kunci pribadi server (standar: server.pem)</translation> </message> <message> <location line="+16"/> <source>This help message</source> <translation>Pesan bantuan ini</translation> </message> <message> <location line="+7"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Tidak dapat mengikat ke %s dengan komputer ini (ikatan gagal %d, %s)</translation> </message> <message> <location line="-107"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Izinkan peninjauan DNS untuk -addnote, -seednode dan -connect</translation> </message> <message> <location line="+60"/> <source>Loading addresses...</source> <translation>Memuat alamat...</translation> </message> <message> <location line="-37"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Gagal memuat wallet.dat: Dompet rusak</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Freshcoin Core</source> <translation>Gagal memuat wallet.dat: Dompet memerlukan versi Freshcoin yang terbaru</translation> </message> <message> <location line="+98"/> <source>Wallet needed to be rewritten: restart Freshcoin Core to complete</source> <translation>Dompet diperlukan untuk disimpan-ulang: nyala-ulangkan Freshcoin untuk menyelesaikan</translation> </message> <message> <location line="-100"/> <source>Error loading wallet.dat</source> <translation>Gagal memuat wallet.dat</translation> </message> <message> <location line="+31"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Alamat -proxy salah: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Jaringan tidak diketahui yang ditentukan dalam -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Diminta versi proxy -socks tidak diketahui: %i</translation> </message> <message> <location line="-101"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Tidak dapat menyelesaikan alamat -bind: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Tidak dapat menyelesaikan alamat -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+48"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Jumlah salah untuk -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Jumlah salah</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Saldo tidak mencukupi</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Memuat indeks blok...</translation> </message> <message> <location line="-62"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Tambahkan node untuk dihubungkan dan upaya untuk menjaga hubungan tetap terbuka</translation> </message> <message> <location line="-32"/> <source>Unable to bind to %s on this computer. Freshcoin Core is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+95"/> <source>Loading wallet...</source> <translation>Memuat dompet...</translation> </message> <message> <location line="-56"/> <source>Cannot downgrade wallet</source> <translation>Tidak dapat menurunkan versi dompet</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Tidak dapat menyimpan alamat standar</translation> </message> <message> <location line="+67"/> <source>Rescanning...</source> <translation>Memindai ulang...</translation> </message> <message> <location line="-58"/> <source>Done loading</source> <translation>Memuat selesai</translation> </message> <message> <location line="+85"/> <source>To use the %s option</source> <translation>Gunakan pilihan %s</translation> </message> <message> <location line="-77"/> <source>Error</source> <translation>Gagal</translation> </message> <message> <location line="-35"/> <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>Anda harus mengatur rpcpassword=&lt;kata sandi&gt; dalam berkas konfigurasi: %s Jika berkas tidak ada, buatlah dengan permisi berkas hanya-dapat-dibaca-oleh-pemilik.</translation> </message> </context> </TS>
{'content_hash': 'a8f5bfb0b4385bc55bc3f64f8c7936aa', 'timestamp': '', 'source': 'github', 'line_count': 4026, 'max_line_length': 394, 'avg_line_length': 34.30774962742176, 'alnum_prop': 0.5982928259594709, 'repo_name': 'savale/freshcoin', 'id': '3fad7d60ce8baccac1ab512c8fc72768d9cf95e6', 'size': '138123', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/qt/locale/bitcoin_id_ID.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '399214'}, {'name': 'C++', 'bytes': '2928674'}, {'name': 'CSS', 'bytes': '1127'}, {'name': 'Objective-C++', 'bytes': '6262'}, {'name': 'Python', 'bytes': '95476'}, {'name': 'Shell', 'bytes': '40770'}, {'name': 'TypeScript', 'bytes': '10331235'}]}
package org.jsmiparser.phase.xref; import org.jsmiparser.smi.SmiConstants; import org.jsmiparser.smi.SmiRange; import org.jsmiparser.smi.SmiType; import org.jsmiparser.util.pair.StringIntPair; import org.jsmiparser.util.token.BigIntegerToken; import java.util.ArrayList; import java.util.List; public class SNMPv2_SMISymbolDefiner extends AbstractSymbolDefiner { protected SNMPv2_SMISymbolDefiner() { super("SNMPv2-SMI"); } @Override protected void defineSymbols() { super.defineSymbols(); addOrgOid(); addDodOid(); addInternetOid(); addDirectoryOid(); addMgmtOid(); addMib2Oid(); addTransmissionOid(); addExperimentalOid(); addPrivateOid(); addEnterprisesOid(); addSnmpV2Oid(); addSnmpDomainsOid(); addSnmpProxysOid(); addSnmpModulesOid(); addExtUTCTimeType(); addModuleIdentityMacro(); addObjectIdentityMacro(); addObjectNameType(); addNotificationNameType(); addObjectSyntaxType(); addSimpleSyntaxType(); addInteger32Type(); addApplicationSyntaxType(); addNetworkAddressType(); addIpAddressType(); addCounter32Type(); addGauge32Type(); addTimeTicksType(); addOpaqueType(); addCounter64Type(); addObjectTypeMacro(); addNotificationTypeMacro(); addZeroDotZeroObjectIdentity(); } private void addSnmpV2Oid() { addOid("snmpV2", new StringIntPair("internet"), new StringIntPair(6)); } private void addSnmpDomainsOid() { addOid("snmpDomains", new StringIntPair("snmpV2"), new StringIntPair(1)); } private void addSnmpProxysOid() { addOid("snmpProxys", new StringIntPair("snmpV2"), new StringIntPair(2)); } private void addSnmpModulesOid() { addOid("snmpModules", new StringIntPair("snmpV2"), new StringIntPair(3)); } private void addExtUTCTimeType() { if (isMissing("ExtUTCTime")) { SmiType type = new SmiType(idt("ExtUTCTime"), m_module); type.setBaseType(SmiConstants.OCTET_STRING_TYPE); List<SmiRange> constraints = new ArrayList<SmiRange>(); constraints.add(new SmiRange(new BigIntegerToken(11))); constraints.add(new SmiRange(new BigIntegerToken(13))); type.setSizeConstraints(constraints); m_module.addSymbol(type); } } private void addModuleIdentityMacro() { addMacro("MODULE-IDENTITY"); } private void addObjectIdentityMacro() { addMacro("OBJECT-IDENTITY"); } private void addNotificationTypeMacro() { addMacro("NOTIFICATION-TYPE"); } private void addZeroDotZeroObjectIdentity() { // TODO this should be SmiObjectIdentity addOid("zeroDotZero", new StringIntPair(0), new StringIntPair(0)); } }
{'content_hash': '8919bba58d1b3f801b34ac307c337a6f', 'timestamp': '', 'source': 'github', 'line_count': 118, 'max_line_length': 81, 'avg_line_length': 25.203389830508474, 'alnum_prop': 0.6375252185608608, 'repo_name': 'gallenliu/smiparser', 'id': '6f835d95b7588fda8df47a149d6f3ce10cbefe74', 'size': '3594', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'smiparser/src/main/java/org/jsmiparser/phase/xref/SNMPv2_SMISymbolDefiner.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GAP', 'bytes': '115774'}, {'name': 'Java', 'bytes': '324150'}, {'name': 'Shell', 'bytes': '146'}]}
platform_is :windows do require 'win32ole' describe 'WIN32OLE_TYPE#ole_methods for Shell Controls' do before :each do @ole_type = WIN32OLE_TYPE.new("Microsoft Shell Controls And Automation", "Shell") end after :each do @ole_type = nil end it 'returns an Integer' do @ole_type.ole_methods.all? { |m| m.kind_of? WIN32OLE_METHOD }.should be_true end end end
{'content_hash': '51ac20fba7ad7b5dc7cb7f913d631646', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 87, 'avg_line_length': 22.555555555555557, 'alnum_prop': 0.6551724137931034, 'repo_name': 'calavera/rubyspec', 'id': '3451e29f87aefd793821df51306c90f7285a75c7', 'size': '406', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'library/win32ole/win32ole_type/ole_methods_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '123874'}, {'name': 'Ruby', 'bytes': '4391858'}]}
title: Telerik.Web.UI.PivotGridConfigurationPanelLayoutType description: Telerik.Web.UI.PivotGridConfigurationPanelLayoutType slug: Telerik.Web.UI.PivotGridConfigurationPanelLayoutType --- # enum Telerik.Web.UI.PivotGridConfigurationPanelLayoutType ## Inheritance Hierarchy * *[Telerik.Web.UI.PivotGridConfigurationPanelLayoutType]({%slug Telerik.Web.UI.PivotGridConfigurationPanelLayoutType%})* ## Fields ### "Stacked" `1` ### "SideBySide" `2` ### "TwoByTwo" `4` ### "OneByFour" `8`
{'content_hash': '7679eaa62c6faa26855e1d6ca50d9a2c', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 121, 'avg_line_length': 22.454545454545453, 'alnum_prop': 0.7813765182186235, 'repo_name': 'telerik/ajax-docs', 'id': '839da52251ffc6a174f0e2a74837a8325d1663fd', 'size': '498', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'api/client/enums/Telerik.Web.UI.PivotGridConfigurationPanelLayoutType.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP.NET', 'bytes': '2253'}, {'name': 'C#', 'bytes': '6026'}, {'name': 'HTML', 'bytes': '2240'}, {'name': 'JavaScript', 'bytes': '3052'}, {'name': 'Ruby', 'bytes': '3275'}]}
module I18nDocs class Translations attr_accessor :locales, :tmp_folder, :config_file, :csv_files def initialize(config_file = nil, tmp_folder = nil) @config_file = config_file @tmp_folder = tmp_folder @csv_files = {} load_config load_locales end def load_locales @locales = [] @locales = I18n.available_locales if defined?(I18n) end def load_config @settings = {} @settings = YAML.load_file(config_file) if File.exists?(config_file) end def download_files files = @settings['files'] files.each do |target_file, url| #ensure .yml filename target_file = target_file + ".yml" if target_file !~ /\.yml$/ # download file to tmp directory tmp_file = File.basename(target_file).gsub('.yml', '.csv') tmp_file = File.join(@tmp_folder, tmp_file) download(url, tmp_file) @csv_files[target_file] = tmp_file end end def store_translations @csv_files.each do |target_file, csv_file| converter = CsvToYaml.new(csv_file, target_file, @locales) converter.process converter.write_files end @csv_files end def clean_up # remove all tmp files @csv_files.each do |target_file, csv_file| File.unlink(csv_file) end end def download(url, destination_file) puts "Download '#{url}' to '#{destination_file}'" doc_data = open(url).read.force_encoding('UTF-8') File.open(destination_file, 'w') do |dst| dst.write(doc_data) end end end end
{'content_hash': '040c7342280d3c05cc0fcb9ede8d0850', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 74, 'avg_line_length': 24.134328358208954, 'alnum_prop': 0.5943104514533086, 'repo_name': 'royzheng0410/i18n-docs-kayla', 'id': 'f2561a252945fce02897792129e6763a8fa091f4', 'size': '1713', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'lib/i18n_docs/translations.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '23589'}]}
package org.mule.example.bookstore; import org.mule.api.lifecycle.Initialisable; import org.mule.api.lifecycle.InitialisationException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jws.WebService; /** * Bookstore catalog service which implements both the public interface for * browsing the catalog and the admin interface for adding books to the catalog. * * @see CatalogService * @see CatalogAdminService */ @WebService(serviceName="CatalogService", endpointInterface="org.mule.example.bookstore.CatalogService") public class CatalogServiceImpl implements CatalogService, CatalogAdminService, Initialisable { /** Simple hashmap used to store the catalog, in real life this would be a database */ private Map <Long, Book> books = new HashMap <Long, Book> (); public void initialise() throws InitialisationException { books = new HashMap <Long, Book> (); // Add some initial test data addBook(new Book("J.R.R. Tolkien", "The Fellowship of the Ring", 8)); addBook(new Book("J.R.R. Tolkien", "The Two Towers", 10)); addBook(new Book("J.R.R. Tolkien", "The Return of the King", 10)); addBook(new Book("C.S. Lewis", "The Lion, the Witch and the Wardrobe", 6)); addBook(new Book("C.S. Lewis", "Prince Caspian", 8)); addBook(new Book("C.S. Lewis", "The Voyage of the Dawn Treader", 6)); addBook(new Book("Leo Tolstoy", "War and Peace", 8)); addBook(new Book("Leo Tolstoy", "Anna Karenina", 6)); addBook(new Book("Henry David Thoreau", "Walden", 8)); addBook(new Book("Harriet Beecher Stowe", "Uncle Tom's Cabin", 6)); addBook(new Book("George Orwell", "1984", 8)); addBook(new Book("George Orwell", "Animal Farm", 8)); addBook(new Book("Aldous Huxley", "Brave New World", 8)); } public long addBook(Book book) { System.out.println("Adding book " + book.getTitle()); long id = books.size() + 1; book.setId(id); books.put(id, book); return id; } public Collection <Long> addBooks(Collection<Book> booksToAdd) { List <Long> ids = new ArrayList <Long> (); if (booksToAdd != null) { for (Book book : booksToAdd) { ids.add(addBook(book)); } } return ids; } public Collection <Book> getBooks() { return books.values(); } public Book getBook(long bookId) { return books.get(bookId); } }
{'content_hash': '45690c118bbef6627c1a7bd9f3b28c5d', 'timestamp': '', 'source': 'github', 'line_count': 80, 'max_line_length': 104, 'avg_line_length': 32.8625, 'alnum_prop': 0.6302776721186764, 'repo_name': 'danielkennedy/cf-buildpack-mule', 'id': '91cc25ec3e71b37cba8342b4d7311fdfe0859de1', 'size': '2889', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'examples/bookstore/src/main/java/org/mule/example/bookstore/CatalogServiceImpl.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '20837'}, {'name': 'Shell', 'bytes': '1852'}]}
<?php /** * The interface that should be implemented by all special status objects. * * Statis objects are used to specify non-normal results from actions. * As an example that could be a "Authorization Required" status, an external * redirect etc. * * * @package MvcTools * @version 1.1.3 */ interface ezcMvcResultStatusObject { /** * This method is called by the response writers to process the data * contained in the status objects. * * The process method it responsible for undertaking the proper action * depending on which response writer is used. * * @param ezcMvcResponseWriter $writer */ public function process( ezcMvcResponseWriter $writer ); } ?>
{'content_hash': '61a3b29c7f138c1a033be43dcbd9f9e5', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 77, 'avg_line_length': 25.714285714285715, 'alnum_prop': 0.6958333333333333, 'repo_name': 'gewthen/ezcomponents', 'id': '55744747f57d2a6b1ce3dd10f76b5c9feb132d41', 'size': '970', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'MvcTools/src/interfaces/result_status_object.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
package com.tapglue.exampleapp_v2; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
{'content_hash': '5d7a31fe6ba0e08111cc1fff03ff2e0b', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 93, 'avg_line_length': 27.384615384615383, 'alnum_prop': 0.75, 'repo_name': 'tapglue/android_sample', 'id': '55288891bed44f9d982732bceffb9c682d126068', 'size': '356', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'android_sample_v2/app/src/androidTest/java/com/tapglue/exampleapp_v2/ApplicationTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '109640'}]}
package org.springframework.beans.propertyeditors; import junit.framework.TestCase; import java.beans.PropertyEditor; /** * Unit tests for the {@link CharArrayPropertyEditor} class. * * @author Rick Evans */ public final class CharArrayPropertyEditorTests extends TestCase { public void testSunnyDaySetAsText() throws Exception { final String text = "Hideous towns make me throw... up"; PropertyEditor charEditor = new CharArrayPropertyEditor(); charEditor.setAsText(text); Object value = charEditor.getValue(); assertNotNull(value); assertTrue(value instanceof char[]); char[] chars = (char[]) value; for (int i = 0; i < text.length(); ++i) { assertEquals("char[] differs at index '" + i + "'", text.charAt(i), chars[i]); } assertEquals(text, charEditor.getAsText()); } public void testGetAsTextReturnsEmptyStringIfValueIsNull() throws Exception { PropertyEditor charEditor = new CharArrayPropertyEditor(); assertEquals("", charEditor.getAsText()); charEditor.setAsText(null); assertEquals("", charEditor.getAsText()); } }
{'content_hash': '3e85406974a90143234eb5567c720d1b', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 81, 'avg_line_length': 26.85, 'alnum_prop': 0.729050279329609, 'repo_name': 'cbeams-archive/spring-framework-2.5.x', 'id': '3f28d1c2512a4724cd7043b5c30498cf4db42105', 'size': '1694', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'test/org/springframework/beans/propertyeditors/CharArrayPropertyEditorTests.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '3220'}, {'name': 'Java', 'bytes': '18679619'}, {'name': 'JavaScript', 'bytes': '1830'}, {'name': 'Ruby', 'bytes': '623'}, {'name': 'Shell', 'bytes': '1092'}]}
Kaminari.configure do |config| config.default_per_page = 20 config.max_per_page = nil config.window = 4 config.outer_window = 0 config.left = 0 config.right = 0 config.page_method_name = :page config.param_name = :page end
{'content_hash': 'd253bb438a5d4c3ba379f6c9a44907c9', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 33, 'avg_line_length': 23.9, 'alnum_prop': 0.694560669456067, 'repo_name': 'minoruito/rbase', 'id': 'dc5a53681eef464675e98502fafe555cb18c7ebd', 'size': '239', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'config/initializers/kaminari_config.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1169335'}, {'name': 'HTML', 'bytes': '231554'}, {'name': 'JavaScript', 'bytes': '9259784'}, {'name': 'Python', 'bytes': '60184'}, {'name': 'Ruby', 'bytes': '299462'}]}
<?xml version="1.0" encoding="utf-8"?> <!--Generated by crowdin.com--> <resources> <string name="app_name">Naptár modul</string> <string name="today">Ma</string> <string name="tomorrow">Holnap</string> <string name="no_upcoming_events">Nincs közelgő esemény</string> <string name="widget_name">Naptár</string> <string name="open_prefs_desc">A naptár modul beállításainak megnyitása</string> <string name="add_event_desc">Új esemény</string> <string name="indicator_alarm">Jelölő emlékeztető beállításánál</string> <string name="indicator_recurring">Jelölő ismétlődő eseménynél</string> <string name="no_title">(Üres esemény név)</string> <string name="calendars_prefs">Naptárak</string> <string name="calendars_prefs_desc">Válassza ki a naptárakat</string> <string name="appearance_prefs">Megjelenés</string> <string name="appearance_prefs_desc">A modul megjelenésének beállítása</string> <string name="appearance_text_size_title">Szövegméret</string> <string name="appearance_text_size_desc">Szövegméret beállítása</string> <string name="appearance_text_size_very_small">Nagyon kicsi</string> <string name="appearance_text_size_small">Kicsi</string> <string name="appearance_text_size_medium">Közepes</string> <string name="appearance_text_size_large">Nagy</string> <string name="appearance_text_size_very_large">Nagyon nagy</string> <string name="appearance_multiline_title_title">Többsoros cím</string> <string name="appearance_multiline_title_desc">Esemény címét törje több sorba, ha nem fér ki</string> <string name="appearance_date_format_desc">Válassza ki az idő formátumát</string> <string name="appearance_date_format_title">Idő formátum</string> <string name="appearance_date_format_auto">Alapértelmezett</string> <string name="appearance_date_format_24">17:00</string> <string name="appearance_date_format_12">5:00</string> <string name="appearance_display_header_title">Mutassa a modul fejlécét</string> <string name="appearance_display_header_desc">Mutassa a dátumot és a parancs ikonokat a fejlécben</string> <string name="appearance_display_header_warning">A fejléc elrejtése után a modulból nem fogja elérni a beállításokat.</string> <string name="appearance_group_color_title">Színek</string> <string name="appearance_background_color_title">Háttér átlátszóság </string> <string name="appearance_background_color_desc">A háttér átlátszóság beállítása</string> <string name="appearance_day_header_alignment_desc">Igazítsa a nap fejlécét</string> <string name="appearance_day_header_alignment_title">Nap fejlécének igazítása</string> <string name="appearance_day_header_alignment_left">Balra</string> <string name="appearance_day_header_alignment_center">Középre</string> <string name="appearance_day_header_alignment_right">Jobbra</string> <string name="appearance_header_theme_title">Modul fejlécének árnyalata</string> <string name="appearance_header_theme_desc">Modul fejlécének árnyalata sötét vagy világos legyen</string> <string name="appearance_entries_theme_title">Esemény árnyalata</string> <string name="appearance_entries_theme_desc">Esemény szövegének árnyalata sötét vagy világos legyen</string> <string name="appearance_theme_black">Fehér</string> <string name="appearance_theme_dark">Világos</string> <string name="appearance_theme_light">Sötét</string> <string name="appearance_theme_white">Fekete</string> <string name="event_details_prefs_desc">Az esemény részleteinek beállítása</string> <string name="event_details_show_end_time_title">Befejezési idő</string> <string name="event_details_show_end_time_desc">Az esemény befejezési időpontjának megjelenítése</string> <string name="event_details_show_location_title">Hely mutatása</string> <string name="event_details_show_location_desc">Az esemény helyének elrejtése vagy mutatása</string> <string name="event_details_fill_all_day_events_title">Többnapos egész napos események összekötése</string> <string name="event_details_fill_all_day_events_desc">Több napon átívelő egész napos események mutatása minden nap</string> <string name="event_details_indicators">Jelölések</string> <string name="event_details_indicate_alert_desc">Jelölje meg az emlékeztetővel rendelkező eseményeket</string> <string name="event_details_indicate_alert_title">Emlékeztetők</string> <string name="event_details_indicate_recurring_desc">Jelölje meg az ismétlődő eseményeket</string> <string name="event_details_indicate_recurring_title">Ismétlődő események</string> <string name="event_details_event_range_title">Dátum intervallum</string> <string name="event_details_event_range_desc">Megjelenítendő események számának beállítása</string> <string name="event_range_one_day">Egy nap</string> <string name="event_range_one_week">Egy hét</string> <string name="event_range_two_weeks">Két hét</string> <string name="event_range_one_month">Egy hónap</string> <string name="event_range_two_months">Két hónap</string> <string name="event_range_three_months">Három hónap</string> <string name="event_range_six_months">Hat hónap</string> <string name="event_range_one_year">Egy év</string> <string name="feedback_prefs">Visszajelzés</string> <string name="feedback_prefs_desc">Lépjen kapcsolatba velünk</string> <string name="feedback_github_desc">Visszajelzés a projekt oldalán</string> <string name="feedback_github_title">A modul a Github-on</string> <string name="feedback_play_store_desc">Értékelés a Google Play-en</string> <string name="feedback_play_store_title">Modul a Google Play-en</string> </resources>
{'content_hash': 'f4431b16ecc5d4908831e96ee6670ac7', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 128, 'avg_line_length': 71.17721518987342, 'alnum_prop': 0.7684510048017072, 'repo_name': 'JordanRobinson/task-widget', 'id': '73b2cc05b1d23c2b3a700528c24063ac1b63fac5', 'size': '5822', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/task-widget/src/main/res/values-hu/strings.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '152216'}]}
@implementation NSObject (JPKitAdditions_Reflection) + (BOOL)jp_hasPropertyWithKey:(NSString *)key { SEL selector = NSSelectorFromString(key); return [self instancesRespondToSelector:selector]; } + (NSString *)jp_typeNameFromRawPropertyType:(const char *)rawPropertyType { if (strcmp(rawPropertyType, @encode(int)) == 0) return @"int"; if (strcmp(rawPropertyType, @encode(BOOL)) == 0) return @"BOOL"; if (strcmp(rawPropertyType, @encode(bool)) == 0) return @"bool"; if (strcmp(rawPropertyType, @encode(short)) == 0) return @"short"; if (strcmp(rawPropertyType, @encode(long)) == 0) return @"long"; if (strcmp(rawPropertyType, @encode(long long)) == 0) return @"long long"; if (strcmp(rawPropertyType, @encode(unsigned char)) == 0) return @"unsigned char"; if (strcmp(rawPropertyType, @encode(unsigned int)) == 0) return @"unsigned int"; if (strcmp(rawPropertyType, @encode(unsigned short)) == 0) return @"unsigned short"; if (strcmp(rawPropertyType, @encode(unsigned long)) == 0) return @"unsigned long"; if (strcmp(rawPropertyType, @encode(unsigned long long)) == 0) return @"unsigned long long"; if (strcmp(rawPropertyType, @encode(float)) == 0) return @"float"; if (strcmp(rawPropertyType, @encode(double)) == 0) return @"double"; if (strcmp(rawPropertyType, @encode(id)) == 0) return @"id"; if (strcmp(rawPropertyType, @encode(Class)) == 0) return @"Class"; // If it is a struct, return the struct's type NSString *propertyType = [NSString stringWithCString:rawPropertyType encoding:[NSString defaultCStringEncoding]]; // e.g. {CGPoint:ff} we don't care about the types in the struct NSString *pattern = @"\\{(\\w*)="; NSRange range = NSMakeRange(0, [propertyType length]); NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil]; NSArray *matches = [regex matchesInString:propertyType options:0 range:range]; for (NSTextCheckingResult *match in matches) { NSRange matchRange = [match rangeAtIndex:1]; NSString* matchString = [propertyType substringWithRange:matchRange]; return matchString; } return nil; } + (NSString *)jp_typeNameForPropertyKey:(NSString *)propertyKey { objc_property_t property = class_getProperty( [self class], [propertyKey cStringUsingEncoding:[NSString defaultCStringEncoding]] ); const char *type = property_getAttributes(property); NSString *typeString = [NSString stringWithUTF8String:type]; NSArray *attributes = [typeString componentsSeparatedByString:@","]; NSString *typeAttribute = [attributes objectAtIndex:0]; NSString *propertyType = [typeAttribute substringFromIndex:1]; const char *rawPropertyType = [propertyType UTF8String]; NSString *typeName = [self jp_typeNameFromRawPropertyType:rawPropertyType]; if (typeName == nil && [typeAttribute hasPrefix:@"T@"]) { typeName = [typeAttribute substringWithRange:NSMakeRange(3, [typeAttribute length] - 4)]; } return typeName; } + (Class)jp_classForPropertyKey:(NSString *)propertyKey { NSString *typeClassName = [self jp_typeNameForPropertyKey:propertyKey]; return NSClassFromString(typeClassName); } + (BOOL)jp_isOrPrecedesClass:(Class)class { Class c = class; while (c != [self class] && (c = class_getSuperclass(c))); return c == [self class]; } @end
{'content_hash': '3cf464444b8d3d5e8ab5e7f476e4a7b1', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 97, 'avg_line_length': 44.91566265060241, 'alnum_prop': 0.6437768240343348, 'repo_name': 'jpmcglone/JPKit', 'id': 'dec1638c07b6e6e04d02efe08b463571003b4f70', 'size': '3900', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/JPKit/Cocoa Categories/NSObject/NSObject+JPKitAdditions_Reflection.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '116383'}, {'name': 'Ruby', 'bytes': '242'}]}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation; using System.Collections.Immutable; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class TypeVariablesExpansionTests : CSharpResultProviderTestBase { [Fact] public void TypeVariables() { var source0 = @"class A { } class B : A { internal static object F = 1; }"; var assembly0 = GetAssembly(source0); var type0 = assembly0.GetType("B"); var source1 = @".class private abstract sealed beforefieldinit specialname '<>c__TypeVariables'<T,U> { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(source1, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly1 = ReflectionUtilities.Load(assemblyBytes); var type1 = assembly1.GetType(ExpressionCompilerConstants.TypeVariablesClassName).MakeGenericType(new[] { typeof(int), type0 }); var value = CreateDkmClrValue(value: null, type: type1, valueFlags: DkmClrValueFlags.Synthetic); var evalResult = FormatResult("typevars", value); Verify(evalResult, EvalResult("Type variables", "", "", null, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var children = GetChildren(evalResult); Verify(children, EvalResult("T", "int", "int", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("U", "B", "B", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); } } }
{'content_hash': '833f7d3bcce1274f6adabdef4a0596b8', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 167, 'avg_line_length': 45.416666666666664, 'alnum_prop': 0.7, 'repo_name': 'reaction1989/roslyn', 'id': 'dfaa1a8e952dd2a998c8c971dac0f6a5f48308a6', 'size': '2182', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/ExpressionEvaluator/CSharp/Test/ResultProvider/TypeVariablesExpansionTests.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': '1C Enterprise', 'bytes': '289100'}, {'name': 'Batchfile', 'bytes': '8757'}, {'name': 'C#', 'bytes': '123682008'}, {'name': 'C++', 'bytes': '5392'}, {'name': 'CMake', 'bytes': '9153'}, {'name': 'Dockerfile', 'bytes': '2102'}, {'name': 'F#', 'bytes': '508'}, {'name': 'PowerShell', 'bytes': '222412'}, {'name': 'Shell', 'bytes': '85934'}, {'name': 'Smalltalk', 'bytes': '622'}, {'name': 'Visual Basic', 'bytes': '70096866'}]}
package v1 import ( kapi "k8s.io/kubernetes/pkg/api" oapi "github.com/openshift/origin/pkg/api" "github.com/openshift/origin/pkg/oauth/api" ) func init() { if err := kapi.Scheme.AddFieldLabelConversionFunc("v1", "OAuthAccessToken", oapi.GetFieldLabelConversionFunc(api.OAuthAccessTokenToSelectableFields(&api.OAuthAccessToken{}), nil), ); err != nil { panic(err) } if err := kapi.Scheme.AddFieldLabelConversionFunc("v1", "OAuthAuthorizeToken", oapi.GetFieldLabelConversionFunc(api.OAuthAuthorizeTokenToSelectableFields(&api.OAuthAuthorizeToken{}), nil), ); err != nil { panic(err) } if err := kapi.Scheme.AddFieldLabelConversionFunc("v1", "OAuthClient", oapi.GetFieldLabelConversionFunc(api.OAuthClientToSelectableFields(&api.OAuthClient{}), nil), ); err != nil { panic(err) } if err := kapi.Scheme.AddFieldLabelConversionFunc("v1", "OAuthClientAuthorization", oapi.GetFieldLabelConversionFunc(api.OAuthClientAuthorizationToSelectableFields(&api.OAuthClientAuthorization{}), nil), ); err != nil { panic(err) } }
{'content_hash': 'eacf061fb2032a002bee20fc53fcefb9', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 121, 'avg_line_length': 30.852941176470587, 'alnum_prop': 0.7540514775977121, 'repo_name': 'aweiteka/origin', 'id': 'f33422b4665bff2eda8388c3a461b43e4c736753', 'size': '1049', 'binary': False, 'copies': '17', 'ref': 'refs/heads/master', 'path': 'pkg/oauth/api/v1/conversion.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '76071'}, {'name': 'DIGITAL Command Language', 'bytes': '117'}, {'name': 'Go', 'bytes': '7160493'}, {'name': 'Groff', 'bytes': '2046'}, {'name': 'HTML', 'bytes': '217585'}, {'name': 'JavaScript', 'bytes': '450071'}, {'name': 'Makefile', 'bytes': '4466'}, {'name': 'Python', 'bytes': '13238'}, {'name': 'Ruby', 'bytes': '242'}, {'name': 'Shell', 'bytes': '1037210'}]}
package clui import ( "fmt" "os" "path/filepath" "sort" "strings" term "github.com/nsf/termbox-go" ) // FileSelectDialog is a dialog to select a file or directory. // Public properties: // * Selected - whether a user has selected an object, or the user canceled // or closed the dialog. In latter case all other properties are not // used and contain default values // * FilePath - full path to the selected file or directory // * Exists - if the selected object exists or a user entered manually a // name of the object type FileSelectDialog struct { View *Window FilePath string Exists bool Selected bool fileMasks []string currPath string mustExist bool selectDir bool result int onClose func() listBox *ListBox edFile *EditField curDir *Label } // Set the cursor the first item in the file list func (d *FileSelectDialog) selectFirst() { d.listBox.SelectItem(0) } // Checks if the file name matches the mask. Empty mask, *, and *.* match any file func (d *FileSelectDialog) fileFitsMask(finfo os.FileInfo) bool { if finfo.IsDir() { return true } if d.selectDir { return false } if len(d.fileMasks) == 0 { return true } for _, msk := range d.fileMasks { if msk == "*" || msk == "*.*" { return true } matched, err := filepath.Match(msk, finfo.Name()) if err == nil && matched { return true } } return false } // Fills the ListBox with the file names from current directory. // Files which names do not match mask are filtered out. // If select directory is set, then the ListBox contains only directories. // Directory names ends with path separator func (d *FileSelectDialog) populateFiles() error { d.listBox.Clear() isRoot := filepath.Dir(d.currPath) == d.currPath if !isRoot { d.listBox.AddItem("..") } f, err := os.Open(d.currPath) if err != nil { return err } finfos, err := f.Readdir(0) f.Close() if err != nil { return err } fnLess := func(i, j int) bool { if finfos[i].IsDir() && !finfos[j].IsDir() { return true } else if !finfos[i].IsDir() && finfos[j].IsDir() { return false } return strings.ToLower(finfos[i].Name()) < strings.ToLower(finfos[j].Name()) } sort.Slice(finfos, fnLess) for _, finfo := range finfos { if !d.fileFitsMask(finfo) { continue } if finfo.IsDir() { d.listBox.AddItem(finfo.Name() + string(os.PathSeparator)) } else { d.listBox.AddItem(finfo.Name()) } } return nil } // Tries to find the best fit for the given path. // It goes up until it gets into the existing directory. // If all fails it returns working directory. func (d *FileSelectDialog) detectPath() { p := d.currPath if p == "" { d.currPath, _ = os.Getwd() return } p = filepath.Clean(p) for { _, err := os.Stat(p) if err == nil { break } dirUp := filepath.Dir(p) if dirUp == p { p, _ = os.Getwd() break } p = dirUp } d.currPath = p } // Goes up in the directory tree if it is possible func (d *FileSelectDialog) pathUp() { dirUp := filepath.Dir(d.currPath) if dirUp == d.currPath { return } d.currPath = dirUp d.populateFiles() d.selectFirst() } // Enters the directory func (d *FileSelectDialog) pathDown(dir string) { d.currPath = filepath.Join(d.currPath, dir) d.populateFiles() d.selectFirst() } // Sets the EditField value with the selected item in ListBox if: // * a directory is selected and option 'select directory' is set // * a file is selected and option 'select directory' is not set func (d *FileSelectDialog) updateEditBox() { s := d.listBox.SelectedItemText() if s == "" || s == ".." || (strings.HasSuffix(s, string(os.PathSeparator)) && !d.selectDir) { d.edFile.Clear() return } d.edFile.SetTitle(strings.TrimSuffix(s, string(os.PathSeparator))) } // CreateFileSelectDialog creates a new file select dialog. It is useful if // the application needs a way to select a file or directory for reading and // writing data. // * title - custom dialog title (the final dialog title includes this one // and the file mask // * fileMasks - a list of file masks separated with comma or path separator. // If selectDir is true this option is not used. Setting fileMasks to // '*', '*.*', or empty string means all files // * selectDir - what kind of object to select: file (false) or directory // (true). If selectDir is true then the dialog does not show files // * mustExists - if it is true then the dialog allows a user to select // only existing object ('open file' case). If it is false then the dialog // makes possible to enter a name manually and click 'Select' (useful // for file 'file save' case) func CreateFileSelectDialog(title, fileMasks, initPath string, selectDir, mustExist bool) *FileSelectDialog { dlg := new(FileSelectDialog) cw, ch := term.Size() dlg.selectDir = selectDir dlg.mustExist = mustExist if fileMasks != "" { maskList := strings.FieldsFunc(fileMasks, func(c rune) bool { return c == ',' || c == ':' }) dlg.fileMasks = make([]string, 0, len(maskList)) for _, m := range maskList { if m != "" { dlg.fileMasks = append(dlg.fileMasks, m) } } } dlg.View = AddWindow(10, 4, 20, 16, fmt.Sprintf("%s (%s)", title, fileMasks)) WindowManager().BeginUpdate() defer WindowManager().EndUpdate() dlg.View.SetModal(true) dlg.View.SetPack(Vertical) dlg.currPath = initPath dlg.detectPath() dlg.curDir = CreateLabel(dlg.View, AutoSize, AutoSize, "", Fixed) dlg.curDir.SetTextDisplay(AlignRight) flist := CreateFrame(dlg.View, 1, 1, BorderNone, 1) flist.SetPaddings(1, 1) flist.SetPack(Horizontal) dlg.listBox = CreateListBox(flist, 16, ch-20, 1) fselected := CreateFrame(dlg.View, 1, 1, BorderNone, Fixed) // text + edit field to enter name manually fselected.SetPack(Vertical) fselected.SetPaddings(1, 0) CreateLabel(fselected, AutoSize, AutoSize, "Selected object:", 1) dlg.edFile = CreateEditField(fselected, cw-22, "", 1) // buttons at the right blist := CreateFrame(flist, 1, 1, BorderNone, Fixed) blist.SetPack(Vertical) blist.SetPaddings(1, 1) btnOpen := CreateButton(blist, AutoSize, AutoSize, "Open", Fixed) btnSelect := CreateButton(blist, AutoSize, AutoSize, "Select", Fixed) btnCancel := CreateButton(blist, AutoSize, AutoSize, "Cancel", Fixed) btnCancel.OnClick(func(ev Event) { WindowManager().DestroyWindow(dlg.View) WindowManager().BeginUpdate() dlg.Selected = false closeFunc := dlg.onClose WindowManager().EndUpdate() if closeFunc != nil { closeFunc() } }) btnSelect.OnClick(func(ev Event) { WindowManager().DestroyWindow(dlg.View) WindowManager().BeginUpdate() dlg.Selected = true dlg.FilePath = filepath.Join(dlg.currPath, dlg.listBox.SelectedItemText()) if dlg.edFile.Title() != "" { dlg.FilePath = filepath.Join(dlg.currPath, dlg.edFile.Title()) } _, err := os.Stat(dlg.FilePath) dlg.Exists = !os.IsNotExist(err) closeFunc := dlg.onClose WindowManager().EndUpdate() if closeFunc != nil { closeFunc() } }) dlg.View.OnClose(func(ev Event) bool { if dlg.result == DialogAlive { dlg.result = DialogClosed if ev.X != 1 { WindowManager().DestroyWindow(dlg.View) } if dlg.onClose != nil { dlg.onClose() } } return true }) dlg.listBox.OnSelectItem(func(ev Event) { item := ev.Msg if item == ".." { btnSelect.SetEnabled(false) btnOpen.SetEnabled(true) return } isDir := strings.HasSuffix(item, string(os.PathSeparator)) if isDir { btnOpen.SetEnabled(true) if !dlg.selectDir { btnSelect.SetEnabled(false) return } } if !isDir { btnOpen.SetEnabled(false) } btnSelect.SetEnabled(true) if (isDir && dlg.selectDir) || !isDir { dlg.edFile.SetTitle(item) } else { dlg.edFile.Clear() } }) btnOpen.OnClick(func(ev Event) { s := dlg.listBox.SelectedItemText() if s != ".." && (s == "" || !strings.HasSuffix(s, string(os.PathSeparator))) { return } if s == ".." { dlg.pathUp() } else { dlg.pathDown(s) } }) dlg.edFile.OnChange(func(ev Event) { s := "" lowCurrText := strings.ToLower(dlg.listBox.SelectedItemText()) lowEditText := strings.ToLower(dlg.edFile.Title()) if !strings.HasPrefix(lowCurrText, lowEditText) { itemIdx := dlg.listBox.PartialFindItem(dlg.edFile.Title(), false) if itemIdx == -1 { if dlg.mustExist { btnSelect.SetEnabled(false) } return } s, _ = dlg.listBox.Item(itemIdx) dlg.listBox.SelectItem(itemIdx) } else { s = dlg.listBox.SelectedItemText() } isDir := strings.HasSuffix(s, string(os.PathSeparator)) equal := strings.EqualFold(s, dlg.edFile.Title()) || strings.EqualFold(s, dlg.edFile.Title()+string(os.PathSeparator)) btnOpen.SetEnabled(isDir || s == "..") if isDir { btnSelect.SetEnabled(dlg.selectDir && (equal || !dlg.mustExist)) return } btnSelect.SetEnabled(equal || !dlg.mustExist) }) dlg.edFile.OnKeyPress(func(key term.Key, c rune) bool { if key == term.KeyArrowUp { idx := dlg.listBox.SelectedItem() if idx > 0 { dlg.listBox.SelectItem(idx - 1) dlg.updateEditBox() } return true } if key == term.KeyArrowDown { idx := dlg.listBox.SelectedItem() if idx < dlg.listBox.ItemCount()-1 { dlg.listBox.SelectItem(idx + 1) dlg.updateEditBox() } return true } return false }) dlg.listBox.OnKeyPress(func(key term.Key) bool { if key == term.KeyBackspace || key == term.KeyBackspace2 { dlg.pathUp() return true } if key == term.KeyCtrlM { s := dlg.listBox.SelectedItemText() if s == ".." { dlg.pathUp() return true } if strings.HasSuffix(s, string(os.PathSeparator)) { dlg.pathDown(s) return true } return false } return false }) dlg.curDir.SetTitle(dlg.currPath) dlg.populateFiles() dlg.selectFirst() ActivateControl(dlg.View, dlg.listBox) return dlg } // OnClose sets the callback that is called when the // dialog is closed func (d *FileSelectDialog) OnClose(fn func()) { WindowManager().BeginUpdate() defer WindowManager().EndUpdate() d.onClose = fn }
{'content_hash': '8371bd6d334eb4d0f22a52f74efb2083', 'timestamp': '', 'source': 'github', 'line_count': 419, 'max_line_length': 109, 'avg_line_length': 24.143198090692124, 'alnum_prop': 0.6663701067615658, 'repo_name': 'VladimirMarkelov/clui', 'id': '9275c5bb7813c19befbd59c9599e6ad6a207b03f', 'size': '10116', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'fileselectdlg.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '247537'}]}
A Hubot script that respond "鷹に決まってんじゃねえか" ![](http://img.f.hatena.ne.jp/images/fotolife/b/bouzuya/20140906/20140906180403.gif) ## Installation $ npm install git://github.com/bouzuya/hubot-taka.git or $ # TAG is the package version you need. $ npm install 'git://github.com/bouzuya/hubot-taka.git#TAG' ## Example bouzuya> hubot 一体何者なの? hubot> 鷹に決まってんじゃねえか ## Configuration See [`src/scripts/taka.coffee`](src/scripts/taka.coffee). ## Development `npm run` ## License [MIT](LICENSE) ## Author [bouzuya][user] &lt;[[email protected]][mail]&gt; ([http://bouzuya.net][url]) ## Badges [![Build Status][travis-badge]][travis] [![Dependencies status][david-dm-badge]][david-dm] [![Coverage Status][coveralls-badge]][coveralls] [travis]: https://travis-ci.org/bouzuya/hubot-taka [travis-badge]: https://travis-ci.org/bouzuya/hubot-taka.svg?branch=master [david-dm]: https://david-dm.org/bouzuya/hubot-taka [david-dm-badge]: https://david-dm.org/bouzuya/hubot-taka.png [coveralls]: https://coveralls.io/r/bouzuya/hubot-taka [coveralls-badge]: https://img.shields.io/coveralls/bouzuya/hubot-taka.svg [user]: https://github.com/bouzuya [mail]: mailto:[email protected] [url]: http://bouzuya.net
{'content_hash': '6ab4bf7bcb6235d8be05d7d77984e43b', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 84, 'avg_line_length': 24.816326530612244, 'alnum_prop': 0.7113486842105263, 'repo_name': 'bouzuya/hubot-taka', 'id': '6ce76ac82ab0a2db095e8ce7f0a3fe2d06d893b8', 'size': '1292', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CoffeeScript', 'bytes': '3252'}, {'name': 'JavaScript', 'bytes': '320'}]}
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'NotificationEmail' db.create_table(u'notifications_notificationemail', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['users.TruffeUser'])), ('notification', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['notifications.Notification'])), )) db.send_create_signal(u'notifications', ['NotificationEmail']) def backwards(self, orm): # Deleting model 'NotificationEmail' db.delete_table(u'notifications_notificationemail') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'notifications.notification': { 'Meta': {'object_name': 'Notification'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'metadata': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'seen': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'seen_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'species': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'notifications.notificationemail': { 'Meta': {'object_name': 'NotificationEmail'}, 'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'notification': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['notifications.Notification']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'notifications.notificationrestriction': { 'Meta': {'object_name': 'NotificationRestriction'}, 'autoread': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'no_email': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.TruffeUser']"}) }, u'users.truffeuser': { 'Meta': {'object_name': 'TruffeUser'}, 'adresse': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'body': ('django.db.models.fields.CharField', [], {'default': "'.'", 'max_length': '1'}), 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '255'}), 'email_perso': ('django.db.models.fields.EmailField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), 'iban_ou_ccp': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_betatester': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'mobile': ('django.db.models.fields.CharField', [], {'max_length': '25', 'blank': 'True'}), 'nom_banque': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) } } complete_apps = ['notifications']
{'content_hash': '17f84946634d599a847624552d88267e', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 195, 'avg_line_length': 71.92857142857143, 'alnum_prop': 0.5695843382040006, 'repo_name': 'agepoly/truffe2', 'id': 'e710139579d1853f8173edbac42b60cbc0dd56af', 'size': '7073', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'truffe2/notifications/migrations/0006_auto__add_notificationemail.py', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'ActionScript', 'bytes': '15982'}, {'name': 'ApacheConf', 'bytes': '45'}, {'name': 'CSS', 'bytes': '551150'}, {'name': 'HTML', 'bytes': '692880'}, {'name': 'JavaScript', 'bytes': '2096877'}, {'name': 'PHP', 'bytes': '2274'}, {'name': 'Python', 'bytes': '2473222'}]}
#include "tensorflow/lite/kernels/internal/optimized/integer_ops/depthwise_conv.h" #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <iostream> #include <limits> #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/c_api_internal.h" #include "tensorflow/lite/kernels/cpu_backend_context.h" #include "tensorflow/lite/kernels/internal/optimized/cpu_check.h" #include "tensorflow/lite/kernels/internal/optimized/depthwiseconv_multithread.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/reference/depthwiseconv_float.h" #include "tensorflow/lite/kernels/internal/reference/depthwiseconv_uint8.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/depthwise_conv.h" #include "tensorflow/lite/kernels/internal/tensor.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/op_macros.h" #include "tensorflow/lite/kernels/padding.h" namespace tflite { namespace ops { namespace builtin { namespace depthwise_conv { constexpr int kInputTensor = 0; constexpr int kFilterTensor = 1; constexpr int kBiasTensor = 2; constexpr int kOutputTensor = 0; // This file has three implementation of DepthwiseConv. enum KernelType { kReference, kGenericOptimized, // Neon-free kNeonOptimized, }; struct OpData { TfLitePaddingValues padding; // The scaling factor from input to output (aka the 'real multiplier') can // be represented as a fixed point multiplier plus a left shift. int32_t output_multiplier; int output_shift; // The range of the fused activation layer. For example for kNone and // uint8_t these would be 0 and 255. int32_t output_activation_min; int32_t output_activation_max; // Per channel output multiplier and shift. std::vector<int32_t> per_channel_output_multiplier; std::vector<int> per_channel_output_shift; }; void* Init(TfLiteContext* context, const char* buffer, size_t length) { // This is a builtin op, so we don't use the contents in 'buffer', if any. // Instead, we allocate a new object to carry information from Prepare() to // Eval(). return new OpData; } void Free(TfLiteContext* context, void* buffer) { delete reinterpret_cast<OpData*>(buffer); } TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteDepthwiseConvParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); // TODO(ahentz): use could use GetOptionalInputTensor() here, but we need to // decide whether we are OK with optional tensors being completely absent, as // opposed to having -1 as their index. bool hasBias = NumInputs(node) == 3; TF_LITE_ENSURE(context, hasBias || NumInputs(node) == 2); const TfLiteTensor* input = GetInput(context, node, kInputTensor); const TfLiteTensor* filter = GetInput(context, node, kFilterTensor); const TfLiteTensor* bias = nullptr; TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE_EQ(context, NumDimensions(input), 4); TF_LITE_ENSURE_EQ(context, NumDimensions(filter), 4); const TfLiteType data_type = input->type; TF_LITE_ENSURE(context, data_type == kTfLiteFloat32 || data_type == kTfLiteUInt8 || data_type == kTfLiteInt8); TF_LITE_ENSURE_EQ(context, output->type, data_type); TF_LITE_ENSURE_EQ(context, filter->type, data_type); // Filter in DepthwiseConv is expected to be [1, H, W, O]. TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 0), 1); if (hasBias) { bias = GetInput(context, node, kBiasTensor); if (data_type == kTfLiteUInt8 || data_type == kTfLiteInt8) { TF_LITE_ENSURE_EQ(context, bias->type, kTfLiteInt32); TF_LITE_ENSURE_EQ(context, bias->params.zero_point, 0); } else { TF_LITE_ENSURE_EQ(context, bias->type, data_type); } TF_LITE_ENSURE_EQ(context, NumDimensions(bias), 1); TF_LITE_ENSURE_EQ(context, SizeOfDimension(filter, 3), SizeOfDimension(bias, 0)); } int channels_out = SizeOfDimension(filter, 3); int width = SizeOfDimension(input, 2); int height = SizeOfDimension(input, 1); int filter_width = SizeOfDimension(filter, 2); int filter_height = SizeOfDimension(filter, 1); int batches = SizeOfDimension(input, 0); // Matching GetWindowedOutputSize in TensorFlow. auto padding = params->padding; int out_width, out_height; data->padding = ComputePaddingHeightWidth( params->stride_height, params->stride_width, params->dilation_height_factor, params->dilation_width_factor, height, width, filter_height, filter_width, padding, &out_height, &out_width); // Note that quantized inference requires that all tensors have their // parameters set. This is usually done during quantized training or // calibration. if (data_type != kTfLiteFloat32) { TF_LITE_ENSURE_EQ(context, filter->quantization.type, kTfLiteAffineQuantization); const auto* affine_quantization = reinterpret_cast<TfLiteAffineQuantization*>( filter->quantization.params); TF_LITE_ENSURE(context, affine_quantization); TF_LITE_ENSURE(context, affine_quantization->scale); const int number_channel = affine_quantization->scale->size; data->per_channel_output_multiplier.resize(number_channel); data->per_channel_output_shift.resize(number_channel); TF_LITE_ENSURE_STATUS(tflite::PopulateConvolutionQuantizationParams( context, input, filter, bias, output, params->activation, &data->output_multiplier, &data->output_shift, &data->output_activation_min, &data->output_activation_max, data->per_channel_output_multiplier.data(), data->per_channel_output_shift.data())); } TfLiteIntArray* outputSize = TfLiteIntArrayCreate(4); outputSize->data[0] = batches; outputSize->data[1] = out_height; outputSize->data[2] = out_width; outputSize->data[3] = channels_out; return context->ResizeTensor(context, output, outputSize); } TfLiteStatus ComputeDepthMultiplier(TfLiteContext* context, const TfLiteTensor* input, const TfLiteTensor* filter, int16* depth_multiplier) { int num_filter_channels = SizeOfDimension(filter, 3); int num_input_channels = SizeOfDimension(input, 3); TF_LITE_ENSURE_EQ(context, num_filter_channels % num_input_channels, 0); *depth_multiplier = num_filter_channels / num_input_channels; return kTfLiteOk; } template <KernelType kernel_type> TfLiteStatus EvalFloat(TfLiteContext* context, TfLiteNode* node, TfLiteDepthwiseConvParams* params, OpData* data, const TfLiteTensor* input, const TfLiteTensor* filter, const TfLiteTensor* bias, TfLiteTensor* output) { float output_activation_min, output_activation_max; CalculateActivationRange(params->activation, &output_activation_min, &output_activation_max); DepthwiseParams op_params; op_params.padding_type = PaddingType::kSame; op_params.padding_values.width = data->padding.width; op_params.padding_values.height = data->padding.height; op_params.stride_width = params->stride_width; op_params.stride_height = params->stride_height; op_params.dilation_width_factor = params->dilation_width_factor; op_params.dilation_height_factor = params->dilation_height_factor; op_params.float_activation_min = output_activation_min; op_params.float_activation_max = output_activation_max; TF_LITE_ENSURE_STATUS(ComputeDepthMultiplier(context, input, filter, &op_params.depth_multiplier)); if (kernel_type == kReference) { reference_ops::DepthwiseConv( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(filter), GetTensorData<float>(filter), GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output), GetTensorData<float>(output)); } else { optimized_ops::DepthwiseConv<float, float>( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(filter), GetTensorData<float>(filter), GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output), GetTensorData<float>(output), CpuBackendContext::GetFromContext(context)); } return kTfLiteOk; } template <KernelType kernel_type> TfLiteStatus EvalQuantized(TfLiteContext* context, TfLiteNode* node, TfLiteDepthwiseConvParams* params, OpData* data, const TfLiteTensor* input, const TfLiteTensor* filter, const TfLiteTensor* bias, TfLiteTensor* output) { auto input_offset = -input->params.zero_point; auto filter_offset = -filter->params.zero_point; auto output_offset = output->params.zero_point; DepthwiseParams op_params; op_params.padding_type = PaddingType::kSame; op_params.padding_values.width = data->padding.width; op_params.padding_values.height = data->padding.height; op_params.stride_width = params->stride_width; op_params.stride_height = params->stride_height; op_params.dilation_width_factor = params->dilation_width_factor; op_params.dilation_height_factor = params->dilation_height_factor; op_params.input_offset = input_offset; op_params.weights_offset = filter_offset; op_params.output_offset = output_offset; op_params.output_multiplier = data->output_multiplier; op_params.output_shift = -data->output_shift; op_params.quantized_activation_min = data->output_activation_min; op_params.quantized_activation_max = data->output_activation_max; TF_LITE_ENSURE_STATUS(ComputeDepthMultiplier(context, input, filter, &op_params.depth_multiplier)); if (kernel_type == kReference) { reference_ops::DepthwiseConv( op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(filter), GetTensorData<uint8_t>(filter), GetTensorShape(bias), GetTensorData<int32_t>(bias), GetTensorShape(output), GetTensorData<uint8_t>(output)); } else { optimized_ops::DepthwiseConv<uint8, int32>( op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(filter), GetTensorData<uint8_t>(filter), GetTensorShape(bias), GetTensorData<int32_t>(bias), GetTensorShape(output), GetTensorData<uint8_t>(output), CpuBackendContext::GetFromContext(context)); } return kTfLiteOk; } template <KernelType kernel_type> TfLiteStatus EvalQuantizedPerChannel(TfLiteContext* context, TfLiteNode* node, TfLiteDepthwiseConvParams* params, OpData* data, const TfLiteTensor* input, const TfLiteTensor* filter, const TfLiteTensor* bias, TfLiteTensor* output) { DepthwiseParams op_params; op_params.padding_type = PaddingType::kSame; op_params.padding_values.width = data->padding.width; op_params.padding_values.height = data->padding.height; op_params.stride_width = params->stride_width; op_params.stride_height = params->stride_height; op_params.dilation_width_factor = params->dilation_width_factor; op_params.dilation_height_factor = params->dilation_height_factor; op_params.input_offset = -input->params.zero_point; op_params.weights_offset = 0; op_params.output_offset = output->params.zero_point; // TODO(b/130439627): Use calculated value for clamping. op_params.quantized_activation_min = std::numeric_limits<int8_t>::min(); op_params.quantized_activation_max = std::numeric_limits<int8_t>::max(); TF_LITE_ENSURE_STATUS(ComputeDepthMultiplier(context, input, filter, &op_params.depth_multiplier)); if (kernel_type == kReference) { reference_integer_ops::DepthwiseConvPerChannel( op_params, data->per_channel_output_multiplier.data(), data->per_channel_output_shift.data(), GetTensorShape(input), GetTensorData<int8>(input), GetTensorShape(filter), GetTensorData<int8>(filter), GetTensorShape(bias), GetTensorData<int32>(bias), GetTensorShape(output), GetTensorData<int8>(output)); } else { optimized_integer_ops::DepthwiseConvPerChannel( op_params, data->per_channel_output_multiplier.data(), data->per_channel_output_shift.data(), GetTensorShape(input), GetTensorData<int8>(input), GetTensorShape(filter), GetTensorData<int8>(filter), GetTensorShape(bias), GetTensorData<int32>(bias), GetTensorShape(output), GetTensorData<int8>(output), CpuBackendContext::GetFromContext(context)); } return kTfLiteOk; } template <KernelType kernel_type> TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteDepthwiseConvParams*>(node->builtin_data); OpData* data = reinterpret_cast<OpData*>(node->user_data); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); const TfLiteTensor* input = GetInput(context, node, kInputTensor); const TfLiteTensor* filter = GetInput(context, node, kFilterTensor); const TfLiteTensor* bias = (NumInputs(node) == 3) ? GetInput(context, node, kBiasTensor) : nullptr; // TODO(aselle): Consider whether float conv and quantized conv should be // separate ops to avoid dispatch overhead here. switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: TF_LITE_ENSURE_STATUS(EvalFloat<kernel_type>( context, node, params, data, input, filter, bias, output)); break; case kTfLiteUInt8: TF_LITE_ENSURE_STATUS(EvalQuantized<kernel_type>( context, node, params, data, input, filter, bias, output)); break; case kTfLiteInt8: { TF_LITE_ENSURE_STATUS(EvalQuantizedPerChannel<kernel_type>( context, node, params, data, input, filter, bias, output)); break; } default: context->ReportError(context, "Type %d not currently supported.", input->type); return kTfLiteError; } return kTfLiteOk; } } // namespace depthwise_conv TfLiteRegistration* Register_DEPTHWISE_CONVOLUTION_REF() { static TfLiteRegistration r = { depthwise_conv::Init, depthwise_conv::Free, depthwise_conv::Prepare, depthwise_conv::Eval<depthwise_conv::kReference>}; return &r; } TfLiteRegistration* Register_DEPTHWISE_CONVOLUTION_GENERIC_OPT() { static TfLiteRegistration r = { depthwise_conv::Init, depthwise_conv::Free, depthwise_conv::Prepare, depthwise_conv::Eval<depthwise_conv::kGenericOptimized>}; return &r; } TfLiteRegistration* Register_DEPTHWISE_CONVOLUTION_NEON_OPT() { static TfLiteRegistration r = { depthwise_conv::Init, depthwise_conv::Free, depthwise_conv::Prepare, depthwise_conv::Eval<depthwise_conv::kNeonOptimized>}; return &r; } TfLiteRegistration* Register_DEPTHWISE_CONV_2D() { #ifdef USE_NEON return Register_DEPTHWISE_CONVOLUTION_NEON_OPT(); #else return Register_DEPTHWISE_CONVOLUTION_GENERIC_OPT(); #endif } } // namespace builtin } // namespace ops } // namespace tflite
{'content_hash': 'a98bf65e982a6bd1b55ec628265d18b5', 'timestamp': '', 'source': 'github', 'line_count': 367, 'max_line_length': 82, 'avg_line_length': 42.37874659400545, 'alnum_prop': 0.6960072011830515, 'repo_name': 'ppwwyyxx/tensorflow', 'id': '38a3f34709e5bc6cf8e3b226da6579acd7eff504', 'size': '16221', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tensorflow/lite/kernels/depthwise_conv.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '5003'}, {'name': 'Batchfile', 'bytes': '45318'}, {'name': 'C', 'bytes': '796611'}, {'name': 'C#', 'bytes': '8562'}, {'name': 'C++', 'bytes': '76521274'}, {'name': 'CMake', 'bytes': '6545'}, {'name': 'Dockerfile', 'bytes': '81136'}, {'name': 'Go', 'bytes': '1679107'}, {'name': 'HTML', 'bytes': '4686483'}, {'name': 'Java', 'bytes': '952883'}, {'name': 'Jupyter Notebook', 'bytes': '567243'}, {'name': 'LLVM', 'bytes': '6536'}, {'name': 'MLIR', 'bytes': '1254789'}, {'name': 'Makefile', 'bytes': '61284'}, {'name': 'Objective-C', 'bytes': '104706'}, {'name': 'Objective-C++', 'bytes': '297774'}, {'name': 'PHP', 'bytes': '24055'}, {'name': 'Pascal', 'bytes': '3752'}, {'name': 'Pawn', 'bytes': '17546'}, {'name': 'Perl', 'bytes': '7536'}, {'name': 'Python', 'bytes': '38709528'}, {'name': 'RobotFramework', 'bytes': '891'}, {'name': 'Ruby', 'bytes': '7469'}, {'name': 'Shell', 'bytes': '643731'}, {'name': 'Smarty', 'bytes': '34743'}, {'name': 'Swift', 'bytes': '62814'}]}
using JsonParser; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { string data = File.ReadAllText(@"....."); Stopwatch watch = new Stopwatch(); for (int i = 0; i < 20; i++) { watch.Start(); Newtonsoft.Json.Linq.JObject jObj = Newtonsoft.Json.Linq.JObject.Parse(data); watch.Stop(); Console.WriteLine(watch.Elapsed); watch.Reset(); } Console.WriteLine(" "); GC.Collect(); for (int i = 0; i < 20; i++) { watch.Start(); JParser parser = new JParser(); JToken token = parser.Parse(data); watch.Stop(); Console.WriteLine(watch.Elapsed); watch.Reset(); } Console.WriteLine(" "); } } }
{'content_hash': '2277a50483785703b48ed1b3012cedf9', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 93, 'avg_line_length': 26.046511627906977, 'alnum_prop': 0.4919642857142857, 'repo_name': 'srpanwar/JSONParser', 'id': 'aab3f70a185c9e39de10cf47a0641ce38dc955ad', 'size': '1122', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ConsoleApplication2/Program.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '20111'}]}
<html dir="LTR"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" /> <title>RequiresLayout Property</title> <xml> </xml> <link rel="stylesheet" type="text/css" href="MSDN.css" /> </head> <body id="bodyID" class="dtBODY"> <div id="nsbanner"> <div id="bannerrow1"> <table class="bannerparthead" cellspacing="0"> <tr id="hdr"> <td class="runninghead">Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0</td> <td class="product"> </td> </tr> </table> </div> <div id="TitleRow"> <h1 class="dtH1">TraceAppender.RequiresLayout Property</h1> </div> </div> <div id="nstext"> <p> This appender requires a <a href="log4net.Layout.html">log4net.Layout</a> to be set. </p> <div class="syntax"> <span class="lang">[Visual Basic]</span> <br />Overrides Protected ReadOnly Property RequiresLayout As <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemBooleanClassTopic.htm">Boolean</a></div> <div class="syntax"> <span class="lang">[C#]</span> <br />protected override <a href="ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrfSystemBooleanClassTopic.htm">bool</a> RequiresLayout {get;}</div> <p> </p> <h4 class="dtH4">Property Value</h4> <p> <code>true</code> </p> <h4 class="dtH4">Remarks</h4> <p> This appender requires a <a href="log4net.Layout.html">log4net.Layout</a> to be set. </p> <h4 class="dtH4">See Also</h4><p><a href="log4net.Appender.TraceAppender.html">TraceAppender Class</a> | <a href="log4net.Appender.html">log4net.Appender Namespace</a></p><object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"><param name="Keyword" value="RequiresLayout property"></param><param name="Keyword" value="RequiresLayout property, TraceAppender class"></param><param name="Keyword" value="TraceAppender.RequiresLayout property"></param></object><hr /><div id="footer"><a href='http://logging.apache.org/log4net/'>Copyright 2004-2013 The Apache Software Foundation.</a><br></br>Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.</div></div> </body> </html>
{'content_hash': 'ff42896625922d7755e039b9275bc178', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 774, 'avg_line_length': 57.30232558139535, 'alnum_prop': 0.648538961038961, 'repo_name': 'red2901/sandbox', 'id': 'd0f586363170431672b61d5db015961cf46c1c0d', 'size': '2464', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'exceldna/Libs/log4net-1.2.13/doc/release/sdk/log4net.Appender.TraceAppender.RequiresLayout.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '7920'}, {'name': 'Assembly', 'bytes': '526787'}, {'name': 'Batchfile', 'bytes': '17812'}, {'name': 'C', 'bytes': '416259'}, {'name': 'C#', 'bytes': '11438116'}, {'name': 'C++', 'bytes': '2770094'}, {'name': 'CMake', 'bytes': '6806'}, {'name': 'CSS', 'bytes': '20674'}, {'name': 'E', 'bytes': '800'}, {'name': 'F#', 'bytes': '702'}, {'name': 'HTML', 'bytes': '9558034'}, {'name': 'Java', 'bytes': '409044'}, {'name': 'JavaScript', 'bytes': '37364'}, {'name': 'Makefile', 'bytes': '54316'}, {'name': 'Objective-C', 'bytes': '1629'}, {'name': 'PowerShell', 'bytes': '10735'}, {'name': 'Python', 'bytes': '1094'}, {'name': 'Shell', 'bytes': '2038'}, {'name': 'Visual Basic', 'bytes': '64564'}]}
<?php /** * AuthenticationMagicTokenCredentialsTest * * PHP version 5 * * @category Class * @package Alfaview * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * authService/authenticationService.proto * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: version not set * * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.4.27 */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Please update the test case below to test the model. */ namespace Alfaview; use PHPUnit\Framework\TestCase; /** * AuthenticationMagicTokenCredentialsTest Class Doc Comment * * @category Class * @description * MagicTokenCredentials are used to obtain an access token from a magic token (and possibly a refresh token if one was provided when the magic token was created). They are one-time use only. * @package Alfaview * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class AuthenticationMagicTokenCredentialsTest extends TestCase { /** * Setup before running any test case */ public static function setUpBeforeClass(): void { } /** * Setup before running each test case */ public function setUp(): void { } /** * Clean up after running each test case */ public function tearDown(): void { } /** * Clean up after running all test cases */ public static function tearDownAfterClass(): void { } /** * Test "AuthenticationMagicTokenCredentials" */ public function testAuthenticationMagicTokenCredentials() { } /** * Test attribute "magic_token" */ public function testPropertyMagicToken() { } }
{'content_hash': 'a53c1e359e3f2fdd77d6ec2b17fdb1a9', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 206, 'avg_line_length': 22.568181818181817, 'alnum_prop': 0.6711983887210473, 'repo_name': 'alfatraining/alfaview-php-sdk', 'id': '2418dda246f879da3ae8bbed4f691771903147b3', 'size': '1986', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/Model/AuthenticationMagicTokenCredentialsTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '2425530'}]}
Captain.config do |config| config.public_key = "00000000000" end
{'content_hash': '469cf9d715e36160a874636478fff626', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 34, 'avg_line_length': 21.666666666666668, 'alnum_prop': 0.7692307692307693, 'repo_name': 'alessiosantocs/captain-rails', 'id': 'c1fd8f880168bf779fa4de317554a150cb636126', 'size': '65', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'config/initializers/captain.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '7508'}]}
__author__ = 'Yves Bonjour' import sys import os import ConfigParser from Feeds import Feed from Feeds import create_feeds from WerkzeugService import WerkzeugService from WerkzeugService import create_status_error_response from WerkzeugService import create_status_ok_response from WerkzeugService import create_json_response from werkzeug.routing import Map, Rule import uuid USAGE = "USAGE: python Service.py [config_file]" def create_feed_service(host, port, debug, redis_host, redis_port): feeds = create_feeds(redis_host, redis_port) return FeedService(feeds, host, port, debug) class FeedService(WerkzeugService): def __init__(self, feeds, host, port, debug): super(FeedService, self).__init__(host, port, Map([ Rule('/add', endpoint='add'), Rule('/feed_urls', endpoint='feed_urls') ]), debug=debug) self.feeds = feeds def on_add(self, request): if request.method != "POST": return create_status_error_response("Request must be POST", status=400) if "url" not in request.form or "name" not in request.form or "user" not in request.form: return create_status_error_response("Request must have the url, name and user", status=400) feed = Feed(request.form["url"], request.form["name"]) user_id = uuid.UUID(request.form["user"]) try: self.feeds.add_feed(feed, user_id) except Exception as e: return create_status_error_response(str(e)) return create_status_ok_response() def on_feed_urls(self, _): urls = self.feeds.get_feed_urls() return create_json_response(list(urls)) if __name__ == "__main__": arguments = sys.argv[1:] if len(arguments) != 1: print(USAGE) quit() config_file = arguments[0] if not os.path.isfile(config_file): print(USAGE) quit() config_parser = ConfigParser.RawConfigParser() config_parser.read(config_file) host = config_parser.get("FeedService", "host") port = config_parser.getint("FeedService", "port") debug = config_parser.getboolean("FeedService", "debug") redis_host = config_parser.get("FeedService", "redis_host") redis_port = config_parser.getint("FeedService", "redis_port") service = create_feed_service(host, port, debug, redis_host, redis_port) service.run()
{'content_hash': '93d667ea972417bd85a87e9800ea3c72', 'timestamp': '', 'source': 'github', 'line_count': 72, 'max_line_length': 103, 'avg_line_length': 33.208333333333336, 'alnum_prop': 0.657465495608532, 'repo_name': 'ybonjour/nuus', 'id': 'c658d5ba638ebdb103226f1b1d923f294a47509d', 'size': '2391', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'services/feeds/Service.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CoffeeScript', 'bytes': '229'}, {'name': 'JavaScript', 'bytes': '210240'}, {'name': 'Python', 'bytes': '133059'}, {'name': 'Ruby', 'bytes': '21666'}, {'name': 'Shell', 'bytes': '2943'}]}
<app-dialog [showDialog]="showDialog" [heading]="'SAVE_TO_COLLECTION_HEADER' | translate" [subheading]="'SAVE_TO_COLLCTION_SUBTEXT' | translate" (toggleDialog)="toggleDialogChange.emit($event)" (saveChange)="onSaveChange()" > <div class="add-to-collection-wrapper"> <div class="app-dialog-section"> {{ 'SAVE_TO_COLLECTION_NAME_OF_QUERY' | translate }} <input type="text" class="dialog-input" [(ngModel)]="newCollectionQueryTitle" attr.aria-label="{{ 'SAVE_TO_COLLECTION_NAME_OF_QUERY' | translate }}" data-test-id="collection-query-name" > </div> <div class="app-dialog-section"> <nz-form-label>{{ 'SAVE_TO_COLLECTION_SELECT_COLLECTION' | translate }}</nz-form-label> <nz-form-control> <nz-select class="dialog-block" [(ngModel)]="collectionId" name="collection" nzPlaceHolder="Choose"> <nz-option *ngFor="let collection of collections; trackBy:trackById" [nzValue]="collection.id" [nzLabel]="collection.title"></nz-option> <nz-option [nzValue]="-1" [nzLabel]="'SAVE_TO_COLLECTION_OR_CREATE_NEW_COLLECTION_LABEL' | translate"></nz-option> </nz-select> </nz-form-control> </div> <div *ngIf="collectionId === -1" class="app-dialog-section" > {{ 'SAVE_TO_COLLECTION_COLLECTION_NAME' | translate }} <input type="text" class="dialog-input" [(ngModel)]="newCollectionTitle" attr.aria-label="{{ 'SAVE_TO_COLLECTION_COLLECTION_NAME' | translate }}" data-test-id="new-collection-name" > </div> </div> </app-dialog>
{'content_hash': 'e6b12c84c7f30ebc5692e5333ba5213b', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 146, 'avg_line_length': 37.93023255813954, 'alnum_prop': 0.6210913549969344, 'repo_name': 'imolorhe/altair', 'id': '1a3396af33f1d7c54f636badcf90fec9da4421eb', 'size': '1631', 'binary': False, 'copies': '1', 'ref': 'refs/heads/staging', 'path': 'packages/altair-app/src/app/modules/altair/components/add-collection-query-dialog/add-collection-query-dialog.component.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '73038'}, {'name': 'HTML', 'bytes': '96843'}, {'name': 'JavaScript', 'bytes': '71257'}, {'name': 'Shell', 'bytes': '6759'}, {'name': 'TypeScript', 'bytes': '483664'}]}
use std::collections::HashMap; use std::env; use std::ffi::{OsStr, OsString}; use std::path::PathBuf; pub struct CommandFinder { cache: HashMap<OsString, Option<PathBuf>>, path: OsString, } impl CommandFinder { pub fn new() -> Self { Self { cache: HashMap::new(), path: env::var_os("PATH").unwrap_or_default(), } } pub fn maybe_have<S: AsRef<OsStr>>(&mut self, cmd: S) -> Option<PathBuf> { let cmd: OsString = cmd.as_ref().into(); let path = self.path.clone(); self.cache .entry(cmd.clone()) .or_insert_with(|| { for path in env::split_paths(&path) { let target = path.join(&cmd); let mut cmd_alt = cmd.clone(); cmd_alt.push(".exe"); let mut symlink_is_file = false; if let Ok(metadata) = target.with_extension("exe").symlink_metadata() { symlink_is_file = metadata.is_file() } if target.is_file() || // some/path/git symlink_is_file || target.with_extension("exe").exists() || // some/path/git.exe target.join(&cmd_alt).exists() { // some/path/git/git.exe return Some(target); } } None }) .clone() } pub fn must_have<S: AsRef<OsStr>>(&mut self, cmd: S) -> PathBuf { self.maybe_have(&cmd).unwrap_or_else(|| { panic!("\n\ncouldn't find required command: {:?}\n\n", cmd.as_ref()); }) } }
{'content_hash': 'c774bf3b4d33dc441e460ec83d84c536', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 91, 'avg_line_length': 32.88461538461539, 'alnum_prop': 0.45964912280701753, 'repo_name': 'google/shaderc-rs', 'id': '5dcf9e70a78e98a36a6d4fa2340014079e3cabc0', 'size': '1925', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'shaderc-sys/build/cmd_finder.rs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CMake', 'bytes': '424'}, {'name': 'Rust', 'bytes': '96346'}]}
module Traits::Controller::Actions::Show module InstanceMethods def show response_with_options instance_variable_get("@#{singular_name}") end end def self.included(receiver) receiver.send :include, InstanceMethods end end
{'content_hash': 'e1737545baee6ded341daed7ada7acae', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 70, 'avg_line_length': 22.727272727272727, 'alnum_prop': 0.72, 'repo_name': 'binarycode/traits', 'id': '0701ff2bb26f89c47abc91908f8e3eb76227a9d3', 'size': '250', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/traits/controller/actions/show.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '12079'}]}
/** * @private * * This class is used only by the grid's HeaderContainer docked child. * * It adds the ability to shrink the vertical size of the inner container element back if a grouped * column header has all its child columns dragged out, and the whole HeaderContainer needs to shrink back down. * * Also, after every layout, after all headers have attained their 'stretchmax' height, it goes through and calls * `setPadding` on the columns so that they lay out correctly. */ Ext.define('Ext.grid.ColumnLayout', { extend: 'Ext.layout.container.HBox', alias: 'layout.gridcolumn', type : 'gridcolumn', requires: [ 'Ext.panel.Table' ], firstHeaderCls: Ext.baseCSSPrefix + 'column-header-first', lastHeaderCls: Ext.baseCSSPrefix + 'column-header-last', initLayout: function() { this.callParent(); if (this.scrollbarWidth === undefined) { this.self.prototype.scrollbarWidth = Ext.getScrollbarSize().width; } }, beginLayout: function (ownerContext) { var me = this, owner = me.owner, view = owner.grid ? owner.grid.getView() : null, firstCls = me.firstHeaderCls, lastCls = me.lastHeaderCls, bothCls = [firstCls, lastCls], items = me.getVisibleItems(), len = items.length, i, item; if (view && view.scrollFlags.x) { me.viewScrollX = view.getScrollX(); owner.suspendEvent('scroll'); view.suspendEvent('scroll'); } me.callParent([ ownerContext ]); // Sync the first/lastCls states for all the headers. for (i = 0; i < len; i++) { item = items[i]; if (len === 1) { // item is the only item so it is both first and last item.addCls(bothCls); } else if (i === 0) { // item is the first of 2+ items item.addCls(firstCls); item.removeCls(lastCls); } else if (i === len - 1) { // item is the last of 2+ items item.removeCls(firstCls); item.addCls(lastCls); } else { item.removeCls(bothCls); } } // Start this at 0 and for the root headerCt call determineScrollbarWidth to get // it set properly. Typically that amounts to a "delete" to expose the system's // scrollbar width stored on our prototype. me.scrollbarWidth = 0; if (owner.isRootHeader) { me.determineScrollbarWidth(ownerContext); } if (!me.scrollbarWidth) { // By default Mac OS X has overlay scrollbars that do not take space, but also // the RTL override may have set this to 0... so make sure we don't try to // compensate for a scrollbar when there isn't one. ownerContext.manageScrollbar = false; } }, moveItemBefore: function (item, before) { var prevOwner = item.ownerCt; // Due to the nature of grid headers, index calculation for // moving items is complicated, especially since removals can trigger // groups to be removed (and thus alter indexes). As such, the logic // is simplified by removing the item first, then calculating the index // and inserting it if (item !== before && prevOwner) { prevOwner.remove(item, false); } return this.callParent([item, before]); }, determineScrollbarWidth: function (ownerContext) { var me = this, owner = me.owner, grid = owner.grid, // locking headerCt can refuse to reserveScrollbar, even if the locking grid // view does reserveScrollbar (special technique for hiding the vertical // scrollbar on the locked side) vetoReserveScrollbar = owner.reserveScrollbar === false, // We read this value off of the immediate grid since the locked side of a // locking grid will not have this set. The ownerGrid in that case would have // it set but will pass along true only to the normal side. reserveScrollbar = grid.reserveScrollbar && !vetoReserveScrollbar, manageScrollbar = !reserveScrollbar && !vetoReserveScrollbar && grid.view.scrollFlags.y; // If we have reserveScrollbar then we will always have a vertical scrollbar so // manageScrollbar should be false. Otherwise it is based on overflow-y: ownerContext.manageScrollbar = manageScrollbar; // Determine if there is any need to deal with the width of the vertical scrollbar // and set "scrollbarWidth" to 0 if not or the system determined value (stored on // our prototype). // if (!grid.ownerGrid.collapsed && (reserveScrollbar || manageScrollbar)) { // Ensure the real scrollbarWidth value is exposed from the prototype. This // may be needed if the scrollFlags have changed since we may have a 0 set on // this instance from a previous layout run. delete me.scrollbarWidth; } // On return, the RTL override (Ext.rtl.grid.ColumnLayout) will deal with various // browser bugs and may set me.scrollbarWidth to 0 or a negative value. }, calculate: function (ownerContext) { var me = this, grid = me.owner.grid, // Our TableLayout buddy sets this in its beginLayout so we can work this // out together: viewContext = ownerContext.viewContext, state = ownerContext.state, context = ownerContext.context, lockingPartnerContext, ownerGrid, columnsChanged, columns, len, i, column, scrollbarAdjustment, viewOverflowY; me.callParent([ ownerContext ]); if (grid && state.parallelDone) { lockingPartnerContext = viewContext.lockingPartnerContext; ownerGrid = grid.ownerGrid; // A force-fit needs to be "reflexed" so check that now. If we have to reflex // the items, we need to re-cacheFlexes and invalidate ourselves. if (ownerGrid.forceFit && !state.reflexed) { if (me.convertWidthsToFlexes(ownerContext)) { me.cacheFlexes(ownerContext); me.done = false; ownerContext.invalidate({ state: { reflexed: true, scrollbarAdjustment: me.getScrollbarAdjustment(ownerContext) } }); return; } } // Once the parallelDone flag goes up, we need to pack up the changed column // widths for our TableLayout partner. if ((columnsChanged = state.columnsChanged) === undefined) { columns = ownerContext.target.getVisibleGridColumns(); columnsChanged = false; for (i = 0, len = columns.length; i < len; i++) { column = context.getCmp(columns[i]); // Since we are parallelDone, all of the children should have width, // so we can if (!column.lastBox || column.props.width !== column.lastBox.width) { (columnsChanged || (columnsChanged = []))[i] = column; } } state.columnsChanged = columnsChanged; // This will trigger our TableLayout partner and allow it to proceed. ownerContext.setProp('columnsChanged', columnsChanged); } if (ownerContext.manageScrollbar) { // If we changed the column widths, we need to wait for the TableLayout to // return whether or not we have overflowY... well, that is, if we are // needing to tweak the scrollbarAdjustment... scrollbarAdjustment = me.getScrollbarAdjustment(ownerContext); if (scrollbarAdjustment) { // Since we start with the assumption that we will need the scrollbar, // we now need to wait to see if our guess was correct. viewOverflowY = viewContext.getProp('viewOverflowY'); if (viewOverflowY === undefined) { // The TableLayout has not determined this yet, so park it. me.done = false; return; } if (!viewOverflowY) { // We have our answer, and it turns out the view did not overflow // (even with the reduced width we gave it), so we need to remove // the scrollbarAdjustment and go again. if (lockingPartnerContext) { // In a locking grid, only the normal side plays this game, // so now that we know the resolution, we need to invalidate // the locking view and its headerCt. lockingPartnerContext.invalidate(); lockingPartnerContext.headerContext.invalidate(); } viewContext.invalidate(); ownerContext.invalidate({ state: { // Pass a 0 adjustment on into our next life. If this is // the invalidate that resets ownerContext then this is // put onto the new state. If not, it will reset back to // undefined and we'll have to begin again (which is the // correct thing to do in that case). scrollbarAdjustment: 0 } }); } } // else { // We originally assumed we would need the scrollbar and since we do // not now, we must be on the second pass, so we can move on... // } } } }, finishedLayout: function(ownerContext) { var me = this, owner = me.owner, view = owner.grid ? owner.grid.getView() : null, viewScrollX = me.viewScrollX; me.callParent([ ownerContext ]); // Keep the HeaderContainer's horizontal scroll position synced with where the user // has scrolled the view to (it will reset during a layout) IF this is a top lever // grid HeaderContainer and the view is doing horizontal scrolling and the // HeaderContainer overflows. Only do this after the initial layout where scroll // position will be at default. if (view && view.scrollFlags.x) { if (viewScrollX !== undefined && owner.tooNarrow && owner.componentLayoutCounter) { owner.setScrollX(viewScrollX); } view.resumeEvent('scroll'); owner.resumeEvent('scroll'); } if (owner.ariaRole === 'rowgroup') { me.innerCt.dom.setAttribute('role', 'row'); } }, convertWidthsToFlexes: function(ownerContext) { var me = this, totalWidth = 0, calculated = me.sizeModels.calculated, childItems, len, i, childContext, item; childItems = ownerContext.childItems; len = childItems.length; for (i = 0; i < len; i++) { childContext = childItems[i]; item = childContext.target; totalWidth += childContext.props.width; // Only allow to be flexed if it's a resizable column if (!(item.fixed || item.resizable === false)) { // For forceFit, just use allocated width as the flex value, and the proportions // will end up the same whatever HeaderContainer width they are being forced into. item.flex = ownerContext.childItems[i].flex = childContext.props.width; item.width = null; childContext.widthModel = calculated; } } // Only need to loop back if the total column width is not already an exact fit return totalWidth !== ownerContext.props.width; }, getScrollbarAdjustment: function (ownerContext) { var me = this, state = ownerContext.state, grid = me.owner.grid, scrollbarAdjustment = state.scrollbarAdjustment; // If there is potential for a vertical scrollbar, then we start by assuming // we will need to reserve space for it. Unless, of course, there are no // records! if (scrollbarAdjustment === undefined) { scrollbarAdjustment = 0; if (grid.reserveScrollbar || (ownerContext.manageScrollbar && !grid.ownerGrid.layout.ownerContext.heightModel.shrinkWrap)) { scrollbarAdjustment = me.scrollbarWidth; } state.scrollbarAdjustment = scrollbarAdjustment; } return scrollbarAdjustment; }, /** * @private * Local getContainerSize implementation accounts for vertical scrollbar in the view. */ getContainerSize: function (ownerContext) { var me = this, got, needed, padding, gotWidth, gotHeight, width, height, result; if (me.owner.isRootHeader) { result = me.callParent([ ownerContext ]); if (result.gotWidth) { result.width -= me.getScrollbarAdjustment(ownerContext); } } else { padding = ownerContext.paddingContext.getPaddingInfo(); got = needed = 0; // The container size here has to be provided by the ColumnComponentLayout to // account for borders in its odd way. if (!ownerContext.widthModel.shrinkWrap) { ++needed; width = ownerContext.getProp('innerWidth'); gotWidth = (typeof width === 'number'); if (gotWidth) { ++got; width -= padding.width; if (width < 0) { width = 0; } } } if (!ownerContext.heightModel.shrinkWrap) { ++needed; height = ownerContext.getProp('innerHeight'); gotHeight = (typeof height === 'number'); if (gotHeight) { ++got; height -= padding.height; if (height < 0) { height = 0; } } } return { width: width, height: height, needed: needed, got: got, gotAll: got === needed, gotWidth: gotWidth, gotHeight: gotHeight }; } return result; }, publishInnerCtSize: function(ownerContext) { var me = this, owner = me.owner, cw = ownerContext.peek('contentWidth'), adjustment = 0; // Pass negative "reservedSpace", so that the innerCt gets *extra* size to accommodate the view's vertical scrollbar if (cw != null && owner.isRootHeader) { adjustment = -ownerContext.state.scrollbarAdjustment; } return me.callParent([ownerContext, adjustment]); } });
{'content_hash': 'e64ff27b1d7e0adb44115b1f6308fd65', 'timestamp': '', 'source': 'github', 'line_count': 392, 'max_line_length': 124, 'avg_line_length': 40.57397959183673, 'alnum_prop': 0.5450487268154668, 'repo_name': 'hirmerpl/FlexMash', 'id': '5a6c780257551a81a1cba73646e6172e4200d668', 'size': '15905', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'WebContent/extjs/ext-6.0.0/classic/classic/src/grid/ColumnLayout.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '21436272'}, {'name': 'HTML', 'bytes': '14290'}, {'name': 'Java', 'bytes': '136935'}, {'name': 'JavaScript', 'bytes': '15376176'}, {'name': 'PHP', 'bytes': '144867'}, {'name': 'Python', 'bytes': '5010'}, {'name': 'Ruby', 'bytes': '15630'}]}
require 'spec_helper' describe AttachmentsController, type: :controller do before :each do user = create(:user) session[:user_id] = user.id @page = create(:page, user: user) end describe 'POST#create' do it 'saves the valid attachment' do expect do post :create, params: { format: :js, attachment: attributes_for(:attachment), page_id: @page.slug } end.to change(Attachment, :count).by(1) end end describe 'DELETE#destroy' do it 'deletes the attachment' do attachment = create(:attachment, blog_record: @page) expect do delete :destroy, params: { format: :js, page_id: @page.slug, id: attachment.id } end.to change(Attachment, :count).by(-1) end end end
{'content_hash': '5558a7f7ee2477165d8043bdae41d73a', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 107, 'avg_line_length': 26.642857142857142, 'alnum_prop': 0.6447721179624665, 'repo_name': 'ksevelyar/dobroserver', 'id': '28dfa1136c0d4af18562a99624d01f0bacc62ed3', 'size': '777', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/controllers/attachments_controller_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '69287'}, {'name': 'CoffeeScript', 'bytes': '2178'}, {'name': 'HTML', 'bytes': '18574'}, {'name': 'JavaScript', 'bytes': '1693'}, {'name': 'Ruby', 'bytes': '84123'}, {'name': 'Shell', 'bytes': '1458'}]}
class AppListControllerDelegate; class Profile; namespace extensions { class Extension; } // Shows the chrome app information dialog box. void ShowAppInfoDialog(AppListControllerDelegate* app_list_controller_delegate, Profile* profile, const extensions::Extension* app); #endif // CHROME_BROWSER_UI_APPS_APP_INFO_DIALOG_H_
{'content_hash': '1b5588ba48a87f7203c99602efb080b8', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 79, 'avg_line_length': 28.692307692307693, 'alnum_prop': 0.7024128686327078, 'repo_name': 'AICP/external_chromium_org', 'id': 'fc36b88cc857b45886aad9417e850869bb4d234c', 'size': '640', 'binary': False, 'copies': '14', 'ref': 'refs/heads/lp5.0', 'path': 'chrome/browser/ui/apps/app_info_dialog.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Assembly', 'bytes': '24741'}, {'name': 'C', 'bytes': '5543105'}, {'name': 'C++', 'bytes': '199178257'}, {'name': 'CSS', 'bytes': '942505'}, {'name': 'Java', 'bytes': '5192594'}, {'name': 'JavaScript', 'bytes': '11002659'}, {'name': 'Makefile', 'bytes': '20865646'}, {'name': 'Objective-C', 'bytes': '793237'}, {'name': 'Objective-C++', 'bytes': '7082902'}, {'name': 'PHP', 'bytes': '61320'}, {'name': 'Perl', 'bytes': '69392'}, {'name': 'Python', 'bytes': '6310377'}, {'name': 'Rebol', 'bytes': '262'}, {'name': 'Shell', 'bytes': '464327'}, {'name': 'Standard ML', 'bytes': '1589'}, {'name': 'XSLT', 'bytes': '418'}, {'name': 'nesC', 'bytes': '15206'}]}
require_relative 'helper' prepare do Theme.setup do |c| c.component_path = './test/dummy/components' end Cuba.reset! Cuba.plugin Theme Cuba.define do on 'header' do menu = { 'Home' => { href: '/', links: { 'Sub Menu' => { href: '/sub_menu' } } }, 'Test' => { href: '/test' } } res.write component(:header, menu: menu).render end end end scope 'theme' do test 'component' do _, _, resp = Cuba.call({ 'PATH_INFO' => '/header', 'SCRIPT_NAME' => '/header', 'REQUEST_METHOD' => 'GET', 'rack.input' => {} }) body = resp.join assert body[/Home/] assert body[/Test/] assert body[/\/test/] assert body[/Sub Menu/] assert body[/\/sub_menu/] end test 'events' do _, _, resp = Cuba.call({ 'PATH_INFO' => '/components', 'SCRIPT_NAME' => '/components', 'REQUEST_METHOD' => 'GET', 'rack.input' => {}, 'QUERY_STRING' => 'component_name=some_component&component_event=test' }) body = resp.join assert body['this is from the header component'] end end
{'content_hash': '4211d4bd2c997a330de6187f4d3af3bc', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 78, 'avg_line_length': 21.089285714285715, 'alnum_prop': 0.5088907705334462, 'repo_name': 'cj/theme', 'id': 'd5a35905cd904ad0f0210597acb0e97e956f9675', 'size': '1181', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/theme_test.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '21653'}]}
/* Includes ------------------------------------------------------------------*/ #include "stm32f30x_usart.h" #include "stm32f30x_rcc.h" /** @addtogroup STM32F30x_StdPeriph_Driver * @{ */ /** @defgroup USART * @brief USART driver modules * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /*!< USART CR1 register clear Mask ((~(uint32_t)0xFFFFE6F3)) */ #define CR1_CLEAR_MASK ((uint32_t)(USART_CR1_M | USART_CR1_PCE | \ USART_CR1_PS | USART_CR1_TE | \ USART_CR1_RE)) /*!< USART CR2 register clock bits clear Mask ((~(uint32_t)0xFFFFF0FF)) */ #define CR2_CLOCK_CLEAR_MASK ((uint32_t)(USART_CR2_CLKEN | USART_CR2_CPOL | \ USART_CR2_CPHA | USART_CR2_LBCL)) /*!< USART CR3 register clear Mask ((~(uint32_t)0xFFFFFCFF)) */ #define CR3_CLEAR_MASK ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE)) /*!< USART Interrupts mask */ #define IT_MASK ((uint32_t)0x000000FF) /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @defgroup USART_Private_Functions * @{ */ /** @defgroup USART_Group1 Initialization and Configuration functions * @brief Initialization and Configuration functions * @verbatim =============================================================================== ##### Initialization and Configuration functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to initialize the USART in asynchronous and in synchronous modes. (+) For the asynchronous mode only these parameters can be configured: (++) Baud Rate. (++) Word Length. (++) Stop Bit. (++) Parity: If the parity is enabled, then the MSB bit of the data written in the data register is transmitted but is changed by the parity bit. Depending on the frame length defined by the M bit (8-bits or 9-bits), the possible USART frame formats are as listed in the following table: [..] +-------------------------------------------------------------+ | M bit | PCE bit | USART frame | |---------------------|---------------------------------------| | 0 | 0 | | SB | 8 bit data | STB | | |---------|-----------|---------------------------------------| | 0 | 1 | | SB | 7 bit data | PB | STB | | |---------|-----------|---------------------------------------| | 1 | 0 | | SB | 9 bit data | STB | | |---------|-----------|---------------------------------------| | 1 | 1 | | SB | 8 bit data | PB | STB | | +-------------------------------------------------------------+ [..] (++) Hardware flow control. (++) Receiver/transmitter modes. [..] The USART_Init() function follows the USART asynchronous configuration procedure(details for the procedure are available in reference manual. (+) For the synchronous mode in addition to the asynchronous mode parameters these parameters should be also configured: (++) USART Clock Enabled. (++) USART polarity. (++) USART phase. (++) USART LastBit. [..] These parameters can be configured using the USART_ClockInit() function. @endverbatim * @{ */ /** * @brief Deinitializes the USARTx peripheral registers to their default reset values. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @retval None */ void USART_DeInit(USART_TypeDef* USARTx) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); if (USARTx == USART1) { RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, ENABLE); RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, DISABLE); } else if (USARTx == USART2) { RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, DISABLE); } else if (USARTx == USART3) { RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3, DISABLE); } else if (USARTx == UART4) { RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART4, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART4, DISABLE); } else { if (USARTx == UART5) { RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART5, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART5, DISABLE); } } } /** * @brief Initializes the USARTx peripheral according to the specified * parameters in the USART_InitStruct . * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_InitStruct: pointer to a USART_InitTypeDef structure * that contains the configuration information for the specified USART peripheral. * @retval None */ void USART_Init(USART_TypeDef* USARTx, USART_InitTypeDef* USART_InitStruct) { uint32_t divider = 0, apbclock = 0, tmpreg = 0; RCC_ClocksTypeDef RCC_ClocksStatus; /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_BAUDRATE(USART_InitStruct->USART_BaudRate)); assert_param(IS_USART_WORD_LENGTH(USART_InitStruct->USART_WordLength)); assert_param(IS_USART_STOPBITS(USART_InitStruct->USART_StopBits)); assert_param(IS_USART_PARITY(USART_InitStruct->USART_Parity)); assert_param(IS_USART_MODE(USART_InitStruct->USART_Mode)); assert_param(IS_USART_HARDWARE_FLOW_CONTROL(USART_InitStruct->USART_HardwareFlowControl)); /* Disable USART */ USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_UE); /*---------------------------- USART CR2 Configuration -----------------------*/ tmpreg = USARTx->CR2; /* Clear STOP[13:12] bits */ tmpreg &= (uint32_t)~((uint32_t)USART_CR2_STOP); /* Configure the USART Stop Bits, Clock, CPOL, CPHA and LastBit ------------*/ /* Set STOP[13:12] bits according to USART_StopBits value */ tmpreg |= (uint32_t)USART_InitStruct->USART_StopBits; /* Write to USART CR2 */ USARTx->CR2 = tmpreg; /*---------------------------- USART CR1 Configuration -----------------------*/ tmpreg = USARTx->CR1; /* Clear M, PCE, PS, TE and RE bits */ tmpreg &= (uint32_t)~((uint32_t)CR1_CLEAR_MASK); /* Configure the USART Word Length, Parity and mode ----------------------- */ /* Set the M bits according to USART_WordLength value */ /* Set PCE and PS bits according to USART_Parity value */ /* Set TE and RE bits according to USART_Mode value */ tmpreg |= (uint32_t)USART_InitStruct->USART_WordLength | USART_InitStruct->USART_Parity | USART_InitStruct->USART_Mode; /* Write to USART CR1 */ USARTx->CR1 = tmpreg; /*---------------------------- USART CR3 Configuration -----------------------*/ tmpreg = USARTx->CR3; /* Clear CTSE and RTSE bits */ tmpreg &= (uint32_t)~((uint32_t)CR3_CLEAR_MASK); /* Configure the USART HFC -------------------------------------------------*/ /* Set CTSE and RTSE bits according to USART_HardwareFlowControl value */ tmpreg |= USART_InitStruct->USART_HardwareFlowControl; /* Write to USART CR3 */ USARTx->CR3 = tmpreg; /*---------------------------- USART BRR Configuration -----------------------*/ /* Configure the USART Baud Rate -------------------------------------------*/ RCC_GetClocksFreq(&RCC_ClocksStatus); if (USARTx == USART1) { apbclock = RCC_ClocksStatus.USART1CLK_Frequency; } else if (USARTx == USART2) { apbclock = RCC_ClocksStatus.USART2CLK_Frequency; } else if (USARTx == USART3) { apbclock = RCC_ClocksStatus.USART3CLK_Frequency; } else if (USARTx == UART4) { apbclock = RCC_ClocksStatus.UART4CLK_Frequency; } else { apbclock = RCC_ClocksStatus.UART5CLK_Frequency; } /* Determine the integer part */ if ((USARTx->CR1 & USART_CR1_OVER8) != 0) { /* (divider * 10) computing in case Oversampling mode is 8 Samples */ divider = (uint32_t)((2 * apbclock) / (USART_InitStruct->USART_BaudRate)); tmpreg = (uint32_t)((2 * apbclock) % (USART_InitStruct->USART_BaudRate)); } else /* if ((USARTx->CR1 & CR1_OVER8_Set) == 0) */ { /* (divider * 10) computing in case Oversampling mode is 16 Samples */ divider = (uint32_t)((apbclock) / (USART_InitStruct->USART_BaudRate)); tmpreg = (uint32_t)((apbclock) % (USART_InitStruct->USART_BaudRate)); } /* round the divider : if fractional part i greater than 0.5 increment divider */ if (tmpreg >= (USART_InitStruct->USART_BaudRate) / 2) { divider++; } /* Implement the divider in case Oversampling mode is 8 Samples */ if ((USARTx->CR1 & USART_CR1_OVER8) != 0) { /* get the LSB of divider and shift it to the right by 1 bit */ tmpreg = (divider & (uint16_t)0x000F) >> 1; /* update the divider value */ divider = (divider & (uint16_t)0xFFF0) | tmpreg; } /* Write to USART BRR */ USARTx->BRR = (uint16_t)divider; } /** * @brief Fills each USART_InitStruct member with its default value. * @param USART_InitStruct: pointer to a USART_InitTypeDef structure * which will be initialized. * @retval None */ void USART_StructInit(USART_InitTypeDef* USART_InitStruct) { /* USART_InitStruct members default value */ USART_InitStruct->USART_BaudRate = 9600; USART_InitStruct->USART_WordLength = USART_WordLength_8b; USART_InitStruct->USART_StopBits = USART_StopBits_1; USART_InitStruct->USART_Parity = USART_Parity_No ; USART_InitStruct->USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_InitStruct->USART_HardwareFlowControl = USART_HardwareFlowControl_None; } /** * @brief Initializes the USARTx peripheral Clock according to the * specified parameters in the USART_ClockInitStruct. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3. * @param USART_ClockInitStruct: pointer to a USART_ClockInitTypeDef * structure that contains the configuration information for the specified * USART peripheral. * @retval None */ void USART_ClockInit(USART_TypeDef* USARTx, USART_ClockInitTypeDef* USART_ClockInitStruct) { uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_USART_123_PERIPH(USARTx)); assert_param(IS_USART_CLOCK(USART_ClockInitStruct->USART_Clock)); assert_param(IS_USART_CPOL(USART_ClockInitStruct->USART_CPOL)); assert_param(IS_USART_CPHA(USART_ClockInitStruct->USART_CPHA)); assert_param(IS_USART_LASTBIT(USART_ClockInitStruct->USART_LastBit)); /*---------------------------- USART CR2 Configuration -----------------------*/ tmpreg = USARTx->CR2; /* Clear CLKEN, CPOL, CPHA, LBCL and SSM bits */ tmpreg &= (uint32_t)~((uint32_t)CR2_CLOCK_CLEAR_MASK); /* Configure the USART Clock, CPOL, CPHA, LastBit and SSM ------------*/ /* Set CLKEN bit according to USART_Clock value */ /* Set CPOL bit according to USART_CPOL value */ /* Set CPHA bit according to USART_CPHA value */ /* Set LBCL bit according to USART_LastBit value */ tmpreg |= (uint32_t)(USART_ClockInitStruct->USART_Clock | USART_ClockInitStruct->USART_CPOL | USART_ClockInitStruct->USART_CPHA | USART_ClockInitStruct->USART_LastBit); /* Write to USART CR2 */ USARTx->CR2 = tmpreg; } /** * @brief Fills each USART_ClockInitStruct member with its default value. * @param USART_ClockInitStruct: pointer to a USART_ClockInitTypeDef * structure which will be initialized. * @retval None */ void USART_ClockStructInit(USART_ClockInitTypeDef* USART_ClockInitStruct) { /* USART_ClockInitStruct members default value */ USART_ClockInitStruct->USART_Clock = USART_Clock_Disable; USART_ClockInitStruct->USART_CPOL = USART_CPOL_Low; USART_ClockInitStruct->USART_CPHA = USART_CPHA_1Edge; USART_ClockInitStruct->USART_LastBit = USART_LastBit_Disable; } /** * @brief Enables or disables the specified USART peripheral. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the USARTx peripheral. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_Cmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected USART by setting the UE bit in the CR1 register */ USARTx->CR1 |= USART_CR1_UE; } else { /* Disable the selected USART by clearing the UE bit in the CR1 register */ USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_UE); } } /** * @brief Enables or disables the USART's transmitter or receiver. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_Direction: specifies the USART direction. * This parameter can be any combination of the following values: * @arg USART_Mode_Tx: USART Transmitter * @arg USART_Mode_Rx: USART Receiver * @param NewState: new state of the USART transfer direction. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_DirectionModeCmd(USART_TypeDef* USARTx, uint32_t USART_DirectionMode, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_MODE(USART_DirectionMode)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the USART's transfer interface by setting the TE and/or RE bits in the USART CR1 register */ USARTx->CR1 |= USART_DirectionMode; } else { /* Disable the USART's transfer interface by clearing the TE and/or RE bits in the USART CR3 register */ USARTx->CR1 &= (uint32_t)~USART_DirectionMode; } } /** * @brief Enables or disables the USART's 8x oversampling mode. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the USART 8x oversampling mode. * This parameter can be: ENABLE or DISABLE. * @note * This function has to be called before calling USART_Init() * function in order to have correct baudrate Divider value. * @retval None */ void USART_OverSampling8Cmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the 8x Oversampling mode by setting the OVER8 bit in the CR1 register */ USARTx->CR1 |= USART_CR1_OVER8; } else { /* Disable the 8x Oversampling mode by clearing the OVER8 bit in the CR1 register */ USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_OVER8); } } /** * @brief Enables or disables the USART's one bit sampling method. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the USART one bit sampling method. * This parameter can be: ENABLE or DISABLE. * @note * This function has to be called before calling USART_Cmd() function. * @retval None */ void USART_OneBitMethodCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the one bit method by setting the ONEBITE bit in the CR3 register */ USARTx->CR3 |= USART_CR3_ONEBIT; } else { /* Disable the one bit method by clearing the ONEBITE bit in the CR3 register */ USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_ONEBIT); } } /** * @brief Enables or disables the USART's most significant bit first * transmitted/received following the start bit. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the USART most significant bit first * transmitted/received following the start bit. * This parameter can be: ENABLE or DISABLE. * @note * This function has to be called before calling USART_Cmd() function. * @retval None */ void USART_MSBFirstCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the most significant bit first transmitted/received following the start bit by setting the MSBFIRST bit in the CR2 register */ USARTx->CR2 |= USART_CR2_MSBFIRST; } else { /* Disable the most significant bit first transmitted/received following the start bit by clearing the MSBFIRST bit in the CR2 register */ USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_MSBFIRST); } } /** * @brief Enables or disables the binary data inversion. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new defined levels for the USART data. * This parameter can be: ENABLE or DISABLE. * @arg ENABLE: Logical data from the data register are send/received in negative * logic. (1=L, 0=H). The parity bit is also inverted. * @arg DISABLE: Logical data from the data register are send/received in positive * logic. (1=H, 0=L) * @note * This function has to be called before calling USART_Cmd() function. * @retval None */ void USART_DataInvCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the binary data inversion feature by setting the DATAINV bit in the CR2 register */ USARTx->CR2 |= USART_CR2_DATAINV; } else { /* Disable the binary data inversion feature by clearing the DATAINV bit in the CR2 register */ USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_DATAINV); } } /** * @brief Enables or disables the Pin(s) active level inversion. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_InvPin: specifies the USART pin(s) to invert. * This parameter can be any combination of the following values: * @arg USART_InvPin_Tx: USART Tx pin active level inversion. * @arg USART_InvPin_Rx: USART Rx pin active level inversion. * @param NewState: new active level status for the USART pin(s). * This parameter can be: ENABLE or DISABLE. * - ENABLE: pin(s) signal values are inverted (Vdd =0, Gnd =1). * - DISABLE: pin(s) signal works using the standard logic levels (Vdd =1, Gnd =0). * @note * This function has to be called before calling USART_Cmd() function. * @retval None */ void USART_InvPinCmd(USART_TypeDef* USARTx, uint32_t USART_InvPin, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_INVERSTION_PIN(USART_InvPin)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the active level inversion for selected pins by setting the TXINV and/or RXINV bits in the USART CR2 register */ USARTx->CR2 |= USART_InvPin; } else { /* Disable the active level inversion for selected requests by clearing the TXINV and/or RXINV bits in the USART CR2 register */ USARTx->CR2 &= (uint32_t)~USART_InvPin; } } /** * @brief Enables or disables the swap Tx/Rx pins. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the USARTx TX/RX pins pinout. * This parameter can be: ENABLE or DISABLE. * @arg ENABLE: The TX and RX pins functions are swapped. * @arg DISABLE: TX/RX pins are used as defined in standard pinout * @note * This function has to be called before calling USART_Cmd() function. * @retval None */ void USART_SWAPPinCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the SWAP feature by setting the SWAP bit in the CR2 register */ USARTx->CR2 |= USART_CR2_SWAP; } else { /* Disable the SWAP feature by clearing the SWAP bit in the CR2 register */ USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_SWAP); } } /** * @brief Enables or disables the receiver Time Out feature. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the USARTx receiver Time Out. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_ReceiverTimeOutCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the receiver time out feature by setting the RTOEN bit in the CR2 register */ USARTx->CR2 |= USART_CR2_RTOEN; } else { /* Disable the receiver time out feature by clearing the RTOEN bit in the CR2 register */ USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_RTOEN); } } /** * @brief Sets the receiver Time Out value. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_ReceiverTimeOut: specifies the Receiver Time Out value. * @retval None */ void USART_SetReceiverTimeOut(USART_TypeDef* USARTx, uint32_t USART_ReceiverTimeOut) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_TIMEOUT(USART_ReceiverTimeOut)); /* Clear the receiver Time Out value by clearing the RTO[23:0] bits in the RTOR register */ USARTx->RTOR &= (uint32_t)~((uint32_t)USART_RTOR_RTO); /* Set the receiver Time Out value by setting the RTO[23:0] bits in the RTOR register */ USARTx->RTOR |= USART_ReceiverTimeOut; } /** * @brief Sets the system clock prescaler. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_Prescaler: specifies the prescaler clock. * @note * This function has to be called before calling USART_Cmd() function. * @retval None */ void USART_SetPrescaler(USART_TypeDef* USARTx, uint8_t USART_Prescaler) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); /* Clear the USART prescaler */ USARTx->GTPR &= USART_GTPR_GT; /* Set the USART prescaler */ USARTx->GTPR |= USART_Prescaler; } /** * @} */ /** @defgroup USART_Group2 STOP Mode functions * @brief STOP Mode functions * @verbatim =============================================================================== ##### STOP Mode functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage WakeUp from STOP mode. [..] The USART is able to WakeUp from Stop Mode if USART clock is set to HSI or LSI. [..] The WakeUp source is configured by calling USART_StopModeWakeUpSourceConfig() function. [..] After configuring the source of WakeUp and before entering in Stop Mode USART_STOPModeCmd() function should be called to allow USART WakeUp. @endverbatim * @{ */ /** * @brief Enables or disables the specified USART peripheral in STOP Mode. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the USARTx peripheral state in stop mode. * This parameter can be: ENABLE or DISABLE. * @note * This function has to be called when USART clock is set to HSI or LSE. * @retval None */ void USART_STOPModeCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected USART in STOP mode by setting the UESM bit in the CR1 register */ USARTx->CR1 |= USART_CR1_UESM; } else { /* Disable the selected USART in STOP mode by clearing the UE bit in the CR1 register */ USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_UESM); } } /** * @brief Selects the USART WakeUp method form stop mode. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_WakeUp: specifies the selected USART wakeup method. * This parameter can be one of the following values: * @arg USART_WakeUpSource_AddressMatch: WUF active on address match. * @arg USART_WakeUpSource_StartBit: WUF active on Start bit detection. * @arg USART_WakeUpSource_RXNE: WUF active on RXNE. * @note * This function has to be called before calling USART_Cmd() function. * @retval None */ void USART_StopModeWakeUpSourceConfig(USART_TypeDef* USARTx, uint32_t USART_WakeUpSource) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_STOPMODE_WAKEUPSOURCE(USART_WakeUpSource)); USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_WUS); USARTx->CR3 |= USART_WakeUpSource; } /** * @} */ /** @defgroup USART_Group3 AutoBaudRate functions * @brief AutoBaudRate functions * @verbatim =============================================================================== ##### AutoBaudRate functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the AutoBaudRate detections. [..] Before Enabling AutoBaudRate detection using USART_AutoBaudRateCmd () The character patterns used to calculate baudrate must be chosen by calling USART_AutoBaudRateConfig() function. These function take as parameter : (#)USART_AutoBaudRate_StartBit : any character starting with a bit 1. (#)USART_AutoBaudRate_FallingEdge : any character starting with a 10xx bit pattern. [..] At any later time, another request for AutoBaudRate detection can be performed using USART_RequestCmd() function. [..] The AutoBaudRate detection is monitored by the status of ABRF flag which indicate that the AutoBaudRate detection is completed. In addition to ABRF flag, the ABRE flag indicate that this procedure is completed without success. USART_GetFlagStatus () function should be used to monitor the status of these flags. @endverbatim * @{ */ /** * @brief Enables or disables the Auto Baud Rate. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the USARTx auto baud rate. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_AutoBaudRateCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the auto baud rate feature by setting the ABREN bit in the CR2 register */ USARTx->CR2 |= USART_CR2_ABREN; } else { /* Disable the auto baud rate feature by clearing the ABREN bit in the CR2 register */ USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_ABREN); } } /** * @brief Selects the USART auto baud rate method. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_AutoBaudRate: specifies the selected USART auto baud rate method. * This parameter can be one of the following values: * @arg USART_AutoBaudRate_StartBit: Start Bit duration measurement. * @arg USART_AutoBaudRate_FallingEdge: Falling edge to falling edge measurement. * @arg USART_AutoBaudRate_0x7FFrame: 0x7F frame. * @arg USART_AutoBaudRate_0x55Frame: 0x55 frame. * @note * This function has to be called before calling USART_Cmd() function. * @retval None */ void USART_AutoBaudRateConfig(USART_TypeDef* USARTx, uint32_t USART_AutoBaudRate) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_AUTOBAUDRATE_MODE(USART_AutoBaudRate)); USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_ABRMODE); USARTx->CR2 |= USART_AutoBaudRate; } /** * @} */ /** @defgroup USART_Group4 Data transfers functions * @brief Data transfers functions * @verbatim =============================================================================== ##### Data transfers functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the USART data transfers. [..] During an USART reception, data shifts in least significant bit first through the RX pin. When a transmission is taking place, a write instruction to the USART_TDR register stores the data in the shift register. [..] The read access of the USART_RDR register can be done using the USART_ReceiveData() function and returns the RDR value. Whereas a write access to the USART_TDR can be done using USART_SendData() function and stores the written data into TDR. @endverbatim * @{ */ /** * @brief Transmits single data through the USARTx peripheral. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param Data: the data to transmit. * @retval None */ void USART_SendData(USART_TypeDef* USARTx, uint16_t Data) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_DATA(Data)); /* Transmit Data */ USARTx->TDR = (Data & (uint16_t)0x01FF); } /** * @brief Returns the most recent received data by the USARTx peripheral. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @retval The received data. */ uint16_t USART_ReceiveData(USART_TypeDef* USARTx) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); /* Receive Data */ return (uint16_t)(USARTx->RDR & (uint16_t)0x01FF); } /** * @} */ /** @defgroup USART_Group5 MultiProcessor Communication functions * @brief Multi-Processor Communication functions * @verbatim =============================================================================== ##### Multi-Processor Communication functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the USART multiprocessor communication. [..] For instance one of the USARTs can be the master, its TX output is connected to the RX input of the other USART. The others are slaves, their respective TX outputs are logically ANDed together and connected to the RX input of the master. USART multiprocessor communication is possible through the following procedure: (#) Program the Baud rate, Word length = 9 bits, Stop bits, Parity, Mode transmitter or Mode receiver and hardware flow control values using the USART_Init() function. (#) Configures the USART address using the USART_SetAddress() function. (#) Configures the wake up methode (USART_WakeUp_IdleLine or USART_WakeUp_AddressMark) using USART_WakeUpConfig() function only for the slaves. (#) Enable the USART using the USART_Cmd() function. (#) Enter the USART slaves in mute mode using USART_ReceiverWakeUpCmd() function. [..] The USART Slave exit from mute mode when receive the wake up condition. @endverbatim * @{ */ /** * @brief Sets the address of the USART node. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_Address: Indicates the address of the USART node. * @retval None */ void USART_SetAddress(USART_TypeDef* USARTx, uint8_t USART_Address) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); /* Clear the USART address */ USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_ADD); /* Set the USART address node */ USARTx->CR2 |=((uint32_t)USART_Address << (uint32_t)0x18); } /** * @brief Enables or disables the USART's mute mode. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the USART mute mode. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_MuteModeCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the USART mute mode by setting the MME bit in the CR1 register */ USARTx->CR1 |= USART_CR1_MME; } else { /* Disable the USART mute mode by clearing the MME bit in the CR1 register */ USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_MME); } } /** * @brief Selects the USART WakeUp method from mute mode. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_WakeUp: specifies the USART wakeup method. * This parameter can be one of the following values: * @arg USART_WakeUp_IdleLine: WakeUp by an idle line detection * @arg USART_WakeUp_AddressMark: WakeUp by an address mark * @retval None */ void USART_MuteModeWakeUpConfig(USART_TypeDef* USARTx, uint32_t USART_WakeUp) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_MUTEMODE_WAKEUP(USART_WakeUp)); USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_WAKE); USARTx->CR1 |= USART_WakeUp; } /** * @brief Configure the the USART Address detection length. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_AddressLength: specifies the USART address length detection. * This parameter can be one of the following values: * @arg USART_AddressLength_4b: 4-bit address length detection * @arg USART_AddressLength_7b: 7-bit address length detection * @retval None */ void USART_AddressDetectionConfig(USART_TypeDef* USARTx, uint32_t USART_AddressLength) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_ADDRESS_DETECTION(USART_AddressLength)); USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_ADDM7); USARTx->CR2 |= USART_AddressLength; } /** * @} */ /** @defgroup USART_Group6 LIN mode functions * @brief LIN mode functions * @verbatim =============================================================================== ##### LIN mode functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the USART LIN Mode communication. [..] In LIN mode, 8-bit data format with 1 stop bit is required in accordance with the LIN standard. [..] Only this LIN Feature is supported by the USART IP: (+) LIN Master Synchronous Break send capability and LIN slave break detection capability : 13-bit break generation and 10/11 bit break detection. [..] USART LIN Master transmitter communication is possible through the following procedure: (#) Program the Baud rate, Word length = 8bits, Stop bits = 1bit, Parity, Mode transmitter or Mode receiver and hardware flow control values using the USART_Init() function. (#) Enable the LIN mode using the USART_LINCmd() function. (#) Enable the USART using the USART_Cmd() function. (#) Send the break character using USART_SendBreak() function. [..] USART LIN Master receiver communication is possible through the following procedure: (#) Program the Baud rate, Word length = 8bits, Stop bits = 1bit, Parity, Mode transmitter or Mode receiver and hardware flow control values using the USART_Init() function. (#) Configures the break detection length using the USART_LINBreakDetectLengthConfig() function. (#) Enable the LIN mode using the USART_LINCmd() function. (#) Enable the USART using the USART_Cmd() function. [..] (@) In LIN mode, the following bits must be kept cleared: (+@) CLKEN in the USART_CR2 register. (+@) STOP[1:0], SCEN, HDSEL and IREN in the USART_CR3 register. @endverbatim * @{ */ /** * @brief Sets the USART LIN Break detection length. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_LINBreakDetectLength: specifies the LIN break detection length. * This parameter can be one of the following values: * @arg USART_LINBreakDetectLength_10b: 10-bit break detection * @arg USART_LINBreakDetectLength_11b: 11-bit break detection * @retval None */ void USART_LINBreakDetectLengthConfig(USART_TypeDef* USARTx, uint32_t USART_LINBreakDetectLength) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_LIN_BREAK_DETECT_LENGTH(USART_LINBreakDetectLength)); USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_LBDL); USARTx->CR2 |= USART_LINBreakDetectLength; } /** * @brief Enables or disables the USART's LIN mode. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the USART LIN mode. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_LINCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the LIN mode by setting the LINEN bit in the CR2 register */ USARTx->CR2 |= USART_CR2_LINEN; } else { /* Disable the LIN mode by clearing the LINEN bit in the CR2 register */ USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_LINEN); } } /** * @} */ /** @defgroup USART_Group7 Halfduplex mode function * @brief Half-duplex mode function * @verbatim =============================================================================== ##### Half-duplex mode function ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the USART Half-duplex communication. [..] The USART can be configured to follow a single-wire half-duplex protocol where the TX and RX lines are internally connected. [..] USART Half duplex communication is possible through the following procedure: (#) Program the Baud rate, Word length, Stop bits, Parity, Mode transmitter or Mode receiver and hardware flow control values using the USART_Init() function. (#) Configures the USART address using the USART_SetAddress() function. (#) Enable the half duplex mode using USART_HalfDuplexCmd() function. (#) Enable the USART using the USART_Cmd() function. [..] (@) The RX pin is no longer used. (@) In Half-duplex mode the following bits must be kept cleared: (+@) LINEN and CLKEN bits in the USART_CR2 register. (+@) SCEN and IREN bits in the USART_CR3 register. @endverbatim * @{ */ /** * @brief Enables or disables the USART's Half Duplex communication. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the USART Communication. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_HalfDuplexCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the Half-Duplex mode by setting the HDSEL bit in the CR3 register */ USARTx->CR3 |= USART_CR3_HDSEL; } else { /* Disable the Half-Duplex mode by clearing the HDSEL bit in the CR3 register */ USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_HDSEL); } } /** * @} */ /** @defgroup USART_Group8 Smartcard mode functions * @brief Smartcard mode functions * @verbatim =============================================================================== ##### Smartcard mode functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the USART Smartcard communication. [..] The Smartcard interface is designed to support asynchronous protocol Smartcards as defined in the ISO 7816-3 standard. The USART can provide a clock to the smartcard through the SCLK output. In smartcard mode, SCLK is not associated to the communication but is simply derived from the internal peripheral input clock through a 5-bit prescaler. [..] Smartcard communication is possible through the following procedure: (#) Configures the Smartcard Prsecaler using the USART_SetPrescaler() function. (#) Configures the Smartcard Guard Time using the USART_SetGuardTime() function. (#) Program the USART clock using the USART_ClockInit() function as following: (++) USART Clock enabled. (++) USART CPOL Low. (++) USART CPHA on first edge. (++) USART Last Bit Clock Enabled. (#) Program the Smartcard interface using the USART_Init() function as following: (++) Word Length = 9 Bits. (++) 1.5 Stop Bit. (++) Even parity. (++) BaudRate = 12096 baud. (++) Hardware flow control disabled (RTS and CTS signals). (++) Tx and Rx enabled (#) Optionally you can enable the parity error interrupt using the USART_ITConfig() function. (#) Enable the Smartcard NACK using the USART_SmartCardNACKCmd() function. (#) Enable the Smartcard interface using the USART_SmartCardCmd() function. (#) Enable the USART using the USART_Cmd() function. [..] Please refer to the ISO 7816-3 specification for more details. [..] (@) It is also possible to choose 0.5 stop bit for receiving but it is recommended to use 1.5 stop bits for both transmitting and receiving to avoid switching between the two configurations. (@) In smartcard mode, the following bits must be kept cleared: (+@) LINEN bit in the USART_CR2 register. (+@) HDSEL and IREN bits in the USART_CR3 register. @endverbatim * @{ */ /** * @brief Sets the specified USART guard time. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3. * @param USART_GuardTime: specifies the guard time. * @retval None */ void USART_SetGuardTime(USART_TypeDef* USARTx, uint8_t USART_GuardTime) { /* Check the parameters */ assert_param(IS_USART_123_PERIPH(USARTx)); /* Clear the USART Guard time */ USARTx->GTPR &= USART_GTPR_PSC; /* Set the USART guard time */ USARTx->GTPR |= (uint16_t)((uint16_t)USART_GuardTime << 0x08); } /** * @brief Enables or disables the USART's Smart Card mode. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3. * @param NewState: new state of the Smart Card mode. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_SmartCardCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_123_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the SC mode by setting the SCEN bit in the CR3 register */ USARTx->CR3 |= USART_CR3_SCEN; } else { /* Disable the SC mode by clearing the SCEN bit in the CR3 register */ USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_SCEN); } } /** * @brief Enables or disables NACK transmission. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3. * @param NewState: new state of the NACK transmission. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_SmartCardNACKCmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_123_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the NACK transmission by setting the NACK bit in the CR3 register */ USARTx->CR3 |= USART_CR3_NACK; } else { /* Disable the NACK transmission by clearing the NACK bit in the CR3 register */ USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_NACK); } } /** * @brief Sets the Smart Card number of retries in transmit and receive. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3. * @param USART_AutoCount: specifies the Smart Card auto retry count. * @retval None */ void USART_SetAutoRetryCount(USART_TypeDef* USARTx, uint8_t USART_AutoCount) { /* Check the parameters */ assert_param(IS_USART_123_PERIPH(USARTx)); assert_param(IS_USART_AUTO_RETRY_COUNTER(USART_AutoCount)); /* Clear the USART auto retry count */ USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_SCARCNT); /* Set the USART auto retry count*/ USARTx->CR3 |= (uint32_t)((uint32_t)USART_AutoCount << 0x11); } /** * @brief Sets the Smart Card Block length. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3. * @param USART_BlockLength: specifies the Smart Card block length. * @retval None */ void USART_SetBlockLength(USART_TypeDef* USARTx, uint8_t USART_BlockLength) { /* Check the parameters */ assert_param(IS_USART_123_PERIPH(USARTx)); /* Clear the Smart card block length */ USARTx->RTOR &= (uint32_t)~((uint32_t)USART_RTOR_BLEN); /* Set the Smart Card block length */ USARTx->RTOR |= (uint32_t)((uint32_t)USART_BlockLength << 0x18); } /** * @} */ /** @defgroup USART_Group9 IrDA mode functions * @brief IrDA mode functions * @verbatim =============================================================================== ##### IrDA mode functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the USART IrDA communication. [..] IrDA is a half duplex communication protocol. If the Transmitter is busy, any data on the IrDA receive line will be ignored by the IrDA decoder and if the Receiver is busy, data on the TX from the USART to IrDA will not be encoded by IrDA. While receiving data, transmission should be avoided as the data to be transmitted could be corrupted. [..] IrDA communication is possible through the following procedure: (#) Program the Baud rate, Word length = 8 bits, Stop bits, Parity, Transmitter/Receiver modes and hardware flow control values using the USART_Init() function. (#) Configures the IrDA pulse width by configuring the prescaler using the USART_SetPrescaler() function. (#) Configures the IrDA USART_IrDAMode_LowPower or USART_IrDAMode_Normal mode using the USART_IrDAConfig() function. (#) Enable the IrDA using the USART_IrDACmd() function. (#) Enable the USART using the USART_Cmd() function. [..] (@) A pulse of width less than two and greater than one PSC period(s) may or may not be rejected. (@) The receiver set up time should be managed by software. The IrDA physical layer specification specifies a minimum of 10 ms delay between transmission and reception (IrDA is a half duplex protocol). (@) In IrDA mode, the following bits must be kept cleared: (+@) LINEN, STOP and CLKEN bits in the USART_CR2 register. (+@) SCEN and HDSEL bits in the USART_CR3 register. @endverbatim * @{ */ /** * @brief Configures the USART's IrDA interface. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_IrDAMode: specifies the IrDA mode. * This parameter can be one of the following values: * @arg USART_IrDAMode_LowPower * @arg USART_IrDAMode_Normal * @retval None */ void USART_IrDAConfig(USART_TypeDef* USARTx, uint32_t USART_IrDAMode) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_IRDA_MODE(USART_IrDAMode)); USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_IRLP); USARTx->CR3 |= USART_IrDAMode; } /** * @brief Enables or disables the USART's IrDA interface. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the IrDA mode. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_IrDACmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the IrDA mode by setting the IREN bit in the CR3 register */ USARTx->CR3 |= USART_CR3_IREN; } else { /* Disable the IrDA mode by clearing the IREN bit in the CR3 register */ USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_IREN); } } /** * @} */ /** @defgroup USART_Group10 RS485 mode function * @brief RS485 mode function * @verbatim =============================================================================== ##### RS485 mode functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to manage the USART RS485 flow control. [..] RS485 flow control (Driver enable feature) handling is possible through the following procedure: (#) Program the Baud rate, Word length = 8 bits, Stop bits, Parity, Transmitter/Receiver modes and hardware flow control values using the USART_Init() function. (#) Enable the Driver Enable using the USART_DECmd() function. (#) Configures the Driver Enable polarity using the USART_DEPolarityConfig() function. (#) Configures the Driver Enable assertion time using USART_SetDEAssertionTime() function and deassertion time using the USART_SetDEDeassertionTime() function. (#) Enable the USART using the USART_Cmd() function. [..] (@) The assertion and dessertion times are expressed in sample time units (1/8 or 1/16 bit time, depending on the oversampling rate). @endverbatim * @{ */ /** * @brief Enables or disables the USART's DE functionality. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param NewState: new state of the driver enable mode. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_DECmd(USART_TypeDef* USARTx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the DE functionality by setting the DEM bit in the CR3 register */ USARTx->CR3 |= USART_CR3_DEM; } else { /* Disable the DE functionality by clearing the DEM bit in the CR3 register */ USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DEM); } } /** * @brief Configures the USART's DE polarity * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_DEPolarity: specifies the DE polarity. * This parameter can be one of the following values: * @arg USART_DEPolarity_Low * @arg USART_DEPolarity_High * @retval None */ void USART_DEPolarityConfig(USART_TypeDef* USARTx, uint32_t USART_DEPolarity) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_DE_POLARITY(USART_DEPolarity)); USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DEP); USARTx->CR3 |= USART_DEPolarity; } /** * @brief Sets the specified RS485 DE assertion time * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_AssertionTime: specifies the time between the activation of the DE * signal and the beginning of the start bit * @retval None */ void USART_SetDEAssertionTime(USART_TypeDef* USARTx, uint32_t USART_DEAssertionTime) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_DE_ASSERTION_DEASSERTION_TIME(USART_DEAssertionTime)); /* Clear the DE assertion time */ USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_DEAT); /* Set the new value for the DE assertion time */ USARTx->CR1 |=((uint32_t)USART_DEAssertionTime << (uint32_t)0x15); } /** * @brief Sets the specified RS485 DE deassertion time * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_DeassertionTime: specifies the time between the middle of the last * stop bit in a transmitted message and the de-activation of the DE signal * @retval None */ void USART_SetDEDeassertionTime(USART_TypeDef* USARTx, uint32_t USART_DEDeassertionTime) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_DE_ASSERTION_DEASSERTION_TIME(USART_DEDeassertionTime)); /* Clear the DE deassertion time */ USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_DEDT); /* Set the new value for the DE deassertion time */ USARTx->CR1 |=((uint32_t)USART_DEDeassertionTime << (uint32_t)0x10); } /** * @} */ /** @defgroup USART_Group11 DMA transfers management functions * @brief DMA transfers management functions * @verbatim =============================================================================== ##### DMA transfers management functions ##### =============================================================================== [..] This section provides two functions that can be used only in DMA mode. [..] In DMA Mode, the USART communication can be managed by 2 DMA Channel requests: (#) USART_DMAReq_Tx: specifies the Tx buffer DMA transfer request. (#) USART_DMAReq_Rx: specifies the Rx buffer DMA transfer request. [..] In this Mode it is advised to use the following function: (+) void USART_DMACmd(USART_TypeDef* USARTx, uint16_t USART_DMAReq, FunctionalState NewState). @endverbatim * @{ */ /** * @brief Enables or disables the USART's DMA interface. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4. * @param USART_DMAReq: specifies the DMA request. * This parameter can be any combination of the following values: * @arg USART_DMAReq_Tx: USART DMA transmit request * @arg USART_DMAReq_Rx: USART DMA receive request * @param NewState: new state of the DMA Request sources. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_DMACmd(USART_TypeDef* USARTx, uint32_t USART_DMAReq, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_1234_PERIPH(USARTx)); assert_param(IS_USART_DMAREQ(USART_DMAReq)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the DMA transfer for selected requests by setting the DMAT and/or DMAR bits in the USART CR3 register */ USARTx->CR3 |= USART_DMAReq; } else { /* Disable the DMA transfer for selected requests by clearing the DMAT and/or DMAR bits in the USART CR3 register */ USARTx->CR3 &= (uint32_t)~USART_DMAReq; } } /** * @brief Enables or disables the USART's DMA interface when reception error occurs. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4. * @param USART_DMAOnError: specifies the DMA status in case of reception error. * This parameter can be any combination of the following values: * @arg USART_DMAOnError_Enable: DMA receive request enabled when the USART DMA * reception error is asserted. * @arg USART_DMAOnError_Disable: DMA receive request disabled when the USART DMA * reception error is asserted. * @retval None */ void USART_DMAReceptionErrorConfig(USART_TypeDef* USARTx, uint32_t USART_DMAOnError) { /* Check the parameters */ assert_param(IS_USART_1234_PERIPH(USARTx)); assert_param(IS_USART_DMAONERROR(USART_DMAOnError)); /* Clear the DMA Reception error detection bit */ USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DDRE); /* Set the new value for the DMA Reception error detection bit */ USARTx->CR3 |= USART_DMAOnError; } /** * @} */ /** @defgroup USART_Group12 Interrupts and flags management functions * @brief Interrupts and flags management functions * @verbatim =============================================================================== ##### Interrupts and flags management functions ##### =============================================================================== [..] This subsection provides a set of functions allowing to configure the USART Interrupts sources, Requests and check or clear the flags or pending bits status. The user should identify which mode will be used in his application to manage the communication: Polling mode, Interrupt mode. *** Polling Mode *** ==================== [..] In Polling Mode, the SPI communication can be managed by these flags: (#) USART_FLAG_REACK: to indicate the status of the Receive Enable acknowledge flag (#) USART_FLAG_TEACK: to indicate the status of the Transmit Enable acknowledge flag. (#) USART_FLAG_WUF: to indicate the status of the Wake up flag. (#) USART_FLAG_RWU: to indicate the status of the Receive Wake up flag. (#) USART_FLAG_SBK: to indicate the status of the Send Break flag. (#) USART_FLAG_CMF: to indicate the status of the Character match flag. (#) USART_FLAG_BUSY: to indicate the status of the Busy flag. (#) USART_FLAG_ABRF: to indicate the status of the Auto baud rate flag. (#) USART_FLAG_ABRE: to indicate the status of the Auto baud rate error flag. (#) USART_FLAG_EOBF: to indicate the status of the End of block flag. (#) USART_FLAG_RTOF: to indicate the status of the Receive time out flag. (#) USART_FLAG_nCTSS: to indicate the status of the Inverted nCTS input bit status. (#) USART_FLAG_TXE: to indicate the status of the transmit buffer register. (#) USART_FLAG_RXNE: to indicate the status of the receive buffer register. (#) USART_FLAG_TC: to indicate the status of the transmit operation. (#) USART_FLAG_IDLE: to indicate the status of the Idle Line. (#) USART_FLAG_CTS: to indicate the status of the nCTS input. (#) USART_FLAG_LBD: to indicate the status of the LIN break detection. (#) USART_FLAG_NE: to indicate if a noise error occur. (#) USART_FLAG_FE: to indicate if a frame error occur. (#) USART_FLAG_PE: to indicate if a parity error occur. (#) USART_FLAG_ORE: to indicate if an Overrun error occur. [..] In this Mode it is advised to use the following functions: (+) FlagStatus USART_GetFlagStatus(USART_TypeDef* USARTx, uint16_t USART_FLAG). (+) void USART_ClearFlag(USART_TypeDef* USARTx, uint16_t USART_FLAG). *** Interrupt Mode *** ====================== [..] In Interrupt Mode, the USART communication can be managed by 8 interrupt sources and 10 pending bits: (+) Pending Bits: (##) USART_IT_WU: to indicate the status of the Wake up interrupt. (##) USART_IT_CM: to indicate the status of Character match interrupt. (##) USART_IT_EOB: to indicate the status of End of block interrupt. (##) USART_IT_RTO: to indicate the status of Receive time out interrupt. (##) USART_IT_CTS: to indicate the status of CTS change interrupt. (##) USART_IT_LBD: to indicate the status of LIN Break detection interrupt. (##) USART_IT_TC: to indicate the status of Transmission complete interrupt. (##) USART_IT_IDLE: to indicate the status of IDLE line detected interrupt. (##) USART_IT_ORE: to indicate the status of OverRun Error interrupt. (##) USART_IT_NE: to indicate the status of Noise Error interrupt. (##) USART_IT_FE: to indicate the status of Framing Error interrupt. (##) USART_IT_PE: to indicate the status of Parity Error interrupt. (+) Interrupt Source: (##) USART_IT_WU: specifies the interrupt source for Wake up interrupt. (##) USART_IT_CM: specifies the interrupt source for Character match interrupt. (##) USART_IT_EOB: specifies the interrupt source for End of block interrupt. (##) USART_IT_RTO: specifies the interrupt source for Receive time-out interrupt. (##) USART_IT_CTS: specifies the interrupt source for CTS change interrupt. (##) USART_IT_LBD: specifies the interrupt source for LIN Break detection interrupt. (##) USART_IT_TXE: specifies the interrupt source for Tansmit Data Register empty interrupt. (##) USART_IT_TC: specifies the interrupt source for Transmission complete interrupt. (##) USART_IT_RXNE: specifies the interrupt source for Receive Data register not empty interrupt. (##) USART_IT_IDLE: specifies the interrupt source for Idle line detection interrupt. (##) USART_IT_PE: specifies the interrupt source for Parity Error interrupt. (##) USART_IT_ERR: specifies the interrupt source for Error interrupt (Frame error, noise error, overrun error) -@@- Some parameters are coded in order to use them as interrupt source or as pending bits. [..] In this Mode it is advised to use the following functions: (+) void USART_ITConfig(USART_TypeDef* USARTx, uint16_t USART_IT, FunctionalState NewState). (+) ITStatus USART_GetITStatus(USART_TypeDef* USARTx, uint16_t USART_IT). (+) void USART_ClearITPendingBit(USART_TypeDef* USARTx, uint16_t USART_IT). @endverbatim * @{ */ /** * @brief Enables or disables the specified USART interrupts. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_IT: specifies the USART interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg USART_IT_WU: Wake up interrupt. * @arg USART_IT_CM: Character match interrupt. * @arg USART_IT_EOB: End of block interrupt. * @arg USART_IT_RTO: Receive time out interrupt. * @arg USART_IT_CTS: CTS change interrupt. * @arg USART_IT_LBD: LIN Break detection interrupt. * @arg USART_IT_TXE: Tansmit Data Register empty interrupt. * @arg USART_IT_TC: Transmission complete interrupt. * @arg USART_IT_RXNE: Receive Data register not empty interrupt. * @arg USART_IT_IDLE: Idle line detection interrupt. * @arg USART_IT_PE: Parity Error interrupt. * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) * @param NewState: new state of the specified USARTx interrupts. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_ITConfig(USART_TypeDef* USARTx, uint32_t USART_IT, FunctionalState NewState) { uint32_t usartreg = 0, itpos = 0, itmask = 0; uint32_t usartxbase = 0; /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_CONFIG_IT(USART_IT)); assert_param(IS_FUNCTIONAL_STATE(NewState)); usartxbase = (uint32_t)USARTx; /* Get the USART register index */ usartreg = (((uint16_t)USART_IT) >> 0x08); /* Get the interrupt position */ itpos = USART_IT & IT_MASK; itmask = (((uint32_t)0x01) << itpos); if (usartreg == 0x02) /* The IT is in CR2 register */ { usartxbase += 0x04; } else if (usartreg == 0x03) /* The IT is in CR3 register */ { usartxbase += 0x08; } else /* The IT is in CR1 register */ { } if (NewState != DISABLE) { *(__IO uint32_t*)usartxbase |= itmask; } else { *(__IO uint32_t*)usartxbase &= ~itmask; } } /** * @brief Enables the specified USART's Request. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_Request: specifies the USART request. * This parameter can be any combination of the following values: * @arg USART_Request_TXFRQ: Transmit data flush ReQuest * @arg USART_Request_RXFRQ: Receive data flush ReQuest * @arg USART_Request_MMRQ: Mute Mode ReQuest * @arg USART_Request_SBKRQ: Send Break ReQuest * @arg USART_Request_ABRRQ: Auto Baud Rate ReQuest * @param NewState: new state of the DMA interface when reception error occurs. * This parameter can be: ENABLE or DISABLE. * @retval None */ void USART_RequestCmd(USART_TypeDef* USARTx, uint32_t USART_Request, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_REQUEST(USART_Request)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the USART ReQuest by setting the dedicated request bit in the RQR register.*/ USARTx->RQR |= USART_Request; } else { /* Disable the USART ReQuest by clearing the dedicated request bit in the RQR register.*/ USARTx->RQR &= (uint32_t)~USART_Request; } } /** * @brief Enables or disables the USART's Overrun detection. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_OVRDetection: specifies the OVR detection status in case of OVR error. * This parameter can be any combination of the following values: * @arg USART_OVRDetection_Enable: OVR error detection enabled when the USART OVR error * is asserted. * @arg USART_OVRDetection_Disable: OVR error detection disabled when the USART OVR error * is asserted. * @retval None */ void USART_OverrunDetectionConfig(USART_TypeDef* USARTx, uint32_t USART_OVRDetection) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_OVRDETECTION(USART_OVRDetection)); /* Clear the OVR detection bit */ USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_OVRDIS); /* Set the new value for the OVR detection bit */ USARTx->CR3 |= USART_OVRDetection; } /** * @brief Checks whether the specified USART flag is set or not. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_FLAG: specifies the flag to check. * This parameter can be one of the following values: * @arg USART_FLAG_REACK: Receive Enable acknowledge flag. * @arg USART_FLAG_TEACK: Transmit Enable acknowledge flag. * @arg USART_FLAG_WUF: Wake up flag. * @arg USART_FLAG_RWU: Receive Wake up flag. * @arg USART_FLAG_SBK: Send Break flag. * @arg USART_FLAG_CMF: Character match flag. * @arg USART_FLAG_BUSY: Busy flag. * @arg USART_FLAG_ABRF: Auto baud rate flag. * @arg USART_FLAG_ABRE: Auto baud rate error flag. * @arg USART_FLAG_EOBF: End of block flag. * @arg USART_FLAG_RTOF: Receive time out flag. * @arg USART_FLAG_nCTSS: Inverted nCTS input bit status. * @arg USART_FLAG_CTS: CTS Change flag. * @arg USART_FLAG_LBD: LIN Break detection flag. * @arg USART_FLAG_TXE: Transmit data register empty flag. * @arg USART_FLAG_TC: Transmission Complete flag. * @arg USART_FLAG_RXNE: Receive data register not empty flag. * @arg USART_FLAG_IDLE: Idle Line detection flag. * @arg USART_FLAG_ORE: OverRun Error flag. * @arg USART_FLAG_NE: Noise Error flag. * @arg USART_FLAG_FE: Framing Error flag. * @arg USART_FLAG_PE: Parity Error flag. * @retval The new state of USART_FLAG (SET or RESET). */ FlagStatus USART_GetFlagStatus(USART_TypeDef* USARTx, uint32_t USART_FLAG) { FlagStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_FLAG(USART_FLAG)); if ((USARTx->ISR & USART_FLAG) != (uint16_t)RESET) { bitstatus = SET; } else { bitstatus = RESET; } return bitstatus; } /** * @brief Clears the USARTx's pending flags. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_FLAG: specifies the flag to clear. * This parameter can be any combination of the following values: * @arg USART_FLAG_WUF: Wake up flag. * @arg USART_FLAG_CMF: Character match flag. * @arg USART_FLAG_EOBF: End of block flag. * @arg USART_FLAG_RTOF: Receive time out flag. * @arg USART_FLAG_CTS: CTS Change flag. * @arg USART_FLAG_LBD: LIN Break detection flag. * @arg USART_FLAG_TC: Transmission Complete flag. * @arg USART_FLAG_IDLE: IDLE line detected flag. * @arg USART_FLAG_ORE: OverRun Error flag. * @arg USART_FLAG_NE: Noise Error flag. * @arg USART_FLAG_FE: Framing Error flag. * @arg USART_FLAG_PE: Parity Errorflag. * * @note * - RXNE pending bit is cleared by a read to the USART_RDR register * (USART_ReceiveData()) or by writing 1 to the RXFRQ in the register USART_RQR * (USART_RequestCmd()). * - TC flag can be also cleared by software sequence: a read operation to * USART_SR register (USART_GetFlagStatus()) followed by a write operation * to USART_TDR register (USART_SendData()). * - TXE flag is cleared by a write to the USART_TDR register * (USART_SendData()) or by writing 1 to the TXFRQ in the register USART_RQR * (USART_RequestCmd()). * - SBKF flag is cleared by 1 to the SBKRQ in the register USART_RQR * (USART_RequestCmd()). * @retval None */ void USART_ClearFlag(USART_TypeDef* USARTx, uint32_t USART_FLAG) { /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_CLEAR_FLAG(USART_FLAG)); USARTx->ICR = USART_FLAG; } /** * @brief Checks whether the specified USART interrupt has occurred or not. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_IT: specifies the USART interrupt source to check. * This parameter can be one of the following values: * @arg USART_IT_WU: Wake up interrupt. * @arg USART_IT_CM: Character match interrupt. * @arg USART_IT_EOB: End of block interrupt. * @arg USART_IT_RTO: Receive time out interrupt. * @arg USART_IT_CTS: CTS change interrupt. * @arg USART_IT_LBD: LIN Break detection interrupt. * @arg USART_IT_TXE: Tansmit Data Register empty interrupt. * @arg USART_IT_TC: Transmission complete interrupt. * @arg USART_IT_RXNE: Receive Data register not empty interrupt. * @arg USART_IT_IDLE: Idle line detection interrupt. * @arg USART_IT_ORE: OverRun Error interrupt. * @arg USART_IT_NE: Noise Error interrupt. * @arg USART_IT_FE: Framing Error interrupt. * @arg USART_IT_PE: Parity Error interrupt. * @retval The new state of USART_IT (SET or RESET). */ ITStatus USART_GetITStatus(USART_TypeDef* USARTx, uint32_t USART_IT) { uint32_t bitpos = 0, itmask = 0, usartreg = 0; ITStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_GET_IT(USART_IT)); /* Get the USART register index */ usartreg = (((uint16_t)USART_IT) >> 0x08); /* Get the interrupt position */ itmask = USART_IT & IT_MASK; itmask = (uint32_t)0x01 << itmask; if (usartreg == 0x01) /* The IT is in CR1 register */ { itmask &= USARTx->CR1; } else if (usartreg == 0x02) /* The IT is in CR2 register */ { itmask &= USARTx->CR2; } else /* The IT is in CR3 register */ { itmask &= USARTx->CR3; } bitpos = USART_IT >> 0x10; bitpos = (uint32_t)0x01 << bitpos; bitpos &= USARTx->ISR; if ((itmask != (uint16_t)RESET)&&(bitpos != (uint16_t)RESET)) { bitstatus = SET; } else { bitstatus = RESET; } return bitstatus; } /** * @brief Clears the USARTx's interrupt pending bits. * @param USARTx: Select the USART peripheral. This parameter can be one of the * following values: USART1 or USART2 or USART3 or UART4 or UART5. * @param USART_IT: specifies the interrupt pending bit to clear. * This parameter can be one of the following values: * @arg USART_IT_WU: Wake up interrupt. * @arg USART_IT_CM: Character match interrupt. * @arg USART_IT_EOB: End of block interrupt. * @arg USART_IT_RTO: Receive time out interrupt. * @arg USART_IT_CTS: CTS change interrupt. * @arg USART_IT_LBD: LIN Break detection interrupt. * @arg USART_IT_TC: Transmission complete interrupt. * @arg USART_IT_IDLE: IDLE line detected interrupt. * @arg USART_IT_ORE: OverRun Error interrupt. * @arg USART_IT_NE: Noise Error interrupt. * @arg USART_IT_FE: Framing Error interrupt. * @arg USART_IT_PE: Parity Error interrupt. * @note * - RXNE pending bit is cleared by a read to the USART_RDR register * (USART_ReceiveData()) or by writing 1 to the RXFRQ in the register USART_RQR * (USART_RequestCmd()). * - TC pending bit can be also cleared by software sequence: a read * operation to USART_SR register (USART_GetITStatus()) followed by a write * operation to USART_TDR register (USART_SendData()). * - TXE pending bit is cleared by a write to the USART_TDR register * (USART_SendData()) or by writing 1 to the TXFRQ in the register USART_RQR * (USART_RequestCmd()). * @retval None */ void USART_ClearITPendingBit(USART_TypeDef* USARTx, uint32_t USART_IT) { uint32_t bitpos = 0, itmask = 0; /* Check the parameters */ assert_param(IS_USART_ALL_PERIPH(USARTx)); assert_param(IS_USART_CLEAR_IT(USART_IT)); bitpos = USART_IT >> 0x10; itmask = ((uint32_t)0x01 << (uint32_t)bitpos); USARTx->ICR = (uint32_t)itmask; } /** * @} */ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{'content_hash': '9737e06ae71542af6a2aba0300135212', 'timestamp': '', 'source': 'github', 'line_count': 2007, 'max_line_length': 106, 'avg_line_length': 41.17937219730942, 'alnum_prop': 0.6160538192553874, 'repo_name': 'gerikkub/gameboyCartFirmware', 'id': 'f779b2e88607a35000745d3b26b4182ee8d9d38e', 'size': '86537', 'binary': False, 'copies': '44', 'ref': 'refs/heads/master', 'path': 'tetrisTest/stm32/periph/src/stm32f30x_usart.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '13165'}, {'name': 'C', 'bytes': '2977740'}, {'name': 'C++', 'bytes': '41426'}, {'name': 'Makefile', 'bytes': '1743'}]}
using System; using System.Runtime.InteropServices; namespace SharpVk.Interop { /// <summary> /// /// </summary> [StructLayout(LayoutKind.Sequential)] public unsafe partial struct DeviceQueueCreateInfo { /// <summary> /// The type of this structure. /// </summary> public SharpVk.StructureType SType; /// <summary> /// Null or an extension-specific structure. /// </summary> public void* Next; /// <summary> /// Reserved for future use. /// </summary> public SharpVk.DeviceQueueCreateFlags Flags; /// <summary> /// An unsigned integer indicating the index of the queue family to /// create on this device. This index corresponds to the index of an /// element of the pQueueFamilyProperties array that was returned by /// fname:vkGetPhysicalDeviceQueueFamilyProperties. /// </summary> public uint QueueFamilyIndex; /// <summary> /// An unsigned integer specifying the number of queues to create in /// the queue family indicated by queueFamilyIndex. /// </summary> public uint QueueCount; /// <summary> /// An array of queueCount normalized floating point values, specifying /// priorities of work that will be submitted to each created queue. /// See Queue Priority for more information. /// </summary> public float* QueuePriorities; } }
{'content_hash': '81338ebe7fa967e5ce7c0f54db8a9a64', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 79, 'avg_line_length': 32.479166666666664, 'alnum_prop': 0.5914047466324567, 'repo_name': 'FacticiusVir/SharpVk', 'id': 'f90debe7d69334219b751221c8ce193586b62d40', 'size': '2796', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/SharpVk/Interop/DeviceQueueCreateInfo.gen.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '5249731'}]}
package org.aredis.cache; import java.util.Arrays; import org.aredis.net.AsyncSocketTransport; import org.aredis.net.AsyncSocketTransportFactory; import org.aredis.net.ServerInfo; class RedisServerWideData { private static volatile RedisServerWideData [] instances = new RedisServerWideData[0]; private ServerInfo serverInfo; private volatile AsyncRedisConnection commonAredisConnection; private volatile ScriptStatuses scriptStatuses; private volatile String auth; private RedisServerWideData(ServerInfo pserverInfo) { serverInfo = pserverInfo; } public static RedisServerWideData getInstance(ServerInfo serverInfo) { int serverIndex = serverInfo.getServerIndex(); if (serverIndex > 100000) { throw new RuntimeException("ServerIndex too big, 100000 is max allowed: " + serverIndex); } RedisServerWideData d = null; RedisServerWideData [] instancesArray = instances; if (instancesArray.length > serverIndex) { d = instancesArray[serverIndex]; } if (d == null) { synchronized (RedisServerWideData.class) { instancesArray = instances; int newLen = instancesArray.length; if (newLen > serverIndex) { d = instancesArray[serverIndex]; } else { newLen = serverIndex + 1; } if (d == null) { d = new RedisServerWideData(serverInfo); instancesArray = Arrays.copyOf(instancesArray, newLen); instancesArray[serverIndex] = d; instances = instancesArray; } } } return d; } /** * Gets a common Redis connection for a given server. The uses of this common connection must be synchronized * on the aredis object. Also the dbIndex is honoured only for the first call. Currently the common connection is * used only for Redis Class Descriptor storage so it is fine. In future if a different dbIndex is required * the user of aredis should use the select command and have a select back to the original dbIndex in a finally block. * * @param tf Transport Factory to use or null for default * @param dbIndex dbIndex to use * @return Common aredis connection one per server */ public AsyncRedisConnection getCommonAredisConnection(AsyncSocketTransportFactory tf, int dbIndex) { AsyncRedisConnection aredis = commonAredisConnection; if (aredis == null) { synchronized(this) { aredis = commonAredisConnection; if (aredis == null) { if(tf == null) { tf = AsyncSocketTransportFactory.getDefault(); } AsyncSocketTransport con = tf.getTransport(serverInfo.getHost(), serverInfo.getPort()); aredis = new AsyncRedisConnection(con, dbIndex, null, ConnectionType.STANDALONE); aredis.isCommonConnection = true; commonAredisConnection = aredis; } } } return aredis; } public ScriptStatuses getScriptStatuses() { ScriptStatuses statuses = scriptStatuses; if (statuses == null) { synchronized(this) { statuses = scriptStatuses; if (statuses == null) { statuses = new ScriptStatuses(); scriptStatuses = statuses; } } } return statuses; } public String getAuth() { return auth; } public void setAuth(String pauth) { auth = pauth; } }
{'content_hash': 'a42df1cd2830e0fbce7f84e3dbb02678', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 122, 'avg_line_length': 36.25, 'alnum_prop': 0.5810983397190294, 'repo_name': 'buaazp/libuq', 'id': 'beed468d32668f7379b8c81cd5e76b5bd4000d99', 'size': '5292', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'juq/src/main/java/org/aredis/cache/RedisServerWideData.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Go', 'bytes': '23061'}, {'name': 'Java', 'bytes': '275289'}]}
<?php /** * Migration class * * @package munkireport * @author AvB **/ class Migration extends Model { function __construct($table_name = '') { parent::__construct('id', strtolower(get_class($this))); //primary key, tablename $this->rs['id'] = ''; $this->rs['table_name'] = ''; $this->rt['table_name'] = 'VARCHAR(255) UNIQUE'; $this->rs['version'] = 0; // Create table if it does not exist $this->create_table(); if($table_name) { $this->retrieve_one('table_name=?', array($table_name)); $this->table_name = $table_name; } return $this; } } // END class
{'content_hash': '58a3968fdafb61674a8f7d1ff8d2ea63', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 86, 'avg_line_length': 22.866666666666667, 'alnum_prop': 0.5145772594752187, 'repo_name': 'dannooooo/munkireport-php', 'id': 'f935ac8b7eb11c5be78812e7d5124a37bb405c16', 'size': '686', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'app/models/migration.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '179'}, {'name': 'C', 'bytes': '2283'}, {'name': 'CSS', 'bytes': '6159'}, {'name': 'HTML', 'bytes': '709'}, {'name': 'JavaScript', 'bytes': '265979'}, {'name': 'Makefile', 'bytes': '467'}, {'name': 'PHP', 'bytes': '737979'}, {'name': 'Python', 'bytes': '48139'}, {'name': 'Shell', 'bytes': '36103'}]}
 using System; using System.Globalization; namespace Citrix.XenCenter { public class TimeUtil { public const long TicksBefore1970 = 621355968000000000; public const string ISO8601DateFormat = "yyyyMMddTHH:mm:ssZ"; public static long TicksToSeconds(long ticks) { return ticks / 10000000; } public static long TicksToSecondsSince1970(long ticks) { return (long)Math.Floor(new TimeSpan(ticks - (TicksBefore1970)).TotalSeconds); } /// <summary> /// Parses an ISO 8601 date/time into a DateTime. /// </summary> /// <param name="toParse">Must be of the format yyyyMMddTHH:mm:ssZ. Must not be null.</param> /// <returns>The parsed DateTime with Kind DateTimeKind.Utc.</returns> public static DateTime ParseISO8601DateTime(string toParse) { return DateTime.ParseExact(toParse, ISO8601DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); } public static string ToISO8601DateTime(DateTime t) { return t.ToUniversalTime().ToString(ISO8601DateFormat, CultureInfo.InvariantCulture); } } }
{'content_hash': 'a26a766896adafa8a9450a50d89fcea5', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 131, 'avg_line_length': 31.28205128205128, 'alnum_prop': 0.6491803278688525, 'repo_name': 'aftabahmedsajid/XenCenter-Complete-dependencies-', 'id': '47527072916560089f5792fef46930f15cf62f53', 'size': '2650', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'XenCenterLib/TimeUtil.cs', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C', 'bytes': '1907'}, {'name': 'C#', 'bytes': '16370140'}, {'name': 'C++', 'bytes': '21035'}, {'name': 'JavaScript', 'bytes': '812'}, {'name': 'PowerShell', 'bytes': '40'}, {'name': 'Shell', 'bytes': '62958'}, {'name': 'Visual Basic', 'bytes': '11351'}]}
<content-type name="/component/component-media-banner" is-wcm-type="true"> <label>Component - Media Banner</label> <form>/component/component-media-banner</form> <form-path>simple</form-path> <model-instance-path>NOT-USED-BY-SIMPLE-FORM-ENGINE</model-instance-path> <file-extension>xml</file-extension> <content-as-folder>false</content-as-folder> <previewable>false</previewable> <noThumbnail>true</noThumbnail> <image-thumbnail></image-thumbnail> </content-type>
{'content_hash': 'b1d03a782c3fec9f03a1ab16ea538b1c', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 74, 'avg_line_length': 44.09090909090909, 'alnum_prop': 0.7443298969072165, 'repo_name': 'rivetlogic/craftercms-bp-fitness', 'id': '00bba36270d0d771f798588774cbbe1127d9bac5', 'size': '485', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'config/studio/content-types/component/component-media-banner/config.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '23242'}, {'name': 'FreeMarker', 'bytes': '17366'}, {'name': 'Groovy', 'bytes': '9596'}, {'name': 'JavaScript', 'bytes': '12101'}]}
version = (node[:phantomjs] && node[:phantomjs][:version]) || '2.0.0' if `which phantomjs && phantomjs --version`.chomp == version puts "phantomjs #{version} is already installed" return end execute 'apt-get update' %w(build-essential g++ flex bison gperf ruby perl libsqlite3-dev libfontconfig1-dev libicu-dev libfreetype6 libssl-dev libjpeg-dev python libx11-dev libxext-dev ttf-mscorefonts-installer git).each do |p| package p end execute 'install libpng' do cwd '/tmp' command <<-EOC wget ftp://ftp.simplesystems.org/pub/libpng/png/src/libpng16/libpng-1.6.18.tar.gz tar xvf libpng-1.6.18.tar.gz cd libpng-1.6.18 ./configure make make install EOC not_if 'test -e /usr/local/lib/libpng16.so' end tmp_dir = '/tmp/phantomjs' execute "git clone git://github.com/ariya/phantomjs.git #{tmp_dir}" do not_if "test -d #{tmp_dir}" end execute 'git fetch && git clean -xfd' do cwd tmp_dir end execute "git checkout #{version}" do cwd tmp_dir end jobs = if node[:phantomjs] && node[:phantomjs][:jobs] "--jobs #{node[:phantomjs][:jobs]}" else '' end execute "./build.sh --confirm #{jobs}" do cwd tmp_dir end
{'content_hash': '4a2db82579d6e06a94b2445c0765b0f4', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 85, 'avg_line_length': 24.244897959183675, 'alnum_prop': 0.6708754208754208, 'repo_name': 'muratayusuke/itamae-plugin-recipe-phantomjs', 'id': '74caaa18c0dc2bd6670ddb32e7c1b3ceb55faee7', 'size': '1188', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/itamae/plugin/recipe/phantomjs/source.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '4969'}]}
package org.knowm.xchange.bitso.service; import static org.knowm.xchange.dto.Order.OrderType.BID; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import org.knowm.xchange.Exchange; import org.knowm.xchange.bitso.BitsoAdapters; import org.knowm.xchange.bitso.dto.BitsoException; import org.knowm.xchange.bitso.dto.trade.BitsoOrder; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.MarketOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrades; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.exceptions.NotAvailableFromExchangeException; import org.knowm.xchange.service.trade.TradeService; import org.knowm.xchange.service.trade.params.CancelOrderByIdParams; import org.knowm.xchange.service.trade.params.CancelOrderParams; import org.knowm.xchange.service.trade.params.DefaultTradeHistoryParamPaging; import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging; import org.knowm.xchange.service.trade.params.TradeHistoryParams; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams; /** @author Piotr Ładyżyński */ public class BitsoTradeService extends BitsoTradeServiceRaw implements TradeService { /** * Constructor * * @param exchange */ public BitsoTradeService(Exchange exchange) { super(exchange); } @Override public OpenOrders getOpenOrders() throws IOException, BitsoException { return getOpenOrders(createOpenOrdersParams()); } @Override public OpenOrders getOpenOrders(OpenOrdersParams params) throws IOException { BitsoOrder[] openOrders = getBitsoOpenOrders(); List<LimitOrder> limitOrders = new ArrayList<>(); for (BitsoOrder bitsoOrder : openOrders) { OrderType orderType = bitsoOrder.getType() == 0 ? OrderType.BID : OrderType.ASK; String id = bitsoOrder.getId(); BigDecimal price = bitsoOrder.getPrice(); limitOrders.add( new LimitOrder( orderType, bitsoOrder.getAmount(), new CurrencyPair(Currency.BTC, Currency.MXN), id, bitsoOrder.getTime(), price)); } return new OpenOrders(limitOrders); } @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException, BitsoException { throw new NotAvailableFromExchangeException(); } @Override public String placeLimitOrder(LimitOrder limitOrder) throws IOException, BitsoException { BitsoOrder bitsoOrder; if (limitOrder.getType() == BID) { bitsoOrder = buyBitoOrder(limitOrder.getOriginalAmount(), limitOrder.getLimitPrice()); } else { bitsoOrder = sellBitsoOrder(limitOrder.getOriginalAmount(), limitOrder.getLimitPrice()); } if (bitsoOrder.getErrorMessage() != null) { throw new ExchangeException(bitsoOrder.getErrorMessage()); } return bitsoOrder.getId(); } @Override public boolean cancelOrder(String orderId) throws IOException, BitsoException { return cancelBitsoOrder(orderId); } @Override public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { if (orderParams instanceof CancelOrderByIdParams) { return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId()); } else { return false; } } /** * Required parameter types: {@link TradeHistoryParamPaging#getPageLength()} * * <p>Warning: using a limit here can be misleading. The underlying call retrieves trades, * withdrawals, and deposits. So the example here will limit the result to 17 of those types and * from those 17 only trades are returned. It is recommended to use the raw service demonstrated * below if you want to use this feature. */ @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { return BitsoAdapters.adaptTradeHistory( getBitsoUserTransactions(Long.valueOf(((TradeHistoryParamPaging) params).getPageLength()))); } @Override public TradeHistoryParams createTradeHistoryParams() { return new DefaultTradeHistoryParamPaging(1000); } @Override public OpenOrdersParams createOpenOrdersParams() { return null; } }
{'content_hash': 'd68d62535546a7aa8a67c9ead0d06f3d', 'timestamp': '', 'source': 'github', 'line_count': 131, 'max_line_length': 100, 'avg_line_length': 33.82442748091603, 'alnum_prop': 0.7506206273978786, 'repo_name': 'stachon/XChange', 'id': '36192dd96349740d75bfc3c435ac538a063f2a3e', 'size': '4434', 'binary': False, 'copies': '11', 'ref': 'refs/heads/develop', 'path': 'xchange-bitso/src/main/java/org/knowm/xchange/bitso/service/BitsoTradeService.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '11344390'}]}
@implementation NIJSONKitProcessorHTTPRequest /////////////////////////////////////////////////////////////////////////////////////////////////// - (id)objectFromResponseData:(NSData *)data error:(NSError **)processingError { return [[JSONDecoder decoder] objectWithData:data error:processingError]; } @end
{'content_hash': '1159f58a492f87e6b3112eed9cde2e0c', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 99, 'avg_line_length': 31.3, 'alnum_prop': 0.5399361022364217, 'repo_name': 'alloy/nimbus', 'id': '0c0adb437a1d315cc673f744497ef46e11993c6b', 'size': '1275', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/processors/src_JSONKit/NIJSONKitProcessorHTTPRequest.m', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '148572'}, {'name': 'C++', 'bytes': '829'}, {'name': 'JavaScript', 'bytes': '6040'}, {'name': 'Objective-C', 'bytes': '2143498'}, {'name': 'Python', 'bytes': '97638'}, {'name': 'Shell', 'bytes': '3578'}]}
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_11.html">Class Test_AbaRouteValidator_11</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_22635_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_11.html?line=4504#src-4504" >testAbaNumberCheck_22635_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:40:28 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_22635_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=39942#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
{'content_hash': 'b0e7f4f52c4828591d4aa24ce08ceccb', 'timestamp': '', 'source': 'github', 'line_count': 209, 'max_line_length': 297, 'avg_line_length': 43.91866028708134, 'alnum_prop': 0.5096415731561172, 'repo_name': 'dcarda/aba.route.validator', 'id': 'cc73db11ca4f8dffa180da68bb21fd6769370d98', 'size': '9179', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_11_testAbaNumberCheck_22635_good_uti.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '18715254'}]}
package layer // import "github.com/docker/docker/layer" import ( "bytes" "compress/gzip" "io" "io/ioutil" "os" "path/filepath" "runtime" "testing" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/pkg/stringid" "github.com/vbatts/tar-split/tar/asm" "github.com/vbatts/tar-split/tar/storage" ) func writeTarSplitFile(name string, tarContent []byte) error { f, err := os.OpenFile(name, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return err } defer f.Close() fz := gzip.NewWriter(f) metaPacker := storage.NewJSONPacker(fz) defer fz.Close() rdr, err := asm.NewInputTarStream(bytes.NewReader(tarContent), metaPacker, nil) if err != nil { return err } if _, err := io.Copy(ioutil.Discard, rdr); err != nil { return err } return nil } func TestLayerMigration(t *testing.T) { // TODO Windows: Figure out why this is failing if runtime.GOOS == "windows" { t.Skip("Failing on Windows") } td, err := ioutil.TempDir("", "migration-test-") if err != nil { t.Fatal(err) } defer os.RemoveAll(td) layer1Files := []FileApplier{ newTestFile("/root/.bashrc", []byte("# Boring configuration"), 0644), newTestFile("/etc/profile", []byte("# Base configuration"), 0644), } layer2Files := []FileApplier{ newTestFile("/root/.bashrc", []byte("# Updated configuration"), 0644), } tar1, err := tarFromFiles(layer1Files...) if err != nil { t.Fatal(err) } tar2, err := tarFromFiles(layer2Files...) if err != nil { t.Fatal(err) } graph, err := newVFSGraphDriver(filepath.Join(td, "graphdriver-")) if err != nil { t.Fatal(err) } graphID1 := stringid.GenerateRandomID() if err := graph.Create(graphID1, "", nil); err != nil { t.Fatal(err) } if _, err := graph.ApplyDiff(graphID1, "", bytes.NewReader(tar1)); err != nil { t.Fatal(err) } tf1 := filepath.Join(td, "tar1.json.gz") if err := writeTarSplitFile(tf1, tar1); err != nil { t.Fatal(err) } root := filepath.Join(td, "layers") ls, err := newStoreFromGraphDriver(root, graph, runtime.GOOS) if err != nil { t.Fatal(err) } newTarDataPath := filepath.Join(td, ".migration-tardata") diffID, size, err := ls.(*layerStore).ChecksumForGraphID(graphID1, "", tf1, newTarDataPath) if err != nil { t.Fatal(err) } layer1a, err := ls.(*layerStore).RegisterByGraphID(graphID1, "", diffID, newTarDataPath, size) if err != nil { t.Fatal(err) } layer1b, err := ls.Register(bytes.NewReader(tar1), "") if err != nil { t.Fatal(err) } assertReferences(t, layer1a, layer1b) // Attempt register, should be same layer2a, err := ls.Register(bytes.NewReader(tar2), layer1a.ChainID()) if err != nil { t.Fatal(err) } graphID2 := stringid.GenerateRandomID() if err := graph.Create(graphID2, graphID1, nil); err != nil { t.Fatal(err) } if _, err := graph.ApplyDiff(graphID2, graphID1, bytes.NewReader(tar2)); err != nil { t.Fatal(err) } tf2 := filepath.Join(td, "tar2.json.gz") if err := writeTarSplitFile(tf2, tar2); err != nil { t.Fatal(err) } diffID, size, err = ls.(*layerStore).ChecksumForGraphID(graphID2, graphID1, tf2, newTarDataPath) if err != nil { t.Fatal(err) } layer2b, err := ls.(*layerStore).RegisterByGraphID(graphID2, layer1a.ChainID(), diffID, tf2, size) if err != nil { t.Fatal(err) } assertReferences(t, layer2a, layer2b) if metadata, err := ls.Release(layer2a); err != nil { t.Fatal(err) } else if len(metadata) > 0 { t.Fatalf("Unexpected layer removal after first release: %#v", metadata) } metadata, err := ls.Release(layer2b) if err != nil { t.Fatal(err) } assertMetadata(t, metadata, createMetadata(layer2a)) } func tarFromFilesInGraph(graph graphdriver.Driver, graphID, parentID string, files ...FileApplier) ([]byte, error) { t, err := tarFromFiles(files...) if err != nil { return nil, err } if err := graph.Create(graphID, parentID, nil); err != nil { return nil, err } if _, err := graph.ApplyDiff(graphID, parentID, bytes.NewReader(t)); err != nil { return nil, err } ar, err := graph.Diff(graphID, parentID) if err != nil { return nil, err } defer ar.Close() return ioutil.ReadAll(ar) } func TestLayerMigrationNoTarsplit(t *testing.T) { // TODO Windows: Figure out why this is failing if runtime.GOOS == "windows" { t.Skip("Failing on Windows") } td, err := ioutil.TempDir("", "migration-test-") if err != nil { t.Fatal(err) } defer os.RemoveAll(td) layer1Files := []FileApplier{ newTestFile("/root/.bashrc", []byte("# Boring configuration"), 0644), newTestFile("/etc/profile", []byte("# Base configuration"), 0644), } layer2Files := []FileApplier{ newTestFile("/root/.bashrc", []byte("# Updated configuration"), 0644), } graph, err := newVFSGraphDriver(filepath.Join(td, "graphdriver-")) if err != nil { t.Fatal(err) } graphID1 := stringid.GenerateRandomID() graphID2 := stringid.GenerateRandomID() tar1, err := tarFromFilesInGraph(graph, graphID1, "", layer1Files...) if err != nil { t.Fatal(err) } tar2, err := tarFromFilesInGraph(graph, graphID2, graphID1, layer2Files...) if err != nil { t.Fatal(err) } root := filepath.Join(td, "layers") ls, err := newStoreFromGraphDriver(root, graph, runtime.GOOS) if err != nil { t.Fatal(err) } newTarDataPath := filepath.Join(td, ".migration-tardata") diffID, size, err := ls.(*layerStore).ChecksumForGraphID(graphID1, "", "", newTarDataPath) if err != nil { t.Fatal(err) } layer1a, err := ls.(*layerStore).RegisterByGraphID(graphID1, "", diffID, newTarDataPath, size) if err != nil { t.Fatal(err) } layer1b, err := ls.Register(bytes.NewReader(tar1), "") if err != nil { t.Fatal(err) } assertReferences(t, layer1a, layer1b) // Attempt register, should be same layer2a, err := ls.Register(bytes.NewReader(tar2), layer1a.ChainID()) if err != nil { t.Fatal(err) } diffID, size, err = ls.(*layerStore).ChecksumForGraphID(graphID2, graphID1, "", newTarDataPath) if err != nil { t.Fatal(err) } layer2b, err := ls.(*layerStore).RegisterByGraphID(graphID2, layer1a.ChainID(), diffID, newTarDataPath, size) if err != nil { t.Fatal(err) } assertReferences(t, layer2a, layer2b) if metadata, err := ls.Release(layer2a); err != nil { t.Fatal(err) } else if len(metadata) > 0 { t.Fatalf("Unexpected layer removal after first release: %#v", metadata) } metadata, err := ls.Release(layer2b) if err != nil { t.Fatal(err) } assertMetadata(t, metadata, createMetadata(layer2a)) }
{'content_hash': '29c2de213960684047883821e1ccc9d0', 'timestamp': '', 'source': 'github', 'line_count': 269, 'max_line_length': 116, 'avg_line_length': 24.055762081784387, 'alnum_prop': 0.6645031679802195, 'repo_name': 'AkihiroSuda/docker', 'id': '2b5c3301f88f95727cb254e60d79a3788094e0e2', 'size': '6471', 'binary': False, 'copies': '19', 'ref': 'refs/heads/master', 'path': 'layer/migration_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '81'}, {'name': 'C', 'bytes': '4815'}, {'name': 'Dockerfile', 'bytes': '20034'}, {'name': 'Go', 'bytes': '9139363'}, {'name': 'Makefile', 'bytes': '10596'}, {'name': 'PowerShell', 'bytes': '78573'}, {'name': 'Python', 'bytes': '7179'}, {'name': 'Shell', 'bytes': '186734'}]}
<!doctype html> <html lang="en" class="no-js"> <head> <meta charset="utf-8"> <!-- begin SEO --> <title>Ch. Brester</title> <meta property="og:locale" content="en"> <meta property="og:site_name" content="Ch. Brester"> <meta property="og:title" content="Ch. Brester"> <link rel="canonical" href="http://localhost:4000/_pages/interests2/"> <meta property="og:url" content="http://localhost:4000/_pages/interests2/"> <script type="application/ld+json"> { "@context" : "http://schema.org", "@type" : "Person", "name" : "Christina Brester", "url" : "http://localhost:4000", "sameAs" : null } </script> <!-- end SEO --> <link href="http://localhost:4000/feed.xml" type="application/atom+xml" rel="alternate" title="Ch. Brester Feed"> <!-- http://t.co/dKP3o1e --> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> document.documentElement.className = document.documentElement.className.replace(/\bno-js\b/g, '') + ' js '; </script> <!-- For all browsers --> <link rel="stylesheet" href="http://localhost:4000/assets/css/main.css"> <meta http-equiv="cleartype" content="on"> <!-- start custom head snippets --> <!-- insert favicons. use http://realfavicongenerator.net/ --> <!-- end custom head snippets --> </head> <body class="layout--archive"> <!--[if lt IE 9]> <div class="notice--danger align-center" style="margin: 0;">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</div> <![endif]--> <div class="masthead"> <div class="masthead__inner-wrap"> <div class="masthead__menu"> <nav id="site-nav" class="greedy-nav"> <button><div class="navicon"></div></button> <ul class="visible-links"> <li class="masthead__menu-item masthead__menu-item--lg"><a target="_blank" href="http://localhost:4000/">Ch. Brester</a></li> <li class="masthead__menu-item"><a href="http://localhost:4000/_pages/publications/">Publications</a></li> <li class="masthead__menu-item"><a href="http://localhost:4000/_pages/projects/">Projects</a></li> <li class="masthead__menu-item"><a target="_blank" href="http://localhost:4000/documents/CV_Brester.pdf">CV</a></li> <li class="masthead__menu-item"><a href="http://localhost:4000/_pages/interests/">Interests</a></li> </ul> <ul class="hidden-links hidden"></ul> </nav> </div> </div> </div> <div id="main" role="main"> <div class="sidebar sticky"> <div itemscope itemtype="http://schema.org/Person"> <div class="author__avatar"> <img src="http://localhost:4000/images/20.jpg" class="author__avatar" alt="Christina Brester"> </div> <div class="author__content"> <h3 class="author__name">Christina Brester</h3> <p class="author__bio">Data Scientist and Machine Learning Devotee. <br> Dreamer with a sweet tooth.</p> </div> <div class="author__urls-wrapper"> <button class="btn btn--inverse">Follow</button> <ul class="author__urls social-icons"> <li><i class="fa fa-fw fa-map-marker" aria-hidden="true"></i> Kuopio, Finland</li> <li><a href="mailto:[email protected]"><i class="fa fa-fw fa-envelope-square" aria-hidden="true"></i> Email</a></li> <li><a href="https://www.facebook.com/profile.php?id=100008543322030"><i class="fa fa-fw fa-facebook-square" aria-hidden="true"></i> Facebook</a></li> <li><a href="https://www.linkedin.com/in/christina-brester-3a4148a8?trk=hp-identity-name"><i class="fa fa-fw fa-linkedin-square" aria-hidden="true"></i> LinkedIn</a></li> <li><a href="https://instagram.com/bres_ch"><i class="fa fa-fw fa-instagram" aria-hidden="true"></i> Instagram</a></li> </ul> </div> </div> </div> <div class="archive"> <h1 class="page__title"></h1> <h3 class="archive__subtitle"> Travelling </h3> <script src="https://www.amcharts.com/lib/3/ammap.js" type="text/javascript"></script> <script src="https://www.amcharts.com/lib/3/maps/js/worldHigh.js" type="text/javascript"></script> <script src="https://www.amcharts.com/lib/3/themes/dark.js" type="text/javascript"></script> <div id="mapdiv" style="width: 1000px; height: 450px;"></div> <div style="width: 1000px; font-size: 70%; padding: 5px 0; text-align: center; background-color: #628196; margin-top: 1px; color: #B4B4B7;"><a href="https://www.amcharts.com/visited_countries/" style="color: #B4B4B7;">Create your own visited countries map</a> or check out the <a href="https://www.amcharts.com/" style="color: #B4B4B7;">JavaScript Charts</a>.</div> <script type="text/javascript"> var map = AmCharts.makeChart("mapdiv",{ type: "map", theme: "dark", projection: "mercator", panEventsEnabled : true, backgroundColor : "#628196", backgroundAlpha : 1, zoomControl: { zoomControlEnabled : true }, dataProvider : { map : "worldHigh", getAreasFromMap : true, areas : [ { "id": "AL", "showAsSelected": true }, { "id": "AT", "showAsSelected": true }, { "id": "CZ", "showAsSelected": true }, { "id": "DE", "showAsSelected": true }, { "id": "EE", "showAsSelected": true }, { "id": "FI", "showAsSelected": true }, { "id": "FR", "showAsSelected": true }, { "id": "GR", "showAsSelected": true }, { "id": "ME", "showAsSelected": true }, { "id": "SI", "showAsSelected": true }, { "id": "RU", "showAsSelected": true }, { "id": "VN", "showAsSelected": true } ] }, areasSettings : { autoZoom : true, color : "#B4B4B7", colorSolid : "#EBCB49", selectedColor : "#EBCB49", outlineColor : "#666666", rollOverColor : "#9EC2F7", rollOverOutlineColor : "#000000" } }); </script> </div> </div> <div class="page__footer"> <footer> <!-- start custom footer snippets --> <!-- end custom footer snippets --> <div class="page__footer-follow"> <ul class="social-icons"> <li><strong>Follow:</strong></li> <li><a href="http://localhost:4000/feed.xml"><i class="fa fa-fw fa-rss-square" aria-hidden="true"></i> Feed</a></li> </ul> </div> <div class="page__footer-copyright">&copy; 2020 Christina Brester. Powered by <a href="http://jekyllrb.com" rel="nofollow">Jekyll</a> &amp; <a href="https://mademistakes.com/work/minimal-mistakes-jekyll-theme/" rel="nofollow">Minimal Mistakes</a>.</div> </footer> </div> <script src="http://localhost:4000/assets/js/main.min.js"></script> </body> </html>
{'content_hash': 'a00d2df536ddedb79753462b43564e5f', 'timestamp': '', 'source': 'github', 'line_count': 345, 'max_line_length': 365, 'avg_line_length': 20.797101449275363, 'alnum_prop': 0.584808362369338, 'repo_name': 'christinabrester/brester', 'id': '73863c3c31f0b22ff3bb4817da193cc14d595255', 'size': '7177', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': '_site/_pages/interests2/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '129793'}, {'name': 'JavaScript', 'bytes': '53349'}, {'name': 'Ruby', 'bytes': '706'}, {'name': 'SCSS', 'bytes': '65207'}]}
namespace Fixtures.AcceptanceTestsRequiredOptional.Models { using System.Linq; public partial class Product { /// <summary> /// Initializes a new instance of the Product class. /// </summary> public Product() { } /// <summary> /// Initializes a new instance of the Product class. /// </summary> public Product(int id, string name = default(string)) { Id = id; Name = name; } /// <summary> /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "id")] public int Id { get; set; } /// <summary> /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { //Nothing to validate } } }
{'content_hash': '62169b3ca5f0b98ff438a77ee9b693d1', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 65, 'avg_line_length': 26.047619047619047, 'alnum_prop': 0.5182815356489945, 'repo_name': 'haocs/autorest', 'id': 'ab5d7b5e407dd3062a6c03e22e81950cd1d96e12', 'size': '1407', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/generator/AutoRest.CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/Models/Product.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '12942'}, {'name': 'C#', 'bytes': '12768592'}, {'name': 'CSS', 'bytes': '110'}, {'name': 'Go', 'bytes': '142004'}, {'name': 'HTML', 'bytes': '274'}, {'name': 'Java', 'bytes': '6303425'}, {'name': 'JavaScript', 'bytes': '4746656'}, {'name': 'PowerShell', 'bytes': '44986'}, {'name': 'Python', 'bytes': '2283819'}, {'name': 'Ruby', 'bytes': '301935'}, {'name': 'Shell', 'bytes': '423'}, {'name': 'TypeScript', 'bytes': '179578'}]}
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" default-lazy-init="true"> <!-- Activates scanning of @Autowired --> <context:annotation-config/> <!-- Activates scanning of @Repository and @Service --> <context:component-scan base-package="com.desiEngg"/> <!-- Add new DAOs here --> <!-- Add new Managers here --> </beans>
{'content_hash': '41c8588ab6cc15a05e53294a37198163', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 135, 'avg_line_length': 46.1764705882353, 'alnum_prop': 0.6955414012738853, 'repo_name': 'git4sinu/proDesi', 'id': '70b2f2970f117353fb29bcffde773769c7d6122b', 'size': '785', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/webapp/WEB-INF/applicationContext.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '157419'}, {'name': 'Java', 'bytes': '221223'}, {'name': 'JavaScript', 'bytes': '29257'}]}
apt-get update apt-get upgrade apt-get install git nodejs npm mkdir /proj cd /proj git clone https://github.com/class-of-ellis/server
{'content_hash': 'e9b49770320eab63db5cc20417457a7d', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 50, 'avg_line_length': 11.666666666666666, 'alnum_prop': 0.75, 'repo_name': 'class-of-ellis/server', 'id': '392580ff4cc74b37849ef6b702cf377a9dc35cc6', 'size': '153', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'script/init-install.sh', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '8806'}, {'name': 'JavaScript', 'bytes': '1699'}, {'name': 'Shell', 'bytes': '153'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>MNE-CPP: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">MNE-CPP &#160;<span id="projectnumber">beta 1.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">IObserver Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="class_i_observer.html">IObserver</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="class_i_observer.html#ad3b61ed030b82a747cbf131d43fa8f89">ConstSPtr</a> typedef</td><td class="entry"><a class="el" href="class_i_observer.html">IObserver</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="class_i_observer.html#a373d00790e9ab9163a251e3b952c8833">SPtr</a> typedef</td><td class="entry"><a class="el" href="class_i_observer.html">IObserver</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="class_i_observer.html#a8499f376f794502fdd9ef197edd77b53">update</a>(Subject *pSubject)=0</td><td class="entry"><a class="el" href="class_i_observer.html">IObserver</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="class_i_observer.html#afdfe9e2ebd9aa794142968de574daa9a">~IObserver</a>()</td><td class="entry"><a class="el" href="class_i_observer.html">IObserver</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Fri Mar 27 2015 22:54:37 for MNE-CPP by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{'content_hash': '6d0e2a90e7858fee60dbf265fa337974', 'timestamp': '', 'source': 'github', 'line_count': 107, 'max_line_length': 298, 'avg_line_length': 48.99065420560748, 'alnum_prop': 0.6535673407096528, 'repo_name': 'CBoensel/mne-cpp', 'id': 'ca5ba4169a3e7c6947099e22c496697fb20725cf', 'size': '5242', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/html/class_i_observer-members.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '533427'}, {'name': 'C++', 'bytes': '11295418'}, {'name': 'Prolog', 'bytes': '27894'}, {'name': 'QMake', 'bytes': '322871'}]}
'use strict'; var vid1 = document.getElementById('vid1'); var vid2 = document.getElementById('vid2'); var btn1 = document.getElementById('btn1'); var btn2 = document.getElementById('btn2'); var btn3 = document.getElementById('btn3'); btn1.addEventListener('click', start); btn2.addEventListener('click', accept); btn3.addEventListener('click', stop); btn1.disabled = true; btn2.disabled = true; btn3.disabled = true; var pc1 = null; var pc2 = null; var localstream; var sdpConstraints = {'mandatory': { 'OfferToReceiveAudio': true, 'OfferToReceiveVideo': true} }; function gotStream(stream) { trace('Received local stream'); vid1.srcObject = stream; localstream = stream; btn1.disabled = false; } navigator.mediaDevices.getUserMedia({ audio: true, video: true }) .then(gotStream) .catch(function(e) { alert('getUserMedia() error: ' + e.name); }); function start() { btn1.disabled = true; btn2.disabled = false; btn3.disabled = false; trace('Starting Call'); var videoTracks = localstream.getVideoTracks(); var audioTracks = localstream.getAudioTracks(); if (videoTracks.length > 0) { trace('Using Video device: ' + videoTracks[0].label); } if (audioTracks.length > 0) { trace('Using Audio device: ' + audioTracks[0].label); } var servers = null; pc1 = new RTCPeerConnection(servers); trace('Created local peer connection object pc1'); pc1.onicecandidate = iceCallback1; pc2 = new RTCPeerConnection(servers); trace('Created remote peer connection object pc2'); pc2.onicecandidate = iceCallback2; pc2.onaddstream = gotRemoteStream; pc1.addStream(localstream); trace('Adding Local Stream to peer connection'); pc1.createOffer(gotDescription1, onCreateSessionDescriptionError); } function onCreateSessionDescriptionError(error) { trace('Failed to create session description: ' + error.toString()); stop(); } function onCreateAnswerError(error) { trace('Failed to set createAnswer: ' + error.toString()); stop(); } function onSetLocalDescriptionError(error) { trace('Failed to set setLocalDescription: ' + error.toString()); stop(); } function onSetLocalDescriptionSuccess() { trace('localDescription success.'); } function gotDescription1(desc) { pc1.setLocalDescription(desc, onSetLocalDescriptionSuccess, onSetLocalDescriptionError); trace('Offer from pc1 \n' + desc.sdp); pc2.setRemoteDescription(desc); // Since the 'remote' side has no media stream we need // to pass in the right constraints in order for it to // accept the incoming offer of audio and video. pc2.createAnswer(gotDescription2, onCreateSessionDescriptionError, sdpConstraints); } function gotDescription2(desc) { // Provisional answer, set a=inactive & set sdp type to pranswer. desc.sdp = desc.sdp.replace(/a=recvonly/g, 'a=inactive'); desc.type = 'pranswer'; pc2.setLocalDescription(desc, onSetLocalDescriptionSuccess, onSetLocalDescriptionError); trace('Pranswer from pc2 \n' + desc.sdp); pc1.setRemoteDescription(desc); } function gotDescription3(desc) { // Final answer, setting a=recvonly & sdp type to answer. desc.sdp = desc.sdp.replace(/a=inactive/g, 'a=recvonly'); desc.type = 'answer'; pc2.setLocalDescription(desc, onSetLocalDescriptionSuccess, onSetLocalDescriptionError); trace('Answer from pc2 \n' + desc.sdp); pc1.setRemoteDescription(desc); } function accept() { pc2.createAnswer(gotDescription3, onCreateAnswerError, sdpConstraints); btn2.disabled = true; btn1.disabled = false; } function stop() { trace('Ending Call' + '\n\n'); pc1.close(); pc2.close(); pc1 = null; pc2 = null; btn2.disabled = true; btn1.disabled = false; btn3.disabled = true; } function gotRemoteStream(e) { vid2.srcObject = e.stream; trace('Received remote stream'); } function iceCallback1(event) { if (event.candidate) { pc2.addIceCandidate(new RTCIceCandidate(event.candidate), onAddIceCandidateSuccess, onAddIceCandidateError); trace('Local ICE candidate: \n' + event.candidate.candidate); } } function iceCallback2(event) { if (event.candidate) { pc1.addIceCandidate(new RTCIceCandidate(event.candidate), onAddIceCandidateSuccess, onAddIceCandidateError); trace('Remote ICE candidate: \n ' + event.candidate.candidate); } } function onAddIceCandidateSuccess() { trace('AddIceCandidate success.'); } function onAddIceCandidateError(error) { trace('Failed to add Ice Candidate: ' + error.toString()); }
{'content_hash': 'ac91a35d0a2e9e6bde615d2f8a79bf19', 'timestamp': '', 'source': 'github', 'line_count': 168, 'max_line_length': 74, 'avg_line_length': 27.083333333333332, 'alnum_prop': 0.7151648351648352, 'repo_name': 'EmreAkkoyun/sample', 'id': 'ef108b78080098ab85064ea359ab0e5fe260f6d4', 'size': '4772', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'src/content/peerconnection/pr-answer/js/main.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '16062'}, {'name': 'HTML', 'bytes': '80256'}, {'name': 'JavaScript', 'bytes': '217590'}, {'name': 'Shell', 'bytes': '447'}]}
module Apiman { export var _module = angular.module(Apiman.pluginName, [ 'angular-clipboard', 'ngRoute', 'ngSanitize', 'ui.bootstrap', 'ui.select', 'ui.sortable', 'xeditable', 'ngFileUpload', 'ngAnimate', 'ApimanRPC', 'ApimanFilters', 'ApimanLogger', 'ApimanConfiguration', 'ApimanTranslation', 'ApimanPageLifecycle', 'ApimanCurrentUser', 'ApimanModals' ]); _module.config([ '$locationProvider', '$routeProvider', 'uiSelectConfig', ($locationProvider, $routeProvider, uiSelectConfig) => { var path = 'plugins/api-manager/html/'; var prefix = '/api-manager'; uiSelectConfig.theme = 'select2'; uiSelectConfig.searchEnabled = false; // Define Routes $routeProvider .when(prefix + '/', { templateUrl: path + 'dash.html' }) .when(prefix + '/about', { templateUrl: path + 'about.html' }) .when(prefix + '/profile', { templateUrl: path + 'user/user-profile.html' }) .when(prefix + '/admin/gateways', { templateUrl: path + 'admin/admin-gateways.html' }) .when(prefix + '/admin/plugins', { templateUrl: path + 'admin/admin-plugins.html' }) .when(prefix + '/admin/policyDefs', { templateUrl: path + 'admin/admin-policyDefs.html' }) .when(prefix + '/admin/roles', { templateUrl: path + 'admin/admin-roles.html' }) .when(prefix + '/admin/export', { templateUrl: path + 'admin/admin-export.html' }) .when(prefix + '/admin/gateways/:gateway', { templateUrl: path + 'forms/edit-gateway.html' }) .when(prefix + '/admin/plugins/:plugin', { templateUrl: path + 'forms/edit-plugin.html' }) .when(prefix + '/admin/policyDefs/:policyDef', { templateUrl: path + 'forms/edit-policyDef.html' }) .when(prefix + '/admin/roles/:role', { templateUrl: path + 'forms/edit-role.html' }) .when(prefix + '/orgs/:org/:type/:id/:ver/policies/:policy', { templateUrl: path + 'forms/edit-policy.html' }) .when(prefix + '/orgs/:org/:type/:id/:ver/new-policy', { templateUrl: path + 'forms/new-policy.html' }) .when(prefix + '/orgs/:org/clients/:client', { templateUrl: path + 'client/client.html' }) .when(prefix + '/orgs/:org/clients/:client/:version', { templateUrl: path + 'client/client-overview.html' }) .when(prefix + '/orgs/:org/clients/:client/:version/contracts', { templateUrl: path + 'client/client-contracts.html' }) .when(prefix + '/orgs/:org/clients/:client/:version/apis', { templateUrl: path + 'client/client-apis.html' }) .when(prefix + '/orgs/:org/clients/:client/:version/metrics', { templateUrl: path + 'client/client-metrics.html' }) .when(prefix + '/orgs/:org/clients/:client/:version/policies', { templateUrl: path + 'client/client-policies.html' }) .when(prefix + '/orgs/:org/clients/:client/:version/activity', { templateUrl: path + 'client/client-activity.html' }) .when(prefix + '/orgs/:org/clients/:client/:version/new-version', { templateUrl: path + 'forms/new-clientversion.html' }) .when(prefix + '/orgs/:org/plans/:plan', { templateUrl: path + 'plan/plan.html' }) .when(prefix + '/orgs/:org/plans/:plan/:version', { templateUrl: path + 'plan/plan-overview.html' }) .when(prefix + '/orgs/:org/plans/:plan/:version/policies', { templateUrl: path + 'plan/plan-policies.html' }) .when(prefix + '/orgs/:org/plans/:plan/:version/activity', { templateUrl: path + 'plan/plan-activity.html' }) .when(prefix + '/orgs/:org/plans/:plan/:version/new-version', { templateUrl: path + 'forms/new-planversion.html' }) .when(prefix + '/orgs/:org/apis/:api', { templateUrl: path + 'api/api.html' }) .when(prefix + '/orgs/:org/apis/:api/:version', { templateUrl: path + 'api/api-overview.html' }) .when(prefix + '/orgs/:org/apis/:api/:version/impl', { templateUrl: path + 'api/api-impl.html' }) .when(prefix + '/orgs/:org/apis/:api/:version/def', { templateUrl: path + 'api/api-def.html' }) .when(prefix + '/orgs/:org/apis/:api/:version/plans', { templateUrl: path + 'api/api-plans.html' }) .when(prefix + '/orgs/:org/apis/:api/:version/policies', { templateUrl: path + 'api/api-policies.html' }) .when(prefix + '/orgs/:org/apis/:api/:version/endpoint', { templateUrl: path + 'api/api-endpoint.html' }) .when(prefix + '/orgs/:org/apis/:api/:version/contracts', { templateUrl: path + 'api/api-contracts.html' }) .when(prefix + '/orgs/:org/apis/:api/:version/metrics', { templateUrl: path + 'api/api-metrics.html' }) .when(prefix + '/orgs/:org/apis/:api/:version/activity', { templateUrl: path + 'api/api-activity.html' }) .when(prefix + '/orgs/:org/apis/:api/:version/new-version', { templateUrl: path + 'forms/new-apiversion.html' }) .when(prefix + '/orgs/:org/import/apis', { templateUrl: path + 'api/import-apis.html' }) .when(prefix + '/catalog/api-catalog', { templateUrl: path + 'catalog/api-catalog.html' }) .when(prefix + '/catalog/api-catalog/:name/def', { templateUrl: path + 'catalog/api-catalog-def.html' }) .when(prefix + '/browse/orgs', { templateUrl: path + 'consumer/consumer-orgs.html' }) .when(prefix + '/browse/apis', { templateUrl: path + 'consumer/consumer-apis.html' }) .when(prefix + '/browse/orgs/:org', { templateUrl: path + 'consumer/consumer-org.html' }) .when(prefix + '/browse/orgs/:org/:api', { templateUrl: path + 'consumer/consumer-api-redirect.html' }) .when(prefix + '/browse/orgs/:org/:api/:version', { templateUrl: path + 'consumer/consumer-api.html' }) .when(prefix + '/browse/orgs/:org/:api/:version/def', { templateUrl: path + 'consumer/consumer-api-def.html' }) .when(prefix + '/new-client', { templateUrl: path + 'forms/new-client.html' }) .when(prefix + '/new-contract', { templateUrl: path + 'forms/new-contract.html' }) .when(prefix + '/new-gateway', { templateUrl: path + 'forms/new-gateway.html' }) .when(prefix + '/new-org', { templateUrl: path + 'forms/new-org.html' }) .when(prefix + '/new-plan', { templateUrl: path + 'forms/new-plan.html' }) .when(prefix + '/new-plugin', { templateUrl: path + 'forms/new-plugin.html' }) .when(prefix + '/new-role', { templateUrl: path + 'forms/new-role.html' }) .when(prefix + '/new-api', { templateUrl: path + 'forms/new-api.html' }) .when(prefix + '/import-policyDefs', { templateUrl: path + 'forms/import-policyDefs.html' }) .when(prefix + '/orgs/:org', { templateUrl: path + 'org/org.html' }) .when(prefix + '/orgs/:org/plans', { templateUrl: path + 'org/org-plans.html' }) .when(prefix + '/orgs/:org/apis', { templateUrl: path + 'org/org-apis.html' }) .when(prefix + '/orgs/:org/clients', { templateUrl: path + 'org/org-clients.html' }) .when(prefix + '/orgs/:org/members', { templateUrl: path + 'org/org-members.html' }) .when(prefix + '/orgs/:org/manage-members', { templateUrl: path + 'org/org-manage-members.html' }) .when(prefix + '/orgs/:org/activity', { templateUrl: path + 'org/org-activity.html' }) .when(prefix + '/orgs/:org/new-member', { templateUrl: path + 'org/org-new-member.html' }) .when(prefix + '/users/:user', { templateUrl: path + 'user/user.html' }) .when(prefix + '/users/:user/activity', { templateUrl: path + 'user/user-activity.html' }) .when(prefix + '/users/:user/clients', { templateUrl: path + 'user/user-clients.html' }) .when(prefix + '/users/:user/orgs', { templateUrl: path + 'user/user-orgs.html' }) .when(prefix + '/users/:user/apis', { templateUrl: path + 'user/user-apis.html' }) .when(prefix + '/errors/invalid_server', { templateUrl: path + 'errors/invalid_server.html' }) .when(prefix + '/errors/400', { templateUrl: path + 'errors/400.html' }) .when(prefix + '/errors/403', { templateUrl: path + 'errors/403.html' }) .when(prefix + '/errors/404', { templateUrl: path + 'errors/404.html' }) .when(prefix + '/errors/409', { templateUrl: path + 'errors/409.html' }) .when(prefix + '/errors/409-8002', { templateUrl: path + 'errors/409-8002.html' }) .when(prefix + '/errors/500', { templateUrl: path + 'errors/500.html' }) .otherwise({redirectTo: prefix + '/'}); $locationProvider.html5Mode(true); }]); _module.factory('authInterceptor', ['$q', '$timeout', 'Configuration', 'Logger', ($q, $timeout, Configuration, Logger) => { var refreshBearerToken = function () { Logger.info('Refreshing bearer token now.'); // Note: we need to use jquery directly for this call, otherwise we will have // a circular dependency in angular. $.get('rest/tokenRefresh', function (reply) { Logger.info('Bearer token successfully refreshed: {0}', reply); Configuration.api.auth.bearerToken.token = reply.token; var refreshPeriod = reply.refreshPeriod; if (!refreshPeriod || refreshPeriod < 1) { Logger.info('Refresh period was invalid! (using 60s)'); refreshPeriod = 60; } $timeout(refreshBearerToken, refreshPeriod * 1000); }).fail(function (error) { Logger.error('Failed to refresh bearer token: {0}', error); }); }; if (Configuration.api.auth.type == 'bearerToken') { var refreshPeriod = Configuration.api.auth.bearerToken.refreshPeriod; $timeout(refreshBearerToken, refreshPeriod * 1000); } var requestInterceptor = { request: function (config) { var authHeader = Configuration.getAuthorizationHeader(); if (authHeader) { config.headers.Authorization = authHeader; } return config; } }; return requestInterceptor; }]); _module.config(['$httpProvider', function ($httpProvider) { $httpProvider.interceptors.push('authInterceptor'); }]); _module.run([ '$rootScope', 'SystemSvcs', 'Configuration', '$location', ($rootScope, SystemSvcs, Configuration, $location) => { $rootScope.isDirty = false; $rootScope.$on('$locationChangeStart', function (event, newUrl, oldUrl) { if ($rootScope.isDirty) { if (confirm('You have unsaved changes. Are you sure you would like to navigate away from this page? You will lose these changes.') != true) { event.preventDefault(); } } }); $rootScope.pluginName = Apiman.pluginName; }]); // Load the configuration jsonp script $.getScript('apiman/config.js') .done((script, textStatus) => { log.info('Loaded the config.js config!'); }) .fail((response) => { log.debug('Error fetching configuration: ', response); }) .always(() => { // Load the i18n jsonp script $.getScript('apiman/translations.js').done((script, textStatus) => { log.info('Loaded the translations.js bundle!'); angular.element(document).ready(function () { angular.bootstrap(document, ['api-manager']); }); }).fail((response) => { log.debug('Error fetching translations: ', response); }); }); }
{'content_hash': 'ee6b5a78df022a9a35aaecec42bcaff8', 'timestamp': '', 'source': 'github', 'line_count': 355, 'max_line_length': 161, 'avg_line_length': 44.816901408450704, 'alnum_prop': 0.436392206159648, 'repo_name': 'jcechace/apiman', 'id': 'ac8e82e07fb18485f4c0096d21f2e8b8e1b37781', 'size': '15995', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'manager/ui/war/plugins/api-manager/ts/apimanPlugin.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '58563'}, {'name': 'HTML', 'bytes': '358504'}, {'name': 'Java', 'bytes': '3731061'}, {'name': 'JavaScript', 'bytes': '20095'}, {'name': 'Shell', 'bytes': '1900'}, {'name': 'TypeScript', 'bytes': '362947'}]}
<!doctype html><bgsound><frameset>
{'content_hash': '49aed7f1c41d98f9e640bd47e61fad5a', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 34, 'avg_line_length': 35.0, 'alnum_prop': 0.7428571428571429, 'repo_name': 'guhelski/tnsfpg', 'id': '0b8af74a2df32a0697ff1b10fdc6ec8e026afa3a', 'size': '35', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'node_modules/zombie/node_modules/html5/data/tree-construction/tests19.dat-60/input.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2941'}, {'name': 'JavaScript', 'bytes': '15386'}]}
package org.apache.hadoop.hbase.test; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.UUID; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.IntegrationTestingUtility; import org.apache.hadoop.hbase.IntegrationTests; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.mapreduce.TableMapper; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.VLongWritable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Counters; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; /** * This is an integration test borrowed from goraci, written by Keith Turner, * which is in turn inspired by the Accumulo test called continous ingest (ci). * The original source code can be found here: * https://github.com/keith-turner/goraci * https://github.com/enis/goraci/ * * Apache Accumulo [0] has a simple test suite that verifies that data is not * lost at scale. This test suite is called continuous ingest. This test runs * many ingest clients that continually create linked lists containing 25 * million nodes. At some point the clients are stopped and a map reduce job is * run to ensure no linked list has a hole. A hole indicates data was lost.·· * * The nodes in the linked list are random. This causes each linked list to * spread across the table. Therefore if one part of a table loses data, then it * will be detected by references in another part of the table. * * THE ANATOMY OF THE TEST * * Below is rough sketch of how data is written. For specific details look at * the Generator code. * * 1 Write out 1 million nodes· 2 Flush the client· 3 Write out 1 million that * reference previous million· 4 If this is the 25th set of 1 million nodes, * then update 1st set of million to point to last· 5 goto 1 * * The key is that nodes only reference flushed nodes. Therefore a node should * never reference a missing node, even if the ingest client is killed at any * point in time. * * When running this test suite w/ Accumulo there is a script running in * parallel called the Aggitator that randomly and continuously kills server * processes.·· The outcome was that many data loss bugs were found in Accumulo * by doing this.· This test suite can also help find bugs that impact uptime * and stability when· run for days or weeks.·· * * This test suite consists the following· - a few Java programs· - a little * helper script to run the java programs - a maven script to build it.·· * * When generating data, its best to have each map task generate a multiple of * 25 million. The reason for this is that circular linked list are generated * every 25M. Not generating a multiple in 25M will result in some nodes in the * linked list not having references. The loss of an unreferenced node can not * be detected. * * * Below is a description of the Java programs * * Generator - A map only job that generates data. As stated previously,· * its best to generate data in multiples of 25M. * * Verify - A map reduce job that looks for holes. Look at the counts after running. REFERENCED and * UNREFERENCED are· ok, any UNDEFINED counts are bad. Do not run at the· same * time as the Generator. * * Walker - A standalong program that start following a linked list· and emits timing info.·· * * Print - A standalone program that prints nodes in the linked list * * Delete - A standalone program that deletes a single node * * This class can be run as a unit test, as an integration test, or from the command line */ @Category(IntegrationTests.class) public class IntegrationTestBigLinkedList extends Configured implements Tool { private static final String TABLE_NAME_KEY = "IntegrationTestBigLinkedList.table"; private static final String DEFAULT_TABLE_NAME = "IntegrationTestBigLinkedList"; private static byte[] FAMILY_NAME = Bytes.toBytes("meta"); //link to the id of the prev node in the linked list private static final byte[] COLUMN_PREV = Bytes.toBytes("prev"); //identifier of the mapred task that generated this row private static final byte[] COLUMN_CLIENT = Bytes.toBytes("client"); //the id of the row within the same client. private static final byte[] COLUMN_COUNT = Bytes.toBytes("count"); /** How many rows to write per map task. This has to be a multiple of 25M */ private static final String GENERATOR_NUM_ROWS_PER_MAP_KEY = "IntegrationTestBigLinkedList.generator.num_rows"; private static final String GENERATOR_NUM_MAPPERS_KEY = "IntegrationTestBigLinkedList.generator.map.tasks"; static class CINode { long key; long prev; String client; long count; } /** * A Map only job that generates random linked list and stores them. */ static class Generator extends Configured implements Tool { private static final Log LOG = LogFactory.getLog(Generator.class); private static final int WIDTH = 1000000; private static final int WRAP = WIDTH * 25; public static enum Counts { UNREFERENCED, UNDEFINED, REFERENCED, CORRUPT } static class GeneratorInputFormat extends InputFormat<LongWritable,NullWritable> { static class GeneratorInputSplit extends InputSplit implements Writable { @Override public long getLength() throws IOException, InterruptedException { return 1; } @Override public String[] getLocations() throws IOException, InterruptedException { return new String[0]; } @Override public void readFields(DataInput arg0) throws IOException { } @Override public void write(DataOutput arg0) throws IOException { } } static class GeneratorRecordReader extends RecordReader<LongWritable,NullWritable> { private long count; private long numNodes; private Random rand; @Override public void close() throws IOException { } @Override public LongWritable getCurrentKey() throws IOException, InterruptedException { return new LongWritable(Math.abs(rand.nextLong())); } @Override public NullWritable getCurrentValue() throws IOException, InterruptedException { return NullWritable.get(); } @Override public float getProgress() throws IOException, InterruptedException { return (float)(count / (double)numNodes); } @Override public void initialize(InputSplit arg0, TaskAttemptContext context) throws IOException, InterruptedException { numNodes = context.getConfiguration().getLong(GENERATOR_NUM_ROWS_PER_MAP_KEY, 25000000); rand = new Random(); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { return count++ < numNodes; } } @Override public RecordReader<LongWritable,NullWritable> createRecordReader( InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { GeneratorRecordReader rr = new GeneratorRecordReader(); rr.initialize(split, context); return rr; } @Override public List<InputSplit> getSplits(JobContext job) throws IOException, InterruptedException { int numMappers = job.getConfiguration().getInt(GENERATOR_NUM_MAPPERS_KEY, 1); ArrayList<InputSplit> splits = new ArrayList<InputSplit>(numMappers); for (int i = 0; i < numMappers; i++) { splits.add(new GeneratorInputSplit()); } return splits; } } /** Ensure output files from prev-job go to map inputs for current job */ static class OneFilePerMapperSFIF<K, V> extends SequenceFileInputFormat<K, V> { @Override protected boolean isSplitable(JobContext context, Path filename) { return false; } } /** * Some ASCII art time: * [ . . . ] represents one batch of random longs of length WIDTH * * _________________________ * | ______ | * | | || * __+_________________+_____ || * v v v ||| * first = [ . . . . . . . . . . . ] ||| * ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ||| * | | | | | | | | | | | ||| * prev = [ . . . . . . . . . . . ] ||| * ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ||| * | | | | | | | | | | | ||| * current = [ . . . . . . . . . . . ] ||| * ||| * ... ||| * ||| * last = [ . . . . . . . . . . . ] ||| * | | | | | | | | | | |-----||| * | |--------|| * |___________________________| */ static class GeneratorMapper extends Mapper<LongWritable, NullWritable, NullWritable, NullWritable> { Random rand = new Random(); long[] first = null; long[] prev = null; long[] current = new long[WIDTH]; byte[] id; long count = 0; int i; HTable table; long numNodes; long wrap = WRAP; protected void setup(Context context) throws IOException, InterruptedException { id = Bytes.toBytes(UUID.randomUUID().toString()); Configuration conf = context.getConfiguration(); table = new HTable(conf, getTableName(conf)); table.setAutoFlush(false); table.setWriteBufferSize(4 * 1024 * 1024); numNodes = context.getConfiguration().getLong(GENERATOR_NUM_ROWS_PER_MAP_KEY, 25000000); if (numNodes < 25000000) { wrap = numNodes; } }; protected void cleanup(Context context) throws IOException ,InterruptedException { table.close(); }; @Override protected void map(LongWritable key, NullWritable value, Context output) throws IOException { current[i++] = Math.abs(key.get()); if (i == current.length) { persist(output, count, prev, current, id); i = 0; if (first == null) first = current; prev = current; current = new long[WIDTH]; count += current.length; output.setStatus("Count " + count); if (count % wrap == 0) { // this block of code turns the 1 million linked list of length 25 into one giant //circular linked list of 25 million circularLeftShift(first); persist(output, -1, prev, first, null); first = null; prev = null; } } } private static void circularLeftShift(long[] first) { long ez = first[0]; for (int i = 0; i < first.length - 1; i++) first[i] = first[i + 1]; first[first.length - 1] = ez; } private void persist(Context output, long count, long[] prev, long[] current, byte[] id) throws IOException { for (int i = 0; i < current.length; i++) { Put put = new Put(Bytes.toBytes(current[i])); put.add(FAMILY_NAME, COLUMN_PREV, Bytes.toBytes(prev == null ? -1 : prev[i])); if (count >= 0) { put.add(FAMILY_NAME, COLUMN_COUNT, Bytes.toBytes(count + i)); } if (id != null) { put.add(FAMILY_NAME, COLUMN_CLIENT, id); } table.put(put); if (i % 1000 == 0) { // Tickle progress every so often else maprunner will think us hung output.progress(); } } table.flushCommits(); } } @Override public int run(String[] args) throws Exception { if (args.length < 3) { System.out.println("Usage : " + Generator.class.getSimpleName() + " <num mappers> <num nodes per map> <tmp output dir>"); System.out.println(" where <num nodes per map> should be a multiple of 25M"); return 0; } int numMappers = Integer.parseInt(args[0]); long numNodes = Long.parseLong(args[1]); Path tmpOutput = new Path(args[2]); return run(numMappers, numNodes, tmpOutput); } protected void createSchema() throws IOException { HBaseAdmin admin = new HBaseAdmin(getConf()); byte[] tableName = getTableName(getConf()); if (!admin.tableExists(tableName)) { HTableDescriptor htd = new HTableDescriptor(getTableName(getConf())); htd.addFamily(new HColumnDescriptor(FAMILY_NAME)); admin.createTable(htd); } admin.close(); } public int runRandomInputGenerator(int numMappers, long numNodes, Path tmpOutput) throws Exception { LOG.info("Running RandomInputGenerator with numMappers=" + numMappers + ", numNodes=" + numNodes); Job job = new Job(getConf()); job.setJobName("Random Input Generator"); job.setNumReduceTasks(0); job.setJarByClass(getClass()); job.setInputFormatClass(GeneratorInputFormat.class); job.setOutputKeyClass(LongWritable.class); job.setOutputValueClass(NullWritable.class); job.getConfiguration().setInt(GENERATOR_NUM_MAPPERS_KEY, numMappers); job.getConfiguration().setLong(GENERATOR_NUM_ROWS_PER_MAP_KEY, numNodes); job.setMapperClass(Mapper.class); //identity mapper FileOutputFormat.setOutputPath(job, tmpOutput); job.setOutputFormatClass(SequenceFileOutputFormat.class); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } public int runGenerator(int numMappers, long numNodes, Path tmpOutput) throws Exception { LOG.info("Running Generator with numMappers=" + numMappers +", numNodes=" + numNodes); createSchema(); Job job = new Job(getConf()); job.setJobName("Link Generator"); job.setNumReduceTasks(0); job.setJarByClass(getClass()); FileInputFormat.setInputPaths(job, tmpOutput); job.setInputFormatClass(OneFilePerMapperSFIF.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(NullWritable.class); job.getConfiguration().setInt(GENERATOR_NUM_MAPPERS_KEY, numMappers); job.getConfiguration().setLong(GENERATOR_NUM_ROWS_PER_MAP_KEY, numNodes); job.setMapperClass(GeneratorMapper.class); job.setOutputFormatClass(NullOutputFormat.class); job.getConfiguration().setBoolean("mapred.map.tasks.speculative.execution", false); TableMapReduceUtil.addDependencyJars(job); TableMapReduceUtil.initCredentials(job); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } public int run(int numMappers, long numNodes, Path tmpOutput) throws Exception { int ret = runRandomInputGenerator(numMappers, numNodes, tmpOutput); if (ret > 0) { return ret; } return runGenerator(numMappers, numNodes, tmpOutput); } } /** * A Map Reduce job that verifies that the linked lists generated by * {@link Generator} do not have any holes. */ static class Verify extends Configured implements Tool { private static final Log LOG = LogFactory.getLog(Verify.class); private static final VLongWritable DEF = new VLongWritable(-1); private Job job; public static class VerifyMapper extends TableMapper<LongWritable, VLongWritable> { private LongWritable row = new LongWritable(); private LongWritable ref = new LongWritable(); private VLongWritable vrow = new VLongWritable(); @Override protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException ,InterruptedException { row.set(Bytes.toLong(key.get())); context.write(row, DEF); long prev = Bytes.toLong(value.getValue(FAMILY_NAME, COLUMN_PREV)); if (prev >= 0) { ref.set(prev); vrow.set(Bytes.toLong(key.get())); context.write(ref, vrow); } } } public static enum Counts { UNREFERENCED, UNDEFINED, REFERENCED, CORRUPT } public static class VerifyReducer extends Reducer<LongWritable,VLongWritable,Text,Text> { private ArrayList<Long> refs = new ArrayList<Long>(); public void reduce(LongWritable key, Iterable<VLongWritable> values, Context context) throws IOException, InterruptedException { int defCount = 0; refs.clear(); for (VLongWritable type : values) { if (type.get() == -1) { defCount++; } else { refs.add(type.get()); } } // TODO check for more than one def, should not happen if (defCount == 0 && refs.size() > 0) { // this is bad, found a node that is referenced but not defined. It must have been //lost, emit some info about this node for debugging purposes. StringBuilder sb = new StringBuilder(); String comma = ""; for (Long ref : refs) { sb.append(comma); comma = ","; sb.append(String.format("%016x", ref)); } context.write(new Text(String.format("%016x", key.get())), new Text(sb.toString())); context.getCounter(Counts.UNDEFINED).increment(1); } else if (defCount > 0 && refs.size() == 0) { // node is defined but not referenced context.getCounter(Counts.UNREFERENCED).increment(1); } else { // node is defined and referenced context.getCounter(Counts.REFERENCED).increment(1); } } } @Override public int run(String[] args) throws Exception { if (args.length != 2) { System.out.println("Usage : " + Verify.class.getSimpleName() + " <output dir> <num reducers>"); return 0; } String outputDir = args[0]; int numReducers = Integer.parseInt(args[1]); return run(outputDir, numReducers); } public int run(String outputDir, int numReducers) throws Exception { return run(new Path(outputDir), numReducers); } public int run(Path outputDir, int numReducers) throws Exception { LOG.info("Running Verify with outputDir=" + outputDir +", numReducers=" + numReducers); job = new Job(getConf()); job.setJobName("Link Verifier"); job.setNumReduceTasks(numReducers); job.setJarByClass(getClass()); Scan scan = new Scan(); scan.addColumn(FAMILY_NAME, COLUMN_PREV); scan.setCaching(10000); scan.setCacheBlocks(false); TableMapReduceUtil.initTableMapperJob(getTableName(getConf()), scan, VerifyMapper.class, LongWritable.class, VLongWritable.class, job); job.getConfiguration().setBoolean("mapred.map.tasks.speculative.execution", false); job.setReducerClass(VerifyReducer.class); job.setOutputFormatClass(TextOutputFormat.class); TextOutputFormat.setOutputPath(job, outputDir); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } public boolean verify(long expectedReferenced) throws Exception { if (job == null) { throw new IllegalStateException("You should call run() first"); } Counters counters = job.getCounters(); Counter referenced = counters.findCounter(Counts.REFERENCED); Counter unreferenced = counters.findCounter(Counts.UNREFERENCED); Counter undefined = counters.findCounter(Counts.UNDEFINED); boolean success = true; //assert if (expectedReferenced != referenced.getValue()) { LOG.error("Expected referenced count does not match with actual referenced count. " + "expected referenced=" + expectedReferenced + " ,actual=" + referenced.getValue()); success = false; } if (unreferenced.getValue() > 0) { LOG.error("Unreferenced nodes were not expected. Unreferenced count=" + unreferenced.getValue()); success = false; } if (undefined.getValue() > 0) { LOG.error("Found an undefined node. Undefined count=" + undefined.getValue()); success = false; } return success; } } /** * Executes Generate and Verify in a loop. Data is not cleaned between runs, so each iteration * adds more data. */ private static class Loop extends Configured implements Tool { private static final Log LOG = LogFactory.getLog(Loop.class); protected void runGenerator(int numMappers, long numNodes, String outputDir) throws Exception { Path outputPath = new Path(outputDir); UUID uuid = UUID.randomUUID(); //create a random UUID. Path generatorOutput = new Path(outputPath, uuid.toString()); Generator generator = new Generator(); generator.setConf(getConf()); int retCode = generator.run(numMappers, numNodes, generatorOutput); if (retCode > 0) { throw new RuntimeException("Generator failed with return code: " + retCode); } } protected void runVerify(String outputDir, int numReducers, long expectedNumNodes) throws Exception { Path outputPath = new Path(outputDir); UUID uuid = UUID.randomUUID(); //create a random UUID. Path iterationOutput = new Path(outputPath, uuid.toString()); Verify verify = new Verify(); verify.setConf(getConf()); int retCode = verify.run(iterationOutput, numReducers); if (retCode > 0) { throw new RuntimeException("Verify.run failed with return code: " + retCode); } boolean verifySuccess = verify.verify(expectedNumNodes); if (!verifySuccess) { throw new RuntimeException("Verify.verify failed"); } LOG.info("Verify finished with succees. Total nodes=" + expectedNumNodes); } @Override public int run(String[] args) throws Exception { if (args.length < 5) { System.err.println("Usage: Loop <num iterations> <num mappers> <num nodes per mapper> <output dir> <num reducers>"); return 1; } LOG.info("Running Loop with args:" + Arrays.deepToString(args)); int numIterations = Integer.parseInt(args[0]); int numMappers = Integer.parseInt(args[1]); long numNodes = Long.parseLong(args[2]); String outputDir = args[3]; int numReducers = Integer.parseInt(args[4]); long expectedNumNodes = 0; if (numIterations < 0) { numIterations = Integer.MAX_VALUE; //run indefinitely (kind of) } for (int i=0; i < numIterations; i++) { LOG.info("Starting iteration = " + i); runGenerator(numMappers, numNodes, outputDir); expectedNumNodes += numMappers * numNodes; runVerify(outputDir, numReducers, expectedNumNodes); } return 0; } } /** * A stand alone program that prints out portions of a list created by {@link Generator} */ private static class Print extends Configured implements Tool { public int run(String[] args) throws Exception { Options options = new Options(); options.addOption("s", "start", true, "start key"); options.addOption("e", "end", true, "end key"); options.addOption("l", "limit", true, "number to print"); GnuParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.getArgs().length != 0) { throw new ParseException("Command takes no arguments"); } } catch (ParseException e) { System.err.println("Failed to parse command line " + e.getMessage()); System.err.println(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(getClass().getSimpleName(), options); System.exit(-1); } HTable table = new HTable(getConf(), getTableName(getConf())); Scan scan = new Scan(); scan.setBatch(10000); if (cmd.hasOption("s")) scan.setStartRow(Bytes.toBytes(new BigInteger(cmd.getOptionValue("s"), 16).longValue())); if (cmd.hasOption("e")) scan.setStopRow(Bytes.toBytes(new BigInteger(cmd.getOptionValue("e"), 16).longValue())); int limit = 0; if (cmd.hasOption("l")) limit = Integer.parseInt(cmd.getOptionValue("l")); else limit = 100; ResultScanner scanner = table.getScanner(scan); CINode node = new CINode(); Result result = scanner.next(); int count = 0; while (result != null && count++ < limit) { node = getCINode(result, node); System.out.printf("%016x:%016x:%012d:%s\n", node.key, node.prev, node.count, node.client); result = scanner.next(); } scanner.close(); table.close(); return 0; } } /** * A stand alone program that deletes a single node. */ private static class Delete extends Configured implements Tool { public int run(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage : " + Delete.class.getSimpleName() + " <node to delete>"); return 0; } long val = new BigInteger(args[0], 16).longValue(); org.apache.hadoop.hbase.client.Delete delete = new org.apache.hadoop.hbase.client.Delete(Bytes.toBytes(val)); HTable table = new HTable(getConf(), getTableName(getConf())); table.delete(delete); table.flushCommits(); table.close(); System.out.println("Delete successful"); return 0; } } /** * A stand alone program that follows a linked list created by {@link Generator} and prints timing info. */ private static class Walker extends Configured implements Tool { public int run(String[] args) throws IOException { Options options = new Options(); options.addOption("n", "num", true, "number of queries"); GnuParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.getArgs().length != 0) { throw new ParseException("Command takes no arguments"); } } catch (ParseException e) { System.err.println("Failed to parse command line " + e.getMessage()); System.err.println(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(getClass().getSimpleName(), options); System.exit(-1); } long maxQueries = Long.MAX_VALUE; if (cmd.hasOption('n')) { maxQueries = Long.parseLong(cmd.getOptionValue("n")); } HTable table = new HTable(getConf(), getTableName(getConf())); Random rand = new Random(); long numQueries = 0; while (numQueries < maxQueries) { CINode node = findStartNode(rand, table); numQueries++; while (node != null && node.prev >= 0 && numQueries < maxQueries) { long prev = node.prev; long t1 = System.currentTimeMillis(); node = getNode(prev, table, node); long t2 = System.currentTimeMillis(); System.out.printf("CQ %d %016x \n", t2 - t1, prev); //cold cache numQueries++; t1 = System.currentTimeMillis(); node = getNode(prev, table, node); t2 = System.currentTimeMillis(); System.out.printf("HQ %d %016x \n", t2 - t1, prev); //hot cache numQueries++; } } table.close(); return 0; } private static CINode findStartNode(Random rand, HTable table) throws IOException { Scan scan = new Scan(); scan.setStartRow(Bytes.toBytes(Math.abs(rand.nextLong()))); scan.setBatch(1); scan.addColumn(FAMILY_NAME, COLUMN_PREV); long t1 = System.currentTimeMillis(); ResultScanner scanner = table.getScanner(scan); Result result = scanner.next(); long t2 = System.currentTimeMillis(); scanner.close(); if ( result != null) { CINode node = getCINode(result, new CINode()); System.out.printf("FSR %d %016x\n", t2 - t1, node.key); return node; } System.out.println("FSR " + (t2 - t1)); return null; } private CINode getNode(long row, HTable table, CINode node) throws IOException { Get get = new Get(Bytes.toBytes(row)); get.addColumn(FAMILY_NAME, COLUMN_PREV); Result result = table.get(get); return getCINode(result, node); } } private static byte[] getTableName(Configuration conf) { return Bytes.toBytes(conf.get(TABLE_NAME_KEY, DEFAULT_TABLE_NAME)); } private static CINode getCINode(Result result, CINode node) { node.key = Bytes.toLong(result.getRow()); if (result.containsColumn(FAMILY_NAME, COLUMN_PREV)) { node.prev = Bytes.toLong(result.getValue(FAMILY_NAME, COLUMN_PREV)); } else { node.prev = -1; } if (result.containsColumn(FAMILY_NAME, COLUMN_COUNT)) { node.count = Bytes.toLong(result.getValue(FAMILY_NAME, COLUMN_COUNT)); } else { node.count = -1; } if (result.containsColumn(FAMILY_NAME, COLUMN_CLIENT)) { node.client = Bytes.toString(result.getValue(FAMILY_NAME, COLUMN_CLIENT)); } else { node.client = ""; } return node; } private IntegrationTestingUtility util; @Before public void setUp() throws Exception { util = getTestingUtil(); util.initializeCluster(3); this.setConf(util.getConfiguration()); } @After public void tearDown() throws Exception { util.restoreCluster(); } @Test public void testContinuousIngest() throws IOException, Exception { //Loop <num iterations> <num mappers> <num nodes per mapper> <output dir> <num reducers> int ret = ToolRunner.run(getTestingUtil().getConfiguration(), new Loop(), new String[] {"1", "1", "2000000", getTestDir("IntegrationTestBigLinkedList", "testContinuousIngest").toString(), "1"}); org.junit.Assert.assertEquals(0, ret); } public Path getTestDir(String testName, String subdir) throws IOException { //HBaseTestingUtility.getDataTestDirOnTestFs() has not been backported. FileSystem fs = FileSystem.get(getConf()); Path base = new Path(fs.getWorkingDirectory(), "test-data"); String randomStr = UUID.randomUUID().toString(); Path testDir = new Path(base, randomStr); fs.deleteOnExit(testDir); return new Path(new Path(testDir, testName), subdir); } private IntegrationTestingUtility getTestingUtil() { if (this.util == null) { if (getConf() == null) { this.util = new IntegrationTestingUtility(); } else { this.util = new IntegrationTestingUtility(getConf()); } } return util; } private int printUsage() { System.err.println("Usage: " + this.getClass().getSimpleName() + " COMMAND [COMMAND options]"); System.err.println(" where COMMAND is one of:"); System.err.println(""); System.err.println(" Generator A map only job that generates data."); System.err.println(" Verify A map reduce job that looks for holes"); System.err.println(" Look at the counts after running"); System.err.println(" REFERENCED and UNREFERENCED are ok"); System.err.println(" any UNDEFINED counts are bad. Do not"); System.err.println(" run at the same time as the Generator."); System.err.println(" Walker A standalong program that starts "); System.err.println(" following a linked list and emits"); System.err.println(" timing info."); System.err.println(" Print A standalone program that prints nodes"); System.err.println(" in the linked list."); System.err.println(" Delete A standalone program that deletes a·"); System.err.println(" single node."); System.err.println(" Loop A program to Loop through Generator and"); System.err.println(" Verify steps"); System.err.println("\t "); return 1; } @Override public int run(String[] args) throws Exception { //get the class, run with the conf if (args.length < 1) { return printUsage(); } Tool tool = null; if (args[0].equals("Generator")) { tool = new Generator(); } else if (args[0].equals("Verify")) { tool = new Verify(); } else if (args[0].equals("Loop")) { tool = new Loop(); } else if (args[0].equals("Walker")) { tool = new Walker(); } else if (args[0].equals("Print")) { tool = new Print(); } else if (args[0].equals("Delete")) { tool = new Delete(); } else { return printUsage(); } args = Arrays.copyOfRange(args, 1, args.length); return ToolRunner.run(getConf(), tool, args); } public static void main(String[] args) throws Exception { int ret = ToolRunner.run(HBaseConfiguration.create(), new IntegrationTestBigLinkedList(), args); System.exit(ret); } }
{'content_hash': '2168e4cb0b838310369d8583e6280bd1', 'timestamp': '', 'source': 'github', 'line_count': 1003, 'max_line_length': 124, 'avg_line_length': 35.465603190428716, 'alnum_prop': 0.6358933993028224, 'repo_name': 'algarecu/hbase-0.94.8-qod', 'id': '8f2f86e852ff018a9f797256cd678f674168dc7a', 'size': '36401', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'target/hbase-0.94.8/hbase-0.94.8/src/test/java/org/apache/hadoop/hbase/test/IntegrationTestBigLinkedList.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '19836'}, {'name': 'CSS', 'bytes': '20794'}, {'name': 'HTML', 'bytes': '139288'}, {'name': 'Java', 'bytes': '24259991'}, {'name': 'Makefile', 'bytes': '2514'}, {'name': 'PHP', 'bytes': '14700'}, {'name': 'Perl', 'bytes': '17334'}, {'name': 'Python', 'bytes': '29070'}, {'name': 'Ruby', 'bytes': '779544'}, {'name': 'Shell', 'bytes': '175912'}, {'name': 'Thrift', 'bytes': '69092'}, {'name': 'XSLT', 'bytes': '8758'}]}
// This file was generated using Parlex's cpp_generator #ifndef INCLUDED_GREATER_CHAIN_HPP #define INCLUDED_GREATER_CHAIN_HPP #include <optional> #include <variant> #include <vector> #include "erased.hpp" #include "parlex/detail/abstract_syntax_tree.hpp" #include "parlex/detail/builtins.hpp" #include "parlex/detail/document.hpp" #include "plange_grammar.hpp" namespace plc { struct EXPRESSION; struct GREATER_CHAIN_LOOP; struct IC; struct GREATER_CHAIN { erased<EXPRESSION> expression; std::vector<erased<IC>> field_1; erased<GREATER_CHAIN_LOOP> greater_chain_loop; explicit GREATER_CHAIN( erased<EXPRESSION> && expression, std::vector<erased<IC>> && field_1, erased<GREATER_CHAIN_LOOP> && greater_chain_loop) : expression(std::move(expression)), field_1(std::move(field_1)), greater_chain_loop(std::move(greater_chain_loop)) {} GREATER_CHAIN(GREATER_CHAIN const & other) = default; GREATER_CHAIN(GREATER_CHAIN && move) = default; static GREATER_CHAIN build(parlex::detail::ast_node const & n); static parlex::detail::state_machine const & state_machine(); }; } // namespace plc #endif //INCLUDED_GREATER_CHAIN_HPP
{'content_hash': '598e606ed95d4e42f016c2f4d265c926', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 240, 'avg_line_length': 23.510204081632654, 'alnum_prop': 0.7369791666666666, 'repo_name': 'dlin172/Plange', 'id': 'dd6e663cc9f368008ccf95a61fc8218ce28c65cd', 'size': '1154', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'source/plc/include/document/GREATER_CHAIN.hpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '302'}, {'name': 'C++', 'bytes': '1357953'}, {'name': 'CMake', 'bytes': '27256'}, {'name': 'CSS', 'bytes': '3771'}, {'name': 'Makefile', 'bytes': '203'}, {'name': 'PHP', 'bytes': '48923'}, {'name': 'Python', 'bytes': '5829'}, {'name': 'Shell', 'bytes': '230'}, {'name': 'SourcePawn', 'bytes': '97692'}]}
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_GPU_MATMUL_UTILS_H_ #define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_MATMUL_UTILS_H_ #include <cstdint> #include <optional> #include <utility> #include <vector> #include "absl/types/span.h" #include "tensorflow/compiler/xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h" #include "tensorflow/compiler/xla/service/gpu/backend_configs.pb.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/shape.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/stream_executor/blas.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #if GOOGLE_CUDA #include "tensorflow/compiler/xla/stream_executor/cuda/cuda_blas_lt.h" #include "tensorflow/compiler/xla/stream_executor/scratch_allocator.h" #endif // GOOGLE_CUDA namespace xla { namespace gpu { StatusOr<std::vector<int64_t>> GetNonContractingDims( const Shape& shape, absl::Span<const int64_t> batch_dims, absl::Span<const int64_t> contracting_dims); // Normalize shape to (batch, rows, columns) logical dimensions. StatusOr<Shape> GetBatchRowColumnShape(const Shape& shape, absl::Span<const int64_t> batch_dims, absl::Span<const int64_t> row_dims, absl::Span<const int64_t> col_dims); struct MatrixLayout { enum class Order { kRowMajor, // Elements in the same row are contiguous in memory. kColumnMajor, // Elements in the same column are contiguous in memory. }; // Returns the matrix layout for a logical shape (batch, rows, columns). static StatusOr<MatrixLayout> For(const Shape& shape); // Returns the matrix layout with the given batch, row, col dimensions. static StatusOr<MatrixLayout> For(const Shape& shape, absl::Span<const int64_t> batch_dims, absl::Span<const int64_t> row_dims, absl::Span<const int64_t> col_dims); // Returns the matrix layout for the output. static StatusOr<MatrixLayout> For(const Shape& shape, size_t lhs_num_batch_dims, size_t lhs_num_row_dims, size_t rhs_num_batch_dims, size_t rhs_num_col_dims); void Transpose(); PrimitiveType dtype; // `num_rows` / `num_cols` are for the "logical" matrix shape: // i.e. the contracting dim has size `num_cols` for LHS operands and // `num_rows` for RHS operands. int64_t num_rows; int64_t num_cols; Order order; int64_t leading_dim_stride; int64_t batch_size; int64_t batch_stride; // `batch_stride` is set to `0` when `batch_size == 1`. }; // GPU folding rule for the `TransposeFolding` pass. StatusOr<bool> CanFoldTransposeOperandIntoDot(const HloInstruction& dot, int64_t operand_idx); struct GemmConfig { static StatusOr<GemmConfig> For(const HloInstruction* gemm); static StatusOr<GemmConfig> For(mlir::lmhlo_gpu::GEMMOp op); static StatusOr<GemmConfig> For( const Shape& lhs_shape, absl::Span<const int64_t> lhs_batch_dims, absl::Span<const int64_t> lhs_contracting_dims, const Shape& rhs_shape, absl::Span<const int64_t> rhs_batch_dims, absl::Span<const int64_t> rhs_contracting_dims, const Shape& output_shape, double alpha_real, double alpha_imag, double beta, std::optional<int64_t> algorithm, int64_t compute_precision); MatrixLayout lhs_layout; MatrixLayout rhs_layout; MatrixLayout output_layout; complex128 alpha; double beta; std::optional<int64_t> algorithm; int64_t compute_precision; }; StatusOr<se::blas::ComputationType> GetBlasComputationType(PrimitiveType dtype); namespace cublas_lt { // Returns the type for the alpha and beta scalars. se::blas::DataType GetScaleType(se::blas::DataType c_type, se::blas::ComputationType computation_type); } // namespace cublas_lt // Run the given GEMM instruction `gemm` subject to the configuration // in `gemm_config` and the passed buffers. // // If `algorithm` is provided, it overrides the one specified in `config`. Status RunGemm(const GemmConfig& config, se::DeviceMemoryBase lhs_buffer, se::DeviceMemoryBase rhs_buffer, se::DeviceMemoryBase output_buffer, se::Stream* stream, std::optional<se::blas::AlgorithmType> algorithm = std::nullopt, se::blas::ProfileResult* profile_result = nullptr); namespace cublas_lt { StatusOr<bool> EpilogueAddsVectorBias(GemmBackendConfig_Epilogue epilogue); } // namespace cublas_lt StatusOr<se::blas::DataType> AsBlasDataType(PrimitiveType dtype); #if GOOGLE_CUDA namespace cublas_lt { StatusOr<se::cuda::BlasLt::Epilogue> AsBlasLtEpilogue( mlir::lmhlo_gpu::CublasLtMatmulEpilogue epilogue); class MatmulPlan { public: static StatusOr<MatmulPlan> For(mlir::lmhlo_gpu::CublasLtMatmulOp op); static StatusOr<MatmulPlan> From(const GemmConfig& config, se::cuda::BlasLt::Epilogue epilogue); Status ExecuteOnStream(se::Stream* stream, se::DeviceMemoryBase a_buffer, se::DeviceMemoryBase b_buffer, se::DeviceMemoryBase c_buffer, se::DeviceMemoryBase d_buffer, se::DeviceMemoryBase bias_buffer, // may be null const se::cuda::BlasLt::MatmulAlgorithm& algorithm, se::ScratchAllocator& scratch_allocator, se::blas::ProfileResult* profile_result = nullptr); StatusOr<std::vector<se::cuda::BlasLt::MatmulAlgorithm>> GetAlgorithms( se::Stream* stream) const; private: MatmulPlan(se::cuda::BlasLt::MatmulPlan plan, complex128 alpha, double beta, bool must_swap_operands) : plan_(std::move(plan)), alpha_(alpha), beta_(beta), must_swap_operands_(must_swap_operands) {} template <typename Input, typename Scale = Input> Status DoMatmul(se::Stream* stream, se::DeviceMemoryBase a_buffer, se::DeviceMemoryBase b_buffer, se::DeviceMemoryBase c_buffer, se::DeviceMemoryBase d_buffer, se::DeviceMemoryBase bias_buffer, // may be null const se::cuda::BlasLt::MatmulAlgorithm& algorithm, se::ScratchAllocator& scratch_allocator, se::blas::ProfileResult* profile_result); se::cuda::BlasLt::MatmulPlan plan_; complex128 alpha_; double beta_; bool must_swap_operands_; }; } // namespace cublas_lt #endif // GOOGLE_CUDA } // namespace gpu } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_SERVICE_GPU_MATMUL_UTILS_H_
{'content_hash': '62079d3b15dbaac124bf4a865320119c', 'timestamp': '', 'source': 'github', 'line_count': 181, 'max_line_length': 80, 'avg_line_length': 38.226519337016576, 'alnum_prop': 0.6528400057811823, 'repo_name': 'karllessard/tensorflow', 'id': 'ea18916471c1f6b5a356dd592abde4593db88e28', 'size': '7587', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tensorflow/compiler/xla/service/gpu/matmul_utils.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '36962'}, {'name': 'C', 'bytes': '1366182'}, {'name': 'C#', 'bytes': '13584'}, {'name': 'C++', 'bytes': '124800442'}, {'name': 'CMake', 'bytes': '183072'}, {'name': 'Cython', 'bytes': '5003'}, {'name': 'Dockerfile', 'bytes': '416070'}, {'name': 'Go', 'bytes': '2104698'}, {'name': 'HTML', 'bytes': '4686483'}, {'name': 'Java', 'bytes': '1074438'}, {'name': 'Jupyter Notebook', 'bytes': '792868'}, {'name': 'LLVM', 'bytes': '6536'}, {'name': 'MLIR', 'bytes': '11176792'}, {'name': 'Makefile', 'bytes': '2760'}, {'name': 'Objective-C', 'bytes': '169288'}, {'name': 'Objective-C++', 'bytes': '294187'}, {'name': 'Pawn', 'bytes': '5552'}, {'name': 'Perl', 'bytes': '7536'}, {'name': 'Python', 'bytes': '42620525'}, {'name': 'Roff', 'bytes': '5034'}, {'name': 'Ruby', 'bytes': '9199'}, {'name': 'Shell', 'bytes': '620121'}, {'name': 'Smarty', 'bytes': '89545'}, {'name': 'SourcePawn', 'bytes': '14607'}, {'name': 'Starlark', 'bytes': '7545879'}, {'name': 'Swift', 'bytes': '78435'}, {'name': 'Vim Snippet', 'bytes': '58'}]}
title: Advanced taxonomy: category: docs --- ### Chapter 3 # Advanced Get into the **nitty gritty** with these advanced topics
{'content_hash': '0520b40fcf8c6fc9322776fad2bcc3af', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 56, 'avg_line_length': 13.4, 'alnum_prop': 0.6940298507462687, 'repo_name': 'walzdev/docs-xmail', 'id': 'a53d707442602a84d8e62a08bb96f431b471beaf', 'size': '138', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'pages/03.advanced/chapter.md', 'mode': '33188', 'license': 'mit', 'language': []}
Version 0.0.12 -------------- * Fixed import errors of the **six** module. * Fixed an bug when decoding binary provider response resulted in an error. Version 0.0.11 -------------- * Added **Python 3.x** support thanks to `Emmanuel Leblond <https://github.com/touilleMan>`__. * Fixed a bug when :class:`.authomatic.Response` could not be decoded. * The :class:`.oauth2.Foursquare` provider now supports :attr:`.User.birth_date`. Version 0.0.10 -------------- * Fixed a bug when saving non-JSON-serializable values to third party sessions by the ``python-openid`` package caused a ``KeyError``. * Added the :class:`.oauth2.Eventbrite` provider. * Added the :class:`.oauth2.Amazon` provider. * Improved OAuth 2.0 Error Handling. Version 0.0.9 ------------- .. note:: This version is still in development and has not been released to `PyPI <https://pypi.python.org/pypi/Authomatic>`__ yet. * Updated *user info* URL scheme of the :class:`.oauth1.Yahoo` provider. * The :class:`.oauth2.Yandex` provider now supports :attr:`.User.name` and. :attr:`.User.username` properties. * Updated :class:`.oauth2.WindowsLive` |oauth2| endpoints. * Fixed a bug with the :class:`.oauth2.Yammer` provider when *user info* request failed because the ``token_type`` was not ``"Bearer"``. * The :class:`.oauth2.Yammer` provider now supports CSRF protection. * Added the ``logger`` keyword argument to :class:`.Authomatic` constructor. * Added the ``v=20140501`` parameter to each request of the :class:`.oauth2.Foursquare` provider. * The :class:`.oauth2.LinkedIn` provider now supports the :attr:`.User.birth_date` attribute. * The :class:`.oauth2.Reddit` provider now supports the :attr:`.User.username` attribute. Version 0.0.8 ------------- * Added the ``supported_user_attributes`` to tested provider classes. * The :class:`.oauth2.Facebook` provider now populates the :attr:`.User.city` and :attr:`.User.country` properties. * The :class:`.oauth2.Google` prowider now uses ``https://www.googleapis.com/plus/v1/people/me`` as the ``user_info_url`` instead of the deprecated ``https://www.googleapis.com/oauth2/v3/userinfo``. Also the ``user_info_scope`` reflects these changes. * Added missing ``user_info_scope`` to :class:`.oauth2.DeviantART` provider. * Changed the ``user_authorization_url`` of :class:`.oauth1.Twitter` provider from ``https://api.twitter.com/oauth/authorize`` to ``https://api.twitter.com/oauth/authenticate``. * Added the :class:`.oauth1.Xing` provider. * Made compatible with **Python 2.6**. Version 0.0.7 ------------- * Added user email extraction to :class:`.oauth1.Yahoo` provider. * Added the ``access_headers`` and ``access_params`` keyword arguments to the :class:`.AuthorizationProvider` constructor. * Fixed a bug in :class:`.oauth2.GitHub` provider when ``ValueError`` got risen when a user had only the city specified. * Added a workaround for `issue #11 <https://github.com/peterhudec/authomatic/issues/11>`__, when WebKit-based browsers failed to accept cookies set as part of a redirect response in some circumstances. Version 0.0.6 ------------- * Added the :class:`.DjangoAdapter`. * Switched the ``user_info_url`` attribute of the :class:`.oauth2.Google` provider to Google API ``v3``.
{'content_hash': '3bea2e2d4891d897ad81148e2d2d0ada', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 86, 'avg_line_length': 37.666666666666664, 'alnum_prop': 0.7012511443393348, 'repo_name': 'scorphus/authomatic', 'id': '023a83fd25f3cdaaefb8eafe39cee46e8b0a0a07', 'size': '3277', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CHANGES.rst', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '309043'}, {'name': 'CoffeeScript', 'bytes': '26033'}, {'name': 'HTML', 'bytes': '15368'}, {'name': 'JavaScript', 'bytes': '4916'}, {'name': 'Python', 'bytes': '409142'}, {'name': 'Ruby', 'bytes': '655'}, {'name': 'Shell', 'bytes': '1898'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_32) on Tue Jul 10 11:40:51 MST 2012 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> org.apache.log4j.lf5 Class Hierarchy (Apache Log4j 1.2.17-1 API) </TITLE> <META NAME="date" CONTENT="2012-07-10"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.log4j.lf5 Class Hierarchy (Apache Log4j 1.2.17-1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/log4j/jmx/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/log4j/lf5/util/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/log4j/lf5/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package org.apache.log4j.lf5 </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL> <LI TYPE="circle">org.apache.log4j.lf5.<A HREF="../../../../org/apache/log4j/lf5/AppenderFinalizer.html" title="class in org.apache.log4j.lf5"><B>AppenderFinalizer</B></A><LI TYPE="circle">org.apache.log4j.<A HREF="../../../../org/apache/log4j/AppenderSkeleton.html" title="class in org.apache.log4j"><B>AppenderSkeleton</B></A> (implements org.apache.log4j.<A HREF="../../../../org/apache/log4j/Appender.html" title="interface in org.apache.log4j">Appender</A>, org.apache.log4j.spi.<A HREF="../../../../org/apache/log4j/spi/OptionHandler.html" title="interface in org.apache.log4j.spi">OptionHandler</A>) <UL> <LI TYPE="circle">org.apache.log4j.lf5.<A HREF="../../../../org/apache/log4j/lf5/LF5Appender.html" title="class in org.apache.log4j.lf5"><B>LF5Appender</B></A></UL> <LI TYPE="circle">org.apache.log4j.lf5.<A HREF="../../../../org/apache/log4j/lf5/DefaultLF5Configurator.html" title="class in org.apache.log4j.lf5"><B>DefaultLF5Configurator</B></A> (implements org.apache.log4j.spi.<A HREF="../../../../org/apache/log4j/spi/Configurator.html" title="interface in org.apache.log4j.spi">Configurator</A>) <LI TYPE="circle">org.apache.log4j.lf5.<A HREF="../../../../org/apache/log4j/lf5/LogLevel.html" title="class in org.apache.log4j.lf5"><B>LogLevel</B></A> (implements java.io.<A HREF="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A>) <LI TYPE="circle">org.apache.log4j.lf5.<A HREF="../../../../org/apache/log4j/lf5/LogRecord.html" title="class in org.apache.log4j.lf5"><B>LogRecord</B></A> (implements java.io.<A HREF="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A>) <UL> <LI TYPE="circle">org.apache.log4j.lf5.<A HREF="../../../../org/apache/log4j/lf5/Log4JLogRecord.html" title="class in org.apache.log4j.lf5"><B>Log4JLogRecord</B></A></UL> <LI TYPE="circle">org.apache.log4j.lf5.<A HREF="../../../../org/apache/log4j/lf5/PassingLogRecordFilter.html" title="class in org.apache.log4j.lf5"><B>PassingLogRecordFilter</B></A> (implements org.apache.log4j.lf5.<A HREF="../../../../org/apache/log4j/lf5/LogRecordFilter.html" title="interface in org.apache.log4j.lf5">LogRecordFilter</A>) <LI TYPE="circle">org.apache.log4j.lf5.<A HREF="../../../../org/apache/log4j/lf5/StartLogFactor5.html" title="class in org.apache.log4j.lf5"><B>StartLogFactor5</B></A><LI TYPE="circle">java.lang.<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html?is-external=true" title="class or interface in java.lang"><B>Throwable</B></A> (implements java.io.<A HREF="http://java.sun.com/javase/6/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A>) <UL> <LI TYPE="circle">java.lang.<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Exception.html?is-external=true" title="class or interface in java.lang"><B>Exception</B></A><UL> <LI TYPE="circle">org.apache.log4j.lf5.<A HREF="../../../../org/apache/log4j/lf5/LogLevelFormatException.html" title="class in org.apache.log4j.lf5"><B>LogLevelFormatException</B></A></UL> </UL> </UL> </UL> <H2> Interface Hierarchy </H2> <UL> <LI TYPE="circle">org.apache.log4j.lf5.<A HREF="../../../../org/apache/log4j/lf5/LogRecordFilter.html" title="interface in org.apache.log4j.lf5"><B>LogRecordFilter</B></A></UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/log4j/jmx/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/log4j/lf5/util/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/log4j/lf5/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 1999-2012 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
{'content_hash': '24e79a1ee4c7ac7cc25254a55cb51bb3', 'timestamp': '', 'source': 'github', 'line_count': 173, 'max_line_length': 606, 'avg_line_length': 56.68208092485549, 'alnum_prop': 0.6388945543544768, 'repo_name': 'HBHBHB/log4j-android', 'id': '92552b19b83d8562b338c1e601f29ecab9d75a20', 'size': '9806', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'target/apidocs/org/apache/log4j/lf5/package-tree.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '7265'}, {'name': 'C++', 'bytes': '10639'}, {'name': 'CSS', 'bytes': '2195'}, {'name': 'Groff', 'bytes': '143048'}, {'name': 'HTML', 'bytes': '11081186'}, {'name': 'Java', 'bytes': '2299145'}, {'name': 'Perl', 'bytes': '2643'}, {'name': 'Perl6', 'bytes': '1808'}]}
/* # FLASHdispatch Styling # author: Hashtag Consulting */ /* # Global configuration */ html { height:100% !important; } body { min-height:100% !important; text-align: left; } /* # Main Menu Template */ .main-menu-container { display:inline-block; height:100% !important; min-width:200px; vertical-align: top; } /* # Content Elements */ .page { display: inline-block; padding-right:25px; text-align: left; max-width:1000px; } /* # Footer Elements */ .footer { padding-top:20px; font-size:11px; text-align: center; line-height:120%; }
{'content_hash': '4d7d56f564e379c15468e697c94791b2', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 29, 'avg_line_length': 11.895833333333334, 'alnum_prop': 0.6549912434325744, 'repo_name': 'raphacosta/easy-backbone-on-CI', 'id': '7a8451a70c372d32edb86b009587132c2f63e4a8', 'size': '571', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'css/theme.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '146132'}, {'name': 'JavaScript', 'bytes': '1184607'}, {'name': 'PHP', 'bytes': '1278183'}, {'name': 'Perl', 'bytes': '26'}, {'name': 'Shell', 'bytes': '2525'}]}
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (c) 2013 The CCP project authors. All Rights Reserved. Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license that can be found in the LICENSE file in the root of the web site. http://www.yuntongxun.com An additional intellectual property rights grant can be found in the file PATENTS. All contributing project authors may be found in the AUTHORS file in the root of the source tree. --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_ui_container" style="@style/NavPage" > <ListView android:id="@+id/lv_serverconfig" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentTop="true" android:cacheColorHint="#00000000" android:divider="@null" android:dividerHeight="0.0px" android:listSelector="@null" /> </RelativeLayout>
{'content_hash': 'ef1209ff72a40cbdc3311130b8905d2c', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 102, 'avg_line_length': 35.48275862068966, 'alnum_prop': 0.6870748299319728, 'repo_name': 'hairlun/radix-android', 'id': 'f016e0e909b51f5504b12865dd350ebe1d333055', 'size': '1029', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'res/layout/ec_serverconfig_list.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '3395011'}]}
<!-- Copyright 2015 The Chromium Authors Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <!DOCTYPE html> <html> <body> <p> This is a mock application which will play the role of the bad app in AppViewTest.KillGuest* tests. It always gets killed. </p> </body> </html>
{'content_hash': 'eeddf94e9819ae41a6f9c0c7bc8592a0', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 73, 'avg_line_length': 23.785714285714285, 'alnum_prop': 0.7057057057057057, 'repo_name': 'nwjs/chromium.src', 'id': 'ab87c479d10f3e78b317b1aa398b2533d8ec6660', 'size': '333', 'binary': False, 'copies': '6', 'ref': 'refs/heads/nw70', 'path': 'chrome/test/data/extensions/platform_apps/app_view/bad_app/window.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
package com.tarks.saosp; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import com.fima.cardsui.objects.CardStack; import com.fima.cardsui.views.CardUI; import com.tarks.saosp.start.join; import com.tarks.saosp.start.tarks_account_login; import com.tarks.saosp.start.welcome; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.AdapterView.OnItemClickListener; import android.widget.FrameLayout.LayoutParams; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewFlipper; public class StoryFragment extends Fragment { // 카드 유아이 정의한다. CardUI mCardView; private ListView maListViewPerso; private static final String ARG_POSITION = "position"; private int position; // drawable 정 Drawable drawable; // 년,월,일 int year; int month; int day; ImageView imgView; ViewFlipper flipper; private ImageView downloadedImg; //for downloader String myId, myPWord, myTitle, mySubject, myResult; private class Downloader extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... param) { // TODO Auto-generated method stub //Error Login return downloadBitmap(myId); } @Override protected void onPreExecute() { Log.i("Async-Example", "onPreExecute Called"); } protected void onPostExecute(Bitmap result) { Log.i("Async-Example", "onPostExecute Called"); //IF REsult Exist new ImageDownloader() .execute(myResult); } private Bitmap downloadBitmap(String url ) { try { // 자신의 신분 설정값을 불러옵니다. SharedPreferences prefs = getActivity().getSharedPreferences("setting", getActivity().MODE_PRIVATE); String grade = prefs.getString("student_grade", "000"); String school_class = prefs.getString("student_class", "000"); String number = prefs.getString("student_number", "000"); // -------------------------- // URL 설정하고 접속하기 // -------------------------- URL url1 = new URL( "http://tarks.net/buldangapp/background_info.php"); // URL // 설정 HttpURLConnection http = (HttpURLConnection) url1 .openConnection(); // 접속 // -------------------------- // 전송 모드 설정 - 기본적인 설정이다 // -------------------------- http.setDefaultUseCaches(false); http.setDoInput(true); // 서버에서 읽기 모드 지정 http.setDoOutput(true); // 서버로 쓰기 모드 지정 http.setRequestMethod("POST"); // 전송 방식은 POST // 서버에게 웹에서 <Form>으로 값이 넘어온 것과 같은 방식으로 처리하라는 걸 알려준다 http.setRequestProperty("content-type", "application/x-www-form-urlencoded"); // -------------------------- // 서버로 값 전송 // -------------------------- StringBuffer buffer = new StringBuffer(); buffer.append("buldangcode").append("=").append("558952") .append("&"); // php 변수에 값 대입 buffer.append("class").append("=").append(grade + school_class); OutputStreamWriter outStream = new OutputStreamWriter( http.getOutputStream(), "EUC-KR"); PrintWriter writer = new PrintWriter(outStream); writer.write(buffer.toString()); writer.flush(); // -------------------------- // 서버에서 전송받기 // -------------------------- InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "EUC-KR"); BufferedReader reader = new BufferedReader(tmp); StringBuilder builder = new StringBuilder(); String str; while ((str = reader.readLine()) != null) { // 서버에서 라인단위로 보내줄 것이므로 라인단위로 읽는다 builder.append(str); //구분자 추가 안함 // builder.append(str + "\n"); // View에 표시하기 위해 라인 구분자 추가 } myResult = builder.toString(); // 전송결과를 전역 변수에 저장 } catch (MalformedURLException e) { // } catch (IOException e) { // } return null; } } public static StoryFragment newInstance(int position) { StoryFragment f = new StoryFragment(); Bundle b = new Bundle(); b.putInt(ARG_POSITION, position); f.setArguments(b); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); position = getArguments().getInt(ARG_POSITION); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View fl = inflater.inflate(R.layout.story, container, false); // 자신의 신분 설정값을 불러옵니다. SharedPreferences prefs = getActivity().getSharedPreferences("setting", getActivity().MODE_PRIVATE); String grade = prefs.getString("student_grade", "000"); String school_class = prefs.getString("student_class", "000"); String number = prefs.getString("student_number", "000"); // TODO Auto-generated method stub downloadedImg = (ImageView) fl.findViewById(R.id.image); //Click to see more bigger image downloadedImg.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), imageview.class); intent.putExtra("url", myResult); startActivity(intent); } }); //Check Internet Connection ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); boolean isWifiAvail = ni.isAvailable(); boolean isWifiConn = ni.isConnected(); ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); boolean isMobileAvail = ni.isAvailable(); boolean isMobileConn = ni.isConnected(); // Check Internet Connection if (isWifiConn == true || isMobileConn == true) { // Connection Start new Downloader().execute(); } maListViewPerso = (ListView) fl.findViewById(R.id.listView1); // Création de la ArrayList qui nous permettra de remplire la listView ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>(); // On déclare la HashMap qui contiendra les informations pour un item HashMap<String, String> map; map = new HashMap<String, String>(); map.put("title", getString(R.string.story)); map.put("n", "1"); map.put("des", getString(R.string.not_support_feature)); map.put("img", String.valueOf(R.drawable.chat)); listItem.add(map); map = new HashMap<String, String>(); map.put("title", getString(R.string.school_story)); map.put("n", "1"); map.put("des", getString(R.string.not_support_feature)); map.put("img", String.valueOf(R.drawable.group)); listItem.add(map); map = new HashMap<String, String>(); map.put("title", "우리반 친구"); map.put("n", "2"); map.put("des", getString(R.string.not_support_feature)); map.put("img", String.valueOf(R.drawable.community_dark)); listItem.add(map); map = new HashMap<String, String>(); map.put("title", "게시판"); map.put("n", "3"); map.put("des", "게시판에서 정보공유"); map.put("img", String.valueOf(R.drawable.list)); listItem.add(map); map = new HashMap<String, String>(); map.put("title", getString(R.string.background_change)); map.put("n", "3"); map.put("des", getString(R.string.not_support_feature)); map.put("img", String.valueOf(R.drawable.list)); listItem.add(map); // Création d'un SimpleAdapter qui se chargera de mettre les items // présent dans notre list (listItem) dans la vue affichageitem SimpleAdapter mSchedule = new SimpleAdapter(getActivity() .getBaseContext(), listItem, R.layout.list2, new String[] { "img", "title", "des" }, new int[] { R.id.img, R.id.titre, R.id.description }); // On attribut à notre listView l'adapter que l'on vient de créer maListViewPerso.setAdapter(mSchedule); // Enfin on met un écouteur d'évènement sur notre listView maListViewPerso.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("unchecked") public void onItemClick(AdapterView<?> a, View v, int position, long id) { HashMap<String, String> map = (HashMap<String, String>) maListViewPerso .getItemAtPosition(position); if (map.get("n").matches("1")) { Intent intent = new Intent(getActivity(), story.class); // intent.putExtra("url", "http://tarks.net/buldangb"); startActivity(intent); } } }); return fl; } private class ImageDownloader extends AsyncTask<String, Void, Bitmap> { protected Bitmap doInBackground(String... param) { // TODO Auto-generated method stub return downloadBitmap(param[0]); } @Override protected void onPreExecute() { Log.i("Async-Example", "onPreExecute Called"); } protected void onPostExecute(Bitmap result) { Log.i("Async-Example", "onPostExecute Called"); downloadedImg.setImageBitmap(result); // simpleWaitDialog.dismiss(); } private Bitmap downloadBitmap(String url) { // initilize the default HTTP client object final DefaultHttpClient client = new DefaultHttpClient(); // forming a HttoGet request final HttpGet getRequest = new HttpGet(url); try { HttpResponse response = client.execute(getRequest); // check 200 OK for success final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { // getting contents from the stream inputStream = entity.getContent(); // decoding stream data back into image Bitmap that // android understands final Bitmap bitmap = BitmapFactory .decodeStream(inputStream); return bitmap; } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (Exception e) { // You Could provide a more explicit error message for // IOException getRequest.abort(); Log.e("ImageDownloader", "Something went wrong while" + " retrieving bitmap from " + url + e.toString()); } return null; } } }
{'content_hash': '6064a28117811c57f82b55400c6b44b4', 'timestamp': '', 'source': 'github', 'line_count': 396, 'max_line_length': 113, 'avg_line_length': 30.224747474747474, 'alnum_prop': 0.6581168017378227, 'repo_name': 'tarksgit/SAOSP', 'id': '5376f3938d71746a66940e269a27d4e0ec3f680d', 'size': '13041', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SAOSP/src/com/tarks/saosp/StoryFragment.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1126'}, {'name': 'Java', 'bytes': '584502'}]}
/** * @file unary_chain_remover.h * @author Chase Geigle * * All files in META are released under the MIT license. For more details, * consult the file LICENSE in the root of the project. */ #ifndef META_PARSE_UNARY_CHAIN_REMOVER_H_ #define META_PARSE_UNARY_CHAIN_REMOVER_H_ #include "parser/trees/visitors/tree_transformer.h" namespace meta { namespace parser { /** * Transforms trees by removing any unary X -> X rules. These may arise * from filtering out trace/empty nodes, for example, and may cause * problems in parsing if they persist. */ class unary_chain_remover : public tree_transformer { public: std::unique_ptr<node> operator()(const leaf_node&) override; std::unique_ptr<node> operator()(const internal_node&) override; }; } } #endif
{'content_hash': 'fa3ded1cb4efccefb550df60d1070511', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 74, 'avg_line_length': 23.454545454545453, 'alnum_prop': 0.7196382428940569, 'repo_name': 'husseinhazimeh/meta', 'id': 'b491a342d8e554dd7bf019e0adf04ca2c4e11efd', 'size': '774', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'include/parser/trees/visitors/unary_chain_remover.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2431'}, {'name': 'C++', 'bytes': '1069699'}, {'name': 'CMake', 'bytes': '24091'}, {'name': 'Python', 'bytes': '3197'}, {'name': 'Ruby', 'bytes': '248'}, {'name': 'Shell', 'bytes': '650'}]}
<?php namespace CodeIgniter\HTTP; /** * Expected behavior of an HTTP request * * @mixin \CodeIgniter\HTTP\IncomingRequest * @mixin \CodeIgniter\HTTP\CLIRequest * @mixin \CodeIgniter\HTTP\CURLRequest */ interface RequestInterface { /** * Gets the user's IP address. * * @return string IP address */ public function getIPAddress(): string; //-------------------------------------------------------------------- /** * Validate an IP address * * @param string $ip IP Address * @param string $which IP protocol: 'ipv4' or 'ipv6' * * @return bool */ public function isValidIP(string $ip, string $which = null): bool; //-------------------------------------------------------------------- /** * Get the request method. * * @param bool $upper Whether to return in upper or lower case. * * @return string */ public function getMethod($upper = false): string; //-------------------------------------------------------------------- /** * Fetch an item from the $_SERVER array. * * @param string $index Index for item to be fetched from $_SERVER * @param null $filter A filter name to be applied * @return mixed */ public function getServer($index = null, $filter = null); //-------------------------------------------------------------------- }
{'content_hash': 'b39da73e3abdd8ab55c090cd3ca8cef1', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 71, 'avg_line_length': 23.105263157894736, 'alnum_prop': 0.5125284738041003, 'repo_name': 'JakeAi/MinnichRW', 'id': '9306f518b0adf0d571ae84ae39c2f2ae2a917ae2', 'size': '2882', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'system/HTTP/RequestInterface.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '143163'}, {'name': 'HTML', 'bytes': '43514'}, {'name': 'JavaScript', 'bytes': '324797'}, {'name': 'Makefile', 'bytes': '4808'}, {'name': 'PHP', 'bytes': '3115963'}, {'name': 'PLSQL', 'bytes': '1411'}, {'name': 'Python', 'bytes': '11560'}]}
/* * Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { public partial class ModifyNetworkInterfaceAttributeResponse : AmazonWebServiceResponse { } }
{'content_hash': '289698853193471aa2ee45c51cb08957', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 101, 'avg_line_length': 19.857142857142858, 'alnum_prop': 0.7697841726618705, 'repo_name': 'ykbarros/aws-sdk-xamarin', 'id': 'd3caec89f01099d6d55654db271533729ff5ae41', 'size': '1004', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'AWS.XamarinSDK/AWSSDK_iOS-Classic/Amazon.EC2/Model/ModifyNetworkInterfaceAttributeResponse.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '70640975'}, {'name': 'PowerShell', 'bytes': '3661'}]}
package app; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { Shape circle = new Circle(5.5); Shape rect = new Rectangle(5.0, 6.0); List<Shape> list = new ArrayList<>(); list.add(circle); list.add((rect)); for(Shape shape: list){ System.out.println(shape.getArea()); System.out.println(shape.getPerimeter()); } } }
{'content_hash': 'a4c006af8aebd43b01fb041809354244', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 53, 'avg_line_length': 22.428571428571427, 'alnum_prop': 0.5732484076433121, 'repo_name': 'RosenGevshekov/SoftUni-Homeworks', 'id': 'ed54255a7d667eea20beb052fc106acd98eb5521', 'size': '471', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'JavaOOP/Shapes/src/app/Main.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '59700'}]}
package org.keycloak.testsuite.arquillian.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author mhajas */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface EnableVault { }
{'content_hash': '4dc9a37e1178d7b19b0b561fac181285', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 53, 'avg_line_length': 24.357142857142858, 'alnum_prop': 0.8035190615835777, 'repo_name': 'brat000012001/keycloak', 'id': 'ac56a5f49d843f06e787bab45a5d7b5ba42021d6', 'size': '341', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/annotation/EnableVault.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '4656'}, {'name': 'Batchfile', 'bytes': '8572'}, {'name': 'CSS', 'bytes': '86367'}, {'name': 'Dockerfile', 'bytes': '3788'}, {'name': 'FreeMarker', 'bytes': '167125'}, {'name': 'Gnuplot', 'bytes': '1817'}, {'name': 'Groovy', 'bytes': '4973'}, {'name': 'HTML', 'bytes': '959360'}, {'name': 'Java', 'bytes': '24141870'}, {'name': 'JavaScript', 'bytes': '2163842'}, {'name': 'Scala', 'bytes': '67175'}, {'name': 'Shell', 'bytes': '70659'}, {'name': 'TypeScript', 'bytes': '131455'}, {'name': 'XSLT', 'bytes': '35968'}]}
'use strict'; var Presence = require('node-xmpp-server').Presence, EventListener = require('./../event-listener'); module.exports = EventListener.extend({ on: 'presence:user_leave', then: function(data) { var connections = this.getConnectionsForRoom(data.roomId); connections.forEach(function(connection) { var presence = new Presence({ to: connection.jid(data.roomSlug), from: connection.getRoomJid(data.roomSlug, data.username), type: 'unavailable' }); var x = presence.c('x', { xmlns: 'http://jabber.org/protocol/muc#user' }); x.c('item', { jid: connection.getUserJid(data.username), role: 'none', affiliation: 'none' }); x.c('status', { code: '110' }); this.send(connection, presence); }, this); } });
{'content_hash': '8988eba2a1cc885d6627c2e567061e16', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 74, 'avg_line_length': 27.5, 'alnum_prop': 0.5070707070707071, 'repo_name': 'adam-nnl/lets-chat', 'id': '061a28847f5cc10340ff7e8235cc01977357d542', 'size': '990', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'app/xmpp/events/user-leave.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '23651'}, {'name': 'HTML', 'bytes': '46590'}, {'name': 'JavaScript', 'bytes': '251042'}]}
#import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** The KeychainItemWrapper class is an abstraction layer for the iPhone Keychain communication. This is merely a simple wrapper to provide a distinct barrier between all the idiosyncracies involved with the Keychain CF/NS container objects. */ @interface BMKeychainItemWrapper : NSObject /** Value transformer for converting the value data. The forward transformation should be to NSData and the value transformer should support reverse transformation. By default the value is transformed to a NSString using UTF8 encoding. If set to nil the NSData from the keychain is not transformed. */ @property (nullable, nonatomic, readonly) NSValueTransformer *valueDataTransformer; /** Designated initializer. Initializes with the supplied identifier and optional accessGroup (in case more than one application from the same company share the same keychain, see Apple documentation for more info). */ - (id)initWithIdentifier: (NSString *)identifier accessGroup:(nullable NSString *) accessGroup; - (id)initWithIdentifier: (NSString *)identifier accessGroup:(nullable NSString *) accessGroup valueDataTransformer:(nullable NSValueTransformer *)transformer NS_DESIGNATED_INITIALIZER; /** Sets the object for the specified key and flushes immediately. */ - (void)setObject:(id)inObject forKey:(id)key; /** Sets the object for the specified key and optionally flushes immediately. */ - (void)setObject:(id)inObject forKey:(id)key flush:(BOOL)flush; /** Sets the object and keys that exist in the specified dictionary (leaves other keys untouched). Flushes immediately. */ - (void)setObjectAndKeysFromDictionary:(NSDictionary *)dictionary; /** Returns the object for the specified key. */ - (nullable id)objectForKey:(id)key; /** Initializes and resets the default generic keychain item data. */ - (void)resetKeychainItem; /** Flushes the keychain. */ - (void)flush; @end NS_ASSUME_NONNULL_END
{'content_hash': '66dab53519fffaa4e4f9d95da4a7a54a', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 188, 'avg_line_length': 29.83582089552239, 'alnum_prop': 0.7708854427213607, 'repo_name': 'werner77/BMCommons', 'id': '0128aadffaf7a4b449899057bc63a8a3065fca45', 'size': '4497', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'BMCommons/Modules/BMCore/Sources/Classes/BMKeychainItemWrapper.h', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '13714'}, {'name': 'Objective-C', 'bytes': '3313720'}, {'name': 'Ruby', 'bytes': '3711'}, {'name': 'Shell', 'bytes': '1120'}]}
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; using System.Threading.Tasks; using Bibliotheca.Server.Gateway.Core.DataTransferObjects; using Bibliotheca.Server.Gateway.Core.Exceptions; using Bibliotheca.Server.Gateway.Core.HttpClients; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; namespace Bibliotheca.Server.Gateway.Core.Services { public class DocumentsService : IDocumentsService { private readonly IDocumentsClient _documentsClient; private readonly IBranchesService _branchService; private readonly IProjectsService _projectsService; private readonly ICacheService _cacheService; private readonly ILogger<DocumentsService> _logger; public DocumentsService( IDocumentsClient documentsClient, IBranchesService branchService, IProjectsService projectsService, ICacheService cacheService, ILogger<DocumentsService> logger) { _documentsClient = documentsClient; _branchService = branchService; _projectsService = projectsService; _cacheService = cacheService; _logger = logger; } public async Task<IList<BaseDocumentDto>> GetDocumentsAsync(string projectId, string branchName) { var documentsDto = await _documentsClient.Get(projectId, branchName); return documentsDto; } public async Task<DocumentDto> GetDocumentAsync(string projectId, string branchName, string fileUri) { DocumentDto documentDto = null; if(branchName == null || branchName == "undefined") { branchName = await GetDefaultBranch(projectId); } if(fileUri == null || fileUri == "undefined") { fileUri = await GetDefaultFileUri(projectId, branchName); } if (!_cacheService.TryGetDocument(projectId, branchName, fileUri, out documentDto)) { documentDto = await _documentsClient.Get(projectId, branchName, fileUri); _cacheService.AddDocument(projectId, branchName, fileUri, documentDto); } return documentDto; } public async Task CreateDocumentAsync(string projectId, string branchName, DocumentDto document) { var result = await _documentsClient.Post(projectId, branchName, document); if(!result.IsSuccessStatusCode) { var content = await result.Content.ReadAsStringAsync(); throw new CreateDocumentException("During creating document error occurs: " + content); } var fileUri = document.Uri.Replace("/", ":"); _cacheService.ClearDocumentCache(projectId, branchName, fileUri); } public async Task UpdateDocumentAsync(string projectId, string branchName, string fileUri, DocumentDto document) { var result = await _documentsClient.Put(projectId, branchName, fileUri, document); if(!result.IsSuccessStatusCode) { var content = await result.Content.ReadAsStringAsync(); throw new UpdateDocumentException("During updating document error occurs: " + content); } _cacheService.ClearDocumentCache(projectId, branchName, fileUri); } public async Task UploadBranchAsync(string projectId, string branchName, Stream body, StringBuilder logs) { byte[] mkdocsContent = null; Dictionary<string, byte[]> filesContent = new Dictionary<string, byte[]>(); LogInformation(logs, $"Unzipping file ({projectId}/{branchName})."); using (var zipArchive = new ZipArchive(body)) { var entries = zipArchive.Entries; foreach (var entry in entries) { bool isDirectory = entry.FullName.EndsWith("/"); if (!isDirectory) { LogInformation(logs, $"Reading file: '{entry.FullName}'."); byte[] content = null; using (var stream = entry.Open()) using (MemoryStream ms = new MemoryStream()) { stream.CopyTo(ms); content = ms.ToArray(); } var fileUri = GetPathWithoutRootDirectory(entry.FullName); if(fileUri == "mkdocs.yml") { LogInformation(logs, $"mkdocs.yml file was founded."); mkdocsContent = content; } else { filesContent.Add(fileUri, content); } } } } if(mkdocsContent == null) { throw new BranchConfigurationFileNotExistsException("Zip file have to contains mkdocs.yml file."); } LogInformation(logs, $"Creating folder for branch ({projectId}/{branchName})."); await CreateBranchAsync(projectId, branchName, mkdocsContent); LogInformation(logs, $"Folder for branch was created ({projectId}/{branchName})."); int counter = 0; foreach(var item in filesContent) { counter++; LogInformation(logs, $"Uploading file '{item.Key}' ({counter}/{filesContent.Count})."); await UploadDocumnentAsync(projectId, branchName, item.Key, item.Value); LogInformation(logs, $"File was uploaded '{item.Key}' ({counter}/{filesContent.Count})."); } } public async Task DeleteDocumentAsync(string projectId, string branchName, string fileUri) { var result = await _documentsClient.Delete(projectId, branchName, fileUri); if(!result.IsSuccessStatusCode) { var content = await result.Content.ReadAsStringAsync(); throw new DeleteDocumentException("During deleting document error occurs: " + content); } _cacheService.ClearDocumentCache(projectId, branchName, fileUri); } private async Task CreateBranchAsync(string projectId, string branchName, byte[] content) { string mkdocsContent = Encoding.UTF8.GetString(content); var branch = new BranchDto { Name = branchName, MkDocsYaml = mkdocsContent }; await _branchService.CreateBranchAsync(projectId, branch); } private async Task UploadDocumnentAsync(string projectId, string branchName, string fileUri, byte[] content) { var fileName = Path.GetFileName(fileUri); var document = new DocumentDto { Content = content, Uri = fileUri, Name = fileName }; await CreateDocumentAsync(projectId, branchName, document); } private string GetPathWithoutRootDirectory(string path) { var parts = path.Split('/'); string newPath = string.Empty; for(int i = 1; i < parts.Length; ++i) { newPath = Path.Combine(newPath, parts[i]); } return newPath; } private async Task<string> GetDefaultBranch(string projectId) { var project = await _projectsService.GetProjectAsync(projectId); if(project == null) { throw new ProjectNotFoundException($"I cannot find default branch. Project '{projectId}' not found."); } return project.DefaultBranch; } private async Task<string> GetDefaultFileUri(string projectId, string branchName) { var branch = await _branchService.GetBranchAsync(projectId, branchName); if(branch == null) { throw new BranchNotFoundException($"I cannot calculate default file uri. Branch '' not found."); } var fileUri = $"{branch.DocsDir}:index.md"; return fileUri; } private void LogInformation(StringBuilder stringBuilder, string message) { stringBuilder.AppendLine($"[{DateTime.UtcNow}] {message}"); _logger.LogInformation($"[Uploading] {message}."); } } }
{'content_hash': 'ecf8e25357d19a54552c2b155e63e33b', 'timestamp': '', 'source': 'github', 'line_count': 230, 'max_line_length': 120, 'avg_line_length': 38.35217391304348, 'alnum_prop': 0.5712504251218683, 'repo_name': 'BibliothecaTeam/Bibliotheca.Server.Gateway', 'id': '0ac5667ac9a0cfb909f0eb6369a02a15b1964c62', 'size': '8821', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Bibliotheca.Server.Gateway.Core/Services/DocumentsService.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '293094'}, {'name': 'Shell', 'bytes': '61'}]}
--TEST-- Test array_diff_key() function : usage variation - Passing unexpected values to second argument --FILE-- <?php /* Prototype : array array_diff_key(array arr1, array arr2 [, array ...]) * Description: Returns the entries of arr1 that have keys which are not present in any of the others arguments. * Source code: ext/standard/array.c */ echo "*** Testing array_diff_key() : usage variation ***\n"; // Initialise function arguments not being substituted (if any) $array1 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8); $array3 = array(1, 2, 3, 4, 5); //get an unset variable $unset_var = 10; unset ($unset_var); //resource variable $fp = fopen(__FILE__, "r"); // define some classes class classWithToString { public function __toString() { return "Class A object"; } } class classWithoutToString { } // heredoc string $heredoc = <<<EOT hello world EOT; //array of values to iterate over $inputs = array( // int data 'int 0' => 0, 'int 1' => 1, 'int 12345' => 12345, 'int -12345' => -12345, // float data 'float 10.5' => 10.5, 'float -10.5' => -10.5, 'float 12.3456789000e10' => 12.3456789000e10, 'float -12.3456789000e10' => -12.3456789000e10, 'float .5' => .5, // null data 'uppercase NULL' => NULL, 'lowercase null' => null, // boolean data 'lowercase true' => true, 'lowercase false' =>false, 'uppercase TRUE' =>TRUE, 'uppercase FALSE' =>FALSE, // empty data 'empty string DQ' => "", 'empty string SQ' => '', // string data 'string DQ' => "string", 'string SQ' => 'string', 'mixed case string' => "sTrInG", 'heredoc' => $heredoc, // object data 'instance of classWithToString' => new classWithToString(), 'instance of classWithoutToString' => new classWithoutToString(), // undefined data 'undefined var' => @$undefined_var, // unset data 'unset var' => @$unset_var, // resource data 'resource' => $fp, ); // loop through each element of the array for arr1 foreach($inputs as $key =>$value) { echo "\n--$key--\n"; var_dump( array_diff_key($array1, $value) ); var_dump( array_diff_key($array1, $value, $array3) ); }; fclose($fp); ?> ===DONE=== --EXPECTF-- *** Testing array_diff_key() : usage variation *** --int 0-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --int 1-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --int 12345-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --int -12345-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --float 10.5-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --float -10.5-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --float 12.3456789000e10-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --float -12.3456789000e10-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --float .5-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --uppercase NULL-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --lowercase null-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --lowercase true-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --lowercase false-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --uppercase TRUE-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --uppercase FALSE-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --empty string DQ-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --empty string SQ-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --string DQ-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --string SQ-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --mixed case string-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --heredoc-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --instance of classWithToString-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --instance of classWithoutToString-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --undefined var-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --unset var-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL --resource-- Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL Warning: array_diff_key(): Argument #2 is not an array in %s on line %d NULL ===DONE===
{'content_hash': '3bd9125ec13f6bc283593014c82d4510', 'timestamp': '', 'source': 'github', 'line_count': 311, 'max_line_length': 113, 'avg_line_length': 22.411575562700964, 'alnum_prop': 0.6502152080344333, 'repo_name': 'ericpp/hippyvm', 'id': '737ee2e57f45d4ea88efdc6e77a6e00c47833283', 'size': '6970', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'test_phpt/ext/standard/array/array_diff_key_variation2.phpt', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '86842'}, {'name': 'Python', 'bytes': '446089'}]}
/** * Created by Mark Sarukhanov on 29.07.2016. */ var uuid = require('node-uuid'); var multiR = client.multi(); var helper = require('./helperFunctions'); module.exports = { setUser : function(id, data, callback) { console.log(id); client.set('token:' + id, JSON.stringify(data), callback); }, getUser : function(id, callback) { client.get('token:' + id, callback); }, delUser : function(id, callback) { client.del('token:' + id, callback); }, customer : function (customer_id, what, data, callback) { switch (what) { case 'add': client.hset('customer:', customer_id, JSON.stringify(data.customer_info), callback); break; case 'edit': client.hset('customer:', data.customer_id, JSON.stringify(data.customer_info), callback); break; case 'all': client.hgetall('customer:', callback); break; case 'get': client.hget('customer:', customer_id, callback); break; case 'del': client.hdel('customer:', customer_id, callback); break; case 'config': client.get('customer:' + customer_id + ':config', callback); break; } }, user : function (customer_id, what, data, callback) { var userData, devUser, uniqId, now; switch (what) { case 'all': client.hgetall('customer:' + customer_id + ':users:', callback); break; case 'get': client.hget('customer:' + customer_id + ':users:', data, callback); break; case 'del': client.hdel('customer:' + customer_id + ':users:', data, function(err, resp) { client.hdel('devusers:', data, function (errD, respD) { callback(err, resp); }) }); break; case 'add': client.hset('customer:' + customer_id + ':users:', "" + data.login, JSON.stringify(data.user_info), function(err, resp){ client.hset('devusers:', "" + devUser.login, JSON.stringify({login : data.user_info.login, password : data.user_info.password, customer : data.user_info.customer}), function(errD, respD){ callback(err, resp); }); }); break; case 'edit': client.hset('customer:' + customer_id + ':users:', "" + data.user_id, JSON.stringify(data.user_info), function(err, resp) { client.hset('devusers:', "" + devUser.login, JSON.stringify({login : data.user_info.login, password : data.user_info.password, customer : data.user_info.customer}), function (errD, respD) { callback(err, resp); }) }); break; case 'devget': client.hget('devusers:', "" + data, callback); break; case 'dev-all': client.hgetall('devusers:', callback); break; } }, clients : function (customer_id, what, data, callback) { switch (what) { case 'add': client.hset('customer:' + customer_id + ':clients:', "" + uuid.v4(), JSON.stringify(data.client_info), callback); break; case 'edit': client.hset('customer:' + customer_id + ':clients:', "" + data.client_id, "" + JSON.stringify(data.client_info), callback); break; case 'all': client.hgetall('customer:' + customer_id + ':clients:', callback); break; case 'get': client.hget('customer:' + customer_id + ':clients:', data.client_id, callback); break; case 'del': client.hdel('customer:' + customer_id + ':clients:', data.client_id, callback); break; } }, transactions : function (customer_id, what, date, data, callback) { switch (what) { case 'add': multiR.hset('customer:' + customer_id + ':transactions:' , data.id, JSON.stringify(data)); multiR.hset('customer:' + customer_id + ':user:transactions:' + data.doctor_id , data.id, data.id); multiR.hset('customer:' + customer_id + ':daily:transactions:' + date, data.id, data.id); if(data.client_id) multiR.hset('customer:' + customer_id + ':client:' + data.client_id +':transactions:', data.id, ''); multiR.exec(callback); break; case 'edit': client.hset('customer:' + customer_id + ':transactions:', "" + data.transaction_id, "" + JSON.stringify(data.transaction_info), callback); break; case 'get-by-customer': client.hgetall('customer:' + customer_id + ':transactions:', callback); break; case 'get-by-users': client.hmget('customer:' + customer_id + ':user:transactions:', data.users, callback); break; case 'get-by-client': client.hget('customer:' + customer_id + ':client:' + data + ':transactions:', callback); break; case 'get-by-date': client.hmget('customer:' + customer_id + ':daily:transactions:', data, callback); break; case 'get-by-id': client.hget('customer:' + customer_id + ':transactions:', data.id, callback); break; case 'del': multiR.hdel('customer:' + customer_id + ':transactions:' , data.id); multiR.hdel('customer:' + customer_id + ':user:transactions:' + data.user_id , data.id); multiR.hdel('customer:' + customer_id + ':daily:transactions:' + date, data.id); if(data.client_id) multiR.hdel('customer:' + customer_id + ':client:' + data.client_id +':transactions:', data.id); multiR.exec(callback); break; } }, events : function (customer_id, what, date, data, callback) { switch (what) { case 'add': console.log('customer:' + customer_id + ':events:' , data.id, JSON.stringify(data)); console.log('customer:' + customer_id + ':user:events:' + data.doctor_id , data.id, data.id); console.log('customer:' + customer_id + ':daily:events:' + date, data.id, data.id); multiR.hset('customer:' + customer_id + ':events:' , data.id, JSON.stringify(data)); multiR.hset('customer:' + customer_id + ':user:events:' + data.user_id , data.id, data.id); multiR.hset('customer:' + customer_id + ':daily:events:' + date, data.id, data.id); if(data.client_id) multiR.hset('customer:' + customer_id + ':client:' + data.client_id +':events:', data.id, ''); multiR.exec(callback); break; case 'edit': client.hset('customer:' + customer_id + ':events:', "" + data.transaction_id, "" + JSON.stringify(data.transaction_info), callback); break; case 'get-by-customer': client.hgetall('customer:' + customer_id + ':events:', callback); break; case 'get-by-users': client.hmget('customer:' + customer_id + ':user:events:', data.users, callback); break; case 'get-by-client': client.hget('customer:' + customer_id + ':client:' + data + ':events:', callback); break; case 'get-by-date': //client.hmget('customer:' + customer_id + ':daily:events:', data, callback); callback _.each(data, function(item){ multiR.hgetall('customer:admin:daily:events:' + item); }); multiR.exec(function(err, resp){ var keys = []; _.each(resp, function(day, key){ if(day && day!= 'null') keys = keys.concat(_.keys(day)) }); client.hmget('customer:' + customer_id + ':events:', keys, function(err, bydays){ _.each(bydays, function(day, key){ bydays[key] = JSON.parse(day)}); bydays = _.groupBy(bydays, function(item) {return helper.formattedDate(item.dt)}); callback(err, bydays); }); }); break; case 'get-by-id': client.hget('customer:' + customer_id + ':events:', data, callback); break; case 'del': multiR.hdel('customer:' + customer_id + ':events:' , data.id); multiR.hdel('customer:' + customer_id + ':user:events:' + data.user_id , data.id); multiR.hdel('customer:' + customer_id + ':daily:events:' + date, data.id); if(data.client_id) multiR.hdel('customer:' + customer_id + ':client:' + data.client_id +':events:', data.id); multiR.exec(callback); break; } }, upcomingEvent : function (customer_id, what, data, callback) { var date; if(data && data.date) date = "" + new Date(data.date).getDay() + "-" + new Date(data.date).getMonth() + "-" + new Date(data.date).getFullYear(); switch (what) { case 'add': client.hset('customer:' + customer_id +':upcomingEvents:', "" + uuid.v4(), JSON.stringify(data.upcomingEvent), callback); break; case 'edit': client.hset('customer:' + customer_id +':upcomingEvents:', data.id, JSON.stringify(data.upcomingEvent), callback); break; case 'all': client.hgetall('customer:' + customer_id +':upcomingEvents:', callback); break; case 'get': client.hget('customer:' + customer_id +':upcomingEvents:', data.id, callback); break; case 'del': client.hdel('customer:' + customer_id +':upcomingEvents:', data.id, callback); break; } } };
{'content_hash': '7ee34dda0e922713c1e3bd1205b6c86f', 'timestamp': '', 'source': 'github', 'line_count': 219, 'max_line_length': 209, 'avg_line_length': 47.986301369863014, 'alnum_prop': 0.49671709962888955, 'repo_name': 'crm-node/alpha', 'id': '03de5a1a3ffb8d95cd033256f268bcd3f927e688', 'size': '10509', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'middleware/redisRequests.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '114281'}, {'name': 'HTML', 'bytes': '132180'}, {'name': 'JavaScript', 'bytes': '381752'}]}
#ifndef GrTextureStripAtlas_DEFINED #define GrTextureStripAtlas_DEFINED #include "SkBitmap.h" #include "GrTHashCache.h" #include "SkGr.h" #include "SkTDArray.h" #include "GrBinHashKey.h" /** * Maintains a single large texture whose rows store many textures of a small fixed height, * stored in rows across the x-axis such that we can safely wrap/repeat them horizontally. */ class GrTextureStripAtlas { public: /** * Descriptor struct which we'll use as a hash table key **/ struct Desc { Desc() { memset(this, 0, sizeof(*this)); } uint16_t fWidth, fHeight, fRowHeight; GrPixelConfig fConfig; GrContext* fContext; const uint32_t* asKey() const { return reinterpret_cast<const uint32_t*>(this); } }; /** * Try to find an atlas with the required parameters, creates a new one if necessary */ static GrTextureStripAtlas* GetAtlas(const Desc& desc); ~GrTextureStripAtlas(); /** * Add a texture to the atlas * @param data Bitmap data to copy into the row * @return The row index we inserted into, or -1 if we failed to find an open row. The caller * is responsible for calling unlockRow() with this row index when it's done with it. */ int lockRow(const SkBitmap& data); void unlockRow(int row); /** * These functions help turn an integer row index in [0, 1, 2, ... numRows] into a scalar y * texture coordinate in [0, 1] that we can use in a shader. * * If a regular texture access without using the atlas looks like: * * texture2D(sampler, vec2(x, y)) * * Then when using the atlas we'd replace it with: * * texture2D(sampler, vec2(x, yOffset + y * scaleFactor)) * * Where yOffset, returned by getYOffset(), is the offset to the start of the row within the * atlas and scaleFactor, returned by getVerticalScaleFactor(), is the y-scale of the row, * relative to the height of the overall atlas texture. */ SkScalar getYOffset(int row) const { return SkIntToScalar(row) / fNumRows; } SkScalar getVerticalScaleFactor() const { return SkIntToScalar(fDesc.fRowHeight) / fDesc.fHeight; } GrContext* getContext() const { return fDesc.fContext; } GrTexture* getTexture() const { return fTexture; } private: // Key to indicate an atlas row without any meaningful data stored in it const static uint32_t kEmptyAtlasRowKey = 0xffffffff; /** * The state of a single row in our cache, next/prev pointers allow these to be chained * together to represent LRU status */ struct AtlasRow : public GrNoncopyable { AtlasRow() : fKey(kEmptyAtlasRowKey), fLocks(0), fNext(NULL), fPrev(NULL) { } // GenerationID of the bitmap that is represented by this row, 0xffffffff means "empty" uint32_t fKey; // How many times this has been locked (0 == unlocked) int32_t fLocks; // We maintain an LRU linked list between unlocked nodes with these pointers AtlasRow* fNext; AtlasRow* fPrev; }; /** * We'll only allow construction via the static GrTextureStripAtlas::GetAtlas */ GrTextureStripAtlas(Desc desc); void lockTexture(); void unlockTexture(); /** * Initialize our LRU list (if one already exists, clear it and start anew) */ void initLRU(); /** * Grabs the least recently used free row out of the LRU list, returns NULL if no rows are free. */ AtlasRow* getLRU(); void appendLRU(AtlasRow* row); void removeFromLRU(AtlasRow* row); /** * Searches the key table for a key and returns the index if found; if not found, it returns * the bitwise not of the index at which we could insert the key to maintain a sorted list. **/ int searchByKey(uint32_t key); /** * Compare two atlas rows by key, so we can sort/search by key */ static bool KeyLess(const AtlasRow& lhs, const AtlasRow& rhs) { return lhs.fKey < rhs.fKey; } #ifdef SK_DEBUG void validate(); #endif /** * Clean up callback registered with GrContext. Allows this class to * free up any allocated AtlasEntry and GrTextureStripAtlas objects */ static void CleanUp(const GrContext* context, void* info); // Hash table entry for atlases class AtlasEntry; typedef GrTBinHashKey<AtlasEntry, sizeof(GrTextureStripAtlas::Desc)> AtlasHashKey; class AtlasEntry : public ::GrNoncopyable { public: AtlasEntry() : fAtlas(NULL) {} ~AtlasEntry() { SkDELETE(fAtlas); } int compare(const AtlasHashKey& key) const { return fKey.compare(key); } AtlasHashKey fKey; GrTextureStripAtlas* fAtlas; }; static GrTHashTable<AtlasEntry, AtlasHashKey, 8>* gAtlasCache; static GrTHashTable<AtlasEntry, AtlasHashKey, 8>* GetCache(); // We increment gCacheCount for each atlas static int32_t gCacheCount; // A unique ID for this texture (formed with: gCacheCount++), so we can be sure that if we // get a texture back from the texture cache, that it's the same one we last used. const int32_t fCacheKey; // Total locks on all rows (when this reaches zero, we can unlock our texture) int32_t fLockedRows; const Desc fDesc; const uint16_t fNumRows; GrTexture* fTexture; // Array of AtlasRows which store the state of all our rows. Stored in a contiguous array, in // order that they appear in our texture, this means we can subtract this pointer from a row // pointer to get its index in the texture, and can save storing a row number in AtlasRow. AtlasRow* fRows; // Head and tail for linked list of least-recently-used rows (front = least recently used). // Note that when a texture is locked, it gets removed from this list until it is unlocked. AtlasRow* fLRUFront; AtlasRow* fLRUBack; // A list of pointers to AtlasRows that currently contain cached images, sorted by key SkTDArray<AtlasRow*> fKeyTable; }; #endif
{'content_hash': 'c7d3bcb15b5257859972cd8e11b63930', 'timestamp': '', 'source': 'github', 'line_count': 176, 'max_line_length': 103, 'avg_line_length': 34.57386363636363, 'alnum_prop': 0.6700082169268694, 'repo_name': 'Frankie-666/color-emoji.skia', 'id': '0148665a4c4b9ffeacac009fa5eeeefffcb99d51', 'size': '6228', 'binary': False, 'copies': '25', 'ref': 'refs/heads/master', 'path': 'src/gpu/effects/GrTextureStripAtlas.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '10259'}, {'name': 'Batchfile', 'bytes': '1071'}, {'name': 'C', 'bytes': '765704'}, {'name': 'C++', 'bytes': '13378021'}, {'name': 'CSS', 'bytes': '2042'}, {'name': 'HTML', 'bytes': '884432'}, {'name': 'Java', 'bytes': '16199'}, {'name': 'Makefile', 'bytes': '4209'}, {'name': 'Objective-C', 'bytes': '21731'}, {'name': 'Objective-C++', 'bytes': '108175'}, {'name': 'Python', 'bytes': '272877'}, {'name': 'Shell', 'bytes': '35396'}]}
import os import sys import unittest import mock from oslo_config import cfg from st2common.constants.pack import SYSTEM_PACK_NAMES from st2common.util.sandboxing import get_sandbox_path from st2common.util.sandboxing import get_sandbox_python_path from st2common.util.sandboxing import get_sandbox_python_binary_path import st2tests.config as tests_config class SandboxingUtilsTestCase(unittest.TestCase): @classmethod def setUpClass(cls): tests_config.parse_args() def test_get_sandbox_python_binary_path(self): # Non-system content pack, should use pack specific virtualenv binary result = get_sandbox_python_binary_path(pack='mapack') expected = os.path.join(cfg.CONF.system.base_path, 'virtualenvs/mapack/bin/python') self.assertEqual(result, expected) # System content pack, should use current process (system) python binary result = get_sandbox_python_binary_path(pack=SYSTEM_PACK_NAMES[0]) self.assertEqual(result, sys.executable) def test_get_sandbox_path(self): # Mock the current PATH value old_path = os.environ.get('PATH', '') os.environ['PATH'] = '/home/path1:/home/path2:/home/path3:' virtualenv_path = '/home/venv/test' result = get_sandbox_path(virtualenv_path=virtualenv_path) self.assertEqual(result, '/home/venv/test/bin/:/home/path1:/home/path2:/home/path3') os.environ['PATH'] = old_path @mock.patch('st2common.util.sandboxing.get_python_lib') def test_get_sandbox_python_path(self, mock_get_python_lib): # No inheritence python_path = get_sandbox_python_path(inherit_from_parent=False, inherit_parent_virtualenv=False) self.assertEqual(python_path, ':') # Inherit python path from current process # Mock the current process python path old_python_path = os.environ.get('PYTHONPATH', '') os.environ['PYTHONPATH'] = ':/data/test1:/data/test2' python_path = get_sandbox_python_path(inherit_from_parent=True, inherit_parent_virtualenv=False) self.assertEqual(python_path, ':/data/test1:/data/test2') # Inherit from current process and from virtualenv (not running inside virtualenv) old_real_prefix = sys.real_prefix del sys.real_prefix python_path = get_sandbox_python_path(inherit_from_parent=True, inherit_parent_virtualenv=False) self.assertEqual(python_path, ':/data/test1:/data/test2') # Inherit from current process and from virtualenv (running inside virtualenv) sys.real_prefix = '/usr' mock_get_python_lib.return_value = sys.prefix + '/virtualenvtest' python_path = get_sandbox_python_path(inherit_from_parent=True, inherit_parent_virtualenv=True) self.assertEqual(python_path, ':/data/test1:/data/test2:%s/virtualenvtest' % (sys.prefix)) os.environ['PYTHONPATH'] = old_python_path sys.real_prefix = old_real_prefix
{'content_hash': '866ff2037f90558db8e6b637b4b1613c', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 92, 'avg_line_length': 43.0, 'alnum_prop': 0.6508485229415462, 'repo_name': 'dennybaa/st2', 'id': 'd30b1d0d8c1f65a42f674aa59e077d37f724e71e', 'size': '3182', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'st2common/tests/unit/test_util_sandboxing.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '198'}, {'name': 'Makefile', 'bytes': '37319'}, {'name': 'PowerShell', 'bytes': '299'}, {'name': 'Python', 'bytes': '3306365'}, {'name': 'Shell', 'bytes': '27148'}, {'name': 'Slash', 'bytes': '677'}]}
/** * This file tests the methods on XPCOMUtils.jsm. */ Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); const Cc = Components.classes; const Ci = Components.interfaces; //////////////////////////////////////////////////////////////////////////////// //// Tests function test_generateQI_string_names() { var x = { QueryInterface: XPCOMUtils.generateQI([ Components.interfaces.nsIClassInfo, "nsIDOMNode" ]) }; try { x.QueryInterface(Components.interfaces.nsIClassInfo); } catch(e) { do_throw("Should QI to nsIClassInfo"); } try { x.QueryInterface(Components.interfaces.nsIDOMNode); } catch(e) { do_throw("Should QI to nsIDOMNode"); } try { x.QueryInterface(Components.interfaces.nsIDOMDocument); do_throw("QI should not have succeeded!"); } catch(e) {} } function test_defineLazyGetter() { let accessCount = 0; let obj = { inScope: false }; const TEST_VALUE = "test value"; XPCOMUtils.defineLazyGetter(obj, "foo", function() { accessCount++; this.inScope = true; return TEST_VALUE; }); do_check_eq(accessCount, 0); // Get the property, making sure the access count has increased. do_check_eq(obj.foo, TEST_VALUE); do_check_eq(accessCount, 1); do_check_true(obj.inScope); // Get the property once more, making sure the access count has not // increased. do_check_eq(obj.foo, TEST_VALUE); do_check_eq(accessCount, 1); } function test_defineLazyServiceGetter() { let obj = { }; XPCOMUtils.defineLazyServiceGetter(obj, "service", "@mozilla.org/consoleservice;1", "nsIConsoleService"); let service = Cc["@mozilla.org/consoleservice;1"]. getService(Ci.nsIConsoleService); // Check that the lazy service getter and the actual service have the same // properties. for (let prop in obj.service) do_check_true(prop in service); for (let prop in service) do_check_true(prop in obj.service); } function test_categoryRegistration() { const CATEGORY_NAME = "test-cat"; const XULAPPINFO_CONTRACTID = "@mozilla.org/xre/app-info;1"; const XULAPPINFO_CID = Components.ID("{fc937916-656b-4fb3-a395-8c63569e27a8}"); // Create a fake app entry for our category registration apps filter. let XULAppInfo = { vendor: "Mozilla", name: "catRegTest", ID: "{adb42a9a-0d19-4849-bf4d-627614ca19be}", version: "1", appBuildID: "2007010101", platformVersion: "", platformBuildID: "2007010101", inSafeMode: false, logConsoleErrors: true, OS: "XPCShell", XPCOMABI: "noarch-spidermonkey", QueryInterface: XPCOMUtils.generateQI([ Ci.nsIXULAppInfo, Ci.nsIXULRuntime, ]) }; let XULAppInfoFactory = { createInstance: function (outer, iid) { if (outer != null) throw Cr.NS_ERROR_NO_AGGREGATION; return XULAppInfo.QueryInterface(iid); } }; let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); registrar.registerFactory( XULAPPINFO_CID, "XULAppInfo", XULAPPINFO_CONTRACTID, XULAppInfoFactory ); // Load test components. do_load_manifest("CatRegistrationComponents.manifest"); const EXPECTED_ENTRIES = ["CatAppRegisteredComponent", "CatRegisteredComponent"]; // Check who is registered in "test-cat" category. let foundEntriesCount = 0; let catMan = Cc["@mozilla.org/categorymanager;1"]. getService(Ci.nsICategoryManager); let entries = catMan.enumerateCategory(CATEGORY_NAME); while (entries.hasMoreElements()) { foundEntriesCount++; let entry = entries.getNext().QueryInterface(Ci.nsISupportsCString).data; print("Check the found category entry (" + entry + ") is expected."); do_check_true(EXPECTED_ENTRIES.indexOf(entry) != -1); } print("Check there are no more or less than expected entries."); do_check_eq(foundEntriesCount, EXPECTED_ENTRIES.length); } //////////////////////////////////////////////////////////////////////////////// //// Test Runner let tests = [ test_generateQI_string_names, test_defineLazyGetter, test_defineLazyServiceGetter, test_categoryRegistration, ]; function run_test() { tests.forEach(function(test) { print("Running next test: " + test.name); test(); }); }
{'content_hash': 'f1d0ca78eb615f5d36919453f2f2f785', 'timestamp': '', 'source': 'github', 'line_count': 163, 'max_line_length': 81, 'avg_line_length': 27.779141104294478, 'alnum_prop': 0.6214664310954063, 'repo_name': 'havocp/hwf', 'id': '7d337bb4a9b7338eb17c2f1ac69282cd2caf15ec', 'size': '6410', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'deps/spidermonkey/xpconnect/tests/unit/test_xpcomutils.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '554069'}, {'name': 'Emacs Lisp', 'bytes': '402'}, {'name': 'JavaScript', 'bytes': '84'}, {'name': 'Shell', 'bytes': '11734'}]}