repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
nevil-brownlee/check_svg
word_properties.py
11930
# 1113, 15 Jan 2018 (NZDT) # 1305, 9 Jan 2018 (NZDT) # # Nevil Brownlee, U Auckland # imported as wp ''' Elements not allowed in SVG 1.2: https://www.ruby-forum.com/topic/144684 http://inkscape.13.x6.nabble.com/SVG-Tiny-td2881845.html marker clipPath style properties come from the CSS, they are allowed in Tiny 1.2 DrawBerry produces attributes with inkscape:, 'http://www.w3.org/XML/1998/namespace', # wordle uses this e.g. inkscape:label and inkscape:groupmode DrawBerry and Inkscape seem to use this for layers; don't use it! XML NameSpaces. Specified by xmlns attribute, e.g. xmlns:inkscape="http://inkscape..." specifies inkscape elements such elements are prefixed by the namespace identifier, e.g. inkscape:label="Background" inkscape:groupmode="layer" Attributes in elements{} 'bottom lines' added during chek.py testing ''' elements = { 'svg': ('version', 'baseProfile', 'width', 'viewBox', 'preserveAspectRatio', 'snapshotTime', 'height', 'id', 'role', 'color-rendering', 'fill-rule', '<tbreak>'), 'desc': ( 'id', 'role', 'shape-rendering', 'text-rendering', 'buffered-rendering', 'visibility', '<tbreak>'), 'title': ( 'id', 'role', 'shape-rendering', 'text-rendering', 'buffered-rendering', 'visibility', '<tbreak>'), 'path': ('d', 'pathLength', 'stroke-miterlimit', 'id', 'role', 'fill', 'style', 'transform', 'font-size', 'fill-rule', '<tbreak>'), 'rect': ('x', 'y', 'width', 'height', 'rx', 'ry', 'stroke-miterlimit', 'id', 'role', 'fill', 'style','transform', 'fill-rule', '<tbreak>'), 'circle': ('cx', 'cy', 'r', 'id', 'role', 'fill', 'style', 'transform', 'fill-rule', '<tbreak>'), 'line': ('x1', 'y1', 'x2', 'y2', 'id', 'role', 'fill', 'transform', 'fill-rule', '<tbreak>'), 'ellipse': ('cx', 'cy', 'rx', 'ry', 'id', 'role', 'fill', 'style', 'transform', 'fill-rule', '<tbreak>'), 'polyline': ('points', 'id', 'role', 'fill', 'transform', 'fill-rule', '<tbreak>'), 'polygon': ('points', 'id', 'role', 'fill', 'style', 'transform', 'fill-rule', '<tbreak>'), 'solidColor': ( 'id', 'role', 'fill', 'fill-rule', '<tbreak>'), 'textArea': ('x', 'y', 'width', 'height', 'auto', 'id', 'role', 'fill', 'transform', 'fill-rule', '<tbreak>'), 'text': ('x', 'y', 'rotate', 'space', 'id', 'role', 'fill', 'style', 'transform', 'font-size', 'fill-rule', '<tbreak>'), 'g': ( 'label', 'class', 'id', 'role', 'fill', 'style', 'transform', 'fill-rule', 'visibility', '<tbreak>'), 'defs': ( 'id', 'role', 'fill', 'fill-rule', '<tbreak>'), 'use': ('x', 'y', 'href', 'id', 'role', 'fill', 'transform', 'fill-rule', '<tbreak>'), 'a': ( 'id', 'role', 'fill', 'transform', # Linking 'fill-rule', '<tbreak>'), 'tspan': ('x', 'y', 'id', 'role', 'fill', 'fill-rule', '<tbreak>'), # 'linearGradient': ('gradientUnits', 'x1', 'y1', 'x2', 'y2', # 'id', 'role', 'fill', # '<tbreak>'), # 'radialGradient': ('gradientUnits', 'cx', 'cy', 'r', # 'id', 'role', 'fill', # '<tbreak>'), # 'stop': ( 'id', 'role', 'fill', # Gradients # 'fill-rule', '<tbreak>'), } # Elements have a list of attributes (above), # we need to know what attributes each can have ... # Properties capture CSS info, they have lists of allowable values. # Attributes have allowed values too; # we also need to know which elements they're allowed in. # if string or xsd:string is allowed, we don't check, # but the 'syntax' values are shown as a comment below properties = { # Attributes allowed in elements 'about': (), # Allowed values for element attributes, 'base': (), # including those listed in <tbreak> 'baseProfile': (), 'd': (), 'break': (), 'class': (), 'content': (), 'cx': ('<number>'), 'cy': ('<number>'), 'datatype': (), 'height': ('<number>'), 'href': (), 'id': (), 'label': (), 'lang': (), 'pathLength': (), 'points': (), 'preserveAspectRatio': (), 'property': (), 'r': ('<number>'), 'rel': (), 'resource': (), 'rev': (), 'role': (), 'rotate': (), 'rx': ('<number>'), 'ry': ('<number>'), 'space': (), 'snapshotTime': (), 'transform': (), 'typeof': (), 'version': (), 'width': ('<number>'), 'viewBox': ('<number>'), 'x': ('<number>'), 'x1': ('<number>'), 'x2': ('<number>'), 'y': ('<number>'), 'y1': ('<number>'), 'y2': ('<number>'), 'stroke': ('<paint>', 'none'), # Change from I-D 'stroke-width': (), # 'inherit' 'stroke-linecap': ('butt', 'round', 'square', 'inherit'), 'stroke-linejoin': ('miter', 'round', 'bevel', 'inherit'), 'stroke-miterlimit': (), # 'inherit' 'stroke-dasharray': (), # 'inherit', 'none' 'stroke-dashoffset': (), # 'inherit' 'stroke-opacity': (), # 'inherit' 'vector-effect': ('non-scaling-stroke', 'none', 'inherit'), 'viewport-fill': ('none', 'currentColor', '<color>'), 'display': ('inline', 'block', 'list-item', 'run-in', 'compact', 'marker', 'table', 'inline-table', 'table-row-group', 'table-header-group', 'table-footer-group', 'table-row,' 'table-column-group', 'table-column', 'table-cell', 'table-caption', 'none'), 'viewport-fill-opacity': (), # "inherit" 'visibility': ('visible', 'hidden', 'collapse', 'inherit'), 'image-rendering': ('auto', 'optimizeSpeed', 'optimizeQuality', 'inherit'), 'color-rendering': ('auto', 'optimizeSpeed', 'optimizeQuality', 'inherit'), 'shape-rendering': ('auto', 'optimizeSpeed', 'crispEdges', 'geometricPrecision', 'inherit'), 'text-rendering': ('auto', 'optimizeSpeed', 'optimizeLegibility', 'geometricPrecision', 'inherit'), 'buffered-rendering': ('auto', 'dynamic', 'static', 'inherit'), 'solid-opacity': (), # 'inherit' 'solid-color': ('currentColor', '<color>'), 'color': ('currentColor', '<color>'), 'stop-color': ('currentColor', '<color>'), 'stop-opacity': (), # 'inherit' 'line-increment': (''), # 'auto', 'inherit' 'text-align': ('start', 'end', 'center', 'inherit'), 'display-align': ('auto', 'before', 'center', 'after', 'inherit'), 'font-size': (), # 'inherit' 'font-family': ('serif', 'sans-serif', 'monospace', 'inherit'), 'font-weight': ('normal', 'bold', 'bolder', 'lighter', '<hundreds>', 'inherit'), 'font-style': ('normal', 'italic', 'oblique', 'inherit'), 'font-variant': ('normal', 'small-caps', 'inherit'), 'direction': ('ltr', 'rtl', 'inherit'), 'unicode-bidi': ('normal', 'embed', 'bidi-override', 'inherit'), 'text-anchor': ('start', 'middle', 'end', 'inherit'), 'fill': ('none', '<color>'), # # = RGB val 'fill-rule': ('nonzero', 'evenodd', 'inherit'), 'fill-opacity': (), # 'inherit' 'height': ('<number>'), 'style': () #'[style]'), # Check properties in [style] # Not needed Jan 2018 versionq } basic_types = { # Lists of allowed values '<color>': ('black', 'white', '#000000', '#ffffff', '#FFFFFF'), # 'grey', 'darkgrey', 'dimgrey', 'lightgrey', # 'gray', 'darkgray', 'dimgray', 'lightgray', # '#808080', '#A9A9A9', '#696969', '#D3D3D3', , '<paint>': ('<color>', 'none', 'currentColor', 'inherit'), # attributes allowed in the rnc. We check their names, but not their values '<tbreak>': ('id', 'base', 'lang', 'class', 'rel', 'rev', 'typeof', 'content', 'datatype', 'resource', 'about', 'property', 'space', 'fill-rule'), '<number>': ('+g'), '<hundreds>': ('+h') , } color_default = 'black' #property_lists = { # Lists of properties to check (for Inkscape) # Not needed Jan 2018 versionq # '[style]': ('font-family', 'font-weight', 'font-style', # 'font-variant', 'direction', 'unicode-bidi', 'text-anchor', # 'fill', 'fill-rule'), # } # Elements allowed within other elements svg_child = ('title', 'path', 'rect', 'circle', 'line', 'ellipse', 'polyline', 'polygon', 'solidColor', 'textArea', 'text', 'g', 'defs', 'use', 'a', 'tspan') # 'stop', 'linearGradient', 'radialGradient' text_child = ('desc', 'title', 'tspan', 'text', 'a') element_children = { # Elements allowed within other elements 'svg': svg_child, 'desc': ('text'), 'title': ('text'), 'path': ('title'), 'rect': ('title'), 'circle': ('title'), 'line': ('title'), 'ellipse': ('title'), 'polyline': ('title'), 'polygon': ('title'), 'solidColor': ('title'), 'textArea': text_child, 'text': text_child, 'g': svg_child, 'defs': svg_child, 'use': ('title'), 'a': svg_child, 'tspan': text_child, # 'linearGradient': ('title'), # 'radialGradient': ('title'), # 'stop': ('title'), } xmlns_urls = ( # Whitelist of allowed URLs 'http://www.w3.org/2000/svg', # Base namespace for SVG 'http://www.w3.org/1999/xlink', # svgwrite uses this 'http://www.w3.org/XML/1998/namespace', # imagebot uses this )
mit
tridesclous/tridesclous
example/online_low_level_demo.py
5240
from tridesclous import * from tridesclous.online import * import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import pyacq from pyacq.viewers import QOscilloscope, QTimeFreq import numpy as np import time import os import shutil def setup_catalogue(): if os.path.exists('tridesclous_onlinepeeler'): shutil.rmtree('tridesclous_onlinepeeler') dataio = DataIO(dirname='tridesclous_onlinepeeler') localdir, filenames, params = download_dataset(name='olfactory_bulb') filenames = filenames[:1] #only first file dataio.set_data_source(type='RawData', filenames=filenames, **params) channel_group = {0:{'channels':[5, 6, 7, 8]}} dataio.set_channel_groups(channel_group) catalogueconstructor = CatalogueConstructor(dataio=dataio) params = get_auto_params_for_catalogue(dataio, chan_grp=0) apply_all_catalogue_steps(catalogueconstructor, params, verbose=True) catalogueconstructor = CatalogueConstructor(dataio=dataio) app = pg.mkQApp() win = CatalogueWindow(catalogueconstructor) win.show() app.exec_() def tridesclous_onlinepeeler(): dataio = DataIO(dirname='tridesclous_onlinepeeler') catalogue = dataio.load_catalogue(chan_grp=0) #~ catalogue.pop('clusters') #~ def print_dict(d): #~ for k, v in d.items(): #~ if type(v) is dict: #~ print('k', k, 'dict') #~ print_dict(v) #~ else: #~ print('k', k, type(v)) #~ print_dict(catalogue) #~ from pyacq.core.rpc.serializer import MsgpackSerializer #~ serializer = MsgpackSerializer() #~ b = serializer.dumps(catalogue) #~ catalogue2 = serializer.loads(b) #~ print(catalogue2['clusters']) #~ exit() sigs = dataio.datasource.array_sources[0] sigs = sigs.astype('float32').copy() sample_rate = dataio.sample_rate in_group_channels = dataio.channel_groups[0]['channels'] #~ print(channel_group) chunksize = 1024 # Device node man = pyacq.create_manager(auto_close_at_exit=True) ng0 = man.create_nodegroup() #~ ng0 = None ng1 = man.create_nodegroup() #~ ng1 = None ng2 = man.create_nodegroup() #~ ng2 = None dev = make_pyacq_device_from_buffer(sigs, sample_rate, nodegroup=ng0, chunksize=chunksize) #~ print(type(dev)) #~ exit() #~ print(dev.output.params) #~ exit() app = pg.mkQApp() dev.start() # Node QOscilloscope oscope = QOscilloscope() oscope.configure(with_user_dialog=True) oscope.input.connect(dev.output) oscope.initialize() oscope.show() oscope.start() oscope.params['decimation_method'] = 'min_max' oscope.params['mode'] = 'scan' oscope.params['scale_mode'] = 'by_channel' # Node Peeler if ng1 is None: peeler = OnlinePeeler() else: ng1.register_node_type_from_module('tridesclous.online', 'OnlinePeeler') peeler = ng1.create_node('OnlinePeeler') peeler.configure(catalogue=catalogue, in_group_channels=in_group_channels, chunksize=chunksize) #~ print(dev.output.params) #~ print(peeler.input.connect) #~ exit() peeler.input.connect(dev.output) #~ exit() stream_params = dict(protocol='tcp', interface='127.0.0.1', transfermode='plaindata') peeler.outputs['signals'].configure(**stream_params) peeler.outputs['spikes'].configure(**stream_params) peeler.initialize() peeler.start() # Node traceviewer if ng2 is None: tviewer = OnlineTraceViewer() else: ng2.register_node_type_from_module('tridesclous.online', 'OnlineTraceViewer') tviewer = ng2.create_node('OnlineTraceViewer') tviewer.configure(catalogue=catalogue) tviewer.inputs['signals'].connect(peeler.outputs['signals']) tviewer.inputs['spikes'].connect(peeler.outputs['spikes']) tviewer.initialize() tviewer.show() tviewer.start() tviewer.params['xsize'] = 3. tviewer.params['decimation_method'] = 'min_max' tviewer.params['mode'] = 'scan' tviewer.params['scale_mode'] = 'same_for_all' #~ tviewer.params['mode'] = 'scroll' tfr_viewer = QTimeFreq() tfr_viewer.configure(with_user_dialog=True, nodegroup_friends=None) tfr_viewer.input.connect(dev.output) tfr_viewer.initialize() tfr_viewer.show() tfr_viewer.params['refresh_interval'] = 300 tfr_viewer.params['timefreq', 'f_start'] = 1 tfr_viewer.params['timefreq', 'f_stop'] = 100. tfr_viewer.params['timefreq', 'deltafreq'] = 5 tfr_viewer.start() def ajust_yrange(): oscope.auto_scale() tviewer.auto_scale() tviewer.params_controller.apply_ygain_zoom(.3) timer = QtCore.QTimer(interval=1000, singleShot=True) timer.timeout.connect(ajust_yrange) timer.start() def terminate(): dev.stop() oscope.stop() peeler.stop() tviewer.stop() app.quit() app.exec_() if __name__ =='__main__': setup_catalogue() tridesclous_onlinepeeler()
mit
200sc/go-dist
floatrange/linear.go
1456
package floatrange import "math/rand" // NewSpread returns a linear range from base-spread to base+spread func NewSpread(base, spread float64) Range { return Linear{base - spread, base + spread, nowRand()} } // NewLinear returns a linear range from min to max func NewLinear(min, max float64) Range { return Linear{min, max, nowRand()} } // Linear is a range from min to max type Linear struct { Max, Min float64 rng *rand.Rand } // Poll on a linear float range returns a float at uniform // distribution in lfr's range func (lfr Linear) Poll() float64 { return ((lfr.Max - lfr.Min) * lfr.rng.Float64()) + lfr.Min } // Mult scales a Linear by f func (lfr Linear) Mult(f float64) Range { lfr.Max *= f lfr.Min *= f return lfr } // InRange returns whether an input float could be returned // by Poll() func (lfr Linear) InRange(f float64) bool { // should still work if min is greater than max return (f > lfr.Min) == (f < lfr.Max) } // EnforceRange returns f, if InRange(f), or the closest value // in the range to f. func (lfr Linear) EnforceRange(f float64) float64 { if lfr.InRange(f) { return f } // At this point we need to enforce min < max if lfr.Min > lfr.Max { lfr.Min, lfr.Max = lfr.Max, lfr.Min } if f <= lfr.Min { return lfr.Min } return lfr.Max } // Percentile returns the fth percentile value along this range func (lfr Linear) Percentile(f float64) float64 { return ((lfr.Max - lfr.Min) * f) + lfr.Min }
mit
navroopsingh/HepBProject
config/initializers/devise.rb
12714
# Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. config.secret_key = 'edddf33597b269f6ac9cf25bae21543778b8d9d7a90faeecbcf2b9a2a34dfb880e54316404aa4ca1ed1ee2b47835474a0b076ebac2d7c4268441f34b503a2b5d' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = 'noreply@hepbproject.com' # Configure the class responsible to send e-mails. config.mailer = 'Devise::Mailer' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [ :email ] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [ :email ] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [ :email ] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # encryptor), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = '02e8b24f3e0a2f03d4c9b3dba9a7aa60734e0d99dfc69b95d72ce740097a9edfcd7876c1c5ef7020e9913478b31f002a617310fdafa4379d9686b50c1f497cc2' # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [ :email ] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. config.password_length = 8..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # If true, expires auth token on session timeout. # config.expire_auth_token_on_timeout = false # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [ :email ] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = true # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [ :email ] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using omniauth, Devise cannot automatically set Omniauth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' end
mit
mattfili/NSSAccelerator
src/js/directives.js
918
/** * Wraps ng-cloak so that, instead of simply waiting for Angular to compile, it waits until * Auth resolves with the remote Firebase services. * * <code> * <div ng-cloak>Authentication has resolved.</div> * </code> */ angular.module('valueprop') .config(['$provide', function($provide) { // adapt ng-cloak to wait for auth before it does its magic $provide.decorator('ngCloakDirective', ['$delegate', 'Auth', function($delegate, Auth) { var directive = $delegate[0]; // make a copy of the old directive var _compile = directive.compile; directive.compile = function(element, attr) { Auth.$waitForAuth().then(function() { // after auth, run the original ng-cloak directive _compile.call(directive, element, attr); }); }; // return the modified directive return $delegate; }]); }]);
mit
npetzall/http-double
server/src/main/java/npetzall/httpdouble/BaseServer.java
909
package npetzall.httpdouble; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; public abstract class BaseServer { protected volatile boolean running = false; protected EventLoopGroup bossGroup; protected EventLoopGroup workerGroup; protected Channel channel; public abstract void start(); protected boolean isStopped() { return !running; } public void stop() { if (running) { try { channel.close(); channel.closeFuture().sync(); channel = null; } catch (InterruptedException e) { //nothing } finally { bossGroup.shutdownGracefully(); bossGroup = null; workerGroup.shutdownGracefully(); workerGroup = null; } running = false; } } }
mit
gztproject/Boter
Tools/Password.php
14082
<?php /** * A Compatibility library with PHP 5.5's simplified password hashing API. * * @author Anthony Ferrara <ircmaxell@php.net> * @license http://www.opensource.org/licenses/mit-license.html MIT License * @copyright 2012 The Authors */ namespace { if (! defined('PASSWORD_BCRYPT')) { /** * PHPUnit Process isolation caches constants, but not function * declarations. * So we need to check if the constants are defined separately from * the functions to enable supporting process isolation in userland * code. */ define('PASSWORD_BCRYPT', 1); define('PASSWORD_DEFAULT', PASSWORD_BCRYPT); define('PASSWORD_BCRYPT_DEFAULT_COST', 10); } if (! function_exists('password_hash')) { /** * Hash the password using the specified algorithm * * @param string $password * The password to hash * @param int $algo * The algorithm to use (Defined by PASSWORD_* constants) * @param array $options * The options for the algorithm to use * * @return string|false The hashed password, or false on error. */ function password_hash ($password, $algo, array $options = array()) { if (! function_exists('crypt')) { trigger_error( "Crypt must be loaded for password_hash to function", E_USER_WARNING); return null; } if (is_null($password) || is_int($password)) { $password = (string) $password; } if (! is_string($password)) { trigger_error("password_hash(): Password must be a string", E_USER_WARNING); return null; } if (! is_int($algo)) { trigger_error( "password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING); return null; } $resultLength = 0; switch ($algo) { case PASSWORD_BCRYPT: $cost = PASSWORD_BCRYPT_DEFAULT_COST; if (isset($options['cost'])) { $cost = (int) $options['cost']; if ($cost < 4 || $cost > 31) { trigger_error( sprintf( "password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING); return null; } } // The length of salt to generate $raw_salt_len = 16; // The length required in the final serialization $required_salt_len = 22; $hash_format = sprintf("$2y$%02d$", $cost); // The expected length of the final crypt() output $resultLength = 60; break; default: trigger_error( sprintf( "password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING); return null; } $salt_req_encoding = false; if (isset($options['salt'])) { switch (gettype($options['salt'])) { case 'NULL': case 'boolean': case 'integer': case 'double': case 'string': $salt = (string) $options['salt']; break; case 'object': if (method_exists($options['salt'], '__tostring')) { $salt = (string) $options['salt']; break; } case 'array': case 'resource': default: trigger_error( 'password_hash(): Non-string salt parameter supplied', E_USER_WARNING); return null; } if (PasswordCompat\binary\_strlen($salt) < $required_salt_len) { trigger_error( sprintf( "password_hash(): Provided salt is too short: %d expecting %d", PasswordCompat\binary\_strlen($salt), $required_salt_len), E_USER_WARNING); return null; } elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) { $salt_req_encoding = true; } } else { $buffer = ''; $buffer_valid = false; if (function_exists('mcrypt_create_iv') && ! defined( 'PHALANGER')) { $buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM); if ($buffer) { $buffer_valid = true; } } if (! $buffer_valid && function_exists('openssl_random_pseudo_bytes')) { $strong = false; $buffer = openssl_random_pseudo_bytes($raw_salt_len, $strong); if ($buffer && $strong) { $buffer_valid = true; } } if (! $buffer_valid && @is_readable('/dev/urandom')) { $file = fopen('/dev/urandom', 'r'); $read = 0; $local_buffer = ''; while ($read < $raw_salt_len) { $local_buffer .= fread($file, $raw_salt_len - $read); $read = PasswordCompat\binary\_strlen($local_buffer); } fclose($file); if ($read >= $raw_salt_len) { $buffer_valid = true; } $buffer = str_pad($buffer, $raw_salt_len, "\0") ^ str_pad($local_buffer, $raw_salt_len, "\0"); } if (! $buffer_valid || PasswordCompat\binary\_strlen($buffer) < $raw_salt_len) { $buffer_length = PasswordCompat\binary\_strlen($buffer); for ($i = 0; $i < $raw_salt_len; $i ++) { if ($i < $buffer_length) { $buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255)); } else { $buffer .= chr(mt_rand(0, 255)); } } } $salt = $buffer; $salt_req_encoding = true; } if ($salt_req_encoding) { // encode string with the Base64 variant used by crypt $base64_digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; $bcrypt64_digits = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $base64_string = base64_encode($salt); $salt = strtr(rtrim($base64_string, '='), $base64_digits, $bcrypt64_digits); } $salt = PasswordCompat\binary\_substr($salt, 0, $required_salt_len); $hash = $hash_format . $salt; $ret = crypt($password, $hash); if (! is_string($ret) || PasswordCompat\binary\_strlen($ret) != $resultLength) { return false; } return $ret; } /** * Get information about the password hash. * Returns an array of the information * that was used to generate the password hash. * * array( * 'algo' => 1, * 'algoName' => 'bcrypt', * 'options' => array( * 'cost' => PASSWORD_BCRYPT_DEFAULT_COST, * ), * ) * * @param string $hash * The password hash to extract info from * * @return array The array of information about the hash. */ function password_get_info ($hash) { $return = array( 'algo' => 0, 'algoName' => 'unknown', 'options' => array() ); if (PasswordCompat\binary\_substr($hash, 0, 4) == '$2y$' && PasswordCompat\binary\_strlen($hash) == 60) { $return['algo'] = PASSWORD_BCRYPT; $return['algoName'] = 'bcrypt'; list ($cost) = sscanf($hash, "$2y$%d$"); $return['options']['cost'] = $cost; } return $return; } /** * Determine if the password hash needs to be rehashed according to the * options provided * * If the answer is true, after validating the password using * password_verify, rehash it. * * @param string $hash * The hash to test * @param int $algo * The algorithm used for new password hashes * @param array $options * The options array passed to password_hash * * @return boolean True if the password needs to be rehashed. */ function password_needs_rehash ($hash, $algo, array $options = array()) { $info = password_get_info($hash); if ($info['algo'] !== (int) $algo) { return true; } switch ($algo) { case PASSWORD_BCRYPT: $cost = isset($options['cost']) ? (int) $options['cost'] : PASSWORD_BCRYPT_DEFAULT_COST; if ($cost !== $info['options']['cost']) { return true; } break; } return false; } /** * Verify a password against a hash using a timing attack resistant * approach * * @param string $password * The password to verify * @param string $hash * The hash to verify against * * @return boolean If the password matches the hash */ function password_verify ($password, $hash) { if (! function_exists('crypt')) { trigger_error( "Crypt must be loaded for password_verify to function", E_USER_WARNING); return false; } $ret = crypt($password, $hash); if (! is_string($ret) || PasswordCompat\binary\_strlen($ret) != PasswordCompat\binary\_strlen($hash) || PasswordCompat\binary\_strlen($ret) <= 13) { return false; } $status = 0; for ($i = 0; $i < PasswordCompat\binary\_strlen($ret); $i ++) { $status |= (ord($ret[$i]) ^ ord($hash[$i])); } return $status === 0; } } } namespace PasswordCompat\binary { if (! function_exists('PasswordCompat\\binary\\_strlen')) { /** * Count the number of bytes in a string * * We cannot simply use strlen() for this, because it might be * overwritten by the mbstring extension. * In this case, strlen() will count the number of *characters* based on * the internal encoding. A * sequence of bytes might be regarded as a single multibyte character. * * @param string $binary_string * The input string * * @internal * * @return int The number of bytes */ function _strlen ($binary_string) { if (function_exists('mb_strlen')) { return mb_strlen($binary_string, '8bit'); } return strlen($binary_string); } /** * Get a substring based on byte limits * * @see _strlen() * * @param string $binary_string * The input string * @param int $start * @param int $length * * @internal * * @return string The substring */ function _substr ($binary_string, $start, $length) { if (function_exists('mb_substr')) { return mb_substr($binary_string, $start, $length, '8bit'); } return substr($binary_string, $start, $length); } /** * Check if current PHP version is compatible with the library * * @return boolean the check result */ function check () { static $pass = NULL; if (is_null($pass)) { if (function_exists('crypt')) { $hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG'; $test = crypt("password", $hash); $pass = $test == $hash; } else { $pass = false; } } return $pass; } } }
mit
EasyExpress/Easylink
EasylinkApp/EasylinkApp.Business/Models/AuditRecord.cs
414
using System; namespace EasylinkApp.Business { public class AuditRecord { public string RecordType { get; set; } public string RecordId { get; set; } public string UserId { get; set; } public string Description { get; set; } public string Operation { get; set; } public DateTime TimeStamp { get; set; } } }
mit
dmpe/Semester2and5-Examples
src-semester2/msfp07/Lostrommel.java
179
package msfp07; public interface Lostrommel { void setzeMaxWertDerLose(int max); void setzeMinWertDerLose(int min); void trommelFuellen(); Loszieher loszieher(); }
mit
bitcababy/saphira
test/unit/saphira/file_item_test.rb
151
require 'test_helper' module Saphira class FileItemTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end end
mit
maurer/tiamat
samples/Juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s04/CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_22a.cpp
3793
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_22a.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-22a.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: realloc Allocate data using realloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources. * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_22 { #ifndef OMITBAD /* The global variable below is used to drive control flow in the sink function. Since it is in a C++ namespace, it doesn't need a globally unique name. */ int badGlobal = 0; void badSink(long * data); void bad() { long * data; /* Initialize data*/ data = NULL; data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (long *)realloc(data, 100*sizeof(long)); badGlobal = 1; /* true */ badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* The global variables below are used to drive control flow in the sink functions. Since they are in a C++ namespace, they don't need globally unique names. */ int goodB2G1Global = 0; int goodB2G2Global = 0; int goodG2B1Global = 0; /* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */ void goodB2G1Sink(long * data); static void goodB2G1() { long * data; /* Initialize data*/ data = NULL; data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (long *)realloc(data, 100*sizeof(long)); goodB2G1Global = 0; /* false */ goodB2G1Sink(data); } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */ void goodB2G2Sink(long * data); static void goodB2G2() { long * data; /* Initialize data*/ data = NULL; data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (long *)realloc(data, 100*sizeof(long)); goodB2G2Global = 1; /* true */ goodB2G2Sink(data); } /* goodG2B1() - use goodsource and badsink */ void goodG2B1Sink(long * data); static void goodG2B1() { long * data; /* Initialize data*/ data = NULL; /* FIX: Allocate memory from the heap using new */ data = new long; goodG2B1Global = 1; /* true */ goodG2B1Sink(data); } void good() { goodB2G1(); goodB2G2(); goodG2B1(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_22; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
mit
peichhorn/tinybinding
src/main/java/de/fips/util/tinybinding/IConverter.java
1478
/* * Copyright © 2010-2011 Philipp Eichhorn. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package de.fips.util.tinybinding; /** * Implementations of this interface a capable of transforming * objects of one type to objects of another type. * * @param <SOURCE> * @param <TARGET> * @author Philipp Eichhorn */ public interface IConverter<SOURCE, TARGET> { public TARGET convert(SOURCE source); }
mit
hhirsch/magento-core-composer-installer
src/GitIgnore.php
3143
<?php namespace AydinHassan\MagentoCoreComposerInstaller; /** * Class GitIgnore * @package AydinHassan\MagentoCoreComposerInstaller * @author Aydin Hassan <aydin@hotmail.co.uk> */ class GitIgnore { /** * @var array */ protected $lines = array(); /** * @var array */ protected $directoriesToIgnoreEntirely = array(); /** * @var string|null */ protected $gitIgnoreLocation; /** * @var bool */ protected $hasChanges = false; /** * @var bool */ protected $disabled = false; /** * @param string $fileLocation * @param array $directoriesToIgnoreEntirely * @param bool $gitIgnoreAppend */ public function __construct($fileLocation, array $directoriesToIgnoreEntirely, $gitIgnoreAppend = true) { $this->gitIgnoreLocation = $fileLocation; if (file_exists($fileLocation) && $gitIgnoreAppend) { $this->lines = explode("\n", file_get_contents($fileLocation)); } $this->directoriesToIgnoreEntirely = $directoriesToIgnoreEntirely; $this->addEntriesForDirectoriesToIgnoreEntirely(); } /** * @param string $file */ public function addEntry($file) { $addToGitIgnore = true; foreach ($this->directoriesToIgnoreEntirely as $directory) { if (substr($file, 0, strlen($directory)) === $directory) { $addToGitIgnore = false; } } if ($addToGitIgnore && !in_array($file, $this->lines)) { $this->lines[] = $file; } $this->hasChanges = true; } /** * @param string $file */ public function removeEntry($file) { $index = array_search($file, $this->lines); if ($index !== false) { unset($this->lines[$index]); $this->hasChanges = true; } } /** * Remove all the directories to ignore */ public function removeIgnoreDirectories() { foreach ($this->directoriesToIgnoreEntirely as $directory) { $this->removeEntry($directory); } } /** * @return array */ public function getEntries() { return array_values($this->lines); } /** * Wipe out the gitginore */ public function wipeOut() { $this->lines = array(); $this->hasChanges = true; } /** * Write the file */ public function __destruct() { if ($this->hasChanges && !$this->disabled) { file_put_contents($this->gitIgnoreLocation, implode("\n", $this->lines)); } } public function disable() { $this->disabled = true; } /** * Add entries to for all directories ignored entirely. */ protected function addEntriesForDirectoriesToIgnoreEntirely() { foreach ($this->directoriesToIgnoreEntirely as $directory) { if (!in_array($directory, $this->lines)) { $this->lines[] = $directory; $this->hasChanges = true; } } } }
mit
alertedsnake/pycrust
pycrust/tools/mako.py
2300
""" Mako Templates -------------- Mako templating code was based on the code and discussion at http://tools.cherrypy.org/wiki/Mako To use the Mako renderer: cherrypy.tools.mako = cherrypy.Tool('on_start_resource', MakoLoader(directories=['/path/to/templates'])) Then in your handler: @cherrypy.tools.mako(filename='index.html') def index(self): return {} """ from mako.lookup import TemplateLookup import cherrypy try: import simplejson as json except ImportError: import json from pycrust import url class MakoHandler(cherrypy.dispatch.LateParamPageHandler): """Callable which sets response.body.""" def __init__(self, template, next_handler): self.template = template self.next_handler = next_handler def __call__(self): env = globals().copy() env.update(self.next_handler()) ## Add any default session globals env.update({ 'session': cherrypy.session, 'url': url, }) return self.template.render_unicode(**env) class MakoLoader(object): """Template loader for Mako""" def __init__(self, directories=[]): self.lookups = {} self.directories = directories def __call__(self, filename, directories=None, module_directory=None, collection_size=-1): if not directories: directories = self.directories # Find the appropriate template lookup. key = (tuple(directories), module_directory) try: lookup = self.lookups[key] except KeyError: lookup = TemplateLookup(directories=directories, module_directory=module_directory, collection_size=collection_size, input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace' ) self.lookups[key] = lookup cherrypy.request.lookup = lookup # Replace the current handler. cherrypy.request.template = t = lookup.get_template(filename) cherrypy.request.handler = MakoHandler(t, cherrypy.request.handler)
mit
mjenrungrot/competitive_programming
UVa Online Judge/v2/271.py
965
# ============================================================================= # Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/ # FileName: 271.py # Description: UVa Online Judge - 271 # ============================================================================= from collections import deque def check(x): if len(x) == 0: return False, [] if x[0] == "N": x.popleft() return check(x) elif x[0] in "CDEI": x.popleft() valid, rem = check(x) if valid: return check(rem) else: return False, [] elif ord("p") <= ord(x[0]) <= ord("z"): x.popleft() return True, x else: return False, [] while True: try: line = input() except EOFError: break data = deque(line) valid, rem = check(data) if valid and len(rem) == 0: print("YES") else: print("NO")
mit
robertjanetzko/LegendsBrowser
src/main/java/legends/model/basic/NamedObject.java
311
package legends.model.basic; import legends.model.basic.AbstractObject; import legends.xml.annotation.Xml; public class NamedObject extends AbstractObject { @Xml("name") protected String name = ""; public String getName() { return name; } public void setName(String name) { this.name = name; } }
mit
kylawl/imgui
examples/sdl_opengl3_example/imgui_impl_sdl_gl3.cpp
15683
// ImGui SDL2 binding with OpenGL3 // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui #include "imgui.h" #include "imgui_impl_sdl_gl3.h" // SDL,GL3W #include <SDL.h> #include <SDL_syswm.h> #include <GL/gl3w.h> // Data static SDL_Window* g_Window = NULL; static double g_Time = 0.0f; static bool g_MousePressed[3] = { false, false, false }; static float g_MouseWheel = 0.0f; static GLuint g_FontTexture = 0; static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0; static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0; static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0; // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) // If text or lines are blurry when integrating ImGui in your engine: // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) void ImGui_ImplSdlGL3_RenderDrawLists(ImDrawData* draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) ImGuiIO& io = ImGui::GetIO(); int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); if (fb_width == 0 || fb_height == 0) return; draw_data->ScaleClipRects(io.DisplayFramebufferScale); // Backup GL state GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src); GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst); GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); GLboolean last_enable_blend = glIsEnabled(GL_BLEND); GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); // Setup orthographic projection matrix glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); const float ortho_projection[4][4] = { { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, {-1.0f, 1.0f, 0.0f, 1.0f }, }; glUseProgram(g_ShaderHandle); glUniform1i(g_AttribLocationTex, 0); glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); glBindVertexArray(g_VaoHandle); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawIdx* idx_buffer_offset = 0; glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW); for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++) { if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); } idx_buffer_offset += pcmd->ElemCount; } } // Restore modified GL state glUseProgram(last_program); glBindTexture(GL_TEXTURE_2D, last_texture); glBindVertexArray(last_vertex_array); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); glBlendFunc(last_blend_src, last_blend_dst); if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND); if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); } static const char* ImGui_ImplSdlGL3_GetClipboardText() { return SDL_GetClipboardText(); } static void ImGui_ImplSdlGL3_SetClipboardText(const char* text) { SDL_SetClipboardText(text); } bool ImGui_ImplSdlGL3_ProcessEvent(SDL_Event* event) { ImGuiIO& io = ImGui::GetIO(); switch (event->type) { case SDL_MOUSEWHEEL: { if (event->wheel.y > 0) g_MouseWheel = 1; if (event->wheel.y < 0) g_MouseWheel = -1; return true; } case SDL_MOUSEBUTTONDOWN: { if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true; if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true; if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true; return true; } case SDL_TEXTINPUT: { ImGuiIO& io = ImGui::GetIO(); io.AddInputCharactersUTF8(event->text.text); return true; } case SDL_KEYDOWN: case SDL_KEYUP: { int key = event->key.keysym.sym & ~SDLK_SCANCODE_MASK; io.KeysDown[key] = (event->type == SDL_KEYDOWN); io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); return true; } } return false; } void ImGui_ImplSdlGL3_CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader. // Upload texture to graphics system GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGenTextures(1, &g_FontTexture); glBindTexture(GL_TEXTURE_2D, g_FontTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // Store our identifier io.Fonts->TexID = (void *)(intptr_t)g_FontTexture; // Restore state glBindTexture(GL_TEXTURE_2D, last_texture); } bool ImGui_ImplSdlGL3_CreateDeviceObjects() { // Backup GL state GLint last_texture, last_array_buffer, last_vertex_array; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); const GLchar *vertex_shader = "#version 330\n" "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar* fragment_shader = "#version 330\n" "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n" "}\n"; g_ShaderHandle = glCreateProgram(); g_VertHandle = glCreateShader(GL_VERTEX_SHADER); g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(g_VertHandle, 1, &vertex_shader, 0); glShaderSource(g_FragHandle, 1, &fragment_shader, 0); glCompileShader(g_VertHandle); glCompileShader(g_FragHandle); glAttachShader(g_ShaderHandle, g_VertHandle); glAttachShader(g_ShaderHandle, g_FragHandle); glLinkProgram(g_ShaderHandle); g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position"); g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV"); g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color"); glGenBuffers(1, &g_VboHandle); glGenBuffers(1, &g_ElementsHandle); glGenVertexArrays(1, &g_VaoHandle); glBindVertexArray(g_VaoHandle); glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glEnableVertexAttribArray(g_AttribLocationPosition); glEnableVertexAttribArray(g_AttribLocationUV); glEnableVertexAttribArray(g_AttribLocationColor); #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos)); glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col)); #undef OFFSETOF ImGui_ImplSdlGL3_CreateFontsTexture(); // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindVertexArray(last_vertex_array); return true; } void ImGui_ImplSdlGL3_InvalidateDeviceObjects() { if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle); if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle); if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle); g_VaoHandle = g_VboHandle = g_ElementsHandle = 0; glDetachShader(g_ShaderHandle, g_VertHandle); glDeleteShader(g_VertHandle); g_VertHandle = 0; glDetachShader(g_ShaderHandle, g_FragHandle); glDeleteShader(g_FragHandle); g_FragHandle = 0; glDeleteProgram(g_ShaderHandle); g_ShaderHandle = 0; if (g_FontTexture) { glDeleteTextures(1, &g_FontTexture); ImGui::GetIO().Fonts->TexID = 0; g_FontTexture = 0; } } bool ImGui_ImplSdlGL3_Init(SDL_Window *window) { g_Window = window; ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP; io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN; io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE; io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN; io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE; io.KeyMap[ImGuiKey_A] = SDLK_a; io.KeyMap[ImGuiKey_C] = SDLK_c; io.KeyMap[ImGuiKey_V] = SDLK_v; io.KeyMap[ImGuiKey_X] = SDLK_x; io.KeyMap[ImGuiKey_Y] = SDLK_y; io.KeyMap[ImGuiKey_Z] = SDLK_z; io.RenderDrawListsFn = ImGui_ImplSdlGL3_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer. io.SetClipboardTextFn = ImGui_ImplSdlGL3_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplSdlGL3_GetClipboardText; #ifdef _WIN32 SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(window, &wmInfo); io.ImeWindowHandle = wmInfo.info.win.window; #endif return true; } void ImGui_ImplSdlGL3_Shutdown() { ImGui_ImplSdlGL3_InvalidateDeviceObjects(); ImGui::Shutdown(); } void ImGui_ImplSdlGL3_NewFrame() { if (!g_FontTexture) ImGui_ImplSdlGL3_CreateDeviceObjects(); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) int w, h; SDL_GetWindowSize(g_Window, &w, &h); io.DisplaySize = ImVec2((float)w, (float)h); io.DisplayFramebufferScale = ImVec2(1.0f, 1.0f); // Setup time step Uint32 time = SDL_GetTicks(); double current_time = time / 1000.0; io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f); g_Time = current_time; // Setup inputs // (we already got mouse wheel, keyboard keys & characters from SDL_PollEvent()) int mx, my; Uint32 mouseMask = SDL_GetMouseState(&mx, &my); if (SDL_GetWindowFlags(g_Window) & SDL_WINDOW_MOUSE_FOCUS) io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) else io.MousePos = ImVec2(-1, -1); io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. io.MouseDown[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false; io.MouseWheel = g_MouseWheel; g_MouseWheel = 0.0f; // Hide OS mouse cursor if ImGui is drawing it SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1); // Start the frame ImGui::NewFrame(); }
mit
dVakulen/Storm
Storm/Storm.Worker/Executor/ExecutorInfo.cs
332
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Storm.Worker.Executor { class ExecutorInfo { public int COMPONENT_ID; public int HOST; public int PORT; public int UPTIME_SECS; public int STATS; } }
mit
shyftplan/fullcalendar
src/resource/ResourceView.js
10314
var ResourceView = View.extend({ resourceGrid: null, timelineGrid: null, resourceColWidth: null, // width of all the resource-name cells running down the side initialize: function() { this.processOptions(); this.resourceGrid = new ResourceGrid(this); this.timelineGrid = new TimelineGrid(this); this.coordMap = this.timelineGrid.coordMap; }, processOptions: function() { this.resources = this.opt('resources'); this.rowCnt = this.resources.length; }, // Sets the display range and computes all necessary dates setRange: function(range) { View.prototype.setRange.call(this, range); // call the super-method this.timelineGrid.setRange(range); }, // Compute the value to feed into setRange. Overrides superclass. computeRange: function(date) { var range = View.prototype.computeRange.call(this, date); // get value from the super-method // year and month views should be aligned with weeks. this is already done for week if (/year|month/.test(range.intervalUnit)) { range.start.startOf('week'); range.start = this.skipHiddenDays(range.start); // make end-of-week if not already if (range.end.weekday()) { range.end.add(1, 'week').startOf('week'); range.end = this.skipHiddenDays(range.end, -1, true); // exclusively move backwards } } return range; }, // Renders the view into `this.el`, which should already be assigned renderDates: function() { var resourceAreaEl; var timelineAreaEl; this.dayNumbersVisible = this.resourceGrid.rowCnt > 1; // TODO: make grid responsible this.el.addClass('fc-nested fc-timeline') this.el.html(this.renderHtml()); this.headRowEl = this.el.find('thead .fc-row'); resourceAreaEl = this.el.find('.fc-body .fc-resource-area .fc-scrollpane-inner'); this.scrollerEl = resourceAreaEl; this.resourceGrid.coordMap.containerEl = resourceAreaEl; // constrain clicks/etc to the dimensions of the scroller this.resourceGrid.setElement(resourceAreaEl); this.resourceGrid.renderDates(); timelineAreaEl = this.el.find('.fc-body .fc-time-area .fc-scrollpane-inner'); this.timelineGrid.coordMap.containerEl = timelineAreaEl; // constrain clicks/etc to the dimensions of the scroller this.timelineGrid.setElement(timelineAreaEl); this.timelineGrid.renderDates(this.hasRigidRows()); }, // Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering, // always completely kill the resourceGrid's rendering. unrenderDates: function() { this.resourceGrid.unrenderDates(); this.resourceGrid.removeElement(); this.timelineGrid.unrenderDates(); this.timelineGrid.removeElement(); }, renderHtml: function() { return '' + '<table>' + '<thead class="fc-head">' + '<tr>' + this.headHtml() + '</tr>' + '</thead>' + '<tbody class="fc-body">' + '<tr>' + '<td class="fc-resource-area '+ this.widgetContentClass +'">' + '<div class="fc-scrollpane">' + '<div style="overflow-x: scroll; overflow-y: hidden; margin: 0px;">' + '<div class="fc-scrollpane-inner">' + '</div>' + '</div>' + '</div>' + '</td>' + '<td class="fc-time-area '+ this.widgetContentClass +'">' + '<div class="fc-scrollpane">' + '<div style="overflow-x: scroll; overflow-y: hidden; margin: 0px;">' + '<div class="fc-scrollpane-inner">' + '</div>' + '</div>' + '</div>' + '</td>' + '</tr>' + '</tbody>' + '</table>'; }, headHtml: function() { var resourceGridHeadHtml = this.resourceGrid.headHtml(); var timelineGridHeadHtml = this.timelineGrid.headHtml(); return '' + '<td class="fc-resource-area '+ this.widgetHeaderClass +'">' + '<div class="fc-scrollpane">' + '<div style="overflow-x: scroll; overflow-y: hidden; margin: 0px;">' + '<div class="fc-scrollpane-inner" style="min-width: 70px;">' + '<div class="fc-content">' + resourceGridHeadHtml + '</div>' + '</div>' + '</div>' + '</div>' + '</td>' + '<td class="fc-time-area '+ this.widgetHeaderClass +'">' + '<div class="fc-scrollpane">' + '<div style="overflow-x: scroll; overflow-y: hidden; margin: 0px;">' + '<div class="fc-scrollpane-inner">' + '<div class="fc-content">' + timelineGridHeadHtml + '</div>' + '</div>' + '</div>' + '</div>' + '</td>'; }, // Generates an HTML attribute string for setting the width of the week number column, if it is known // Determines whether each row should have a constant height hasRigidRows: function() { var eventLimit = this.opt('eventLimit'); return eventLimit && typeof eventLimit !== 'number'; }, /* Dimensions ------------------------------------------------------------------------------------------------------------------*/ // Refreshes the horizontal dimensions of the view updateWidth: function() { // Make sure all week number cells running down the side have the same width. // Record the width for cells created later. this.resourceColWidth = matchCellWidths( this.el.find('.fc-resource-name') ); }, // Adjusts the vertical dimensions of the view to the specified values setHeight: function(totalHeight, isAuto) { var eventLimit = this.opt('eventLimit'); var scrollerHeight; // reset all heights to be natural unsetScroller(this.scrollerEl); uncompensateScroll(this.headRowEl); // this.timelineGrid.removeSegPopover(); // kill the "more" popover if displayed // is the event limit a constant level number? if (eventLimit && typeof eventLimit === 'number') { console.log("eventLimit"); // this.timelineGrid.limitRows(eventLimit); // limit the levels first so the height can redistribute after } scrollerHeight = this.computeScrollerHeight(totalHeight); this.setGridHeight(scrollerHeight, isAuto); // is the event limit dynamically calculated? if (eventLimit && typeof eventLimit !== 'number') { console.log("eventLimit"); // this.timelineGrid.limitRows(eventLimit); // limit the levels after the grid's row heights have been set } if (!isAuto && setPotentialScroller(this.scrollerEl, scrollerHeight)) { // using scrollbars? compensateScroll(this.headRowEl, getScrollbarWidths(this.scrollerEl)); // doing the scrollbar compensation might have created text overflow which created more height. redo scrollerHeight = this.computeScrollerHeight(totalHeight); this.scrollerEl.height(scrollerHeight); } }, // Sets the height of just the ResourceGrid component in this view setGridHeight: function(height, isAuto) { if (isAuto) { undistributeHeight(this.resourceGrid.rowEls); undistributeHeight(this.timelineGrid.rowEls); } else { distributeHeight(this.resourceGrid.rowEls, height, true); // true = compensate for height-hogging rows distributeHeight(this.timelineGrid.rowEls, height, true); // true = compensate for height-hogging rows } }, rowToResourceId: function(row){ return this.resources[row].id; }, resourceIdToRow: function(resourceId) { var resources = this.resources; var row; for (row = 0; row < this.rowCnt; row++) { if (resources[row].id == resourceId) { return row; } } return -1; }, updateSize: function(isResize) { // this.resourceGrid.updateSize(isResize); this.timelineGrid.updateSize(isResize); View.prototype.updateSize.call(this, isResize); // call the super-method }, /* Events ------------------------------------------------------------------------------------------------------------------*/ // Renders the given events onto the view and populates the segments array renderEvents: function(events) { var i; var event; for (i = 0; i < events.length; i++) { event = events[i]; event.row = this.resourceIdToRow(event.resource); } this.timelineGrid.renderEvents(events); this.updateHeight(); // must compensate for events that overflow the row }, // Retrieves all segment objects that are rendered in the view getEventSegs: function() { return this.timelineGrid.getEventSegs(); }, // Unrenders all event elements and clears internal segment data unrenderEvents: function() { this.timelineGrid.unrenderEvents(); // we DON'T need to call updateHeight() because: // A) a renderEvents() call always happens after this, which will eventually call updateHeight() // B) in IE8, this causes a flash whenever events are rerendered }, /* Dragging (for both events and external elements) ------------------------------------------------------------------------------------------------------------------*/ // A returned value of `true` signals that a mock "helper" event has been rendered. renderDrag: function(dropLocation, seg) { return this.timelineGrid.renderDrag(dropLocation, seg); }, unrenderDrag: function() { this.timelineGrid.unrenderDrag(); }, /* Selection ------------------------------------------------------------------------------------------------------------------*/ // Renders a visual indication of a selection renderSelection: function(range) { this.timelineGrid.renderSelection(range); }, // Unrenders a visual indications of a selection unrenderSelection: function() { this.timelineGrid.unrenderSelection(); }, // Event drop reportEventDrop: function(event, dropLocation, largeUnit, el, ev) { var newRow = dropLocation.row; if (newRow !== undefined) { dropLocation.resource = this.rowToResourceId(newRow); } View.prototype.reportEventDrop.apply(this, arguments); }, isEventResizableFromStart: function(event) { return this.isEventResizable(event); }, });
mit
enjoycreative/enjoy_cms_pages
app/helpers/enjoy/pages/canonical_helper.rb
402
module Enjoy::Pages::CanonicalHelper def enjoy_canonical_tag(url = "") return if url.blank? tag(:link, href: url, rel: :canonical) end def enjoy_canonical_tag_for(obj) return if obj.use_enjoy_canonicalable url = obj.enjoy_canonicalable_url url = url_for(obj.enjoy_canonicalable) if !url.blank? and obj.enjoy_canonicalable enjoy_canonical_tag(url) if url.blank? end end
mit
azl397985856/ltcrm-components
stories/checkBoxGroup.js
3175
import React from 'react'; import { render } from 'react-dom' import {Table, Icon, Checkbox, Input, Row, Col, Form, Button, message, InputNumber } from 'antd'; import CheckboxGroup from '../components/CheckboxGroup/index' import { storiesOf, action } from '@kadira/storybook'; import R from 'ramda'; import mixin from '../utils/mixin.js'; const FormItem = Form.Item; const columns = [{ title: '参数', dataIndex: 'name', key: 'name', }, { title: '说明', dataIndex: 'desc', key: 'desc', }, { title: '类型', dataIndex: 'type', key: 'type', }, { title: '默认值', dataIndex: 'default', key: 'default', }]; const data = [{ name: 'options', desc: '指定可选项', type: 'array', default: '[]' }, { name: 'value', desc: '指定选中的选项', type: 'array', default: '[]' }, { name: 'onChange', desc: '变化时回调函数', type: 'Function(checkedValue)', default: 'noop' }, { name: 'span', desc: '控制单个值列宽', type: '整数', default: '4' }]; const Component = React.createClass({ getInitialState() { return { } }, render() { console.log(this.props.options); return ( <div> <CheckboxGroup options={this.props.options} span={this.props.span}/> </div> ) } }); const Sample = React.createClass({ mixins: [mixin], getInitialState() { return { options: ['Apple', 'Pear', 'Orange'] } }, onChange() { }, onDurationBlur() { }, render() { return ( <Form horizontal className="advanced-search-form"> <Row> <Component span={this.state.span} value={this.state.value} options={this.state.options} onChange={this.onChange}/> </Row> <Row style={{margin: 10}}> <Col span="12"> <FormItem label="span: " labelCol={{ span: 6 }} wrapperCol={{ span: 14 }}> <Input max={1000000} placeholder="plz input span" value={this.state.span} onChange={this.setValue.bind(this, 'span')} /> </FormItem> </Col> </Row> </Form> ) } }); storiesOf('CheckboxGroup', module) .add('CheckboxGroup', () => { return ( <div className="lt-com-container"> <h2 style={{textAlign: 'center', marginBottom: 15, color: '#4078c0'}}>CheckboxGroup</h2> CheckboxGroup主要是对Checkbox的封装,以便于更方便的使用。支持传入数组显示多个checkbox,支持列排版<br/><br/> <div className="lt-com-box"> <span className="lt-com-title">Code Lab</span> <div id="codeLab" className="lt-com-component"/><Sample/> </div> <div className="lt-com-box"> <span className="lt-com-title">Code List</span> <div className="lt-com-component"> {' <CheckboxGroup options={this.props.options} span={this.props.span}/>'}<br/> </div> </div> <div className="lt-com-box"> <span className="lt-com-title">API</span> <div className="lt-com-code-interface"> <Table columns={columns} dataSource={data} /> </div> </div> </div> ); });
mit
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_90/safe/CWE_90__backticks__func_preg_match-only_letters__name-sprintf_%s_simple_quote.php
1415
<?php /* Safe sample input : backticks interpretation, reading the file /tmp/tainted.txt sanitize : check if there is only letters construction : use of sprintf via a %s with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = `cat /tmp/tainted.txt`; $re = "/^[a-zA-Z]*$/"; if(preg_match($re, $tainted) == 1){ $tainted = $tainted; } else{ $tainted = ""; } $query = sprintf("name='%s'", $tainted); $ds=ldap_connect("localhost"); $r=ldap_bind($ds); $sr=ldap_search($ds,"o=My Company, c=US", $query); ldap_close($ds); ?>
mit
stonedz/pff2-mongo
src/Pff2Mongo.php
1240
<?php /** * User: paolo.fagni@gmail.com * Date: 03/11/14 * Time: 23.22 */ namespace pff\modules; use pff\Abs\AModule; use pff\Iface\IBeforeSystemHook; use pff\Iface\IConfigurableModule; use Doctrine\MongoDB\Connection; use Doctrine\ODM\MongoDB\Configuration; use Doctrine\ODM\MongoDB\DocumentManager; use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver; class Pff2Mongo extends AModule implements IConfigurableModule, IBeforeSystemHook { private $_server, $_dbName; public function __construct($confFile = 'pff2-mongo/module.conf.local.yaml') { $this->loadConfig($confFile); } /** * @param array $parsedConfig * @return mixed */ public function loadConfig($parsedConfig) { $conf = $this->readConfig($parsedConfig); $this->_server = $conf['moduleConf']['server']; $this->_dbName = $conf['moduleConf']['dbName']; } /** * Executed before the system startup * * @return mixed */ public function doBeforeSystem() { $this->_app->getConfig()->setConfig('mongo_server', $this->_server); $this->_app->getConfig()->setConfig('mongo_dbName', $this->_dbName); // TODO: Implement doBeforeSystem() method. } }
mit
Preiscoin/1
src/qt/locale/bitcoin_cs.ts
118427
<?xml version="1.0" ?><!DOCTYPE TS><TS language="cs" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Preiscoin</source> <translation>O Preiscoinu</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Preiscoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Preiscoin&lt;/b&gt; verze</translation> </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 (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Tohle je experimentální program. Šířen pod licencí MIT/X11, viz přiložený soubor COPYING nebo http://www.opensource.org/licenses/mit-license.php. Tento produkt zahrnuje programy vyvinuté OpenSSL Projektem pro použití v OpenSSL Toolkitu (http://www.openssl.org/) a kryptografický program od Erika Younga (eay@cryptsoft.com) a program UPnP od Thomase Bernarda.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The Preiscoin developers</source> <translation>Vývojáři Preiscoinu</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresář</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dvojklikem myši začneš upravovat označení adresy</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Vytvoř novou adresu</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Zkopíruj aktuálně vybranou adresu do systémové schránky</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>Nová &amp;adresa</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Preiscoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Tohle jsou tvé Preiscoinové adresy pro příjem plateb. Můžeš dát pokaždé každému plátci novou adresu, abys věděl, kdo ti kdy kolik platil.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopíruj adresu</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Zobraz &amp;QR kód</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Preiscoin address</source> <translation>Podepiš zprávu, čímž prokážeš, že jsi vlastníkem Preiscoinové adresy</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Po&amp;depiš zprávu</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Smaž zvolenou adresu ze seznamu</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Exportuj data z tohoto panelu do souboru</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Export</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Preiscoin address</source> <translation>Ověř zprávu, aby ses ujistil, že byla podepsána danou Preiscoinovou adresou</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Ověř zprávu</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>S&amp;maž</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Preiscoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Tohle jsou tvé Preiscoinové adresy pro posílání plateb. Před odesláním mincí si vždy zkontroluj částku a cílovou adresu.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopíruj &amp;označení</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Uprav</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Pošli min&amp;ce</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exportuj data adresáře</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>CSV formát (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Chyba při exportu</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Nemohu zapisovat do souboru %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Označení</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(bez označení)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Změna hesla</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Zadej platné heslo</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Zadej nové heslo</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Totéž heslo ještě jednou</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <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>Zadej nové heslo k peněžence.&lt;br/&gt;Použij &lt;b&gt;alespoň 10 náhodných znaků&lt;/b&gt; nebo &lt;b&gt;alespoň osm slov&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Zašifruj peněženku</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>K provedení této operace musíš zadat heslo k peněžence, aby se mohla odemknout.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Odemkni peněženku</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>K provedení této operace musíš zadat heslo k peněžence, aby se mohla dešifrovat.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dešifruj peněženku</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Změň heslo</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Zadej staré a nové heslo k peněžence.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Potvrď zašifrování peněženky</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 PreiscoinS&lt;/b&gt;!</source> <translation>Varování: Pokud si zašifruješ peněženku a ztratíš či zapomeneš heslo, &lt;b&gt;PŘIJDEŠ O VŠECHNY PreiscoinY&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Jsi si jistý, že chceš peněženku zašifrovat?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>DŮLEŽITÉ: Všechny předchozí zálohy peněženky by měly být nahrazeny nově vygenerovanou, zašifrovanou peněženkou. Z bezpečnostních důvodů budou předchozí zálohy nešifrované peněženky nepoužitelné, jakmile začneš používat novou zašifrovanou peněženku.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Upozornění: Caps Lock je zapnutý!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Peněženka je zašifrována</translation> </message> <message> <location line="-56"/> <source>Preiscoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Preiscoins from being stolen by malware infecting your computer.</source> <translation>Preiscoin se teď ukončí, aby dokončil zašifrování. Pamatuj však, že pouhé zašifrování peněženky úplně nezabraňuje krádeži tvých Preiscoinů malwarem, kterým se může počítač nakazit.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Zašifrování peněženky selhalo</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Zašifrování peněženky selhalo kvůli vnitřní chybě. Tvá peněženka tedy nebyla zašifrována.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Zadaná hesla nejsou shodná.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Odemčení peněženky selhalo</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Nezadal jsi správné heslo pro dešifrování peněženky.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Dešifrování peněženky selhalo</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Heslo k peněžence bylo v pořádku změněno.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Po&amp;depiš zprávu...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Synchronizuji se se sítí...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Přehled</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Zobraz celkový přehled peněženky</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transakce</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Procházej historii transakcí</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Uprav seznam uložených adres a jejich označení</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Zobraz seznam adres pro příjem plateb</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Konec</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Ukonči aplikaci</translation> </message> <message> <location line="+4"/> <source>Show information about Preiscoin</source> <translation>Zobraz informace o Preiscoinu</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>O &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Zobraz informace o Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Možnosti...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>Zaši&amp;fruj peněženku...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Zazálohuj peněženku...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Změň &amp;heslo...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importuji bloky z disku...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Vytvářím nový index bloků na disku...</translation> </message> <message> <location line="-347"/> <source>Send coins to a Preiscoin address</source> <translation>Pošli mince na Preiscoinovou adresu</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Preiscoin</source> <translation>Uprav nastavení Preiscoinu</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Zazálohuj peněženku na jiné místo</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Změň heslo k šifrování peněženky</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Ladicí okno</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Otevři ladicí a diagnostickou konzoli</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Ověř zprávu...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Preiscoin</source> <translation>Preiscoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Peněženka</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Pošli</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>Při&amp;jmi</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Adresy</translation> </message> <message> <location line="+22"/> <source>&amp;About Preiscoin</source> <translation>O &amp;Preiscoinu</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Zobraz/Skryj</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Zobraz nebo skryj hlavní okno</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Zašifruj soukromé klíče ve své peněžence</translation> </message> <message> <location line="+7"/> <source>Sign messages with your Preiscoin addresses to prove you own them</source> <translation>Podepiš zprávy svými Preiscoinovými adresami, čímž prokážeš, že jsi jejich vlastníkem</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Preiscoin addresses</source> <translation>Ověř zprávy, aby ses ujistil, že byly podepsány danými Preiscoinovými adresami</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Soubor</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Nastavení</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>Ná&amp;pověda</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Panel s listy</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>Preiscoin client</source> <translation>Preiscoin klient</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Preiscoin network</source> <translation><numerusform>%n aktivní spojení do Preiscoinové sítě</numerusform><numerusform>%n aktivní spojení do Preiscoinové sítě</numerusform><numerusform>%n aktivních spojení do Preiscoinové sítě</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Není dostupný žádný zdroj bloků...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Zpracováno %1 z přibližně %2 bloků transakční historie.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Zpracováno %1 bloků transakční historie.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>hodinu</numerusform><numerusform>%n hodiny</numerusform><numerusform>%n hodin</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>den</numerusform><numerusform>%n dny</numerusform><numerusform>%n dnů</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>týden</numerusform><numerusform>%n týdny</numerusform><numerusform>%n týdnů</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>Stahuji ještě bloky transakcí za poslední %1</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Poslední stažený blok byl vygenerován %1 zpátky.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Následné transakce ještě nebudou vidět.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Chyba</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Upozornění</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informace</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Tahle transakce přesahuje velikostní limit. I tak ji ale můžeš poslat, pokud za ni zaplatíš poplatek %1, který půjde uzlům, které tvou transakci zpracují, a navíc tak podpoříš síť. Chceš zaplatit poplatek?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Aktuální</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Stahuji...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Potvrď transakční poplatek</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Odeslané transakce</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Příchozí transakce</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1 Částka: %2 Typ: %3 Adresa: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Zpracování URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Preiscoin address or malformed URI parameters.</source> <translation>Nepodařilo se analyzovat URI! Důvodem může být neplatná Preiscoinová adresa nebo poškozené parametry URI.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Peněženka je &lt;b&gt;zašifrovaná&lt;/b&gt; a momentálně &lt;b&gt;odemčená&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>Peněženka je &lt;b&gt;zašifrovaná&lt;/b&gt; a momentálně &lt;b&gt;zamčená&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Preiscoin can no longer continue safely and will quit.</source> <translation>Stala se fatální chyba. Preiscoin nemůže bezpečně pokračovat v činnosti, a proto skončí.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Upozornění sítě</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Uprav adresu</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Označení</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Označení spojené s tímto záznamem v adresáři</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresa spojená s tímto záznamem v adresáři. Lze upravovat jen pro odesílací adresy.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nová přijímací adresa</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nová odesílací adresa</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Uprav přijímací adresu</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Uprav odesílací adresu</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Zadaná adresa &quot;%1&quot; už v adresáři je.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Preiscoin address.</source> <translation>Zadaná adresa &quot;%1&quot; není platná Preiscoinová adresa.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Nemohu odemknout peněženku.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Nepodařilo se mi vygenerovat nový klíč.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Preiscoin-Qt</source> <translation>Preiscoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>verze</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Užití:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>možnosti příkazové řádky</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Možnosti UI</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Nastavit jazyk, například &quot;de_DE&quot; (výchozí: systémové nastavení)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Nastartovat minimalizovaně</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Zobrazit startovací obrazovku (výchozí: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Možnosti</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Hlavní</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>Dobrovolný transakční poplatek za každý započatý kB dopomáhá k rychlému zpracování tvých transakcí. Většina transakcí má do 1 kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Platit &amp;transakční poplatek</translation> </message> <message> <location line="+31"/> <source>Automatically start Preiscoin after logging in to the system.</source> <translation>Automaticky spustí Preiscoin po přihlášení do systému.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Preiscoin on system login</source> <translation>S&amp;pustit Preiscoin po přihlášení do systému</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Vrátí všechny volby na výchozí hodnoty.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Obnovit nastavení</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Síť</translation> </message> <message> <location line="+6"/> <source>Automatically open the Preiscoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automaticky otevře potřebný port na routeru. Tohle funguje jen za předpokladu, že tvůj router podporuje UPnP a že je UPnP povolené.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Namapovat port přes &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Preiscoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Připojí se do Preiscoinové sítě přes SOCKS proxy (např. když se připojuje přes Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Připojit přes SOCKS proxy:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP adresa proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP adresa proxy (např. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>Por&amp;t:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Port proxy (např. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>&amp;Verze SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Verze SOCKS proxy (např. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>O&amp;kno</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Po minimalizaci okna zobrazí pouze ikonu v panelu.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimalizovávat do ikony v panelu</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>Zavřením se aplikace minimalizuje. Pokud je tato volba zaškrtnuta, tak se aplikace ukončí pouze zvolením Konec v menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Za&amp;vřením minimalizovat</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>Zobr&amp;azení</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Jazyk uživatelského rozhraní:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Preiscoin.</source> <translation>Tady lze nastavit jazyk uživatelského rozhraní. Nastavení se projeví až po restartování Preiscoinu.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>J&amp;ednotka pro částky: </translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Zvol výchozí podjednotku, která se bude zobrazovat v programu a při posílání mincí.</translation> </message> <message> <location line="+9"/> <source>Whether to show Preiscoin addresses in the transaction list or not.</source> <translation>Zda ukazovat Preiscoinové adresy ve výpisu transakcí nebo ne.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Ukazo&amp;vat adresy ve výpisu transakcí</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Budiž</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Zrušit</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Uložit</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>výchozí</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Potvrzení obnovení nastavení</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Některá nastavení mohou vyžadovat restart klienta, aby se mohly projevit.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Chceš pokračovat?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Upozornění</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Preiscoin.</source> <translation>Nastavení se projeví až po restartování Preiscoinu.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Zadaná adresa proxy je neplatná.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Preiscoin network after a connection is established, but this process has not completed yet.</source> <translation>Zobrazené informace nemusí být aktuální. Tvá peněženka se automaticky sesynchronizuje s Preiscoinovou sítí, jakmile se s ní spojí. Zatím ale ještě není synchronizace dokončena.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Stav účtu:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Nepotvrzeno:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Peněženka</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Nedozráno:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Vytěžené mince, které ještě nejsou zralé</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Poslední transakce&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Aktuální stav tvého účtu</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Celkem z transakcí, které ještě nejsou potvrzené a které se ještě nezapočítávají do celkového stavu účtu</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>nesynchronizováno</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start Preiscoin: click-to-pay handler</source> <translation>Nemůžu spustit Preiscoin: obsluha click-to-pay</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR kód</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Požadovat platbu</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Částka:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Označení:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Zpráva:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Ulož jako...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Chyba při kódování URI do QR kódu.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Zadaná částka je neplatná, překontroluj ji prosím.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Výsledná URI je příliš dlouhá, zkus zkrátit text označení / zprávy.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Ulož QR kód</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG obrázky (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Název klienta</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>N/A</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Verze klienta</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informace</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Používaná verze OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Čas spuštění</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Síť</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Počet spojení</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>V testnetu</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Řetězec bloků</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Aktuální počet bloků</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Odhad celkového počtu bloků</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Čas posledního bloku</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Otevřít</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Argumenty z příkazové řádky</translation> </message> <message> <location line="+7"/> <source>Show the Preiscoin-Qt help message to get a list with possible Preiscoin command-line options.</source> <translation>Seznam parametrů Preiscoinu pro příkazovou řádku získáš v nápovědě Preiscoinu Qt.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Zobrazit</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konzole</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Datum kompilace</translation> </message> <message> <location line="-104"/> <source>Preiscoin - Debug window</source> <translation>Preiscoin - ladicí okno</translation> </message> <message> <location line="+25"/> <source>Preiscoin Core</source> <translation>Jádro Preiscoinu</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Soubor s ladicími záznamy</translation> </message> <message> <location line="+7"/> <source>Open the Preiscoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Otevři soubor s ladicími záznamy Preiscoinu z aktuálního datového adresáře. U velkých logů to může pár vteřin zabrat.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Vyčistit konzoli</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Preiscoin RPC console.</source> <translation>Vítej v Preiscoinové RPC konzoli.</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>V historii se pohybuješ šipkami nahoru a dolů a pomocí &lt;b&gt;Ctrl-L&lt;/b&gt; čistíš obrazovku.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Napsáním &lt;b&gt;help&lt;/b&gt; si vypíšeš přehled dostupných příkazů.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Pošli mince</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Pošli více příjemcům naráz</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Při&amp;dej příjemce</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Smaž všechny transakční formuláře</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Všechno s&amp;maž</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Stav účtu:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Potvrď odeslání</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>P&amp;ošli</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; pro %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Potvrď odeslání mincí</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Jsi si jistý, že chceš poslat %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> a </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adresa příjemce je neplatná, překontroluj ji prosím.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Odesílaná částka musí být větší než 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Částka překračuje stav účtu.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Celková částka při připočítání poplatku %1 překročí stav účtu.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Zaznamenána duplikovaná adresa; každá adresa může být v odesílané platbě pouze jednou.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Chyba: Vytvoření transakce selhalo!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Chyba: Transakce byla odmítnuta. Tohle může nastat, pokud nějaké mince z tvé peněženky už jednou byly utraceny, například pokud používáš kopii souboru wallet.dat a mince byly utraceny v druhé kopii, ale nebyly označeny jako utracené v této.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Čás&amp;tka:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Komu:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Adresa příjemce (např. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Zadej označení této adresy; obojí se ti pak uloží do adresáře</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>O&amp;značení:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Vyber adresu z adresáře</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Vlož adresu ze schránky</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Smaž tohoto příjemce</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Preiscoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Zadej Preiscoinovou adresu (např. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Podpisy - podepsat/ověřit zprávu</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Podepiš zprávu</translation> </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>Podepsáním zprávy svými adresami můžeš prokázat, že je skutečně vlastníš. Buď opatrný a nepodepisuj nic vágního; například při phishingových útocích můžeš být lákán, abys něco takového podepsal. Podepisuj pouze zcela úplná a detailní prohlášení, se kterými souhlasíš.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Adresa, kterou se zpráva podepíše (např. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Vyber adresu z adresáře</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Vlož adresu ze schránky</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Sem vepiš zprávu, kterou chceš podepsat</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Podpis</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Zkopíruj aktuálně vybraný podpis do systémové schránky</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Preiscoin address</source> <translation>Podepiš zprávu, čímž prokážeš, že jsi vlastníkem této Preiscoinové adresy</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Po&amp;depiš zprávu</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Vymaž všechna pole formuláře pro podepsání zrávy</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Všechno &amp;smaž</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Ověř zprávu</translation> </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>K ověření podpisu zprávy zadej podepisující adresu, zprávu (ověř si, že správně kopíruješ zalomení řádků, mezery, tabulátory apod.) a podpis. Dávej pozor na to, abys nezkopíroval do podpisu víc, než co je v samotné podepsané zprávě, abys nebyl napálen man-in-the-middle útokem.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Adresa, kterou je zpráva podepsána (např. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Preiscoin address</source> <translation>Ověř zprávu, aby ses ujistil, že byla podepsána danou Preiscoinovou adresou</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>O&amp;věř zprávu</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Vymaž všechna pole formuláře pro ověření zrávy</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Preiscoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Zadej Preiscoinovou adresu (např. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Kliknutím na &quot;Podepiš zprávu&quot; vygeneruješ podpis</translation> </message> <message> <location line="+3"/> <source>Enter Preiscoin signature</source> <translation>Vlož Preiscoinový podpis</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Zadaná adresa je neplatná.</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>Zkontroluj ji prosím a zkus to pak znovu.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Zadaná adresa nepasuje ke klíči.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Odemčení peněženky bylo zrušeno.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Soukromý klíč pro zadanou adresu není dostupný.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Podepisování zprávy selhalo.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Zpráv podepsána.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Podpis nejde dekódovat.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Zkontroluj ho prosím a zkus to pak znovu.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Podpis se neshoduje s hašem zprávy.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Ověřování zprávy selhalo.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Zpráva ověřena.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Preiscoin developers</source> <translation>Vývojáři Preiscoinu</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Otřevřeno dokud %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepotvrzeno</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 potvrzení</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Stav</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, rozesláno přes 1 uzel</numerusform><numerusform>, rozesláno přes %n uzly</numerusform><numerusform>, rozesláno přes %n uzlů</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Zdroj</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Vygenerováno</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Od</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Pro</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>vlastní adresa</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>označení</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Příjem</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>dozraje po jednom bloku</numerusform><numerusform>dozraje po %n blocích</numerusform><numerusform>dozraje po %n blocích</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>neakceptováno</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Výdaj</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transakční poplatek</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Čistá částka</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Zpráva</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Komentář</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID transakce</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 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>Vygenerované mince musí čekat 120 bloků, než mohou být utraceny. Když jsi vygeneroval tenhle blok, tak byl rozposlán do sítě, aby byl přidán do řetězce bloků. Pokud se mu nepodaří dostat se do řetězce, změní se na &quot;neakceptovaný&quot; a nepůjde utratit. To se občas může stát, pokud jiný uzel vygeneruje blok zhruba ve stejném okamžiku jako ty.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Ladicí informace</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transakce</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Vstupy</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Částka</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>true</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>false</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ještě nebylo rozesláno</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Otevřeno pro 1 další blok</numerusform><numerusform>Otevřeno pro %n další bloky</numerusform><numerusform>Otevřeno pro %n dalších bloků</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>neznámo</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detaily transakce</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Toto okno zobrazuje detailní popis transakce</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Částka</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Otevřeno pro 1 další blok</numerusform><numerusform>Otevřeno pro %n další bloky</numerusform><numerusform>Otevřeno pro %n dalších bloků</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Otřevřeno dokud %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 potvrzení)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepotvrzeno (%1 z %2 potvrzení)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Potvrzeno (%1 potvrzení)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Vytěžené mince budou použitelné po dozrání, tj. po jednom bloku</numerusform><numerusform>Vytěžené mince budou použitelné po dozrání, tj. po %n blocích</numerusform><numerusform>Vytěžené mince budou použitelné po dozrání, tj. po %n blocích</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Tento blok nedostal žádný jiný uzel a pravděpodobně nebude akceptován!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Vygenerováno, ale neakceptováno</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Přijato do</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Přijato od</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Posláno na</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Platba sama sobě</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Vytěženo</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Stav transakce. Najetím myši na toto políčko si zobrazíš počet potvrzení.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Datum a čas přijetí transakce.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Druh transakce.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Cílová adresa transakce.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Částka odečtená z nebo přičtená k účtu.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Vše</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Dnes</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Tento týden</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Tento měsíc</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Minulý měsíc</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Letos</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Rozsah...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Přijato</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Posláno</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Sám sobě</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Vytěženo</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Ostatní</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Zadej adresu nebo označení pro její vyhledání</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimální částka</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopíruj adresu</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopíruj její označení</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopíruj částku</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Kopíruj ID transakce</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Uprav označení</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Zobraz detaily transakce</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exportuj transakční data</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>CSV formát (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Potvrzeno</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Označení</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Částka</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Chyba při exportu</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Nemohu zapisovat do souboru %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Rozsah:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>až</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Pošli mince</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Export</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Exportuj data z tohoto panelu do souboru</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Záloha peněženky</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Data peněženky (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Zálohování selhalo</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Při ukládání peněženky na nové místo se přihodila nějaká chyba.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Úspěšně zazálohováno</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Data z peněženky byla v pořádku uložena na nové místo.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Preiscoin version</source> <translation>Verze Preiscoinu</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Užití:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or Preiscoind</source> <translation>Poslat příkaz pro -server nebo Preiscoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Výpis příkazů</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Získat nápovědu pro příkaz</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Možnosti:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: Preiscoin.conf)</source> <translation>Konfigurační soubor (výchozí: Preiscoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: Preiscoind.pid)</source> <translation>PID soubor (výchozí: Preiscoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Adresář pro data</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Nastavit velikost databázové vyrovnávací paměti v megabajtech (výchozí: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Čekat na spojení na &lt;portu&gt; (výchozí: 9333 nebo testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Povolit nejvýše &lt;n&gt; připojení k uzlům (výchozí: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Připojit se k uzlu, získat adresy jeho protějšků a odpojit se</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Specifikuj svou veřejnou adresu</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Práh pro odpojování zlobivých uzlů (výchozí: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Doba ve vteřinách, po kterou se nebudou moci zlobivé uzly znovu připojit (výchozí: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Při nastavování naslouchacího RPC portu %i pro IPv4 nastala chyba: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Čekat na JSON RPC spojení na &lt;portu&gt; (výchozí: 9332 nebo testnet: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Akceptovat příkazy z příkazové řádky a přes JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Běžet na pozadí jako démon a akceptovat příkazy</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Použít testovací síť (testnet)</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Přijímat spojení zvenčí (výchozí: 1, pokud není zadáno -proxy nebo -connect)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=Preiscoinrpc 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;Preiscoin Alert&quot; admin@foo.com </source> <translation>%s, musíš nastavit rpcpassword v konfiguračním souboru: %s Je vhodné použít následující náhodné heslo: rpcuser=Preiscoinrpc rpcpassword=%s (není potřeba si ho pamatovat) rpcuser a rpcpassword NESMÍ být stejné. Pokud konfigurační soubor ještě neexistuje, vytvoř ho tak, aby ho mohl číst pouze vlastník. Je také doporučeno si nastavit alertnotify, abys byl upozorněn na případné problémy; například: alertnotify=echo %%s | mail -s &quot;Preiscoin Alert&quot; admin@foo.com </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Při nastavování naslouchacího RPC portu %u pro IPv6 nastala chyba, vracím se k IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Poslouchat na zadané adrese. Pro zápis IPv6 adresy použij notaci [adresa]:port</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Preiscoin is probably already running.</source> <translation>Nedaří se mi získat zámek na datový adresář %s. Preiscoin pravděpodobně už jednou běží.</translation> </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>Chyba: Transakce byla odmítnuta! Tohle může nastat, pokud nějaké mince z tvé peněženky už jednou byly utraceny, například pokud používáš kopii souboru wallet.dat a mince byly utraceny v druhé kopii, ale nebyly označeny jako utracené v této.</translation> </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>Chyba: Tahle transakce vyžaduje transakční poplatek nejméně %s kvůli velikosti zasílané částky, komplexnosti nebo použití nedávno přijatých mincí!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Spustit příkaz po přijetí relevantního hlášení (%s se v příkazu nahradí za zprávu)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Spustit příkaz, když se objeví transakce týkající se peněženky (%s se v příkazu nahradí za TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Nastavit maximální velikost prioritních/nízkopoplatkových transakcí v bajtech (výchozí: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Tohle je testovací verze – používej ji jen na vlastní riziko, ale rozhodně ji nepoužívej k těžbě nebo pro obchodní aplikace</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Upozornění: -paytxfee je nastaveno velmi vysoko! Toto je transakční poplatek, který zaplatíš za každou poslanou transakci.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Upozornění: Zobrazené transakce nemusí být správné! Možná potřebuješ aktualizovat nebo ostatní uzly potřebují aktualizovat.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Preiscoin will not work properly.</source> <translation>Upozornění: Zkontroluj, že máš v počítači správně nastavený datum a čas! Pokud jsou nastaveny špatně, Preiscoin nebude fungovat správně.</translation> </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>Upozornění: nastala chyba při čtení souboru wallet.dat! Všechny klíče se přečetly správně, ale data o transakcích nebo záznamy v adresáři mohou chybět či být nesprávné.</translation> </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>Upozornění: soubor wallet.dat je poškozený, data jsou však zachráněna! Původní soubor wallet.dat je uložený jako wallet.{timestamp}.bak v %s. Pokud je stav tvého účtu nebo transakce nesprávné, zřejmě bys měl obnovit zálohu.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Pokusit se zachránit soukromé klíče z poškozeného souboru wallet.dat</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Možnosti vytvoření bloku:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Připojit se pouze k zadanému uzlu (příp. zadaným uzlům)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Bylo zjištěno poškození databáze bloků</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Zjistit vlastní IP adresu (výchozí: 1, pokud naslouchá a není zadáno -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Chceš přestavět databázi bloků hned teď?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Chyba při zakládání databáze bloků</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Chyba při vytváření databázového prostředí %s pro peněženku!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Chyba při načítání databáze bloků</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Chyba při otevírání databáze bloků</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Problém: Na disku je málo místa!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Chyba: Peněženka je zamčená, nemohu vytvořit transakci!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Chyba: systémová chyba: </translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Nepodařilo se naslouchat na žádném portu. Použij -listen=0, pokud to byl tvůj záměr.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Nepodařilo se přečíst informace o bloku</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Nepodařilo se přečíst blok</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Nepodařilo se sesynchronizovat index bloků</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Nepodařilo se zapsat index bloků</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Nepodařilo se zapsat informace o bloku</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Nepodařilo se zapsat blok</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Nepodařilo se zapsat informace o souboru</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Selhal zápis do databáze mincí</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Nepodařilo se zapsat index transakcí</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Nepodařilo se zapsat data o vracení změn</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Hledat uzly přes DNS (výchozí: 1, pokud není zadáno -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Generovat mince (výchozí: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Kolik bloků při startu zkontrolovat (výchozí: 288, 0 = všechny)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Jak moc důkladná má být verifikace bloků (0-4, výchozí: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>Je nedostatek deskriptorů souborů.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Znovu vytvořit index řetězce bloků z aktuálních blk000??.dat souborů</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Nastavení počtu vláken pro servisní RPC volání (výchozí: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Ověřuji bloky...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Kontroluji peněženku...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importovat bloky z externího souboru blk000??.dat</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>Nastavení počtu vláken pro verifikaci skriptů (max. 16, 0 = automaticky, &lt;0 = nechat daný počet jader volný, výchozí: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informace</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Neplatná -tor adresa: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Neplatná částka pro -minrelaytxfee=&lt;částka&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Neplatná částka pro -mintxfee=&lt;částka&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Spravovat úplný index transakcí (výchozí: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maximální velikost přijímacího bufferu pro každé spojení, &lt;n&gt;*1000 bajtů (výchozí: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maximální velikost odesílacího bufferu pro každé spojení, &lt;n&gt;*1000 bajtů (výchozí: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Uznávat pouze řetěz bloků, který odpovídá vnitřním kontrolním bodům (výchozí: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Připojit se pouze k uzlům v &lt;net&gt; síti (IPv4, IPv6 nebo Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Tisknout speciální ladicí informace. Implikuje použití všech -debug* voleb</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Tisknout speciální ladicí informace o síti</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Připojit před ladicí výstup časové razítko</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Preiscoin Wiki for SSL setup instructions)</source> <translation>Možnosti SSL: (viz instrukce nastavení SSL v Preiscoin Wiki)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Zvol verzi socks proxy (4-5, výchozí: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Posílat stopovací/ladicí informace do konzole místo do souboru debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Posílat stopovací/ladicí informace do debuggeru</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Nastavit maximální velikost bloku v bajtech (výchozí: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Nastavit minimální velikost bloku v bajtech (výchozí: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Při spuštění klienta zmenšit soubor debug.log (výchozí: 1, pokud není zadáno -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Podepisování transakce selhalo</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Zadej časový limit spojení v milisekundách (výchozí: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Systémová chyba: </translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Částka v transakci je příliš malá</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Částky v transakci musí být kladné</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Transace je příliš velká</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Použít UPnP k namapování naslouchacího portu (výchozí: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Použít UPnP k namapování naslouchacího portu (výchozí: 1, pokud naslouchá)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Použít proxy k připojení ke skryté služby (výchozí: stejné jako -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Uživatelské jméno pro JSON-RPC spojení</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Upozornění</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Upozornění: tahle verze je zastaralá, měl bys ji aktualizovat!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>Je třeba přestavět databázi použitím -reindex, aby bylo možné změnit -txindex</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>Soubor wallet.dat je poškozen, jeho záchrana se nezdařila</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Heslo pro JSON-RPC spojení</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Povolit JSON-RPC spojení ze specifikované IP adresy</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Posílat příkazy uzlu běžícím na &lt;ip&gt; (výchozí: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Spustit příkaz, když se změní nejlepší blok (%s se v příkazu nahradí hashem bloku)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Převést peněženku na nejnovější formát</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Nastavit zásobník klíčů na velikost &lt;n&gt; (výchozí: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Přeskenovat řetězec bloků na chybějící transakce tvé pěněženky</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Použít OpenSSL (https) pro JSON-RPC spojení</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Soubor se serverovým certifikátem (výchozí: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Soubor se serverovým soukromým klíčem (výchozí: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Akceptovatelné šifry (výchozí: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Tato nápověda</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Nedaří se mi připojit na %s na tomhle počítači (operace bind vrátila chybu %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Připojit se přes socks proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Povolit DNS dotazy pro -addnode (přidání uzlu), -seednode a -connect (připojení)</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Načítám adresy...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Chyba při načítání wallet.dat: peněženka je poškozená</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Preiscoin</source> <translation>Chyba při načítání wallet.dat: peněženka vyžaduje novější verzi Preiscoinu</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Preiscoin to complete</source> <translation>Soubor s peněženkou potřeboval přepsat: restartuj Preiscoin, aby se operace dokončila</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Chyba při načítání wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Neplatná -proxy adresa: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>V -onlynet byla uvedena neznámá síť: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>V -socks byla požadována neznámá verze proxy: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Nemohu přeložit -bind adresu: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Nemohu přeložit -externalip adresu: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Neplatná částka pro -paytxfee=&lt;částka&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Neplatná částka</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Nedostatek prostředků</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Načítám index bloků...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Přidat uzel, ke kterému se připojit a snažit se spojení udržet</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Preiscoin is probably already running.</source> <translation>Nedaří se mi připojit na %s na tomhle počítači. Preiscoin už pravděpodobně jednou běží.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Poplatek za kB, který se přidá ke každé odeslané transakci</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Načítám peněženku...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Nemohu převést peněženku do staršího formátu</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Nemohu napsat výchozí adresu</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Přeskenovávám...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Načítání dokončeno</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>K použití volby %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Chyba</translation> </message> <message> <location line="-31"/> <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>Musíš nastavit rpcpassword=&lt;heslo&gt; v konfiguračním souboru: %s Pokud konfigurační soubor ještě neexistuje, vytvoř ho tak, aby ho mohl číst pouze vlastník.</translation> </message> </context> </TS>
mit
prophile/compd
src/redis_process.py
734
from twisted.internet import reactor, protocol import sys import config class RedisDataReceiver(protocol.ProcessProtocol): def __init__(self, on_started): self.on_started = on_started def outReceived(self, data): print >>sys.stderr, data, if 'now ready to accept connections' in data: self.on_started() def errReceived(self, data): print >>sys.stderr, data, def run_redis_server(on_started): print >>sys.stderr, "Starting Redis server..." server = config.redis['server'] reactor.spawnProcess(RedisDataReceiver(on_started), server, args = [server, 'redis.conf'], path = '../database/')
mit
jeanpsv/node-cassandra-querybuilder
conditions/where.js
855
/** * Where constructor */ function Where() { this._clauses = []; this._clauses.push('WHERE'); }; /** * add condition * @param {Operator} condition clause condition * @return {Where} the instance */ Where.prototype.where = function(clause) { if (clause) { this._clauses.push(clause.toString()); } return this; }; /** * concat condition * @param {Operator} clause condition * @return {Where} the instance */ Where.prototype.and = function(clause) { if (clause) { this._clauses.push('AND'); this._clauses.push(clause.toString()); } return this; }; /** * to string * @return {string} string that represents the instance */ Where.prototype.toString = function() { return (this._clauses.length == 1) ? '' : this._clauses.join(' '); }; /*---------- Module exports ----------*/ module.exports = Where;
mit
sensorbee/sensorbee
bql/udf/builtin/array.go
675
package builtin import ( "fmt" "gopkg.in/sensorbee/sensorbee.v0/bql/udf" "gopkg.in/sensorbee/sensorbee.v0/core" "gopkg.in/sensorbee/sensorbee.v0/data" ) // arrayLengthFunc returns the length of the given array. // NULL elements are counted as well. // // It can be used in BQL as `array_length`. // // Input: Array // Return Type: Int var arrayLengthFunc udf.UDF = udf.UnaryFunc(func(ctx *core.Context, arg data.Value) (val data.Value, err error) { if arg.Type() == data.TypeNull { return data.Null{}, nil } else if arg.Type() == data.TypeArray { a, _ := data.AsArray(arg) return data.Int(len(a)), nil } return nil, fmt.Errorf("%v is not an array", arg) })
mit
codefordayton/metroparks-tribute
tribute_files/navigation.js
7970
function initNavigation() { var mainNav, mainNavItems, mainNavLinks, submenu mainNav = jQuery('.main-nav'); mainNavItems = mainNav.children(); mainNavLinks = mainNavItems.children('p'); submenu = jQuery('.sub-menu'); customSubmenu = jQuery('.custom-post-type-submenu'); function fadeInNavigation() { if(isMd){ jQuery('.main-navigations').fadeIn('slow'); } } //fadeInNavigation(); // Reposition Custom Post Types inside menu items w/ corresponding data-attr & link, // assign sub-menu class // Drop Misc items in Places to Go inside Nav List for Conservation Areas var customListMisc = jQuery('.custom-post-misc-areas'); var customConservationList = jQuery('.custom-post-conservation-areas'); customListMisc.children().addClass('custom-misc'); customConservationList.prepend( customListMisc.children() ); customListMisc.remove(); // When on desktop, hover for submenus function setUpSubMenuHover () { // SubMenu for Utility Nav jQuery('.utility-nav').children('.menu-item-has-children').hover(function(){ jQuery(this).addClass('open'); jQuery(this).siblings().removeClass('open'); var subMenu = jQuery(this).children('.sub-menu'); if(!subMenu.hasClass('open')) { jQuery(this).addClass('open'); subMenu.addClass('open'); jQuery(this).siblings().children('.sub-menu').removeClass('open'); } else { return; } }); jQuery('.utility-nav').children('.menu-item-has-children').mouseleave(function(){ var subMenu = jQuery(this).children('.sub-menu'); if(subMenu.hasClass('open')) { subMenu.removeClass('open'); jQuery(this).removeClass('open'); } }); // SubMenu for Main Nav mainNavItems.hover(function(){ jQuery(this).addClass('open'); jQuery(this).siblings().removeClass('open'); var subMenu = jQuery(this).children('.sub-menu'); if(!subMenu.hasClass('open')) { subMenu.addClass('open'); jQuery(this).siblings().children('.sub-menu').removeClass('open'); } else { return; } }); /*jQuery('.sub-menu').mouseleave(function() { var thisSubMenu = jQuery(this); if(jQuery('.sub-menu').hasClass('open')) { setTimeout(function() { jQuery('.sub-menu').addClass('close'); thisSubMenu.parent().removeClass('open'); }, 5); setTimeout(function() { jQuery('.sub-menu').removeClass('close'); jQuery('.sub-menu').removeClass('open'); }, 10); mainNavItems.removeClass('open'); } });*/ // Close sub-menus when mouseenters site-content jQuery( ".site-content" ).mouseenter(function() { setTimeout(function() { jQuery('.sub-menu').addClass('close'); }, 500); setTimeout(function() { jQuery('.sub-menu').removeClass('close'); jQuery('.sub-menu').removeClass('open'); }, 800); mainNavItems.removeClass('open'); }); } // When on mobile, click for submenus function setUpSubMenuClick () { mainNavItems.click(function(event){ var subMenu = jQuery(this).children('.sub-menu'); if(subMenu.length > 0 &&!subMenu.hasClass('open')) { //event.preventDefault(); subMenu.addClass('open'); jQuery(this).addClass('open'); jQuery(this).siblings().removeClass('open'); jQuery(this).siblings().children('.sub-menu').removeClass('open'); } else if (subMenu.length > 0 && subMenu.hasClass('open')){ //event.preventDefault(); subMenu.removeClass('open'); jQuery(this).removeClass('open'); } }); jQuery('.utility-nav').children('.menu-item-has-children').children('a').click(function(e){ if(!jQuery(this).parent().hasClass('open')) { e.preventDefault(); jQuery(this).parent().addClass('open'); jQuery(this).parent().siblings().removeClass('open'); var subMenu = jQuery(this).parent().children('.sub-menu'); if(!subMenu.hasClass('open')) { jQuery(this).addClass('open'); subMenu.addClass('open'); jQuery(this).siblings().children('.sub-menu').removeClass('open'); } } /*jQuery(this).addClass('open'); jQuery(this).siblings().removeClass('open'); var subMenu = jQuery(this).children('.sub-menu'); if(!subMenu.hasClass('open')) { jQuery(this).addClass('open'); subMenu.addClass('open'); jQuery(this).siblings().children('.sub-menu').removeClass('open'); } else { return; }*/ }); } if(isMd) { setUpSubMenuHover(); } else { setUpSubMenuClick(); } // Mobile Navigation function setUpMobileNav() { var menuButton = jQuery('.header-mobile-menu-button'); menuButton.click(function(){ if(!jQuery(this).hasClass('menu-open')) { jQuery(this).addClass('menu-open'); jQuery('.main-mobile-navigations').addClass('menu-open'); jQuery('body').css('position', 'fixed'); jQuery('body').css('top', '0'); jQuery('body').css('right', '0'); jQuery('body').css('left', '0'); jQuery('body').css('width', '100%'); } else { jQuery(this).removeClass('menu-open'); jQuery('.main-mobile-navigations').removeClass('menu-open'); jQuery('body').css('position', 'relative'); } }); jQuery('.header-utility-nav-button').click(function(){ if(!jQuery(this).hasClass('open')) { jQuery(this).addClass('open'); jQuery('.header-utility-navigation').addClass('open'); } else { jQuery(this).removeClass('open'); jQuery('.header-utility-navigation').removeClass('open'); } }); } setUpMobileNav(); // Animate Navigation var header = jQuery('header'); function setUpStickyNav () { jQuery(window).scroll(function() { if (jQuery(this).scrollTop() > 50){ jQuery('header').addClass("sticky"); } else{ jQuery('header').removeClass("sticky"); } }); } setUpStickyNav(); var utilityNav = jQuery('.header-utility-navigation'); function hoverUtilityMenu() { utilityNav.mouseenter(function(){ if(header.hasClass('sticky') && !utilityNav.hasClass('expanded')) { utilityNav.addClass('expanded'); header.addClass('utility-expanded'); } }); utilityNav.mouseleave(function(){ if(header.hasClass('sticky') && utilityNav.hasClass('expanded')) { utilityNav.removeClass('expanded'); header.removeClass('utility-expanded'); } }); } hoverUtilityMenu(); function showCurrentPage() { if (window.location.href.indexOf("places-to-go") > -1) { jQuery('.places-to-go').parent().addClass('current'); } if (window.location.href.indexOf("things-to-do") > -1) { jQuery('.things-to-do').parent().addClass('current'); } if (window.location.href.indexOf("make-a-difference") > -1) { jQuery('.make-a-difference').parent().addClass('current'); } if (window.location.href.indexOf("rentals-permits") > -1) { jQuery('.rentals-permits').parent().addClass('current'); } if (window.location.href.indexOf("what-we-do") > -1) { jQuery('.what-we-do').parent().addClass('current'); } var pageSlug = jQuery('.site-content').attr('data-page-slug'); if(pageSlug.length > 0) { jQuery('.sub-menu li a').each(function(){ if(jQuery(this).attr('data-slug') === pageSlug){ jQuery(this).addClass('current'); } }); if(isMobile) { jQuery('.submenu-category-list > li[data-id]').each(function(){ var postID = jQuery(this).attr('data-id'); var link = jQuery(this).children('a'); if(!jQuery('body').hasClass(postID)) { link.removeClass('current'); } }); } else { jQuery('.submenu-category-list > li[data-page-id]').each(function(){ var postID = jQuery(this).attr('data-page-id'); var link = jQuery(this).children('a'); if(!jQuery('body').hasClass(postID)) { link.removeClass('current'); } }); } } } showCurrentPage() ; }
mit
rainliu/sip
header/RouteList.go
1142
package header import "sip/core" /** * A list of Route Headers. */ type RouteList struct { SIPHeaderList //private HashSet routeSet; } /** default constructor */ func NewRouteList() *RouteList { this := &RouteList{} this.SIPHeaderList.super(core.SIPHeaderNames_ROUTE) //this.routeSet = new HashSet(); return this } // public boolean add(Object rh) { // if (! routeSet.contains(rh) ) { // this.routeSet.add(rh); // return super.add(rh); // } else return false; // } /** Constructor * @param sip SIPObjectList to set */ // public RouteList (SIPObjectList sip) { // super(sip, RouteHeader.NAME); // } /** * Order is important when comparing route lists. */ // public boolean equals(Object other) { // if (!(other instanceof RouteList)) return false; // RouteList that = (RouteList) other; // if (this.size() != that.size()) return false; // ListIterator it = this.listIterator(); // ListIterator it1 = that.listIterator(); // while (it.hasNext()) { // Route route = (Route) it.next(); // Route route1 = (Route) it1.next(); // if (! route.equals(route1)) return false; // } // return true; // }
mit
iataylor/SWEN-262-Proj01
src/R2/Controller.java
1462
package R2; import R2.Trans.Transaction; public class Controller { private LoginFrame lg; public Controller(){ lg = new LoginFrame(); lg.setVisible(true); } //import //don't know what I need since tyler isn't done yet public void imp(){ } //export //don't know what I need since tyler isn't done yet public void exp(){ } //or save public void update(){ } public void addEquity(String ticker, int numberOfStocks, double pricePerStock){ } public void removeEquity(Equity e){ } public void updateEquity(Equity equity, String ticker, int numberOfStocks, double pricePerStock){ } public void YahooTimer(int timeInterval){ } public void searchEquities(String searchString){ } public void newEquityTransaction(Equity equity, int numberOfStock){ } public void newAccountTransaction(String transType, Account account, double amount){ } public void undoTransaction(Transaction t){ } public void redoTransaction(Transaction t){ } public void addAccount(String name, double balance){ } public void removeAccount(Account a){ } public void updateAccount(String name, double balance){ } public double runSim(String simType, int steps, char stepSize, double pricePerStock, double percentChange){ return 0; } public void resetSim(){ } public static void main(String[] args) { LoginFrame lg = new LoginFrame(); lg.setVisible(true); } }
mit
itdoors/sd
src/ITDoors/ControllingBundle/Entity/InvoiceCompanystructure.php
2931
<?php namespace ITDoors\ControllingBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * InvoiceCompanystructure */ class InvoiceCompanystructure { /** * @var integer */ private $id; /** * @var integer */ private $invoiceId; /** * @var integer */ private $companystructureId; /** * @var \ITDoors\ControllingBundle\Entity\Invoice */ private $invoice; /** * @var \Lists\CompanystructureBundle\Entity\Companystructure */ private $companystructure; /** * Get id * * @return integer */ public function getId () { return $this->id; } /** * Set invoiceId * * @param integer $invoiceId * * @return InvoiceCompanystructure */ public function setInvoiceId ($invoiceId) { $this->invoiceId = $invoiceId; return $this; } /** * Get invoiceId * * @return integer */ public function getInvoiceId () { return $this->invoiceId; } /** * Set companystructureId * * @param integer $companystructureId * * @return InvoiceCompanystructure */ public function setCompanystructureId ($companystructureId) { $this->companystructureId = $companystructureId; return $this; } /** * Get companystructureId * * @return integer */ public function getCompanystructureId () { return $this->companystructureId; } /** * Set invoice * * @param \ITDoors\ControllingBundle\Entity\Invoice $invoice * * @return InvoiceCompanystructure */ public function setInvoice (\ITDoors\ControllingBundle\Entity\Invoice $invoice = null) { $this->invoice = $invoice; return $this; } /** * Get invoice * * @return \ITDoors\ControllingBundle\Entity\Invoice */ public function getInvoice () { return $this->invoice; } /** * Set companystructure * * @param \Lists\CompanystructureBundle\Entity\Companystructure $companystructure * * @return InvoiceCompanystructure */ public function setCompanystructure (\Lists\CompanystructureBundle\Entity\Companystructure $companystructure = null) { $this->companystructure = $companystructure; return $this; } /** * Get companystructure * * @return \Lists\CompanystructureBundle\Entity\Companystructure */ public function getCompanystructure () { return $this->companystructure; } /** * @ORM\PreUpdate */ public function addHistory () { $history = new \ITDoors\HistoryBundle\Entity\History(); $history->setModelName('InvoiceCompanystructyre'); $history->setModelId($this->id); $history->setAction('update'); } }
mit
indriHutabalian/dl-module
test/etl/purchasing/fact-purchasing/basic.js
6883
var helper = require("../../../helper"); // var Manager = require("../../../src/etl/fact-purchasing-etl-manager"); var Manager = require("../../../../src/etl/purchasing/fact-pembelian"); var instanceManager = null; var should = require("should"); var sqlHelper = require("../../../sql-helper"); before("#00. connect db", function (done) { Promise.all([helper, sqlHelper]) .then((result) => { var db = result[0]; var sql = result[1]; db.getDb().then((db) => { instanceManager = new Manager(db, { username: "unit-test" }, sql); done(); }) .catch((e) => { done(e); }) }); }); it("#01. should success when create etl fact-purchasing", function (done) { instanceManager.run() .then((a) => { console.log(a); done(); }) .catch((e) => { console.log(e); done(e); }); }); it("#02. should success when transforming data", function (done) { var data = [ { purchaseOrder: { _deleted: false, _createdDate: new Date(), purchaseOrderExternal: { date: new Date(1970, 1, 1) }, items: [ { fulfillments: [ { deliveryOrderDate: new Date() } ] } ] }, purchaseRequest: { _deleted: false, category: { name: "" }, date: new Date(1970, 1, 1) } }, { purchaseOrder: { _deleted: false, _createdDate: new Date(), purchaseOrderExternal: { date: new Date() }, items: [ { fulfillments: [ { deliveryOrderDate: new Date() } ] } ] }, purchaseRequest: { category: { name: "BAHAN BAKU" }, date: new Date() } }, { _deleted: true, purchaseOrder: { _createdDate: new Date("2017-03-29T16:13:51+07:00"), purchaseOrderExternal: { date: new Date("2017-04-16T16:14:08+07:00") }, items: [ { fulfillments: [ { deliveryOrderDate: new Date("2017-05-29T16:14:08+07:00") } ] } ] }, purchaseRequest: { _deleted: false, category: { name: "BUKAN BAHAN BAKU" }, date: new Date("2017-04-08T16:14:08+07:00") } }, { _deleted: true, purchaseOrder: { _createdDate: new Date("2017-03-29T16:13:51+07:00"), purchaseOrderExternal: { date: new Date("2017-04-16T16:14:08+07:00") }, items: [ { fulfillments: [ { deliveryOrderDate: new Date("2017-06-29T16:14:08+07:00") } ] } ] }, purchaseRequest: { _deleted: false, category: { name: "BUKAN BAHAN BAKU" }, date: new Date("2017-04-08T16:14:08+07:00") } }, { _deleted: true, purchaseOrder: { _createdDate: new Date("2017-03-29T16:13:51+07:00"), purchaseOrderExternal: { date: new Date("2017-04-16T16:14:08+07:00") }, items: [ { fulfillments: [ ] } ] }, purchaseRequest: { _deleted: false, category: { name: "BUKAN BAHAN BAKU" }, date: new Date("2017-04-08T16:14:08+07:00") } }, { purchaseOrder: null, purchaseRequest: { _deleted: false, category: { name: "BUKAN BAHAN BAKU" }, date: new Date("2017-04-08T16:14:08+07:00"), items: [ ] } } ]; instanceManager.transform(data) .then(() => { done(); }) .catch((e) => { done(e); }); }); it("#03. should success when extracting PR from PO", function (done) { var data = [ { purchaseRequest: {} } ]; instanceManager.getPRFromPO(data) .then(() => { done(); }) .catch((e) => { done(e); }); }); it("#04. should success when joining PR to PO", function (done) { var data = []; instanceManager.joinPurchaseOrder(data) .then(() => { done(); }) .catch((e) => { done(e); }); }); it("#05. should success when remove duplicate data", function (done) { var arr = [{ no: {} }, { no: {} }]; instanceManager.removeDuplicates(arr) .then((a) => { done(); }) .catch((e) => { done(e); }); }); // it("#06. should error when load empty data", function (done) { // instanceManager.load({}) // .then(id => { // done("should error when create with empty data"); // }) // .catch((e) => { // try { // done(); // } // catch (ex) { // done(ex); // } // }); // }); it("#07. should error when insert empty data", function (done) { instanceManager.insertQuery(this.sql, "") .then((id) => { done("should error when create with empty data"); }) .catch((e) => { try { done(); } catch (ex) { done(ex); } }); });
mit
maovt/p3_api
media/cufflinks+gff.js
2870
var debug = require("debug")("p3api-server:media/cufflinks+gff"); var when = require("promised-io/promise").when; var es = require("event-stream"); // var wrap = require("../util/linewrap"); function serializeRow(type, o){ var row = []; if(o.feature_type == "source"){ o.feature_type = "region" } if(o.feature_type == "misc_RNA"){ o.feature_type = "transcript" } if(o.feature_type == "CDS"){ o.feature_type = "gene" } if(o.feature_type == "region"){ row.push("##sequence-region\taccn|" + o.accession + "\t" + o.start + "\t" + o.end + "\n"); return; } row.push(o.accession + "\t" + o.annotation + "\t" + o.feature_type + "\t" + o.start + "\t" + o.end + "\t.\t" + o.strand + "\t0\t"); switch(o.annotation){ case "PATRIC": row.push("ID=" + o.patric_id); row.push(";name=" + o.patric_id); break; case "RefSeq": row.push("ID=" + o.refseq_locus_tag); row.push(";name=" + o.refseq_locus_tag); break; } if(o.refseq_locus_tag){ row.push(";locus_tag=" + o.refseq_locus_tag); } if(o.product){ row.push(";product=" + o.product); } if(o.go){ row.push(";Ontology_term=" + o.go); } if(o.ec){ row.push(";ec_number=" + o.ec.join("|")); } return row.join("") + "\n"; } module.exports = { contentType: "application/cufflinks+gff", serialize: function(req, res, next){ debug("application/cufflinks+gff"); if(req.isDownload){ res.attachment('PATRIC_' + req.call_collection + '.fasta'); // res.set("content-disposition", "attachment; filename=patric_genomes.fasta"); } if(req.call_method == "stream"){ when(res.results, function(results){ debug("res.results: ", results); var docCount = 0; var head; if(!results.stream){ throw Error("Expected ReadStream in Serializer") } results.stream.pipe(es.mapSync(function(data){ if(!head){ head = data; }else{ // debug(JSON.stringify(data)); if(docCount < 1){ res.write("##gff-version 3\n"); res.write("#Genome: " + data.genome_id + "\t" + data.genome_name); if(data.product){ res.write(" " + data.product); } } res.write(serializeRow(req.call_collection, data)); docCount++; } })).on('end', function(){ debug("Exported " + docCount + " Documents"); res.end(); }) }); }else{ if(res.results && res.results.response && res.results.response.docs && res.results.response.docs.length > 0){ res.write("##gff-version 3\n"); res.write("#Genome: " + res.results.response.docs[0].genome_id + "\t" + res.results.response.docs[0].genome_name); if(res.results.response.docs[0].product){ res.write(" " + res.results.response.docs[0].product); } res.write("\n"); res.results.response.docs.forEach(function(o){ res.write(serializeRow(req.call_collection, o)); }); } res.end(); } } };
mit
imnotjames/syndicator
tests/ArticleTest.php
793
<?php class ArticleTest extends PHPUnit_Framework_TestCase { public function testCreateArticle() { $expectTitle = 'Title'; $expectDescription = 'Description'; $expectURI = 'http://example.org/example?example=example'; $article = new \imnotjames\Syndicator\Article(); $article->setTitle($expectTitle); $article->setDescription($expectDescription); $article->setURI($expectURI); $this->assertEquals($article->getTitle(), $expectTitle); $this->assertEquals($article->getDescription(), $expectDescription); $this->assertEquals($article->getURI(), $expectURI); } /** * @expectedException \imnotjames\Syndicator\Exceptions\InvalidURIException */ public function testInvalidUri() { $article = new \imnotjames\Syndicator\Article(); $article->setURI('test'); } }
mit
MorganRodgers/Macroinvertebrate-Field-Guide
fix_qt.py
3416
#!/usr/bin/env python import os import subprocess from contextlib import contextmanager @contextmanager def cd(path): cwd = os.getcwd() os.chdir(path) yield os.chdir(cwd) def check_output(cmd_list): process = subprocess.Popen( cmd_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) result = process.communicate()[0] if process.returncode != 0: raise Exception('`%s` failed to complete cleanly.\n\t%s' % (' '.join(cmd_list), result)) return result def main(): qt_dir = '/Users/%s/Qt/5.7' % os.getenv('USER') os.chdir(qt_dir) platforms = [ 'android_armv7', 'android_x86', 'clang_64', 'ios' ] # Must escape this string due the the number of regex meta characters original_xcrun_line = '(isEmpty.{3}list.{3}system.+find.)xcrun' replacement_xcrun_line = '$1xcodebuild' original_sdk_version = '(lessThan.QMAKE_MAC_SDK_VERSION, ")8.0' replacement_sdk_version = '${1}10.0' original_file = 'default_pre.prf' backup_file = original_file + '.bak' sdk_file = 'sdk.prf' sdk_file_bak = sdk_file + '.bak' for platform in platforms: default_pre_path = '%s/mkspecs/features/mac/' % platform with cd(default_pre_path): backup_exists = backup_file in os.listdir('.') if not backup_exists: print('Backing up %s to %s' % (original_file, backup_file)) check_output([ 'cp', original_file, backup_file ]) else: print('Using backup %s as %s' % (backup_file, original_file)) check_output([ 'cp', backup_file, original_file ]) cmd = [ 'perl', '-pi', '-e', 's#%s#%s#g' % (original_xcrun_line, replacement_xcrun_line), original_file ] print('Running: %s' % ' '.join(cmd)) check_output(cmd) if platform == 'ios': with cd('ios/mkspecs/macx-ios-clang/features'): print(os.getcwd()) print(os.listdir('.')) sdk_backup_exists = sdk_file_bak in os.listdir('.') if not sdk_backup_exists: print('Backing up %s to %s' % (sdk_file, sdk_file_bak)) check_output([ 'cp', sdk_file, sdk_file_bak ]) else: print('Using backup %s as %s' % (sdk_file_bak, sdk_file)) check_output([ 'cp', sdk_file_bak, sdk_file ]) cmd = [ 'perl', '-pi', '-e', 's#%s#%s#g' % (original_sdk_version, replacement_sdk_version), sdk_file ] print('Upgrading iOS SDK version') print(' '.join(cmd)) check_output(cmd) print(check_output([ 'cat', 'sdk.prf' ])) if __name__ == '__main__': main()
mit
briancappello/flask-react-spa
tests/security/views/test_check_auth_token.py
312
from flask import url_for def test_check_auth_token(api_client, user): r = api_client.get(url_for('api.check_auth_token'), headers={'Authentication-Token': user.get_auth_token()}) assert r.status_code == 200 assert 'user' in r.json assert r.json['user']['id'] == user.id
mit
civinomics/city-council
cloud/functions/tests.ts
1116
/* const app = initializeAdminApp(); const database = app.database(); */ /*getFollowersWithEmailAddresses('group', 'id_acc', database).then(it => { console.log(it); })*/ /*computeMeetingStats('id_meeting_511').then(it => { fs.writeFileSync('dev-stats2.json', JSON.stringify(it)); console.log('done'); });*/ /* getOrComputeMeetingStats('-KjZWYD7GevirhrxSmF2').then(it => { fs.writeFileSync('dev-stats2.json', JSON.stringify(it)); console.log('done'); }); */ /* doImport( { //this will ultimately be persisted and loaded for the relavant group groupId: 'id_acc', adminId: 'id_doug', canEditIds: [ 'id_doug' ], restEndpoint: { host: 'data.austintexas.gov', path: '/resource/es7e-878h.json', method: 'GET' }, pullMeetingTypes: [ 'Austin City Council' ], meetingTypeDisplayNames: { 'Austin City Council': 'Regular Meeting of the Austin City Council' }, closeFeedback: 1440, //number of minutes before meeting to close feedback (1440 = 24 * 60) meetingLength: 120, //number of minutes after start that meeting ends timeZone: '+06:00' }).then(()=> { console.log('success'); }); */
mit
dinhvan5481/ee382v-adv-algorithms-vehicle-routing-problem
src/vhr/SolutionAcceptor/ISolutionAcceptor.java
237
package vhr.SolutionAcceptor; /** * Created by quachv on 4/4/2017. */ public interface ISolutionAcceptor { boolean acceptSolution(double prevCost, double newCost); void updateAcceptor(); boolean canTerminateSearching(); }
mit
bcvsolutions/CzechIdMng
Realization/backend/core/core-impl/src/main/java/eu/bcvsolutions/idm/core/eav/service/impl/DefaultIdentityProjectionManager.java
23655
package eu.bcvsolutions.idm.core.eav.service.impl; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import eu.bcvsolutions.idm.core.api.domain.ConceptRoleRequestOperation; import eu.bcvsolutions.idm.core.api.domain.ConfigurationMap; import eu.bcvsolutions.idm.core.api.domain.IdentityState; import eu.bcvsolutions.idm.core.api.domain.RoleRequestState; import eu.bcvsolutions.idm.core.api.domain.RoleRequestedByType; import eu.bcvsolutions.idm.core.api.dto.IdmConceptRoleRequestDto; import eu.bcvsolutions.idm.core.api.dto.IdmContractPositionDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityContractDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto; import eu.bcvsolutions.idm.core.api.dto.IdmRoleRequestDto; import eu.bcvsolutions.idm.core.api.dto.filter.FormableFilter; import eu.bcvsolutions.idm.core.api.dto.filter.IdmContractPositionFilter; import eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityContractFilter; import eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityFilter; import eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityRoleFilter; import eu.bcvsolutions.idm.core.api.dto.projection.IdmIdentityProjectionDto; import eu.bcvsolutions.idm.core.api.event.EntityEvent; import eu.bcvsolutions.idm.core.api.event.EventContext; import eu.bcvsolutions.idm.core.api.exception.EntityNotFoundException; import eu.bcvsolutions.idm.core.api.exception.ForbiddenEntityException; import eu.bcvsolutions.idm.core.api.service.AutomaticRoleManager; import eu.bcvsolutions.idm.core.api.service.EntityEventManager; import eu.bcvsolutions.idm.core.api.service.IdmConceptRoleRequestService; import eu.bcvsolutions.idm.core.api.service.IdmContractPositionService; import eu.bcvsolutions.idm.core.api.service.IdmIdentityContractService; import eu.bcvsolutions.idm.core.api.service.IdmIdentityRoleService; import eu.bcvsolutions.idm.core.api.service.IdmIdentityService; import eu.bcvsolutions.idm.core.api.service.IdmRoleRequestService; import eu.bcvsolutions.idm.core.api.service.LookupService; import eu.bcvsolutions.idm.core.eav.api.dto.FormDefinitionAttributes; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormProjectionDto; import eu.bcvsolutions.idm.core.eav.api.service.FormProjectionManager; import eu.bcvsolutions.idm.core.eav.api.service.IdentityProjectionManager; import eu.bcvsolutions.idm.core.model.entity.IdmIdentity_; import eu.bcvsolutions.idm.core.model.event.ContractPositionEvent; import eu.bcvsolutions.idm.core.model.event.ContractPositionEvent.ContractPositionEventType; import eu.bcvsolutions.idm.core.model.event.IdentityContractEvent; import eu.bcvsolutions.idm.core.model.event.IdentityContractEvent.IdentityContractEventType; import eu.bcvsolutions.idm.core.model.event.IdentityEvent; import eu.bcvsolutions.idm.core.model.event.IdentityEvent.IdentityEventType; import eu.bcvsolutions.idm.core.model.event.RoleRequestEvent; import eu.bcvsolutions.idm.core.model.event.RoleRequestEvent.RoleRequestEventType; import eu.bcvsolutions.idm.core.security.api.domain.BasePermission; import eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission; import eu.bcvsolutions.idm.core.security.api.utils.PermissionUtils; /** * Identity projection - get / save. * * @author Radek Tomiška * @since 10.2.0 * @see FormProjectionManager */ public class DefaultIdentityProjectionManager implements IdentityProjectionManager { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DefaultIdentityProjectionManager.class); // @Autowired private IdmIdentityService identityService; @Autowired private IdmIdentityContractService contractService; @Autowired private IdmContractPositionService contractPositionService; @Autowired private IdmRoleRequestService roleRequestService; @Autowired private IdmConceptRoleRequestService conceptRoleRequestService; @Autowired private IdmIdentityRoleService identityRoleService; @Autowired private LookupService lookupService; @Autowired private EntityEventManager entityEventManager; @Autowired private ObjectMapper mapper; @Override public IdmIdentityProjectionDto get(Serializable codeableIdentifier, BasePermission... permission) { LOG.trace("Load identity projection [{}]", codeableIdentifier); IdmIdentityDto identity = getIdentity(codeableIdentifier, permission); IdmIdentityProjectionDto dto = new IdmIdentityProjectionDto(identity); // contracts List<IdmIdentityContractDto> contracts = getContracts(dto, permission); if (!contracts.isEmpty()) { IdmIdentityContractDto contract = contracts.get(0); // prime contract dto.setContract(contract); contracts.removeIf(c -> Objects.equals(c, contract)); // other contracts dto.setOtherContracts(contracts); } // other positions dto.setOtherPositions(getOtherPositions(dto, permission)); // assigned roles dto.setIdentityRoles(getIdentityRoles(dto, permission)); // LOG.trace("Loaded identity projection [{}]", codeableIdentifier); return dto; } @Override @Transactional public EventContext<IdmIdentityProjectionDto> publish(EntityEvent<IdmIdentityProjectionDto> event, BasePermission... permission) { return publish(event, (EntityEvent<?>) null, permission); } @Override @Transactional public EventContext<IdmIdentityProjectionDto> publish( EntityEvent<IdmIdentityProjectionDto> event, EntityEvent<?> parentEvent, BasePermission... permission) { Assert.notNull(event, "Event must be not null!"); IdmIdentityProjectionDto dto = event.getContent(); Assert.notNull(dto, "Content (dto) in event must be not null!"); // check permissions - check access to filled form values event.setPermission(permission); // load previous projection IdmIdentityDto identity = dto.getIdentity(); if (!identityService.isNew(identity)) { event.setOriginalSource( get(identity.getId(), PermissionUtils.isEmpty(permission) ? null : IdmBasePermission.UPDATE) // UPDATE permission ); } // return entityEventManager.process(event, parentEvent); } @Override @Transactional public IdmIdentityProjectionDto saveInternal(EntityEvent<IdmIdentityProjectionDto> event, BasePermission... permission) { Assert.notNull(event, "Event is required."); IdmIdentityProjectionDto dto = event.getContent(); Assert.notNull(dto, "DTO is required."); // identity IdmIdentityDto identity = saveIdentity(event, permission); dto.setIdentity(identity); event.setContent(dto); // prime contract - will be saved all time dto.setContract(saveContract(event, permission)); event.setContent(dto); // other contracts dto.setOtherContracts(saveOtherContracts(event, permission)); event.setContent(dto); // other positions dto.setOtherPositions(saveOtherPositions(event, permission)); event.setContent(dto); // assigned roles - new identity only saveIdentityRoles(event, permission); // return event.getContent(); } protected IdmIdentityDto saveIdentity(EntityEvent<IdmIdentityProjectionDto> event, BasePermission... permission) { IdentityEventType eventType = IdentityEventType.CREATE; IdmIdentityProjectionDto dto = event.getContent(); IdmIdentityDto identity = dto.getIdentity(); IdmIdentityProjectionDto previousProjection = event.getOriginalSource(); // if (previousProjection != null) { eventType = IdentityEventType.UPDATE; identity.setState(previousProjection.getIdentity().getState()); } else { identity.setState(IdentityState.CREATED); } // EntityEvent<IdmIdentityDto> identityEvent = new IdentityEvent(eventType, identity); // disable default contract creation identityEvent.getProperties().put(IdmIdentityContractService.SKIP_CREATION_OF_DEFAULT_POSITION, Boolean.TRUE); // if contract is saved with identity => automatic roles for identity has to be skipped, // will be recount with contract together // check contract has to be saved IdmIdentityContractDto contract = dto.getContract(); if (contract != null ) { if (identity.getFormProjection() == null) { LOG.debug("Automatic roles will be recount with contract together. Projection s not defined."); // identityEvent.getProperties().put(AutomaticRoleManager.SKIP_RECALCULATION, Boolean.TRUE); } else { IdmFormProjectionDto formProjection = lookupService.lookupEmbeddedDto(dto.getIdentity(), IdmIdentity_.formProjection); if (formProjection.getProperties().getBooleanValue(IdentityFormProjectionRoute.PARAMETER_ALL_CONTRACTS) || formProjection.getProperties().getBooleanValue(IdentityFormProjectionRoute.PARAMETER_PRIME_CONTRACT)) { LOG.debug("Automatic roles will be recount with contract together. Projection [{}] saves contracts.", formProjection.getCode()); // identityEvent.getProperties().put(AutomaticRoleManager.SKIP_RECALCULATION, Boolean.TRUE); } } } // publish return identityService.publish(identityEvent, event, permission).getContent(); } /** * Save the first ~ prime contract. * * @param event * @param permission * @return */ protected IdmIdentityContractDto saveContract(EntityEvent<IdmIdentityProjectionDto> event, BasePermission... permission) { IdmIdentityProjectionDto dto = event.getContent(); IdmIdentityDto identity = dto.getIdentity(); // IdmIdentityContractDto contract = dto.getContract(); if (contract == null) { // prime contract was not sent => not save, but is needed in other processing List<IdmIdentityContractDto> contracts = getContracts(dto, PermissionUtils.isEmpty(permission) ? null : IdmBasePermission.READ); if (contracts.isEmpty()) { return null; } return contracts.get(0); // ~ prime contract } // // check contract has to be saved if (identity.getFormProjection() != null) { IdmFormProjectionDto formProjection = lookupService.lookupEmbeddedDto(dto.getIdentity(), IdmIdentity_.formProjection); if (!formProjection.getProperties().getBooleanValue(IdentityFormProjectionRoute.PARAMETER_ALL_CONTRACTS) && !formProjection.getProperties().getBooleanValue(IdentityFormProjectionRoute.PARAMETER_PRIME_CONTRACT)) { LOG.debug("Projection [{}] doesn't save prime contract.", formProjection.getCode()); return contract; } } contract.setIdentity(identity.getId()); IdentityContractEventType contractEventType = IdentityContractEventType.CREATE; if (!contractService.isNew(contract)) { contractEventType = IdentityContractEventType.UPDATE; } EntityEvent<IdmIdentityContractDto> contractEvent = new IdentityContractEvent(contractEventType, contract); // return contractService.publish(contractEvent, event, permission).getContent(); } protected List<IdmIdentityContractDto> saveOtherContracts(EntityEvent<IdmIdentityProjectionDto> event, BasePermission... permission) { IdmIdentityProjectionDto dto = event.getContent(); IdmIdentityProjectionDto previousProjection = event.getOriginalSource(); List<IdmIdentityContractDto> savedContracts = new ArrayList<>(dto.getOtherContracts().size()); // // check all contracts has to be saved IdmIdentityDto identity = dto.getIdentity(); if (identity.getFormProjection() != null) { IdmFormProjectionDto formProjection = lookupService.lookupEmbeddedDto(dto.getIdentity(), IdmIdentity_.formProjection); if (!formProjection.getProperties().getBooleanValue(IdentityFormProjectionRoute.PARAMETER_ALL_CONTRACTS)) { LOG.debug("Projection [{}] doesn't save other contracts.", formProjection.getCode()); return savedContracts; } } // for (IdmIdentityContractDto contract : dto.getOtherContracts()) { IdentityContractEventType contractEventType = IdentityContractEventType.CREATE; if (!contractService.isNew(contract)) { contractEventType = IdentityContractEventType.UPDATE; // TODO: validation - identity cannot be changed } else { contract.setIdentity(dto.getIdentity().getId()); } IdentityContractEvent otherContractEvent = new IdentityContractEvent(contractEventType, contract); // savedContracts.add(contractService.publish(otherContractEvent, event, permission).getContent()); if (previousProjection != null) { previousProjection.getOtherContracts().removeIf(c -> { return Objects.equals(c.getId(), contract.getId()); }); } } // remove not sent contracts, if previous exists if (previousProjection != null) { boolean primeContractChanged = false; // for (IdmIdentityContractDto contract : previousProjection.getOtherContracts()) { if (Objects.equals(dto.getContract(), contract)) { // new prime contract is saved all time primeContractChanged = true; continue; } // deleteContract(event, contract, permission); } // delete previous prime contract, if order of contracts changed if (primeContractChanged && !savedContracts.contains(previousProjection.getContract())) { deleteContract(event, previousProjection.getContract(), permission); } } // return savedContracts; } protected List<IdmContractPositionDto> saveOtherPositions( EntityEvent<IdmIdentityProjectionDto> event, BasePermission... permission) { IdmIdentityProjectionDto dto = event.getContent(); IdmIdentityProjectionDto previousProjection = event.getOriginalSource(); List<IdmContractPositionDto> savedPositions = new ArrayList<>(dto.getOtherPositions().size()); IdmIdentityContractDto contract = dto.getContract(); // // check other contract position has to be saved IdmIdentityDto identity = dto.getIdentity(); if (identity.getFormProjection() != null) { IdmFormProjectionDto formProjection = lookupService.lookupEmbeddedDto(dto.getIdentity(), IdmIdentity_.formProjection); if (!formProjection.getProperties().getBooleanValue(IdentityFormProjectionRoute.PARAMETER_OTHER_POSITION)) { LOG.debug("Projection [{}] doesn't save other contract positions.", formProjection.getCode()); return savedPositions; } } // for (IdmContractPositionDto otherPosition : dto.getOtherPositions()) { if (otherPosition.getIdentityContract() == null) { if (contract == null) { throw new ForbiddenEntityException("contract", IdmBasePermission.READ); } otherPosition.setIdentityContract(contract.getId()); } ContractPositionEventType positionEventType = ContractPositionEventType.CREATE; if (!contractPositionService.isNew(otherPosition)) { positionEventType = ContractPositionEventType.UPDATE; } ContractPositionEvent positionEvent = new ContractPositionEvent(positionEventType, otherPosition); // savedPositions.add(contractPositionService.publish(positionEvent, event, permission).getContent()); if (previousProjection != null) { previousProjection.getOtherPositions().removeIf(p -> { return Objects.equals(p.getId(), otherPosition.getId()); }); } } // remove not sent positions, if previous exists if (previousProjection != null) { for (IdmContractPositionDto contractPosition : previousProjection.getOtherPositions()) { ContractPositionEventType positionEventType = ContractPositionEventType.DELETE; ContractPositionEvent positionEvent = new ContractPositionEvent(positionEventType, contractPosition); // contractPositionService.publish( positionEvent, event, PermissionUtils.isEmpty(permission) ? null : IdmBasePermission.DELETE ); } } // return savedPositions; } protected void saveIdentityRoles(EntityEvent<IdmIdentityProjectionDto> event, BasePermission... permission) { IdmIdentityProjectionDto dto = event.getContent(); IdmIdentityProjectionDto previousProjection = event.getOriginalSource(); IdmIdentityContractDto contract = dto.getContract(); IdmIdentityDto identity = dto.getIdentity(); // if (previousProjection == null) { List<IdmConceptRoleRequestDto> concepts = new ArrayList<>(dto.getIdentityRoles().size()); // for (IdmIdentityRoleDto assignedRole : dto.getIdentityRoles()) { // create new identity role IdmConceptRoleRequestDto concept = new IdmConceptRoleRequestDto(); if (assignedRole.getIdentityContract() != null) { concept.setIdentityContract(assignedRole.getIdentityContract()); } else if (contract != null) { concept.setIdentityContract(contract.getId()); } else { throw new ForbiddenEntityException("contract", IdmBasePermission.READ); } concept.setRole(assignedRole.getRole()); concept.setOperation(ConceptRoleRequestOperation.ADD); concept.setValidFrom(assignedRole.getValidFrom()); concept.setValidTill(assignedRole.getValidTill()); concept.setEavs(assignedRole.getEavs()); // concepts.add(concept); } if (!concepts.isEmpty()) { IdmRoleRequestDto roleRequest = new IdmRoleRequestDto(); roleRequest.setState(RoleRequestState.CONCEPT); roleRequest.setExecuteImmediately(false); roleRequest.setApplicant(identity.getId()); roleRequest.setRequestedByType(RoleRequestedByType.MANUALLY); roleRequest = roleRequestService.save(roleRequest); // for (IdmConceptRoleRequestDto concept : concepts) { concept.setRoleRequest(roleRequest.getId()); // conceptRoleRequestService.save(concept); } // // start event with skip check authorities RoleRequestEvent requestEvent = new RoleRequestEvent(RoleRequestEventType.EXCECUTE, roleRequest); requestEvent.getProperties().put(IdmIdentityRoleService.SKIP_CHECK_AUTHORITIES, Boolean.TRUE); requestEvent.setPriority(event.getPriority()); // frontend requestEvent.setParentId(event.getId()); // prevent to start asynchronous event before previous update event is completed. requestEvent.setSuperOwnerId(identity.getId()); // roleRequestService.startRequestInternal(requestEvent); } } } /** * Load identity. * * @param codeableIdentifier uuid or username * @param permission * @return */ protected IdmIdentityDto getIdentity(Serializable codeableIdentifier, BasePermission... permission) { // codeable decorator IdmIdentityDto identity = lookupService.lookupDto(IdmIdentityDto.class, codeableIdentifier); if (identity == null) { throw new EntityNotFoundException(identityService.getEntityClass(), codeableIdentifier); } // IdmIdentityFilter context = new IdmIdentityFilter(); context.setAddPermissions(true); context.setAddBasicFields(true); // load (~filter) specified form definitions and attributes only setAddEavMetadata(context, identity); // evaluate access / load eavs identity = identityService.get(identity, context, permission); // return identity; } /** * Load others than prime contract. * * @param dto * @param permission * @return */ protected List<IdmIdentityContractDto> getContracts(IdmIdentityProjectionDto dto, BasePermission... permission) { IdmIdentityDto identity = dto.getIdentity(); IdmIdentityContractFilter contractFilter = new IdmIdentityContractFilter(); contractFilter.setAddPermissions(true); contractFilter.setAddBasicFields(true); contractFilter.setAddControlledBySlices(true); contractFilter.setIdentity(identity.getId()); setAddEavMetadata(contractFilter, identity); // eav attributes are secured automatically on this form (without configuration is needed) List<IdmIdentityContractDto> contracts = Lists.newArrayList(contractService .find(contractFilter, null, permission) .getContent()); // // sort -> prime first contractService.sortByPrimeContract(contracts); // return contracts; } /** * Load other positions. * * @param dto * @param permission * @return */ protected List<IdmContractPositionDto> getOtherPositions(IdmIdentityProjectionDto dto, BasePermission... permission) { IdmContractPositionFilter positionFilter = new IdmContractPositionFilter(); positionFilter.setIdentity(dto.getIdentity().getId()); positionFilter.setAddPermissions(true); // return Lists.newArrayList(contractPositionService.find(positionFilter, null, permission).getContent()); } /** * Load assigned roles. * * @param dto * @param permission * @return */ protected List<IdmIdentityRoleDto> getIdentityRoles(IdmIdentityProjectionDto dto, BasePermission... permission) { // check all assigned roles has to be loaded IdmIdentityDto identity = dto.getIdentity(); if (identity.getFormProjection() != null) { IdmFormProjectionDto formProjection = lookupService.lookupEmbeddedDto(dto.getIdentity(), IdmIdentity_.formProjection); ConfigurationMap properties = formProjection.getProperties(); // if (properties.containsKey(IdentityFormProjectionRoute.PARAMETER_LOAD_ASSIGNED_ROLES) // backward compatible && !properties.getBooleanValue(IdentityFormProjectionRoute.PARAMETER_LOAD_ASSIGNED_ROLES)) { LOG.debug("Projection [{}] does not load all assigned roles.", formProjection.getCode()); // return Lists.newArrayList(); } } // // load all assigned identity roles IdmIdentityRoleFilter filter = new IdmIdentityRoleFilter(); filter.setIdentityId(identity.getId()); // return Lists.newArrayList(identityRoleService.find(filter, null, permission).getContent()); } /** * Load extended attributes, if needed by projection. * * @param context * @param identity */ protected void setAddEavMetadata(FormableFilter context, IdmIdentityDto identity) { if (identity.getFormProjection() == null) { // load all form instances => ~ full form projection as default, when no projection is specified context.setAddEavMetadata(Boolean.TRUE); return; } // IdmFormProjectionDto formProjection = lookupService.lookupEmbeddedDto(identity, IdmIdentity_.formProjection); String formDefinitions = formProjection.getFormDefinitions(); if (StringUtils.isEmpty(formDefinitions)) { // form instances are not needed - not configured in this projection return; } // try { List<FormDefinitionAttributes> attributes = mapper.readValue(formDefinitions, new TypeReference<List<FormDefinitionAttributes>>() {}); if (!attributes.isEmpty()) { context.setFormDefinitionAttributes(attributes); } else { LOG.debug("Extended attribute values is not needed by form projection [{}], will not be loaded."); } } catch (IOException ex) { LOG.warn("Form projection [{}] is wrongly configured. Fix configured form definitions. " + "All eav attributes will be loaded as default.", formProjection.getCode(), ex); context.setAddEavMetadata(Boolean.TRUE); } } private void deleteContract(EntityEvent<IdmIdentityProjectionDto> event, IdmIdentityContractDto contract, BasePermission... permission) { IdentityContractEventType contractEventType = IdentityContractEventType.DELETE; IdentityContractEvent otherContractEvent = new IdentityContractEvent(contractEventType, contract); if (BooleanUtils.isTrue(contract.getControlledBySlices())) { LOG.debug("Contract [{}] is controlled by contract slices, will be ignored in projection.", contract.getId()); return; } // contractService.publish( otherContractEvent, event, PermissionUtils.isEmpty(permission) ? null : IdmBasePermission.DELETE ); } }
mit
legoboy0215/PocketMine-Plugins
PlanB/src/planb/command/PlanBCommand.php
4273
<?php namespace planb\command; use planb\PlanB; use pocketmine\command\Command; use pocketmine\command\CommandSender; use pocketmine\command\ConsoleCommandSender; use pocketmine\command\PluginIdentifiableCommand; class PlanBCommand extends Command implements PluginIdentifiableCommand{ public function __construct(PlanB $plugin){ parent::__construct( "planb", "Shows all the sub-commands for PlanB", "/planb <sub-command> [parameters]", array("pb") ); $this->setPermission("planb.command.planb"); $this->plugin = $plugin; } public function getPlugin(){ return $this->plugin; } private function sendCommandHelp(CommandSender $sender){ $sender->sendMessage("§bPlanB commands:"); $sender->sendMessage("§a/planb addbackup §c- §fAdds a player to backups.txt"); $sender->sendMessage("§a/planb delbackup §c- §fRemoves a player from backups.txt"); $sender->sendMessage("§a/planb help §c- §fShows all the sub-commands for PlanB"); $sender->sendMessage("§a/planb list §c- §fLists all backup players"); $sender->sendMessage("§a/planb restore §c- §fRestores OP status of all online players listed in backup.txt"); } public function execute(CommandSender $sender, $label, array $args){ if(isset($args[0])){ if(strtolower($args[0]) === "addbackup" or strtolower($args[0]) === "ab"){ if(isset($args[1])){ if($sender instanceof ConsoleCommandSender){ if($this->getPlugin()->isBackupPlayer($args[1])){ $sender->sendMessage("§c".$args[1]." already exists in backups.txt."); } else{ $this->getPlugin()->addBackup($args[1]); $sender->sendMessage("§aAdded ".$args[1]." to backups.txt."); } } else{ $sender->sendMessage("§cPlease run this command on the console."); } } else{ $sender->sendMessage("§cPlease specify a valid player."); } return true; } if(strtolower($args[0]) === "delbackup" or strtolower($args[0]) === "db"){ if(isset($args[1])){ if($sender instanceof ConsoleCommandSender){ if($this->getPlugin()->isBackupPlayer($args[1])){ $this->getPlugin()->removeBackup($args[1]); $sender->sendMessage("§aRemoved ".$args[1]." from backups.txt."); } else{ $sender->sendMessage("§c".$args[1]." does not exist in backups.txt."); } } else{ $sender->sendMessage("§cPlease run this command on the console."); } } else{ $sender->sendMessage("§cPlease specify a valid player."); } return true; } if(strtolower($args[0]) === "help"){ $this->sendCommandHelp($sender); return true; } if(strtolower($args[0]) === "list"){ $this->getPlugin()->sendBackups($sender); return true; } if(strtolower($args[0]) === "restore"){ if($this->getPlugin()->isBackupPlayer($sender->getName()) or $sender instanceof ConsoleCommandSender){ $this->getPlugin()->restoreOps(); $sender->sendMessage("§aRestoring the statuses of OPs..."); } else{ $sender->sendMessage("§cYou do not not have permissions to restore OPs."); } return true; } else{ $sender->sendMessage("§cUsage: ".$this->getUsage()); } } else{ $this->sendCommandHelp($sender); } } }
mit
akkirilov/SoftUniProject
07_OOP_Advanced/23_Exam/src/main/java/app/factory/TargetableFactoryImpl.java
999
package app.factory; import java.lang.reflect.InvocationTargetException; import app.contracts.Targetable; import app.contracts.TargetableFactory; import app.models.participants.Boss; import app.models.participants.Necromancer; import app.models.participants.Warrior; import app.models.participants.Wizard; public class TargetableFactoryImpl implements TargetableFactory { @Override public Targetable create(String name, String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { Targetable target = null; switch (className) { case "Warrior": target = new Warrior(); target.setName(name); break; case "Wizard": target = new Wizard(); target.setName(name); break; case "Necromancer": target = new Necromancer(); target.setName(name); break; case "Boss": target = new Boss(); target.setName(name); break; default: break; } return target; } }
mit
Pabloitto/Surviving-elements
Surviving-Elements/painters/enemydrawable.js
383
$.EnemyDrawable = function(e){ var enemy; function init(){ enemy = e; } function draw(ctx){ ctx.drawImage(enemy.sprite.image, enemy.sprite.pos.x, enemy.sprite.pos.y, enemy.width, enemy.height, enemy.x, enemy.y, enemy.width, enemy.height); } init(); return { draw: draw } };
mit
viralsolani/laravel-adminpanel
routes/frontend/home.php
1317
<?php use App\Http\Controllers\Frontend\ContactController; use App\Http\Controllers\Frontend\HomeController; use App\Http\Controllers\Frontend\User\AccountController; use App\Http\Controllers\Frontend\User\DashboardController; use App\Http\Controllers\Frontend\User\ProfileController; /* * Frontend Controllers * All route names are prefixed with 'frontend.'. */ Route::get('/', [HomeController::class, 'index'])->name('index'); Route::get('contact', [ContactController::class, 'index'])->name('contact'); Route::post('contact/send', [ContactController::class, 'send'])->name('contact.send'); /* * These frontend controllers require the user to be logged in * All route names are prefixed with 'frontend.' * These routes can not be hit if the password is expired */ Route::group(['middleware' => ['auth', 'password_expires']], function () { Route::group(['namespace' => 'User', 'as' => 'user.'], function () { // User Dashboard Specific Route::get('dashboard', [DashboardController::class, 'index'])->name('dashboard'); // User Account Specific Route::get('account', [AccountController::class, 'index'])->name('account'); // User Profile Specific Route::patch('profile/update', [ProfileController::class, 'update'])->name('profile.update'); }); });
mit
Write365/WordSalad-Service
application/view/test/testdetails.php
8580
<!-- DataTables JavaScript --> <script src="<?php echo URL; ?>libs/datatables/media/js/jquery.dataTables.min.js"></script> <script src="<?php echo URL; ?>libs/datatables-plugins/integration/bootstrap/3/dataTables.bootstrap.min.js"></script> <script> $(document).ready(function () { $('#datatable-test-details').DataTable({ responsive: true }); }); </script> <div class="col-lg-12"> <div class="col-lg-4 col-md-6"> <div class="panel panel-primary"> <div class="panel-heading"> <div class="row"> <div class="col-xs-2"> <i class="fa fa-bar-chart fa-5x"></i> </div> <div class="col-xs-10 text-right"> <div class="large"><?php echo $resultDetails['TotalTest']; ?></div> <div>Total Post!</div> </div> </div> </div> </div> </div> <div class="col-lg-4 col-md-6"> <div class="panel panel-red"> <div class="panel-heading"> <div class="row"> <div class="col-xs-3"> <i class="fa fa-times fa-5x"></i> </div> <div class="col-xs-9 text-right"> <div class="large"><?php echo $resultDetails['TotalGibberish']; ?></div> <div>Total Fail Post!</div> </div> </div> </div> </div> </div> <div class="col-lg-4 col-md-6"> <div class="panel panel-green"> <div class="panel-heading"> <div class="row"> <div class="col-xs-3"> <i class="fa fa-check fa-5x"></i> </div> <div class="col-xs-9 text-right"> <div class="large"><?php echo $resultDetails['TotalNonGibberish'];?></div> <div>Total Passed Post!</div> </div> </div> </div> </div> </div> </div> <div class="col-lg-6 col-md-6"> <div class="panel panel-yellow"> <div class="panel-heading"> <div class="row"> <div class="col-xs-2"> <i class="fa fa-5x"><strong>#</strong></i> </div> <div class="col-xs-10 text-right"> <div class="large"><?php echo number_format($resultTest['threshold'], 6, '.', ''); ?></div> <div>Current Threshold!</div> </div> </div> </div> </div> </div> <div class="col-lg-6 col-md-6"> <div class="panel panel-default"> <div class="panel-heading"> <div class="row"> <div class="col-xs-3"> <i class="fa fa-5x"><strong>%</strong></i> </div> <div class="col-xs-9 text-right"> <div class="large"><?php echo $resultTest['percentage']; ?></div> <div>Current Word Percentage!</div> </div> </div> </div> </div> </div> <div class="col-lg-12"> <table class="table" id="datatable-test-details"> <thead> <tr> <th>Id</th> <th>Is Gibberish</th> <th>Score</th> <th>Word Percentage</th> <th>Unique Words</th> <th>Total Words</th> <th>Unique English Words</th> <th>Total English Words</th> <th>Text</th> </tr> </thead> <tbody> <?php $count = 0; foreach ($resultScores as $score) { ?> <tr> <td><?php if (isset($score->id)) { echo htmlspecialchars($score->id, ENT_QUOTES, 'UTF-8'); } ?></td> <td><?php if(isset($score->is_gibberish)) { if ($score->is_gibberish == FALSE) { echo '<div class="alert alert-success"><p>' . $score->is_gibberish . 'Post Passed</p></div>'; } elseif ($score->is_gibberish == TRUE) { echo '<div class="alert alert-warning"><p>' . $score->is_gibberish . 'Post Failed</p></div>'; } } ?></td> <td><?php if (isset($score->gibberish_score)) { if ($score->gibberish_score < $resultTest['threshold']) { echo '<div class="alert alert-warning"><p>' . htmlspecialchars($score->gibberish_score, ENT_QUOTES, 'UTF-8') . '</p></div>'; } elseif ($resultTest['threshold'] <= $score->gibberish_score) { echo '<div class="alert alert-success"><p>' . htmlspecialchars($score->gibberish_score, ENT_QUOTES, 'UTF-8') . '</p></div>'; } else{ echo '<div class="alert alert-error"><p> Error! </p></div>'; } } ?></td> <td><?php if (isset($score->word_percentage)) { if ($score->word_percentage < $resultTest['percentage']) { echo '<div class="alert alert-warning"><p>' . htmlspecialchars($score->word_percentage, ENT_QUOTES, 'UTF-8') . '</p></div>'; } elseif ($resultTest['percentage'] <= $score->word_percentage) { echo '<div class="alert alert-success"><p>' . htmlspecialchars($score->word_percentage, ENT_QUOTES, 'UTF-8') . '</p></div>'; } else{ echo '<div class="alert alert-error"><p> Error! </p></div>'; } } ?></td> <td><?php if (isset($score->unique_word)) { echo htmlspecialchars($score->unique_word, ENT_QUOTES, 'UTF-8'); } ?></td> <td><?php if (isset($score->total_word)) { echo htmlspecialchars($score->total_word, ENT_QUOTES, 'UTF-8'); } ?></td> <td><?php if (isset($score->unique_english_word)) { echo htmlspecialchars($score->unique_english_word, ENT_QUOTES, 'UTF-8'); } ?></td> <td><?php if (isset($score->total_english_word)) { echo htmlspecialchars($score->total_english_word, ENT_QUOTES, 'UTF-8'); } ?></td> <td> <div class=""> <?php if ($resultTest['is_gibberish']) { if (isset($resultText[$score->gibberish_id]->id)) { echo $resultText[$score->gibberish_id - 1]->body_text; } } elseif ($resultTest['is_control']) { if (isset($resultText[$score->control_id]->id)) { echo $resultText[$score->control_id - 1]->body_text; } } else if ($resultTest['is_live']){ if(isset($resultText[$count]->nid)){ echo $resultText[$count]->body_text; $count++; } } ?> </div> </td> </tr> <?php } ?> </tbody> </table> </div>
mit
Oui42/NewWar
source/admin/item/add.php
4210
<?php if(isset($_POST['addItem'])) { $error = array(); $type = (isset($_POST['type']))? $_POST['type'] : ""; $name = (isset($_POST['name']))? vtxt($_POST['name']) : ""; $level = (isset($_POST['level']))? vtxt($_POST['level']) : ""; $value1 = (isset($_POST['value1']))? vtxt($_POST['value1']) : ""; $value2 = (isset($_POST['value2']))? vtxt($_POST['value2']) : ""; $cost = (isset($_POST['cost']))? $_POST['cost'] : ""; if(empty($name) || empty($level) || empty($value1) || empty($value2) || empty($cost)) { $error[] = "Wypełnij wszystkie pola."; } else { if(empty($type)) $error[] = "Musisz wybrać typ przedmiotu."; if(strlen($name) < 3 || strlen($name) > 32) $error[] = "Nazwa musi mieć minimum 3 i maksimum 32 znaki."; if(strlen($level) > 4 || !is_numeric($level)) $error[] = "Poziom musi być liczbą i może mieć maksymalnie 4 cyfry."; if(strlen($value1) > 8 || !is_numeric($value1)) $error[] = "Wartość 1 musi być liczbą i może mieć maksymalnie 8 cyfr."; if(strlen($value2) > 8 || !is_numeric($value2)) $error[] = "Wartość 2 musi być liczbą i może mieć maksymalnie 8 cyfr."; if(strlen($cost) > 8 || !is_numeric($cost)) $error[] = "Koszt musi być liczbą i może mieć maksymalnie 8 cyfr."; } if(empty($error)) { mysql_query("INSERT INTO `nw_items` (iid, iType, iName, iLevel, iValue1, iValue2, iCost) VALUES('NULL', '".$type."', '".$name."', '".$level."', '".$value1."', '".$value2."', '".$cost."')") or die(mysql_error()); $id = mysql_insert_id(); header("Location: index.php?app=admin&module=item"); } else { echo "<div class='alert alert-danger' role='alert'><i class='fa fa-times-circle' style='font-size: 20;'></i> <b>Błąd!</b> Wystąpiły następujące błędy:<br>"; foreach($error as $e) echo "- ".$e."<br>"; echo "</div>"; } } ?> <form method="post" action="" class="col-md-offset-4 col-md-4"> <div class="form-group"> <label for="type">Typ</label> <select id="type" name="type" class="form-control"> <option disabled selected>Wybierz typ przedmiotu</option> <option value="<?php echo $__ITEM['armor_head']['dbname']; ?>">Pancerz: Głowa</option> <option value="<?php echo $__ITEM['armor_body']['dbname']; ?>">Pancerz: Korpus</option> <option value="<?php echo $__ITEM['armor_hands']['dbname']; ?>">Pancerz: Ręce</option> <option value="<?php echo $__ITEM['armor_legs']['dbname']; ?>">Pancerz: Nogi</option> <option value="<?php echo $__ITEM['weapon_gun']['dbname']; ?>">Broń: Palna</option> <option value="<?php echo $__ITEM['weapon_white']['dbname']; ?>">Broń: Biała</option> <option value="<?php echo $__ITEM['weapon_ammo']['dbname']; ?>">Broń: Amunicja</option> <option value="<?php echo $__ITEM['weapon_thrown']['dbname']; ?>">Broń: Miotana</option> <option value="<?php echo $__ITEM['upgrade_armor']['dbname']; ?>">Ulepszenia: Pancerz</option> <option value="<?php echo $__ITEM['upgrade_weapon']['dbname']; ?>">Ulepszenia: Broń</option> <option value="<?php echo $__ITEM['other_value']['dbname']; ?>">Różności: Kosztowność</option> <option value="<?php echo $__ITEM['other_component']['dbname']; ?>">Różności: Składnik</option> <option value="<?php echo $__ITEM['other_trash']['dbname']; ?>">Różności: Śmieć</option> </select> </div> <div class="form-group"> <label for="name">Nazwa</label> <input id="name" type="text" class="form-control" name="name"> </div> <div class="form-group"> <label for="level">Minimalny poziom</label> <input id="level" type="text" class="form-control" name="level"> </div> <div class="form-group"> <label for="value1">Wartość 1</label> <input id="value1" type="text" class="form-control" name="value1"> </div> <div class="form-group"> <label for="value2">Wartość 2</label> <input id="value2" type="text" class="form-control" name="value2"> </div> <div class="form-group"> <label for="cost">Koszt</label> <input id="cost" type="text" class="form-control" name="cost"> </div> <div class="row"> <div class="text-center"> <button class="btn btn-success" type="submit" name="addItem"> <i class="fa fa-plus"></i> Dodaj przedmiot </button> </div> </div> </form>
mit
codiak/zuul-experiment
src/main/java/zuulserver/ZuulServerApplication.java
659
package org.artstor.test.filter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Controller; @Configuration @ComponentScan @EnableAutoConfiguration @Controller @EnableZuulProxy public class ZuulServerApplication { public static void main(String[] args) { new SpringApplicationBuilder(ZuulServerApplication.class).web(true).run(args); } }
mit
ChrisFadden/PartyTowers
src/main.cpp
23926
#include <iostream> #include <SDL.h> #include <SDL_net.h> #include <SDL_image.h> #include <string> #include <vector> #include <algorithm> #include <MsgStruct.h> #include "Player.h" #include "GameObject.h" #include "Enemy.h" #include "Cursor.h" #include "Tower.h" #include "Cannon.h" #include "Rocket.h" #include "Path.h" #include "Soldier.h" #include "Sound.h" #include "Bullet.h" #include "Text.h" #include "TextureLoader.h" #include <unordered_map> #include "TowerBase.h" using namespace std; int send(string); int send(MsgStruct*, int); int send(string, int); MsgStruct* createMsgStruct(int, bool); void setupMessages(); MsgStruct* newPacket(int); bool canHandleMsg(); MsgStruct* readPacket(); void drawPath(Path*, SDL_Renderer*); Player* getPlayerbyID(string); Tower* getTowerbyPos(int, int); const int SCREEN_WIDTH = 1280; const int SCREEN_HEIGHT = 768; SDLNet_SocketSet socketSet; TCPsocket sock; char buffer[512]; char tempBuffer[512]; int bufferSize; map<int, MsgStruct*> outMsgStructs; map<int, MsgStruct*> inMsgStructs; string roomCode; vector<Tower*> listTower; vector<Enemy*> listEnemy; vector<GameObject*> listFloors; vector<Bullet*> listBullet; unordered_map<int, Player*> listPlayers; Level lvl1(1280, 768); // User IO functions to be called from networking code? Player* getPlayerbyID(int id); void addPlayerbyID(int id, SDL_Renderer* r); void addTower(int id, int type, SDL_Renderer* r); int init(); void gameOver() { drawString("Game Over!!!", 600, 360); } int main() { if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) == -1) { std::cout << "SDL_Init: " << SDLNet_GetError() << "\n"; return -1; } srand (time(NULL)); cout << "SDL2 loaded.\n"; GameSound game_audio; game_audio.PlaySound("./res/BackgroundMusic.wav"); // The window we'll be rendering to SDL_Window* window = NULL; window = SDL_CreateWindow("Party Towers", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (init() == -1) { std::cout << "Quitting\n"; return -1; } std::cout << "SDL_net loaded.\n"; IPaddress ip; if (SDLNet_ResolveHost(&ip, "preston.room409.xyz", atoi("8886")) < 0) { fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } if (!(sock = SDLNet_TCP_Open(&ip))) { fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError()); } socketSet = SDLNet_AllocSocketSet(1); SDLNet_TCP_AddSocket(socketSet, sock); setupMessages(); send("TCP"); bool waiting = true; while (waiting) { if (SDLNet_TCP_Recv(sock, buffer, 512) > 0) { waiting = false; if (string(buffer) == "1") { cout << "Handshake to server made.\n"; } } } send("9990000"); // Create Renderer SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); fontSetRenderer(renderer); SDL_Event e; bool running = true; int k = 0; Uint32 ctime = SDL_GetTicks(); bool confirmed = false; int genWidth = SCREEN_WIDTH / 32; int genHeight = SCREEN_HEIGHT / 32; int baseX = 2 + rand() % (genWidth-4); int baseY = 5 + rand() % (genHeight-10); cout << "(" << baseX << ", " << baseY << ") \n"; int crX = 0; int crY = 0; int success = 0; int want = 4 + (rand() % 3); while (success < want) { crX = rand() % genWidth; crY = rand() % genHeight; int clamp = rand() % 4; if (clamp < 2) { crX = clamp * (genWidth-1); } else { crY = (clamp - 2) * (genHeight-1); } Path* path = new Path(); path->addDest(crX * 32, crY * 32); int kx = 1; int ky = 1; if (crX > baseX) { kx = -1; } if (crY > baseY) { ky = -1; } while (crX != baseX || crY != baseY) { crX += kx * (rand() % ((baseX-crX)+kx)); crY += ky * (rand() % ((baseY-crY)+ky)); path->addDest(crX * 32, crY * 32); } path -> addDest(baseX * 32, baseY * 32); if (path->length() > 10) { success += 1; drawPath(path, renderer); lvl1.addPath(path); } else { delete(path); } } for (auto floor : listFloors) { lvl1.addGameObject(floor); } int wave = 1; TowerBase* baseTower = new TowerBase(wave); baseTower->loadImg(renderer); baseTower->setPosition(pair<int,int>(baseX*32, baseY*32)); pair<int, int> base_pos = baseTower->getPosition(); int enemyRegen = 5 * 60; int enemySpawn = 20 * 60; game_audio.PlaySound("./res/Wilhelm.wav"); int enemyRemain = 20; while (running) { SDL_UpdateWindowSurface(window); while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { running = false; } } int ready = SDLNet_CheckSockets(socketSet, 15); if (ready > 0 && SDLNet_SocketReady(sock)) { int s = SDLNet_TCP_Recv(sock, tempBuffer, 512); for (int i = 0; i < s; i++) { buffer[bufferSize + i] = tempBuffer[i]; } if (s > 1) { bufferSize += s; } cout << "Buffer: " << buffer << "\n"; } if (canHandleMsg()) { MsgStruct* packet = readPacket(); //int pID = packet->getPID(); int msgID = packet->getMsgID(); if (msgID == 999) { confirmed = true; roomCode = packet->read(); cout << "Room code: " + roomCode + "\n"; } else if (msgID == 998) { cout << "New player!\n"; int pID = packet->readInt(); addPlayerbyID(pID, renderer); MsgStruct* p2 = newPacket(5); p2->write(to_string(getPlayerbyID(pID)->getMoney())); send(p2, pID); } else if (msgID == 2) { int pID = packet->readInt(); string dir = packet->read(); // We have pID and dir Player* p = getPlayerbyID(pID); if (dir == "l") { p->moveLeft(); } else if (dir == "r") { p->moveRight(); } else if (dir == "u") { p->moveUp(); } else if (dir == "d") { p->moveDown(); } else { cout << "error, direction: " << dir << "\n"; } } else if (msgID == 3) { int pID = packet->readInt(); MsgStruct* p = newPacket(3); // Can I place a tower here? 1 yes, 0 no Player* player = getPlayerbyID(pID); auto player_pos = player->getPos(); if(lvl1.spotOpen(player_pos.first, player_pos.second)) { p->write("1"); p->write(""); } else { Tower* t = getTowerbyPos(player_pos.first, player_pos.second); if(t != nullptr && player == t->getPlayer()) { if(t->getType() == 0) { //cannon p->write("3"); } else { //rocket p->write("4"); } p->write(to_string(t->getUpgrade())); } else { p->write("0"); p->write(""); } } send(p, pID); } else if (msgID == 4) { int pID = packet->readInt(); int towerType = packet->readInt(); // Attempt to place towerType // here string out = "1"; if (towerType == 1) { if ((getPlayerbyID(pID)->getMoney()) >= 50) { addTower(pID, towerType, renderer); getPlayerbyID(pID)->addMoney(-50); } else { out = "0"; } } else { if ((getPlayerbyID(pID)->getMoney()) >= 100) { addTower(pID, towerType, renderer); getPlayerbyID(pID)->addMoney(-100); } else { out = "0"; } } MsgStruct* p = newPacket(4); // Write success p->write(out); send(p, pID); MsgStruct* p2 = newPacket(5); p2->write(to_string(getPlayerbyID(pID)->getMoney())); send(p2, pID); } else if (msgID == 6) { int pID = packet->readInt(); // Attempt to upgrade tower here // Please Player* player = getPlayerbyID(pID); auto player_pos = player->getPos(); Tower* t = getTowerbyPos(player_pos.first, player_pos.second); MsgStruct* p = newPacket(6); if(t->getPlayer() == player) { int l; //To those who made the Tower hierarchy... //If all of the subclasses have a member (level FOR EXAMPLE!) //But the base class doesn't have it, it tends to lead to code //Like the following. This is not good and I will change it //Sometime soon. Thanks. ~Marcus l = t->level; if (player->getMoney() >= t->getUpgrade()) { player->addMoney(-(t->getUpgrade())); t->setLevel(l+1); p->write("1"); } else { p->write("0"); } } else { p->write("0"); } send(p,pID); MsgStruct* p2 = newPacket(5); p2->write(to_string(player->getMoney())); send(p2, pID); } else if (msgID == 10) { int pID = packet->readInt(); string name = packet->read(); getPlayerbyID(pID)->setName(name); } } k += 1; if (SDL_GetTicks() - ctime > 1000) { k = 0; ctime = SDL_GetTicks(); } if (enemyRemain <= 0) { //Increment wave, refresh counters. std::cout << "Wave " << wave+1 << " incoming.\n"; wave++; enemyRemain = 20; enemySpawn = 20*60; } else if (enemySpawn < 0) { Soldier* soldier = new Soldier(wave, 0, 0); soldier->setWave(wave); soldier->loadImg(renderer); listEnemy.push_back(soldier); int num = rand() % lvl1.getNumPaths(); soldier->setPath(lvl1.getPath(num)); enemySpawn = enemyRegen; if (enemyRegen > 60) { enemyRegen -= 10; } } else { enemySpawn -= 1; } /*************** * Aiming Code **************/ for (auto t : listTower) { Enemy* attacked = nullptr; int r, radius; int radiusAttacked = 10000; t->update(); if (!(t->canFire())) { continue; } for (auto e : listEnemy) { r = t->getRange(); auto tpair = t->getPosition(); auto epair = e->getPosition(); radius = sqrt((epair.first - tpair.first) * (epair.first - tpair.first) + (epair.second - tpair.second) * (epair.second - tpair.second)); if (radius < r && radius < radiusAttacked) { radiusAttacked = radius; attacked = e; } } // end of enemy loop if (attacked) { Bullet* bullet = new Bullet(t->getPlayer(), attacked, t->getPower()); bullet->setPosition(t->getPosition()); bullet->loadImg(renderer,t->getType()); listBullet.push_back(bullet); t->reloadTower(); } } // end of tower loop // Drawing code SDL_RenderClear(renderer); // test font SDL_Rect txr; // img size txr.w = 32; txr.h = 32; //draw background image //txr.w = 900; //txr.h = 579; txr.w = SCREEN_WIDTH; txr.h = SCREEN_HEIGHT; txr.x = 0; txr.y = 0; SDL_Texture* bkgtx = TextureLoader::getInstance().loadImg("./res/bkgImg.png", renderer); SDL_RenderCopy(renderer, bkgtx, NULL, &txr); /*txr.x = 900; SDL_RenderCopy(renderer, bkgtx, NULL, &txr); txr.x = 0; txr.y = 579; SDL_RenderCopy(renderer, bkgtx, NULL, &txr); txr.x = 900; SDL_RenderCopy(renderer, bkgtx, NULL, &txr); */ txr.w = 32; txr.h = 32; // For each path item, draw // For each base tower, draw for (auto it : listFloors) { GameObject* f = it; pair<int, int> floor_pos = f->getPosition(); txr.x = floor_pos.first; txr.y = floor_pos.second; SDL_Texture* tx = f->draw(); if (!tx) { std::cout << "Error, tx is NULL"; } SDL_RenderCopy(renderer, tx, NULL, &txr); } for (auto it : listTower) { Tower* t = it; pair<int, int> tower_pos = t->getPosition(); txr.x = tower_pos.first; txr.y = tower_pos.second; SDL_Texture* tx = t->draw(); if (!tx) { std::cout << "Error, tx is NULL"; } SDL_RenderCopy(renderer, tx, NULL, &txr); } vector<int> toRemove; int tCount = -1; bool isGameOver = false; for (auto e : listEnemy) { tCount += 1; if (!(e->getAlive())) { game_audio.PlaySound("./res/Wilhelm.wav"); e->loadImg("./res/Explosion.png",renderer); toRemove.push_back(tCount); continue; } // pair<int, int> e_posOld = e->getPosition(); e->move(); pair<int, int> e_posNew = e->getPosition(); txr.x = e_posNew.first; txr.y = e_posNew.second; if ((e_posNew.first == base_pos.first) && (e_posNew.second == base_pos.second)) { baseTower->setHealth((baseTower->getHealth()) - e->getPower()); if ((e->getAlive())) { game_audio.PlaySound("./res/Wilhelm.wav"); e->loadImg("./res/Explosion.png",renderer); toRemove.push_back(tCount); continue; } if ((baseTower->getHealth()) <= 0) { gameOver(); isGameOver = true; } // txr.x = e_posOld.first; // txr.y = e_posOld.second; } SDL_Texture* tx = e->draw(); if (!tx) { cout << "Error, tx is NULL"; } SDL_RenderCopy(renderer, tx, NULL, &txr); } txr.x = base_pos.first; txr.y = base_pos.second; SDL_Texture* ttx = baseTower->draw(); SDL_RenderCopy(renderer, ttx, NULL, &txr); txr.w = 16; txr.h = 16; vector<int> toRemoveBullets; int bCount = -1; for (auto it : listBullet) { bCount += 1; Bullet* b = it; if (b->getDead()) { toRemoveBullets.push_back(bCount); continue; } if (b->move()) { Enemy* attacked = b->getTarget(); attacked->setHealth(attacked->getHealth() - b->getPower()); b->getSource()->addMoney(5); if (attacked->getHealth() <= 0 && attacked->getAlive()) { cout << "BAM! Gotem!\n"; enemyRemain--; b->getSource()->addMoney(attacked->getMoney()); attacked->setAlive(false); for (auto ee : listBullet) { if (ee->getTarget() == b->getTarget()) { ee->setDead(true); } } } toRemoveBullets.push_back(bCount); MsgStruct* p = newPacket(5); p->write(to_string(b->getSource()->getMoney())); send(p, b->getSource()->getPlayerID()); continue; } pair<int, int> bullet_pos = b->getPosition(); txr.x = bullet_pos.first; txr.y = bullet_pos.second; SDL_Texture* tx = b->draw(); if (!tx) { std::cout << "Error, tx is NULL"; } SDL_RenderCopy(renderer, tx, NULL, &txr); } txr.w = 32; txr.h = 32; // For each player, get cursor, draw for (auto it : listPlayers) { Player* p = it.second; pair<int, int> player_pos = p->getPos(); txr.x = player_pos.first; txr.y = player_pos.second; SDL_Texture* t = p->getTexture(); SDL_RenderCopy(renderer, t, NULL, &txr); drawString(p->getName(), txr.x + 48, txr.y); } std::sort(toRemove.begin(), toRemove.end(), std::greater<int>()); for (auto i : toRemove) { delete (listEnemy.at(i)); listEnemy.erase(listEnemy.begin() + i); } std::sort(toRemoveBullets.begin(), toRemoveBullets.end(), std::greater<int>()); for (auto i : toRemoveBullets) { delete (listBullet.at(i)); listBullet.erase(listBullet.begin() + i); } drawString("Host Code: "+roomCode, 16, 16); drawString("http://preston.room409.xyz:8001", 16, 48); SDL_RenderPresent(renderer); if(isGameOver) { running = false; } } while (1) { SDL_PollEvent(&e); if (e.type == SDL_QUIT) { break; } } SDL_DestroyWindow(window); SDLNet_TCP_Close(sock); SDLNet_Quit(); SDL_Quit(); return 0; } void drawPath(Path* path, SDL_Renderer* renderer) { int stage = 0; pair<int, int> walker = path->getDest(stage); stage += 1; while (stage < path->length()) { GameObject* obj = new GameObject(); obj->setPos(walker.first, walker.second); obj->loadImg("./res/BlueRect.png", renderer); listFloors.push_back(obj); pair<int, int> goal = path->getDest(stage); if (walker.first < goal.first) { walker.first += 32; } else if (walker.first > goal.first) { walker.first -= 32; } else if (walker.second < goal.second) { walker.second += 32; } else if (walker.second > goal.second) { walker.second -= 32; } else { stage += 1; } } } void setupMessages() { MsgStruct* m1 = createMsgStruct(999, false); m1->addChars(4); MsgStruct* m998 = createMsgStruct(998, false); m998->addChars(2); MsgStruct* m2 = createMsgStruct(2, false); m2->addChars(2); m2->addChars(1); MsgStruct* m3 = createMsgStruct(3, false); m3->addChars(2); MsgStruct* o3 = createMsgStruct(3, true); o3->addChars(1); o3->addString(); MsgStruct* m4 = createMsgStruct(4, false); m4->addChars(2); m4->addChars(2); MsgStruct* o4 = createMsgStruct(4, true); o4->addChars(1); MsgStruct* o5 = createMsgStruct(5, true); o5->addString(); MsgStruct* m6 = createMsgStruct(6, false); m6->addChars(2); MsgStruct* o6 = createMsgStruct(6, true); o6->addChars(1); MsgStruct* m10 = createMsgStruct(10, false); m10->addChars(2); m10->addString(); } bool canHandleMsg() { if (bufferSize < 3) { return false; } string data = string(buffer); if (data.size() < 3) { return false; } // cout << "Handling message...\n"; int offset = 0; // cout << data + "\n"; data = data.substr(offset); // cout << data + "\n"; string rawMsgID = data.substr(0, 3); // cout << rawMsgID + "\n"; int msgID = atoi(rawMsgID.c_str()); if (inMsgStructs.find(msgID) != inMsgStructs.end()) { return inMsgStructs[msgID]->canHandle(data); } cout << "Message ID does not exist. Raw: " << rawMsgID << " | Parsed: " << msgID << "\n"; cout << "Buffer: " << buffer << "\n"; cout << "Data: " << data << "\n"; bufferSize = 0; return false; } MsgStruct* readPacket() { string data = string(buffer).substr(0, bufferSize); int offset = 0; int msgID = atoi(data.substr(offset, 3).c_str()); return inMsgStructs[msgID]->fillFromData(); } MsgStruct* createMsgStruct(int msgID, bool outgoing) { MsgStruct* packet = new MsgStruct(msgID); if (outgoing) { outMsgStructs[msgID] = packet; } else { inMsgStructs[msgID] = packet; } return packet; } MsgStruct* newPacket(int msgID) { return outMsgStructs[msgID]->reset(); } int send(string data) { send(data, 0); } int send(string data, int pID) { if (pID > 0) { data = extend(pID, 2) + data + "*"; } int len = data.size() + 1; int out = SDLNet_TCP_Send(sock, (void*)data.c_str(), len); if (out < len) { fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } return 0; } int send(MsgStruct* packet, int pID) { send(packet->getData(), pID); } Player* getPlayerbyID(string id) { return getPlayerbyID(atoi(id.c_str())); } Player* getPlayerbyID(int id) { auto it = listPlayers.find(id); if (it != listPlayers.end()) { return it->second; } return nullptr; } void addPlayerbyID(int id, SDL_Renderer* r) { auto it = listPlayers.find(id); if (it == listPlayers.end()) { Player* p = new Player(id, &lvl1); p->loadImg(r); listPlayers.emplace(id, p); } } void addTower(int id, int type, SDL_Renderer* r) { Player* p = getPlayerbyID(id); if (p == nullptr) { return; } auto pos = p->getPos(); int x = pos.first; int y = pos.second; std::cout << "x,y " << x << "," << y << "\n"; Tower* t; std::cout << type << "\n"; if(type == 1) { Cannon* cannon = new Cannon(x,y,1); cannon->loadImg(r); t = cannon; } else { Rocket* rocket = new Rocket(x,y,1); rocket->loadImg(r); t = rocket; } if(!lvl1.spotOpen(x, y)) { delete t; return; } t->setPlayer(p); listTower.push_back(t); lvl1.addGameObject(t); } int init() { int flag = IMG_INIT_PNG; if ((IMG_Init(flag) & flag) != flag) { std::cout << "Error, SDL_image" << "\n"; return -1; } if (SDLNet_Init() == -1) { std::cout << "Error, SDLNet_Init\n"; return -1; } initFont(); return 0; } //return //3 if cannon //4 if rocket Tower* getTowerbyPos(int x, int y) { for(auto t : listTower) { auto pos = t->getPosition(); if(pos.first == x && pos.second == y) { return t; } } return nullptr; }
mit
DFEAGILEDEVOPS/gender-pay-gap
Beta/GenderPayGap.Tests.Common/Mocks/MockClassQueue.cs
560
using GenderPayGap.Core.Interfaces; using System.Collections.Generic; using System.Threading.Tasks; public class MockClassQueue : IQueue { Queue<object> _queue = new Queue<object>(); public MockClassQueue(string queueName) { this.Name = queueName; } public string Name { get; } public Task AddMessageAsync<T>(T instance) { _queue.Enqueue(instance); return Task.CompletedTask; } public Task AddMessageAsync(string message) { throw new System.NotImplementedException(); } }
mit
nodoid/PointOfSale
C-Sharp/frmDeposit.Designer.cs
30643
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmDeposit { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmDeposit() : base() { FormClosed += frmDeposit_FormClosed; KeyPress += frmDeposit_KeyPress; Resize += frmDeposit_Resize; Load += frmDeposit_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.CheckBox _chkFields_1; public System.Windows.Forms.TextBox _txtFloat_3; public System.Windows.Forms.TextBox _txtFloat_2; public System.Windows.Forms.TextBox _txtFloat_1; public System.Windows.Forms.TextBox _txtFloat_0; public System.Windows.Forms.TextBox _txtHide_1; public System.Windows.Forms.TextBox _txtHide_0; public System.Windows.Forms.TextBox _txtInteger_5; public System.Windows.Forms.TextBox _txtFields_4; public System.Windows.Forms.TextBox _txtFields_3; public System.Windows.Forms.TextBox _txtFields_28; private System.Windows.Forms.Button withEventsField_cmdPrint; public System.Windows.Forms.Button cmdPrint { get { return withEventsField_cmdPrint; } set { if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click -= cmdPrint_Click; } withEventsField_cmdPrint = value; if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click += cmdPrint_Click; } } } private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; private myDataGridView withEventsField_cmbVat; public myDataGridView cmbVat { get { return withEventsField_cmbVat; } set { if (withEventsField_cmbVat != null) { withEventsField_cmbVat.KeyDown -= cmbVat_KeyDown; } withEventsField_cmbVat = value; if (withEventsField_cmbVat != null) { withEventsField_cmbVat.KeyDown += cmbVat_KeyDown; } } } public System.Windows.Forms.Label _lbl_0; public System.Windows.Forms.Label _lblLabels_2; public System.Windows.Forms.Label _lblLabels_9; public System.Windows.Forms.Label _lblLabels_8; public System.Windows.Forms.Label _lblLabels_7; public System.Windows.Forms.Label _lblLabels_6; public System.Windows.Forms.Label _lblLabels_5; public System.Windows.Forms.Label _lblLabels_4; public System.Windows.Forms.Label _lblLabels_3; public System.Windows.Forms.Label _lblLabels_38; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2; public System.Windows.Forms.Label _lbl_5; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0; //Public WithEvents chkFields As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray //Public WithEvents txtFloat As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray //Public WithEvents txtHide As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray //Public WithEvents txtInteger As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._chkFields_1 = new System.Windows.Forms.CheckBox(); this._txtFloat_3 = new System.Windows.Forms.TextBox(); this._txtFloat_2 = new System.Windows.Forms.TextBox(); this._txtFloat_1 = new System.Windows.Forms.TextBox(); this._txtFloat_0 = new System.Windows.Forms.TextBox(); this._txtHide_1 = new System.Windows.Forms.TextBox(); this._txtHide_0 = new System.Windows.Forms.TextBox(); this._txtInteger_5 = new System.Windows.Forms.TextBox(); this._txtFields_4 = new System.Windows.Forms.TextBox(); this._txtFields_3 = new System.Windows.Forms.TextBox(); this._txtFields_28 = new System.Windows.Forms.TextBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdPrint = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdClose = new System.Windows.Forms.Button(); this.cmbVat = new _4PosBackOffice.NET.myDataGridView(); this._lbl_0 = new System.Windows.Forms.Label(); this._lblLabels_2 = new System.Windows.Forms.Label(); this._lblLabels_9 = new System.Windows.Forms.Label(); this._lblLabels_8 = new System.Windows.Forms.Label(); this._lblLabels_7 = new System.Windows.Forms.Label(); this._lblLabels_6 = new System.Windows.Forms.Label(); this._lblLabels_5 = new System.Windows.Forms.Label(); this._lblLabels_4 = new System.Windows.Forms.Label(); this._lblLabels_3 = new System.Windows.Forms.Label(); this._lblLabels_38 = new System.Windows.Forms.Label(); this._lbl_5 = new System.Windows.Forms.Label(); this.Shape1 = new _4PosBackOffice.NET.RectangleShapeArray(this.components); this.picButtons.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)this.cmbVat).BeginInit(); ((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit(); this.SuspendLayout(); // //ShapeContainer1 // this.ShapeContainer1.Location = new System.Drawing.Point(0, 0); this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0); this.ShapeContainer1.Name = "ShapeContainer1"; this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] { this._Shape1_2, this._Shape1_0 }); this.ShapeContainer1.Size = new System.Drawing.Size(549, 205); this.ShapeContainer1.TabIndex = 26; this.ShapeContainer1.TabStop = false; // //_Shape1_2 // this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_2.FillColor = System.Drawing.Color.Black; this.Shape1.SetIndex(this._Shape1_2, Convert.ToInt16(2)); this._Shape1_2.Location = new System.Drawing.Point(15, 60); this._Shape1_2.Name = "_Shape1_2"; this._Shape1_2.Size = new System.Drawing.Size(286, 136); // //_Shape1_0 // this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_0.FillColor = System.Drawing.Color.Black; this.Shape1.SetIndex(this._Shape1_0, Convert.ToInt16(0)); this._Shape1_0.Location = new System.Drawing.Point(309, 60); this._Shape1_0.Name = "_Shape1_0"; this._Shape1_0.Size = new System.Drawing.Size(229, 76); // //_chkFields_1 // this._chkFields_1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkFields_1.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkFields_1.Cursor = System.Windows.Forms.Cursors.Default; this._chkFields_1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkFields_1.ForeColor = System.Drawing.SystemColors.WindowText; this._chkFields_1.Location = new System.Drawing.Point(171, 174); this._chkFields_1.Name = "_chkFields_1"; this._chkFields_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkFields_1.Size = new System.Drawing.Size(118, 19); this._chkFields_1.TabIndex = 11; this._chkFields_1.Text = "Disable this Deposit"; this._chkFields_1.UseVisualStyleBackColor = false; // //_txtFloat_3 // this._txtFloat_3.AcceptsReturn = true; this._txtFloat_3.BackColor = System.Drawing.SystemColors.Window; this._txtFloat_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloat_3.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloat_3.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloat_3.Location = new System.Drawing.Point(465, 99); this._txtFloat_3.MaxLength = 0; this._txtFloat_3.Name = "_txtFloat_3"; this._txtFloat_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloat_3.Size = new System.Drawing.Size(61, 19); this._txtFloat_3.TabIndex = 20; this._txtFloat_3.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //_txtFloat_2 // this._txtFloat_2.AcceptsReturn = true; this._txtFloat_2.BackColor = System.Drawing.SystemColors.Window; this._txtFloat_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloat_2.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloat_2.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloat_2.Location = new System.Drawing.Point(402, 99); this._txtFloat_2.MaxLength = 0; this._txtFloat_2.Name = "_txtFloat_2"; this._txtFloat_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloat_2.Size = new System.Drawing.Size(61, 19); this._txtFloat_2.TabIndex = 17; this._txtFloat_2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //_txtFloat_1 // this._txtFloat_1.AcceptsReturn = true; this._txtFloat_1.BackColor = System.Drawing.SystemColors.Window; this._txtFloat_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloat_1.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloat_1.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloat_1.Location = new System.Drawing.Point(465, 78); this._txtFloat_1.MaxLength = 0; this._txtFloat_1.Name = "_txtFloat_1"; this._txtFloat_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloat_1.Size = new System.Drawing.Size(61, 19); this._txtFloat_1.TabIndex = 19; this._txtFloat_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //_txtFloat_0 // this._txtFloat_0.AcceptsReturn = true; this._txtFloat_0.BackColor = System.Drawing.SystemColors.Window; this._txtFloat_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFloat_0.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFloat_0.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFloat_0.Location = new System.Drawing.Point(402, 78); this._txtFloat_0.MaxLength = 0; this._txtFloat_0.Name = "_txtFloat_0"; this._txtFloat_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFloat_0.Size = new System.Drawing.Size(61, 19); this._txtFloat_0.TabIndex = 16; this._txtFloat_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //_txtHide_1 // this._txtHide_1.AcceptsReturn = true; this._txtHide_1.BackColor = System.Drawing.SystemColors.Window; this._txtHide_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtHide_1.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtHide_1.ForeColor = System.Drawing.SystemColors.WindowText; this._txtHide_1.Location = new System.Drawing.Point(329, 167); this._txtHide_1.MaxLength = 0; this._txtHide_1.Name = "_txtHide_1"; this._txtHide_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtHide_1.Size = new System.Drawing.Size(99, 19); this._txtHide_1.TabIndex = 25; this._txtHide_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtHide_1.Visible = false; // //_txtHide_0 // this._txtHide_0.AcceptsReturn = true; this._txtHide_0.BackColor = System.Drawing.SystemColors.Window; this._txtHide_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtHide_0.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtHide_0.ForeColor = System.Drawing.SystemColors.WindowText; this._txtHide_0.Location = new System.Drawing.Point(329, 142); this._txtHide_0.MaxLength = 0; this._txtHide_0.Name = "_txtHide_0"; this._txtHide_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtHide_0.Size = new System.Drawing.Size(99, 19); this._txtHide_0.TabIndex = 24; this._txtHide_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._txtHide_0.Visible = false; // //_txtInteger_5 // this._txtInteger_5.AcceptsReturn = true; this._txtInteger_5.BackColor = System.Drawing.SystemColors.Window; this._txtInteger_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtInteger_5.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtInteger_5.ForeColor = System.Drawing.SystemColors.WindowText; this._txtInteger_5.Location = new System.Drawing.Point(239, 152); this._txtInteger_5.MaxLength = 0; this._txtInteger_5.Name = "_txtInteger_5"; this._txtInteger_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtInteger_5.Size = new System.Drawing.Size(51, 19); this._txtInteger_5.TabIndex = 10; this._txtInteger_5.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //_txtFields_4 // this._txtFields_4.AcceptsReturn = true; this._txtFields_4.BackColor = System.Drawing.SystemColors.Window; this._txtFields_4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_4.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_4.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_4.Location = new System.Drawing.Point(104, 108); this._txtFields_4.MaxLength = 15; this._txtFields_4.Name = "_txtFields_4"; this._txtFields_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_4.Size = new System.Drawing.Size(184, 19); this._txtFields_4.TabIndex = 6; // //_txtFields_3 // this._txtFields_3.AcceptsReturn = true; this._txtFields_3.BackColor = System.Drawing.SystemColors.Window; this._txtFields_3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_3.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_3.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_3.Location = new System.Drawing.Point(105, 87); this._txtFields_3.MaxLength = 20; this._txtFields_3.Name = "_txtFields_3"; this._txtFields_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_3.Size = new System.Drawing.Size(184, 19); this._txtFields_3.TabIndex = 4; // //_txtFields_28 // this._txtFields_28.AcceptsReturn = true; this._txtFields_28.BackColor = System.Drawing.SystemColors.Window; this._txtFields_28.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_28.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_28.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_28.Location = new System.Drawing.Point(104, 64); this._txtFields_28.MaxLength = 128; this._txtFields_28.Name = "_txtFields_28"; this._txtFields_28.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_28.Size = new System.Drawing.Size(184, 19); this._txtFields_28.TabIndex = 2; // //picButtons // this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Controls.Add(this.cmdPrint); this.picButtons.Controls.Add(this.cmdCancel); this.picButtons.Controls.Add(this.cmdClose); this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.Name = "picButtons"; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Size = new System.Drawing.Size(549, 39); this.picButtons.TabIndex = 23; // //cmdPrint // this.cmdPrint.BackColor = System.Drawing.SystemColors.Control; this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPrint.Location = new System.Drawing.Point(375, 3); this.cmdPrint.Name = "cmdPrint"; this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPrint.Size = new System.Drawing.Size(73, 29); this.cmdPrint.TabIndex = 26; this.cmdPrint.TabStop = false; this.cmdPrint.Text = "&Print"; this.cmdPrint.UseVisualStyleBackColor = false; // //cmdCancel // this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Location = new System.Drawing.Point(5, 3); this.cmdCancel.Name = "cmdCancel"; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Size = new System.Drawing.Size(73, 29); this.cmdCancel.TabIndex = 22; this.cmdCancel.TabStop = false; this.cmdCancel.Text = "&Undo"; this.cmdCancel.UseVisualStyleBackColor = false; // //cmdClose // this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Location = new System.Drawing.Point(460, 3); this.cmdClose.Name = "cmdClose"; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.TabIndex = 21; this.cmdClose.TabStop = false; this.cmdClose.Text = "E&xit"; this.cmdClose.UseVisualStyleBackColor = false; // //cmbVat // this.cmbVat.AllowAddNew = true; this.cmbVat.BoundText = ""; this.cmbVat.CellBackColor = System.Drawing.SystemColors.AppWorkspace; this.cmbVat.Col = 0; this.cmbVat.CtlText = ""; this.cmbVat.DataField = null; this.cmbVat.Location = new System.Drawing.Point(105, 129); this.cmbVat.Name = "cmbVat"; this.cmbVat.row = 0; this.cmbVat.Size = new System.Drawing.Size(184, 21); this.cmbVat.TabIndex = 8; this.cmbVat.TopRow = 0; // //_lbl_0 // this._lbl_0.AutoSize = true; this._lbl_0.BackColor = System.Drawing.Color.Transparent; this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_0.Location = new System.Drawing.Point(309, 45); this._lbl_0.Name = "_lbl_0"; this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_0.Size = new System.Drawing.Size(57, 14); this._lbl_0.TabIndex = 12; this._lbl_0.Text = "&2. Pricing"; // //_lblLabels_2 // this._lblLabels_2.AutoSize = true; this._lblLabels_2.BackColor = System.Drawing.Color.Transparent; this._lblLabels_2.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_2.Location = new System.Drawing.Point(72, 132); this._lblLabels_2.Name = "_lblLabels_2"; this._lblLabels_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_2.Size = new System.Drawing.Size(31, 13); this._lblLabels_2.TabIndex = 7; this._lblLabels_2.Text = "VAT:"; this._lblLabels_2.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lblLabels_9 // this._lblLabels_9.AutoSize = true; this._lblLabels_9.BackColor = System.Drawing.Color.Transparent; this._lblLabels_9.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_9.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_9.Location = new System.Drawing.Point(498, 66); this._lblLabels_9.Name = "_lblLabels_9"; this._lblLabels_9.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_9.Size = new System.Drawing.Size(31, 13); this._lblLabels_9.TabIndex = 18; this._lblLabels_9.Text = "Case"; this._lblLabels_9.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lblLabels_8 // this._lblLabels_8.AutoSize = true; this._lblLabels_8.BackColor = System.Drawing.Color.Transparent; this._lblLabels_8.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_8.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_8.Location = new System.Drawing.Point(432, 66); this._lblLabels_8.Name = "_lblLabels_8"; this._lblLabels_8.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_8.Size = new System.Drawing.Size(34, 13); this._lblLabels_8.TabIndex = 15; this._lblLabels_8.Text = "Bottle"; this._lblLabels_8.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lblLabels_7 // this._lblLabels_7.AutoSize = true; this._lblLabels_7.BackColor = System.Drawing.Color.Transparent; this._lblLabels_7.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_7.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_7.Location = new System.Drawing.Point(318, 99); this._lblLabels_7.Name = "_lblLabels_7"; this._lblLabels_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_7.Size = new System.Drawing.Size(84, 13); this._lblLabels_7.TabIndex = 14; this._lblLabels_7.Text = "2. Special Price:"; this._lblLabels_7.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lblLabels_6 // this._lblLabels_6.AutoSize = true; this._lblLabels_6.BackColor = System.Drawing.Color.Transparent; this._lblLabels_6.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_6.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_6.Location = new System.Drawing.Point(312, 81); this._lblLabels_6.Name = "_lblLabels_6"; this._lblLabels_6.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_6.Size = new System.Drawing.Size(91, 13); this._lblLabels_6.TabIndex = 13; this._lblLabels_6.Text = "1. Inclusive Price:"; this._lblLabels_6.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lblLabels_5 // this._lblLabels_5.AutoSize = true; this._lblLabels_5.BackColor = System.Drawing.Color.Transparent; this._lblLabels_5.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_5.Location = new System.Drawing.Point(104, 155); this._lblLabels_5.Name = "_lblLabels_5"; this._lblLabels_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_5.Size = new System.Drawing.Size(138, 13); this._lblLabels_5.TabIndex = 9; this._lblLabels_5.Text = "Number of Bottles In a case"; this._lblLabels_5.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lblLabels_4 // this._lblLabels_4.AutoSize = true; this._lblLabels_4.BackColor = System.Drawing.Color.Transparent; this._lblLabels_4.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_4.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_4.Location = new System.Drawing.Point(21, 108); this._lblLabels_4.Name = "_lblLabels_4"; this._lblLabels_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_4.Size = new System.Drawing.Size(84, 13); this._lblLabels_4.TabIndex = 5; this._lblLabels_4.Text = "POS Quick Key:"; this._lblLabels_4.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lblLabels_3 // this._lblLabels_3.AutoSize = true; this._lblLabels_3.BackColor = System.Drawing.Color.Transparent; this._lblLabels_3.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_3.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_3.Location = new System.Drawing.Point(27, 87); this._lblLabels_3.Name = "_lblLabels_3"; this._lblLabels_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_3.Size = new System.Drawing.Size(78, 13); this._lblLabels_3.TabIndex = 3; this._lblLabels_3.Text = "Receipt Name:"; this._lblLabels_3.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lblLabels_38 // this._lblLabels_38.AutoSize = true; this._lblLabels_38.BackColor = System.Drawing.Color.Transparent; this._lblLabels_38.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_38.ForeColor = System.Drawing.SystemColors.ControlText; this._lblLabels_38.Location = new System.Drawing.Point(30, 69); this._lblLabels_38.Name = "_lblLabels_38"; this._lblLabels_38.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_38.Size = new System.Drawing.Size(75, 13); this._lblLabels_38.TabIndex = 1; this._lblLabels_38.Text = "Display Name:"; this._lblLabels_38.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lbl_5 // this._lbl_5.AutoSize = true; this._lbl_5.BackColor = System.Drawing.Color.Transparent; this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_5.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_5.Location = new System.Drawing.Point(15, 45); this._lbl_5.Name = "_lbl_5"; this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_5.Size = new System.Drawing.Size(62, 14); this._lbl_5.TabIndex = 0; this._lbl_5.Text = "&1. General"; // //frmDeposit // this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224))); this.ClientSize = new System.Drawing.Size(549, 205); this.ControlBox = false; this.Controls.Add(this._chkFields_1); this.Controls.Add(this._txtFloat_3); this.Controls.Add(this._txtFloat_2); this.Controls.Add(this._txtFloat_1); this.Controls.Add(this._txtFloat_0); this.Controls.Add(this._txtHide_1); this.Controls.Add(this._txtHide_0); this.Controls.Add(this._txtInteger_5); this.Controls.Add(this._txtFields_4); this.Controls.Add(this._txtFields_3); this.Controls.Add(this._txtFields_28); this.Controls.Add(this.picButtons); this.Controls.Add(this.cmbVat); this.Controls.Add(this._lbl_0); this.Controls.Add(this._lblLabels_2); this.Controls.Add(this._lblLabels_9); this.Controls.Add(this._lblLabels_8); this.Controls.Add(this._lblLabels_7); this.Controls.Add(this._lblLabels_6); this.Controls.Add(this._lblLabels_5); this.Controls.Add(this._lblLabels_4); this.Controls.Add(this._lblLabels_3); this.Controls.Add(this._lblLabels_38); this.Controls.Add(this._lbl_5); this.Controls.Add(this.ShapeContainer1); this.Cursor = System.Windows.Forms.Cursors.Default; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.KeyPreview = true; this.Location = new System.Drawing.Point(73, 22); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmDeposit"; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Edit Deposit Details"; this.picButtons.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)this.cmbVat).EndInit(); ((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
mit
vbence86/fivenations
src/js/gui/NotificationBar.js
4438
/* global Phaser */ import { DEFAULT_FONT, NOTIFICATION_PANEL } from '../common/Const'; import TranslationManager from '../common/TranslationManager'; import EventEmitter from '../sync/EventEmitter'; /** * Notification bar implementation that can be used to display * any form of Notification on the top of the game stage */ class NotificationBar extends Phaser.Group { /** * Initialise an extended Phaser.Group with the notification background * and a Text element that can be updated through the exposed API * @param {object} phaserGame - Phaser.Game instance */ constructor(phaserGame) { super(phaserGame); this.setDefaultVisiblity(); this.initBackground(); this.initTextComponent(); this.initListeners(); } /** * Sets the default visibility of the Group */ setDefaultVisiblity() { this.visible = false; } /** * Adds the semi transparent background to the Group */ initBackground() { const graphics = this.game.add.graphics(0, 0); const { width, height } = NOTIFICATION_PANEL; const color = 0x000000; graphics.beginFill(color); graphics.drawRect(0, 0, width, height); graphics.alpha = 0.5; this.add(graphics); } /** * Adds the Text element to the Group */ initTextComponent() { this.label = this.add(this.game.add.text(0, 0, '', { font: DEFAULT_FONT.font.replace('11px', '13px'), fill: DEFAULT_FONT.color, boundsAlignH: 'center', boundsAlignV: 'middle', })); this.label.setTextBounds( 0, 0, NOTIFICATION_PANEL.width, NOTIFICATION_PANEL.height, ); } /** * Registers the default event listeners */ initListeners() { const translator = TranslationManager.getInstance(); const emitter = EventEmitter.getInstance(); const notEnoughPrefix = 'notifications.notenough.'; const eventsTranslationsMap = { // insufficient founds notifications 'resources/unsufficient/titanium': `${notEnoughPrefix}titanium`, 'resources/unsufficient/silicium': `${notEnoughPrefix}silicium`, 'resources/unsufficient/energy': `${notEnoughPrefix}energy`, 'resources/unsufficient/uranium': `${notEnoughPrefix}uranium`, 'resources/unsufficient/space': `${notEnoughPrefix}space`, 'building/placement/occupied': 'notifications.cannotBuildThere', }; Object.keys(eventsTranslationsMap).forEach((key) => { const translation = eventsTranslationsMap[key]; const text = translator.translate(translation); emitter.local.addEventListener(key, this.show.bind(this, text)); }); } /** * Attaches the Notification Bar to the given group * @param {object} group * @param {number} x - Horizontal offset from the parent's anchor point * @param {number} y - Vertical offset from the parent's anchor point */ appendTo(object, x, y) { if (!object) { throw new Error('Invalid Phaser.Sprite object!'); } object.addChild(this); this.x = x; this.y = y; } /** * Updates the label of the NotificationBar according to the given string * @param {string} text */ updateContent(text) { this.label.text = text; } /** * Displays Notification Bar with the fadeIn Tween * @param {string} text - Text to be shown on the bar */ show(text) { this.updateContent(text); this.visible = true; // when invoked more than once simultaniously we just update // the text on the bar and resets the timer if (!this.showAnim) { this.alpha = 0; this.showAnim = this.game.add .tween(this) .to( { alpha: 1 }, NOTIFICATION_PANEL.fadeAnimationDuration, 'Linear', true, ); } if (this.timer) { clearTimeout(this.timer); } this.timer = setTimeout(() => this.hide(), NOTIFICATION_PANEL.displayTime); } /** * Makes Notification Bar disapear with a Fade Out Tween */ hide() { // guard against multiple calls simultaniously if (this.hideAnim) return; this.hideAnim = this.game.add .tween(this) .to( { alpha: 0 }, NOTIFICATION_PANEL.fadeAnimationDuration, 'Linear', true, ); this.hideAnim.onComplete.addOnce(() => { this.hideAnim = null; this.showAnim = null; this.timer = null; this.visible = false; }); } } export default NotificationBar;
mit
nico01f/z-pec
ZimbraWebClient/WebRoot/js/zimbraMail/voicemail/controller/ZmVoiceTreeController.js
3367
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Web Client * Copyright (C) 2007, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ ZmVoiceTreeController = function() { ZmFolderTreeController.call(this, ZmOrganizer.VOICE); this._voiceApp = appCtxt.getApp(ZmApp.VOICE); }; ZmVoiceTreeController.prototype = new ZmFolderTreeController; ZmVoiceTreeController.prototype.constructor = ZmVoiceTreeController; // Public Methods ZmVoiceTreeController.prototype.toString = function() { return "ZmVoiceTreeController"; }; ZmVoiceTreeController.prototype.getDataTree = function(overviewId) { var phone = (overviewId instanceof ZmPhone) ? overviewId : this._opc.getOverview(overviewId).phone; if (phone) { var dataTree = this._dataTree[phone.name]; if (!dataTree) { dataTree = this._dataTree[phone.name] = phone.folderTree; dataTree.addChangeListener(this._getTreeChangeListener()); } return dataTree; } }; ZmVoiceTreeController.prototype._createTreeView = function(params) { return new ZmVoiceTreeView(params); }; ZmVoiceTreeController.prototype._postSetup = function(overviewId) { ZmTreeController.prototype._postSetup.call(this, overviewId); // expand all root account folders var view = this._treeView[overviewId]; var app = appCtxt.getApp(ZmApp.VOICE); for (var i = 0; i < app.phones.length; i++) { var root = app.phones[i].folderTree.root; var ti = this._treeView[overviewId].getTreeItemById(root.id); if (ti) { ti.setExpanded(true); } } // show start folder as selected var parts = overviewId.split(":"); if (parts && (parts.length == 2)) { var startFolder = this._voiceApp.getStartFolder(parts[1]); if (startFolder) { var treeItem = view.getTreeItemById(startFolder.id); if (treeItem) { view.setSelection(treeItem, true); } } } }; ZmVoiceTreeController.prototype.resetOperations = function(parent, type, id) { var folder = appCtxt.getById(id); parent.enable(ZmOperation.EXPAND_ALL, (folder.size() > 0)); }; // Returns a list of desired header action menu operations ZmVoiceTreeController.prototype._getHeaderActionMenuOps = function() { return null; }; ZmVoiceTreeController.prototype._getActionMenu = function(ev) { var folder = ev.item.getData(Dwt.KEY_OBJECT); if ((folder instanceof ZmVoiceFolder) && (folder.callType == ZmVoiceFolder.TRASH)) { return ZmTreeController.prototype._getActionMenu.call(this, ev); } return null; }; // Returns a list of desired action menu operations ZmVoiceTreeController.prototype._getActionMenuOps = function() { return [ZmOperation.EMPTY_FOLDER]; }; ZmVoiceTreeController.prototype._getAllowedSubTypes = function() { var types = {}; types[ZmOrganizer.VOICE] = true; return types; }; /* * Called when a left click occurs (by the tree view listener). * * @param folder ZmVoiceFolder folder that was clicked */ ZmVoiceTreeController.prototype._itemClicked = function(folder) { appCtxt.getApp(ZmApp.VOICE).search(folder); };
mit
Jacodom/aeris
aeris-app/modules/registers/client/config/registers.client.config.js
669
(function () { 'use strict'; angular .module('registers') .run(menuConfig); menuConfig.$inject = ['Menus']; function menuConfig(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', { title: 'Registers', state: 'registers', type: 'dropdown', roles: ['*'] }); // Add the dropdown list item Menus.addSubMenuItem('topbar', 'registers', { title: 'List Registers', state: 'registers.list' }); // Add the dropdown create item Menus.addSubMenuItem('topbar', 'registers', { title: 'Create Register', state: 'registers.create', roles: ['user'] }); } })();
mit
Sakuyakun/Yorha-Experiment
react-demo/react-electron-env/webpack.dev.config.js
862
const path = require("path"); const webpack = require("webpack"); const ExtractTextPlugin = require("extract-text-webpack-plugin"); const publicPath = "http://localhost:3004/"; const {baseConfig} = require("./webpack.config.js"); const devConfig = { devtool: "inline-source-map", entry: [ "react-hot-loader/patch", "webpack-dev-server/client?" + publicPath, "webpack/hot/only-dev-server", "./src/entry" ], output: { path: path.resolve(__dirname, "dist"), filename: "bundle.js", publicPath: "/" }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), ], devServer: { host: "localhost", port: 3004, historyApiFallback: true, hot: true, overlay: { errors: true, warnings: true } } }; module.exports = Object.assign(baseConfig, devConfig);
mit
enBask/Asgard
Asgard.Core/Network/Packets/PacketTypes.Internal.cs
319
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Asgard.Core.Network.Packets { enum PacketTypes { PACKET = 1, LOGIN_RESPONSE, DATA_OBJECT, ACK_STATE_TICK, RPC, MAX_PACKET=32 } }
mit
c-square/homework
Licență/Anul I/POO/Shapes/Shape.cpp
437
#include <istream> #include <ostream> #include "Shape.h" using namespace std; /* template <class TIP> Shape<TIP>::~Shape() { } template <class TIP> void Shape<TIP>::readFrom(std::istream &) { } template <class TIP> void Shape<TIP>::moveBy(TIP, TIP) { } template <class TIP> void Shape<TIP>::output(std::ostream &o) const { o<<"<Shape Object>"; }*/ /*ostream &operator<<(ostream &o, const Shape *s) { s->output(o); return o; } */
mit
lordazzi/calculator
src/config/config.service.ts
1494
import { CalcConfig } from './calc-config'; export class ConfigService { private static instance: ConfigService | null = null; static defaultConfig: CalcConfig = { thrownStrategy: 'emit-event', throwNaN: true, throwInfinite: true, throwUnsafeNumber: true }; static getInstance(): ConfigService { if (!this.instance) { this.instance = new ConfigService(); } return this.instance; } private constructor() { } static configure(config: CalcConfig): void { this.defaultConfig = this.getInstance().mergeConfigs(this.defaultConfig, config); } private mergeConfigs(config: CalcConfig, mergeWith?: CalcConfig): CalcConfig { const clonedConfig: CalcConfig = JSON.parse(JSON.stringify(config)); if (!mergeWith) { return clonedConfig; } if (mergeWith.thrownStrategy !== undefined) { clonedConfig.thrownStrategy = mergeWith.thrownStrategy; } if (mergeWith.throwNaN !== undefined) { clonedConfig.throwNaN = mergeWith.throwNaN; } if (mergeWith.throwInfinite !== undefined) { clonedConfig.throwInfinite = mergeWith.throwInfinite; } if (mergeWith.throwUnsafeNumber !== undefined) { clonedConfig.throwUnsafeNumber = mergeWith.throwUnsafeNumber; } return clonedConfig; } createConfigs(customConfig?: CalcConfig): CalcConfig { return this.mergeConfigs(ConfigService.defaultConfig, customConfig); } }
mit
Karasiq/scalajs-highcharts
src/main/scala/com/highmaps/config/SeriesFunnelDataDragDropGuideBox.scala
1108
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highmaps]] */ package com.highmaps.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>series&lt;funnel&gt;-data-dragDrop-guideBox</code> */ @js.annotation.ScalaJSDefined class SeriesFunnelDataDragDropGuideBox extends com.highcharts.HighchartsGenericObject { /** * <p>Style options for the guide box default state.</p> * @since 6.2.0 */ val default: js.UndefOr[js.Object] = js.undefined } object SeriesFunnelDataDragDropGuideBox { /** * @param default <p>Style options for the guide box default state.</p> */ def apply(default: js.UndefOr[js.Object] = js.undefined): SeriesFunnelDataDragDropGuideBox = { val defaultOuter: js.UndefOr[js.Object] = default com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesFunnelDataDragDropGuideBox { override val default: js.UndefOr[js.Object] = defaultOuter }) } }
mit
smichael1/SingleAxisReactUI
webpack.config.js
489
module.exports = { entry: [ './src/index.js' ], output: { path: __dirname, publicPath: '/', filename: 'bundle.js' }, module: { loaders: [{ exclude: /node_modules/, loader: 'babel', query: { presets: ['react', 'es2015', 'stage-1'] } }] }, resolve: { extensions: ['', '.js', '.jsx'] }, devServer: { historyApiFallback: true, contentBase: './', //host: '0.0.0.0', // disableHostCheck: true } };
mit
xDryan/game-engine
serveur/save_proprietes.php
140
<?php $json_data = print_r(json_decode(file_get_contents('php://input'), true), true); file_put_contents('proprietes.json', $json_data); ?>
mit
ivanifan/RevitCustomIFCexporter
trunk/2015/Source/Revit.IFC.Export/Utility/PropertyInfoCache.cs
12289
// // BIM IFC library: this library works with Autodesk(R) Revit(R) to export IFC files containing model geometry. // Copyright (C) 2012 Autodesk, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // using System; using System.Collections.Generic; using System.Linq; using System.Text; using Autodesk.Revit.DB; using Autodesk.Revit.DB.IFC; using Revit.IFC.Export.Toolkit; using Revit.IFC.Export.Exporter.PropertySet; using Revit.IFC.Common.Enums; namespace Revit.IFC.Export.Utility { /// <summary> /// Manages caches necessary for caching properties for IFC export. /// </summary> public class PropertyInfoCache { /// <summary> /// The DoublePropertyInfoCache object. /// </summary> IDictionary<PropertyType, DoublePropertyInfoCache> m_DoublePropertyInfoCacheMap = null; /// <summary> /// The StringPropertyInfoCache object. /// </summary> IDictionary<PropertyType, StringPropertyInfoCache> m_StringPropertyInfoCacheMap = null; /// <summary> /// The BooleanPropertyInfoCache object. /// </summary> BooleanPropertyInfoCache m_BooleanPropertyInfoCache = null; /// <summary> /// The LogicalPropertyInfoCache object. /// </summary> LogicalPropertyInfoCache m_LogicalPropertyInfoCache = null; /// <summary> /// The IntegerPropertyInfoCache object. /// </summary> IntegerPropertyInfoCache m_IntegerPropertyInfoCache = null; private IDictionary<PropertyType, DoublePropertyInfoCache> DoubleCacheMap { get { if (m_DoublePropertyInfoCacheMap == null) m_DoublePropertyInfoCacheMap = new Dictionary<PropertyType, DoublePropertyInfoCache>(); return m_DoublePropertyInfoCacheMap; } } /// <summary> /// The StringPropertyInfoCache object. /// </summary> private IDictionary<PropertyType, StringPropertyInfoCache> StringCacheMap { get { if (m_StringPropertyInfoCacheMap == null) m_StringPropertyInfoCacheMap = new Dictionary<PropertyType, StringPropertyInfoCache>(); return m_StringPropertyInfoCacheMap; } } /// <summary> /// The BooleanPropertyInfoCache object. /// </summary> public BooleanPropertyInfoCache BooleanCache { get { if (m_BooleanPropertyInfoCache == null) m_BooleanPropertyInfoCache = new BooleanPropertyInfoCache(); return m_BooleanPropertyInfoCache; } } /// <summary> /// The LogicalPropertyInfoCache object. /// </summary> public LogicalPropertyInfoCache LogicalCache { get { if (m_LogicalPropertyInfoCache == null) m_LogicalPropertyInfoCache = new LogicalPropertyInfoCache(); return m_LogicalPropertyInfoCache; } } /// <summary> /// The IntegerPropertyInfoCache object. /// </summary> public IntegerPropertyInfoCache IntegerCache { get { if (m_IntegerPropertyInfoCache == null) m_IntegerPropertyInfoCache = new IntegerPropertyInfoCache(); return m_IntegerPropertyInfoCache; } } /// <summary> /// The StringPropertyInfoCache object for Text property type. /// </summary> public StringPropertyInfoCache TextCache { get { StringPropertyInfoCache textPropertyInfoCache; if (!StringCacheMap.TryGetValue(PropertyType.Text, out textPropertyInfoCache)) { textPropertyInfoCache = new StringPropertyInfoCache(); StringCacheMap[PropertyType.Text] = textPropertyInfoCache; } return textPropertyInfoCache; } } /// <summary> /// The StringPropertyInfoCache object for Label property type. /// </summary> public StringPropertyInfoCache LabelCache { get { StringPropertyInfoCache labelPropertyInfoCache; if (!StringCacheMap.TryGetValue(PropertyType.Label, out labelPropertyInfoCache)) { labelPropertyInfoCache = new StringPropertyInfoCache(); StringCacheMap[PropertyType.Label] = labelPropertyInfoCache; } return labelPropertyInfoCache; } } /// <summary> /// The StringPropertyInfoCache object for Label property type. /// </summary> public StringPropertyInfoCache IdentifierCache { get { StringPropertyInfoCache identifierCache; if (!StringCacheMap.TryGetValue(PropertyType.Identifier, out identifierCache)) { identifierCache = new StringPropertyInfoCache(); StringCacheMap[PropertyType.Identifier] = identifierCache; } return identifierCache; } } /// <summary> /// The DoublePropertyInfoCache object for Real parameter types. /// </summary> public DoublePropertyInfoCache RealCache { get { DoublePropertyInfoCache realPropertyInfoCache; if (!DoubleCacheMap.TryGetValue(PropertyType.Real, out realPropertyInfoCache)) { realPropertyInfoCache = new DoublePropertyInfoCache(); DoubleCacheMap[PropertyType.Real] = realPropertyInfoCache; } return realPropertyInfoCache; } } /// <summary> /// The DoublePropertyInfoCache object for LengthMeasure parameter types. /// </summary> public DoublePropertyInfoCache LengthMeasureCache { get { DoublePropertyInfoCache lengthMeasurePropertyInfoCache; if (!DoubleCacheMap.TryGetValue(PropertyType.Length, out lengthMeasurePropertyInfoCache)) { lengthMeasurePropertyInfoCache = new DoublePropertyInfoCache(); DoubleCacheMap[PropertyType.Length] = lengthMeasurePropertyInfoCache; } return lengthMeasurePropertyInfoCache; } } /// <summary> /// The DoublePropertyInfoCache object for PlaneAngle parameter types. /// </summary> public DoublePropertyInfoCache PlaneAngleCache { get { DoublePropertyInfoCache planeAngleCache; if (!DoubleCacheMap.TryGetValue(PropertyType.PlaneAngle, out planeAngleCache)) { planeAngleCache = new DoublePropertyInfoCache(); DoubleCacheMap[PropertyType.PlaneAngle] = planeAngleCache; } return planeAngleCache; } } /// <summary> /// The DoublePropertyInfoCache object for ElectricalCurrent parameter types. /// </summary> public DoublePropertyInfoCache ElectricalCurrentCache { get { DoublePropertyInfoCache electricalCurrentCache; if (!DoubleCacheMap.TryGetValue(PropertyType.ElectricalCurrent, out electricalCurrentCache)) { electricalCurrentCache = new DoublePropertyInfoCache(); DoubleCacheMap[PropertyType.ElectricalCurrent] = electricalCurrentCache; } return electricalCurrentCache; } } /// <summary> /// The DoublePropertyInfoCache object for ElectricalVoltage parameter types. /// </summary> public DoublePropertyInfoCache ElectricalVoltageCache { get { DoublePropertyInfoCache electricalVoltageCache; if (!DoubleCacheMap.TryGetValue(PropertyType.ElectricalVoltage, out electricalVoltageCache)) { electricalVoltageCache = new DoublePropertyInfoCache(); DoubleCacheMap[PropertyType.ElectricalVoltage] = electricalVoltageCache; } return electricalVoltageCache; } } /// <summary> /// The DoublePropertyInfoCache object for PositivePlaneAngle parameter types. /// </summary> public DoublePropertyInfoCache PositivePlaneAngleCache { get { DoublePropertyInfoCache planeAngleCache; if (!DoubleCacheMap.TryGetValue(PropertyType.PlaneAngle, out planeAngleCache)) { planeAngleCache = new DoublePropertyInfoCache(); DoubleCacheMap[PropertyType.PositivePlaneAngle] = planeAngleCache; } return planeAngleCache; } } /// <summary> /// The DoublePropertyInfoCache object for ThermodynamicTemperature parameter types. /// </summary> public DoublePropertyInfoCache ThermodynamicTemperatureCache { get { DoublePropertyInfoCache thermodynamicTemperaturePropertyInfoCache; if (!DoubleCacheMap.TryGetValue(PropertyType.ThermodynamicTemperature, out thermodynamicTemperaturePropertyInfoCache)) { thermodynamicTemperaturePropertyInfoCache = new DoublePropertyInfoCache(); DoubleCacheMap[PropertyType.ThermodynamicTemperature] = thermodynamicTemperaturePropertyInfoCache; } return thermodynamicTemperaturePropertyInfoCache; } } /// <summary> /// The DoublePropertyInfoCache object for ThermalTransmittance parameter types. /// </summary> public DoublePropertyInfoCache ThermalTransmittanceCache { get { DoublePropertyInfoCache thermalTransmittancePropertyInfoCache; if (!DoubleCacheMap.TryGetValue(PropertyType.ThermalTransmittance, out thermalTransmittancePropertyInfoCache)) { thermalTransmittancePropertyInfoCache = new DoublePropertyInfoCache(); DoubleCacheMap[PropertyType.ThermalTransmittance] = thermalTransmittancePropertyInfoCache; } return thermalTransmittancePropertyInfoCache; } } /// <summary> /// The DoublePropertyInfoCache object for Power parameter types. /// </summary> public DoublePropertyInfoCache PowerCache { get { DoublePropertyInfoCache powerPropertyInfoCache; if (!DoubleCacheMap.TryGetValue(PropertyType.Power, out powerPropertyInfoCache)) { powerPropertyInfoCache = new DoublePropertyInfoCache(); DoubleCacheMap[PropertyType.Power] = powerPropertyInfoCache; } return powerPropertyInfoCache; } } } }
mit
okmttdhr/YoutuVote
Tests/mock/user.js
320
// @flow export const userMock = { displayName: 'MOCK_DISPLAY_NAME', email: 'MOCK_EMAIL', emailVerified: false, isAnonymous: false, phoneNumber: 'MOCK_PHONE_NUMBER', photoURL: 'MOCK_PHOTO_URL', providerData: [], providerId: 'MOCK_PROVIDER_ID', refreshToken: 'MOCK_REFRESH_TOKEN', uid: 'MOCK_UID', };
mit
plivo/plivo-java
src/main/java/com/plivo/api/models/powerpack/RemoveShortcode.java
673
package com.plivo.api.models.powerpack; import com.plivo.api.models.base.Deleter; import okhttp3.ResponseBody; public class RemoveShortcode extends Deleter<Shortcode> { private String shortcode; public RemoveShortcode(String id) { super(id); if (id == null) { throw new IllegalArgumentException("powerpack uuid cannot be null"); } this.id = id; } public RemoveShortcode shortcode(final String shortcode) { this.shortcode = shortcode; return this; } @Override protected retrofit2.Call<ResponseBody> obtainCall() { return client().getApiService().powerpackShortcodeDelete(client().getAuthId(), id, shortcode, this); } }
mit
mutatis/WereWolfTheApocalipse
Assets/Script/Interface/LoadScene.cs
454
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class LoadScene : MonoBehaviour { public string sceneName; public int tipo; void Start () { if (tipo == 0) { StartCoroutine("GO"); } } public void Muda() { SceneManager.LoadScene(sceneName); } IEnumerator GO() { yield return new WaitForSeconds(2); Muda(); } }
mit
csuffyy/Orc.FilterBuilder
src/Orc.FilterBuilder/Orc.FilterBuilder.Shared/Models/Interfaces/IPropertyMetadata.cs
891
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IPropertyMetadata.cs" company="Orcomp development team"> // Copyright (c) 2008 - 2014 Orcomp development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Orc.FilterBuilder.Models { using System; public interface IPropertyMetadata { /// <summary> /// Display name of the property /// </summary> string DisplayName { get; set; } string Name { get; } Type OwnerType { get; } Type Type { get; } object GetValue(object instance); TValue GetValue<TValue>(object instance); void SetValue(object instance, object value); } }
mit
lanamolana/package
Lana/User/resources/views/profile/petugas.blade.php
984
@extends("LanaTemplate::one-column") @section("content") <div class="container"> <div class="col-md-12"> <h2>My Profile</h2> <br> <table class="table table-striped table-bordered table-hover table-condensed"> <thead> <th>No</th> <th>Nama</th> <th>NIP</th> <th>Alamat</th> <th>Email</th> <th>Telp</th> <th>Action</th> </thead> @foreach($profile as $index=>$profile) <tr> <th>{{ $index+1 }}</th> <th>{{ $profile->nama }}</th> <th>{{ $profile->nip }}</th> <th>{{ $profile->alamat }}</th> <th>{{ $profile->email }}</th> <th>{{ $profile->telp }}</th> <th> <a href="/profile/{{ $profile->id }}"><button class="btn btn-info btn-sm"> <span class="glyphicon glyphicon-info-sign" aria-hidden="true"> Info</span></button></a> <a href="{{ url("/profile/$profile->id/edit")}}"><button class="btn btn-success btn-sm"> <span class="glyphicon glyphicon-cog" aria-hidden="true"> Ubah</span></button></a> </th> </tr> @endforeach </table> </form> @stop
mit
lukeed/arr
tests/forEach.js
1032
'use strict'; const test = require('tape'); const fn = require('../packages/forEach'); const foo = ['a', 'b', 'c']; const bar = ['a', undefined, void 0, , 'b']; test('@arr/forEach', t => { let x='', y=''; fn(foo, (val, idx, arr) => { x += `${val}-${idx}-${arr.length}`; }); foo.forEach((val, idx, arr) => { y += `${val}-${idx}-${arr.length}`; }); t.equal(x, y, 'matches native output'); t.equal(x, 'a-0-3b-1-3c-2-3', 'is expected output'); let a = 0; fn(bar, _ => a++); t.equal(a, bar.length, 'iterates thru all slots; incl `undefined` & holes'); let b = 0; bar.forEach(_ => b++); t.notEqual(b, a, 'does not match native behavior; re: holes & undefined'); t.equal(b, 4, 'native iterates all except holes'); t.end(); }); test('@arr/forEach - callback', t => { let i = 0; fn(foo, (val, idx, arr) => { t.equal(val, foo[i], 'receives current value as 1st param'); t.equal(idx, i, 'receives current index as 2nd param'); t.deepEqual(arr, foo, 'receives array as 3rd param'); i++; }); t.end(); });
mit
chcbaram/FPGA
zap-2.3.0-windows/papilio-zap-ide/hardware/papilio/avr8/cores/arduino/HardwareSerial.cpp
8023
/* HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis */ #include <stdio.h> #include <string.h> #include <inttypes.h> #include "wiring.h" #include "wiring_private.h" #include "HardwareSerial.h" // Define constants and variables for buffering incoming serial data. We're // using a ring buffer (I think), in which rx_buffer_head is the index of the // location to which to write the next incoming character and rx_buffer_tail // is the index of the location from which to read. #define RX_BUFFER_SIZE 128 struct ring_buffer { unsigned char buffer[RX_BUFFER_SIZE]; //int head; //int tail; unsigned char head; unsigned char tail; }; ring_buffer rx_buffer = { { 0 }, 0, 0 }; #if defined(__AVR_ATmega1280__) ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; ring_buffer rx_buffer2 = { { 0 }, 0, 0 }; ring_buffer rx_buffer3 = { { 0 }, 0, 0 }; #endif inline void store_char(unsigned char c, ring_buffer *rx_buffer) { unsigned char i = rx_buffer->head + 1; i %= RX_BUFFER_SIZE; //int i = (rx_buffer->head + 1) % RX_BUFFER_SIZE; //JPG changed 7/11/2010 // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != rx_buffer->tail) { rx_buffer->buffer[rx_buffer->head] = c; rx_buffer->head = i; } } #if defined(__AVR_ATmega1280__) SIGNAL(SIG_USART0_RECV) { unsigned char c = UDR0; store_char(c, &rx_buffer); } SIGNAL(SIG_USART1_RECV) { unsigned char c = UDR1; store_char(c, &rx_buffer1); } SIGNAL(SIG_USART2_RECV) { unsigned char c = UDR2; store_char(c, &rx_buffer2); } SIGNAL(SIG_USART3_RECV) { unsigned char c = UDR3; store_char(c, &rx_buffer3); } #else #if defined(__AVR_ATmega8__) SIGNAL(SIG_UART_RECV) #elif defined(__AVR_ATmega103__) SIGNAL(SIG_UART_RECV) #else SIGNAL(USART_RX_vect) #endif { #if defined(__AVR_ATmega8__) unsigned char c = UDR; #elif defined(__AVR_ATmega103__) unsigned char c = UDR; #else unsigned char c = UDR0; #endif store_char(c, &rx_buffer); } #endif // Constructors //////////////////////////////////////////////////////////////// #if defined(__AVR_ATmega103__) HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrr, volatile uint8_t *ucr, volatile uint8_t *usr, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre) { _rx_buffer = rx_buffer; _ubrr = ubrr; _ucr = ucr; _usr = usr; _udr = udr; _rxen = rxen; _txen = txen; _rxcie = rxcie; _udre = udre; } #else HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x) { _rx_buffer = rx_buffer; _ubrrh = ubrrh; _ubrrl = ubrrl; _ucsra = ucsra; _ucsrb = ucsrb; _udr = udr; _rxen = rxen; _txen = txen; _rxcie = rxcie; _udre = udre; _u2x = u2x; } #endif // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(long baud) { uint16_t baud_setting; bool use_u2x; #if defined(__AVR_ATmega103__) // No U2X mode on ATmega103 baud_setting = (F_CPU / 8 / baud - 1) / 2; #else // U2X mode is needed for baud rates higher than (CPU Hz / 16) if (baud > F_CPU / 16) { use_u2x = true; } else { // figure out if U2X mode would allow for a better connection // calculate the percent difference between the baud-rate specified and // the real baud rate for both U2X and non-U2X mode (0-255 error percent) uint8_t nonu2x_baud_error = abs((int)(255-((F_CPU/(16*(((F_CPU/8/baud-1)/2)+1))*255)/baud))); uint8_t u2x_baud_error = abs((int)(255-((F_CPU/(8*(((F_CPU/4/baud-1)/2)+1))*255)/baud))); // prefer non-U2X mode because it handles clock skew better use_u2x = (nonu2x_baud_error > u2x_baud_error); } if (use_u2x) { *_ucsra = 1 << _u2x; baud_setting = (F_CPU / 4 / baud - 1) / 2; } else { *_ucsra = 0; baud_setting = (F_CPU / 8 / baud - 1) / 2; } #endif // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) #if defined(__AVR_ATmega103__) *_ubrr = baud_setting; sbi(*_ucr, _rxen); sbi(*_ucr, _txen); sbi(*_ucr, _rxcie); #else *_ubrrh = baud_setting >> 8; *_ubrrl = baud_setting; sbi(*_ucsrb, _rxen); sbi(*_ucsrb, _txen); sbi(*_ucsrb, _rxcie); #endif } void HardwareSerial::end() { #if defined(__AVR_ATmega103__) cbi(*_ucr, _rxen); cbi(*_ucr, _txen); cbi(*_ucr, _rxcie); #else cbi(*_ucsrb, _rxen); cbi(*_ucsrb, _txen); cbi(*_ucsrb, _rxcie); #endif } uint8_t HardwareSerial::available(void) { unsigned char i = RX_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail; i %= RX_BUFFER_SIZE; return i; //return (RX_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % RX_BUFFER_SIZE; //JPG changed 7/11/2010 } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; _rx_buffer->tail = (_rx_buffer->tail + 1); _rx_buffer->tail %= RX_BUFFER_SIZE; //_rx_buffer->tail = (_rx_buffer->tail + 1) % RX_BUFFER_SIZE; //JPG changed 7/11/2010 return c; } } void HardwareSerial::flush() { // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // were full, not empty. _rx_buffer->head = _rx_buffer->tail; } void HardwareSerial::write(uint8_t c) { #if defined(__AVR_ATmega103__) while (!((*_usr) & (1 << _udre))) ; #else while (!((*_ucsra) & (1 << _udre))) ; #endif *_udr = c; } // Preinstantiate Objects ////////////////////////////////////////////////////// #if defined(__AVR_ATmega8__) HardwareSerial Serial(&rx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRE, U2X); #elif defined(__AVR_ATmega103__) HardwareSerial Serial(&rx_buffer, &UBRR, &UCR, &USR, &UDR, RXEN, TXEN, RXCIE, UDRE); #else HardwareSerial Serial(&rx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRE0, U2X0); #endif #if defined(__AVR_ATmega1280__) HardwareSerial Serial1(&rx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRE1, U2X1); HardwareSerial Serial2(&rx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRE2, U2X2); HardwareSerial Serial3(&rx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRE3, U2X3); #endif
mit
Alec-WAM/CrystalMod
src/main/java/alec_wam/CrystalMod/entities/accessories/ModelWolfArmor.java
2485
package alec_wam.CrystalMod.entities.accessories; import alec_wam.CrystalMod.util.ModLogger; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.model.ModelWolf; import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class ModelWolfArmor extends ModelWolf { public ModelWolfArmor(float scale) { this.wolfHeadMain = new ModelRenderer(this, 0, 0); this.wolfHeadMain.addBox(-2, -3, -2, 6, 6, 4, scale); this.wolfHeadMain.setRotationPoint(-1, 13.5F, -7); this.wolfBody = new ModelRenderer(this, 18, 14); this.wolfBody.addBox(-3, -2, -3, 6, 9, 6, scale); this.wolfBody.setRotationPoint(0, 14, 2); this.wolfLeg1 = new ModelRenderer(this, 0, 18); this.wolfLeg1.addBox(0, 0, -1, 2, 8, 2, scale); this.wolfLeg1.setRotationPoint(-2.5F, 16, 7); this.wolfLeg2 = new ModelRenderer(this, 0, 18); this.wolfLeg2.addBox(0, 0, -1, 2, 8, 2, scale); this.wolfLeg2.setRotationPoint(0.5F, 16, 7); this.wolfLeg3 = new ModelRenderer(this, 0, 18); this.wolfLeg3.addBox(0, 0, -1, 2, 8, 2, scale); this.wolfLeg3.setRotationPoint(-2.5F, 16, -4); this.wolfLeg4 = new ModelRenderer(this, 0, 18); this.wolfLeg4.addBox(0, 0, -1, 2, 8, 2, scale); this.wolfLeg4.setRotationPoint(0.5F, 16, -4); this.wolfHeadMain.setTextureOffset(16, 14).addBox(-2, -5, 0, 2, 2, 1, scale); this.wolfHeadMain.setTextureOffset(16, 14).addBox(2, -5, 0, 2, 2, 1, scale); this.wolfHeadMain.setTextureOffset(0, 10).addBox(-0.5F, 0, -5, 3, 3, 4, scale); ModelRenderer wolfMane = new ModelRenderer(this, 21, 0); wolfMane.addBox(-3, -3, -3, 8, 6, 7, scale); wolfMane.setRotationPoint(-1, 14, 2); ModelRenderer wolfTail = new ModelRenderer(this, 9, 18); wolfTail.addBox(0, 0, -1, 2, 8, 2, scale); wolfTail.setRotationPoint(-1, 12, 8); try { ObfuscationReflectionHelper.setPrivateValue(ModelWolf.class, this, wolfTail, 6); ObfuscationReflectionHelper.setPrivateValue(ModelWolf.class, this, wolfMane, 7); } catch(Exception e){ ModLogger.error("Error while trying to access the needed fields in the ModelWolf class"); e.printStackTrace(); } } }
mit
AlloyTeam/Nuclear
components/icon/esm/highlight-off-rounded.js
547
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M13.89 8.7L12 10.59 10.11 8.7a.9959.9959 0 00-1.41 0c-.39.39-.39 1.02 0 1.41L10.59 12 8.7 13.89c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0L12 13.41l1.89 1.89c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L13.41 12l1.89-1.89c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.38-1.41 0zM12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" }), 'HighlightOffRounded');
mit
guiwoda/phpci-contracts
src/Builder.php
2597
<?php /** * PHPCI - Continuous Integration for PHP * * @copyright Copyright 2014, Block 8 Limited. * @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md * @link https://www.phptesting.org/ */ namespace PHPCI\Contracts; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; /** * PHPCI Builder Interface * @author Guido Contreras Woda <guiwoda@gmail.com> */ interface Builder { /** * Set the config array, as read from phpci.yml * * @param array|null $config * @return void * * @throws \Exception */ public function setConfigArray($config); /** * Access a variable from the phpci.yml file. * * @param string * * @return mixed */ public function getConfig($key); /** * Access a variable from the config.yml * * @param $key * * @return mixed */ public function getSystemConfig($key); /** * @return string The title of the project being built. */ public function getBuildProjectTitle(); /** * Run the active build. * @return void */ public function execute(); /** * Used by this class, and plugins, to execute shell commands. * @param ... All parameters will be passed through * @return bool Indicates success */ public function executeCommand(); /** * Returns the output from the last command run. * @return string */ public function getLastOutput(); /** * @param bool $enableLog * * @return void */ public function logExecOutput($enableLog = true); /** * Find a binary required by a plugin. * * @param $binary * * @return null|string */ public function findBinary($binary); /** * Replace every occurrence of the interpolation vars in the given string * Example: "This is build %PHPCI_BUILD%" => "This is build 182" * * @param string $input * * @return string */ public function interpolate($input); /** * Sets a logger instance on the object * * @param LoggerInterface $logger * * @return null */ public function setLogger(LoggerInterface $logger); /** * @param $message * @param string $level * @param array $context * * @return void */ public function log($message, $level = LogLevel::INFO, $context = []); /** * Add a success-coloured message to the log. * * @param string * @return void */ public function logSuccess($message); /** * Add a failure-coloured message to the log. * * @param string $message * @param \Exception $exception The exception that caused the error. * @return void */ public function logFailure($message, \Exception $exception = null); }
mit
Mangopay/mangopay2-java-sdk
src/main/java/com/mangopay/core/interfaces/BankAccountDetails.java
146
package com.mangopay.core.interfaces; /** * Marker interface for classes with bank account details. */ public interface BankAccountDetails { }
mit
Dutheil/AnagramGameFR
AnagramGameFR/Dependencies/Words.cs
395
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AnagramGameFR.Dependencies { public class Words { public Themes _theme { get; internal set; } public string _word { get; internal set; } public Words(Themes theme, string word) { this._theme = theme; this._word = word; } } }
mit
xtina-starr/force
src/desktop/apps/auction/components/artwork_browser/header/__tests__/HeaderMobile.test.js
1726
import renderTestComponent from "desktop/apps/auction/__tests__/utils/renderTestComponent" import HeaderMobile from "desktop/apps/auction/components/artwork_browser/header/HeaderMobile" import sinon from "sinon" const rewire = require("rewire")("../../../../actions/artworkBrowser") describe("auction/components/artwork_browser/header/HeaderMobile.test", () => { describe("<HeaderMobile />", () => { it("default sort is Default", () => { const { wrapper } = renderTestComponent({ Component: HeaderMobile, }) wrapper .find("select") .find("option") .first() .html() .should.containEql("Default") }) it("calls updateSort on select change", () => { const { wrapper } = renderTestComponent({ Component: HeaderMobile, }) const { store } = wrapper.props() const updateSort = "bidder_positions_count" const auctionQueries = { filter_sale_artworks: { aggregations: [ { slice: "ARTIST", counts: 10, }, { slice: "MEDIUM", counts: 13, }, ], counts: 10, hits: [ { artwork: { _id: "foo", }, }, ], }, } const resetRewire = rewire.__set__( "metaphysics", sinon.stub().returns(Promise.resolve(auctionQueries)) ) wrapper.find("select").simulate("change", { target: { value: updateSort, }, }) store.getState().artworkBrowser.filterParams.sort.should.eql(updateSort) resetRewire() }) }) })
mit
muyinchen/migoShop
migo-sso/src/main/java/com/migo/sso/controller/LoginController.java
2667
package com.migo.sso.controller; import com.migo.pojo.MigoResult; import com.migo.sso.service.LoginService; import com.migo.utils.ExceptionUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.converter.json.MappingJacksonValue; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Author 知秋 * Created by kauw on 2016/10/27. */ @RestController public class LoginController { @Autowired private LoginService loginService; @RequestMapping(value = "/user/login",method = RequestMethod.POST) public MigoResult login(String username, String password, HttpServletRequest request, HttpServletResponse response){ try { MigoResult result = loginService.login(username, password, request, response); return result; } catch (Exception e) { e.printStackTrace(); return MigoResult.build(500, ExceptionUtil.getStackTrace(e)); } } @RequestMapping("/user/token/{token}") public Object getUserByToken(@PathVariable String token,String callback){ try { MigoResult userByToken = loginService.getUserByToken(token); if (!StringUtils.isEmpty(callback)){ //支持jsonp调用 MappingJacksonValue mappingJacksonValue=new MappingJacksonValue(userByToken); mappingJacksonValue.setJsonpFunction(callback); return mappingJacksonValue; } return userByToken; } catch (Exception e) { e.printStackTrace(); return MigoResult.build(500,ExceptionUtil.getStackTrace(e)); } } @RequestMapping("/user/logout/{token}") public Object logoutByToken(@PathVariable String token,String callback){ try{ MigoResult result = loginService.loginoutByToken(token); if (!StringUtils.isEmpty(callback)){ //支持jsonp调用 MappingJacksonValue mappingJacksonValue=new MappingJacksonValue(result); mappingJacksonValue.setJsonpFunction(callback); return mappingJacksonValue; } return result; } catch (Exception e) { e.printStackTrace(); return MigoResult.build(500,ExceptionUtil.getStackTrace(e)); } } }
mit
cristianosoares/Sistema-Dotz
application/forms/VisualizarDestinatario.php
6823
<?php class Application_Form_VisualizarDestinatario extends Zend_Form { public function init() { /* Form Elements & Other Definitions Here ... */ $this->setName('FormularioDestinatario'); $id = new Zend_Form_Element_Hidden('fk_pedido'); $id->addFilter('Int'); $documento = new Zend_Form_Element_Text('documento'); $documento->setLabel('Documento(CPF/CNPJ)') ->setRequired(true) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $documento->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control') ->setAttrib("disable", array(1)); $tipopessoa= new Zend_Form_Element_Select('tipopessoa'); $tipopessoa->setAttrib('class', 'form-control')->setAttrib("disable", array(1)); $tipopessoa->setLabel('Tipo de Pessoa')->setRequired(true); $tipopessoa->setMultiOptions( array("F"=>"Física","J"=>"Júridica") ); $nome = new Zend_Form_Element_Text('nome'); $nome->setLabel('Nome') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags')->setAttrib("disable", array(1)) ->addFilter('StringTrim') ->addValidator('NotEmpty'); $nome->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $email = new Zend_Form_Element_Text('email'); $email->setLabel('E-mail') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $email->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $rua = new Zend_Form_Element_Text('rua'); $rua->setLabel('Rua') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $rua->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $numero = new Zend_Form_Element_Text('numero'); $numero->setLabel('Número') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $numero->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $compl = new Zend_Form_Element_Text('compl'); $compl->setLabel('Complemento') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $compl->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $bairro = new Zend_Form_Element_Text('bairro'); $bairro->setLabel('Bairro') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $bairro->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $cidade = new Zend_Form_Element_Text('cidade'); $cidade->setLabel('Cidade') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $cidade->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $uf = new Zend_Form_Element_Text('uf'); $uf->setLabel('UF') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $uf->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $cep = new Zend_Form_Element_Text('cep'); $cep->setLabel('CEP') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $cep->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $ddd = new Zend_Form_Element_Text('ddd'); $ddd->setLabel('DDD') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $ddd->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $telefone = new Zend_Form_Element_Text('telefone'); $telefone->setLabel('Telefone') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $telefone->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $pontoreferencia = new Zend_Form_Element_Text('pontoreferencia'); $pontoreferencia->setLabel('Ponto refêrencia') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $pontoreferencia->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $codigoident = new Zend_Form_Element_Text('codigoident'); $codigoident->setLabel('Código de identificação do usuário') ->setRequired(true)->setAttrib("disable", array(1)) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator('NotEmpty'); $codigoident->removeDecorator('DtDdWrapper') ->removeDecorator('HtmlTag') ->setAttrib('class', 'form-control'); $this->addElements(array($id,$documento,$tipopessoa,$nome,$email,$rua,$numero,$compl,$bairro,$cidade,$uf,$cep,$ddd,$telefone,$pontoreferencia,$codigoident)); $this->setDecorators( array( array('ViewScript', array('viewScript' => 'formularioVisualizarDestinatario.phtml')))); } }
mit
yannisgu/capercali
src/Capercali.WPF/ViewModel/EventRunners/EditEventRunnerViewModel.cs
1521
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Windows.Navigation; using Capercali.DataAccess.Services; using Capercali.Entities; using Capercali.WPF.ViewModel.Main; using ReactiveUI; namespace Capercali.WPF.ViewModel.EventRunners { public class EditEventRunnerViewModel : ReactiveObject { public IReactiveDerivedList<Course> Courses { get; private set; } public Event Event { get; set; } private ObservableAsPropertyHelper<bool> isEnabledProperty; public bool IsEnabled { get { return isEnabledProperty.Value; } } public EditEventRunnerViewModel(EventRunner runner, IReactiveDerivedList<Course> courses) { this.Courses = courses; isEnabled = this.ObservableForProperty(_ => _.Runner).Select(_ => _.Value != null); isEnabled.ToProperty(this, _ => _.IsEnabled, out isEnabledProperty); Runner = runner; InitCommands(); } private void InitCommands() { Save = new ReactiveCommand(isEnabled); Cancel = new ReactiveCommand(isEnabled); } public ReactiveCommand Cancel { get; private set; } private EventRunner runner; private IObservable<bool> isEnabled; public EventRunner Runner { get { return runner; } set { this.RaiseAndSetIfChanged(ref runner, value); } } public ReactiveCommand Save { get; private set; } } }
mit
potworny/design-patterns
src/ObserverPatternBundle/ObserverPatternBundle.php
137
<?php namespace ObserverPatternBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class ObserverPatternBundle extends Bundle { }
mit
espadana/surveyjs
src/entries/chunks/localization.ts
35
import '../../localization/farsi';
mit
the-blue-alliance/the-blue-alliance
src/backend/tasks_io/datafeeds/parsers/fms_api/tests/test_fms_api_match_tiebreaker.py
25352
import datetime from unittest.mock import Mock import pytest from google.appengine.ext import ndb from google.auth.credentials import AnonymousCredentials from backend.common.consts.alliance_color import AllianceColor from backend.common.consts.comp_level import CompLevel from backend.common.helpers.match_helper import MatchHelper from backend.common.manipulators.match_manipulator import MatchManipulator from backend.common.models.event import Event from backend.common.models.match import Match from backend.common.sitevars.fms_api_secrets import ( ContentType as FMSApiSecretsContentType, ) from backend.common.sitevars.fms_api_secrets import FMSApiSecrets from backend.common.storage.clients.gcloud_client import GCloudStorageClient from backend.tasks_io.datafeeds.datafeed_fms_api import DatafeedFMSAPI @pytest.fixture(autouse=True) def fms_api_secrets(ndb_stub) -> None: FMSApiSecrets.put(FMSApiSecretsContentType(username="zach", authkey="authkey")) @pytest.fixture(autouse=True) def force_prod_gcs_client(monkeypatch: pytest.MonkeyPatch) -> None: from backend.common import storage credentials = AnonymousCredentials() client_fn = Mock() client_fn.return_value = GCloudStorageClient( "tbatv-prod-hrd", credentials=credentials ) monkeypatch.setattr(storage, "_client_for_env", client_fn) def test_2017flwp_sequence(ndb_stub, taskqueue_stub) -> None: from backend.common.storage import ( get_files as cloud_storage_get_files, ) event = Event( id="2017flwp", event_short="flwp", year=2017, event_type_enum=0, timezone_id="America/New_York", ) event.put() event_code = "flwp" file_prefix = "frc-api-response/v2.0/2017/schedule/{}/playoff/hybrid/".format( event_code ) gcs_files = cloud_storage_get_files(file_prefix) for filename in gcs_files: time_str = filename.replace(file_prefix, "").replace(".json", "").strip() file_time = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S.%f") query_time = file_time + datetime.timedelta(seconds=30) MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=query_time, sim_api_version="v2.0" ).get_event_matches("2017{}".format(event_code)), run_post_update_hook=False, ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) sf_matches = Match.query( Match.event == ndb.Key(Event, "2017flwp"), Match.comp_level == "sf" ).fetch() assert len(sf_matches) == 7 sf1m1 = Match.get_by_id("2017flwp_sf1m1") assert sf1m1 is not None assert sf1m1.alliances[AllianceColor.RED]["score"] == 305 assert sf1m1.alliances[AllianceColor.BLUE]["score"] == 255 m1_breakdown = sf1m1.score_breakdown assert m1_breakdown is not None assert m1_breakdown[AllianceColor.RED]["totalPoints"] == 305 assert m1_breakdown[AllianceColor.BLUE]["totalPoints"] == 255 sf1m2 = Match.get_by_id("2017flwp_sf1m2") assert sf1m2 is not None assert sf1m2.alliances[AllianceColor.RED]["score"] == 165 assert sf1m2.alliances[AllianceColor.BLUE]["score"] == 258 m2_breakdown = sf1m2.score_breakdown assert m2_breakdown is not None assert m2_breakdown[AllianceColor.RED]["totalPoints"] == 165 assert m2_breakdown[AllianceColor.BLUE]["totalPoints"] == 258 sf1m3 = Match.get_by_id("2017flwp_sf1m3") assert sf1m3 is not None assert sf1m3.alliances[AllianceColor.RED]["score"] == 255 assert sf1m3.alliances[AllianceColor.BLUE]["score"] == 255 m3_breakdown = sf1m3.score_breakdown assert m3_breakdown is not None assert m3_breakdown[AllianceColor.RED]["totalPoints"] == 255 assert m3_breakdown[AllianceColor.BLUE]["totalPoints"] == 255 sf1m4 = Match.get_by_id("2017flwp_sf1m4") assert sf1m4 is not None assert sf1m4.alliances[AllianceColor.RED]["score"] == 255 assert sf1m4.alliances[AllianceColor.BLUE]["score"] == 255 m4_breakdown = sf1m4.score_breakdown assert m4_breakdown is not None assert m4_breakdown[AllianceColor.RED]["totalPoints"] == 255 assert m4_breakdown[AllianceColor.BLUE]["totalPoints"] == 255 sf1m5 = Match.get_by_id("2017flwp_sf1m5") assert sf1m5 is not None assert sf1m5.alliances[AllianceColor.RED]["score"] == 165 assert sf1m5.alliances[AllianceColor.BLUE]["score"] == 263 m5_breakdown = sf1m5.score_breakdown assert m5_breakdown is not None assert m5_breakdown[AllianceColor.RED]["totalPoints"] == 165 assert m5_breakdown[AllianceColor.BLUE]["totalPoints"] == 263 def test_2017flwp(ndb_stub, taskqueue_stub) -> None: event = Event( id="2017flwp", event_short="flwp", year=2017, event_type_enum=0, timezone_id="America/New_York", ) event.put() MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 4, 21, 22), sim_api_version="v2.0" ).get_event_matches("2017flwp") ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) sf_matches = Match.query( Match.event == ndb.Key(Event, "2017flwp"), Match.comp_level == "sf" ).fetch() assert len(sf_matches) == 5 old_match = Match.get_by_id("2017flwp_sf1m3") assert old_match is not None assert old_match.alliances[AllianceColor.RED]["score"] == 255 assert old_match.alliances[AllianceColor.BLUE]["score"] == 255 breakdown = old_match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 255 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 255 ndb.get_context().clear_cache() # Prevent data from leaking between tests MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 4, 21, 35), sim_api_version="v2.0" ).get_event_matches("2017flwp") ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) sf_matches = Match.query( Match.event == ndb.Key(Event, "2017flwp"), Match.comp_level == "sf" ).fetch() assert len(sf_matches) == 6 new_match = Match.get_by_id("2017flwp_sf1m3") assert new_match is not None assert old_match.alliances == new_match.alliances assert old_match.score_breakdown == new_match.score_breakdown tiebreaker_match = Match.get_by_id("2017flwp_sf1m4") assert tiebreaker_match is not None assert tiebreaker_match.alliances[AllianceColor.RED]["score"] == 165 assert tiebreaker_match.alliances[AllianceColor.BLUE]["score"] == 263 breakdown = tiebreaker_match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 165 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 263 def test_2017pahat(ndb_stub, taskqueue_stub) -> None: event = Event( id="2017pahat", event_short="pahat", year=2017, event_type_enum=0, timezone_id="America/New_York", ) event.put() matches = DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 5, 20, 45), sim_api_version="v2.0" ).get_event_matches("2017pahat") MatchManipulator.createOrUpdate(matches) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) f_matches = Match.query( Match.event == ndb.Key(Event, "2017pahat"), Match.comp_level == CompLevel.F ).fetch() assert len(f_matches) == 3 old_match = Match.get_by_id("2017pahat_f1m2") assert old_match is not None assert old_match.alliances[AllianceColor.RED]["score"] == 255 assert old_match.alliances[AllianceColor.BLUE]["score"] == 255 breakdown = old_match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 255 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 255 ndb.get_context().clear_cache() # Prevent data from leaking between tests MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 5, 21, 2), sim_api_version="v2.0" ).get_event_matches("2017pahat") ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) f_matches = Match.query( Match.event == ndb.Key(Event, "2017pahat"), Match.comp_level == "f" ).fetch() assert len(f_matches) == 4 new_match = Match.get_by_id("2017pahat_f1m2") assert new_match is not None assert old_match.alliances == new_match.alliances assert old_match.score_breakdown == new_match.score_breakdown tiebreaker_match = Match.get_by_id("2017pahat_f1m4") assert tiebreaker_match is not None assert tiebreaker_match.alliances[AllianceColor.RED]["score"] == 240 assert tiebreaker_match.alliances[AllianceColor.BLUE]["score"] == 235 breakdown = tiebreaker_match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 240 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 235 def test_2017scmb_sequence(ndb_stub, taskqueue_stub) -> None: from backend.common.storage import ( get_files as cloud_storage_get_files, ) event = Event( id="2017scmb", event_short="scmb", year=2017, event_type_enum=0, timezone_id="America/New_York", ) event.put() event_code = "scmb" file_prefix = "frc-api-response/v2.0/2017/schedule/{}/playoff/hybrid/".format( event_code ) gcs_files = cloud_storage_get_files(file_prefix) for filename in gcs_files: time_str = filename.replace(file_prefix, "").replace(".json", "").strip() file_time = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S.%f") query_time = file_time + datetime.timedelta(seconds=30) MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=query_time, sim_api_version="v2.0" ).get_event_matches("2017{}".format(event_code)), run_post_update_hook=False, ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) qf_matches = Match.query( Match.event == ndb.Key(Event, "2017scmb"), Match.comp_level == "qf" ).fetch() assert len(qf_matches) == 11 sf_matches = Match.query( Match.event == ndb.Key(Event, "2017scmb"), Match.comp_level == "sf" ).fetch() assert len(sf_matches) == 4 f_matches = Match.query( Match.event == ndb.Key(Event, "2017scmb"), Match.comp_level == "f" ).fetch() assert len(f_matches) == 3 qf4m1 = Match.get_by_id("2017scmb_qf4m1") assert qf4m1 is not None assert qf4m1.alliances[AllianceColor.RED]["score"] == 305 assert qf4m1.alliances[AllianceColor.BLUE]["score"] == 305 m1_breakdown = qf4m1.score_breakdown assert m1_breakdown is not None assert m1_breakdown[AllianceColor.RED]["totalPoints"] == 305 assert m1_breakdown[AllianceColor.BLUE]["totalPoints"] == 305 qf4m2 = Match.get_by_id("2017scmb_qf4m2") assert qf4m2 is not None assert qf4m2.alliances[AllianceColor.RED]["score"] == 213 assert qf4m2.alliances[AllianceColor.BLUE]["score"] == 305 m2_breakdown = qf4m2.score_breakdown assert m2_breakdown is not None assert m2_breakdown[AllianceColor.RED]["totalPoints"] == 213 assert m2_breakdown[AllianceColor.BLUE]["totalPoints"] == 305 qf4m3 = Match.get_by_id("2017scmb_qf4m3") assert qf4m3 is not None assert qf4m3.alliances[AllianceColor.RED]["score"] == 312 assert qf4m3.alliances[AllianceColor.BLUE]["score"] == 255 m3_breakdown = qf4m3.score_breakdown assert m3_breakdown is not None assert m3_breakdown[AllianceColor.RED]["totalPoints"] == 312 assert m3_breakdown[AllianceColor.BLUE]["totalPoints"] == 255 qf4m4 = Match.get_by_id("2017scmb_qf4m4") assert qf4m4 is not None assert qf4m4.alliances[AllianceColor.RED]["score"] == 310 assert qf4m4.alliances[AllianceColor.BLUE]["score"] == 306 m4_breakdown = qf4m4.score_breakdown assert m4_breakdown is not None assert m4_breakdown[AllianceColor.RED]["totalPoints"] == 310 assert m4_breakdown[AllianceColor.BLUE]["totalPoints"] == 306 def test_2017scmb(ndb_stub, taskqueue_stub) -> None: event = Event( id="2017scmb", event_short="scmb", year=2017, event_type_enum=0, timezone_id="America/New_York", ) event.put() MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 4, 19, 17), sim_api_version="v2.0" ).get_event_matches("2017scmb") ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) qf_matches = Match.query( Match.event == ndb.Key(Event, "2017scmb"), Match.comp_level == "qf" ).fetch() assert len(qf_matches) == 12 match = Match.get_by_id("2017scmb_qf4m1") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 305 assert match.alliances[AllianceColor.BLUE]["score"] == 305 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 305 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 305 ndb.get_context().clear_cache() # Prevent data from leaking between tests MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 4, 19, 50), sim_api_version="v2.0" ).get_event_matches("2017scmb") ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) qf_matches = Match.query( Match.event == ndb.Key(Event, "2017scmb"), Match.comp_level == "qf" ).fetch() assert len(qf_matches) == 12 match = Match.get_by_id("2017scmb_qf4m1") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 305 assert match.alliances[AllianceColor.BLUE]["score"] == 305 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 305 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 305 match = Match.get_by_id("2017scmb_qf4m2") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 213 assert match.alliances[AllianceColor.BLUE]["score"] == 305 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 213 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 305 ndb.get_context().clear_cache() # Prevent data from leaking between tests MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 4, 20, 12), sim_api_version="v2.0" ).get_event_matches("2017scmb") ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) qf_matches = Match.query( Match.event == ndb.Key(Event, "2017scmb"), Match.comp_level == "qf" ).fetch() assert len(qf_matches) == 12 match = Match.get_by_id("2017scmb_qf4m1") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 305 assert match.alliances[AllianceColor.BLUE]["score"] == 305 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 305 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 305 match = Match.get_by_id("2017scmb_qf4m2") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 213 assert match.alliances[AllianceColor.BLUE]["score"] == 305 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 213 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 305 match = Match.get_by_id("2017scmb_qf4m3") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 312 assert match.alliances[AllianceColor.BLUE]["score"] == 255 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 312 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 255 ndb.get_context().clear_cache() # Prevent data from leaking between tests MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 4, 20, 48), sim_api_version="v2.0" ).get_event_matches("2017scmb") ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) qf_matches = Match.query( Match.event == ndb.Key(Event, "2017scmb"), Match.comp_level == "qf" ).fetch() assert len(qf_matches) == 13 match = Match.get_by_id("2017scmb_qf4m1") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 305 assert match.alliances[AllianceColor.BLUE]["score"] == 305 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 305 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 305 match = Match.get_by_id("2017scmb_qf4m2") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 213 assert match.alliances[AllianceColor.BLUE]["score"] == 305 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 213 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 305 match = Match.get_by_id("2017scmb_qf4m3") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 312 assert match.alliances[AllianceColor.BLUE]["score"] == 255 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 312 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 255 match = Match.get_by_id("2017scmb_qf4m4") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 310 assert match.alliances[AllianceColor.BLUE]["score"] == 306 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 310 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 306 def test_2017ncwin(ndb_stub, taskqueue_stub) -> None: event = Event( id="2017ncwin", event_short="ncwin", year=2017, event_type_enum=0, timezone_id="America/New_York", ) event.put() MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 5, 21, 2), sim_api_version="v2.0" ).get_event_matches("2017ncwin") ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) sf_matches = Match.query( Match.event == ndb.Key(Event, "2017ncwin"), Match.comp_level == "sf" ).fetch() assert len(sf_matches) == 6 match = Match.get_by_id("2017ncwin_sf2m1") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 265 assert match.alliances[AllianceColor.BLUE]["score"] == 150 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 265 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 150 ndb.get_context().clear_cache() # Prevent data from leaking between tests MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 5, 21, 30), sim_api_version="v2.0" ).get_event_matches("2017ncwin") ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) sf_matches = Match.query( Match.event == ndb.Key(Event, "2017ncwin"), Match.comp_level == "sf" ).fetch() assert len(sf_matches) == 6 match = Match.get_by_id("2017ncwin_sf2m1") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 265 assert match.alliances[AllianceColor.BLUE]["score"] == 150 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 265 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 150 match = Match.get_by_id("2017ncwin_sf2m2") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 205 assert match.alliances[AllianceColor.BLUE]["score"] == 205 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 205 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 205 ndb.get_context().clear_cache() # Prevent data from leaking between tests MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 5, 21, 35), sim_api_version="v2.0" ).get_event_matches("2017ncwin") ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) sf_matches = Match.query( Match.event == ndb.Key(Event, "2017ncwin"), Match.comp_level == "sf" ).fetch() assert len(sf_matches) == 6 match = Match.get_by_id("2017ncwin_sf2m1") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 265 assert match.alliances[AllianceColor.BLUE]["score"] == 150 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 265 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 150 match = Match.get_by_id("2017ncwin_sf2m2") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 205 assert match.alliances[AllianceColor.BLUE]["score"] == 205 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 205 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 205 match = Match.get_by_id("2017ncwin_sf2m3") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 145 assert match.alliances[AllianceColor.BLUE]["score"] == 265 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 145 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 265 ndb.get_context().clear_cache() # Prevent data from leaking between tests MatchManipulator.createOrUpdate( DatafeedFMSAPI( sim_time=datetime.datetime(2017, 3, 5, 21, 51), sim_api_version="v2.0" ).get_event_matches("2017ncwin") ) _, keys_to_delete = MatchHelper.delete_invalid_matches(event.matches, event) MatchManipulator.delete_keys(keys_to_delete) sf_matches = Match.query( Match.event == ndb.Key(Event, "2017ncwin"), Match.comp_level == "sf" ).fetch() assert len(sf_matches) == 7 match = Match.get_by_id("2017ncwin_sf2m1") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 265 assert match.alliances[AllianceColor.BLUE]["score"] == 150 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 265 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 150 match = Match.get_by_id("2017ncwin_sf2m2") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 205 assert match.alliances[AllianceColor.BLUE]["score"] == 205 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 205 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 205 match = Match.get_by_id("2017ncwin_sf2m3") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 145 assert match.alliances[AllianceColor.BLUE]["score"] == 265 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 145 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 265 match = Match.get_by_id("2017ncwin_sf2m4") assert match is not None assert match.alliances[AllianceColor.RED]["score"] == 180 assert match.alliances[AllianceColor.BLUE]["score"] == 305 breakdown = match.score_breakdown assert breakdown is not None assert breakdown[AllianceColor.RED]["totalPoints"] == 180 assert breakdown[AllianceColor.BLUE]["totalPoints"] == 305
mit
reunono/CorgiEngineExtensions
MultipleWeapons/MultipleWeaponsInputManager.cs
2326
using MoreMountains.CorgiEngine; using MoreMountains.Tools; using UnityEngine; namespace CorgiEngineExtensions { [AddComponentMenu("Corgi Engine/Managers/Multiple Weapons Input Manager")] public class MultipleWeaponsInputManager : InputManager { // how many weapons a single character can handle at once public int MaximumNumberOfWeapons = 3; public MMInput.IMButton[] ShootButtons; public MMInput.IMButton[] ReloadButtons; public MMInput.ButtonStates[] ShootAxes { get; protected set; } protected string[] _axesShoot; protected override void Awake() { ShootButtons = new MMInput.IMButton[MaximumNumberOfWeapons]; ReloadButtons = new MMInput.IMButton[MaximumNumberOfWeapons]; ShootAxes = new MMInput.ButtonStates[MaximumNumberOfWeapons]; _axesShoot = new string[MaximumNumberOfWeapons]; base.Awake(); } protected override void InitializeButtons() { base.InitializeButtons(); ShootButtons[0] = ShootButton; ReloadButtons[0] = ReloadButton; ShootButtons[1] = SecondaryShootButton; ButtonList.Add(ReloadButtons[1] = new MMInput.IMButton (PlayerID, "Reload2")); for (var i = 2; i < MaximumNumberOfWeapons; i++) { ButtonList.Add(ShootButtons[i] = new MMInput.IMButton(PlayerID, "Shoot" + (i + 1))); ButtonList.Add(ReloadButtons[i] = new MMInput.IMButton (PlayerID, "Reload" + (i + 1))); } } protected override void InitializeAxis() { base.InitializeAxis(); _axesShoot[0] = _axisShoot; _axesShoot[1] = _axisShootSecondary; for (var i = 2; i < MaximumNumberOfWeapons; i++) _axesShoot[i] = PlayerID + "_ShootAxis" + (i + 1); } protected override void SetShootAxis() { base.SetShootAxis(); if (IsMobile || !InputDetectionActive) return; ShootAxes[0] = ShootAxis; ShootAxes[1] = SecondaryShootAxis; for (var i = 2; i < MaximumNumberOfWeapons; i++) ShootAxes[i] = MMInput.ProcessAxisAsButton(_axesShoot[i], Threshold.y, ShootAxes[i]); } } }
mit
Delinero/php-rabbitmq
src/ClientInterface.php
338
<?php /** * @author Levin Mauritz <l.mauritz@delinero.de> * */ namespace PhpRabbitMq; interface ClientInterface { public function publish($data, string $routingKey, string $exchange = ''); public function rpcCall($data, string $routingKey, string $exchange = '', int $timeout = 30); public function getConnection(); }
mit
KataevAlexander/Silex-Controllers
application/core/vendor/traits/LocalizationTrait.php
721
<?php namespace core\vendor\traits; use Symfony\Component\Yaml\Yaml; trait LocalizationTrait { public function addLocalization($path, $locale = null) { $locale = is_null($locale) ? $this['locale'] : $locale; $way = sprintf('%s/data/localization/%s/%s.yml', DR, trim($path, '/'), $locale); if (file_exists($way)) { $this['translator']->addResource('yaml', $way, $locale); } } public function getLocalization($path, $locale = null) { $locale = is_null($locale) ? $this['locale'] : $locale; $way = sprintf('%s/data/localization/%s/%s.yml', DR, trim($path, '/'), $locale); if (file_exists($way)) { return Yaml::parse($way); } } }
mit
aindenko/awsforumapi
src/AppBundle/DependencyInjection/Configuration.php
402
<?php namespace AppBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $treeBuilder->root('app_bundle'); return $treeBuilder; } }
mit
N4SJAMK/alkobot
index.js
1334
import request from 'superagent'; import { scheduleJob } from 'node-schedule'; const MONDAY = 1; const TUESDAY = 2; const WEDNESDAY = 3; const THURSDAY = 4; const FRIDAY = 5; const SATURDAY = 6; const SUNDAY = 0; /** * */ const beer = [ 'http://media.riemurasia.net/albumit/mmedia/3g/gok/xixk/200436/1116801310.jpg', 'http://files.fitfashion.fi/wp-content/uploads/sites/18/2015/02/file.jpg', 'http://media.riemurasia.net/albumit/mmedia/7u/rnh/6aem/28955/1066601341.jpg', 'http://scontent-a.cdninstagram.com/hphotos-xfa1/t51.2885-15/10748476_1389343018023971_541246281_a.jpg', ] function postSlackMessage(content) { request.post('https://slack.com/api/chat.postMessage') .query({ text: content }) .query({ token: process.env.SLACK_API_TOKEN }) .query({ channel: '#yleinen' }) .query({ as_user: true }) .end(err => err ? console.log(err) : null) } /** * */ scheduleJob({ hour: 14, minute: 0 }, () => { switch(new Date().getDay()) { case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: postSlackMessage(beer[Math.floor(Math.random() * beer.length)]); break; case FRIDAY: case SATURDAY: postSlackMessage('https://www.youtube.com/watch?v=GpP0DOYy9IA'); break; case SUNDAY: postSlackMessage('https://www.youtube.com/watch?v=2vtwkQcHA1I'); break; } });
mit
qvazzler/Flexget
flexget/plugins/output/sms_ru.py
3532
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin import logging import hashlib from flexget import plugin from flexget.event import event from flexget.utils.template import RenderError log = logging.getLogger("sms_ru") sms_send_url = "http://sms.ru/sms/send" sms_token_url = "http://sms.ru/auth/get_token" class OutputSMSru(object): """ Sends SMS notification through sms.ru http api sms/send. Phone number is a login assigned to sms.ru account. Example: sms_ru: phonenumber: <PHONE_NUMBER> (accepted format example: "79997776655") password: <PASSWORD> [message: <MESSAGE_TEXT>] (default: "accepted {{title}}" -- accepts Jinja) Configuration parameters are also supported from entries (eg. through set). """ schema = { 'type': 'object', 'properties': { 'phonenumber': {'type': 'string'}, 'password': {'type': 'string'}, 'message': {'type': 'string', 'default': 'accepted {{title}}'} }, 'additionalProperties': False, 'required': ['phonenumber', 'password'] } # Run last to make sure other outputs are successful before sending notification @plugin.priority(0) def on_task_output(self, task, config): # Get the parameters config = self.prepare_config(config) phonenumber = config["phonenumber"] password = config["password"] # Backend provides temporary token token_response = task.requests.get(sms_token_url, raise_status=False) if token_response.status_code == 200: log.debug("Got auth token") # Auth method without api_id based on hash of password combined with token sha512 = hashlib.sha512(password + token_response.text).hexdigest() else: log.error("Error getting auth token") # Loop through the accepted entries for entry in task.accepted: # Set message from entry message = config["message"] # Attempt to render the message field try: message = entry.render(message) except RenderError as e: log.debug("Problem rendering 'message': %s" % e) message = "accepted %s" % entry["title"] # Check for test mode if task.options.test: log.info("Test mode. Processing for %s" % phonenumber) log.info("Message: %s" % message) # Build request params send_params = {'login': phonenumber, 'sha512': sha512, 'token': token_response.text, 'to': phonenumber, 'text': message} if task.options.test: send_params.update({'test': 1}) # Make the request response = task.requests.get(sms_send_url, params=send_params, raise_status=False) # Get resul code from sms.ru backend returned in body result_text = response.text # Check if it succeeded if response.text.find("100") == 0: log.debug("SMS notification for %s sent" % phonenumber) else: log.error("SMS was not sent. Server response was %s" % response.text) @event('plugin.register') def register_plugin(): plugin.register(OutputSMSru, "sms_ru", api_ver=2)
mit
arkon/Markus
app/models/assignment.rb
38372
require 'csv_invalid_line_error' class Assignment < ActiveRecord::Base include RepositoryHelper MIN_PEER_REVIEWS_PER_GROUP = 1 has_many :rubric_criteria, -> { order(:position) }, class_name: 'RubricCriterion', dependent: :destroy has_many :flexible_criteria, -> { order(:position) }, class_name: 'FlexibleCriterion', dependent: :destroy has_many :checkbox_criteria, -> { order(:position) }, class_name: 'CheckboxCriterion', dependent: :destroy has_many :test_support_files, dependent: :destroy accepts_nested_attributes_for :test_support_files, allow_destroy: true has_many :test_scripts, dependent: :destroy accepts_nested_attributes_for :test_scripts, allow_destroy: true has_many :annotation_categories, -> { order(:position) }, class_name: 'AnnotationCategory', dependent: :destroy has_many :criterion_ta_associations, dependent: :destroy has_many :assignment_files, dependent: :destroy accepts_nested_attributes_for :assignment_files, allow_destroy: true validates_associated :assignment_files has_one :assignment_stat, dependent: :destroy accepts_nested_attributes_for :assignment_stat, allow_destroy: true validates_associated :assignment_stat # Because of app/views/main/_grade_distribution_graph.html.erb:25 validates_presence_of :assignment_stat # Assignments can now refer to themselves, where this is null if there # is no parent (the same holds for the child peer reviews) belongs_to :parent_assignment, class_name: 'Assignment', inverse_of: :pr_assignment has_one :pr_assignment, class_name: 'Assignment', foreign_key: :parent_assignment_id, inverse_of: :parent_assignment has_many :peer_reviews, through: :groupings has_many :pr_peer_reviews, through: :parent_assignment, source: :peer_reviews has_many :annotation_categories, -> { order(:position) }, class_name: 'AnnotationCategory', dependent: :destroy has_many :groupings has_many :ta_memberships, through: :groupings has_many :student_memberships, through: :groupings has_many :tokens, through: :groupings has_many :submissions, through: :groupings has_many :groups, through: :groupings has_many :notes, as: :noteable, dependent: :destroy has_many :section_due_dates accepts_nested_attributes_for :section_due_dates has_one :exam_template, dependent: :destroy validates_uniqueness_of :short_identifier, case_sensitive: true validates_numericality_of :group_min, only_integer: true, greater_than: 0 validates_numericality_of :group_max, only_integer: true, greater_than: 0 has_one :submission_rule, dependent: :destroy, inverse_of: :assignment accepts_nested_attributes_for :submission_rule, allow_destroy: true validates_associated :submission_rule validates_presence_of :submission_rule validates_presence_of :short_identifier validates_presence_of :description validates_presence_of :repository_folder validates_presence_of :due_date validates_presence_of :group_min validates_presence_of :group_max validates_presence_of :notes_count validates_presence_of :assignment_stat # "validates_presence_of" for boolean values. validates_inclusion_of :allow_web_submits, in: [true, false] validates_inclusion_of :vcs_submit, in: [true, false] validates_inclusion_of :display_grader_names_to_students, in: [true, false] validates_inclusion_of :is_hidden, in: [true, false] validates_inclusion_of :has_peer_review, in: [true, false] validates_inclusion_of :assign_graders_to_criteria, in: [true, false] validates_inclusion_of :enable_test, in: [true, false] validates_inclusion_of :enable_student_tests, in: [true, false], if: :enable_test validates_inclusion_of :non_regenerating_tokens, in: [true, false], if: :enable_student_tests validates_inclusion_of :unlimited_tokens, in: [true, false], if: :enable_student_tests validates_presence_of :token_start_date, if: :enable_student_tests with_options if: ->{ :enable_student_tests && !:unlimited_tokens } do |assignment| assignment.validates :tokens_per_period, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 } end with_options if: ->{ !:non_regenerating_tokens && :enable_student_tests && !unlimited_tokens} do |assignment| assignment.validates :token_period, presence: true, numericality: { greater_than: 0 } end validates_inclusion_of :scanned_exam, in: [true, false] validate :minimum_number_of_groups after_create :build_repository before_save :reset_collection_time # Call custom validator in order to validate the :due_date attribute # date: true maps to DateValidator (custom_name: true maps to CustomNameValidator) # Look in lib/validators/* for more info validates :due_date, date: true after_save :update_assigned_tokens after_save :create_peer_review_assignment_if_not_exist after_save :update_repo_auth # Set the default order of assignments: in ascending order of due_date default_scope { order('due_date ASC') } def minimum_number_of_groups if (group_max && group_min) && group_max < group_min errors.add(:group_max, 'must be greater than the minimum number of groups') false end end # Are we past all the due dates for this assignment? def past_all_due_dates? # If no section due dates /!\ do not check empty? it could be wrong unless self.section_due_dates_type return !due_date.nil? && Time.zone.now > due_date end # If section due dates self.section_due_dates.each do |d| if !d.due_date.nil? && Time.zone.now > d.due_date return true end end false end # Return an array with names of sections past def section_names_past_due_date sections_past = [] unless self.section_due_dates_type if !due_date.nil? && Time.zone.now > due_date return sections_past << 'Due Date' end end self.section_due_dates.each do |d| if !d.due_date.nil? && Time.zone.now > d.due_date sections_past << d.section.name end end sections_past end # Whether or not this grouping is past its due date for this assignment. def grouping_past_due_date?(grouping) if section_due_dates_type && grouping && grouping.inviter.section.present? section_due_date = SectionDueDate.due_date_for(grouping.inviter.section, self) !section_due_date.nil? && Time.zone.now > section_due_date else past_all_due_dates? end end def section_due_date(section) unless section_due_dates_type && section return due_date end SectionDueDate.due_date_for(section, self) end # Calculate the latest due date among all sections for the assignment. def latest_due_date return due_date unless section_due_dates_type due_dates = section_due_dates.map(&:due_date) << due_date due_dates.compact.max end def past_collection_date?(section=nil) Time.zone.now > submission_rule.calculate_collection_time(section) end def past_all_collection_dates? Time.zone.now > latest_due_date end def past_remark_due_date? !remark_due_date.nil? && Time.zone.now > remark_due_date end # Return true if this is a group assignment; false otherwise def group_assignment? invalid_override || group_max > 1 end # Returns the group by the user for this assignment. If pending=true, # it will return the group that the user has a pending invitation to. # Returns nil if user does not have a group for this assignment, or if it is # not a group assignment def group_by(uid, pending=false) return unless group_assignment? # condition = "memberships.user_id = ?" # condition += " and memberships.status != 'rejected'" # add non-pending status clause to condition # condition += " and memberships.status != 'pending'" unless pending # groupings.first(include: :memberships, conditions: [condition, uid]) #FIXME: needs schema update #FIXME: needs to be rewritten using a proper query... User.find(uid.id).accepted_grouping_for(id) end def display_for_note short_identifier end # Returns the maximum possible mark for a particular assignment def max_mark(user_visibility = :ta) get_criteria(user_visibility).map(&:max_mark).sum.round(2) end # calculates summary statistics of released results for this assignment def update_results_stats marks = Result.student_marks_by_assignment(id) # No marks released for this assignment. return false if marks.empty? self.results_fails = marks.count { |mark| mark < max_mark / 2.0 } self.results_zeros = marks.count(&:zero?) # Avoid division by 0. self.results_average, self.results_median = if max_mark.zero? [0, 0] else # Calculates average and median in percentage. [average(marks), median(marks)].map do |stat| (stat * 100 / max_mark).round(2) end end self.save end def average(marks) marks.empty? ? 0 : marks.reduce(:+) / marks.size.to_f end def median(marks) count = marks.size return 0 if count.zero? if count.even? average([marks[count/2 - 1], marks[count/2]]) else marks[count/2] end end def self.get_current_assignment # start showing (or "featuring") the assignment 3 days before it's due # query uses Date.today + 4 because results from db seems to be off by 1 current_assignment = Assignment.where('due_date <= ?', Date.today + 4) .reorder('due_date DESC').first if current_assignment.nil? current_assignment = Assignment.reorder('due_date ASC').first end current_assignment end def update_remark_request_count outstanding_count = 0 groupings.each do |grouping| submission = grouping.current_submission_used if !submission.nil? && submission.has_remark? if submission.remark_result.marking_state == Result::MARKING_STATES[:incomplete] outstanding_count += 1 end end end self.outstanding_remark_request_count = outstanding_count self.save end def instructor_test_scripts self.test_scripts .where(run_by_instructors: true) end def student_test_scripts self.test_scripts .where(run_by_students: true) end def total_instructor_test_script_marks self.instructor_test_scripts .sum(:max_marks) end #total marks for scripts that are run on student request def total_student_test_script_marks self.student_test_scripts .sum(:max_marks) end def add_group(new_group_name=nil) if group_name_autogenerated group = Group.new group.save(validate: false) group.group_name = group.get_autogenerated_group_name group.save else return if new_group_name.nil? if group = Group.where(group_name: new_group_name).first unless groupings.where(group_id: group.id).first.nil? raise "Group #{new_group_name} already exists" end else group = Group.create(group_name: new_group_name) end end group.set_repo_permissions Grouping.create(group: group, assignment: self) end # Clones the Groupings from the assignment with id assignment_id # into self. Destroys any previously existing Groupings associated # with this Assignment def clone_groupings_from(assignment_id) original_assignment = Assignment.find(assignment_id) self.transaction do self.group_min = original_assignment.group_min self.group_max = original_assignment.group_max self.student_form_groups = original_assignment.student_form_groups self.group_name_autogenerated = original_assignment.group_name_autogenerated self.group_name_displayed = original_assignment.group_name_displayed self.groupings.destroy_all self.save self.reload original_assignment.groupings.each do |g| unhidden_student_memberships = g.accepted_student_memberships.select do |m| !m.user.hidden end unhidden_ta_memberships = g.ta_memberships.select do |m| !m.user.hidden end #create the memberships for any user that is not hidden unless unhidden_student_memberships.empty? #create the groupings grouping = Grouping.new grouping.group_id = g.group_id grouping.assignment_id = self.id grouping.admin_approved = g.admin_approved raise 'Could not save grouping' if !grouping.save all_memberships = unhidden_student_memberships + unhidden_ta_memberships all_memberships.each do |m| membership = Membership.new membership.user_id = m.user_id membership.type = m.type membership.membership_status = m.membership_status raise 'Could not save membership' if !(grouping.memberships << membership) end # Ensure all student members have permissions on their group repositories grouping.update_repository_permissions end end end end # Add a group and corresponding grouping as provided in # the passed in Array. # Format: [ groupname, repo_name, member, member, etc ] # The groupname, repo_name must not pre exist, each member should exist and # not belong to a different grouping for the same assignment. # If these requirements are not satisfied, the group and the grouping is # not created. def add_csv_group(row) return if row.length.zero? begin row.map! { |item| item.strip } rescue NoMethodError raise CSVInvalidLineError end group = Group.where(group_name: row.first).first unless group.nil? if group.repo_name != row[1] # CASE: Group already exists but the repo name is different duplicate_group_error = I18n.t('csv.group_with_different_repo', group_name: row[0]) raise CSVInvalidLineError, duplicate_group_error else any_grouping = Grouping.find_by group_id: group.id if any_grouping.nil? # CASE: Group exists with same repo name but has no grouping # associated with it for any assignment # Use existing group and create a new grouping between the existing # group and the given students and return without error add_new_grouping_for_group(row, group) return else grouping_for_current_assignment = group.grouping_for_assignment(id) if grouping_for_current_assignment.nil? if same_membership_as_csv_row?(row, any_grouping) # CASE: Group already exists with the same repo name and has a # grouping for another assignment with the same membership # Use existing group and create a new grouping between the # existing group and the given students and return without error add_new_grouping_for_group(row, group) return else # CASE: Group already exists with the same repo name and has # a grouping for another assignment BUT with different # membership # The existing groupings and the current group is not compatible # Return an error. duplicate_group_error = I18n.t( 'csv.group_with_different_membership_different_assignment', group_name: row[0]) raise CSVInvalidLineError, duplicate_group_error end else if same_membership_as_csv_row?(row, grouping_for_current_assignment) # CASE: Group already exists with the same repo name and also has # a grouping for the current assignment with the same # membership # No new group or grouping created. Since the exact group given by # the csv file already exists treat this as a successful case # and don't return an error return else # CASE: Group already exists with the same repo name and has a # grouping for the current assignment BUT the membership is # different. # Return error since the membership is different duplicate_group_error = I18n.t( 'csv.group_with_different_membership_current_assignment', group_name: row[0]) raise CSVInvalidLineError, duplicate_group_error end end end end end # If any of the given members do not exist or is part of another group, # an error is returned without creating a group unless membership_unique?(row) if !errors[:groupings].blank? # groupings error set if a member is already in different group membership_error = I18n.t('csv.memberships_not_unique', group_name: row[0], student_user_name: errors.get(:groupings) .first) errors.delete(:groupings) else # student_membership error set if a member does not exist membership_error = I18n.t( 'csv.member_does_not_exist', group_name: row[0], student_user_name: errors.get(:student_memberships).first) errors.delete(:student_memberships) end return membership_error end # If this assignment is an individual assignment, then the repostiory # name is set to be the student's user name. If this assignment is a # group assignment then the repository name is taken from the csv file if is_candidate_for_setting_custom_repo_name?(row) repo_name = row[2] else repo_name = row[1] end # If a repository already exists with the same repo name as the one given # in the csv file, error is returned and the group is not created begin if repository_already_exists?(repo_name) repository_error = I18n.t('csv.repository_already_exists', group_name: row[0], repo_path: errors.get(:repo_name).last) errors.delete(:repo_name) return repository_error end rescue TypeError raise CSV::MalformedCSVError end # At this point we can be sure that the group_name, memberships and # the repo_name does not already exist. So we create the new group. group = Group.new group.group_name = row[0] group.repo_name = repo_name # Note: after_create hook build_repository might raise # Repository::RepositoryCollision. If it does, it adds the colliding # repo_name to errors.on_base. This is how we can detect repo # collisions here. Unfortunately, we can't raise an exception # here, because we still want the grouping to be created. This really # shouldn't happen anyway, because the lookup earlier should prevent # repo collisions e.g. when uploading the same CSV file twice. group.save unless group.errors[:base].blank? collision_error = I18n.t('csv.repo_collision_warning', repo_name: group.errors.on_base, group_name: row[0]) end add_new_grouping_for_group(row, group) collision_error end def grouped_students student_memberships.map(&:user) end def ungrouped_students Student.where(hidden: false) - grouped_students end def valid_groupings groupings.includes(student_memberships: :user).select do |grouping| grouping.admin_approved || grouping.student_memberships.count >= group_min end end def invalid_groupings groupings - valid_groupings end def assigned_groupings groupings.joins(:ta_memberships).includes(ta_memberships: :user).uniq end def unassigned_groupings groupings - assigned_groupings end # Get a list of subversion client commands to be used for scripting def get_svn_checkout_commands svn_commands = [] # the commands to be exported self.groupings.each do |grouping| submission = grouping.current_submission_used if submission svn_commands.push( "svn checkout -r #{submission.revision_number} " + "#{grouping.group.repository_external_access_url}/" + "#{repository_folder} \"#{grouping.group.group_name}\"") end end svn_commands end # Get a list of group_name, repo-url pairs def get_svn_repo_list CSV.generate do |csv| self.groupings.each do |grouping| group = grouping.group csv << [group.group_name,group.repository_external_access_url] end end end # Get a detailed CSV report of criteria based marks # (includes each criterion, with it's out-of value) for this assignment. # Produces CSV rows such as the following: # student_name,95.22222,3,4,2,5,5,4,0/2 # Criterion values should be read in pairs. I.e. 2,3 means 2 out-of 3. # Last column are grace-credits. def get_detailed_csv_report out_of = max_mark students = Student.all MarkusCSV.generate(students) do |student| result = [student.user_name] grouping = student.accepted_grouping_for(self.id) if grouping.nil? || !grouping.has_submission? # No grouping/no submission # total percentage, total_grade result.concat(['','0']) # mark, max_mark result.concat(Array.new(criteria_count, ''). zip(get_criteria.map(&:max_mark)).flatten) # extra-mark, extra-percentage result.concat(['','']) else # Fill in actual values, since we have a grouping # and a submission. submission = grouping.current_submission_used result.concat([submission.get_latest_result.total_mark / out_of * 100, submission.get_latest_result.total_mark]) get_marks_list(submission).each do |mark| result.concat(mark) end result.concat([submission.get_latest_result.get_total_extra_points, submission.get_latest_result.get_total_extra_percentage]) end # push grace credits info grace_credits_data = student.remaining_grace_credits.to_s + '/' + student.grace_credits.to_s result.push(grace_credits_data) result end end # Returns an array of [mark, max_mark]. def get_marks_list(submission) get_criteria.map do |criterion| mark = submission.get_latest_result.marks.find_by(markable: criterion) [(mark.nil? || mark.mark.nil?) ? '' : mark.mark, criterion.max_mark] end end def replace_submission_rule(new_submission_rule) if self.submission_rule.nil? self.submission_rule = new_submission_rule self.save else self.submission_rule.destroy self.submission_rule = new_submission_rule self.save end end def next_criterion_position # We're using count here because this fires off a DB query, thus # grabbing the most up-to-date count of the criteria. get_criteria.count > 0 ? get_criteria.last.position + 1 : 1 end # Returns a filtered list of criteria. def get_criteria(user_visibility = :all, type = :all, options = {}) include_opt = options[:includes] if user_visibility == :all get_all_criteria(type, include_opt) elsif user_visibility == :ta get_ta_visible_criteria(type, include_opt) elsif user_visibility == :peer get_peer_visible_criteria(type, include_opt) end end def get_all_criteria(type, include_opt) if type == :all all_criteria = rubric_criteria.includes(include_opt) + flexible_criteria.includes(include_opt) + checkbox_criteria.includes(include_opt) all_criteria.sort_by(&:position) elsif type == :rubric rubric_criteria.includes(include_opt).order(:position) elsif type == :flexible flexible_criteria.includes(include_opt).order(:position) elsif type == :checkbox checkbox_criteria.includes(include_opt).order(:position) end end def get_ta_visible_criteria(type, include_opt) get_all_criteria(type, include_opt).select(&:ta_visible) end def get_peer_visible_criteria(type, include_opt) get_all_criteria(type, include_opt).select(&:peer_visible) end def criteria_count get_criteria.size end # Returns an array with the number of groupings who scored between # certain percentage ranges [0-5%, 6-10%, ...] # intervals defaults to 20 def grade_distribution_as_percentage(intervals=20) distribution = Array.new(intervals, 0) out_of = max_mark if out_of == 0 return distribution end steps = 100 / intervals # number of percentage steps in each interval groupings = self.groupings.includes([{current_submission_used: :results}]) groupings.each do |grouping| submission = grouping.current_submission_used if submission && submission.has_result? result = submission.get_latest_completed_result unless result.nil? percentage = (result.total_mark / out_of * 100).ceil if percentage == 0 distribution[0] += 1 elsif percentage >= 100 distribution[intervals - 1] += 1 elsif (percentage % steps) == 0 distribution[percentage / steps - 1] += 1 else distribution[percentage / steps] += 1 end end end end # end of groupings loop distribution end # Returns all the TAs associated with the assignment def tas Ta.find(ta_memberships.map(&:user_id)) end # Returns all the submissions that have been graded (completed) def graded_submission_results results = [] groupings.each do |grouping| if grouping.marking_completed? submission = grouping.current_submission_used results.push(submission.get_latest_result) unless submission.nil? end end results end def groups_submitted groupings.select(&:has_submission?) end def get_num_assigned(ta_id = nil) if ta_id.nil? groupings.size else ta_memberships.where(user_id: ta_id).size end end def get_num_marked(ta_id = nil) if ta_id.nil? groupings.count(marking_completed: true) else n = 0 ta_memberships.includes(grouping: [{current_submission_used: [:submitted_remark, :results]}]).where(user_id: ta_id).find_each do |x| x.grouping.marking_completed? && n += 1 end n end end def get_num_annotations(ta_id = nil) if ta_id.nil? num_annotations_all else n = 0 ta_memberships.where(user_id: ta_id).find_each do |x| x.grouping.marking_completed? && n += x.grouping.current_submission_used.annotations.size end n end end def num_annotations_all groupings = Grouping.arel_table submissions = Submission.arel_table subs = Submission.joins(:grouping) .where(groupings[:assignment_id].eq(id) .and(submissions[:submission_version_used].eq(true))) res = Result.submitted_remarks_and_all_non_remarks .where(submission_id: subs.pluck(:id)) filtered_subs = subs.where(id: res.pluck(:submission_id)) Annotation.joins(:submission_file) .where(submission_files: { submission_id: filtered_subs.pluck(:id) }).size end def average_annotations(ta_id = nil) num_marked = get_num_marked(ta_id) avg = 0 if num_marked != 0 num_annotations = get_num_annotations(ta_id) avg = num_annotations.to_f / num_marked end avg.round(2) end # Assign graders to a criterion for this assignment. # Raise a CSVInvalidLineError if the criterion or a grader doesn't exist. def add_graders_to_criterion(criterion_name, graders) criterion = get_criteria.find{ |crit| crit.name == criterion_name } if criterion.nil? raise CSVInvalidLineError end unless graders.all? { |g| Ta.exists?(user_name: g) } raise CSVInvalidLineError end criterion.add_tas_by_user_name_array(graders) end # Returns the groupings of this assignment associated with the given section def section_groupings(section) groupings.select do |grouping| grouping.inviter.present? && grouping.inviter.has_section? && grouping.inviter.section.id == section.id end end def has_a_collected_submission? submissions.where(submission_version_used: true).count > 0 end # Returns the groupings of this assignment that have no associated section def sectionless_groupings groupings.select do |grouping| grouping.inviter.present? && !grouping.inviter.has_section? end end # TODO: This is currently disabled until starter code is automatically added # to groups. def can_upload_starter_code? #groups.size == 0 false end # Returns true if this is a peer review, meaning it has a parent assignment, # false otherwise. def is_peer_review? not parent_assignment_id.nil? end # Returns true if this is a parent assignment that has a child peer review # assignment. def has_peer_review_assignment? not pr_assignment.nil? end def create_peer_review_assignment_if_not_exist if has_peer_review and Assignment.where(parent_assignment_id: id).empty? peerreview_assignment = Assignment.new peerreview_assignment.parent_assignment = self peerreview_assignment.submission_rule = NoLateSubmissionRule.new peerreview_assignment.assignment_stat = AssignmentStat.new peerreview_assignment.token_period = 1 peerreview_assignment.non_regenerating_tokens = false peerreview_assignment.unlimited_tokens = false peerreview_assignment.short_identifier = short_identifier + '_pr' peerreview_assignment.description = description peerreview_assignment.repository_folder = repository_folder peerreview_assignment.due_date = due_date peerreview_assignment.is_hidden = true # We do not want to have the database in an inconsistent state, so we # need to have the database rollback the 'has_peer_review' column to # be false if not peerreview_assignment.save raise ActiveRecord::Rollback end end end ### REPO ### def repository_name "#{short_identifier}_starter_code" end def build_repository # create repositories if and only if we are admin return true unless MarkusConfigurator.markus_config_repository_admin? # only create if we can add starter code return true unless can_upload_starter_code? begin Repository.get_class(MarkusConfigurator.markus_config_repository_type) .create(File.join(MarkusConfigurator.markus_config_repository_storage, repository_name)) rescue Repository::RepositoryCollision => e # log the collision errors.add(:base, self.repo_name) m_logger = MarkusLogger.instance m_logger.log("Creating repository '#{repository_name}' caused repository collision. " + "Error message: '#{e.message}'", MarkusLogger::ERROR) end true end # Return a repository object, if possible def repo repo_loc = File.join(MarkusConfigurator.markus_config_repository_storage, repository_name) if Repository.get_class(MarkusConfigurator.markus_config_repository_type).repository_exists?(repo_loc) Repository.get_class(MarkusConfigurator.markus_config_repository_type).open(repo_loc) else raise 'Repository not found and MarkUs not in authoritative mode!' # repository not found, and we are not repo-admin end end #Yields a repository object, if possible, and closes it after it is finished def access_repo yield repo repo.close() end ### /REPO ### private # Returns true if we are safe to set the repository name # to a non-autogenerated value. Called by add_csv_group. def is_candidate_for_setting_custom_repo_name?(row) # Repository name can be customized if # - this assignment is set up to allow external submits only # - group_max = 1 # - there's only one student member in this row of the csv and # - the group name is equal to the only group member if MarkusConfigurator.markus_config_repository_admin? && self.allow_web_submits == false && row.length == 3 && self.group_max == 1 && !row[2].blank? && row[0] == row[2] true else false end end def reset_collection_time submission_rule.reset_collection_time end def update_assigned_tokens self.tokens.each do |t| t.update_tokens(tokens_per_period_was, tokens_per_period) end end def add_new_grouping_for_group(row, group) # Create a new Grouping for this assignment and the newly # crafted group grouping = Grouping.new(assignment: self, group: group) grouping.save # Form groups start_index_group_members = 2 (start_index_group_members..(row.length - 1)).each do |i| student = Student.find_by user_name: row[i] if student if grouping.student_membership_number == 0 # Add first valid member as inviter to group. grouping.group_id = group.id grouping.save # grouping has to be saved, before we can add members # We could call grouping.add_member, but it updates repo permissions # For performance reasons in the csv upload we will just create the # member here, and do the permissions update as a bulk operation. member = StudentMembership.new( user: student, membership_status: StudentMembership::STATUSES[:inviter], grouping: grouping) member.save else member = StudentMembership.new( user: student, membership_status: StudentMembership::STATUSES[:accepted], grouping: grouping) member.save end end end end # # Return true if for each membership given, a corresponding student exists # and if they are not part of a different grouping for the same assignment # def membership_unique?(row) start_index_group_members = 2 # index where student names start in the row (start_index_group_members..(row.length - 1)).each do |i| student = Student.find_by user_name: row[i] if student unless student.accepted_grouping_for(id).nil? errors.add(:groupings, student.user_name) return false end else errors.add(:student_memberships, row[i]) return false end end true end # Return true if the given membership in the csv row is the exact same as the # membership of the given existing_grouping. def same_membership_as_csv_row?(row, existing_grouping) start_index_group_members = 2 # index where student names start in the row # check if all the members given in the csv file exists and belongs to the # given grouping (start_index_group_members..(row.length - 1)).each do |i| student = Student.find_by user_name: row[i] if student grouping = student .accepted_grouping_for(existing_grouping.assignment.id) if grouping.nil? # Student doesn't belong to a grouping for the given assignment # ==> membership cannot be the same return false elsif grouping.id != existing_grouping.id # Student belongs to a different grouping for the given assignment # ==> membership is different return false end else # Student doesn't exist in the database # # ==> membership cannot be the same return false end num_students_in_csv_row = row.length - start_index_group_members num_students_in_existing_grouping = grouping.accepted_students.length if num_students_in_csv_row != num_students_in_existing_grouping # All students given in the csv row belongs to the existing grouping # but the existing group contains more students than the ones given in # the csv row # ==> membership is different return false else # All students given in the csv row belongs to the existing grouping # and the grouping contains the same number of students as the one # in the csv row # ==> membership is the exact same return true end end end # Repository authentication subtleties: # 1) a repository is associated with a Group, but.. # 2) ..students are associated with a Grouping (an "instance" of Group for a specific Assignment) # That creates a problem since authentication in svn/git is at the repository level, while Markus handles it at # the assignment level, allowing the same Group repo to have different students according to the assignment. # The two extremes to implement it are using the union of all students (permissive) or the intersection (restrictive). # Instead, we are going to take a last-deadline approach instead, where we assume that the valid students at any point # in time are the ones valid for the last assignment due. # (Basically, it's nice for a group to share a repo among assignments, but at a certain point during the course # we may want to add or [more frequently] remove some students from it) def self.get_repo_auth_records Assignment.includes(groupings: [:group, {accepted_student_memberships: :user}]) .where(vcs_submit: true) .order(due_date: :desc) end def update_repo_auth if self.vcs_submit_was != self.vcs_submit repo = Repository.get_class(MarkusConfigurator.markus_config_repository_type) repo.__set_all_permissions end end end
mit
jakevn/MassiveNet
Unity3d.Examples/Assets/MassiveNet/Examples/NetAdvanced/Client/Scripts/TextFieldInput.cs
5579
// MIT License (MIT) - Copyright (c) 2014 jakevn - Please see included LICENSE file using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Massive.Examples.NetAdvanced { public class TextFieldInput : MonoBehaviour { private static readonly List<TextFieldInput> Fields = new List<TextFieldInput>(); private static readonly Dictionary<string, Action> Listeners = new Dictionary<string, Action>(); private static TextFieldInput currentlySelected; public static bool ListenForSubmit(string fieldName, Action listener) { foreach (var field in Fields) { if (field.name != fieldName) continue; if (Listeners.ContainsKey(fieldName)) return false; Listeners.Add(fieldName, listener); return true; } return false; } public static void StopListenForSubmit(Action listener) { string key = (from kv in Listeners where kv.Value == listener select kv.Key).FirstOrDefault(); if (key != null) Listeners.Remove(key); } public static bool TryGetText(string fieldName, out string text) { foreach (var field in Fields) { if (field.gameObject.name != fieldName) continue; text = field.Text(); return true; } text = null; return false; } public bool PasswordField; public int MaxLength = 64; public int LineLength = 20; public TextFieldInput TabTarget; private TextMesh textMesh; private string initialValue; private string backingText = ""; private void OnEnable() { if (textMesh == null) { textMesh = GetComponentInChildren<TextMesh>(); if (textMesh == null) { Debug.LogError("No TextMesh found in children."); return; } initialValue = textMesh.text; } if (!Fields.Contains(this)) Fields.Add(this); Button.ListenForClick(gameObject.name, Clicked); } private void OnDisable() { if (Fields.Contains(this)) Fields.Remove(this); if (initialValue != null) { textMesh.text = initialValue; backingText = ""; } Button.StopListenForClick(gameObject.name, Clicked); Deselected(); } private void Clicked() { if (currentlySelected == this) return; Selected(); } private void MissedClick() { Deselected(); } public void Selected() { currentlySelected = this; if (textMesh.text == initialValue) textMesh.text = ""; textMesh.text += '|'; InputHandler.Instance.ListenToKeyDown(Tab, KeyCode.Tab); InputHandler.Instance.ListenToKeyDown(Return, KeyCode.Return); Button.ListenForMissedClick(gameObject.name, MissedClick); InputHandler.Instance.ListenToChars(OnInput); InputHandler.Instance.ListenToKey(OnBackspace, KeyCode.Backspace); } private void Deselected() { if (currentlySelected == this) currentlySelected = null; if (textMesh.text[textMesh.text.Length - 1] == '|') textMesh.text = textMesh.text.Remove(textMesh.text.Length - 1); if (backingText.Length == 0) textMesh.text = initialValue; InputHandler.Instance.StopListenToKeyDown(Tab, KeyCode.Tab); InputHandler.Instance.StopListenToKeyDown(Return, KeyCode.Return); Button.StopListenForMissedClick(gameObject.name, MissedClick); InputHandler.Instance.StopListenToChars(OnInput); InputHandler.Instance.StopListenToKey(OnBackspace, KeyCode.Backspace); } private void OnDestroy() { OnDisable(); } private float lastBackspace; private const float BackspaceDelay = 0.1f; void OnBackspace() { if (Time.time - lastBackspace < BackspaceDelay) return; if (backingText.Length == 0) return; lastBackspace = Time.time; backingText = backingText.Remove(backingText.Length - 1); if (textMesh.text[textMesh.text.Length - 2] == '\n') textMesh.text = textMesh.text.Remove(textMesh.text.Length - 2, 1); textMesh.text = textMesh.text.Remove(textMesh.text.Length - 2, 1); } void OnInput(char c) { if (backingText.Length >= MaxLength || c == '\n' || c == '\t') return; backingText += c; c = PasswordField ? '*' : c; if (backingText.Length != 0 && backingText.Length % LineLength == 0) { textMesh.text = textMesh.text.Insert(textMesh.text.Length - 1, "\n" + c); } else { textMesh.text = textMesh.text.Insert(textMesh.text.Length - 1, c.ToString()); } } private void Tab() { if (TabTarget == null) return; Deselected(); TabTarget.Selected(); } private void Return() { if (currentlySelected != this) return; Submit(); } public void Submit() { if (!Listeners.ContainsKey(gameObject.name)) return; Listeners[gameObject.name](); } public string Text() { return backingText; } } }
mit
IdeaSolutionsOnline/ERP4R
core/objs/gap_senha.py
24102
# !/usr/bin/env python3 # -*- encoding: utf-8 -*- """ ERP+ """ __author__ = 'CVtek dev' __credits__ = [] __version__ = "1.0" __maintainer__ = "CVtek dev" __status__ = "Development" __model_name__ = 'gap_senha.GAPSenha' import auth, base_models from orm import * from form import * try: from my_gap_servico import GAPServico except: from gap_servico import GAPServico class GAPSenha(Model, View): def __init__(self, **kargs): Model.__init__(self, **kargs) self.__name__ = 'gap_senha' self.__title__ ='Senha' #Gestão de atendimento Presencial senha self.__model_name__ = __model_name__ self.__list_edit_mode__ = 'edit' self.__get_options__ = ['nr_senha'] self.__order_by__ = 'int8(gap_senha.nr_senha)' self.__auth__ = { 'read':['All'], 'write':['Atendedor'], 'create':['Gestor de Loja'], 'delete':['Gestor de Atendimento'], 'full_access':['Gestor de Atendimento'] } self.servico = combo_field(view_order = 1, name = 'Serviço', size = 50, args = 'required', model = 'gap_servico', search = False, column = 'nome', options = "model.get_opts('GAPServico().get_options()')") self.letra = string_field(view_order=2, name='Letra', size=15, args='readonly',onlist = False) self.nr_senha = string_field(view_order=3 , name='Nº Senha', args='readonly',size=30, onlist = True) self.data = date_field(view_order = 4, name = 'Data Inicial', args='readonly',size=40, default = datetime.date.today()) self.hora_ped = time_field(view_order=5, name ='Hora Pedido', args='readonly',size=40, onlist=False, default=time.strftime('%H:%M:%S')) self.est_atend = string_field(view_order=6 , name='Estimativa Atendimento', args='readonly', size=40, onlist = False) self.pess_fila = string_field(view_order=7, name='Nº Pessoas na Fila', args='readonly',size=40, default = 0, onlist = False) self.estado = combo_field(view_order = 8, name = 'Estado', args = 'required', size = 50, default = 'Espera', options = [('espera','Espera'), ('espera_atendedor','Espera Atendedor'), ('atendido','Atendido'), ('desistiu','Desistiu'), ('transferido','Transferido'), ('para_atendimento','Para Atendimento')], onlist = True) self.terminal = many2many(view_order = 9, name = 'Loja', size = 50, fields=['name'], model_name = 'terminal.Terminal', condition = "gap_senha='{id}'", hidden=True, onlist=False) #Apanha Senha Geral :) def get_self(self): return self.get_options() def get_opts(self, get_str): """ Este get_opts em todos os modelos serve para alimentar os choice e combo deste modelo e não chama as funções get_options deste modelo quando chamadas a partir de um outro! """ return eval(get_str) #Apanha Senhas Atendidas def get_atendido(self): #Essa funçao apanha todas as senhas atendidas def get_results(): options = [] opts = self.get(order_by='int8(gap_senha.nr_senha)') for option in opts: if option['estado'] == 'atendido': options.append((str(option['id']), option['estado'] + ' - ' + option['nr_senha'])) return options return erp_cache.get(key=self.__model_name__ + '_atendido', createfunc=get_results) #Apanha Senhas em Espera def get_espera(self): #Essa funçao apanha todas as senhas em espera def get_results(): options = [] opts = self.get(order_by='int8(gap_senha.nr_senha)') for option in opts: if option['estado'] == 'espera': options.append((str(option['id']), option['estado'] + ' - ' + option['nr_senha'])) return options return erp_cache.get(key=self.__model_name__ + '_espera', createfunc=get_results) #Apanha Senhas que desistiram def get_desistiu(self): #Essa funçao apanha todas as senhas que desistiram def get_results(): options = [] opts = self.get(order_by='int8(gap_senha.nr_senha)') for option in opts: if option['estado'] == 'desistiu': options.append((str(option['id']), option['estado'] + ' - ' + option['nr_senha'])) return options return erp_cache.get(key=self.__model_name__ + '_desistiu', createfunc=get_results) #Apanha Senhas Transferidas def get_transferidas(self): #Essa funçao apanha todas as senhas transferidas def get_results(): options = [] opts = self.get(order_by='int8(gap_senha.nr_senha)') for option in opts: if option['estado'] == 'transferido': options.append((str(option['id']), option['estado'] + ' - ' + option['nr_senha'])) return options return erp_cache.get(key=self.__model_name__ + '_transferido', createfunc=get_results) #Apanha Senhas para atendimento def get_para_atendimento(self): #Essa funçao apanha todas as senhas para atendimento def get_results(): options = [] opts = self.get(order_by='int8(gap_senha.nr_senha)') for option in opts: if option['estado'] == 'para_atendimento': options.append((str(option['id']), option['estado'] + ' - ' + option['nr_senha'])) return options return erp_cache.get(key=self.__model_name__ + '_para_atendimento', createfunc=get_results) #Apanha Senha por Data def get_senha_data(self, data=None): #Essa funçao apanha todas as senhas em uma determinada data def get_results(): options = [] opts = self.get(order_by='int8(gap_senha.nr_senha)') for option in opts: if option['data'] == data: options.append((str(option['id']), option['estado'] + ' - ' + option['nr_senha'])) return options return erp_cache.get(key=self.__model_name__ + '_senha_data', createfunc=get_results) #Mudar Estado Senha para Espera def Espera(self, id=None): try: self.where = "id = '{id}'".format(id=str(id)) self.kargs = self.get(order_by='int8(gap_senha.nr_senha)') if self.kargs: self.kargs = self.kargs[0] self.kargs['user'] = bottle.request.session['user'] self.kargs['estado'] = 'espera' self.put() return True except: return False #Mudar Estado Senha para Atendido def Atendido(self, id=None): try: self.where = "id = '{id}'".format(id=str(id)) self.kargs = self.get(order_by='int8(gap_senha.nr_senha)') if self.kargs: self.kargs = self.kargs[0] self.kargs['user'] = bottle.request.session['user'] self.kargs['estado'] = 'atendido' self.put() return True except: return False #Mudar Estado Senha para Desistido def Desistiu(self, id=None): try: self.where = "id = '{id}'".format(id=str(id)) self.kargs = self.get(order_by='int8(gap_senha.nr_senha)') if self.kargs: self.kargs = self.kargs[0] self.kargs['user'] = bottle.request.session['user'] self.kargs['estado'] = 'desistiu' self.put() return True except: return False #Mudar Estado Senha para Transferido def Transferido(self, id=None,keyservico=None): try: self.where = "id = '{id}'".format(id=str(id)) self.kargs = self.get(order_by='int8(gap_senha.nr_senha)') if self.kargs: self.kargs = self.kargs[0] self.kargs['user'] = bottle.request.session['user'] self.kargs['estado'] = 'transferido' self.kargs['servico'] = keyservico self.put() return True except: return False #Mudar Estado Senha para atendimento def Para_Atendimento(self, id=None): try: self.where = "id = '{id}'".format(id=str(id)) self.kargs = self.get(order_by='int8(gap_senha.nr_senha)') if self.kargs: self.kargs = self.kargs[0] self.kargs['user'] = bottle.request.session['user'] self.kargs['estado'] = 'para_atendimento' self.put() return True except: return False #Mudar Estado Senha para espera por atendedor def Espera_Atendedor(self, id=None): try: self.where = "id = '{id}'".format(id=str(id)) self.kargs = self.get(order_by='int8(gap_senha.nr_senha)') if self.kargs: self.kargs = self.kargs[0] self.kargs['user'] = bottle.request.session['user'] self.kargs['estado'] = 'espera_atendedor' self.put() return True except: return False #set numero de pessoas em fila def Pessoas_Fila(self, id=None,user=None, pess_fila=None): try: self.where = "id = '{id}'".format(id=str(id)) self.kargs = self.get(order_by='int8(gap_senha.nr_senha)') if self.kargs: self.kargs = self.kargs[0] self.kargs['user'] = user self.kargs['pess_fila'] = pess_fila self.put() return True except: return False #get Numero de senha def get_numero_senha(self, loja=None, user=None): #apanha o numero de senha from gap_sequencia import GAPSequencia numero = GAPSequencia().get_sequence(loja=loja, user=user) return numero #get Numero de pessoas na fila numa loja xpto def get_pessoas_fila(self, loja=None): #Essa funçao retorna o numero de pessoas em fila na loja xpto self.kargs['join'] = ",gap_senha_terminal" self.where ="gap_senha_terminal.terminal = '{id}' and gap_senha_terminal.gap_senha= gap_senha.id".format(id=str(loja)) options = [] opts = self.get(order_by='int8(gap_senha.nr_senha)') count = -1 data_hoje = datetime.date.today() for option in opts: data_senha = str(option['data']).split("-") if (option['estado'] == 'espera') and (datetime.date(int(data_senha[0]),int(data_senha[1]), int(data_senha[2]))==data_hoje): count += 1 return count #get Estimativa atendimento def get_estimativa(self, loja=None): #apanha a estimativa de atendimento para uma determinada senha numa loja #Essa funçao faz uma prespectiva que cada senha em espera vai ter pelomenos 5 minutos a serem atendidos self.kargs['join'] = ",gap_senha_terminal" self.where ="gap_senha_terminal.terminal = '{id}' and gap_senha_terminal.gap_senha= gap_senha.id".format(id=str(loja)) options = [] opts = self.get(order_by='int8(gap_senha.nr_senha)') hora = 0 minuto = 0 count = -1 data_hoje = datetime.date.today() for option in opts: data_senha = str(option['data']).split("-") if (option['estado'] == 'espera') and (datetime.date(int(data_senha[0]),int(data_senha[1]), int(data_senha[2]))==data_hoje): count+=1 if(count>0): if (minuto < 59): minuto = minuto+5 elif (minuto >= 59): minuto = 0 hora=hora+1 if (hora == 0) and (minuto == 0): return '00:00:00' else: if (hora < 10): hora = '0'+str(hora) if (minuto < 10): minuto = '0'+str(minuto) return str(hora)+":"+str(minuto)+":00" #Apanhar a proxima senha em espera ou transferido ordenando pela ordem na loja xpto (recebendo o id da respectiva loja :) def get_proximo(self, loja=None): try: self.kargs['join'] = ",gap_senha_terminal" self.where ="gap_senha_terminal.terminal = '{id}' and gap_senha_terminal.gap_senha= gap_senha.id".format(id=str(loja)) options = [] opts = self.get(order_by='int8(gap_senha.nr_senha)') data_hoje = datetime.date.today() for f in get_model_fields(self): if f[0] == 'servico': field=f for option in opts: data_senha = str(option['data']).split("-") if (option['estado'] == 'espera') or (option['estado'] == 'transferido'): if (datetime.date(int(data_senha[0]),int(data_senha[1]), int(data_senha[2]))==data_hoje): servico = get_field_value(record=option, field=field, model=self)['field_value'][1] res = str(option['gap_senha'])+";"+str(option['letra'])+str(option['nr_senha'])+";"+str(servico)+";"+str(option['estado']) return res return None except: return None #Atraves de uma letra e um numero de senha retorna a respectivo senha com o ID def get_senha(self,senha=None, loja=None): try: self.kargs['join'] = ",gap_senha_terminal" self.where ="gap_senha_terminal.terminal = '{id}' and gap_senha_terminal.gap_senha= gap_senha.id".format(id=str(loja)) opts = self.get(order_by='int8(gap_senha.nr_senha)') letrasenha = senha[:1] numerosenha = senha[1:] data_hoje = datetime.date.today() for f in get_model_fields(self): if f[0] == 'servico': field=f for option in opts: data_senha = str(option['data']).split("-") if(int(option['nr_senha'])==int(numerosenha)) and (datetime.date(int(data_senha[0]),int(data_senha[1]), int(data_senha[2])) == data_hoje): if (option['estado'] == 'espera') or (option['estado'] == 'transferido'): servico = get_field_value(record=option, field=field, model=self)['field_value'][1] if(letrasenha==str(option['letra'])): return str(option['gap_senha'])+";"+str(option['letra'])+str(option['nr_senha'])+";"+str(servico)+";"+str(option['estado']) return None except: #Em caso o inviduo insirir uma senha a brincar logo invalida :) return None #get senha com mais informaçoes def get_senhaInfo(self,id=None): try: self.where = "id = '{id}'".format(id=str(id)) self.kargs = self.get(order_by='int8(gap_senha.nr_senha)') if self.kargs: self.kargs = self.kargs[0] return str(self.kargs['id'])+";"+str(self.kargs['letra'])+str(self.kargs['nr_senha'])+";"+str(self.kargs['hora_ped'])+";"+str(self.kargs['data'])+";"+str(self.kargs['estado']) return None except: return None #get senha com mais informaçoes plus extras :D def get_senhaExtraInfo(self,id=None): try: self.where = "id = '{id}'".format(id=str(id)) self.kargs = self.get(order_by='int8(gap_senha.nr_senha)') for f in get_model_fields(self): if f[0] == 'servico': field=f if self.kargs: self.kargs = self.kargs[0] servico = get_field_value(record=self.kargs, field=field, model=self)['field_value'][1] return str(self.kargs['id'])+";"+str(self.kargs['letra'])+str(self.kargs['nr_senha'])+";"+str(servico)+";"+str(self.kargs['hora_ped'])+";"+str(self.kargs['data'])+";"+str(self.kargs['estado']) return None except: return None #Retornar ecran de atendimento def get_ecran_atendimento(self, window_id): return form_gap_atendedor(window_id=window_id).show() #Descartar senhas com data limite expirada para uma loja especifica def descartar_senha(self,loja=None): try: from my_terminal import Terminal from gap_timeAtendimento import GAPTimeAtendimento #Para sabermos o ID da loja onde nos encontramos lojaID = Terminal().get_lojaID(loja=loja) self.kargs['join'] = ",gap_senha_terminal" self.where ="gap_senha_terminal.terminal = '{id}' and gap_senha_terminal.gap_senha=gap_senha.id".format(id=str(lojaID)) args = self.get(order_by='int8(gap_senha.nr_senha)') data_hoje = datetime.date.today() for self.kargs in args: data_fim = str(self.kargs['data']).split("-") if (datetime.date(int(data_fim[0]),int(data_fim[1]), int(data_fim[2])) < data_hoje) and (self.kargs['active'] == True): if(self.kargs['estado'] == 'para_atendimento') or (self.kargs['estado'] == 'espera_atendedor') or (self.kargs['estado'] == 'espera'): senha_id = self.kargs['gap_senha'] self.Desistiu(id=senha_id) GAPTimeAtendimento().checkTimeAtendimentoLater(senha_id=senha_id, loja=loja) return True except: return False #essa funçao e chamada quando o cliente retira uma senha def get_SenhaCliente(self, user=None, servico=None, letra=None, loja=None): try: #Aviso para que o imprimir senha funcione como deve ser e necessario instalar um plugin no browser mozila AttendPrint ou soluçoes do genero para o google chrome aplicando-se comandos como o --kioske print from my_terminal import Terminal from gap_servico import GAPServico lojaId = Terminal().get_lojaID(loja=loja) servico_id = GAPServico().get_servico_id(nome=servico) output = None if(lojaId==0): return None else: if(GAPServico().check_turnoServico(servico_id=servico_id) == True): print("dentro do if ca podi :( ") data = datetime.date.today() hora = datetime.datetime.now().time().strftime('%H:%M:%S') nr_senha = self.get_numero_senha(loja=loja,user=user) content = { 'user': '{user}'.format(user=user), 'servico': servico_id, 'letra':letra, 'nr_senha': nr_senha, 'data':data, 'hora_ped':hora, 'pess_fila': 0, 'est_atend': 0, 'estado':'espera', } GAPSenha(**content).put() #agora buscamos pelo id da senha que acabamos de insirir self.where = "servico = '{servico}' and nr_senha= '{nr_senha}' and hora_ped= '{hora_ped}' and data= '{data}'".format(servico=str(servico_id),nr_senha=str(nr_senha),hora_ped=str(hora),data=str(data)) self.kargs = self.get(order_by='int8(gap_senha.nr_senha)') if self.kargs: self.kargs = self.kargs[0] kargs = {} kargs['terminal'] = lojaId kargs['parent_name'] = 'terminal' kargs['gap_senha'] = self.kargs['id'] kargs['user'] = user #adicionamos na relaçao m2m GAPSenha(**kargs).put_m2m() #actualizamos a senha com os valores das pessoas em fila , estimativa de atendimento nessa loja pess_fila = self.get_pessoas_fila(loja=lojaId) est_atend = self.get_estimativa(loja=lojaId) updatedcontent = { 'id':'{id}'.format(id=self.kargs['id']), 'user': '{user}'.format(user=user), 'pess_fila': pess_fila, 'est_atend': est_atend, } GAPSenha(**updatedcontent).put() #Enfim finalmente vamos imprimir a nossa senha :) from gap_senha_config import GAPSenhaConfig senhaConfigServico = GAPSenhaConfig().get_config_servico(servico=servico_id) senhaConfigLoja = GAPSenhaConfig().get_config_loja(loja=lojaId) senhaConfigLoja = str(senhaConfigLoja).split(";") senhaConfigServico = str(senhaConfigServico).split(";") #Estou a utilizar esse metodo por causa de alguns problemas com o reports nesse caso especifico....alterar depois output = """ <!DOCTYPE html> <html> <head> <title>Senha</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/static/css/foundation.css" /> <link rel="stylesheet" href="/static/css/gap.css" /> </head> <body> <h6 id="TextoSenha"> <img src="/static/logos/logo_minfin.png"/></h6> <h6 id="TextoSenhaCR">{message_cabesalho_loja}</h6> <h6 id="TextoSenhaCR">{message_cabesalho_servico}</h6> <h6 id="TextoSenha">Data: {data}</h6> <h6 id="TextoSenha">Hora de Entrada: {hora_ped}</h6> <h1 id="TextoSenhaSenha"><b>{servico} {nr_senha}</b></h1> <h6 id="TextoSenha">Pessoas na Fila: {pess_fila}</h6> <h6 id="TextoSenha">Tempo estimado: {est_atend}</h6> <h6 id="TextoSenha">{message_rodape_servico}</h6> <h6 id="TextoSenha">{message_rodape_loja}</h6> """.format(message_cabesalho_loja=senhaConfigLoja[0], message_cabesalho_servico=senhaConfigServico[0],data=data, hora_ped=hora, servico=letra, nr_senha=nr_senha,pess_fila=pess_fila, est_atend=est_atend, message_rodape_servico=senhaConfigServico[1], message_rodape_loja=senhaConfigLoja[1]) output+=""" <script src="/static/js/modernizr.js"></script> <script src="/static/js/jquery.min.js"></script> <script> window.print(); window.close(); </script> </body> </html> """ print("retornando output ------------------------------------ ") return str(output) except BaseException as e: return None
mit
Tasarinan/Ufoco
src/components/editor/formattingButtons.js
2795
import React, { PureComponent } from "react"; import { RichUtils } from "draft-js"; import PropTypes from "prop-types"; import cx from "classnames"; const STROKE_WIDTH_DEFAULT = 2; const STROKE_WIDTH_SELECTED = 3; export default class FormattingButtons extends PureComponent { static propTypes = { textEditorState: PropTypes.object.isRequired, onTextChange: PropTypes.func.isRequired, }; constructor(props) { super(props); this.onBoldClick = this.onBoldClick.bind(this); this.onItalicClick = this.onItalicClick.bind(this); this.onUlClick = this.onUlClick.bind(this); this.onOlClick = this.onOlClick.bind(this); } onBoldClick() { this.props.onTextChange( RichUtils.toggleInlineStyle(this.props.textEditorState, "BOLD") ); } onItalicClick() { this.props.onTextChange( RichUtils.toggleInlineStyle(this.props.textEditorState, "ITALIC") ); } onOlClick() { this.props.onTextChange( RichUtils.toggleBlockType(this.props.textEditorState, "ordered-list-item") ); } onUlClick() { this.props.onTextChange( RichUtils.toggleBlockType( this.props.textEditorState, "unordered-list-item" ) ); } render() { // Detect active inline/block styles const inlineStyle = this.props.textEditorState.getCurrentInlineStyle(); const blockType = RichUtils.getCurrentBlockType(this.props.textEditorState); const isBold = inlineStyle.has("BOLD"); const isItalic = inlineStyle.has("ITALIC"); const isOl = blockType === "ordered-list-item"; const isUl = blockType === "unordered-list-item"; const strokeWidthClass = cx({ ["lineThrough"]: isBold, }); return ( <div className="formatting-buttons"> <button type="button" className={`button button-invisible ${isBold ? "button-active" : ""}`} onClick={this.onBoldClick} > <i className="ri-bold" title="Bold"></i> </button> <button type="button" className={`button button-invisible ${ isItalic ? "button-active" : "" }`} onClick={this.onItalicClick} > <i className="ri-italic" title="Italic"></i> </button> <button type="button" className={`button button-invisible ${isUl ? "button-active" : ""}`} onClick={this.onUlClick} > <i className="ri-list-unordered" title="unordered-list-item"></i> </button> <button type="button" className={`button button-invisible ${isOl ? "button-active" : ""}`} onClick={this.onOlClick} > <i className="ri-list-ordered" title="ordered-list-item"></i> </button> </div> ); } }
mit
gsteinbacher/RandomOrgSharp
Obacher.RandomOrgSharp.JsonRPC/Method/StringSignedMethod.cs
2753
using Obacher.RandomOrgSharp.Core; using Obacher.RandomOrgSharp.Core.Request; using Obacher.RandomOrgSharp.Core.Response; using Obacher.RandomOrgSharp.Core.Service; using Obacher.RandomOrgSharp.JsonRPC.Response; namespace Obacher.RandomOrgSharp.JsonRPC.Method { /// <summary> /// This class is a wrapper class the <see cref="MethodCallBroker"/>. It setups a default set of classes to be called when making a call to random.org /// </summary> /// <remarks> /// The following is the sequence of actions that will occur during the call... /// Build the necessary JSON-RPC request string (the package that is used to retrieve a list of blob values) /// Execute the <see cref="AdvisoryDelayHandler"/> to delay the request the time recommended by random.org (based on the value in the previous response) /// Retrieve the random blob values from random.org /// Determine if an error occurred during the call and throw an exception if one did occur /// Store the advisory delay value to ensure the next request to random.org does not occur before the time requested by random.org. This will help prevent you from /// being banned from making requests to random.org /// Verify the Id returned in the response matches the id passed into the request /// Parse the response into a <see cref="DataResponseInfo{T}"/> so the blob values can be extracted /// </remarks> public class StringSignedMethod : StringBasicMethod { /// <summary> /// Constructor /// </summary> /// <param name="advisoryDelayHandler"> /// Class which handles the apprioriate delay before the request is called. /// It is required that this class be passed into the method because the same instance of the <see cref="AdvisoryDelayHandler"/> must be passed in on every request. /// </param> /// <param name="randomService"><see cref="IRandomService"/> to use to get random values. Defaults to <see cref="RandomOrgApiService"/></param> public StringSignedMethod(AdvisoryDelayHandler advisoryDelayHandler, IRandomService randomService = null) : base(advisoryDelayHandler, randomService) { var verifySignatureHandler = new VerifySignatureHandler(RandomService); BeforeRequestCommandFactory = new BeforeRequestCommandFactory(advisoryDelayHandler, verifySignatureHandler); ResponseHandlerFactory = new ResponseHandlerFactory( new ErrorHandlerThrowException(new ErrorParser()), verifySignatureHandler, advisoryDelayHandler, new VerifyIdResponseHandler(), ResponseParser ); } } }
mit
kdjlaw/kdjlaw.github.io
linkchanger.rb
201
pattern = /link_to '(.+)', '(.+)\/'/ Dir['**/*.slim'].each do |fname| text = File.read(fname).gsub(pattern, 'link_to \'\1\', \'\2/index.html\'') File.open(fname, 'w') do |f| f.write(text) end end
mit
SLP-ETR-public/EV3Practice
MultiTask03_01/src/SoundClass.java
316
import lejos.hardware.Sound; import lejos.utility.Delay; public class SoundClass implements Runnable { private int time = 0; @Override public void run() { while (time <= 10000) { Sound.beep(); Delay.msDelay(100); time += 100; } } }
mit
gypsydave5/chitter
features/step_definitions/web_steps.rb
4537
# Taken from the cucumber-rails project. # IMPORTANT: This file is generated by cucumber-sinatra - edit at your own peril. # It is recommended to regenerate this file in the future when you upgrade to a # newer version of cucumber-sinatra. Consider adding your own code to a new file # instead of editing this one. Cucumber will automatically load all features/**/*.rb # files. require 'uri' require 'cgi' require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths")) module WithinHelpers def with_scope(locator) locator ? within(locator) { yield } : yield end end World(WithinHelpers) Given /^(?:|I )am on (.+)$/ do |page_name| visit path_to(page_name) end When /^(?:|I )go to (.+)$/ do |page_name| visit path_to(page_name) end When /^(?:|I )press "([^\"]*)"(?: within "([^\"]*)")?$/ do |button, selector| with_scope(selector) do click_button(button) end end When /^(?:|I )follow "([^\"]*)"(?: within "([^\"]*)")?$/ do |link, selector| with_scope(selector) do click_link(link) end end When /^(?:|I )fill in "([^\"]*)" with "([^\"]*)"(?: within "([^\"]*)")?$/ do |field, value, selector| with_scope(selector) do fill_in(field, :with => value) end end When /^(?:|I )fill in "([^\"]*)" for "([^\"]*)"(?: within "([^\"]*)")?$/ do |value, field, selector| with_scope(selector) do fill_in(field, :with => value) end end # Use this to fill in an entire form with data from a table. Example: # # When I fill in the following: # | Account Number | 5002 | # | Expiry date | 2009-11-01 | # | Note | Nice guy | # | Wants Email? | | # # TODO: Add support for checkbox, select og option # based on naming conventions. # When /^(?:|I )fill in the following(?: within "([^\"]*)")?:$/ do |selector, fields| with_scope(selector) do fields.rows_hash.each do |name, value| When %{I fill in "#{name}" with "#{value}"} end end end When /^(?:|I )select "([^\"]*)" from "([^\"]*)"(?: within "([^\"]*)")?$/ do |value, field, selector| with_scope(selector) do select(value, :from => field) end end When /^(?:|I )check "([^\"]*)"(?: within "([^\"]*)")?$/ do |field, selector| with_scope(selector) do check(field) end end When /^(?:|I )uncheck "([^\"]*)"(?: within "([^\"]*)")?$/ do |field, selector| with_scope(selector) do uncheck(field) end end When /^(?:|I )choose "([^\"]*)"(?: within "([^\"]*)")?$/ do |field, selector| with_scope(selector) do choose(field) end end When /^(?:|I )attach the file "([^\"]*)" to "([^\"]*)"(?: within "([^\"]*)")?$/ do |path, field, selector| with_scope(selector) do attach_file(field, path) end end Then /^(?:|I )should see JSON:$/ do |expected_json| require 'json' expected = JSON.pretty_generate(JSON.parse(expected_json)) actual = JSON.pretty_generate(JSON.parse(response.body)) expected.should == actual end Then /^(?:|I )should see "([^\"]*)"(?: within "([^\"]*)")?$/ do |text, selector| with_scope(selector) do if page.respond_to? :should page.should have_content(text) else assert page.has_content?(text) end end end Then /^(?:|I )should not see \/([^\/]*)\/(?: within "([^\"]*)")?$/ do |regexp, selector| regexp = Regexp.new(regexp) with_scope(selector) do if page.respond_to? :should page.should have_no_xpath('//*', :text => regexp) else assert page.has_no_xpath?('//*', :text => regexp) end end end Then /^the "([^\"]*)" checkbox(?: within "([^\"]*)")? should not be checked$/ do |label, selector| with_scope(selector) do field_checked = find_field(label)['checked'] if field_checked.respond_to? :should_not field_checked.should_not == 'checked' else assert_not_equal 'checked', field_checked end end end Then /^(?:|I )should be on (.+)$/ do |page_name| current_path = URI.parse(current_url).path if current_path.respond_to? :should current_path.should == path_to(page_name) else assert_equal path_to(page_name), current_path end end Then /^(?:|I )should have the following query string:$/ do |expected_pairs| query = URI.parse(current_url).query actual_params = query ? CGI.parse(query) : {} expected_params = {} expected_pairs.rows_hash.each_pair{|k,v| expected_params[k] = v.split(',')} if actual_params.respond_to? :should actual_params.should == expected_params else assert_equal expected_params, actual_params end end Then /^show me the page$/ do save_and_open_page end
mit
pritchardtw/ReactPersonalSite
src/components/Web/health_app.js
1089
import React, { Component } from 'react'; import Project from '../project'; export default class HealthApp extends Component { render() { const images = [ '../../static/images/web/true_health1.png', '../../static/images/web/true_health2.png', '../../static/images/web/true_health3.png' ]; return( <Project title="Health App!" link="https://health-app-3.firebaseapp.com/" description="I am building an app to help people learn what it means to eat healthy. I'm using firebase for BaaS with ReactJS front end. The Firebase products I'm using are Authentication (email/password, google, facebook), Firestore NoSQL Database, Storage, and Hosting. I'm still working on the site content, but you can see all the functionality I've included such as Authentication, saving progress through the app, adding notes, and facebook sharing. I am striving to make it mobile friendly as well so people can use it from their phones until there is a mobile app." images={images} /> ); } }
mit
vivekmittal/javaq
src/main/java/com/javaq/construct/JoinType.java
298
package com.javaq.construct; /** * @author Vivek Mittal */ public enum JoinType { INNER_JOIN("INNER JOIN"), LEFT_JOIN("LEFT JOIN"); private String type; private JoinType(String type) { this.type = type; } public String getType() { return type; } }
mit
simongfxu/dcagent
gulpfile.js
1474
/*jshint node:true*/ var rename = require('gulp-rename') var jshint = require('gulp-jshint') var gulp = require('gulp') var babel = require('gulp-babel') var rollup = require('gulp-rollup') var uglify = require('gulp-uglify') var sourceFile = 'dist/dcagent.v2.src.js' var options = { format: 'umd', moduleName: 'DCAgent' } var babelTransformWhitelist = [ 'es3.memberExpressionLiterals', 'es3.propertyLiterals', 'es6.arrowFunctions', 'es6.blockScoping', 'es6.constants', 'es6.forOf', 'es6.destructuring', 'es6.parameters', 'es6.properties.shorthand', 'es6.templateLiterals' ] gulp.task('compress', ['bundle'], function() { return gulp.src(sourceFile) .pipe(uglify()) .pipe(rename(function (path) { // 移除目录和后缀 path.basename = 'dcagent.v2.min' })) .pipe(gulp.dest('dist')) }); gulp.task('lint', ['bundle'], function () { return gulp.src(sourceFile) .pipe(jshint()) .pipe(jshint.reporter('default')) }) gulp.task('bundle', function () { return gulp.src('src/index.js', {read: false}) .pipe(rollup(options)) .on('error', function(err) { console.log('任务结束,执行出错:') console.log(err) this.emit('end') }) .pipe(rename(function (path) { // 移除目录和后缀 path.basename = 'dcagent.v2.src' })) .pipe(babel({whitelist: babelTransformWhitelist})) .pipe(gulp.dest('dist')) }) gulp.task('default', ['lint', 'compress'])
mit
gamejolt/gamejolt
src/_common/social/youtube/sdk/sdk.service.ts
698
export class YoutubeSdk { private static isBootstrapped = false; static load() { if (import.meta.env.SSR) { return; } if (!this.isBootstrapped) { let bootstrapLib = (d: any, s: any, id: any) => { let js: any, fjs = d.getElementsByTagName(s)[0]; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = 'https://apis.google.com/js/platform.js'; fjs.parentNode.insertBefore(js, fjs); } }; bootstrapLib(document, 'script', 'youtube-sdk'); } else { setTimeout(() => { if (typeof (window as any).gapi !== 'undefined') { (window as any).gapi.ytsubscribe.go(); } }); } this.isBootstrapped = true; } }
mit
korun/d2b
app/models/arena.rb
908
class Arena < ActiveRecord::Base BACKGROUND_CONTENT_TYPES = %w[ image/jpeg ].each(&:freeze).freeze FOREGROUND_CONTENT_TYPES = %w[ image/gif image/png ].each(&:freeze).freeze has_attached_file :background #, styles: {medium: '220x300>', thumb: '50x50>'} #, default_url: '/images/:style/missing.png' has_attached_file :foreground validates :name, presence: true, uniqueness: true, length: {maximum: 255} validates_attachment_size :background, less_than: 5.megabytes validates_attachment_file_name :background, matches: /jpe?g\Z/ validates_attachment_content_type :background, content_type: BACKGROUND_CONTENT_TYPES validates_attachment_size :foreground, less_than: 1.megabyte validates_attachment_file_name :foreground, matches: [/gif\Z/, /png\Z/] validates_attachment_content_type :foreground, content_type: FOREGROUND_CONTENT_TYPES end
mit
ApprecieOpenSource/Apprecie
public/js/validation/messages.js
363
/** * Created by hu86 on 18/08/2015. */ function validateMessage(subject, body) { if (subject == '') { errors.push('Please enter a subject'); } if (subject.length > 100) { errors.push('Your subject is too long. Please keep it below 100 characters') } if (body == '') { errors.push('Please enter a message'); } }
mit
hybmg57/jobeet
lib/vendor/swiftmailer/classes/Swift/Encoder/QpEncoder.php
10074
<?php /* * This file is part of SwiftMailer. * (c) 2004-2009 Chris Corbyn * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Handles Quoted Printable (QP) Encoding in Swift Mailer. * Possibly the most accurate RFC 2045 QP implementation found in PHP. * @package Swift * @subpackage Encoder * @author Chris Corbyn */ class Swift_Encoder_QpEncoder implements Swift_Encoder { /** * The CharacterStream used for reading characters (as opposed to bytes). * @var Swift_CharacterStream * @access protected */ protected $_charStream; /** * A filter used if input should be canonicalized. * @var Swift_StreamFilter * @access protected */ protected $_filter; /** * Pre-computed QP for HUGE optmization. * @var string[] * @access protected */ protected static $_qpMap = array( 0 => '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04', 5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09', 10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E', 15 => '=0F', 16 => '=10', 17 => '=11', 18 => '=12', 19 => '=13', 20 => '=14', 21 => '=15', 22 => '=16', 23 => '=17', 24 => '=18', 25 => '=19', 26 => '=1A', 27 => '=1B', 28 => '=1C', 29 => '=1D', 30 => '=1E', 31 => '=1F', 32 => '=20', 33 => '=21', 34 => '=22', 35 => '=23', 36 => '=24', 37 => '=25', 38 => '=26', 39 => '=27', 40 => '=28', 41 => '=29', 42 => '=2A', 43 => '=2B', 44 => '=2C', 45 => '=2D', 46 => '=2E', 47 => '=2F', 48 => '=30', 49 => '=31', 50 => '=32', 51 => '=33', 52 => '=34', 53 => '=35', 54 => '=36', 55 => '=37', 56 => '=38', 57 => '=39', 58 => '=3A', 59 => '=3B', 60 => '=3C', 61 => '=3D', 62 => '=3E', 63 => '=3F', 64 => '=40', 65 => '=41', 66 => '=42', 67 => '=43', 68 => '=44', 69 => '=45', 70 => '=46', 71 => '=47', 72 => '=48', 73 => '=49', 74 => '=4A', 75 => '=4B', 76 => '=4C', 77 => '=4D', 78 => '=4E', 79 => '=4F', 80 => '=50', 81 => '=51', 82 => '=52', 83 => '=53', 84 => '=54', 85 => '=55', 86 => '=56', 87 => '=57', 88 => '=58', 89 => '=59', 90 => '=5A', 91 => '=5B', 92 => '=5C', 93 => '=5D', 94 => '=5E', 95 => '=5F', 96 => '=60', 97 => '=61', 98 => '=62', 99 => '=63', 100 => '=64', 101 => '=65', 102 => '=66', 103 => '=67', 104 => '=68', 105 => '=69', 106 => '=6A', 107 => '=6B', 108 => '=6C', 109 => '=6D', 110 => '=6E', 111 => '=6F', 112 => '=70', 113 => '=71', 114 => '=72', 115 => '=73', 116 => '=74', 117 => '=75', 118 => '=76', 119 => '=77', 120 => '=78', 121 => '=79', 122 => '=7A', 123 => '=7B', 124 => '=7C', 125 => '=7D', 126 => '=7E', 127 => '=7F', 128 => '=80', 129 => '=81', 130 => '=82', 131 => '=83', 132 => '=84', 133 => '=85', 134 => '=86', 135 => '=87', 136 => '=88', 137 => '=89', 138 => '=8A', 139 => '=8B', 140 => '=8C', 141 => '=8D', 142 => '=8E', 143 => '=8F', 144 => '=90', 145 => '=91', 146 => '=92', 147 => '=93', 148 => '=94', 149 => '=95', 150 => '=96', 151 => '=97', 152 => '=98', 153 => '=99', 154 => '=9A', 155 => '=9B', 156 => '=9C', 157 => '=9D', 158 => '=9E', 159 => '=9F', 160 => '=A0', 161 => '=A1', 162 => '=A2', 163 => '=A3', 164 => '=A4', 165 => '=A5', 166 => '=A6', 167 => '=A7', 168 => '=A8', 169 => '=A9', 170 => '=AA', 171 => '=AB', 172 => '=AC', 173 => '=AD', 174 => '=AE', 175 => '=AF', 176 => '=B0', 177 => '=B1', 178 => '=B2', 179 => '=B3', 180 => '=B4', 181 => '=B5', 182 => '=B6', 183 => '=B7', 184 => '=B8', 185 => '=B9', 186 => '=BA', 187 => '=BB', 188 => '=BC', 189 => '=BD', 190 => '=BE', 191 => '=BF', 192 => '=C0', 193 => '=C1', 194 => '=C2', 195 => '=C3', 196 => '=C4', 197 => '=C5', 198 => '=C6', 199 => '=C7', 200 => '=C8', 201 => '=C9', 202 => '=CA', 203 => '=CB', 204 => '=CC', 205 => '=CD', 206 => '=CE', 207 => '=CF', 208 => '=D0', 209 => '=D1', 210 => '=D2', 211 => '=D3', 212 => '=D4', 213 => '=D5', 214 => '=D6', 215 => '=D7', 216 => '=D8', 217 => '=D9', 218 => '=DA', 219 => '=DB', 220 => '=DC', 221 => '=DD', 222 => '=DE', 223 => '=DF', 224 => '=E0', 225 => '=E1', 226 => '=E2', 227 => '=E3', 228 => '=E4', 229 => '=E5', 230 => '=E6', 231 => '=E7', 232 => '=E8', 233 => '=E9', 234 => '=EA', 235 => '=EB', 236 => '=EC', 237 => '=ED', 238 => '=EE', 239 => '=EF', 240 => '=F0', 241 => '=F1', 242 => '=F2', 243 => '=F3', 244 => '=F4', 245 => '=F5', 246 => '=F6', 247 => '=F7', 248 => '=F8', 249 => '=F9', 250 => '=FA', 251 => '=FB', 252 => '=FC', 253 => '=FD', 254 => '=FE', 255 => '=FF' ); protected static $_safeMapShare = array(); /** * A map of non-encoded ascii characters. * @var string[] * @access protected */ protected $_safeMap = array(); /** * Creates a new QpEncoder for the given CharacterStream. * @param Swift_CharacterStream $charStream to use for reading characters * @param Swift_StreamFilter $filter if input should be canonicalized */ public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null) { $this->_charStream = $charStream; if(!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) { $this->initSafeMap(); self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap; } else { $this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()]; } $this->_filter = $filter; } public function __sleep() { return array('_charStream', '_filter'); } public function __wakeup() { if(!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) { $this->initSafeMap(); self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap; } else { $this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()]; } } protected function getSafeMapShareId() { return get_class($this); } protected function initSafeMap() { foreach (array_merge( array(0x09, 0x20), range(0x21, 0x3C), range(0x3E, 0x7E)) as $byte) { $this->_safeMap[$byte] = chr($byte); } } /** * Takes an unencoded string and produces a QP encoded string from it. * QP encoded strings have a maximum line length of 76 characters. * If the first line needs to be shorter, indicate the difference with * $firstLineOffset. * @param string $string to encode * @param int $firstLineOffset, optional * @param int $maxLineLength, optional, 0 indicates the default of 76 chars * @return string */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { if ($maxLineLength > 76 || $maxLineLength <= 0) { $maxLineLength = 76; } $thisLineLength = $maxLineLength - $firstLineOffset; $lines = array(); $lNo = 0; $lines[$lNo] = ''; $currentLine =& $lines[$lNo++]; $size=$lineLen=0; $this->_charStream->flushContents(); $this->_charStream->importString($string); //Fetching more than 4 chars at one is slower, as is fetching fewer bytes // Conveniently 4 chars is the UTF-8 safe number since UTF-8 has up to 6 // bytes per char and (6 * 4 * 3 = 72 chars per line) * =NN is 3 bytes while (false !== $bytes = $this->_nextSequence()) { //If we're filtering the input if (isset($this->_filter)) { //If we can't filter because we need more bytes while ($this->_filter->shouldBuffer($bytes)) { //Then collect bytes into the buffer if (false === $moreBytes = $this->_nextSequence(1)) { break; } foreach ($moreBytes as $b) { $bytes[] = $b; } } //And filter them $bytes = $this->_filter->filter($bytes); } $enc = $this->_encodeByteSequence($bytes, $size); if ($currentLine && $lineLen+$size >= $thisLineLength) { $lines[$lNo] = ''; $currentLine =& $lines[$lNo++]; $thisLineLength = $maxLineLength; $lineLen=0; } $lineLen+=$size; $currentLine .= $enc; } return $this->_standardize(implode("=\r\n", $lines)); } /** * Updates the charset used. * @param string $charset */ public function charsetChanged($charset) { $this->_charStream->setCharacterSet($charset); } // -- Protected methods /** * Encode the given byte array into a verbatim QP form. * @param int[] $bytes * @return string * @access protected */ protected function _encodeByteSequence(array $bytes, &$size) { $ret = ''; $size=0; foreach ($bytes as $b) { if (isset($this->_safeMap[$b])) { $ret .= $this->_safeMap[$b]; ++$size; } else { $ret .= self::$_qpMap[$b]; $size+=3; } } return $ret; } /** * Get the next sequence of bytes to read from the char stream. * @param int $size number of bytes to read * @return int[] * @access protected */ protected function _nextSequence($size = 4) { return $this->_charStream->readBytes($size); } /** * Make sure CRLF is correct and HT/SPACE are in valid places. * @param string $string * @return string * @access protected */ protected function _standardize($string) { $string = str_replace(array("\t=0D=0A", " =0D=0A", "=0D=0A"), array("=09\r\n", "=20\r\n", "\r\n"), $string ); switch ($end = ord(substr($string, -1))) { case 0x09: case 0x20: $string = substr_replace($string, self::$_qpMap[$end], -1); } return $string; } }
mit