repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
gavinlaking/vedeu
|
lib/vedeu/esc/background.rb
|
<filename>lib/vedeu/esc/background.rb
# frozen_string_literal: true
module Vedeu
module EscapeSequences
# Provides background colour related escape sequences.
#
# @api public
# See {file:docs/dsl/by_method/esc.md}
module Background
extend Forwardable
extend self
def_delegators Vedeu::EscapeSequences::Actions, :bg_reset
# @macro param_block
# @return [String]
def on_black(&block)
background("\e[40m", &block)
end
# @macro param_block
# @return [String]
def on_red(&block)
background("\e[41m", &block)
end
# @macro param_block
# @return [String]
def on_green(&block)
background("\e[42m", &block)
end
# @macro param_block
# @return [String]
def on_yellow(&block)
background("\e[43m", &block)
end
# @macro param_block
# @return [String]
def on_blue(&block)
background("\e[44m", &block)
end
# @macro param_block
# @return [String]
def on_magenta(&block)
background("\e[45m", &block)
end
# @macro param_block
# @return [String]
def on_cyan(&block)
background("\e[46m", &block)
end
# @macro param_block
# @return [String]
def on_light_grey(&block)
background("\e[47m", &block)
end
# @macro param_block
# @return [String]
def on_default(&block)
background(bg_reset, &block)
end
# @macro param_block
# @return [String]
def on_dark_grey(&block)
background("\e[100m", &block)
end
# @macro param_block
# @return [String]
def on_light_red(&block)
background("\e[101m", &block)
end
# @macro param_block
# @return [String]
def on_light_green(&block)
background("\e[102m", &block)
end
# @macro param_block
# @return [String]
def on_light_yellow(&block)
background("\e[103m", &block)
end
# @macro param_block
# @return [String]
def on_light_blue(&block)
background("\e[104m", &block)
end
# @macro param_block
# @return [String]
def on_light_magenta(&block)
background("\e[105m", &block)
end
# @macro param_block
# @return [String]
def on_light_cyan(&block)
background("\e[106m", &block)
end
# @macro param_block
# @return [String]
def on_white(&block)
background("\e[107m", &block)
end
private
# @param sequence [String] The colour escape sequence.
# @macro param_block
# @return [String]
def background(sequence, &block)
if block_given?
sequence + yield + bg_reset
else
sequence
end
end
end # Background
end # EscapeSequences
end # Vedeu
|
lheureuxe13/oppia
|
core/controllers/base.py
|
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Base constants and handlers."""
from __future__ import absolute_import
from __future__ import unicode_literals
import base64
import datetime
import functools
import hmac
import json
import logging
import os
import re
import time
import urllib
from core import feconf
from core import python_utils
from core import utils
from core.controllers import payload_validator
from core.domain import auth_domain
from core.domain import auth_services
from core.domain import config_domain
from core.domain import config_services
from core.domain import user_services
import webapp2
from typing import Any, Dict, Optional # isort: skip
ONE_DAY_AGO_IN_SECS = -24 * 60 * 60
DEFAULT_CSRF_SECRET = 'oppia csrf secret'
CSRF_SECRET = config_domain.ConfigProperty(
'oppia_csrf_secret', {'type': 'unicode'},
'Text used to encrypt CSRF tokens.', DEFAULT_CSRF_SECRET)
# NOTE: These handlers manage user sessions and serve auth pages. Thus, we
# should never reject or replace them when running in maintenance mode;
# otherwise admins will be unable to access the site.
AUTH_HANDLER_PATHS = (
'/csrfhandler',
'/login',
'/session_begin',
'/session_end',
)
@functools.lru_cache(maxsize=128)
def load_template(filename):
"""Return the HTML file contents at filepath.
Args:
filename: str. Name of the requested HTML file.
Returns:
str. The HTML file content.
"""
filepath = os.path.join(feconf.FRONTEND_TEMPLATES_DIR, filename)
with python_utils.open_file(filepath, 'r') as f:
html_text = f.read()
return html_text
class SessionBeginHandler(webapp2.RequestHandler):
"""Handler for creating new authentication sessions."""
def get(self):
"""Establishes a new auth session."""
auth_services.establish_auth_session(self.request, self.response)
class SessionEndHandler(webapp2.RequestHandler):
"""Handler for destroying existing authentication sessions."""
def get(self):
"""Destroys an existing auth session."""
auth_services.destroy_auth_session(self.response)
class UserFacingExceptions:
"""This class contains all the exception class definitions used."""
class NotLoggedInException(Exception):
"""Error class for users that are not logged in (error code 401)."""
pass
class InvalidInputException(Exception):
"""Error class for invalid input on the user side (error code 400)."""
pass
class UnauthorizedUserException(Exception):
"""Error class for unauthorized access."""
pass
class PageNotFoundException(Exception):
"""Error class for a page not found error (error code 404)."""
pass
class InternalErrorException(Exception):
"""Error class for an internal server side error (error code 500)."""
pass
class TemporaryMaintenanceException(Exception):
"""Error class for when the server is currently down for temporary
maintenance (error code 503).
"""
def __init__(self):
super(
UserFacingExceptions.TemporaryMaintenanceException, self
).__init__(
'Oppia is currently being upgraded, and the site should be up '
'and running again in a few hours. Thanks for your patience!')
class BaseHandler(webapp2.RequestHandler):
"""Base class for all Oppia handlers."""
# Whether to check POST and PUT payloads for CSRF tokens prior to
# processing them. Can be overridden by subclasses if this check is
# not necessary.
REQUIRE_PAYLOAD_CSRF_CHECK = True
# Whether to redirect requests corresponding to a logged-in user who has
# not completed signup in to the signup page. This ensures that logged-in
# users have agreed to the latest terms.
REDIRECT_UNFINISHED_SIGNUPS = True
# What format the get method returns when exception raised, json or html.
GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_HTML
POST_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON
PUT_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON
DELETE_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON
# Using Dict[str, Any] here because the following schema can have a
# recursive structure and currently mypy doesn't support recursive type
# currently. See: https://github.com/python/mypy/issues/731
URL_PATH_ARGS_SCHEMAS: Optional[Dict[str, Any]] = None
# Using Dict[str, Any] here because the following schema can have a
# recursive structure and currently mypy doesn't support recursive type
# currently. See: https://github.com/python/mypy/issues/731
HANDLER_ARGS_SCHEMAS: Optional[Dict[str, Any]] = None
def __init__(self, request, response): # pylint: disable=super-init-not-called
# Set self.request, self.response and self.app.
self.initialize(request, response)
self.start_time = datetime.datetime.utcnow()
# Initializes the return dict for the handlers.
self.values = {}
# TODO(#13155): Remove the if-else part once all the handlers have had
# schema validation implemented.
if self.request.get('payload'):
self.payload = json.loads(self.request.get('payload'))
else:
self.payload = None
self.iframed = False
self.user_id = None
self.username = None
self.email = None
self.partially_logged_in = False
self.user_is_scheduled_for_deletion = False
self.current_user_is_super_admin = False
# Once the attribute `normalized_request` is type annotated here, make
# sure to fix all the subclasses using normalized_request.get() method
# by removing their type: ignore[union-attr] and using a type cast
# instead to eliminate the possibility on union types.
# e.g. ClassroomAccessValidationHandler.
self.normalized_request = None
self.normalized_payload = None
try:
auth_claims = auth_services.get_auth_claims_from_request(request)
except auth_domain.StaleAuthSessionError:
auth_services.destroy_auth_session(self.response)
self.redirect(user_services.create_login_url(self.request.uri))
return
except auth_domain.InvalidAuthSessionError:
logging.exception('User session is invalid!')
auth_services.destroy_auth_session(self.response)
self.redirect(user_services.create_login_url(self.request.uri))
return
else:
self.current_user_is_super_admin = (
auth_claims is not None and auth_claims.role_is_super_admin)
if auth_claims:
auth_id = auth_claims.auth_id
user_settings = user_services.get_user_settings_by_auth_id(auth_id)
if user_settings is None:
# If the user settings are not yet created and the request leads
# to signup page create a new user settings. Otherwise logout
# the not-fully registered user.
email = auth_claims.email
if 'signup?' in self.request.uri:
user_settings = (
user_services.create_new_user(auth_id, email))
else:
logging.exception(
'Cannot find user %s with email %s on page %s' % (
auth_id, email, self.request.uri))
auth_services.destroy_auth_session(self.response)
return
self.email = user_settings.email
self.values['user_email'] = user_settings.email
self.user_id = user_settings.user_id
if user_settings.deleted:
self.user_is_scheduled_for_deletion = user_settings.deleted
elif (self.REDIRECT_UNFINISHED_SIGNUPS and
not user_services.has_fully_registered_account(self.user_id)):
self.partially_logged_in = True
else:
self.username = user_settings.username
self.values['username'] = self.username
# In order to avoid too many datastore writes, we do not bother
# recording a log-in if the current time is sufficiently close
# to the last log-in time.
if (user_settings.last_logged_in is None or
not utils.are_datetimes_close(
datetime.datetime.utcnow(),
user_settings.last_logged_in)):
user_services.record_user_logged_in(self.user_id)
self.roles = (
[feconf.ROLE_ID_GUEST]
if self.user_id is None else user_settings.roles)
self.user = user_services.get_user_actions_info(self.user_id)
if not self._is_requested_path_currently_accessible_to_user():
auth_services.destroy_auth_session(self.response)
return
self.values['is_super_admin'] = self.current_user_is_super_admin
def dispatch(self):
"""Overrides dispatch method in webapp2 superclass.
Raises:
Exception. The CSRF token is missing.
UnauthorizedUserException. The CSRF token is invalid.
"""
request_split = urllib.parse.urlsplit(self.request.uri)
# If the request is to the old demo server, redirect it permanently to
# the new demo server. (Unless it is a cron job request, because cron
# job destination URLs are generated by App Engine and we can't change
# their destination.)
if (request_split.netloc == 'oppiaserver.appspot.com' and
not request_split.path.startswith('/cron/')):
self.redirect('https://oppiatestserver.appspot.com', permanent=True)
return
if not self._is_requested_path_currently_accessible_to_user():
self.handle_exception(
self.TemporaryMaintenanceException(), self.app.debug)
return
if self.user_is_scheduled_for_deletion:
self.redirect(
'/logout?redirect_url=%s' % feconf.PENDING_ACCOUNT_DELETION_URL)
return
if self.partially_logged_in and request_split.path != '/logout':
self.redirect('/logout?redirect_url=%s' % request_split.path)
return
if self.payload is not None and self.REQUIRE_PAYLOAD_CSRF_CHECK:
try:
# If user opens a new tab during signup process, the user_id
# parameter is set to None and this causes the signup session
# to expire. The code here checks if user is on the signup
# page and the user_id is None, if that is the case an exception
# is raised which is handled by the frontend by showing a
# continue to registration modal.
if 'signup' in self.request.uri and not self.user_id:
raise self.UnauthorizedUserException(
'Registration session expired.')
csrf_token = self.request.get('csrf_token')
if not csrf_token:
raise self.UnauthorizedUserException(
'Missing CSRF token. Changes were not saved. '
'Please report this bug.')
is_csrf_token_valid = CsrfTokenManager.is_csrf_token_valid(
self.user_id, csrf_token)
if not is_csrf_token_valid:
raise self.UnauthorizedUserException(
'Your session has expired, and unfortunately your '
'changes cannot be saved. Please refresh the page.')
except Exception as e:
logging.exception('%s: payload %s', e, self.payload)
self.handle_exception(e, self.app.debug)
return
schema_validation_succeeded = True
try:
self.validate_and_normalize_args()
except self.InvalidInputException as e:
self.handle_exception(e, self.app.debug)
schema_validation_succeeded = False
# TODO(#13155): Remove this clause once all the handlers have had
# schema validation implemented.
except NotImplementedError as e:
self.handle_exception(e, self.app.debug)
schema_validation_succeeded = False
if not schema_validation_succeeded:
return
super(BaseHandler, self).dispatch()
def validate_and_normalize_args(self):
"""Validates schema for controller layer handler class arguments.
Raises:
InvalidInputException. Schema validation failed.
NotImplementedError. Schema is not provided in handler class.
"""
handler_class_name = self.__class__.__name__
request_method = self.request.environ['REQUEST_METHOD']
url_path_args = self.request.route_kwargs
handler_class_names_with_no_schema = (
payload_validator.HANDLER_CLASS_NAMES_WITH_NO_SCHEMA)
if handler_class_name in handler_class_names_with_no_schema:
return
handler_args = {}
payload_arg_keys = []
request_arg_keys = []
for arg in self.request.arguments():
if arg == 'csrf_token':
# 'csrf_token' has been already validated in the
# dispatch method.
continue
elif arg == 'source':
source_url = self.request.get('source')
regex_pattern = (
r'http[s]?://(?:[a-zA-Z]|[0-9]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' # pylint: disable=line-too-long
)
regex_verified_url = re.findall(regex_pattern, source_url)
if not regex_verified_url:
raise self.InvalidInputException(
'Not a valid source url.')
elif arg == 'payload':
payload_args = self.payload
if payload_args is not None:
payload_arg_keys = list(payload_args.keys())
handler_args.update(payload_args)
else:
request_arg_keys.append(arg)
handler_args[arg] = self.request.get(arg)
# For html handlers, extra args are allowed (to accommodate
# e.g. utm parameters which are not used by the backend but
# needed for analytics).
extra_args_are_allowed = (
self.GET_HANDLER_ERROR_RETURN_TYPE == 'html' and
request_method == 'GET')
if self.URL_PATH_ARGS_SCHEMAS is None:
raise NotImplementedError(
'Missing schema for url path args in %s handler class.' % (
handler_class_name))
schema_for_url_path_args = self.URL_PATH_ARGS_SCHEMAS
normalized_arg_values, errors = (
payload_validator.validate(
url_path_args, schema_for_url_path_args, extra_args_are_allowed)
)
if errors:
raise self.InvalidInputException('\n'.join(errors))
# This check ensures that if a request method is not defined
# in the handler class then schema validation will not raise
# NotImplementedError for that corresponding request method.
if request_method in ['GET', 'POST', 'PUT', 'DELETE'] and (
getattr(self.__class__, request_method.lower()) ==
getattr(BaseHandler, request_method.lower())):
return
try:
schema_for_request_method = self.HANDLER_ARGS_SCHEMAS[
request_method]
except Exception:
raise NotImplementedError(
'Missing schema for %s method in %s handler class.' % (
request_method, handler_class_name))
allow_string_to_bool_conversion = request_method in ['GET', 'DELETE']
normalized_arg_values, errors = (
payload_validator.validate(
handler_args, schema_for_request_method, extra_args_are_allowed,
allow_string_to_bool_conversion)
)
self.normalized_payload = {
arg: normalized_arg_values.get(arg) for arg in payload_arg_keys
}
self.normalized_request = {
arg: normalized_arg_values.get(arg) for arg in request_arg_keys
}
# The following keys are absent in request/payload but present in
# normalized_arg_values because these args are populated from their
# default_value provided in the schema.
keys_that_correspond_to_default_values = list(
set(normalized_arg_values.keys()) -
set(payload_arg_keys + request_arg_keys)
)
# Populate the payload/request with the default args before passing
# execution onwards to the handler.
for arg in keys_that_correspond_to_default_values:
if request_method in ['GET', 'DELETE']:
self.normalized_request[arg] = normalized_arg_values.get(arg)
else:
self.normalized_payload[arg] = normalized_arg_values.get(arg)
if errors:
raise self.InvalidInputException('\n'.join(errors))
@property
def current_user_is_site_maintainer(self):
"""Returns whether the current user is a site maintainer.
A super admin or release coordinator is also a site maintainer.
Returns:
bool. Whether the current user is a site maintainer.
"""
return (
self.current_user_is_super_admin or
feconf.ROLE_ID_RELEASE_COORDINATOR in self.roles)
def _is_requested_path_currently_accessible_to_user(self):
"""Checks whether the requested path is currently accessible to user.
Returns:
bool. Whether the requested path is currently accessible to user.
"""
return (
self.request.path in AUTH_HANDLER_PATHS or
not feconf.ENABLE_MAINTENANCE_MODE or
self.current_user_is_site_maintainer)
def get(self, *args, **kwargs): # pylint: disable=unused-argument
"""Base method to handle GET requests."""
logging.warning('Invalid URL requested: %s', self.request.uri)
self.error(404)
self._render_exception(
404, {
'error': 'Could not find the page %s.' % self.request.uri})
def post(self, *args): # pylint: disable=unused-argument
"""Base method to handle POST requests.
Raises:
PageNotFoundException. Page not found error (error code 404).
"""
raise self.PageNotFoundException
def put(self, *args): # pylint: disable=unused-argument
"""Base method to handle PUT requests.
Raises:
PageNotFoundException. Page not found error (error code 404).
"""
raise self.PageNotFoundException
def delete(self, *args): # pylint: disable=unused-argument
"""Base method to handle DELETE requests.
Raises:
PageNotFoundException. Page not found error (error code 404).
"""
raise self.PageNotFoundException
def render_json(self, values: Dict[Any, Any]) -> None:
"""Prepares JSON response to be sent to the client.
Args:
values: dict. The key-value pairs to encode in the JSON response.
"""
self.response.content_type = 'application/json; charset=utf-8'
self.response.headers['Content-Disposition'] = (
'attachment; filename="oppia-attachment.txt"')
self.response.headers['Strict-Transport-Security'] = (
'max-age=31536000; includeSubDomains')
self.response.headers['X-Content-Type-Options'] = 'nosniff'
self.response.headers['X-Xss-Protection'] = '1; mode=block'
json_output = json.dumps(values, cls=utils.JSONEncoderForHTML)
# Write expects bytes, thus we need to encode the JSON output.
self.response.write(
b'%s%s' % (feconf.XSSI_PREFIX, json_output.encode('utf-8')))
def render_downloadable_file(self, file, filename, content_type):
"""Prepares downloadable content to be sent to the client.
Args:
file: BytesIO. The data of the downloadable file.
filename: str. The name of the file to be rendered.
content_type: str. The type of file to be rendered.
"""
self.response.headers['Content-Type'] = content_type
self.response.headers['Content-Disposition'] = (
'attachment; filename=%s' % filename)
self.response.charset = 'utf-8'
# We use this super in order to bypass the write method
# in webapp2.Response, since webapp2.Response doesn't support writing
# bytes.
super(webapp2.Response, self.response).write(file.getvalue()) # pylint: disable=bad-super-call
def render_template(self, filepath, iframe_restriction='DENY'):
"""Prepares an HTML response to be sent to the client.
Args:
filepath: str. The template filepath.
iframe_restriction: str or None. Possible values are
'DENY' and 'SAMEORIGIN':
DENY: Strictly prevents the template to load in an iframe.
SAMEORIGIN: The template can only be displayed in a frame
on the same origin as the page itself.
"""
# The 'no-store' must be used to properly invalidate the cache when we
# deploy a new version, using only 'no-cache' doesn't work properly.
self.response.cache_control.no_store = True
self.response.cache_control.must_revalidate = True
self.response.headers['Strict-Transport-Security'] = (
'max-age=31536000; includeSubDomains')
self.response.headers['X-Content-Type-Options'] = 'nosniff'
self.response.headers['X-Xss-Protection'] = '1; mode=block'
if iframe_restriction is not None:
if iframe_restriction in ['SAMEORIGIN', 'DENY']:
self.response.headers['X-Frame-Options'] = (
str(iframe_restriction))
else:
raise Exception(
'Invalid X-Frame-Options: %s' % iframe_restriction)
self.response.expires = 'Mon, 01 Jan 1990 00:00:00 GMT'
self.response.pragma = 'no-cache'
self.response.write(load_template(filepath))
def _render_exception_json_or_html(self, return_type, values):
"""Renders an error page, or an error JSON response.
Args:
return_type: str. Indicator to return JSON or HTML.
values: dict. The key-value pairs to include in the response.
"""
method = self.request.environ['REQUEST_METHOD']
if return_type == feconf.HANDLER_TYPE_HTML and method == 'GET':
self.values.update(values)
if self.iframed:
self.render_template(
'error-iframed.mainpage.html', iframe_restriction=None)
elif values['status_code'] == 503:
self.render_template('maintenance-page.mainpage.html')
elif values['status_code'] == 404:
# Only 404 routes can be handled with angular router as it only
# has access to the path, not to the status code.
# That's why 404 status code is treated differently.
self.render_template('oppia-root.mainpage.html')
else:
self.render_template(
'error-page-%s.mainpage.html' % values['status_code'])
else:
if return_type not in (
feconf.HANDLER_TYPE_JSON, feconf.HANDLER_TYPE_DOWNLOADABLE):
logging.warning(
'Not a recognized return type: defaulting to render JSON.')
self.render_json(values)
def _render_exception(self, error_code, values):
"""Renders an error page, or an error JSON response.
Args:
error_code: int. The HTTP status code (expected to be one of
400, 401, 404 or 500).
values: dict. The key-value pairs to include in the response.
"""
# The error codes here should be in sync with the error pages
# generated via webpack.common.config.ts.
assert error_code in [400, 401, 404, 500, 503]
values['status_code'] = error_code
method = self.request.environ['REQUEST_METHOD']
if method == 'GET':
self._render_exception_json_or_html(
self.GET_HANDLER_ERROR_RETURN_TYPE, values)
elif method == 'POST':
self._render_exception_json_or_html(
self.POST_HANDLER_ERROR_RETURN_TYPE, values)
elif method == 'PUT':
self._render_exception_json_or_html(
self.PUT_HANDLER_ERROR_RETURN_TYPE, values)
elif method == 'DELETE':
self._render_exception_json_or_html(
self.DELETE_HANDLER_ERROR_RETURN_TYPE, values)
else:
logging.warning('Not a recognized request method.')
self._render_exception_json_or_html(None, values)
def handle_exception(self, exception, unused_debug_mode):
"""Overwrites the default exception handler.
Args:
exception: Exception. The exception that was thrown.
unused_debug_mode: bool. True if the web application is running
in debug mode.
"""
if isinstance(exception, self.NotLoggedInException):
# This checks if the response should be JSON or HTML.
# For GET requests, there is no payload, so we check against
# GET_HANDLER_ERROR_RETURN_TYPE.
# Otherwise, we check whether self.payload exists.
if (self.payload is not None or
self.GET_HANDLER_ERROR_RETURN_TYPE ==
feconf.HANDLER_TYPE_JSON):
self.error(401)
self._render_exception(
401, {
'error': (
'You must be logged in to access this resource.')})
else:
self.redirect(user_services.create_login_url(self.request.uri))
return
logging.exception('Exception raised: %s', exception)
if isinstance(exception, self.PageNotFoundException):
logging.warning('Invalid URL requested: %s', self.request.uri)
self.error(404)
self._render_exception(
404, {
'error': 'Could not find the page %s.' % self.request.uri})
return
logging.exception('Exception raised: %s', exception)
if isinstance(exception, self.UnauthorizedUserException):
self.error(401)
self._render_exception(401, {'error': str(exception)})
return
if isinstance(exception, self.InvalidInputException):
self.error(400)
self._render_exception(400, {'error': str(exception)})
return
if isinstance(exception, self.InternalErrorException):
self.error(500)
self._render_exception(500, {'error': str(exception)})
return
if isinstance(exception, self.TemporaryMaintenanceException):
self.error(503)
self._render_exception(503, {'error': str(exception)})
return
self.error(500)
self._render_exception(500, {'error': str(exception)})
InternalErrorException = UserFacingExceptions.InternalErrorException
InvalidInputException = UserFacingExceptions.InvalidInputException
NotLoggedInException = UserFacingExceptions.NotLoggedInException
PageNotFoundException = UserFacingExceptions.PageNotFoundException
UnauthorizedUserException = UserFacingExceptions.UnauthorizedUserException
TemporaryMaintenanceException = (
UserFacingExceptions.TemporaryMaintenanceException)
class Error404Handler(BaseHandler):
"""Handles 404 errors."""
pass
class CsrfTokenManager:
"""Manages page/user tokens in memcache to protect against CSRF."""
# Max age of the token (48 hours).
_CSRF_TOKEN_AGE_SECS = 60 * 60 * 48
# Default user id for non-logged-in users.
_USER_ID_DEFAULT = 'non_logged_in_user'
@classmethod
def init_csrf_secret(cls):
"""Verify that non-default CSRF secret exists; creates one if not."""
# Any non-default value is fine.
if CSRF_SECRET.value and CSRF_SECRET.value != DEFAULT_CSRF_SECRET:
return
# Initialize to random value.
config_services.set_property(
feconf.SYSTEM_COMMITTER_ID, CSRF_SECRET.name,
base64.urlsafe_b64encode(os.urandom(20)))
@classmethod
def _create_token(cls, user_id, issued_on):
"""Creates a new CSRF token.
Args:
user_id: str|None. The user_id for which the token is generated.
issued_on: float. The timestamp at which the token was issued.
Returns:
str. The generated CSRF token.
"""
cls.init_csrf_secret()
# The token has 4 parts: hash of the actor user id, hash of the page
# name, hash of the time issued and plain text of the time issued.
if user_id is None:
user_id = cls._USER_ID_DEFAULT
# Round time to seconds.
issued_on = str(int(issued_on))
digester = hmac.new(CSRF_SECRET.value.encode('utf-8'))
digester.update(user_id.encode('utf-8'))
digester.update(b':')
digester.update(issued_on.encode('utf-8'))
digest = digester.digest()
# The b64encode returns bytes, so we first need to decode the returned
# bytes to string.
token = '%s/%s' % (
issued_on, base64.urlsafe_b64encode(digest).decode('utf-8'))
return token
@classmethod
def _get_current_time(cls):
"""Returns the current server time.
Returns:
float. The time in seconds as floating point number.
"""
return time.time()
@classmethod
def create_csrf_token(cls, user_id):
"""Creates a CSRF token for the given user_id.
Args:
user_id: str|None. The user_id for whom the token is generated.
Returns:
str. The generated CSRF token.
"""
return cls._create_token(user_id, cls._get_current_time())
@classmethod
def is_csrf_token_valid(cls, user_id, token):
"""Validates a given CSRF token.
Args:
user_id: str|None. The user_id to validate the CSRF token against.
token: str. The CSRF token to validate.
Returns:
bool. Whether the given CSRF token is valid.
"""
try:
parts = token.split('/')
if len(parts) != 2:
return False
issued_on = int(parts[0])
age = cls._get_current_time() - issued_on
if age > cls._CSRF_TOKEN_AGE_SECS:
return False
authentic_token = cls._create_token(user_id, issued_on)
if authentic_token == token:
return True
return False
except Exception:
return False
class CsrfTokenHandler(BaseHandler):
"""Handles sending CSRF tokens to the frontend."""
GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON
REDIRECT_UNFINISHED_SIGNUPS = False
def get(self):
csrf_token = CsrfTokenManager.create_csrf_token(
self.user_id)
self.render_json({
'token': csrf_token,
})
class OppiaMLVMHandler(BaseHandler):
"""Base class for the handlers that communicate with Oppia-ML VM instances.
"""
def extract_request_message_vm_id_and_signature(self):
"""Returns the OppiaMLAuthInfo domain object containing
information from the incoming request that is necessary for
authentication.
Since incoming request can be either a protobuf serialized binary or
a JSON object, the derived classes must implement the necessary
logic to decode the incoming request and return a tuple of size 3
where message is at index 0, vm_id is at index 1 and signature is at
index 2.
Raises:
NotImplementedError. The derived child classes must implement the
necessary logic as described above.
"""
raise NotImplementedError
|
ScalablyTyped/SlinkyTyped
|
a/aws-sdk/src/main/scala/typingsSlinky/awsSdk/workspacesMod/DefaultWorkspaceCreationProperties.scala
|
<reponame>ScalablyTyped/SlinkyTyped<filename>a/aws-sdk/src/main/scala/typingsSlinky/awsSdk/workspacesMod/DefaultWorkspaceCreationProperties.scala<gh_stars>10-100
package typingsSlinky.awsSdk.workspacesMod
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait DefaultWorkspaceCreationProperties extends StObject {
/**
* The identifier of the default security group to apply to WorkSpaces when they are created. For more information, see Security Groups for Your WorkSpaces.
*/
var CustomSecurityGroupId: js.UndefOr[SecurityGroupId] = js.native
/**
* The organizational unit (OU) in the directory for the WorkSpace machine accounts.
*/
var DefaultOu: js.UndefOr[typingsSlinky.awsSdk.workspacesMod.DefaultOu] = js.native
/**
* Specifies whether to automatically assign an Elastic public IP address to WorkSpaces in this directory by default. If enabled, the Elastic public IP address allows outbound internet access from your WorkSpaces when you’re using an internet gateway in the Amazon VPC in which your WorkSpaces are located. If you're using a Network Address Translation (NAT) gateway for outbound internet access from your VPC, or if your WorkSpaces are in public subnets and you manually assign them Elastic IP addresses, you should disable this setting. This setting applies to new WorkSpaces that you launch or to existing WorkSpaces that you rebuild. For more information, see Configure a VPC for Amazon WorkSpaces.
*/
var EnableInternetAccess: js.UndefOr[BooleanObject] = js.native
/**
* Specifies whether maintenance mode is enabled for WorkSpaces. For more information, see WorkSpace Maintenance.
*/
var EnableMaintenanceMode: js.UndefOr[BooleanObject] = js.native
/**
* Specifies whether the directory is enabled for Amazon WorkDocs.
*/
var EnableWorkDocs: js.UndefOr[BooleanObject] = js.native
/**
* Specifies whether WorkSpace users are local administrators on their WorkSpaces.
*/
var UserEnabledAsLocalAdministrator: js.UndefOr[BooleanObject] = js.native
}
object DefaultWorkspaceCreationProperties {
@scala.inline
def apply(): DefaultWorkspaceCreationProperties = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[DefaultWorkspaceCreationProperties]
}
@scala.inline
implicit class DefaultWorkspaceCreationPropertiesMutableBuilder[Self <: DefaultWorkspaceCreationProperties] (val x: Self) extends AnyVal {
@scala.inline
def setCustomSecurityGroupId(value: SecurityGroupId): Self = StObject.set(x, "CustomSecurityGroupId", value.asInstanceOf[js.Any])
@scala.inline
def setCustomSecurityGroupIdUndefined: Self = StObject.set(x, "CustomSecurityGroupId", js.undefined)
@scala.inline
def setDefaultOu(value: DefaultOu): Self = StObject.set(x, "DefaultOu", value.asInstanceOf[js.Any])
@scala.inline
def setDefaultOuUndefined: Self = StObject.set(x, "DefaultOu", js.undefined)
@scala.inline
def setEnableInternetAccess(value: BooleanObject): Self = StObject.set(x, "EnableInternetAccess", value.asInstanceOf[js.Any])
@scala.inline
def setEnableInternetAccessUndefined: Self = StObject.set(x, "EnableInternetAccess", js.undefined)
@scala.inline
def setEnableMaintenanceMode(value: BooleanObject): Self = StObject.set(x, "EnableMaintenanceMode", value.asInstanceOf[js.Any])
@scala.inline
def setEnableMaintenanceModeUndefined: Self = StObject.set(x, "EnableMaintenanceMode", js.undefined)
@scala.inline
def setEnableWorkDocs(value: BooleanObject): Self = StObject.set(x, "EnableWorkDocs", value.asInstanceOf[js.Any])
@scala.inline
def setEnableWorkDocsUndefined: Self = StObject.set(x, "EnableWorkDocs", js.undefined)
@scala.inline
def setUserEnabledAsLocalAdministrator(value: BooleanObject): Self = StObject.set(x, "UserEnabledAsLocalAdministrator", value.asInstanceOf[js.Any])
@scala.inline
def setUserEnabledAsLocalAdministratorUndefined: Self = StObject.set(x, "UserEnabledAsLocalAdministrator", js.undefined)
}
}
|
bluesjjw/angel
|
angel-ps/core/src/main/java/com/tencent/angel/ps/io/PSModelIOExecutor.java
|
package com.tencent.angel.ps.io;
import com.tencent.angel.conf.AngelConf;
import com.tencent.angel.model.*;
import com.tencent.angel.model.io.IOExecutors;
import com.tencent.angel.model.output.format.*;
import com.tencent.angel.ps.PSContext;
import com.tencent.angel.ps.storage.matrix.ServerMatrix;
import com.tencent.angel.utils.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.RecursiveAction;
/**
* PS Model load/save executors
*/
public class PSModelIOExecutor {
private final static Log LOG = LogFactory.getLog(PSModelIOExecutor.class);
/**
* PS context
*/
private final PSContext context;
private final IOExecutors workers;
/**
* Create PSModelIOExecutor
* @param context ps context
*/
public PSModelIOExecutor(PSContext context) {
this.context = context;
workers = new IOExecutors(context.getConf()
.getInt(AngelConf.ANGEL_PS_MATRIX_DISKIO_WORKER_POOL_SIZE,
AngelConf.DEFAULT_ANGEL_PS_MATRIX_DISKIO_WORKER_POOL_SIZE));
}
public void init() {
workers.init();
}
public void start() {
workers.start();
}
public void stop() {
workers.shutdown();
}
/**
* Load matrices from files
*
* @param loadContext load context
* @throws IOException
*/
public void load(PSMatricesLoadContext loadContext) throws IOException {
LOG.info("start to load matrices :" + loadContext);
Vector<String> errorLogs = new Vector<>();
try {
MatrixDiskIOOp commitOp = new MatrixDiskIOOp(ACTION.LOAD, errorLogs, loadContext, 0,
loadContext.getMatrixLoadContexts().size());
workers.execute(commitOp);
commitOp.join();
if (!errorLogs.isEmpty()) {
throw new IOException(StringUtils.join("\n", errorLogs));
}
} catch (Throwable x) {
throw new IOException(x);
}
}
/**
* Save matrices to files
*
* @param saveContext matrices save context
* @throws IOException
*/
public void save(PSMatricesSaveContext saveContext) throws IOException {
LOG.info("start to save matrices :" + saveContext);
Vector<String> errorLogs = new Vector<>();
try {
MatrixDiskIOOp commitOp = new MatrixDiskIOOp(ACTION.SAVE, errorLogs, saveContext, 0,
saveContext.getMatrixSaveContexts().size());
workers.execute(commitOp);
commitOp.join();
if (!errorLogs.isEmpty()) {
throw new IOException(StringUtils.join("\n", errorLogs));
}
} catch (Throwable x) {
throw new IOException(x);
}
return;
}
enum ACTION {
LOAD, SAVE
}
class MatrixDiskIOOp extends RecursiveAction {
private final ACTION action;
private final Vector<String> errorLogs;
private final Object context;
private final int startPos;
private final int endPos;
public MatrixDiskIOOp(ACTION action, Vector<String> errorLogs, Object context, int start,
int end) {
this.action = action;
this.errorLogs = errorLogs;
this.context = context;
this.startPos = start;
this.endPos = end;
}
@Override protected void compute() {
if (endPos <= startPos) {
return;
}
if (endPos - startPos == 1) {
try {
process(context, startPos, action);
} catch (Throwable e) {
LOG.error(action + " matrix failed ", e);
errorLogs.add(action + " matrix failed:" + StringUtils.stringifyException(e));
}
} else {
int middle = (startPos + endPos) / 2;
MatrixDiskIOOp opLeft = new MatrixDiskIOOp(action, errorLogs, context, startPos, middle);
MatrixDiskIOOp opRight = new MatrixDiskIOOp(action, errorLogs, context, middle, endPos);
invokeAll(opLeft, opRight);
}
}
}
private void process(Object context, int index, ACTION action) throws IOException {
switch (action) {
case LOAD:
loadMatrix(((PSMatricesLoadContext) context).getMatrixLoadContexts().get(index));
break;
case SAVE: {
saveMatrix(
((PSMatricesSaveContext) context).getMatrixSaveContexts().get(index));
break;
}
}
}
private void loadMatrix(PSMatrixLoadContext loadContext) throws IOException {
loadContext.setWorkers(workers);
ServerMatrix matrix = context.getMatrixStorageManager().getMatrix(loadContext.getMatrixId());
if (matrix != null) {
MatrixFormat format = ModelFilesUtils.initFormat(loadContext.getFormatClassName(), context.getConf());
format.load(matrix, loadContext, context.getConf());
}
}
private void saveMatrix(PSMatrixSaveContext saveContext) throws IOException {
saveContext.setWorkers(workers);
ServerMatrix matrix = context.getMatrixStorageManager().getMatrix(saveContext.getMatrixId());
if (matrix != null) {
MatrixFormat format = ModelFilesUtils.initFormat(saveContext.getFormatClassName(), context.getConf());
format.save(matrix, saveContext, context.getConf());
}
}
}
|
Volas171/ReactorBot
|
events/Guild/guildMemberRemove.js
|
const Discord = require ("discord.js");
module.exports = ({client, botUtils}, member) => {
newError = botUtils.newError;
try {
const timeProp = [1, 1000, 60000, 3600000, 86400000, 31536000000, Number.POSITIVE_INFINITY];
const timename = ["ms", "second", "minute", "hour", "day", "year", "??? Eternity"];
let emoji = client.emojis.cache.find (e => e.name == "PaimonPat" && e.animated);
let time = ((new Date (). getTime ()) - member.joinedTimestamp);
let description = "";
timeProp.some ((t, i) => {
const times = (i) => timeProp [i];
if (times (i + 1)> time) {
const getTxt = (time, i) => {
let res = Math.floor (time / times (i));
return `$ {res} $ {timename [i]} $ {res == 1? "": "s"} `;
}
if (time <timeProp [2]) {
description = "\nStay on the server for only";
} else if (time <timeProp [4] * 7) {
description = "\nYou held the server for";
} else if (time <timeProp [4] * 30) {
description = "\nThis was a warrior. He stayed on the server for"
} else if (time <timeProp [4] * 30 * 6) {
description = "\nI bet this was quite important on the server.
} else {
description = "\nThank you for being a server for so long, even. Stayed on the server for"
}
let t1 = Math.floor (time / times (i));
let t2 = Math.floor (time% times (i) / times (i-1));
description + = `$ {t1} $ {timename [i]} $ {t1 == 1? "": "s"} and $ {t2} $ {timename [i-1]} $ {i == 1 || t2 == 1? "": "s"} `;
return true;
}
return false;
});
let welcome = new Discord.MessageEmbed ()
.setTitle (`$ {emoji} See you soon!`)
.setDescription (`$ {member} ($ {member.user.tag}), left our server!` + description)
.setColor ("RANDOM")
.setTimestamp ()
.setThumbnail (member.user.displayAvatarURL ({format: "png", dynamic: true, size: 512}))
//.setImage("https://thumbs.gfycat.com/BrownFavoriteCock-small.gif ");
client.channels.cache.get ("699823229354639474"). send (welcome);
} catch (err) {
console.log (`=> $ {newError (err," guildMemberRemove ")}`);
}
}
|
godnoTA/acm.bsu.by
|
4. Алгоритмы на графах/67.1. Поиск в ширину #3566/[OK]169647.java
|
import java.io.*;
import java.util.*;
public class Search {
static BufferedWriter writer;
public static void main(String[] args) throws IOException {
Scanner in=new Scanner (new File("input.txt"));
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt")));
int n=in.nextInt();
int k=1;
int mas[][]=new int[n][n];
int array[]= new int[n];
Queue <Integer> dek = new LinkedList<>();
boolean flag [] = new boolean [n];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
mas[i][j]=in.nextInt();
}
flag[i]=false;
}
for(int i=0; i<n; i++) {
if(flag[i]==false){
dek.add(i);
flag[i]=true;
array[i]=k;
k++;
while(!dek.isEmpty()){
int c=dek.poll();
for(int p=0; p<n;p++){
if(mas[c][p]==1 && flag[p]==false){
dek.add(p);
flag[p]=true;
array[p]=k;
k++;
}
}
}
}
}
for(int i=0; i<n; i++) {
writer.write(array[i]+" ");
}
writer.write("\n");
in.close();
writer.flush();
}
}
|
prabhjyotsingh/cloudbreak
|
datalake/src/main/java/com/sequenceiq/datalake/flow/delete/event/StackDeletionFailedEvent.java
|
package com.sequenceiq.datalake.flow.delete.event;
import com.sequenceiq.cloudbreak.common.event.Selectable;
public class StackDeletionFailedEvent implements Selectable {
private Long sdxId;
private Exception exception;
public StackDeletionFailedEvent(Long sdxId, Exception exception) {
this.sdxId = sdxId;
this.exception = exception;
}
@Override
public String selector() {
return "StackDeletionFailedEvent";
}
@Override
public Long getResourceId() {
return sdxId;
}
public Exception getException() {
return exception;
}
}
|
CC3002-Metodologias/scrabble-jaedango
|
src/main/java/files/operations/ops/NumOps/NumOps.java
|
package files.operations.ops.NumOps;
import files.operations.ops.Operations;
/**
* @author jaedango
*/
public abstract class NumOps implements Operations {
}
|
reviewboard/ReviewBot
|
extension/reviewbotext/evolutions/old_tool_model.py
|
<gh_stars>10-100
from __future__ import unicode_literals
from django_evolution.mutations import DeleteModel
MUTATIONS = [
DeleteModel('ReviewBotTool'),
]
|
cpgf/cpgf
|
samples/tween/src/ui/paneltweentest.cpp
|
#include "paneltweentest.h"
#include "panelcanvas.h"
#include "panelease.h"
#include "panelcommand.h"
#include "toolpanel.h"
#include "../easeinfo.h"
#include "cpgf/tween/gtweenlist.h"
#include "cpgf/accessor/gaccessor.h"
#if defined(_WIN32)
#include <windows.h>
#endif
#include <GL/gl.h>
#include <GL/glut.h>
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4996)
#endif
using namespace cpgf;
PanelTweenTest::PanelTweenTest(wxWindow * parent)
: super(parent), timer(nullptr)
{
wxBoxSizer * mainSizer;
mainSizer = new wxBoxSizer( wxVERTICAL );
this->toolPanel = new ToolPanel(this);
mainSizer->Add(this->toolPanel, 0, wxEXPAND);
wxBoxSizer * contentSizer;
contentSizer = new wxBoxSizer(wxHORIZONTAL);
mainSizer->Add(contentSizer, 1, wxEXPAND, 5);
wxBoxSizer * leftSizer;
leftSizer = new wxBoxSizer(wxVERTICAL);
this->commandPanel = new PanelCommand(this);
leftSizer->Add(this->commandPanel, 0, wxEXPAND, 5);
this->easePanel = new PanelEase(this);
leftSizer->Add(this->easePanel, 0, wxEXPAND, 5);
contentSizer->Add(leftSizer, 1, wxEXPAND, 5);
wxBoxSizer * canvasSizer;
canvasSizer = new wxBoxSizer(wxVERTICAL);
contentSizer->Add(canvasSizer, 3, wxEXPAND, 5);
this->canvas = new PanelCanvas(this);
canvasSizer->Add(this->canvas, 1, wxEXPAND, 5); //->SetMinSize(wxSize(500, 500));
this->easePanel->addCallback(makeCallback(this, &PanelTweenTest::onEaseButtonClicked));
this->canvas->addRender(makeCallback(this, &PanelTweenTest::onRender));
this->toolPanel->setOnTestCaseChange(makeCallback(this, &PanelTweenTest::onTestCaseChanged));
this->SetSizer(mainSizer);
this->Layout();
}
PanelTweenTest::~PanelTweenTest()
{
this->end();
}
void PanelTweenTest::onEaseButtonClicked(int easeIndex)
{
if(this->testCase) {
this->testCase->setEase(easeIndex);
}
}
void PanelTweenTest::start()
{
this->end();
this->timer = new TestTimer(cpgf::makeCallback(this, &PanelTweenTest::onTimer));
}
void PanelTweenTest::end()
{
delete this->timer;
this->timer = nullptr;
}
void PanelTweenTest::setTestCase(const TestCasePtr & testCase)
{
this->testCase = testCase;
this->testCase->reset();
this->testCase->setEase(this->easePanel->getEaseIndex());
this->commandPanel->setTestCase(testCase);
this->commandPanel->Show(this->testCase->shouldShowCommandButtons());
this->commandPanel->showOrHidePauseAndResumeButtons(this->testCase->shouldShowPauseResumeButtons());
this->easePanel->Show(this->testCase->shouldShowEaseButtons());
this->Layout();
this->commandPanel->Refresh();
this->easePanel->Refresh();
}
void drawFrameRate(int frameRate)
{
if(frameRate == 0) {
return;
}
char str[100];
sprintf(str, "FPS: %d", frameRate);
glColor4f(0, 1.0f, 0, 0.5f);
glPushAttrib(GL_LIGHTING_BIT + GL_CURRENT_BIT);
glDisable(GL_LIGHTING);
glRasterPos3f(1.8f, 0.05f, 0.0f);
int i = 0;
while(str[i]) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, str[i]);
++i;
}
glEnable(GL_LIGHTING);
glPopAttrib();
}
void PanelTweenTest::onRender(int viewWidth, int viewHeight)
{
if(this->testCase) {
this->testCase->render(viewWidth, viewHeight);
}
drawFrameRate(this->timer->getFrameRate());
}
void PanelTweenTest::onTestCaseChanged(const TestCasePtr & testCase)
{
this->setTestCase(testCase);
}
void PanelTweenTest::onTimer(int frameTime)
{
GTweenList::getInstance()->tick((GTweenNumber)frameTime);
this->commandPanel->tick();
this->canvas->Refresh();
}
|
cloudmercato/python-fpb
|
fpb/sum/numpy.py
|
<reponame>cloudmercato/python-fpb<gh_stars>1-10
from fpb.base import numpy
class Runner(numpy.BaseNumpy1dRunner):
def run(self, data):
output = self.np.sum(data, dtype="float128")
return output
|
cnsvili/mybatis-jpa
|
src/main/java/com/mybatis/jpa/plugin/ResultTypePlugin.java
|
package com.mybatis.jpa.plugin;
import com.mybatis.jpa.util.FieldReflectUtil;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.Configuration;
/**
* @author svili
**/
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {
Statement.class})})
public class ResultTypePlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
if (invocation.getTarget() instanceof DefaultResultSetHandler) {
DefaultResultSetHandler resultSetHandler = (DefaultResultSetHandler) invocation.getTarget();
Object[] args = invocation.getArgs();
Statement stmt = (Statement) args[0];
MappedStatement mappedStatement = (MappedStatement) FieldReflectUtil
.getFieldValue(resultSetHandler, "mappedStatement");
List<ResultMap> resultMaps = mappedStatement.getResultMaps();
if (resultMaps != null && !resultMaps.isEmpty()) {
ResultMap resultMap = resultMaps.get(0);
if (resultMap.getResultMappings() == null || resultMap.getResultMappings().isEmpty()) {
if (resultMap.getType().isAnnotationPresent(Entity.class) || resultMap.getType()
.isAnnotationPresent(Table.class)) {
ResultMapSwapper swapper = ResultMapSwapperHolder
.getSwapper(mappedStatement.getConfiguration());
ResultMap newResultMap = swapper
.reloadResultMap(mappedStatement.getResource(), resultMap.getId(),
resultMap.getType());
List<ResultMap> newResultMaps = new ArrayList<>();
newResultMaps.add(newResultMap);
FieldReflectUtil.setFieldValue(mappedStatement, "resultMaps", newResultMaps);
// modify the resultMaps
FieldReflectUtil.setFieldValue(resultSetHandler, "mappedStatement", mappedStatement);
}
}
}
return resultSetHandler.handleResultSets(stmt);
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
/**
* Use static inner classes ensure thread safety
*/
private static class ResultMapSwapperHolder {
private static Map<String, ResultMapSwapper> swappers = new HashMap<>();
static ResultMapSwapper getSwapper(Configuration configuration) {
String id = configuration.getEnvironment().getId();
if (!swappers.containsKey(id)) {
swappers.put(id, new ResultMapSwapper(configuration));
}
return swappers.get(id);
}
}
}
|
cadvena/toolbox
|
tests/test_ez_alchemy.py
|
<filename>tests/test_ez_alchemy.py
import os
import unittest
from toolbox.ez_alchemy import EZOracle, ez_query, _Examples
import pandas as pd
from sqlalchemy import engine
from toolbox.simple_password import get_credentials
from toolbox import tb_cfg
DEFAULT_USER = os.environ['username']
NoneType = type (None)
cfg = tb_cfg
class TestEZQuery(unittest.TestCase):
def setUp(self):
print("\nCalling TestOSWrapper.setUp()...")
self.hosts = tb_cfg['DEFAULT_HOSTS']
self.host, self.usr, self.pw = get_credentials(systems = self.hosts)
self.sql = 'select sysdate from dual'
# verify we can run a simple query before we run remaining tests
ez_query(sql=self.sql, host=self.host, user=self.usr, pw=self.pw)
def tearDown(self):
print("\nCalling TestOSWrapper.tearDown()...")
def test_sqlalchemy_oracle_example(self):
expexted_cols = ["OWNER", "TABLE_NAME", "COLUMN_NAME", "DATA_TYPE", "DATA_TYPE_MOD",
"DATA_TYPE_OWNER", "DATA_LENGTH", "DATA_PRECISION", "DATA_SCALE",
"NULLABLE", "COLUMN_ID", "DEFAULT_LENGTH", "DATA_DEFAULT", "NUM_DISTINCT",
"LOW_VALUE", "HIGH_VALUE", "DENSITY", "NUM_NULLS", "NUM_BUCKETS",
"LAST_ANALYZED", "SAMPLE_SIZE", "CHARACTER_SET_NAME",
"CHAR_COL_DECL_LENGTH", "GLOBAL_STATS", "USER_STATS", "AVG_COL_LEN",
"CHAR_LENGTH", "CHAR_USED", "V80_FMT_IMAGE", "DATA_UPGRADED", "HISTOGRAM",
"DEFAULT_ON_NULL", "IDENTITY_COLUMN", "EVALUATION_EDITION",
"UNUSABLE_BEFORE", "UNUSABLE_BEGINNING", "COLLATION"]
dialect, sql_driver = 'oracle', 'cx_oracle'
engine_string = dialect + '+' + sql_driver + '://' + self.usr + ':' + self.pw + '@' + self.host
db = engine.create_engine (engine_string)
sql = "select * from all_tab_columns where ROWNUM <=10 order by table_name"
df = pd.read_sql_query (sql, db)
self.assertEqual (10, df.shape[0])
cols = [s.lower () for s in list (df.columns)]
expected_cols = [s.lower () for s in expexted_cols]
self.assertEqual (expected_cols, cols)
print (df)
def test_ez_query_one_line(self):
# def ez_query(sql, host: str = default_hosts, user: str = '', pw: str = '',
# as_dataframe = True):
# If not provided, ez_query prompts for user and pw
df = ez_query(sql = "select sysdate from dual", host= self.host, user= self.usr,
pw = self.pw)
self.assertTrue(df.shape, (1,1))
def test_ez_query_with_creds(self):
# You can choose to collect credentials independently and use them
# repeatedly for multiple quick queries.
df = ez_query(sql = "select sysdate from dual", host = self.host,
user = self.usr, pw = self.pw)
self.assertTrue (df.shape, (1, 1))
df = ez_query(sql = "select sysdate from dual", host = self.host,
user = self.usr, pw = self.pw)
class TestEZOracle(unittest.TestCase):
def setUp(self):
print ("\nCalling TestOSWrapper.setUp()...")
self.hosts = tb_cfg['DEFAULT_HOSTS']
self.host, self.usr, self.pw = get_credentials (systems = ['EXSCRSTG'])
self.sql = 'select sysdate from dual'
# verify we can run a simple query before we run remaining tests
ez_query (sql = self.sql, host = self.host, user = self.usr, pw = self.pw)
def tearDown(self):
print ("\nCalling TestOSWrapper.tearDown()...")
def test_ez_oracle_one_line(self):
"""
Run a single query without worrying about cleaning up.
EZOracle cleans itself up.
"""
df = EZOracle(sql = "select sysdate from dual", hosts = self.host,
user = self.usr, pw = self.pw).result
print (df)
def test_ez_oracle_no_context_mgmt(self):
"""
In this example, we keep our connection pool open, so we need to
clean it up with a simple "del" statement
"""
db = EZOracle(sql = "select sysdate from dual", hosts = self.host,
user = self.usr, pw = self.pw)
df = db.result
del db
print(df)
def test_ez_oracle_in_with_statement(self):
"""
Using a "with" statement as a context manager, run 2 sql statements
in a single connection pool.
"""
with EZOracle(hosts = self.host, user = self.usr, pw = self.pw) as db:
result = db.execute(sql = "select 1, sysdate from dual")
result2 = db.execute(sql = "select 2, sysdate from dual")
print(result)
print(result2)
def test_ez_oracle_with_bad_creds(self):
"""
When bad credentials are encountered, the first login will
fail behind the scenes, then the user will be prompted for
credentials via dialog box.
"""
sql = "select sysdate from dual"
# host, user, pw = get_credentials()
with EZOracle(hosts = self.host,
user = 'fake_user',
pw = '<PASSWORD>') as db:
db.execute (sql = sql)
pass
if __name__ == '__main__':
### 2 - invoke the framework ###
# invoke the unittest framework
# unittest.main() will capture all fo the tests
# and run them 1-by-1.
unittest.main ()
|
LeeHounshell/Capstone-Project
|
mobile/src/main/java/com/harlie/radiotheater/radiomysterytheater/utils/EpisodeRecyclerViewAdapter.java
|
<gh_stars>1-10
package com.harlie.radiotheater.radiomysterytheater.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;
import com.harlie.radiotheater.radiomysterytheater.BaseActivity;
import com.harlie.radiotheater.radiomysterytheater.EpisodeDetailActivity;
import com.harlie.radiotheater.radiomysterytheater.EpisodeDetailFragment;
import com.harlie.radiotheater.radiomysterytheater.EpisodeListActivity;
import com.harlie.radiotheater.radiomysterytheater.R;
import com.harlie.radiotheater.radiomysterytheater.data_helper.EpisodeRecyclerViewItem;
import java.text.DecimalFormat;
// from: http://stackoverflow.com/questions/32992239/using-a-recyclerview-with-data-from-loadermanager
public class EpisodeRecyclerViewAdapter
extends CursorRecyclerViewAdapter<EpisodeViewHolder>
{
private final static String TAG = "LEE: <" + EpisodeRecyclerViewAdapter.class.getSimpleName() + ">";
@SuppressWarnings("FieldCanBeLocal")
private final int FADE_DURATION = 2;
private final Context mContext;
private final Cursor mDataCursor;
// --- dummy content disabled ---
// private List<EpisodeRecyclerViewItem> mValues;
//
// public EpisodeRecyclerViewAdapter(List<EpisodeRecyclerViewItem> items, Context context) {
// super(context, null);
// mValues = items;
// mContext = context;
// }
// --- dummy content disabled ---
public EpisodeRecyclerViewAdapter(BaseActivity baseActivity, Cursor cursor) {
super(baseActivity, cursor);
mContext = baseActivity;
mDataCursor = cursor;
setHasStableIds(true);
}
@Override
public EpisodeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.episode_list_content, parent, false);
TextView episode_description = (TextView) view.findViewById(R.id.episode_description);
if (! EpisodeListActivity.isTwoPane()
|| parent.getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
episode_description.setVisibility(View.VISIBLE);
}
else {
episode_description.setVisibility(View.GONE);
}
EpisodeViewHolder holder = new EpisodeViewHolder(view);
holder.setIsRecyclable(false); // stop the special colors from changing during scroll
holder.setSpecialColors();
return holder;
}
@Override
public void onBindViewHolder(EpisodeViewHolder holder, Cursor cursor) {
holder.mItem = EpisodeRecyclerViewItem.fromCursor(cursor, mContext);
DecimalFormat format = new DecimalFormat("####");
int episodeNumber = holder.mItem.getEpisodeNumber();
String formattedEpisodeNumber = format.format(episodeNumber);
holder.mEpisodeNumber.setText(formattedEpisodeNumber);
holder.mEpisodeTitle.setText(holder.mItem.getTitle());
holder.mEpisodeDescription.setText(holder.mItem.getDescription());
holder.mEpisodeRating.setRating(holder.mItem.getRating());
BaseActivity activity = (BaseActivity) mContext;
holder.setFontTypeAndSizes(activity);
holder.setIsRecyclable(false); // stop the special colors from changing during scroll
holder.setSpecialColors();
holderSetOnClickListener(holder);
setFadeAnimation(holder.mView);
}
// --- dummy content disabled ---
// @Override
// public void onBindViewHolder(final EpisodeViewHolder holder, int position) {
// holder.mItem = mValues.get(position);
// DecimalFormat format = new DecimalFormat("####");
// int episodeNumber = position + 1;
// String formattedEpisodeNumber = format.format(episodeNumber);
// holder.sEpisodeNumber.setText(formattedEpisodeNumber);
// holder.sEpisodeTitle.setText(mValues.get(position).episode_title);
// holder.sEpisodeDescription.setText(mValues.get(position).episode_description);
// holderSetOnClickListener(holder);
// setFadeAnimation(holder.mItem);
// }
// --- dummy content disabled ---
// animate the list items using a transition animation
private void setFadeAnimation(View view) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(FADE_DURATION);
view.startAnimation(anim);
}
private void holderSetOnClickListener(final EpisodeViewHolder holder) {
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
showDetailView(v, holder);
}
catch (Exception e) {
LogHelper.e(TAG, "*** showDetailView error="+e.getMessage());
}
}
});
}
@SuppressLint("PrivateResource")
private void showDetailView(View v, EpisodeViewHolder holder) {
if (mContext instanceof EpisodeListActivity) {
EpisodeListActivity episodeListActivity = (EpisodeListActivity) mContext;
if (! EpisodeListActivity.isTwoPane()
|| v.getContext().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
Context context = v.getContext();
Intent intent = new Intent(context, EpisodeDetailActivity.class);
intent.putExtra(EpisodeDetailFragment.ARG_EPISODE_ID, String.valueOf(holder.mItem.getEpisodeNumber()));
intent.putExtra(EpisodeDetailFragment.ARG_EPISODE_PARCELABLE, holder.mItem);
LogHelper.v(TAG, "-NEW- ARG_EPISODE_ID="+holder.mItem.getEpisodeNumber());
Bundle playInfo = new Bundle();
episodeListActivity.savePlayInfoToBundle(playInfo);
intent.putExtras(playInfo);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
LogHelper.v(TAG, "STARTACTIVITY: EpisodeDetailActivity.class");
context.startActivity(intent);
} else {
Bundle arguments = new Bundle();
arguments.putString(EpisodeDetailFragment.ARG_EPISODE_ID, String.valueOf(holder.mItem.getEpisodeNumber()));
arguments.putParcelable(EpisodeDetailFragment.ARG_EPISODE_PARCELABLE, holder.mItem);
LogHelper.v(TAG, "-NEW- ARG_EPISODE_ID="+holder.mItem.getEpisodeNumber());
EpisodeDetailFragment fragment = new EpisodeDetailFragment();
fragment.setArguments(arguments);
episodeListActivity
.getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.abc_fade_in, R.anim.abc_fade_out,R.anim.abc_fade_in, R.anim.abc_fade_out)
.replace(R.id.episode_detail_container, fragment)
.addToBackStack(null)
.commit();
}
}
}
@Override
public int getItemCount() {
if (mDataCursor != null) {
return mDataCursor.getCount();
}
else {
return 0;
}
// --- dummy content disabled ---
// return mValues.size();
// --- dummy content disabled ---
}
@Override
public void onViewRecycled(EpisodeViewHolder holder) {
LogHelper.v(TAG, "onViewRecycled");
super.onViewRecycled(holder);
holder.setNormalColors();
}
}
|
manujanethwidu/tirebuilderv3
|
src/redux/srtpob/srtpobActions.js
|
const { TOGGLE_SRTPOB } = require('./srtpobConstants')
/*Accessed by
TireBuilderView Component -->set true or false
TireCodeInputComp --> set null
*/
const toggleSrtPob = (value) => (dispatch) => {
dispatch({ type: TOGGLE_SRTPOB, payload: value })
}
export { toggleSrtPob }
|
cbsBiram/xarala__ssr
|
src/cart/forms.py
|
from django import forms
from django.utils.translation import gettext_lazy as _
COURSE_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]
class CartAddCourseForm(forms.Form):
quantity = forms.TypedChoiceField(
choices=COURSE_QUANTITY_CHOICES, coerce=int, label=_("Quantité")
)
override = forms.BooleanField(
required=False, initial=False, widget=forms.HiddenInput
)
|
vikash-india/DeveloperNotes2Myself
|
languages/python/src/concepts/P002_HelloWorld.py
|
<gh_stars>1-10
# Description: "Hello World" Program in Python
print("Hello World!")
print('Hello Again! But in single quotes')
print("You can't enter double quotes inside double quoted string but can use ' like this.")
print('Similarly you can enter " inside single quoted string.')
print('Or you can escape single quotes like this \' inside single quoted string.')
print("Or you can escape double quotes like this \" inside double quoted string.")
# Mnemonics: Double Quotes, Single Quotes, One Inside the Other & Escape Quotes
|
vineetseraro/gps-ble-based-guard-trak
|
api/handlers/configuration.js
|
const commonHelper = require('../helpers/common');
const bluebirdPromise = require('bluebird');
const mongoose = require('mongoose');
const configHelper = require('../helpers/configuration');
const akResponse = require('../lib/respones');
const messages = require('../mappings/messagestring.json');
const clientHandler = require('../lib/clientHandler');
const currentUserHandler = require('../lib/currentUserHandler');
/**
* Get configuration List
*
* @param {Object} event event passed to the lambda
* @param {Object} context context passed to the lambda
* @callback callback Lambda Callback
*/
module.exports.getConfigurations = (event, context, callback) => {
commonHelper.decryptDbURI().then(dbURI => {
const parsedEvent = commonHelper.parseLambdaEvent(event);
clientHandler.setClient(clientHandler.getClientObject(parsedEvent));
currentUserHandler.setCurrentUser(currentUserHandler.getCurrentUserObject(parsedEvent));
commonHelper.connectToDb(dbURI);
bluebirdPromise
.all([
configHelper.get(
configHelper.getFilterParams(parsedEvent),
configHelper.getExtraParams(parsedEvent)
),
configHelper.count(configHelper.getFilterParams(parsedEvent))
])
.then(resultObj => {
const response = akResponse.listSuccess(resultObj, 'Configuration List');
mongoose.disconnect();
callback(null, response);
})
.catch(() => {
// TODO : please remove 404 from catch block as it is a valid success response. catch should only catught exceptions and return with status in range of 500
const response = akResponse.noDataFound(messages.NO_RECORDS, messages.NO_RECORDS);
callback(null, response);
});
});
};
/**
* Get Single configuration for specified ID
*
* @param {Object} event event passed to the lambda
* @param {Object} context context passed to the lambda
* @callback callback Lambda Callback
*/
module.exports.getConfigurationById = (event, context, callback) => {
commonHelper.decryptDbURI().then(dbURI => {
const parsedEvent = commonHelper.parseLambdaEvent(event);
clientHandler.setClient(clientHandler.getClientObject(parsedEvent));
currentUserHandler.setCurrentUser(currentUserHandler.getCurrentUserObject(parsedEvent));
commonHelper.connectToDb(dbURI);
configHelper
.getById(parsedEvent.pathParameters.id)
.then(result => {
const response = akResponse.success(
result,
'configuration fetched successfully',
messages.OK
);
mongoose.disconnect();
callback(null, response);
})
.catch(() => {
// TODO : please remove 404 from catch block as it is a valid success response. catch should only catught exceptions and return with status in range of 500
const response = akResponse.noDataFound(messages.NO_RECORDS, messages.NO_RECORDS);
mongoose.disconnect();
callback(null, response);
});
});
};
/**
* Update an configuration.
*
* @param {Object} event event passed to the lambda
* @param {Object} context context passed to the lambda
* @callback callback Lambda Callback
*/
module.exports.updateConfiguration = (event, context, callback) => {
commonHelper.decryptDbURI().then(dbURI => {
const parsedEvent = commonHelper.parseLambdaEvent(event);
clientHandler.setClient(clientHandler.getClientObject(parsedEvent));
currentUserHandler.setCurrentUser(currentUserHandler.getCurrentUserObject(parsedEvent));
commonHelper.connectToDb(dbURI);
configHelper
.validateRequest(parsedEvent)
.then(populatedTags => {
parsedEvent.body.tags = populatedTags.body.tags;
configHelper
.update(parsedEvent)
.then(result => configHelper.getById(result._id))
.then(result => {
const response = akResponse.success(
result,
'configuration updated successfully',
messages.OK
);
mongoose.disconnect();
callback(null, response);
})
.catch(() => {
// TODO : please remove 301 from catch block as it is a not valid success response. catch should only catught exceptions and return with status in range of 500
const response = akResponse.notModified(
messages.ATTRIBUTE_UPDATE_FAIL,
messages.ATTRIBUTE_UPDATE_FAIL
);
mongoose.disconnect();
callback(null, response);
});
})
.catch(errors => {
// TODO : please remove 422 from catch block as it is a not valid success response. catch should only catught exceptions and return with status in range of 500
const response = akResponse.validationFailed(
errors,
messages.VALIDATION_ERRORS_OCCOURED,
messages.VALIDATION_ERROR
);
mongoose.disconnect();
callback(null, response);
});
});
};
/**
* Save an configuration.
*
* @param {Object} event event passed to the lambda
* @param {Object} context context passed to the lambda
* @callback callback Lambda Callback
*/
module.exports.saveConfiguration = (event, context, callback) => {
commonHelper.decryptDbURI().then(dbURI => {
const parsedEvent = commonHelper.parseLambdaEvent(event);
clientHandler.setClient(clientHandler.getClientObject(parsedEvent));
currentUserHandler.setCurrentUser(currentUserHandler.getCurrentUserObject(parsedEvent));
commonHelper.connectToDb(dbURI);
configHelper
.validateRequest(parsedEvent)
.then(populatedTags => {
parsedEvent.body.tags = populatedTags.body.tags;
configHelper
.save(parsedEvent)
.then(result => configHelper.getById(result._id, true))
.then(result => {
const response = akResponse.created(
result,
'configuration saved successfully',
messages.OK
);
mongoose.disconnect();
callback(null, response);
})
.catch(() => {
// TODO : please remove 400 from catch block as it is a not valid response it will be send if Json format is not valid. catch should only catught exceptions and return with status in range of 500
const response = akResponse.badRequest(
'configuration create failed',
'configuration create failed'
);
mongoose.disconnect();
callback(null, response);
});
})
.catch(errors => {
// TODO : please remove 422 from catch block as it is a not valid success response. catch should only catught exceptions and return with status in range of 500
const response = akResponse.validationFailed(
errors,
messages.VALIDATION_ERRORS_OCCOURED,
messages.VALIDATION_ERROR
);
mongoose.disconnect();
callback(null, response);
});
});
};
module.exports.valErrors = (event, context, callback) => {
const response = {
statusCode: 422,
headers: {
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
code: 422,
message: 'ValidationErrors',
description: 'Validation Errors Occured',
data: [
{
message: 'Code is mandatory',
code: 'required',
field: 'code'
},
{
message: 'Name is mandatory',
code: 'required',
field: 'name'
}
]
})
};
callback(null, response);
};
|
BradyBromley/TubeMQ
|
tubemq-client/src/main/java/com/tencent/tubemq/client/producer/MessageProducer.java
|
/*
* Tencent is pleased to support the open source community by making TubeMQ available.
*
* Copyright (C) 2012-2019 Tencent. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at
*
* https://opensource.org/licenses/Apache-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.tencent.tubemq.client.producer;
import com.tencent.tubemq.corebase.Message;
import com.tencent.tubemq.corebase.Shutdownable;
import com.tencent.tubemq.client.exception.TubeClientException;
import java.util.Set;
public interface MessageProducer extends Shutdownable {
void publish(String topic) throws TubeClientException;
Set<String> publish(Set<String> topicSet) throws TubeClientException;
Set<String> getPublishedTopicSet() throws TubeClientException;
boolean isTopicCurAcceptPublish(String topic) throws TubeClientException;
MessageSentResult sendMessage(final Message message)
throws TubeClientException, InterruptedException;
void sendMessage(final Message message, final MessageSentCallback cb)
throws TubeClientException, InterruptedException;
void shutdown() throws Throwable;
}
|
libero/texture
|
src/article/metadata/MetadataEditor.js
|
<filename>src/article/metadata/MetadataEditor.js
import { Component, DefaultDOMElement } from 'substance';
import { Managed, OverlayCanvas } from '../../kit';
import MetadataModel from './MetadataModel';
import MetadataSection from './MetadataSection';
import MetadataSectionTOCEntry from './MetadataSectionTOCEntry';
import ExperimentalArticleValidator from '../ExperimentalArticleValidator';
export default class MetadataEditor extends Component {
constructor(...args) {
super(...args);
this._initialize(this.props);
}
_initialize(props) {
this.articleValidator = new ExperimentalArticleValidator(this.context.api);
this.model = new MetadataModel(this.context.editorSession);
// HACK: this is making all properties dirty, so we have to reset the appState after that
this.articleValidator.initialize();
this.context.editorState._reset();
}
getActionHandlers() {
return {
acquireOverlay: this._acquireOverlay,
releaseOverlay: this._releaseOverlay,
};
}
didMount() {
this._showHideTOC();
DefaultDOMElement.getBrowserWindow().on('resize', this._showHideTOC, this);
this.context.editorSession.setRootComponent(this._getContentPanel());
}
dispose() {
this.articleValidator.dispose();
DefaultDOMElement.getBrowserWindow().off(this);
}
render($$) {
let el = $$('div').addClass('sc-metadata-editor');
el.append(this._renderMainSection($$));
el.on('keydown', this._onKeydown);
return el;
}
_renderMainSection($$) {
let mainSection = $$('div').addClass('se-main-section');
mainSection.append(
this._renderToolbar($$),
$$('div')
.addClass('se-content-section')
.append(
this._renderTOCPane($$),
this._renderContentPanel($$),
// TODO: do we need this ref?
)
.ref('contentSection'),
);
return mainSection;
}
_renderToolbar($$) {
const Toolbar = this.getComponent('toolbar');
let config = this.context.config;
const items = config.getToolPanel('toolbar');
return $$('div')
.addClass('se-toolbar-wrapper')
.append(
$$(Managed(Toolbar), {
items,
bindings: ['commandStates'],
}).ref('toolbar'),
);
}
_renderTOCPane($$) {
const sections = this.model.getSections();
let el = $$('div')
.addClass('se-toc-pane')
.ref('tocPane');
let tocEl = $$('div').addClass('se-toc');
sections.forEach(({ name, model }) => {
let id = model.id;
tocEl.append(
$$(MetadataSectionTOCEntry, {
id,
name,
model,
}),
);
});
el.append(tocEl);
return el;
}
_renderContentPanel($$) {
const sections = this.model.getSections();
const ScrollPane = this.getComponent('scroll-pane');
let contentPanel = $$(ScrollPane, {
contextMenu: 'custom',
scrollbarPosition: 'right',
// NOTE: this ref is needed to access the root element of the editable content
}).ref('contentPanel');
let sectionsEl = $$('div').addClass('se-sections');
sections.forEach(({ name, model }) => {
let content = $$(MetadataSection, { name, model }).ref(name);
sectionsEl.append(content);
});
contentPanel.append(sectionsEl.ref('sections'), this._renderMainOverlay($$), this._renderContextMenu($$));
return contentPanel;
}
_renderMainOverlay($$) {
const panelProvider = () => this.refs.contentPanel;
return $$(OverlayCanvas, {
panelProvider,
theme: this._getTheme(),
}).ref('overlay');
}
_renderContextMenu($$) {
const config = this.context.config;
const ContextMenu = this.getComponent('context-menu');
const items = config.getToolPanel('context-menu');
return $$(Managed(ContextMenu), {
items,
theme: this._getTheme(),
bindings: ['commandStates'],
});
}
_getContentPanel() {
return this.refs.contentPanel;
}
_getTheme() {
return 'dark';
}
_onKeydown(e) {
let handled = this.context.keyboardManager.onKeydown(e, this.context);
if (handled) {
e.stopPropagation();
e.preventDefault();
}
return handled;
}
_scrollElementIntoView(el, force) {
this._getContentPanel().scrollElementIntoView(el, !force);
}
_scrollTo(params) {
let selector;
if (params.nodeId) {
selector = `[data-id="${params.nodeId}"]`;
} else if (params.section) {
selector = `[data-section="${params.section}"]`;
} else {
throw new Error('Illegal argument');
}
let comp = this.refs.contentPanel.find(selector);
if (comp) {
this._scrollElementIntoView(comp.el, true);
}
}
_showHideTOC() {
let contentSectionWidth = this.refs.contentSection.el.width;
if (contentSectionWidth < 960) {
this.el.addClass('sm-compact');
} else {
this.el.removeClass('sm-compact');
}
}
_acquireOverlay(...args) {
this.refs.overlay.acquireOverlay(...args);
}
_releaseOverlay(...args) {
this.refs.overlay.releaseOverlay(...args);
}
}
|
MateusMarttorelli/beecrowd_accepted_solutions_C
|
bee_1133.c
|
<filename>bee_1133.c
#include <stdio.h>
int main() {
int x, y;
scanf("%d %d", &x, &y);
if (x < y) {
x++;
for (x; x < y; x++) {
if (x % 5 == 2 || x % 5 == 3)
printf("%d\n", x);
}
}
else if (y < x) {
y++;
for (y; y < x; y++) {
if (y % 5 == 2 || y % 5 == 3)
printf("%d\n", y);
}
}
return 0;
}
|
ColombiaTransit/datatools-ui
|
lib/common/util/json.js
|
<gh_stars>10-100
// @flow
import { analyze } from 'jju'
/**
* Check if a string is valid JSON.
*/
export function isValidJSON (str: string): boolean {
try {
JSON.parse(str)
} catch (e) {
return false
}
return true
}
/**
* Check if a string is valid JSONC that OTP should be able to
* parse. OTP allows comments and unquoted keys, but not other
* fancy stuff. See OTP json parser here:
* https://github.com/opentripplanner/OpenTripPlanner/blob/27f4ed0a86157bdd4c4bc3004fec25687768d373/src/main/java/org/opentripplanner/standalone/OTPMain.java#L190-L194
*/
export function isValidJSONC (str: string): boolean {
try {
const result = analyze(str)
if (
// if JSON has quotes with single quotes, it is invalid
result.quote_types.indexOf("'") > -1 ||
// if JSON has a multi-line quote, it is invalid
result.has_multi_line_quote ||
// if JSON has trailing commas, it is invalid
result.has_trailing_comma
) {
return false
}
return true
} catch (e) {
return false
}
}
|
andrasigneczi/TravelOptimiser
|
DataCollector/mozilla/xulrunner-sdk/include/nsIFind.h
|
<filename>DataCollector/mozilla/xulrunner-sdk/include/nsIFind.h
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\nsIFind.idl
*/
#ifndef __gen_nsIFind_h__
#define __gen_nsIFind_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIDOMRange; /* forward declaration */
class nsIWordBreaker; /* forward declaration */
/* starting interface: nsIFind */
#define NS_IFIND_IID_STR "75125d55-37ee-4575-b9b5-f33bfa68c2a1"
#define NS_IFIND_IID \
{0x75125d55, 0x37ee, 0x4575, \
{ 0xb9, 0xb5, 0xf3, 0x3b, 0xfa, 0x68, 0xc2, 0xa1 }}
class NS_NO_VTABLE nsIFind : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IFIND_IID)
/* attribute boolean findBackwards; */
NS_IMETHOD GetFindBackwards(bool *aFindBackwards) = 0;
NS_IMETHOD SetFindBackwards(bool aFindBackwards) = 0;
/* attribute boolean caseSensitive; */
NS_IMETHOD GetCaseSensitive(bool *aCaseSensitive) = 0;
NS_IMETHOD SetCaseSensitive(bool aCaseSensitive) = 0;
/* [noscript] attribute nsIWordBreaker wordBreaker; */
NS_IMETHOD GetWordBreaker(nsIWordBreaker * *aWordBreaker) = 0;
NS_IMETHOD SetWordBreaker(nsIWordBreaker *aWordBreaker) = 0;
/* nsIDOMRange Find (in wstring aPatText, in nsIDOMRange aSearchRange, in nsIDOMRange aStartPoint, in nsIDOMRange aEndPoint); */
NS_IMETHOD Find(const char16_t * aPatText, nsIDOMRange *aSearchRange, nsIDOMRange *aStartPoint, nsIDOMRange *aEndPoint, nsIDOMRange * *_retval) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIFind, NS_IFIND_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIFIND \
NS_IMETHOD GetFindBackwards(bool *aFindBackwards) override; \
NS_IMETHOD SetFindBackwards(bool aFindBackwards) override; \
NS_IMETHOD GetCaseSensitive(bool *aCaseSensitive) override; \
NS_IMETHOD SetCaseSensitive(bool aCaseSensitive) override; \
NS_IMETHOD GetWordBreaker(nsIWordBreaker * *aWordBreaker) override; \
NS_IMETHOD SetWordBreaker(nsIWordBreaker *aWordBreaker) override; \
NS_IMETHOD Find(const char16_t * aPatText, nsIDOMRange *aSearchRange, nsIDOMRange *aStartPoint, nsIDOMRange *aEndPoint, nsIDOMRange * *_retval) override;
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIFIND(_to) \
NS_IMETHOD GetFindBackwards(bool *aFindBackwards) override { return _to GetFindBackwards(aFindBackwards); } \
NS_IMETHOD SetFindBackwards(bool aFindBackwards) override { return _to SetFindBackwards(aFindBackwards); } \
NS_IMETHOD GetCaseSensitive(bool *aCaseSensitive) override { return _to GetCaseSensitive(aCaseSensitive); } \
NS_IMETHOD SetCaseSensitive(bool aCaseSensitive) override { return _to SetCaseSensitive(aCaseSensitive); } \
NS_IMETHOD GetWordBreaker(nsIWordBreaker * *aWordBreaker) override { return _to GetWordBreaker(aWordBreaker); } \
NS_IMETHOD SetWordBreaker(nsIWordBreaker *aWordBreaker) override { return _to SetWordBreaker(aWordBreaker); } \
NS_IMETHOD Find(const char16_t * aPatText, nsIDOMRange *aSearchRange, nsIDOMRange *aStartPoint, nsIDOMRange *aEndPoint, nsIDOMRange * *_retval) override { return _to Find(aPatText, aSearchRange, aStartPoint, aEndPoint, _retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIFIND(_to) \
NS_IMETHOD GetFindBackwards(bool *aFindBackwards) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFindBackwards(aFindBackwards); } \
NS_IMETHOD SetFindBackwards(bool aFindBackwards) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SetFindBackwards(aFindBackwards); } \
NS_IMETHOD GetCaseSensitive(bool *aCaseSensitive) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCaseSensitive(aCaseSensitive); } \
NS_IMETHOD SetCaseSensitive(bool aCaseSensitive) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCaseSensitive(aCaseSensitive); } \
NS_IMETHOD GetWordBreaker(nsIWordBreaker * *aWordBreaker) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetWordBreaker(aWordBreaker); } \
NS_IMETHOD SetWordBreaker(nsIWordBreaker *aWordBreaker) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SetWordBreaker(aWordBreaker); } \
NS_IMETHOD Find(const char16_t * aPatText, nsIDOMRange *aSearchRange, nsIDOMRange *aStartPoint, nsIDOMRange *aEndPoint, nsIDOMRange * *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Find(aPatText, aSearchRange, aStartPoint, aEndPoint, _retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsFind : public nsIFind
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIFIND
nsFind();
private:
~nsFind();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS(nsFind, nsIFind)
nsFind::nsFind()
{
/* member initializers and constructor code */
}
nsFind::~nsFind()
{
/* destructor code */
}
/* attribute boolean findBackwards; */
NS_IMETHODIMP nsFind::GetFindBackwards(bool *aFindBackwards)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsFind::SetFindBackwards(bool aFindBackwards)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute boolean caseSensitive; */
NS_IMETHODIMP nsFind::GetCaseSensitive(bool *aCaseSensitive)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsFind::SetCaseSensitive(bool aCaseSensitive)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* [noscript] attribute nsIWordBreaker wordBreaker; */
NS_IMETHODIMP nsFind::GetWordBreaker(nsIWordBreaker * *aWordBreaker)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsFind::SetWordBreaker(nsIWordBreaker *aWordBreaker)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIDOMRange Find (in wstring aPatText, in nsIDOMRange aSearchRange, in nsIDOMRange aStartPoint, in nsIDOMRange aEndPoint); */
NS_IMETHODIMP nsFind::Find(const char16_t * aPatText, nsIDOMRange *aSearchRange, nsIDOMRange *aStartPoint, nsIDOMRange *aEndPoint, nsIDOMRange * *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIFind_h__ */
|
Cinimex-Informatica/activemq
|
activemq-broker/src/main/java/org/apache/activemq/network/LdapNetworkConnector.java
|
<reponame>Cinimex-Informatica/activemq
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.network;
import java.net.URI;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.event.EventDirContext;
import javax.naming.event.NamespaceChangeListener;
import javax.naming.event.NamingEvent;
import javax.naming.event.NamingExceptionEvent;
import javax.naming.event.ObjectChangeListener;
import org.apache.activemq.util.URISupport;
import org.apache.activemq.util.URISupport.CompositeData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* class to create dynamic network connectors listed in an directory server
* using the LDAP v3 protocol as defined in RFC 2251, the entries listed in the
* directory server must implement the ipHost and ipService objectClasses as
* defined in RFC 2307.
*
* @see <a href="http://www.faqs.org/rfcs/rfc2251.html">RFC 2251</a>
* @see <a href="http://www.faqs.org/rfcs/rfc2307.html">RFC 2307</a>
*
* @org.apache.xbean.XBean element="ldapNetworkConnector"
*/
public class LdapNetworkConnector extends NetworkConnector implements NamespaceChangeListener, ObjectChangeListener {
private static final Logger LOG = LoggerFactory.getLogger(LdapNetworkConnector.class);
// force returned entries to implement the ipHost and ipService object classes (RFC 2307)
private static final String REQUIRED_OBJECT_CLASS_FILTER =
"(&(objectClass=ipHost)(objectClass=ipService))";
// connection
private URI[] availableURIs = null;
private int availableURIsIndex = 0;
private String base = null;
private boolean failover = false;
private long curReconnectDelay = 1000; /* 1 sec */
private long maxReconnectDelay = 30000; /* 30 sec */
// authentication
private String user = null;
private String password = <PASSWORD>;
private boolean anonymousAuthentication = false;
// search
private SearchControls searchControls = new SearchControls(/* ONELEVEL_SCOPE */);
private String searchFilter = REQUIRED_OBJECT_CLASS_FILTER;
private boolean searchEventListener = false;
// connector management
private Map<URI, NetworkConnector> connectorMap = new ConcurrentHashMap<URI, NetworkConnector>();
private Map<URI, Integer> referenceMap = new ConcurrentHashMap<URI, Integer>();
private Map<String, URI> uuidMap = new ConcurrentHashMap<String, URI>();
// local context
private DirContext context = null;
// currently in use URI
private URI ldapURI = null;
/**
* returns the next URI from the configured list
*
* @return random URI from the configured list
*/
public URI getUri() {
return availableURIs[++availableURIsIndex % availableURIs.length];
}
/**
* sets the LDAP server URI
*
* @param _uri
* LDAP server URI
*/
public void setUri(URI uri) throws Exception {
CompositeData data = URISupport.parseComposite(uri);
if (data.getScheme().equals("failover")) {
availableURIs = data.getComponents();
failover = true;
} else {
availableURIs = new URI[] { uri };
}
}
/**
* sets the base LDAP dn used for lookup operations
*
* @param _base
* LDAP base dn
*/
public void setBase(String base) {
this.base = base;
}
/**
* sets the LDAP user for access credentials
*
* @param _user
* LDAP dn of user
*/
public void setUser(String user) {
this.user = user;
}
/**
* sets the LDAP password for access credentials
*
* @param _password
* user password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* sets LDAP anonymous authentication access credentials
*
* @param _anonymousAuthentication
* set to true to use anonymous authentication
*/
public void setAnonymousAuthentication(boolean anonymousAuthentication) {
this.anonymousAuthentication = anonymousAuthentication;
}
/**
* sets the LDAP search scope
*
* @param _searchScope
* LDAP JNDI search scope
*/
public void setSearchScope(String searchScope) throws Exception {
int scope;
if (searchScope.equals("OBJECT_SCOPE")) {
scope = SearchControls.OBJECT_SCOPE;
} else if (searchScope.equals("ONELEVEL_SCOPE")) {
scope = SearchControls.ONELEVEL_SCOPE;
} else if (searchScope.equals("SUBTREE_SCOPE")) {
scope = SearchControls.SUBTREE_SCOPE;
} else {
throw new Exception("ERR: unknown LDAP search scope specified: " + searchScope);
}
searchControls.setSearchScope(scope);
}
/**
* sets the LDAP search filter as defined in RFC 2254
*
* @param _searchFilter
* LDAP search filter
* @see <a href="http://www.faqs.org/rfcs/rfc2254.html">RFC 2254</a>
*/
public void setSearchFilter(String searchFilter) {
this.searchFilter = "(&" + REQUIRED_OBJECT_CLASS_FILTER + "(" + searchFilter + "))";
}
/**
* enables/disable a persistent search to the LDAP server as defined in
* draft-ietf-ldapext-psearch-03.txt (2.16.840.1.113730.3.4.3)
*
* @param _searchEventListener
* enable = true, disable = false (default)
* @see <a
* href="http://www.ietf.org/proceedings/01mar/I-D/draft-ietf-ldapext-psearch-03.txt">draft-ietf-ldapext-psearch-03.txt</a>
*/
public void setSearchEventListener(boolean searchEventListener) {
this.searchEventListener = searchEventListener;
}
/**
* start the connector
*/
public void start() throws Exception {
LOG.info("connecting...");
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
this.ldapURI = getUri();
LOG.debug(" URI [{}]", this.ldapURI);
env.put(Context.PROVIDER_URL, this.ldapURI.toString());
if (anonymousAuthentication) {
LOG.debug(" login credentials [anonymous]");
env.put(Context.SECURITY_AUTHENTICATION, "none");
} else {
LOG.debug(" login credentials [{}:******]", user);
if (user != null && !"".equals(user)) {
env.put(Context.SECURITY_PRINCIPAL, user);
} else {
throw new Exception("Empty username is not allowed");
}
if (password != null && !"".equals(password)) {
env.put(Context.SECURITY_CREDENTIALS, password);
} else {
throw new Exception("Empty password is not allowed");
}
}
boolean isConnected = false;
while (!isConnected) {
try {
context = new InitialDirContext(env);
isConnected = true;
} catch (CommunicationException err) {
if (failover) {
this.ldapURI = getUri();
LOG.error("connection error [{}], failover connection to [{}]", env.get(Context.PROVIDER_URL), this.ldapURI.toString());
env.put(Context.PROVIDER_URL, this.ldapURI.toString());
Thread.sleep(curReconnectDelay);
curReconnectDelay = Math.min(curReconnectDelay * 2, maxReconnectDelay);
} else {
throw err;
}
}
}
// add connectors from search results
LOG.info("searching for network connectors...");
LOG.debug(" base [{}]", base);
LOG.debug(" filter [{}]", searchFilter);
LOG.debug(" scope [{}]", searchControls.getSearchScope());
NamingEnumeration<SearchResult> results = context.search(base, searchFilter, searchControls);
while (results.hasMore()) {
addConnector(results.next());
}
// register persistent search event listener
if (searchEventListener) {
LOG.info("registering persistent search listener...");
EventDirContext eventContext = (EventDirContext) context.lookup("");
eventContext.addNamingListener(base, searchFilter, searchControls, this);
} else { // otherwise close context (i.e. connection as it is no longer needed)
context.close();
}
}
/**
* stop the connector
*/
public void stop() throws Exception {
LOG.info("stopping context...");
for (NetworkConnector connector : connectorMap.values()) {
connector.stop();
}
connectorMap.clear();
referenceMap.clear();
uuidMap.clear();
context.close();
}
public String toString() {
return this.getClass().getName() + getName() + "[" + ldapURI.toString() + "]";
}
/**
* add connector of the given URI
*
* @param result
* search result of connector to add
*/
protected synchronized void addConnector(SearchResult result) throws Exception {
String uuid = toUUID(result);
if (uuidMap.containsKey(uuid)) {
LOG.warn("connector already regsitered for UUID [{}]", uuid);
return;
}
URI connectorURI = toURI(result);
if (connectorMap.containsKey(connectorURI)) {
int referenceCount = referenceMap.get(connectorURI) + 1;
LOG.warn("connector reference added for URI [{}], UUID [{}], total reference(s) [{}]", new Object[]{ connectorURI, uuid, referenceCount });
referenceMap.put(connectorURI, referenceCount);
uuidMap.put(uuid, connectorURI);
return;
}
// FIXME: disable JMX listing of LDAP managed connectors, we will
// want to map/manage these differently in the future
// boolean useJMX = getBrokerService().isUseJmx();
// getBrokerService().setUseJmx(false);
NetworkConnector connector = getBrokerService().addNetworkConnector(connectorURI);
// getBrokerService().setUseJmx(useJMX);
// Propagate standard connector properties that may have been set via XML
connector.setDynamicOnly(isDynamicOnly());
connector.setDecreaseNetworkConsumerPriority(isDecreaseNetworkConsumerPriority());
connector.setNetworkTTL(getNetworkTTL());
connector.setConsumerTTL(getConsumerTTL());
connector.setMessageTTL(getMessageTTL());
connector.setConduitSubscriptions(isConduitSubscriptions());
connector.setExcludedDestinations(getExcludedDestinations());
connector.setDynamicallyIncludedDestinations(getDynamicallyIncludedDestinations());
connector.setDuplex(isDuplex());
// XXX: set in the BrokerService.startAllConnectors method and is
// required to prevent remote broker exceptions upon connection
connector.setLocalUri(getBrokerService().getVmConnectorURI());
connector.setBrokerName(getBrokerService().getBrokerName());
connector.setDurableDestinations(getBrokerService().getBroker().getDurableDestinations());
// start network connector
connectorMap.put(connectorURI, connector);
referenceMap.put(connectorURI, 1);
uuidMap.put(uuid, connectorURI);
connector.start();
LOG.info("connector added with URI [{}]", connectorURI);
}
/**
* remove connector of the given URI
*
* @param result
* search result of connector to remove
*/
protected synchronized void removeConnector(SearchResult result) throws Exception {
String uuid = toUUID(result);
if (!uuidMap.containsKey(uuid)) {
LOG.warn("connector not registered for UUID [{}]", uuid);
return;
}
URI connectorURI = uuidMap.get(uuid);
if (!connectorMap.containsKey(connectorURI)) {
LOG.warn("connector not registered for URI [{}]", connectorURI);
return;
}
int referenceCount = referenceMap.get(connectorURI) - 1;
referenceMap.put(connectorURI, referenceCount);
uuidMap.remove(uuid);
LOG.debug("connector referenced removed for URI [{}], UUID[{}], remaining reference(s) [{}]", new Object[]{ connectorURI, uuid, referenceCount });
if (referenceCount > 0) {
return;
}
NetworkConnector connector = connectorMap.remove(connectorURI);
connector.stop();
LOG.info("connector removed with URI [{}]", connectorURI);
}
/**
* convert search result into URI
*
* @param result
* search result to convert to URI
*/
protected URI toURI(SearchResult result) throws Exception {
Attributes attributes = result.getAttributes();
String address = (String) attributes.get("iphostnumber").get();
String port = (String) attributes.get("ipserviceport").get();
String protocol = (String) attributes.get("ipserviceprotocol").get();
URI connectorURI = new URI("static:(" + protocol + "://" + address + ":" + port + ")");
LOG.debug("retrieved URI from SearchResult [{}]", connectorURI);
return connectorURI;
}
/**
* convert search result into URI
*
* @param result
* search result to convert to URI
*/
protected String toUUID(SearchResult result) {
String uuid = result.getNameInNamespace();
LOG.debug("retrieved UUID from SearchResult [{}]", uuid);
return uuid;
}
/**
* invoked when an entry has been added during a persistent search
*/
public void objectAdded(NamingEvent event) {
LOG.debug("entry added");
try {
addConnector((SearchResult) event.getNewBinding());
} catch (Exception err) {
LOG.error("ERR: caught unexpected exception", err);
}
}
/**
* invoked when an entry has been removed during a persistent search
*/
public void objectRemoved(NamingEvent event) {
LOG.debug("entry removed");
try {
removeConnector((SearchResult) event.getOldBinding());
} catch (Exception err) {
LOG.error("ERR: caught unexpected exception", err);
}
}
/**
* invoked when an entry has been renamed during a persistent search
*/
public void objectRenamed(NamingEvent event) {
LOG.debug("entry renamed");
// XXX: getNameInNamespace method does not seem to work properly,
// but getName seems to provide the result we want
String uuidOld = event.getOldBinding().getName();
String uuidNew = event.getNewBinding().getName();
URI connectorURI = uuidMap.remove(uuidOld);
uuidMap.put(uuidNew, connectorURI);
LOG.debug("connector reference renamed for URI [{}], Old UUID [{}], New UUID [{}]", new Object[]{ connectorURI, uuidOld, uuidNew });
}
/**
* invoked when an entry has been changed during a persistent search
*/
public void objectChanged(NamingEvent event) {
LOG.debug("entry changed");
try {
SearchResult result = (SearchResult) event.getNewBinding();
removeConnector(result);
addConnector(result);
} catch (Exception err) {
LOG.error("ERR: caught unexpected exception", err);
}
}
/**
* invoked when an exception has occurred during a persistent search
*/
public void namingExceptionThrown(NamingExceptionEvent event) {
LOG.error("ERR: caught unexpected exception", event.getException());
}
}
|
parthosa/floodlight-plus
|
src/main/java/org/openflow/protocol/factory/OFMeterBandFactory.java
|
<filename>src/main/java/org/openflow/protocol/factory/OFMeterBandFactory.java<gh_stars>0
package org.openflow.protocol.factory;
import java.nio.ByteBuffer;
import java.util.List;
import org.openflow.protocol.meter.OFMeterBand;
import org.openflow.protocol.meter.OFMeterBandType;
/**
* The interface to factories used for retrieving OFMeterBand instances. All
* methods are expected to be thread-safe.
* @author <NAME> (<EMAIL>)
*/
public interface OFMeterBandFactory {
/**
* Retrieves an OFMeterBand instance corresponding to the specified
* OFMeterBandType
* @param t the type of the OFMeterBand to be retrieved
* @return an OFMeterBand instance
*/
public OFMeterBand getMeterBand(OFMeterBandType t);
/**
* Attempts to parse and return all OFMeterBands contained in the given
* ByteBuffer, beginning at the ByteBuffer's position, and ending at
* position+length.
* @param data the ByteBuffer to parse for OpenFlow OFMeterBands
* @param length the number of Bytes to examine for OpenFlow OFMeterBands
* @return a list of OFMeterBand instances
*/
public List<OFMeterBand> parseMeterBands(ByteBuffer data, int length);
/**
* Attempts to parse and return all OFMeterBands contained in the given
* ByteBuffer, beginning at the ByteBuffer's position, and ending at
* position+length.
* @param data the ByteBuffer to parse for OpenFlow OFMeterBands
* @param length the number of Bytes to examine for OpenFlow OFMeterBands
* @param limit the maximum number of OFMeterBands to return, 0 means no limit
* @return a list of OFMeterBand instances
*/
public List<OFMeterBand> parseMeterBands(ByteBuffer data, int length, int limit);
}
|
odwraca/nrf9160-dk-aws-fota-secure
|
samples/nfc/tnep_tag/src/main.c
|
/*
* Copyright (c) 2019 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
*/
#include <stdbool.h>
#include <string.h>
#include <zephyr.h>
#include <sys/util.h>
#include <dk_buttons_and_leds.h>
#include <nfc_t4t_lib.h>
#include <nfc/tnep/tag.h>
#include <nfc/ndef/nfc_ndef_msg.h>
#include <nfc/ndef/nfc_text_rec.h>
#include <logging/log.h>
LOG_MODULE_REGISTER(dupa);
#define NDEF_TNEP_MSG_SIZE 1024
#define LED_INIT DK_LED1
#define LED_SVC_ONE DK_LED3
#define LED_SVC_TWO DK_LED4
static const u8_t msg[] = "Hello World";
static const u8_t en_code[] = {'e', 'n'};
static const char svc_one_msg[] = "Service pi = 3.14159265358979323846";
static const char svc_two_msg[] = "Service e = 2.71828182845904523536";
static const u8_t svc_one_uri[] = "svc:pi";
static const u8_t svc_two_uri[] = "svc:e";
static u8_t tag_buffer[NDEF_TNEP_MSG_SIZE];
static u8_t tag_buffer2[NDEF_TNEP_MSG_SIZE];
NFC_NDEF_MSG_DEF(ndef_msg, 16);
NFC_NDEF_TEXT_RECORD_DESC_DEF(nfc_text, UTF_8, en_code, sizeof(en_code),
msg, sizeof(msg));
NFC_NDEF_TEXT_RECORD_DESC_DEF(svc_one_rec, UTF_8, en_code, sizeof(en_code),
svc_one_msg, sizeof(svc_one_msg));
NFC_NDEF_TEXT_RECORD_DESC_DEF(svc_two_rec, UTF_8, en_code, sizeof(en_code),
svc_two_msg, sizeof(svc_two_msg));
static struct k_poll_event events[NFC_TNEP_EVENTS_NUMBER];
static void tnep_svc_one_selected(void)
{
int err;
printk("Service one selected\n");
err = nfc_tnep_tag_tx_msg_app_data(&NFC_NDEF_TEXT_RECORD_DESC(svc_one_rec),
1, NFC_TNEP_STATUS_SUCCESS);
if (err) {
printk("Service app data set err: %d\n", err);
}
dk_set_led_on(LED_SVC_ONE);
}
static void tnep_svc_one_deselected(void)
{
printk("Service one deselected\n");
dk_set_led_off(LED_SVC_ONE);
}
static void tnep_svc_one_msg_received(const u8_t *data, size_t len)
{
int err;
printk("New service data received. Finish service data exchange\n");
err = nfc_tnep_tag_tx_msg_no_app_data();
if (err) {
printk("TNEP Service data finish err: %d\n", err);
}
}
static void tnep_svc_error(int err_code)
{
printk("Service data exchange error: %d\n", err_code);
}
static void tnep_svc_two_selected(void)
{
printk("Service two selected\n");
dk_set_led_on(LED_SVC_TWO);
}
static void tnep_svc_two_deselected(void)
{
printk("Service two deselected\n");
dk_set_led_off(LED_SVC_TWO);
}
static void tnep_svc_two_msg_received(const u8_t *data, size_t len)
{
int err;
printk("New service data received. Finish service data exchange\n");
err = nfc_tnep_tag_tx_msg_no_app_data();
if (err) {
printk("TNEP Service data finish err: %d\n", err);
}
}
NFC_TNEP_TAG_SERVICE_DEF(svc_one, svc_one_uri, (ARRAY_SIZE(svc_one_uri) - 1),
NFC_TNEP_COMM_MODE_SINGLE_RESPONSE, 20, 4, 1024,
tnep_svc_one_selected, tnep_svc_one_deselected,
tnep_svc_one_msg_received, tnep_svc_error);
NFC_TNEP_TAG_SERVICE_DEF(svc_two, svc_two_uri, (ARRAY_SIZE(svc_two_uri) - 1),
NFC_TNEP_COMM_MODE_SINGLE_RESPONSE, 63, 4, 1024,
tnep_svc_two_selected, tnep_svc_two_deselected,
tnep_svc_two_msg_received, tnep_svc_error);
static struct nfc_tnep_tag_service training_services[] = {
NFC_TNEP_TAG_SERVICE(svc_one),
NFC_TNEP_TAG_SERVICE(svc_two),
};
static void nfc_callback(void *context, enum nfc_t4t_event event,
const u8_t *data, size_t data_length, u32_t flags)
{
switch (event) {
case NFC_T4T_EVENT_NDEF_UPDATED:
if (data_length > 0) {
if (IS_ENABLED(CONFIG_NFC_NDEF_MSG_WITH_NLEN)) {
data += NLEN_FIELD_SIZE;
}
nfc_tnep_tag_rx_msg_indicate(data, data_length);
}
break;
case NFC_T4T_EVENT_FIELD_ON:
case NFC_T4T_EVENT_FIELD_OFF:
nfc_tnep_tag_on_selected();
break;
default:
/* This block intentionally left blank. */
break;
}
}
static void button_pressed(u32_t button_state, u32_t has_changed)
{
int err;
u32_t button = button_state & has_changed;
if (button & DK_BTN1_MSK) {
err = nfc_tnep_tag_tx_msg_app_data(&NFC_NDEF_TEXT_RECORD_DESC(svc_two_rec),
1, NFC_TNEP_STATUS_SUCCESS);
if (err == -EACCES) {
printk("Service is not in selected state. App data cannot be set\n");
} else {
printk("Service app data set err: %d\n", err);
}
}
}
void main(void)
{
int err;
printk("NFC Tag TNEP application\n");
err = dk_leds_init();
if (err) {
printk("led init error %d", err);
return;
}
err = dk_buttons_init(button_pressed);
if (err) {
printk("buttons init error %d", err);
return;
}
/* TNEP init */
err = nfc_tnep_tag_tx_msg_buffer_register(tag_buffer, tag_buffer2,
sizeof(tag_buffer));
if (err) {
printk("Cannot register tnep buffer, err: %d\n", err);
return;
}
err = nfc_tnep_tag_init(events, ARRAY_SIZE(events),
&NFC_NDEF_MSG(ndef_msg),
nfc_t4t_ndef_rwpayload_set);
if (err) {
printk("Cannot initialize TNEP protocol, err: %d\n", err);
return;
}
/* Type 4 Tag setup */
err = nfc_t4t_setup(nfc_callback, NULL);
if (err) {
printk("NFC T4T setup err: %d\n", err);
return;
}
err = nfc_tnep_tag_initial_msg_create(training_services,
ARRAY_SIZE(training_services),
&NFC_NDEF_TEXT_RECORD_DESC(nfc_text), 1);
if (err) {
printk("Cannot create initial TNEP message, err: %d\n", err);
}
err = nfc_t4t_emulation_start();
if (err) {
printk("NFC T4T emulation start err: %d\n", err);
return;
}
dk_set_led_on(LED_INIT);
for (;;) {
k_poll(events, ARRAY_SIZE(events), K_FOREVER);
nfc_tnep_tag_process();
}
}
|
ppak10/audius-protocol
|
creator-node/src/models/clockRecord.js
|
'use strict'
module.exports = (sequelize, DataTypes) => {
// TODO - why is this not externally accessible?
const SourceTableTypesObj = {
AudiusUser: 'AudiusUser',
Track: 'Track',
File: 'File'
}
const ClockRecord = sequelize.define('ClockRecord', {
cnodeUserUUID: {
type: DataTypes.UUID,
primaryKey: true, // composite PK with clock
unique: false,
allowNull: false,
references: {
model: 'CNodeUsers',
key: 'cnodeUserUUID',
as: 'cnodeUserUUID'
},
onDelete: 'RESTRICT'
},
clock: {
type: DataTypes.INTEGER,
primaryKey: true, // composite PK with cnodeUserUUID
unique: false,
allowNull: false
},
sourceTable: {
type: DataTypes.ENUM(
...Object.values(SourceTableTypesObj)
),
allowNull: false
}
}, {
hooks: {
/**
* will run before create op in DBManager.createNewDataRecord()
*/
beforeCreate: async function (clockRecord, options) {
const clock = clockRecord.clock
// DBManager calls ClockRecord.create() with a subquery for clock value instead of a number literal.
// Short-circuit in that case since no validation is required.
if (typeof clock !== 'number') {
return
}
// clock value must be > 0
if (clock <= 0) {
return sequelize.Promise.reject('Clock value must be > 0')
}
// get previous clockRecord for cnodeUser
// this query is very fast because (cnodeUserUUID, clock) is indexed
const currentMaxClock = await sequelize.models.ClockRecord.max('clock', {
where: { cnodeUserUUID: clockRecord.cnodeUserUUID },
transaction: options.transaction
})
// If first clockRecord entry, clock value must be 1
if (!currentMaxClock && clockRecord.clock !== 1) {
return sequelize.Promise.reject('First clockRecord for cnodeUser must have clock value 1')
}
// If not first clockRecord entry, clock value must be (previous.clock + 1)
if (currentMaxClock && clock !== currentMaxClock + 1) {
return sequelize.Promise.reject('Can only insert contiguous clock values')
}
},
/**
* will run before bulkCreate op in nodesync
* performs same validation as beforeCreate hook above
*/
beforeBulkCreate: async function (clockRecords, options) {
// Ensure first clockRecord meets all above rules
let previousClock
if (clockRecords.length) {
const clockRecord = clockRecords[0]
const clock = clockRecord.clock
// DBManager calls ClockRecord.create() with a subquery for clock value instead of a number literal.
// Short-circuit in that case since no validation is required.
if (typeof clock !== 'number') {
return
}
// clock value must be > 0
if (clock <= 0) {
return sequelize.Promise.reject('Clock value must be > 0')
}
// get previous clockRecord for cnodeUser
// this query is very fast because (cnodeUserUUID, clock) is indexed
const currentMaxClock = await sequelize.models.ClockRecord.max('clock', {
where: { cnodeUserUUID: clockRecord.cnodeUserUUID },
transaction: options.transaction
})
// If first clockRecord entry, clock value must be 1
if (!currentMaxClock && clockRecord.clock !== 1) {
return sequelize.Promise.reject('First clockRecord for cnodeUser must have clock value 1')
}
// If not first clockRecord entry, clock value must be (previous.clock + 1)
if (currentMaxClock && clock !== currentMaxClock + 1) {
return sequelize.Promise.reject('Can only insert contiguous clock values')
}
previousClock = clock
}
// Ensure each successive clockRecord is contiguous
for await (const clockRecord of clockRecords.slice(1)) {
const clock = clockRecord.clock
// error if new clock is not previousClock + 1
if (previousClock && clock !== previousClock + 1) {
return sequelize.Promise.reject('Can only insert contiguous clock values')
}
previousClock = clock
}
}
}
})
/**
* TODO - enforce composite foreign key (cnodeUserUUID, clock) on all SourceTables
* - https://stackoverflow.com/questions/9984022/postgres-fk-referencing-composite-pk
*/
ClockRecord.associate = (models) => {
ClockRecord.belongsTo(models.CNodeUser, {
foreignKey: 'cnodeUserUUID',
sourceKey: 'cnodeUserUUID',
onDelete: 'RESTRICT'
})
}
ClockRecord.SourceTableTypesObj = SourceTableTypesObj
return ClockRecord
}
|
dashbangsplat/-opus_alchimia
|
src/actors/actor/master-alchemist/movement-states/jumping.js
|
<reponame>dashbangsplat/-opus_alchimia
import State from '../../../../generics/state';
import ChangeState from '../../../../generics/state-action/change-state';
import { startActorJumping, updateJumpingActor } from '../../../actions/movement';
import Standing from './standing';
export default class Jumping extends State {
init (data) {
// set actor using destructuring
let { actor } = data;
startActorJumping(actor);
return super.init(data);
}
run (data) {
let { actor, time, delta } = data;
let { body } = actor;
if (body.onFloor()) return new ChangeState(Standing, { "actor": actor });
updateJumpingActor(actor, time, delta);
return super.run(data);
}
}
|
Fighters-of-Dawn/ECommerce
|
backend/routes/customer.routes.js
|
<reponame>Fighters-of-Dawn/ECommerce<gh_stars>0
module.exports = (app) => {
const customers = require('../controller/customer.controller.js');
// Create a new Customer
app.post('/customers', customers.create);
// Retrieve all Customers
app.get('/customers', customers.findAll);
};
|
wapache-org/openapi
|
openapi-generator-server/src/main/java/org/wapache/openapi/server/api/GeneratorApi.java
|
package org.wapache.openapi.server.api;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.wapache.openapi.generator.CliOption;
import org.wapache.openapi.server.api.schema.GeneratorInput;
import org.wapache.openapi.server.api.schema.ResponseCode;
import org.wapache.openapi.v3.annotations.Operation;
import org.wapache.openapi.v3.annotations.Parameter;
import org.wapache.openapi.v3.annotations.media.ArraySchema;
import org.wapache.openapi.v3.annotations.media.Content;
import org.wapache.openapi.v3.annotations.media.Schema;
import org.wapache.openapi.v3.annotations.responses.ApiResponse;
import org.wapache.openapi.v3.annotations.responses.ApiResponses;
import org.wapache.openapi.v3.annotations.tags.Tag;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
@Tag(name = "gen", description = "OpenAPI代码生成服务")
public interface GeneratorApi {
// ////////////////////////////////////////////////////////////////////////
// region 客户端代码生成相关接口
@RequestMapping(value = "/gen/clients", method = RequestMethod.GET)
@Operation(
operationId = "clientOptions",
summary = "获取客户端开发语言列表",
description = "获取客户端代码生成支持的所有开发语言",
tags={ "clients", },
responses = @ApiResponse(
responseCode = "200",
description = "操作成功",
content = @Content(array = @ArraySchema(
arraySchema = @Schema(title = "开发语言名称列表"),
schema = @Schema(title = "开发语言名称")
))
)
)
List<String> clientOptions();
// TODO 这个路径和操作名起得不好, 改为/gen/clients/{language}/options
@RequestMapping(
value = "/gen/clients/{language}",
produces = { "application/json" },
method = RequestMethod.GET
)
@Operation(
operationId = "getClientOptions",
summary = "获取客户端代码生成的配置选项",
description = "",
tags={ "clients", },
responses = {
@ApiResponse(
responseCode = "200",
description = "操作成功",
content = {
@Content(
schema = @Schema(
ref = "#/components/schemas/MapOfOptionNameAndCliOption"
)
// schema = @Schema(type = "object", title = "配置选项键值对", description = "key是配置项名称, value是配置项对象")
)
}
)
}
)
// TODO 暂时还没有找到可以直接生成Map<String, CliOption>的配置方法, Schema注解没有additionalProperties
// @Schema(title = "配置选项键值对", ref = "#/components/schemas/MapOfOptionNameAndCliOption")
ResponseEntity<Map<String, CliOption>> getClientOptions(
@PathVariable
@Schema(
title = "开发语言",
description = "客户端代码使用的开发语言"
)
String language
);
@RequestMapping(
method = RequestMethod.POST,
value = "/gen/clients/{language}"
)
@Operation(
operationId = "generateClient",
summary = "生成客户端代码",
description = "根据`OpenAPI文档`和`代码生成配置选项`生成客户端代码。" +
"可以根据返回的`code`调用`GET /gen/download/{fileId}`接口下载生成的客户端代码。",
tags={ "clients", }
)
ResponseEntity<ResponseCode> generateClient(
@PathVariable
@Schema(
title = "开发语言",
description = "客户端代码使用的开发语言"
)
String language,
@Valid
@RequestBody
@Parameter(required=true)
GeneratorInput generatorInput
);
// endregion 客户端代码生成相关接口
// ////////////////////////////////////////////////////////////////////////
// region 服务端代码生成相关接口
@RequestMapping(
method = RequestMethod.GET,
value = "/gen/servers"
)
@Operation(
summary = "获取服务端开发语言列表",
description = "获取客户端代码生成支持的所有开发语言",
operationId = "serverOptions",
tags={ "servers", },
responses = {
@ApiResponse(
responseCode = "200",
description = "操作成功",
content = {
@Content(array = @ArraySchema(schema = @Schema(title = "服务端开发语言列表", description = "")))
}
)
}
)
List<String> serverOptions();
@RequestMapping(
method = RequestMethod.GET,
value = "/gen/servers/{framework}",
produces = { "application/json" }
)
@Operation(
operationId = "getServerOptions",
summary = "获取服务端开发框架代码生成的配置选项",
description = "",
tags={ "servers", },
responses = {
@ApiResponse(
responseCode = "200",
description = "操作成功",
content = {
@Content(
schema = @Schema(
ref = "#/components/schemas/MapOfOptionNameAndCliOption"
)
)
}
)
}
)
ResponseEntity<Map<String, CliOption>> getServerOptions(
@Parameter(description = "服务端开发框架",required=true)
@PathVariable
String framework
);
@RequestMapping(
value = "/gen/servers/{framework}",
method = RequestMethod.POST
)
@Operation(
operationId = "generateServerForLanguage",
summary = "生成服务端代码",
description = "根据`OpenAPI文档`和`代码生成配置选项`生成服务端代码。" +
"可以根据返回的`code`调用`GET /gen/download/{fileId}`接口下载生成的服务端代码。",
tags={ "servers", }//,
// responses = {
// @ApiResponse(
// responseCode = "200",
// description = "操作成功",
// content = {
// @Content(schema=@Schema(title = "", description = ""))
// }
// )
// }
)
ResponseEntity<ResponseCode> generateServerForLanguage(
@Parameter(description = "服务端开发框架",required=true)
@PathVariable
String framework,
@Parameter(description = "代码生成配置选项" ,required=true )
@Valid
@RequestBody
GeneratorInput generatorInput
);
// endregion 服务端代码生成相关接口
// ////////////////////////////////////////////////////////////////////////
// region 代码下载相关接口
@RequestMapping(
method = RequestMethod.GET,
value = "/gen/download/{fileId}",
produces = { "application/zip", "application/octet-stream" }
)
@Operation(
operationId = "downloadFile",
summary = "下载生成的代码",
description = ""
+ "文件ID来自于 `/gen/clients/{language}` 或者 `/gen/servers/{language}` 的 POST 操作。"
+ "一个文件ID只能用一次, 下载完成后文件就会被删除。"
,
tags={ "clients","servers", }
)
@Schema(type = "string", format = "binary", title = "文件内容", description = "返回一个ZIP文件。")
ResponseEntity<Resource> downloadFile(
@PathVariable
@Schema(
title="文件ID",
description = "由 `POST /gen/clients/{language}` 或者 `POST /gen/servers/{language}` 生成。"
)
String fileId
);
// endregion 代码下载相关接口
// ////////////////////////////////////////////////////////////////////////
}
|
ykrasik/jaci
|
jaci-cli-core/src/main/java/com/github/ykrasik/jaci/cli/assist/ParamAssistInfo.java
|
/******************************************************************************
* Copyright (C) 2015 <NAME> *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
******************************************************************************/
package com.github.ykrasik.jaci.cli.assist;
import java.util.Objects;
/**
* Assistance information for a command's parameters.
* Includes parameters that were already bound (and parsed) as well as auto-complete suggestions for the next parameter.
*
* @author <NAME>
*/
public class ParamAssistInfo {
private final BoundParams boundParams;
private final AutoComplete autoComplete;
public ParamAssistInfo(BoundParams boundParams, AutoComplete autoComplete) {
this.boundParams = Objects.requireNonNull(boundParams, "boundParams");
this.autoComplete = Objects.requireNonNull(autoComplete, "autoComplete");
}
/**
* @return Parameters that have already been parsed, as well as the next parameter to parse, if one exists.
*/
public BoundParams getBoundParams() {
return boundParams;
}
/**
* @return Auto-complete suggestions for the next parameter to parse.
*/
public AutoComplete getAutoComplete() {
return autoComplete;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final ParamAssistInfo that = (ParamAssistInfo) o;
if (!boundParams.equals(that.boundParams)) {
return false;
}
return autoComplete.equals(that.autoComplete);
}
@Override
public int hashCode() {
int result = boundParams.hashCode();
result = 31 * result + autoComplete.hashCode();
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ParamAssistInfo{");
sb.append("boundParams=").append(boundParams);
sb.append(", autoComplete=").append(autoComplete);
sb.append('}');
return sb.toString();
}
}
|
ethanlindley/panda3d
|
panda/src/char/characterJoint.h
|
<filename>panda/src/char/characterJoint.h<gh_stars>1-10
/**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file characterJoint.h
* @author drose
* @date 1999-02-23
*/
#ifndef CHARACTERJOINT_H
#define CHARACTERJOINT_H
#include "pandabase.h"
#include "transformState.h"
#include "movingPartMatrix.h"
#include "pandaNode.h"
#include "nodePathCollection.h"
#include "ordered_vector.h"
class JointVertexTransform;
class Character;
/**
* This represents one joint of the character's animation, containing an
* animating transform matrix.
*/
class EXPCL_PANDA_CHAR CharacterJoint : public MovingPartMatrix {
protected:
CharacterJoint();
CharacterJoint(const CharacterJoint ©);
PUBLISHED:
CharacterJoint(Character *character,
PartBundle *root, PartGroup *parent, const string &name,
const LMatrix4 &default_value);
virtual ~CharacterJoint();
public:
virtual bool is_character_joint() const;
virtual PartGroup *make_copy() const;
virtual bool update_internals(PartBundle *root, PartGroup *parent,
bool self_changed, bool parent_changed,
Thread *current_thread);
virtual void do_xform(const LMatrix4 &mat, const LMatrix4 &inv_mat);
PUBLISHED:
bool add_net_transform(PandaNode *node);
bool remove_net_transform(PandaNode *node);
bool has_net_transform(PandaNode *node) const;
void clear_net_transforms();
NodePathCollection get_net_transforms();
bool add_local_transform(PandaNode *node);
bool remove_local_transform(PandaNode *node);
bool has_local_transform(PandaNode *node) const;
void clear_local_transforms();
NodePathCollection get_local_transforms();
void get_transform(LMatrix4 &transform) const;
INLINE const LMatrix4 &get_transform() const;
CPT(TransformState) get_transform_state() const;
void get_net_transform(LMatrix4 &transform) const;
Character *get_character() const;
private:
void set_character(Character *character);
private:
// Not a reference-counted pointer.
Character *_character;
typedef ov_set< PT(PandaNode) > NodeList;
NodeList _net_transform_nodes;
NodeList _local_transform_nodes;
typedef ov_set<JointVertexTransform *> VertexTransforms;
VertexTransforms _vertex_transforms;
public:
static void register_with_read_factory();
virtual void write_datagram(BamWriter* manager, Datagram &me);
virtual int complete_pointers(TypedWritable **p_list,
BamReader *manager);
static TypedWritable *make_CharacterJoint(const FactoryParams ¶ms);
protected:
void fillin(DatagramIterator& scan, BamReader* manager);
private:
int _num_net_nodes, _num_local_nodes;
public:
// The _geom_node member just holds a temporary pointer to a node for the
// CharacterMaker's convenenience while creating the character. It does not
// store any meaningful value after creation is complete.
PT(PandaNode) _geom_node;
// These are filled in as the joint animates.
LMatrix4 _net_transform;
LMatrix4 _initial_net_transform_inverse;
public:
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
MovingPartMatrix::init_type();
register_type(_type_handle, "CharacterJoint",
MovingPartMatrix::get_class_type());
}
private:
static TypeHandle _type_handle;
friend class Character;
friend class CharacterJointBundle;
friend class JointVertexTransform;
};
#include "characterJoint.I"
#endif
|
ckamtsikis/cmssw
|
Configuration/Skimming/python/pdwgSingleMu_cfi.py
|
<reponame>ckamtsikis/cmssw<filename>Configuration/Skimming/python/pdwgSingleMu_cfi.py
import FWCore.ParameterSet.Config as cms
import Configuration.Skimming.pdwgLeptonRecoSkim_cfi
SingleMu = Configuration.Skimming.pdwgLeptonRecoSkim_cfi.PdwgLeptonRecoSkim.clone()
SingleMu.UseMuonSelection = cms.bool(True)
SingleMu.globalMuonPtMin = cms.double(20)
SingleMu.trackerMuonPtMin = cms.double(20)
SingleMu.muonN = cms.int32(1)
SingleMu.filterName = cms.string("SingleMu")
|
skeeey/multicloud-operators-foundation
|
vendor/open-cluster-management.io/addon-framework/pkg/addonmanager/controllers/agentdeploy/hookcontroller.go
|
<reponame>skeeey/multicloud-operators-foundation
package agentdeploy
import (
"context"
"fmt"
"github.com/openshift/library-go/pkg/controller/factory"
"github.com/openshift/library-go/pkg/operator/events"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/cache"
"k8s.io/klog/v2"
"open-cluster-management.io/addon-framework/pkg/addonmanager/constants"
"open-cluster-management.io/addon-framework/pkg/agent"
addonapiv1alpha1 "open-cluster-management.io/api/addon/v1alpha1"
addonv1alpha1client "open-cluster-management.io/api/client/addon/clientset/versioned"
addoninformerv1alpha1 "open-cluster-management.io/api/client/addon/informers/externalversions/addon/v1alpha1"
addonlisterv1alpha1 "open-cluster-management.io/api/client/addon/listers/addon/v1alpha1"
clusterinformers "open-cluster-management.io/api/client/cluster/informers/externalversions/cluster/v1"
clusterlister "open-cluster-management.io/api/client/cluster/listers/cluster/v1"
workv1client "open-cluster-management.io/api/client/work/clientset/versioned"
workinformers "open-cluster-management.io/api/client/work/informers/externalversions/work/v1"
worklister "open-cluster-management.io/api/client/work/listers/work/v1"
workapiv1 "open-cluster-management.io/api/work/v1"
)
// addonHookDeployController reconciles instances of managedClusterAddon and hook manifestWork on the hub.
type addonHookDeployController struct {
workClient workv1client.Interface
addonClient addonv1alpha1client.Interface
managedClusterLister clusterlister.ManagedClusterLister
managedClusterAddonLister addonlisterv1alpha1.ManagedClusterAddOnLister
workLister worklister.ManifestWorkLister
agentAddons map[string]agent.AgentAddon
cache *workCache
eventRecorder events.Recorder
}
func NewAddonHookDeployController(
workClient workv1client.Interface,
addonClient addonv1alpha1client.Interface,
clusterInformers clusterinformers.ManagedClusterInformer,
addonInformers addoninformerv1alpha1.ManagedClusterAddOnInformer,
workInformers workinformers.ManifestWorkInformer,
agentAddons map[string]agent.AgentAddon,
recorder events.Recorder,
) factory.Controller {
c := &addonHookDeployController{
workClient: workClient,
addonClient: addonClient,
managedClusterLister: clusterInformers.Lister(),
managedClusterAddonLister: addonInformers.Lister(),
workLister: workInformers.Lister(),
agentAddons: agentAddons,
cache: newWorkCache(),
eventRecorder: recorder.WithComponentSuffix("addon-hook-deploy-controller"),
}
return factory.New().WithFilteredEventsInformersQueueKeyFunc(
func(obj runtime.Object) string {
key, _ := cache.MetaNamespaceKeyFunc(obj)
return key
},
func(obj interface{}) bool {
accessor, _ := meta.Accessor(obj)
if _, ok := c.agentAddons[accessor.GetName()]; !ok {
return false
}
return true
},
addonInformers.Informer()).
WithFilteredEventsInformersQueueKeyFunc(
func(obj runtime.Object) string {
accessor, _ := meta.Accessor(obj)
return fmt.Sprintf("%s/%s", accessor.GetNamespace(), accessor.GetLabels()[constants.AddonLabel])
},
func(obj interface{}) bool {
accessor, _ := meta.Accessor(obj)
if accessor.GetLabels() == nil {
return false
}
addonName, ok := accessor.GetLabels()[constants.AddonLabel]
if !ok {
return false
}
if _, ok := c.agentAddons[addonName]; !ok {
return false
}
if accessor.GetName() != preDeleteHookWorkName(addonName) {
return false
}
return true
},
workInformers.Informer(),
).
WithSync(c.sync).ToController("addon-hook-deploy-controller", recorder)
}
func (c *addonHookDeployController) sync(ctx context.Context, syncCtx factory.SyncContext) error {
key := syncCtx.QueueKey()
klog.V(4).Infof("Reconciling addon hook deploy %q", key)
clusterName, addonName, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
// ignore addon whose key is not in format: namespace/name
return nil
}
agentAddon, ok := c.agentAddons[addonName]
if !ok {
return nil
}
// Get ManagedCluster
managedCluster, err := c.managedClusterLister.Get(clusterName)
if errors.IsNotFound(err) {
c.cache.removeCache(preDeleteHookWorkName(addonName), clusterName)
return nil
}
if err != nil {
return err
}
// should continue to apply pre-delete hook when the managedCluster is deleting.
managedClusterAddon, err := c.managedClusterAddonLister.ManagedClusterAddOns(clusterName).Get(addonName)
if errors.IsNotFound(err) {
c.cache.removeCache(preDeleteHookWorkName(addonName), clusterName)
return nil
}
if err != nil {
return err
}
managedClusterAddonCopy := managedClusterAddon.DeepCopy()
owner := metav1.NewControllerRef(managedClusterAddon, addonapiv1alpha1.GroupVersion.WithKind("ManagedClusterAddOn"))
objects, err := agentAddon.Manifests(managedCluster, managedClusterAddon)
if err != nil {
return err
}
if len(objects) == 0 {
return nil
}
_, hookWork, err := buildManifestWorkFromObject(clusterName, addonName, objects)
if err != nil {
return err
}
if hookWork == nil {
if !hasFinalizer(managedClusterAddonCopy.GetFinalizers(), constants.PreDeleteHookFinalizer) {
return nil
}
finalizer := removeFinalizer(managedClusterAddonCopy.Finalizers, constants.PreDeleteHookFinalizer)
managedClusterAddonCopy.SetFinalizers(finalizer)
_, err = c.addonClient.AddonV1alpha1().ManagedClusterAddOns(managedClusterAddonCopy.Namespace).Update(
ctx, managedClusterAddonCopy, metav1.UpdateOptions{})
return err
}
if managedClusterAddon.DeletionTimestamp.IsZero() {
if !hasFinalizer(managedClusterAddonCopy.GetFinalizers(), constants.PreDeleteHookFinalizer) {
managedClusterAddonCopy.Finalizers = append(managedClusterAddonCopy.Finalizers, constants.PreDeleteHookFinalizer)
_, err = c.addonClient.AddonV1alpha1().ManagedClusterAddOns(managedClusterAddonCopy.Namespace).Update(
ctx, managedClusterAddonCopy, metav1.UpdateOptions{})
return err
}
return nil
}
// apply hookWork when addon is deleting
hookWork.OwnerReferences = []metav1.OwnerReference{*owner}
hookWork, applyErr := applyWork(ctx, c.workClient, c.workLister, c.cache, c.eventRecorder, hookWork)
completed := hookWorkIsCompleted(hookWork)
if completed && hasFinalizer(managedClusterAddonCopy.Finalizers, constants.PreDeleteHookFinalizer) {
finalizer := removeFinalizer(managedClusterAddonCopy.Finalizers, constants.PreDeleteHookFinalizer)
managedClusterAddonCopy.SetFinalizers(finalizer)
_, err = c.addonClient.AddonV1alpha1().ManagedClusterAddOns(managedClusterAddonCopy.Namespace).Update(
ctx, managedClusterAddonCopy, metav1.UpdateOptions{})
return err
}
switch {
case applyErr != nil:
meta.SetStatusCondition(&managedClusterAddonCopy.Status.Conditions, metav1.Condition{
Type: "HookManifestCompleted",
Status: metav1.ConditionFalse,
Reason: "ManifestWorkApplyFailed",
Message: fmt.Sprintf("failed to apply hook manifestwork: %v", err),
})
case completed:
meta.SetStatusCondition(&managedClusterAddonCopy.Status.Conditions, metav1.Condition{
Type: "HookManifestCompleted",
Status: metav1.ConditionTrue,
Reason: "HookManifestIsCompleted",
Message: fmt.Sprintf("hook manifestWork %v is completed.", hookWork.Name),
})
default:
meta.SetStatusCondition(&managedClusterAddonCopy.Status.Conditions, metav1.Condition{
Type: "HookManifestCompleted",
Status: metav1.ConditionFalse,
Reason: "HookManifestIsNotCompleted",
Message: fmt.Sprintf("hook manifestWork %v is not completed.", hookWork.Name),
})
}
if !equality.Semantic.DeepEqual(managedClusterAddonCopy.Status, managedClusterAddon.Status) {
_, err = c.addonClient.AddonV1alpha1().ManagedClusterAddOns(managedClusterAddonCopy.Namespace).UpdateStatus(
ctx, managedClusterAddonCopy, metav1.UpdateOptions{})
return err
}
return nil
}
// hookWorkIsCompleted checks the hook resources are completed.
// hookManifestWork is completed if all resources are completed.
// currently, we only support job and pod as hook manifest.
// job is completed if the Completed condition of status is true.
// pod is completed if the phase of status is Succeeded.
func hookWorkIsCompleted(hookWork *workapiv1.ManifestWork) bool {
if hookWork == nil {
return false
}
if !meta.IsStatusConditionTrue(hookWork.Status.Conditions, workapiv1.WorkApplied) {
return false
}
if !meta.IsStatusConditionTrue(hookWork.Status.Conditions, workapiv1.WorkAvailable) {
return false
}
if len(hookWork.Spec.ManifestConfigs) == 0 {
klog.Errorf("the hook manifestWork should have manifest configs,but got 0.")
return false
}
for _, manifestConfig := range hookWork.Spec.ManifestConfigs {
switch manifestConfig.ResourceIdentifier.Resource {
case "jobs":
value := FindManifestValue(hookWork.Status.ResourceStatus, manifestConfig.ResourceIdentifier, "JobComplete")
if value.Type == "" {
return false
}
if value.String == nil {
return false
}
if *value.String != "True" {
return false
}
case "pods":
value := FindManifestValue(hookWork.Status.ResourceStatus, manifestConfig.ResourceIdentifier, "PodPhase")
if value.Type == "" {
return false
}
if value.String == nil {
return false
}
if *value.String != "Succeeded" {
return false
}
default:
return false
}
}
return true
}
|
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
|
Variant Programs/2-4/27/programmer/Developer.java
|
package programmer;
import salesperson.Yardmaster;
import faker.AppendageBrake;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
public abstract class Developer {
public int leftDeviceClock;
public int mediocreReversionMoment;
public abstract void cycleIn(Serve work);
public synchronized double producePercentageTakeNow() {
double beam;
beam = 0.7089426775973493;
return (double) this.percentageTakeNow / this.carriedMechanism.size();
}
public Serve prevailingProcedure;
public int actualRetick;
public synchronized void blockageCallback() {
double treated;
treated = 0.593257106497161;
this.isMoving = false;
this.publishingDescribe();
}
public synchronized boolean goIsMoving() {
int span;
span = -1104935636;
return isMoving;
}
public int intendingYears;
public static final int MeterMeasure = 4;
public synchronized double generateFairRecoveryYear() {
double restrain;
restrain = 0.13422962748118095;
return (double) this.mediocreReversionMoment / this.carriedMechanism.size();
}
public abstract void ourTicktack();
public synchronized int bringOngoingBeat() {
int juniorConstrained;
juniorConstrained = 479169496;
return actualRetick;
}
public Developer() {
this.isMoving = false;
this.flyingDay = 0;
this.intendingYears = 0;
this.percentageTakeNow = 0;
this.mediocreReversionMoment = 0;
this.actualRetick = -1;
this.carriedMechanism = new LinkedList<>();
this.inedTent = true;
}
public synchronized void nsoInitiate() {
String border;
border = "EbG";
try {
AppendageBrake.ExportSubmit.write("\n");
System.out.println();
AppendageBrake.ExportSubmit.write("\n" + this.spoolerDistinguish() + "\n");
System.out.println(this.spoolerDistinguish());
} catch (IOException voto) {
System.out.println("Unable to write " + this.spoolerDistinguish() + " to file.");
}
}
public synchronized int driveFinalizationTechniquesCapacity() {
double minimum;
minimum = 0.6121930323903745;
if (carriedMechanism.isEmpty()) {
return 0;
} else {
return carriedMechanism.size();
}
}
public static String fukkianese = "Eo8rPr6dDeAYCuZFCcL";
public synchronized void earlyWorkspace() {
double secondaryRestrain;
secondaryRestrain = 0.4508194715783035;
this.isMoving = true;
this.leftDeviceClock = Yardmaster.MurderWhen;
this.nsoInitiate();
}
public boolean inedTent;
public synchronized void publishingDescribe() {
String consider;
consider = "hpoL9dp8kwpz7r";
try {
String masthead;
Collections.sort(carriedMechanism);
AppendageBrake.ExportSubmit.write("\n");
System.out.println();
masthead = String.format("%-7s%16s%19s", "Process", "Waiting Time", "Turnaround Time");
AppendageBrake.ExportSubmit.write(masthead + "\n");
System.out.println(masthead);
for (Serve postscript : carriedMechanism) {
int leaveChance;
int reverseRoundMoment;
String methods;
leaveChance =
postscript.canEgressYears()
- postscript.obtainSendDays()
- postscript.obtainTimeoutLength();
reverseRoundMoment = postscript.canEgressYears() - postscript.obtainSendDays();
this.percentageTakeNow += leaveChance;
this.mediocreReversionMoment += reverseRoundMoment;
methods =
String.format("%-7s%16d%19d", postscript.beatUser(), leaveChance, reverseRoundMoment);
AppendageBrake.ExportSubmit.write(methods + "\n");
System.out.println(methods);
}
AppendageBrake.ExportSubmit.write("\n");
System.out.println();
} catch (IOException late) {
System.out.println("Unable to write " + this.spoolerDistinguish() + " to file.");
}
}
public LinkedList<Serve> carriedMechanism;
public int percentageTakeNow;
public synchronized void chargeAppendage(Serve writes) {
double chthonicChained;
chthonicChained = 0.018934145884605735;
try {
String cycle;
cycle = String.format("%-5s%3s", "T" + (this.bringOngoingBeat()) + ":", writes.beatUser());
AppendageBrake.ExportSubmit.write(cycle + "\n");
System.out.println(cycle);
} catch (IOException vet) {
System.out.println("Unable to write " + this.spoolerDistinguish() + " to file.");
}
}
public abstract String spoolerDistinguish();
public int flyingDay;
public synchronized void determinedLiveTic(int underwayWalk) {
String weakerTrammel;
weakerTrammel = "rt74xhP499";
this.actualRetick = underwayWalk;
}
public boolean isMoving;
}
|
alessandrojean/anime-no-keiei
|
src/gui/components/RoundedButton.java
|
<gh_stars>1-10
package gui.components;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultButtonModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class RoundedButton extends JButton {
private boolean pressed;
private Color background, hover;
public RoundedButton(Icon icon, Color background, Color hover)
{
this.background = background;
this.hover = hover;
setIcon(icon);
setBackground(background);
setContentAreaFilled(false);
setOpaque(true);
setCursor(new Cursor(Cursor.HAND_CURSOR));
setBorderPainted(false);
addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0)
{
setBackground(pressed ? hover : background);
}
@Override
public void mouseEntered(MouseEvent arg0)
{
setBackground(hover);
}
@Override
public void mouseClicked(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
});
}
public boolean isPressed()
{
return pressed;
}
public void setPressed(boolean pressed)
{
this.pressed = pressed;
setBackground(hover);
}
@Override
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(getBackground());
g2.fillOval(1, 1, getSize().width-2, getSize().height-2);
Image lImage = ((ImageIcon) getIcon()).getImage();
g2.drawImage(lImage, (getWidth()-lImage.getWidth(null))/2, (getHeight()-lImage.getHeight(null))/2, this);
g2.dispose();
}
}
|
iuskye/SREWorks
|
paas/appmanager/tesla-appmanager-meta-helm/src/main/java/com/alibaba/tesla/appmanager/meta/helm/repository/mapper/HelmMetaDOMapper.java
|
package com.alibaba.tesla.appmanager.meta.helm.repository.mapper;
import com.alibaba.tesla.appmanager.meta.helm.repository.domain.HelmMetaDO;
import com.alibaba.tesla.appmanager.meta.helm.repository.domain.HelmMetaDOExample;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface HelmMetaDOMapper {
long countByExample(HelmMetaDOExample example);
int deleteByExample(HelmMetaDOExample example);
int deleteByPrimaryKey(Long id);
int insert(HelmMetaDO record);
int insertSelective(HelmMetaDO record);
List<HelmMetaDO> selectByExample(HelmMetaDOExample example);
HelmMetaDO selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") HelmMetaDO record, @Param("example") HelmMetaDOExample example);
int updateByExample(@Param("record") HelmMetaDO record, @Param("example") HelmMetaDOExample example);
int updateByPrimaryKeySelective(HelmMetaDO record);
int updateByPrimaryKey(HelmMetaDO record);
}
|
BigMountainTiger/aws-cdk-examples
|
code-artifact-cdk/cdk.js
|
<gh_stars>1-10
#!/usr/bin/env node
const cdk = require('@aws-cdk/core');
const { CodeArtifactCdkStack } = require('./stacks/code-artifact-cdk-stack');
const app = new cdk.App();
new CodeArtifactCdkStack(app, 'CodeArtifactCdkStack');
|
BenjaminGonvers/SAE921-GRP4100-CPlusPlus-Class-BGonvers
|
CPlusPlus-Class/04. EX.09 OOP Inventaire/Item.cpp
|
#include "Item.h"
#include <iostream>
item::item(std::string new_name,std::string new_description)
{
this->name_ = new_name;
this->description_ = new_description;
std::cout << "item Constructor" << std::endl;
}
std::string item::get_name()
{
return this->name_;
}
std::string item::get_description()
{
return this->description_;
}
|
tusikalanse/acm-icpc
|
ProjectEuler/092.py
|
<filename>ProjectEuler/092.py
'''
Author: tusikalanse
Date: 2021-07-22 17:13:49
LastEditTime: 2021-07-22 17:27:22
LastEditors: tusikalanse
Description:
'''
from math import factorial
cnt = dict()
def gao(x: int)-> int:
return sum(map(lambda x: int(x) * int(x), str(x)))
for i in range(1, 10000000):
if i in cnt: continue
length = 0
l = dict()
x = i
while x not in l and x not in cnt:
l[x] = length
length += 1
x = gao(x)
if x in cnt:
x = cnt[x]
for d in l:
cnt[d] = x
ans = 0
for d in cnt:
if cnt[d] == 4:
ans += 1
print(ans)
|
dajohi/politeiagui
|
src/hooks/api/useNavigation.js
|
import * as act from "src/actions";
import * as sel from "src/selectors";
import { useSelector, useAction } from "src/redux";
export default function useNavigation() {
const user = useSelector(sel.currentUser);
const username = user && user.username;
const onLogout = useAction(act.onLogout);
const handleLogout = useAction(act.handleLogout);
return { user, username, onLogout, handleLogout };
}
|
kkcookies99/UAST
|
Dataset/Leetcode/train/121/274.java
|
<reponame>kkcookies99/UAST
class Solution {
public int XXX(int[] prices) {
int max = 0;
int min = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[min] >= prices[i]) {
min = i;
}else {
int price = prices[i] - prices[min];
if (max < price) {
max = price;
}
}
}
return max;
}
}
|
matrix-revolution/leetcode
|
src/main/java/com/fishercoder/solutions/_675.java
|
<gh_stars>1-10
package com.fishercoder.solutions;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* 675. Cut Off Trees for Golf Event
*
* You are asked to cut off trees in a forest for a golf event.
* The forest is represented as a non-negative 2D map, in this map:
* 0 represents the obstacle can't be reached.
* 1 represents the ground can be walked through.
*
* The place with number bigger than 1 represents a tree can be walked through,
* and this positive number represents the tree's height.
*
* You are asked to cut off all the trees in this forest in the order of tree's height -
* always cut off the tree with lowest height first.
* And after cutting, the original place has the tree will become a grass (value 1).
*
* You will start from the point (0, 0) and you should output the minimum steps you need to walk to cut off all the trees.
*
* If you can't cut off all the trees, output -1 in that situation.
* You are guaranteed that no two trees have the same height and there is at least one tree needs to be cut off.
*
* Example 1:
* Input:
* [
* [1,2,3],
* [0,0,4],
* [7,6,5]
* ]
* Output: 6
*
* Example 2:
* Input:
* [
* [1,2,3],
* [0,0,0],
* [7,6,5]
* ]
* Output: -1
*
* Example 3:
* Input:
* [
* [2,3,4],
* [0,0,5],
* [8,7,6]
* ]
* Output: 6
*
* Explanation: You started from the point (0,0) and you can cut off the tree in (0,0) directly without walking.
* Hint: size of the given matrix will not exceed 50x50.
*/
public class _675 {
public static class Solution1 {
public int cutOffTree(List<List<Integer>> forest) {
if (forest == null || forest.isEmpty() || forest.size() == 0 || forest.get(0).get(0) == 0) {
return -1;
}
int m = forest.size();
int n = forest.get(0).size();
/**cut trees in ascending order*/
PriorityQueue<Tree> heap = new PriorityQueue<>((a, b) -> a.height - b.height);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (forest.get(i).get(j) > 1) {
/**This is important: we'll add trees that are only taller than 1!!!*/
heap.offer(new Tree(i, j, forest.get(i).get(j)));
}
}
}
int sum = 0;
Tree start = new Tree();
while (!heap.isEmpty()) {
Tree curr = heap.poll();
int step = bfs(forest, curr, start, m, n);
if (step == -1) {
return -1;
}
sum += step;
start = curr;
}
return sum;
}
private int bfs(List<List<Integer>> forest, Tree target, Tree start, int m, int n) {
int[] dirs = new int[]{0, 1, 0, -1, 0};
boolean[][] visited = new boolean[m][n];
Queue<Tree> queue = new LinkedList<>();
queue.offer(start);
visited[start.x][start.y] = true;
int step = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int k = 0; k < size; k++) {
Tree tree = queue.poll();
if (tree.x == target.x && tree.y == target.y) {
return step;
}
for (int i = 0; i < 4; i++) {
int nextX = tree.x + dirs[i];
int nextY = tree.y + dirs[i + 1];
if (nextX < 0 || nextY < 0 || nextX >= m || nextY >= n || visited[nextX][nextY] || forest.get(nextX).get(nextY) == 0) {
continue;
}
queue.offer(new Tree(nextX, nextY, forest.get(nextX).get(nextY)));
visited[nextX][nextY] = true;
}
}
step++;
}
return -1;
}
class Tree {
int x;
int y;
int height;
public Tree(int x, int y, int height) {
this.x = x;
this.y = y;
this.height = height;
}
public Tree() {
this.x = 0;
this.y = 0;
this.height = 0;
}
}
}
}
|
CrackerCat/Recaf
|
src/main/java/me/coley/recaf/plugin/api/ClassVisitorPlugin.java
|
<reponame>CrackerCat/Recaf
package me.coley.recaf.plugin.api;
import org.objectweb.asm.ClassVisitor;
/**
* Allow plugins to intercept and modify {@link ClassVisitor}.
*
* @author xxDark
*/
public interface ClassVisitorPlugin extends BasePlugin {
/**
* Intercepts the given {@link ClassVisitor}.
*
* @param visitor
* Visitor to intercept.
* @return intercepted {@link ClassVisitor}.
*/
ClassVisitor intercept(ClassVisitor visitor);
}
|
AutoPacker-OSS/AutoPacker
|
webapp-test/src/main/java/no/autopacker/webtests/helpers/OsCheck.java
|
package no.autopacker.webtests.helpers;
import java.util.Locale;
/**
* Helper class to check the operating system this Java VM runs in
* <p>
* Code adapted from http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java
*/
public final class OsCheck {
// cached result of OS detection
protected static OSType detectedOS;
/**
* detect the operating system from the os.name System property and cache
* the result
*
* @return - the operating system detected
*/
public static OSType getOperatingSystemType() {
if (detectedOS == null) {
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
System.out.println("OS: " + OS);
if ((OS.contains("mac")) || (OS.contains("darwin"))) {
detectedOS = OSType.MacOS;
} else if (OS.contains("win")) {
detectedOS = OSType.Windows;
} else if (OS.contains("nux")) {
detectedOS = OSType.Linux;
} else {
detectedOS = OSType.Other;
}
}
return detectedOS;
}
}
|
thinking-github/nbone
|
nbone/nbone-core/src/test/java/org/nbone/test/TestMain.java
|
package org.nbone.test;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.nbone.util.BeanMapUtils;
import org.nbone.util.json.JSONOperUtils;
import org.nbone.web.support.WebResultWrapper;
import org.springframework.util.StringUtils;
public class TestMain {
public static void main(String[] args) {
String wrapData=JSONOperUtils.pojoToJSON(WebResultWrapper.failedResultWraped("00"));
System.out.println(wrapData);
Set<String> set = new HashSet<String> ();
set.add("ll");
set.add("ll");
set.add("llpp");
System.out.println(StringUtils.collectionToDelimitedString(set, ",", "'", "'"));
System.out.println(NumberFormat.getNumberInstance().format(3.88999999999999));
System.out.println();
List list = new ArrayList();
list.add(new UserTest());
list.add("chen22");
Map map =BeanMapUtils.populateMap(WebResultWrapper.failedResultWraped("00"));
Map map1 =BeanMapUtils.populateMap(WebResultWrapper.successResultWraped(list));
System.out.println(map);
System.out.println(map1);
WebResultWrapper wrap = new WebResultWrapper();
BeanMapUtils.populateBean(wrap, map1);
System.out.println(wrap);
System.out.println(TestMain.class.getPackage());
System.out.println(-(5.0/4));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("------------");
System.out.println("===========================");
}
}
|
rhbvkleef/SteamBird
|
steambird/settings.py
|
import os
from importlib.util import find_spec
from django.utils.translation import ugettext_lazy as _
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<KEY>
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("DEBUG", "True") in ["True", "1", "true"]
INTERNAL_IPS = ('127.0.0.1',)
ALLOWED_HOSTS = ([
'127.0.0.1',
'localhost'
] if DEBUG else ['*'])
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polymorphic',
'modeltranslation',
'steambird',
'steambird.boecie',
'steambird.teacher',
'steambird.material_management',
'pysidian_core',
'django_select2',
'django_addanother',
] + ([
'django_uwsgi',
] if find_spec('django_uwsgi') else [
]) + ([
'rosetta',
'debug_toolbar',
] if DEBUG else [
])
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
] + ([
'debug_toolbar.middleware.DebugToolbarMiddleware',
] if DEBUG else [
])
ROOT_URLCONF = 'steambird.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'steambird.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': os.getenv('DB_ENGINE', 'django.db.backends.postgresql_psycopg2'),
'NAME': os.getenv('DB_NAME', 'stoomvogel'),
'USER': os.getenv('DB_USERNAME', 'stoomvogel'),
'PASSWORD': os.getenv('DB_PASSWORD', 'stoomvogel'),
'HOST': os.getenv('DB_HOST', 'localhost'),
'PORT': os.getenv('DB_PORT', '5432'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGES = [
('nl', _('Dutch')),
('en', _('English')),
]
LANGUAGE_CODE = 'en'
TIME_ZONE = 'Europe/Amsterdam'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# How to generate locale files:
# https://docs.djangoproject.com/en/2.1/topics/i18n/translation/#localization-how-to-create-language-files
LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Login URL
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/login/'
# Configures email backends
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_HOST = '172.16.31.10'
# EMAIL_PORT = 587
# EMAIL_USE_TLS = True
try:
# pylint: disable=wildcard-import, unused-wildcard-import
from .local import *
except ImportError:
print("Failed to import local.py. It is recommended to add them.")
|
zmdsn/MANSP
|
problem/problem_based.hpp
|
#ifndef _PROBLEM_BASE_
#define _PROBLEM_BASE_
#include <dirent.h>
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h> // 提供mode_t 类型
#include <sys/stat.h> // 提供属性操作函数
//#include <dirent.h> // 提供目录流操作函数
#include <stdlib.h>
#include <fcntl.h> // 提供open()函数
using namespace std;
template<typename EMAP>
inline DType GetTail(int x,EMAP& ES){
return ES[x].tail;
}
template<typename EMAP>
inline DType GetHead(int x,EMAP& ES){
return ES[x].head;
}
template<typename EMAP>
inline DType GetCost(int x,EMAP& ES){
return ES[x].cost;
}
template<typename EMAP>
inline DType GetDemand(int x,EMAP& ES){
return ES[x].demand;
}
inline DType GetTail(int x,EMAP& ES){
return ES[x].tail;
}
inline DType GetHead(int x,EMAP& ES){
return ES[x].head;
}
inline DType GetCost(int x,EMAP& ES){
return ES[x].cost;
}
inline DType GetDemand(int x,EMAP& ES){
return ES[x].demand;
}
inline void RandD(){
int N = 100;
int i,j;
for(i=0;i<DMS;i++){
for(j=0;j<DMS;j++){
D[i][j] = RandChoose(N);
}
}
}
inline void RandEL(){
int N = 100;
int i=0,j;
ES[i].tail = depot;
ES[i].head = depot;
ES[i].cost = 0;
ES[i].demand = 0;
for(i=1;i<30;i++){
ES[i].tail = Rand(6)+1;
ES[i].head = Rand(6)+1;
ES[i].cost = Rand(N);
ES[i].demand = Rand(4)+2;
}
}
template<typename Matrix>
inline bool save2fileMatrix(Matrix &D, int n,string filename){
ofstream destFile(filename,ios::out); //以文本模式打开out.txt备写
if(!destFile) {
cout << "error opening destination file." << endl;
return 0;
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
destFile << D[i][j] <<" ";
}
destFile<<endl;
}
destFile.close();
return 1;
}
template<typename Matrix>
inline bool readfileMatrix(Matrix &D, int n, string filename){
ifstream destFile(filename,ios::in); //以文本模式打开out.txt备写
if(!destFile) {
cout << "error opening destination file." << endl;
return 0;
}
string x;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
destFile >> D[i][j];
}
//destFile >> x;
}
destFile.close();
return 1;
}
template <typename EMAP, typename DMatrix>
bool READ_EGL2GM(string filename, EMAP& ES, DMatrix& D,int &Q,int& LES){
ifstream srcFile(filename,ios::in);
if(!srcFile) {
cout << "error opening source file." << endl;
return 0;
}
int ARISTAS_REQ;
int ARISTAS_NOREQ;
int i,u,v,c,d;
int DEPOSITO;
string x;
int n_vertices = 0;
int esi = 1;
while(srcFile >> x){
if(x == "NOMBRE"){
// cout<<"read name"<<endl;
}
if(x == "CAPACIDAD"){
srcFile >> x;
srcFile >> Q;
}
if(x == "VERTICES"){
srcFile >> x;
srcFile >> n_vertices;
}
if(x == "ARISTAS_REQ"){
srcFile >> x;
srcFile >> ARISTAS_REQ;
}
if(x == "ARISTAS_NOREQ"){
srcFile >> x;
srcFile >> ARISTAS_NOREQ;
}
// BEIJING && HEFEI
if(x == "CAPACITY:"){
srcFile >> Q;
}
if(x == "REQUIRED"){
srcFile >> x;
srcFile >> ARISTAS_REQ;
}
if(x == "LISTA_ARISTAS_REQ"){
srcFile >> x;
int i=0;
while( i<ARISTAS_REQ){
srcFile >> x;
srcFile >> u;
srcFile >> x;
srcFile >> v;
srcFile >> x;
srcFile >> x;
srcFile >> c;
srcFile >> x;
srcFile >> d;
if(u>n_vertices)n_vertices=u;
if(v>n_vertices)n_vertices=v;
ES[esi].tail = u;
ES[esi].head = v;
ES[esi].cost = c;
ES[esi++].demand = d;
#ifdef CODETYPE
ES[esi+ARISTAS_REQ].tail = v;
ES[esi+ARISTAS_REQ].head = u;
ES[esi+ARISTAS_REQ].cost = c;
ES[esi+ARISTAS_REQ].demand = d;
#else
ES[esi].tail = v;
ES[esi].head = u;
ES[esi].cost = c;
ES[esi++].demand = d;
#endif
i++;
}
}
if(x == "DEPOSITO"){
srcFile >> x;
srcFile >> depot;
if (depot) {
depot_not_0 = 1;
}
}
} //可以像用cin那样用ifstream对象
srcFile.close();
ES[0].tail = depot;
ES[0].head = depot;
ES[0].cost = 0;
ES[0].demand = 0;
filename[filename.size()-3] = 'm';
readfileMatrix(D, n_vertices,filename);
// LES = esi-1;
LES = ARISTAS_REQ;
// cout<<"init G ok"<<endl;
return 1;
}
template <typename EMAP, typename DMatrix>
bool READ_BJ2GM(string filename, EMAP& ES, DMatrix& D,int &Q,int& LES)
{
ifstream srcFile(filename,ios::in);
if(!srcFile) {
cout << "error opening source file." << endl;
return 0;
}
int ARISTAS_REQ;
int ARISTAS_NOREQ;
int i,u,v,c,d;
int DEPOSITO;
string x;
int n_vertices = 0;
int esi = 1;
while(srcFile >> x){
if(x == "CAPACITY:"){
srcFile >> Q;
}
if(x == "VERTICES:"){
srcFile >> n_vertices;
}
if(x == "REQUIRED"){
srcFile >> x;
srcFile >> ARISTAS_REQ;
}
if(x == "TOTAL"){
srcFile >> x;
srcFile >> x;
srcFile >> x;
srcFile >> x;
srcFile >> x;
}
if(x == "NON-REQUIRED"){
srcFile >> x;
srcFile >> ARISTAS_NOREQ;
}
if(x == "NODES"){
srcFile >> x;
srcFile >> x;
i = 0;
// cout << ARISTAS_NOREQ<<endl;
while( i<ARISTAS_REQ+ARISTAS_NOREQ){
srcFile >> u;
srcFile >> v;
srcFile >> c;
srcFile >> d;
if(u>n_vertices)n_vertices=u;
if(v>n_vertices)n_vertices=v;
if(d>0){
ES[esi].tail = u;
ES[esi].head = v;
ES[esi].cost = c;
ES[esi++].demand = d;
#ifdef CODETYPE
ES[esi+ARISTAS_REQ].tail = v;
ES[esi+ARISTAS_REQ].head = u;
ES[esi+ARISTAS_REQ].cost = c;
ES[esi+ARISTAS_REQ].demand = d;
#else
ES[esi].tail = v;
ES[esi].head = u;
ES[esi].cost = c;
ES[esi++].demand = d;
#endif
}
i++;
}
}
if(x == "DEPOT:"){
srcFile >> depot;
if (depot) {
depot_not_0 = 1;
}
}
} //可以像用cin那样用ifstream对象
srcFile.close();
ES[0].tail = depot;
ES[0].head = depot;
ES[0].cost = 0;
ES[0].demand = 0;
filename[filename.size()-3] = 'm';
readfileMatrix(D, n_vertices,filename);
LES = ARISTAS_REQ;
// cout<<"init G ok"<<endl;
return 1;
}
void GotFile(string filename){
READ_EGL2GM(filename, ES, D,Q,LES);
}
//template<typename EMAP,typename DMatrix>
inline VType min_Distance(int a,int b,EMAP& ES, DMatrix &D){
int u,v,x,y;
u = ES[a].head-depot_not_0;
v = ES[a].tail-depot_not_0;
x = ES[b].head-depot_not_0;
y = ES[b].tail-depot_not_0;
VType mindistance = INF;
if (D[u][x] < mindistance) mindistance = D[u][x];
if (D[u][y] < mindistance) mindistance = D[u][y];
if (D[v][x] < mindistance) mindistance = D[v][x];
if (D[v][y] < mindistance) mindistance = D[v][y];
return mindistance;
}
//template<typename EMAP,typename DMatrix>
inline VType Distance(int a,int b,EMAP& ES, DMatrix &D){
// cout << ES[a].head<<","<<ES[b].tail;
// #ifdef CODETYPE
// return D[ES[a].head-depot_not_0 ][ES[b].tail-depot_not_0];
// #else
return D[ES[a].head-depot_not_0 ][ES[b].tail-depot_not_0];
// #endif
}
template<typename EMAP,typename DMatrix>
inline VType Distance(int a,int b,EMAP& ES, DMatrix &D){
// #ifdef CODETYPE
// return D[ES[a].head-depot_not_0 ][ES[b].tail-depot_not_0];
// #else
// return D[ES[a].head-depot_not_0 ][ES[b].tail-depot_not_0];
// #endif
return D[ES[a].head-depot_not_0 ][ES[b].tail-depot_not_0];
}
//template<typename PATH,typename EMAP,typename DMatrix>
inline bool QC(PATH &P,EMAP &ES,DMatrix &D,DType& Q){
int len = P[0];
DType dem = 0;
PATH S;
int SP[len];
Decode(S,P);
Split(P,SP);
int nextE,E;
// Trail(SP);
for(int j=1;j<SP[0];j++){
// cout<<SP[j]<<" ";
dem = 0;
for(int i=SP[j];i<SP[j+1];i++){
E = S[i];
dem += GetDemand(E,ES);
}
// cout<<dem<<" ";
if(dem>Q){
return 0;
}
}
return 1;
}
//template<typename PATH,typename EMAP,typename DMatrix>
DType VioConsCal(PATH &P,EMAP &ES,DMatrix &D,DType& Q){
int len = P[0];
DType vio = 0,loadk=0;
PATH S;
Decode(S,P);
int nextE,E;
for(int i=1;i<=len;i++){
E = S[i];
if(E==0){
vio += loadk>Q?loadk - Q:0;
loadk = 0;
continue;
}
loadk += GetDemand(E,ES);
}
return vio;
}
//template<typename PATH,typename EMAP,typename DMatrix>
VType ValueCal(PATH &P,EMAP &ES,DMatrix &D){
int len = P[0];
VType cost = 0;
PATH S;
Decode(S,P);
int nextE,E;
cost += GetCost(P[len],ES);
for(int i=1;i<len;i++){
// E = S[i];
// nextE = S[i+1];
cost += Distance(S[i],S[i+1],ES,D) + GetCost(S[i],ES);
// E = S[i];
// nextE = S[i+1];
// cost += Distance(E,nextE,ES,D) + GetCost(E,ES);
// std::cout<<E<<" ("<<GetTail(E,ES)<<","<<GetHead(E,ES)<<")"<<" : "<<GetCost(E,ES)<<"\t == "<<Distance(E,nextE,ES,D)<<" =>\t"<<nextE<<" ("<<GetTail(nextE,ES)<<","<<GetHead(nextE,ES)<<") :\t "<<","<<cost<<std::endl;
}
// std::cout<<cost <<std::endl;
//delete [] S;
return cost;
}
template<typename PATH,typename EMAP,typename DMatrix>
VType ValueCal(PATH &P,EMAP &ES,DMatrix &D){
int len = P[0];
VType cost = 0;
PATH S;
Decode(S,P);
int nextE,E;
cost += GetCost(P[len],ES);
// for(int i=len-1;i>=1;i--){
for(int i=1;i<len;i++){
// E = S[i];
// nextE = S[i+1];
cost += Distance(S[i],S[i+1],ES,D) + GetCost(S[i],ES);
// E = S[i];
// nextE = S[i+1];
// cost += Distance(E,nextE,ES,D) + GetCost(E,ES);
// std::cout<<E<<" ("<<GetTail(E,ES)<<","<<GetHead(E,ES)<<")"<<" : "<<GetCost(E,ES)<<"\t == "<<Distance(E,nextE,ES,D)<<" =>\t"<<nextE<<" ("<<GetTail(nextE,ES)<<","<<GetHead(nextE,ES)<<") :\t "<<","<<cost<<std::endl;
}
// std::cout<<cost <<std::endl;
//delete [] S;
return cost;
}
VType _0ECal(PATH &P,int& len,EMAP &ES,DMatrix &D){
// calculate all cost of (e,0) and (0,e)
int splitPos[ P[0] ];
Split(P,splitPos);
len = splitPos[0]-1;
VType cost = 0;
PATH S;
Decode(S,P);
for(int i=1;i<splitPos[0];i++){
cost += Distance(S[splitPos[i]],S[splitPos[i]+1],ES,D);
}
for(int i=splitPos[0];i>1;i--){
cost += Distance(S[splitPos[i]-1],S[splitPos[i]],ES,D);
}
return cost;
}
void SubLCal(PATH &P,int* len,EMAP &ES,DMatrix &D){
// calculate all cost of (e,0) and (0,e)
int splitPos[ P[0] ];
Split(P,splitPos);
len[0] = 0;
PATH S;
for(int i=1;i<splitPos[0];i++){
getSubk(S,P,i);
len[++len[0]] = ValueCal(S,ES,D);
}
}
//template<typename PATH,typename EMAP,typename DMatrix>
VType MaxLSubP(PATH &P,EMAP &ES,DMatrix& D){
int len = P[0];
VType cost = 0;
// int* S = new int[len];
PATH S;
Decode(S,P);
int MaxL=0;
int SubLen = 0;
int E;
for(int i=1;i<=len;i++){
E = S[i];
// std::cout<<SubLen<<std::endl;
if(E==0){
if(SubLen>MaxL){
MaxL = SubLen;
}
SubLen = 0;
}else{
SubLen++;
}
}
// delete [] S;
return (VType)MaxL;
}
//template<typename PATH,typename EMAP,typename DMatrix>
VType MObj(PATH &P,EMAP &ES,DMatrix& D,int k){
switch(k){
case 1: return ValueCal(P,ES,D);
case 2: return MaxLSubP(P,ES,D);
case 3: return ValueCal(P,ES,D);
case 4: return ValueCal(P,ES,D);
case 5: return ValueCal(P,ES,D);
case 6: return ValueCal(P,ES,D);
}
return -1;
}
//template<typename PATH,typename EMAP,typename DMatrix>
inline VType ChangeCost(PATH &P,EMAP &ES,DMatrix& D,int e,int k){
if(k==1){
return Distance(Edepot,e,ES,D)+Distance(e,P[k+1],ES,D)-Distance(Edepot,P[k],ES,D) - Distance(P[k],P[k+1],ES,D);
}else if(k==P[0]){
return Distance(P[k-1],e,ES,D)+Distance(e,Edepot,ES,D)-Distance(P[k-1],P[k],ES,D)-Distance(P[k],Edepot,ES,D);
}
return Distance(P[k-1],e,ES,D)+Distance(e,P[k+1],ES,D)-Distance(P[k-1],P[k],ES,D)-Distance(P[k],P[k+1],ES,D);
}
//template<typename PATH,typename EMAP,typename DMatrix>
inline VType OPT2Cost(PATH &P,EMAP &ES,DMatrix& D,int ki,int kj){
VType cost;
int s;
int x,y,u,v;
// ki->y, kj -> u
if (ki<kj) {
// case 1 [(x,y),...,(u,v)] => [(x,u'),...,(y',v)]
x = ki-1;
y = ki;
u = kj;
v = kj+1;
cost = Distance(P[x],ReverseElement(P[u]),ES,D);
cost += Distance(ReverseElement(P[y]),P[v],ES,D);
return cost - Distance(P[x],P[y],ES,D) - Distance(P[u],P[v],ES,D);
} else {
// case 2 [(x,y),...,(u,v)] => [(x,v),...,(u,y)]
x = kj-1;
y = kj;
u = ki;
v = ki+1;
//cout<<P[x]<<P[u];
cost = Distance(P[x],P[v],ES,D);
cost += Distance(P[u],P[y],ES,D);
return cost - Distance(P[x],P[y],ES,D) - Distance(P[u],P[v],ES,D);
}
}
//template<typename PATH,typename EMAP,typename DMatrix>
inline VType InsertCost(PATH &P,EMAP &ES,DMatrix& D,int e,int k){
if(k==1){
return Distance(Edepot,e,ES,D)+Distance(e,P[k],ES,D)-Distance(Edepot,P[k],ES,D);
}else if(k==P[0]+1){
return Distance(P[P[0] ],e,ES,D)+Distance(e,Edepot,ES,D)-Distance(P[P[0] ],Edepot,ES,D);
}
return Distance(P[k-1],e,ES,D)+Distance(e,P[k],ES,D)-Distance(P[k-1],P[k],ES,D);
}
//template<typename PATH,typename EMAP,typename DMatrix>
inline VType DeleteCost(PATH &P,EMAP &ES,DMatrix& D,int k){
if(k==1){
return Distance(Edepot,P[k+1],ES,D)-Distance(Edepot,P[k],ES,D)-Distance(P[k],P[k+1],ES,D);
}else if(k==P[0]){
return Distance(P[k-1],Edepot,ES,D) - Distance(P[k-1],P[k],ES,D) - Distance(P[k],Edepot,ES,D);
}
return Distance(P[k-1],P[k+1],ES,D) - Distance(P[k-1],P[k],ES,D) - Distance(P[k],P[k+1],ES,D);
}
//template<typename PATH,typename EMAP,typename DMatrix>
inline VType InsertSegmentCost(PATH &P,EMAP &ES,DMatrix& D,int* ei,int k){
int ksize = ei[0];
int e1,ed;
e1 = ei[1];
ed = ei[ei[0]];
VType cost=0;
for(int i=1;i<ei[0];i++){
cost += GetCost(ei[i],ES)+Distance(ei[i],ei[i+1],ES,D);
}
cost += GetCost(ei[ei[0] ] ,ES);
if(k==1){
return cost + Distance(Edepot,e1,ES,D)+Distance(ed,P[k],ES,D) - Distance(Edepot,P[k],ES,D);
}else if(k==P[0]+1){
return cost + Distance(Edepot,e1,ES,D)+Distance(ed,Edepot,ES,D);
}
return cost + Distance(P[k-1],e1,ES,D)+Distance(ed,P[k],ES,D) - Distance(P[k-1],P[k],ES,D);
}
//template<typename PATH,typename EMAP,typename DMatrix>
inline VType ChangeSegmentCost(PATH &P,EMAP &ES,DMatrix& D,int* ei,int k){
int ksize = ei[0];
int e1,ed;
int l = ei[0];
e1 = ei[1];
ed = ei[ei[0]];
VType cost=0;
if(k+l>P[0]) return 0x3f3f3f3f;
cost = InsertSegmentCost(P,ES,D,ei,k);
for(int j=k;j<k+l;j++){
cost -= (Distance(P[j],P[j+1],ES,D)+GetCost(P[j],ES));
}
cost += -Distance(ed,P[k],ES,D)+ Distance(ed,P[k+l],ES,D);
return cost ;
}
//template<typename PATH,typename EMAP,typename DMatrix>
inline VType DeleteSegmentCost(PATH &P,EMAP &ES,DMatrix& D,int k,int ksize){
int e1,ed;
e1 = P[k];
ed = P[k+ksize-1];
VType cost=0;
for(int i=k;i<k+ksize;i++){
cost -= GetCost(P[i],ES)+Distance(P[i],P[i+1],ES,D);
}
// cost -= Distance(P[k-1],P[k],ES,D);
if(k==1){
cost -= Distance(Edepot,P[k],ES,D);
return cost + Distance(Edepot,P[k+ksize],ES,D);
}else if(k==P[0]-ksize+1){
cost -= Distance(P[k-1],P[k],ES,D);
return cost + Distance(P[k-1],Edepot,ES,D);
}
cost -= Distance(P[k-1],P[k],ES,D);
return cost+Distance(P[k-1],P[k+ksize],ES,D);
}
vector<string> get_files_under(string FILEPATH){
struct dirent *ptr;
DIR *dir;
// FILEPATH = "./gdb";
dir=opendir(FILEPATH.c_str());
vector<string> files;
cout << "文件列表: "<< endl;
string feature = ".dat";
string feature1 = ".txt";
string fname;
while((ptr=readdir(dir))!=NULL) {
//跳过'.'和'..'两个目录
if(ptr->d_name[0] == '.')
continue;
fname = ptr->d_name;
if(fname.find(feature) != string::npos || fname.find(feature1) != string::npos){
files.push_back(ptr->d_name);
}
}
for (int i = 0; i<files.size(); ++i) {
cout << files[i] << endl;
}
closedir(dir);
return files;
}
vector<string> get_folders_under(string FILEPATH){
// char buff[1000];
// getcwd(buff, 1000);
// cout << "当前路径是:" << buff << endl;
struct dirent *ptr;
DIR *dir;
int res;
#ifdef WIN32
struct _stat statbuf; // 获取下一级成员属性
#else
struct stat statbuf; // 获取下一级成员属性
#endif
dir=opendir(FILEPATH.c_str());
//cout<<FILEPATH<<"\t";
vector<string> folders;
cout<< endl << "文件夹列表: "<< endl;
//chdir (FILEPATH.c_str());
string fname;
// cout<<length(dir);
if(dir) {
while((ptr=readdir(dir))!=NULL)
{
//跳过'.'和'..'两个目录
if (ptr->d_name[0] == '.')
continue;
fname = ptr->d_name;
fname = FILEPATH+"/"+fname;
#ifdef WIN32
cout<<"WIN32"<<endl;
_stat(ptr->d_name, &statbuf); // 获取下一级成员属性
if(statbuf.st_mode & S_IFDIR) // 判断下一级成员是否是目录 S_IFDIR
{
folders.push_back(ptr->d_name);
}
#else
//cout<<fname<<"\t";
res = lstat(fname.c_str(), &statbuf); // 获取下一级成员属性
//res = lstat("../instance/gdb/gdb1.dat", &statbuf); // 获取下一级成员属性
//res = lstat(ptr->d_name, &statbuf); // 获取下一级成员属性
if (res==-1) cout<<ptr->d_name<<" get stat false\n";
if(statbuf.st_mode & __S_IFDIR) // 判断下一级成员是否是目录 S_IFDIR
{
folders.push_back(ptr->d_name);
}
#endif
}
for (int i = 0; i<folders.size(); ++i)
{
cout << folders[i] << endl;
}
//chdir(buff);
closedir(dir);
return folders;
} else {
cout << "can't open the foldes "<< endl;
}
return folders;
}
template<typename PATH>
inline bool readresult(PATH &P, string filename){
ifstream srcFile(filename,ios::in); //以文本模式打开out.txt备写
if(!srcFile) {
cout << "error opening destination file." << endl;
return 0;
}
string x;
while(srcFile >> x) {
if(x == "best"){
srcFile >> x;
if(x == "solution"){
srcFile >> x;
srcFile >> P[0];
for (int i=1;i<=P[0];i++) {
srcFile >> P[i];
}
}
}
}
srcFile.close();
return 1;
}
template<typename T>
bool read_low_bound(string filename,string obj,T& low_bound){
low_bound = 0;
ifstream destFile(filename,ios::in);
if(!destFile) {
cout << "error opening destination file." << endl;
return 0;
}
string x;
int n =10;
int pos,pos2;
string strpos;
while(destFile>>x) {
//cout<<x<<endl;
pos = x.find(",", 0);
//cout<<pos<<endl;
strpos = x.substr(0,pos);
if (strpos == obj) {
pos2 = x.find(",", pos+1);
// cout<<pos<< pos2-pos<<endl;
strpos = x.substr(pos+1,pos2-pos-1);
istringstream is(strpos);
is>>low_bound;
//low_bound = stoi(strpos);
destFile.close();
return 1;
}
}
destFile.close();
return 0;
}
template<typename T>
bool check_low_bound(T& result,T& low_bound){
if (result<=low_bound) {
return 1;
}else{
return 0;
}
}
template<typename EMAP,typename DMatrix>
void Get_graph(EMAP& ES,DMatrix& D,DMatrix& G,DMatrix& W,int depot){
int tail,head;
int n_vertex,v;
for(int i=0;i<=2*LES;i++) {
tail = GetTail(i,ES);
head = GetHead(i,ES);
D[tail][head] = GetCost(i,ES);
if (tail>n_vertex) n_vertex = tail;
if (head>n_vertex) n_vertex = head;
}
for(int i=0;i<=n_vertex;i++) {
for(int j=0;j<=n_vertex;j++) {
G[i][j] = INF;
if (i>0&&j>0) {
v = D[i-depot][j-depot];
if (v>0) G[i][j] = v;
}
if (i==depot&&j==depot)
G[i][j] = 0;
}
}
}
template<typename EMAP,typename DMatrix>
void Get_graph(EMAP& ES,DMatrix& D,DMatrix& G,DMatrix& W,int depot,int& n_vertex){
int tail,head,v;
n_vertex = 0;
for(int i=0;i<=2*LES;i++) {
tail = GetTail(i,ES);
head = GetHead(i,ES);
//cout<<tail<<","<<head<<endl;
if (tail>n_vertex) n_vertex = tail;
if (head>n_vertex) n_vertex = head;
W[tail][head] = GetDemand(i,ES);
}
//cout<<n_vertex<<endl;
for(int i=0;i<=n_vertex;i++) {
for(int j=0;j<=n_vertex;j++) {
G[i][j] = INF;
if (i>0&&j>0) {
v = D[i-depot][j-depot];
if (v>0) G[i][j] = v;
}
if (i==depot&&j==depot)
G[i][j] = 0;
}
}
}
/*
template<typename EMAP,typename DMatrix>
int Get_graph(EMAP& ES,DMatrix& D,DMatrix& W){
int tail,head;
for(int i=0;i<=LES;i++) {
for(int j=0;j<=LES;j++) {
D[i][j] = INF;
}
}
for(int i=0;i<=LES;i++) {
tail = GetTail(i,ES);
head = GetHead(i,ES);
D[tail][head] = GetCost(i,ES);
if (D[tail][head] ==0)
D[tail][head] = INF;
W[tail][head] = GetDemand(i,ES);
}
}
template<typename EMAP,typename DMatrix>
int Get_graph(EMAP& ES,DMatrix& D,DMatrix& W,int& n_vertex){
int tail,head;
n_vertex = 0;
for(int i=0;i<=2*LES;i++) {
for(int j=0;j<=LES;j++) {
D[i][j] = INF;
}
}
for(int i=0;i<=2*LES;i++) {
tail = GetTail(i,ES);
head = GetHead(i,ES);
cout<<tail<<"&"<<head<<endl;
if (tail>n_vertex) n_vertex = tail;
if (head>n_vertex) n_vertex = head;
D[tail][head] = GetCost(i,ES);
if (D[tail][head] ==0)
D[tail][head] = INF;
W[tail][head] = GetDemand(i,ES);
}
}
*/
#endif
|
rjfpeters-iefbr14/mod1-energy-guard-system
|
mod1-cav-service/src/main/java/tld/yggdrasill/services/cav/api/GuardEventListener.java
|
<gh_stars>1-10
package tld.yggdrasill.services.cav.api;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;
import tld.yggdrasill.services.cgs.model.Contingency;
import tld.yggdrasill.services.cgs.model.GridServiceEvent;
import tld.yggdrasill.services.cav.core.service.ContingencyAgreementVerifier;
import java.util.List;
import static net.logstash.logback.argument.StructuredArguments.kv;
@Slf4j
@Service
public class GuardEventListener {
private final ContingencyAgreementVerifier contingencyAgreementVerifier;
public GuardEventListener(ContingencyAgreementVerifier contingencyAgreementVerifier) {
this.contingencyAgreementVerifier = contingencyAgreementVerifier;
}
@KafkaListener(topics = "${app.kafka.consumer.topic}")
public void processMessage(String message,
@Header(KafkaHeaders.RECEIVED_PARTITION_ID) List<Integer> partitions,
@Header(KafkaHeaders.RECEIVED_TOPIC) List<String> topics,
@Header(KafkaHeaders.OFFSET) List<Long> offsets) {
log.info(
String.format("Received: %s-%d[%d] \"%s\"\n", topics.get(0), partitions.get(0), offsets.get(0), message)
);
//create ObjectMapper instance
try {
ObjectMapper objectMapper = new ObjectMapper();
GridServiceEvent event = objectMapper.readValue(message, GridServiceEvent.class);
log.info("Message: {}, {}",
kv("messageId",event.getMessageId()),
kv("caseId",event.getPayload().getmRID()));
Contingency contingency = event.getPayload().getContingency();
log.info("Contingency: {}, {}", kv("contingencyId",
contingency.getmRID()), kv("contingencyName", contingency.getName()));
if ("contingency-verifier".equals(event.getPayload().getState())) {
contingencyAgreementVerifier.processFulfillment(event);
}
} catch (JsonProcessingException e) {
log.error(e.getMessage());
}
}
}
|
sowmyavasudeva/SmartBookmark
|
test/unittests/skills/scheduled_skills.py
|
<reponame>sowmyavasudeva/SmartBookmark<gh_stars>1-10
# Copyright 2017 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import unittest
from datetime import datetime, timedelta
from mycroft.skills.scheduled_skills import ScheduledSkill
class ScheduledSkillTest(unittest.TestCase):
skill = ScheduledSkill(name='ScheduledSkillTest')
def test_formatted_time_today_hours(self):
date = datetime.now() + timedelta(hours=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
"1 hours and 59 minutes from now")
def test_formatted_time_today_min(self):
date = datetime.now() + timedelta(minutes=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
"1 minutes and 59 seconds from now")
def test_formatted_time_days(self):
self.skill.config_core = {}
self.skill.config_core['time_format'] = 'full'
self.skill.config_core['date_format'] = 'DMY'
self.skill.init_format()
date = datetime.now() + timedelta(days=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
date.strftime("%d %B, %Y at %H:%M"))
self.skill.config_core['date_format'] = 'MDY'
self.skill.init_format()
date = datetime.now() + timedelta(days=2)
self.assertEquals(self.skill.
get_formatted_time(float(date.strftime('%s'))),
date.strftime("%B %d, %Y at %H:%M"))
|
SuperMap/iClient-for-JavaScript
|
tests/REST/SpatialAnalyst/ClipParameterTest.js
|
<gh_stars>10-100
module("ClipParameter");
test("TestClipParameter_constructorDefault", function () {
expect(6);
var params = new SuperMap.REST.ClipParameter();
ok(params !== null, "params not null");
equal(params.clipDatasetName, null, "params.clipDatasetName");
equal(params.clipDatasourceName, null, "params.clipDatasourceName");
equal(params.clipRegion, null, "params.clipRegion");
equal(params.isClipInRegion, false, "params.isClipInRegion");
equal(params.isExactClip, null, "params.isExactClip");
});
test("TestClipParameter_constructor_destroy", function () {
expect(10);
//配置剪裁参数
var params = new SuperMap.REST.ClipParameter({
clipDatasetName: "Park@Changchun",
clipDatasourceName: "spatialanalyst",
clipRegion: null,
isClipInRegion: false,
isExactClip: false
});
equal(params.clipDatasetName, "Park@Changchun", "function:constructor");
equal(params.clipDatasourceName, "spatialanalyst", "function:constructor");
equal(params.clipRegion, null, "function:constructor");
equal(params.isClipInRegion, false, "function:constructor");
equal(params.isExactClip, false, "function:constructor");
params.destroy();
equal(params.clipDatasetName, null, "function:destroy");
equal(params.clipDatasourceName, null, "function:destroy");
equal(params.clipRegion, null, "function:destroy");
equal(params.isClipInRegion, null, "function:destroy");
equal(params.isExactClip, null, "function:destroy");
});
test("TestClipParameter_toJSON", function () {
expect(2);
//isClipInRegion为false
var params = new SuperMap.REST.ClipParameter({
clipDatasetName: "Park@Changchun",
clipDatasourceName: "spatialanalyst",
clipRegion: null,
isClipInRegion: false,
isExactClip: false
});
equal(params.toJSON(), null, "function:toJSON_isClipInRegionFalse");
//isClipInRegion为true
var params1 = new SuperMap.REST.ClipParameter({
clipDatasetName: "Park@Changchun",
clipDatasourceName: "spatialanalyst",
clipRegion: null,
isClipInRegion: true,
isExactClip: false
});
var strClipParameter = params1.toJSON();
var expectStrClipParameter = "";
expectStrClipParameter += "'isClipInRegion':" + SuperMap.Util.toJSON(params1.isClipInRegion)
+ "," + "'clipDatasetName':" + SuperMap.Util.toJSON(params1.clipDatasetName)
+ "," + "'clipDatasourceName':" + SuperMap.Util.toJSON(params1.clipDatasourceName)
+ "," + "'isExactClip':" + SuperMap.Util.toJSON(params1.isExactClip);
equal(strClipParameter, "{" + expectStrClipParameter + "}", "function:toJSON") + "}";
});
|
larkov/MailTrackerBlocker
|
MailHeaders/Catalina/MailUI/TemporaryAttachmentOpener.h
|
//
// Generated by class-dump 3.5b1 (64 bit) (Debug version compiled Dec 3 2019 19:59:57).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import "GenericAttachmentFetcher.h"
@class NSString;
@interface TemporaryAttachmentOpener : GenericAttachmentFetcher
{
NSString *_applicationPath; // 8 = 0x8
}
@property(readonly, copy, nonatomic) NSString *applicationPath; // @synthesize applicationPath=_applicationPath;
// - (void).cxx_destruct; // IMP=0x00000001002a3d08
- (double)temporaryFolderTimeout; // IMP=0x00000001002a3ce7
- (void)didSaveAttachment:(id)arg1 toPath:(id)arg2; // IMP=0x00000001002a3b47
- (void)_openAttachmentAtPath:(id)arg1; // IMP=0x00000001002a3aa7
- (void)downloadedAllAttachments; // IMP=0x00000001002a3968
- (id)initWithAttachmentViewControllers:(id)arg1; // IMP=0x00000001002a3899
- (id)initWithAttachmentViewControllers:(id)arg1 applicationPath:(id)arg2; // IMP=0x00000001002a37e8
@end
|
T0mmykn1fe/chaosk
|
src/components/RadioGroup.js
|
<reponame>T0mmykn1fe/chaosk<gh_stars>0
import cx from 'classnames';
import PropTypes from 'prop-types';
import React, { createContext } from 'react';
import FormLabel from './FormLabel';
import FormFooter from './FormFooter';
import Inline from './Inline';
import List from './List';
import ListItem from './ListItem';
import { config } from '../helpers/config';
export const RadioGroupContext = createContext();
export const RadioGroupProvider = RadioGroupContext.Provider;
const RadioGroup = ({
children,
className,
explanationMessage,
inline,
label,
name,
onChange,
selectedValue,
validationMessage,
required,
...opts
}) => {
const renderChildren = () =>
React.Children.map(children, child => {
const onChangeFunc = () => {
onChange(name, child.props.value);
};
return (
<RadioGroupProvider
value={{ selectedValue, name, onChange: onChangeFunc }}
>
{inline ? child : <ListItem>{child}</ListItem>}
</RadioGroupProvider>
);
});
const renderItems = () => {
if (inline) {
return <Inline className="form-inlineCombo">{renderChildren()}</Inline>;
}
return <List type={['space']}>{renderChildren()}</List>;
};
const classes = cx('form-group', className, {
[config.classes.notValid]: validationMessage,
[config.classes.required]: required,
});
return (
<div className={classes} {...opts}>
<FormLabel required={required} id="">
{label}
</FormLabel>
{renderItems()}
<FormFooter
explanationMessage={explanationMessage}
validationMessage={validationMessage}
/>
</div>
);
};
RadioGroup.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
explanationMessage: PropTypes.string,
inline: PropTypes.bool,
label: PropTypes.string,
name: PropTypes.string.isRequired,
onChange: PropTypes.func,
selectedValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
validationMessage: PropTypes.string,
required: PropTypes.bool,
};
export default RadioGroup;
|
valeriocos/jbrex
|
org.eclipse.m2m.atl.engine.emfvm/src/org/eclipse/m2m/atl/engine/emfvm/lib/ASMModule.java
|
/*******************************************************************************
* Copyright (c) 2007 INRIA.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* <NAME> - initial API and implementation
*******************************************************************************/
package org.eclipse.m2m.atl.engine.emfvm.lib;
import java.util.HashMap;
import java.util.Map;
/**
* The ASM Module, which symbolizes an ATL transformation.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class ASMModule implements HasFields {
private Map<Object, Object> fields = new HashMap<Object, Object>();
private String moduleName;
/**
* Creates a new ASMModule with the given name.
*
* @param name
* the module name
*/
public ASMModule(String name) {
this.moduleName = name;
}
/**
* Creates a new ASMModule.
*/
public ASMModule() {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.emfvm.lib.HasFields#set(org.eclipse.m2m.atl.engine.emfvm.lib.AbstractStackFrame,
* java.lang.Object, java.lang.Object)
*/
public void set(AbstractStackFrame frame, Object name, Object value) {
fields.put(name, value);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.emfvm.lib.HasFields#get(org.eclipse.m2m.atl.engine.emfvm.lib.AbstractStackFrame,
* java.lang.Object)
*/
public Object get(AbstractStackFrame frame, Object name) {
return fields.get(name);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.emfvm.lib.HasFields#unset(org.eclipse.m2m.atl.engine.emfvm.lib.AbstractStackFrame,
* java.lang.Object)
*/
public void unset(AbstractStackFrame frame, Object name) {
fields.remove(name);
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
if (moduleName != null) {
return moduleName + " : ASMModule"; //$NON-NLS-1$
}
return "thisModule"; //$NON-NLS-1$
}
/**
* Returns the map of the fields.
*
* @return the map of the fields
*/
public Map<Object, Object> asMap() {
return fields;
}
}
|
patvong/AvaTax-SOAP-Java-SDK
|
avatax4j-accountsvc/src/com/avalara/avatax/services/account/Company.java
|
<reponame>patvong/AvaTax-SOAP-Java-SDK<filename>avatax4j-accountsvc/src/com/avalara/avatax/services/account/Company.java
/**
* Company.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.2.1 Jun 14, 2005 (09:15:57 EDT) WSDL2Java emitter.
*/
package com.avalara.avatax.services.account;
public class Company implements java.io.Serializable {
private int accountId;
private int companyId;
private java.lang.String companyCode;
private java.lang.String companyName;
private java.util.Calendar createdDate;
private int createdUserId;
private int entityNo;
private boolean hasProfile;
private boolean isActive;
private boolean isDefault;
private boolean isReportingEntity;
private java.util.Calendar modifiedDate;
private int modifiedUserId;
private int parentId;
private java.util.Date SSTEffDate;
private java.lang.String SSTPID;
private java.lang.String TIN;
private java.lang.String regalBankId;
private java.lang.String defaultCountry;
private java.lang.String baseCurrencyCode;
private com.avalara.avatax.services.account.RoundingLevelId roundingLevelId;
private boolean cashBasisAccountingEnabled;
private com.avalara.avatax.services.account.ArrayOfCompany children;
private com.avalara.avatax.services.account.ArrayOfCompanyContact contacts;
private com.avalara.avatax.services.account.ArrayOfItem items;
private com.avalara.avatax.services.account.ArrayOfNexus nexuses;
private com.avalara.avatax.services.account.Company parent;
private com.avalara.avatax.services.account.ArrayOfTaxCode taxCodes;
private com.avalara.avatax.services.account.ArrayOfTaxRule taxRules;
private boolean warningsEnabled;
private boolean isTest;
private com.avalara.avatax.services.account.TaxDependencyLevelId taxDependencyLevelId;
private boolean inProgress;
private int defaultLocationId;
public Company() {
}
public Company(
int accountId,
int companyId,
java.lang.String companyCode,
java.lang.String companyName,
java.util.Calendar createdDate,
int createdUserId,
int entityNo,
boolean hasProfile,
boolean isActive,
boolean isDefault,
boolean isReportingEntity,
java.util.Calendar modifiedDate,
int modifiedUserId,
int parentId,
java.util.Date SSTEffDate,
java.lang.String SSTPID,
java.lang.String TIN,
java.lang.String regalBankId,
java.lang.String defaultCountry,
java.lang.String baseCurrencyCode,
com.avalara.avatax.services.account.RoundingLevelId roundingLevelId,
boolean cashBasisAccountingEnabled,
com.avalara.avatax.services.account.ArrayOfCompany children,
com.avalara.avatax.services.account.ArrayOfCompanyContact contacts,
com.avalara.avatax.services.account.ArrayOfItem items,
com.avalara.avatax.services.account.ArrayOfNexus nexuses,
com.avalara.avatax.services.account.Company parent,
com.avalara.avatax.services.account.ArrayOfTaxCode taxCodes,
com.avalara.avatax.services.account.ArrayOfTaxRule taxRules,
boolean warningsEnabled,
boolean isTest,
com.avalara.avatax.services.account.TaxDependencyLevelId taxDependencyLevelId,
boolean inProgress,
int defaultLocationId) {
this.accountId = accountId;
this.companyId = companyId;
this.companyCode = companyCode;
this.companyName = companyName;
this.createdDate = createdDate;
this.createdUserId = createdUserId;
this.entityNo = entityNo;
this.hasProfile = hasProfile;
this.isActive = isActive;
this.isDefault = isDefault;
this.isReportingEntity = isReportingEntity;
this.modifiedDate = modifiedDate;
this.modifiedUserId = modifiedUserId;
this.parentId = parentId;
this.SSTEffDate = SSTEffDate;
this.SSTPID = SSTPID;
this.TIN = TIN;
this.regalBankId = regalBankId;
this.defaultCountry = defaultCountry;
this.baseCurrencyCode = baseCurrencyCode;
this.roundingLevelId = roundingLevelId;
this.cashBasisAccountingEnabled = cashBasisAccountingEnabled;
this.children = children;
this.contacts = contacts;
this.items = items;
this.nexuses = nexuses;
this.parent = parent;
this.taxCodes = taxCodes;
this.taxRules = taxRules;
this.warningsEnabled = warningsEnabled;
this.isTest = isTest;
this.taxDependencyLevelId = taxDependencyLevelId;
this.inProgress = inProgress;
this.defaultLocationId = defaultLocationId;
}
/**
* Gets the accountId value for this Company.
*
* @return accountId
*/
public int getAccountId() {
return accountId;
}
/**
* Sets the accountId value for this Company.
*
* @param accountId
*/
public void setAccountId(int accountId) {
this.accountId = accountId;
}
/**
* Gets the companyId value for this Company.
*
* @return companyId
*/
public int getCompanyId() {
return companyId;
}
/**
* Sets the companyId value for this Company.
*
* @param companyId
*/
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
/**
* Gets the companyCode value for this Company.
*
* @return companyCode
*/
public java.lang.String getCompanyCode() {
return companyCode;
}
/**
* Sets the companyCode value for this Company.
*
* @param companyCode
*/
public void setCompanyCode(java.lang.String companyCode) {
this.companyCode = companyCode;
}
/**
* Gets the companyName value for this Company.
*
* @return companyName
*/
public java.lang.String getCompanyName() {
return companyName;
}
/**
* Sets the companyName value for this Company.
*
* @param companyName
*/
public void setCompanyName(java.lang.String companyName) {
this.companyName = companyName;
}
/**
* Gets the createdDate value for this Company.
*
* @return createdDate
*/
public java.util.Calendar getCreatedDate() {
return createdDate;
}
/**
* Sets the createdDate value for this Company.
*
* @param createdDate
*/
public void setCreatedDate(java.util.Calendar createdDate) {
this.createdDate = createdDate;
}
/**
* Gets the createdUserId value for this Company.
*
* @return createdUserId
*/
public int getCreatedUserId() {
return createdUserId;
}
/**
* Sets the createdUserId value for this Company.
*
* @param createdUserId
*/
public void setCreatedUserId(int createdUserId) {
this.createdUserId = createdUserId;
}
/**
* Gets the entityNo value for this Company.
*
* @return entityNo
*/
public int getEntityNo() {
return entityNo;
}
/**
* Sets the entityNo value for this Company.
*
* @param entityNo
*/
public void setEntityNo(int entityNo) {
this.entityNo = entityNo;
}
/**
* Gets the hasProfile value for this Company.
*
* @return hasProfile
*/
public boolean isHasProfile() {
return hasProfile;
}
/**
* Sets the hasProfile value for this Company.
*
* @param hasProfile
*/
public void setHasProfile(boolean hasProfile) {
this.hasProfile = hasProfile;
}
/**
* Gets the isActive value for this Company.
*
* @return isActive
*/
public boolean isIsActive() {
return isActive;
}
/**
* Sets the isActive value for this Company.
*
* @param isActive
*/
public void setIsActive(boolean isActive) {
this.isActive = isActive;
}
/**
* Gets the isDefault value for this Company.
*
* @return isDefault
*/
public boolean isIsDefault() {
return isDefault;
}
/**
* Sets the isDefault value for this Company.
*
* @param isDefault
*/
public void setIsDefault(boolean isDefault) {
this.isDefault = isDefault;
}
/**
* Gets the isReportingEntity value for this Company.
*
* @return isReportingEntity
*/
public boolean isIsReportingEntity() {
return isReportingEntity;
}
/**
* Sets the isReportingEntity value for this Company.
*
* @param isReportingEntity
*/
public void setIsReportingEntity(boolean isReportingEntity) {
this.isReportingEntity = isReportingEntity;
}
/**
* Gets the modifiedDate value for this Company.
*
* @return modifiedDate
*/
public java.util.Calendar getModifiedDate() {
return modifiedDate;
}
/**
* Sets the modifiedDate value for this Company.
*
* @param modifiedDate
*/
public void setModifiedDate(java.util.Calendar modifiedDate) {
this.modifiedDate = modifiedDate;
}
/**
* Gets the modifiedUserId value for this Company.
*
* @return modifiedUserId
*/
public int getModifiedUserId() {
return modifiedUserId;
}
/**
* Sets the modifiedUserId value for this Company.
*
* @param modifiedUserId
*/
public void setModifiedUserId(int modifiedUserId) {
this.modifiedUserId = modifiedUserId;
}
/**
* Gets the parentId value for this Company.
*
* @return parentId
*/
public int getParentId() {
return parentId;
}
/**
* Sets the parentId value for this Company.
*
* @param parentId
*/
public void setParentId(int parentId) {
this.parentId = parentId;
}
/**
* Gets the SSTEffDate value for this Company.
*
* @return SSTEffDate
*/
public java.util.Date getSSTEffDate() {
return SSTEffDate;
}
/**
* Sets the SSTEffDate value for this Company.
*
* @param SSTEffDate
*/
public void setSSTEffDate(java.util.Date SSTEffDate) {
this.SSTEffDate = SSTEffDate;
}
/**
* Gets the SSTPID value for this Company.
*
* @return SSTPID
*/
public java.lang.String getSSTPID() {
return SSTPID;
}
/**
* Sets the SSTPID value for this Company.
*
* @param SSTPID
*/
public void setSSTPID(java.lang.String SSTPID) {
this.SSTPID = SSTPID;
}
/**
* Gets the TIN value for this Company.
*
* @return TIN
*/
public java.lang.String getTIN() {
return TIN;
}
/**
* Sets the TIN value for this Company.
*
* @param TIN
*/
public void setTIN(java.lang.String TIN) {
this.TIN = TIN;
}
/**
* Gets the regalBankId value for this Company.
*
* @return regalBankId
*/
public java.lang.String getRegalBankId() {
return regalBankId;
}
/**
* Sets the regalBankId value for this Company.
*
* @param regalBankId
*/
public void setRegalBankId(java.lang.String regalBankId) {
this.regalBankId = regalBankId;
}
/**
* Gets the defaultCountry value for this Company.
*
* @return defaultCountry
*/
public java.lang.String getDefaultCountry() {
return defaultCountry;
}
/**
* Sets the defaultCountry value for this Company.
*
* @param defaultCountry
*/
public void setDefaultCountry(java.lang.String defaultCountry) {
this.defaultCountry = defaultCountry;
}
/**
* Gets the baseCurrencyCode value for this Company.
*
* @return baseCurrencyCode
*/
public java.lang.String getBaseCurrencyCode() {
return baseCurrencyCode;
}
/**
* Sets the baseCurrencyCode value for this Company.
*
* @param baseCurrencyCode
*/
public void setBaseCurrencyCode(java.lang.String baseCurrencyCode) {
this.baseCurrencyCode = baseCurrencyCode;
}
/**
* Gets the roundingLevelId value for this Company.
*
* @return roundingLevelId
*/
public com.avalara.avatax.services.account.RoundingLevelId getRoundingLevelId() {
return roundingLevelId;
}
/**
* Sets the roundingLevelId value for this Company.
*
* @param roundingLevelId
*/
public void setRoundingLevelId(com.avalara.avatax.services.account.RoundingLevelId roundingLevelId) {
this.roundingLevelId = roundingLevelId;
}
/**
* Gets the cashBasisAccountingEnabled value for this Company.
*
* @return cashBasisAccountingEnabled
*/
public boolean isCashBasisAccountingEnabled() {
return cashBasisAccountingEnabled;
}
/**
* Sets the cashBasisAccountingEnabled value for this Company.
*
* @param cashBasisAccountingEnabled
*/
public void setCashBasisAccountingEnabled(boolean cashBasisAccountingEnabled) {
this.cashBasisAccountingEnabled = cashBasisAccountingEnabled;
}
/**
* Gets the children value for this Company.
*
* @return children
*/
public com.avalara.avatax.services.account.ArrayOfCompany getChildren() {
return children;
}
/**
* Sets the children value for this Company.
*
* @param children
*/
public void setChildren(com.avalara.avatax.services.account.ArrayOfCompany children) {
this.children = children;
}
/**
* Gets the contacts value for this Company.
*
* @return contacts
*/
public com.avalara.avatax.services.account.ArrayOfCompanyContact getContacts() {
return contacts;
}
/**
* Sets the contacts value for this Company.
*
* @param contacts
*/
public void setContacts(com.avalara.avatax.services.account.ArrayOfCompanyContact contacts) {
this.contacts = contacts;
}
/**
* Gets the items value for this Company.
*
* @return items
*/
public com.avalara.avatax.services.account.ArrayOfItem getItems() {
return items;
}
/**
* Sets the items value for this Company.
*
* @param items
*/
public void setItems(com.avalara.avatax.services.account.ArrayOfItem items) {
this.items = items;
}
/**
* Gets the nexuses value for this Company.
*
* @return nexuses
*/
public com.avalara.avatax.services.account.ArrayOfNexus getNexuses() {
return nexuses;
}
/**
* Sets the nexuses value for this Company.
*
* @param nexuses
*/
public void setNexuses(com.avalara.avatax.services.account.ArrayOfNexus nexuses) {
this.nexuses = nexuses;
}
/**
* Gets the parent value for this Company.
*
* @return parent
*/
public com.avalara.avatax.services.account.Company getParent() {
return parent;
}
/**
* Sets the parent value for this Company.
*
* @param parent
*/
public void setParent(com.avalara.avatax.services.account.Company parent) {
this.parent = parent;
}
/**
* Gets the taxCodes value for this Company.
*
* @return taxCodes
*/
public com.avalara.avatax.services.account.ArrayOfTaxCode getTaxCodes() {
return taxCodes;
}
/**
* Sets the taxCodes value for this Company.
*
* @param taxCodes
*/
public void setTaxCodes(com.avalara.avatax.services.account.ArrayOfTaxCode taxCodes) {
this.taxCodes = taxCodes;
}
/**
* Gets the taxRules value for this Company.
*
* @return taxRules
*/
public com.avalara.avatax.services.account.ArrayOfTaxRule getTaxRules() {
return taxRules;
}
/**
* Sets the taxRules value for this Company.
*
* @param taxRules
*/
public void setTaxRules(com.avalara.avatax.services.account.ArrayOfTaxRule taxRules) {
this.taxRules = taxRules;
}
/**
* Gets the warningsEnabled value for this Company.
*
* @return warningsEnabled
*/
public boolean isWarningsEnabled() {
return warningsEnabled;
}
/**
* Sets the warningsEnabled value for this Company.
*
* @param warningsEnabled
*/
public void setWarningsEnabled(boolean warningsEnabled) {
this.warningsEnabled = warningsEnabled;
}
/**
* Gets the isTest value for this Company.
*
* @return isTest
*/
public boolean isIsTest() {
return isTest;
}
/**
* Sets the isTest value for this Company.
*
* @param isTest
*/
public void setIsTest(boolean isTest) {
this.isTest = isTest;
}
/**
* Gets the taxDependencyLevelId value for this Company.
*
* @return taxDependencyLevelId
*/
public com.avalara.avatax.services.account.TaxDependencyLevelId getTaxDependencyLevelId() {
return taxDependencyLevelId;
}
/**
* Sets the taxDependencyLevelId value for this Company.
*
* @param taxDependencyLevelId
*/
public void setTaxDependencyLevelId(com.avalara.avatax.services.account.TaxDependencyLevelId taxDependencyLevelId) {
this.taxDependencyLevelId = taxDependencyLevelId;
}
/**
* Gets the inProgress value for this Company.
*
* @return inProgress
*/
public boolean isInProgress() {
return inProgress;
}
/**
* Sets the inProgress value for this Company.
*
* @param inProgress
*/
public void setInProgress(boolean inProgress) {
this.inProgress = inProgress;
}
/**
* Gets the defaultLocationId value for this Company.
*
* @return defaultLocationId
*/
public int getDefaultLocationId() {
return defaultLocationId;
}
/**
* Sets the defaultLocationId value for this Company.
*
* @param defaultLocationId
*/
public void setDefaultLocationId(int defaultLocationId) {
this.defaultLocationId = defaultLocationId;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof Company)) return false;
Company other = (Company) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
this.accountId == other.getAccountId() &&
this.companyId == other.getCompanyId() &&
((this.companyCode==null && other.getCompanyCode()==null) ||
(this.companyCode!=null &&
this.companyCode.equals(other.getCompanyCode()))) &&
((this.companyName==null && other.getCompanyName()==null) ||
(this.companyName!=null &&
this.companyName.equals(other.getCompanyName()))) &&
((this.createdDate==null && other.getCreatedDate()==null) ||
(this.createdDate!=null &&
this.createdDate.equals(other.getCreatedDate()))) &&
this.createdUserId == other.getCreatedUserId() &&
this.entityNo == other.getEntityNo() &&
this.hasProfile == other.isHasProfile() &&
this.isActive == other.isIsActive() &&
this.isDefault == other.isIsDefault() &&
this.isReportingEntity == other.isIsReportingEntity() &&
((this.modifiedDate==null && other.getModifiedDate()==null) ||
(this.modifiedDate!=null &&
this.modifiedDate.equals(other.getModifiedDate()))) &&
this.modifiedUserId == other.getModifiedUserId() &&
this.parentId == other.getParentId() &&
((this.SSTEffDate==null && other.getSSTEffDate()==null) ||
(this.SSTEffDate!=null &&
this.SSTEffDate.equals(other.getSSTEffDate()))) &&
((this.SSTPID==null && other.getSSTPID()==null) ||
(this.SSTPID!=null &&
this.SSTPID.equals(other.getSSTPID()))) &&
((this.TIN==null && other.getTIN()==null) ||
(this.TIN!=null &&
this.TIN.equals(other.getTIN()))) &&
((this.regalBankId==null && other.getRegalBankId()==null) ||
(this.regalBankId!=null &&
this.regalBankId.equals(other.getRegalBankId()))) &&
((this.defaultCountry==null && other.getDefaultCountry()==null) ||
(this.defaultCountry!=null &&
this.defaultCountry.equals(other.getDefaultCountry()))) &&
((this.baseCurrencyCode==null && other.getBaseCurrencyCode()==null) ||
(this.baseCurrencyCode!=null &&
this.baseCurrencyCode.equals(other.getBaseCurrencyCode()))) &&
((this.roundingLevelId==null && other.getRoundingLevelId()==null) ||
(this.roundingLevelId!=null &&
this.roundingLevelId.equals(other.getRoundingLevelId()))) &&
this.cashBasisAccountingEnabled == other.isCashBasisAccountingEnabled() &&
((this.children==null && other.getChildren()==null) ||
(this.children!=null &&
this.children.equals(other.getChildren()))) &&
((this.contacts==null && other.getContacts()==null) ||
(this.contacts!=null &&
this.contacts.equals(other.getContacts()))) &&
((this.items==null && other.getItems()==null) ||
(this.items!=null &&
this.items.equals(other.getItems()))) &&
((this.nexuses==null && other.getNexuses()==null) ||
(this.nexuses!=null &&
this.nexuses.equals(other.getNexuses()))) &&
((this.parent==null && other.getParent()==null) ||
(this.parent!=null &&
this.parent.equals(other.getParent()))) &&
((this.taxCodes==null && other.getTaxCodes()==null) ||
(this.taxCodes!=null &&
this.taxCodes.equals(other.getTaxCodes()))) &&
((this.taxRules==null && other.getTaxRules()==null) ||
(this.taxRules!=null &&
this.taxRules.equals(other.getTaxRules()))) &&
this.warningsEnabled == other.isWarningsEnabled() &&
this.isTest == other.isIsTest()&&
((this.taxDependencyLevelId==null && other.getTaxDependencyLevelId()==null) ||
(this.taxDependencyLevelId!=null &&
this.taxDependencyLevelId.equals(other.getTaxDependencyLevelId()))) &&
this.inProgress == other.isInProgress()&&
this.defaultLocationId == other.getDefaultLocationId();
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
_hashCode += getAccountId();
_hashCode += getCompanyId();
if (getCompanyCode() != null) {
_hashCode += getCompanyCode().hashCode();
}
if (getCompanyName() != null) {
_hashCode += getCompanyName().hashCode();
}
if (getCreatedDate() != null) {
_hashCode += getCreatedDate().hashCode();
}
_hashCode += getCreatedUserId();
_hashCode += getEntityNo();
_hashCode += (isHasProfile() ? Boolean.TRUE : Boolean.FALSE).hashCode();
_hashCode += (isIsActive() ? Boolean.TRUE : Boolean.FALSE).hashCode();
_hashCode += (isIsDefault() ? Boolean.TRUE : Boolean.FALSE).hashCode();
_hashCode += (isIsReportingEntity() ? Boolean.TRUE : Boolean.FALSE).hashCode();
if (getModifiedDate() != null) {
_hashCode += getModifiedDate().hashCode();
}
_hashCode += getModifiedUserId();
_hashCode += getParentId();
if (getSSTEffDate() != null) {
_hashCode += getSSTEffDate().hashCode();
}
if (getSSTPID() != null) {
_hashCode += getSSTPID().hashCode();
}
if (getTIN() != null) {
_hashCode += getTIN().hashCode();
}
if (getRegalBankId() != null) {
_hashCode += getRegalBankId().hashCode();
}
if (getDefaultCountry() != null) {
_hashCode += getDefaultCountry().hashCode();
}
if (getBaseCurrencyCode() != null) {
_hashCode += getBaseCurrencyCode().hashCode();
}
if (getRoundingLevelId() != null) {
_hashCode += getRoundingLevelId().hashCode();
}
_hashCode += (isCashBasisAccountingEnabled() ? Boolean.TRUE : Boolean.FALSE).hashCode();
if (getChildren() != null) {
_hashCode += getChildren().hashCode();
}
if (getContacts() != null) {
_hashCode += getContacts().hashCode();
}
if (getItems() != null) {
_hashCode += getItems().hashCode();
}
if (getNexuses() != null) {
_hashCode += getNexuses().hashCode();
}
if (getParent() != null) {
_hashCode += getParent().hashCode();
}
if (getTaxCodes() != null) {
_hashCode += getTaxCodes().hashCode();
}
if (getTaxRules() != null) {
_hashCode += getTaxRules().hashCode();
}
_hashCode += (isWarningsEnabled() ? Boolean.TRUE : Boolean.FALSE).hashCode();
_hashCode += (isIsTest() ? Boolean.TRUE : Boolean.FALSE).hashCode();
if (getTaxDependencyLevelId() != null) {
_hashCode += getTaxDependencyLevelId().hashCode();
}
_hashCode += (isInProgress() ? Boolean.TRUE : Boolean.FALSE).hashCode();
_hashCode += getDefaultLocationId();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(Company.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Company"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("accountId");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "AccountId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("companyId");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CompanyId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("companyCode");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CompanyCode"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("companyName");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CompanyName"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("createdDate");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CreatedDate"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("createdUserId");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CreatedUserId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("entityNo");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "EntityNo"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("hasProfile");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "HasProfile"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("isActive");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "IsActive"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("isDefault");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "IsDefault"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("isReportingEntity");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "IsReportingEntity"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("modifiedDate");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ModifiedDate"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("modifiedUserId");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ModifiedUserId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("parentId");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ParentId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("SSTEffDate");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "SSTEffDate"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "date"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("SSTPID");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "SSTPID"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("TIN");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "TIN"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("regalBankId");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "RegalBankId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("defaultCountry");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "DefaultCountry"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("baseCurrencyCode");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "BaseCurrencyCode"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("roundingLevelId");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "RoundingLevelId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "RoundingLevelId"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("cashBasisAccountingEnabled");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "CashBasisAccountingEnabled"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("children");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Children"));
elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ArrayOfCompany"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("contacts");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Contacts"));
elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ArrayOfCompanyContact"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("items");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Items"));
elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ArrayOfItem"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("nexuses");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Nexuses"));
elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ArrayOfNexus"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("parent");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Parent"));
elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "Company"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("taxCodes");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "TaxCodes"));
elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ArrayOfTaxCode"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("taxRules");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "TaxRules"));
elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "ArrayOfTaxRule"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("warningsEnabled");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "WarningsEnabled"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("isTest");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "IsTest"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("taxDependencyLevelId");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "TaxDependencyLevelId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "TaxDependencyLevelId"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("inProgress");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "InProgress"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("defaultLocationId");
elemField.setXmlName(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "DefaultLocationId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new com.avalara.avatax.services.base.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
DeepBlue14/rqt_ide
|
modules/ide_old/src/SearchWidget.h
|
<reponame>DeepBlue14/rqt_ide<filename>modules/ide_old/src/SearchWidget.h
/*
* File: SearchGui.h
* Module: Run
* Author: <NAME>
* Email: <EMAIL>
* File Description:
*
* Created on June 6, 2015, 3:38 PM
*/
#ifndef SEARCH_WIDGET_H
#define SEARCH_WIDGET_H
#include <QWidget>
#include <QLineEdit>
#include <QString>
#include <QVector>
#include <QPair>
#include <iostream>
#include "SearchType.h"
#include "WindowsConsoleText.h"
#include "UnixConsoleText.h"
#ifdef _WIN32
namespace cct = WindowsConsoleText;
#elif __APPLE
namespace cct = UnixConsoleText;
#elif __linux
namespace cct = UnixConsoleText;
#endif
using namespace std;
class SearchWidget : public QLineEdit
{
Q_OBJECT
private:
QString* searchInputStrPtr;
//QVector<QPair<int, int>*>* searchWordLocVec;
public:
/**
* Constructor.
*
* @param parent reference to parent type.
*/
SearchWidget(QWidget* parent = 0);
/**
* Searches the file connected to the tab currently being focused on
* for all instances of the given word.
*
* @param word the word to search for.
* @return a vector of locations where the word was found (line number,
* collumn number).
*/
QVector<QPair<int, int>*>* searchCurrFileFor(QString* word);
/**
* Searches all files open in tabs in the IDE for all instances of the
* given word.
*
* @param word the word to search for.
* @return
*/
QVector<SearchType*>* searchAllOpenFilesFor(QString* word);
/**
* Searches all source files in the entire project for all instances of
* the given word.
*
* @param word the word to search for.
* @return
*/
QVector<SearchType*>* searchAllSrcFilesInProjFor(QString* word);
/**
* Searches all files (NOT including object files or binary files) for
* all instances of the given word.
*
* @param word the word to search for.
* @return
*/
QVector<SearchType*>* searchAllFilesInProjFor(QString* word);
/**
*
*/
void setSearchInputStrPtr();
/**
*
*
* @return
*/
QString* getSearchInputStrPtr();
/**
*
*
* @return
*/
QString* toString();
/**
*
*/
~SearchWidget();
};
#endif /* SEARCH_WIDGET_H */
|
hajin-kim/2020-HighSchool-Python-Tutoring
|
ch6/6_1.py
|
a = 100
if a < 100:
print("조건이 참입니다")
print("실행을 종료합니다")
|
usegalaxy-no/usegalaxy
|
venv/lib/python3.6/site-packages/ansible_collections/sensu/sensu_go/plugins/modules/secret.py
|
<reponame>usegalaxy-no/usegalaxy
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2020, XLAB Steampunk <<EMAIL>>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["stableinterface"],
"supported_by": "certified",
}
DOCUMENTATION = """
module: secret
author:
- <NAME> (@aljazkosir)
- <NAME> (@mancabizjak)
- <NAME> (@mdolin)
- <NAME> (@tadeboro)
short_description: Manage Sensu Go secrets
description:
- Create, update or delete Sensu secret.
- For more information, refer to the Sensu documentation at
U(https://docs.sensu.io/sensu-go/latest/operations/manage-secrets/secrets/).
version_added: 1.6.0
extends_documentation_fragment:
- sensu.sensu_go.requirements
- sensu.sensu_go.auth
- sensu.sensu_go.name
- sensu.sensu_go.namespace
- sensu.sensu_go.state
seealso:
- module: sensu.sensu_go.secret_info
- module: sensu.sensu_go.secrets_provider_env
- module: sensu.sensu_go.secrets_provider_vault
- module: sensu.sensu_go.secrets_provider_info
options:
provider:
description:
- Name of the secrets provider that backs the secret value.
- Required if I(state) is C(present).
type: str
id:
description:
- Secret's id in the provider store.
- Required if I(state) is C(present).
type: str
"""
EXAMPLES = """
- name: Create an environment varibale-backed secret
sensu.sensu_go.secret:
name: env_secret
provider: env
id: MY_ENV_VARIABLE
- name: Create a HashiCorp Vault-backed secret
sensu.sensu_go.secret:
name: hashi_valut_secret
provider: vault
id: secret/store#name
- name: Delete a secret
sensu.sensu_go.secret:
name: my_secret
state: absent
"""
RETURN = """
object:
description: Object representing Sensu secret.
returned: success
type: dict
sample:
metadata:
name: sensu-ansible
namespace: default
id: 'secret/database#password'
provider: vault
"""
from ansible.module_utils.basic import AnsibleModule
from ..module_utils import arguments, errors, utils
API_GROUP = "enterprise"
API_VERSION = "secrets/v1"
def main():
required_if = [
("state", "present", ["provider", "id"])
]
module = AnsibleModule(
required_if=required_if,
supports_check_mode=True,
argument_spec=dict(
arguments.get_spec("auth", "name", "state", "namespace"),
provider=dict(type="str"),
id=dict(type="str"),
),
)
client = arguments.get_sensu_client(module.params["auth"])
path = utils.build_url_path(
API_GROUP, API_VERSION, module.params["namespace"], "secrets",
module.params["name"],
)
payload = dict(
type="Secret",
api_version=API_VERSION,
metadata=dict(
name=module.params["name"],
namespace=module.params["namespace"],
),
spec=arguments.get_spec_payload(module.params, "provider", "id"),
)
try:
changed, secret = utils.sync_v1(
module.params["state"], client, path, payload, module.check_mode,
)
module.exit_json(changed=changed, object=secret)
except errors.Error as e:
module.fail_json(msg=str(e))
if __name__ == "__main__":
main()
|
anbruzga/Set-Theory-Calc
|
src/Sets/Controler/Calculate.java
|
<reponame>anbruzga/Set-Theory-Calc
package Sets.Controler;
import Sets.Model.*;
import Sets.View.PopUp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Queue;
import static Sets.Model.Symbols.*;
public class Calculate {
private static boolean syntaxCheckPassed = true;
public Calculate() {
}
private static boolean isSyntaxOk(String str) throws IncorrectInputSyntaxException {
boolean balanced = SyntaxAnalyser.checkSyntaxSanity(str);
if (!balanced) {
syntaxCheckPassed = false;
}
if (!syntaxCheckPassed) {
syntaxCheckPassed = true;
throw new IncorrectInputSyntaxException("Please check your syntax", "Calculate.evaluate");
}
return true;
}
private static ArrayList<MixedSet> stringToSet(ArrayList<Pair<String, Boolean>> pairListOfStringAndNotationBool)
throws IncorrectInputSyntaxException {
ArrayList<MixedSet> sets = new ArrayList<>();
for (Pair e : pairListOfStringAndNotationBool) {
if ((boolean) e.getRight() == true) {
//if(!e.getLeft().toString().contains("{")){
// MixedSet rangeSet = SyntaxAnalyser.rangeToSet((String) e.getLeft());
// sets.add(rangeSet);
//}
//else{
sets.add(SyntaxAnalyser.rosterToSet((String) e.getLeft()));
//}
} else {
SetComprehension<Double> setComprehension = new SetComprehension<>();
MixedSet set = setComprehension.stringToSet((String) e.getLeft());
sets.add(set);
}
// it.next();
//it.remove(); // avoids a ConcurrentModificationException
}
return sets;
}
public static MixedSet evaluate(String expr) throws IncorrectInputSyntaxException {
resetStaticVars();
MixedSet answer = null;
//1. Check the Syntax
isSyntaxOk(expr);
//2. Get Operator queue
Queue operatorQueue = SyntaxAnalyser.getOperatorQueue(expr);
//3. crop ( and )
String exprNoParenthesis = strRemoveParenthesis(expr);
//4. Distribute notation -> HashMap<setStr, isRosterNotation>
ArrayList<Pair<String, Boolean>> setsStr = SyntaxAnalyser.getListOfSetNotationTypes(exprNoParenthesis);
//5. Define sets in terms of MixedSet
ArrayList<MixedSet> sets = null;
try {
sets = stringToSet(setsStr);
} catch (IncorrectInputSyntaxException e) {
return null;
} finally {
resetStaticVars();
}
//5.1. Print sets that were constructed
System.out.println("Sets formed:");
for (int i = 0; i < sets.size(); i++) {
System.out.println(i + ". " + sets.get(i).toStringNoIntersectionWithUniversalSet());
}
//6. Calculate
try {
answer = evaluate(sets, operatorQueue);
} catch (IncorrectInputSyntaxException ex) {
throw ex;
} finally {
resetStaticVars();
}
return answer;
}
private static void resetStaticVars() {
syntaxCheckPassed = true;
}
public static ArrayList<MixedSet> strExprToListOfSets(String expr) throws IncorrectInputSyntaxException {
resetStaticVars();
//1. Check the Syntax
isSyntaxOk(expr);
//2. crop ( and )
String exprNoParenthesis = strRemoveParenthesis(expr);
//3. Distribute notation -> HashMap<set, isRosterNotation>
ArrayList<Pair<String, Boolean>> setsStr = SyntaxAnalyser.getListOfSetNotationTypes(exprNoParenthesis);
//4. Define sets in terms of MixedSet
ArrayList<MixedSet> sets = null;
try {
sets = stringToSet(setsStr);
} catch (IncorrectInputSyntaxException e) {
return null;
} finally {
resetStaticVars();
}
return sets;
}
private static String strRemoveParenthesis(String str) {
char[] exprCharArr = str.toCharArray();
StringBuilder strCropped = new StringBuilder();
boolean powerSetSymbol = false;
int balancedParentheses = 0;
for (int i = 0; i < exprCharArr.length; i++) {
if (exprCharArr[i] == '(') {
balancedParentheses++;
//do nothing
} else if (exprCharArr[i] == ')' && powerSetSymbol) {
balancedParentheses--;
if (balancedParentheses % 2 != 0) {
strCropped.append('^'); // add power symbol operator
powerSetSymbol = false;
}
} else if (exprCharArr[i] == ')') {
//do nothing
} else if (exprCharArr[i] == 'P' && exprCharArr[i + 1] == '(') {
powerSetSymbol = true;
} else if (exprCharArr[i] != ' ') {
strCropped.append(exprCharArr[i]);
}
}
return strCropped.toString();
//return str.replaceAll("\\(","")
// .replaceAll("\\)","");
}
/**
* Scratch algorithm
* 1. form priority queue
* 2. map each instruction with its priority
* 3. find max priority
* 4. while instruction set does have max priority values & someBool = true -> perform calculation:
* 4.0. while there is 2 members with operator in between
* {
* 4.1. calculate
* 4.2. change 2 members into 1 in instruction set
* }
* someBool = false
* 5. decrease priority by 1
* 6. go to step 4.
*/
private static MixedSet evaluate(ArrayList<MixedSet> sets, Queue operatorQueue) throws IncorrectInputSyntaxException {
// Tuple < Set, Priority,Operator>
ArrayList<Tuple<MixedSet, Integer, Character>> instructions = new ArrayList<>();
Iterator<Character> it = operatorQueue.iterator();
int setIndex = 0;
int priority = 0;
int maxPriority = 0;
boolean setRepeats = false;
boolean answerIsBoolean = false; // weak/proper subset operations
int counter = 0;
// Generates instructions on further calculation.
while (it.hasNext()) {
char current = it.next();
if (current == 's' && !setRepeats) {
instructions.add(Tuple.of(sets.get(setIndex), priority, current));
setIndex++;
setRepeats = true;
} else if (current == '(') {
priority++;
if (priority > maxPriority) {
maxPriority = priority;
}
} else if (current == ')') {
priority--;
} else if (current == '\u222A' || current == '\u2216' ||
current == '\u2229' || current == '\u2A2F') {
instructions.add(Tuple.of(null, priority, current));
setRepeats = false;
} else if (current == '^') {
int lastElemenet1 = instructions.size() - 1;
if (lastElemenet1 < 2) {
instructions.add(Tuple.of(null, priority, current));
}
// if last added set to instructions has the same priority, it means
// that powerset is not for (AuB...)' but A', thus it has highest priority.
else if (instructions.get(lastElemenet1 - 2).getMiddle() == priority) {
if(sets.get(setIndex - 1).getMultiplicity() > 10) {
System.out.println("Max cardinality of power set is 1024");
throw new IncorrectInputSyntaxException("Max cardinality of power set is 1024", "Calculate.Evaluate");
}
// Perform the powerset immediately and change last instruction
MixedSet setToChangePriority = sets.get(setIndex - 1).powerSet(sets.get(setIndex - 1));
instructions.remove(instructions.size() - 1);
instructions.add(Tuple.of(setToChangePriority, priority, current));
} else {
instructions.add(Tuple.of(null, priority, current));
}
} else if (current == '\'') {
int lastElemenet2 = instructions.size() - 1;
if (lastElemenet2 < 2) {
instructions.add(Tuple.of(null, priority, current));
}
// if last added set to instructions has the same priority, it means
// that complement is not for (AuB...)' but A', thus it has highest priority.
else if (instructions.get(lastElemenet2 - 2).getMiddle() == priority) {
// Perform the complement immediately and change last instruction
if (UniversalSet.getType() == 'Q') {
if (PopUp.confirmBox("When U belongs to Q, complement is uncountable set.\n" +
" Click YES to calculate with U belongs to Z instead", "Calculate Algorithm")) {
UniversalSet.getInstance().setType('Z');
} else {
return null;
}
}
MixedSet setToChangePriority = sets.get(setIndex - 1).complement();
instructions.remove(instructions.size() - 1);
instructions.add(Tuple.of(setToChangePriority, priority, current));
} else {
instructions.add(Tuple.of(null, priority, current));
}
} else if (current == '\u2286' || current == '\u2282') {
if (priority == 0) {
priority++;
}
instructions.add(Tuple.of(null, priority, current));
setRepeats = false;
}
}
MixedSet answer = null;
MixedSet booleanSet = new MixedSet(true);
// while all calculated
while (maxPriority >= 0 && instructions.size() > 1) {
// for each instruction identify max priority
boolean priorityFound = false;
boolean operationApplied = false;
boolean isLastOperationUnary = false;
for (int x = 1; x < instructions.size(); x++) {
if ((Integer) ((Tuple) instructions.get(x - 1)).getMiddle() == maxPriority) {
char operator = (Character) ((Tuple) instructions.get(x)).getRight();
answer = (MixedSet) ((Tuple) instructions.get(x - 1)).getLeft();
MixedSet setToCount;
if (operator != '\'' && operator != '^') {
setToCount = (MixedSet) ((Tuple) instructions.get(x + 1)).getLeft();
} else {
setToCount = answer;
}
if (setToCount == null || answer == null) {
throw new IncorrectInputSyntaxException("Incorrect Syntax", "Calculate Algorithm");
}
priorityFound = true;
//boolean operationApplied = false;
switch (operator) {
case '\'':
if (UniversalSet.getType() == 'Q') {
if (PopUp.confirmBox("When U belongs to Q, complement is uncountable set.\n" +
" Click YES to calculate with U belongs to Z", "Calculate Algorithm")) {
UniversalSet.getInstance().setType('Z');
} else {
return null;
}
}
isLastOperationUnary = true;
operationApplied = true;
answer = answer.complement();
break;
case '^':
if(answer.getMultiplicity() > 10) { // 1024 = 2^10
System.out.println("Max cardinality of power set is 1024");
throw new IncorrectInputSyntaxException("Max cardinality of power set is 1024", "Calculate.Evaluate");
}
isLastOperationUnary = true;
operationApplied = true;
answer = answer.powerSet(answer);
break;
case difference:
operationApplied = true;
answer = answer.difference(setToCount);
break;
case intersection:
operationApplied = true;
answer = answer.intersection(setToCount);
break;
case union:
if(answer.getMultiplicity() + setToCount.getMultiplicity() > 1024) {
System.out.println("Max cardinality for cartesian product is 1024");
throw new IncorrectInputSyntaxException("Max multiplicity for cartesian" +
"product is 1024", "Calculate.Evaluate");
}
operationApplied = true;
answer = answer.union(setToCount);
break;
case properSubset:
operationApplied = true;
booleanSet.add(answer.properSubset(setToCount));
answerIsBoolean = true;
return booleanSet;
case weakSubset:
operationApplied = true;
booleanSet.add(answer.weakSubset(setToCount));
answerIsBoolean = true;
return booleanSet;
case product:
if(answer.getMultiplicity() > 32) { // 32 = sqrt(1024)
System.out.println("Max cardinality for cartesian product 1024");
throw new IncorrectInputSyntaxException("Cardinality for cartesian product" +
" is max is 1024\"", "Calculate.Evaluate");
}
operationApplied = true;
answer = (MixedSet) answer.cartesianProduct(setToCount);
answer.setProduct(true);
}
if (operationApplied) {
System.out.println("result " + answer.toStringNoName(false));
if (!isLastOperationUnary) {
instructions.remove(x - 1);
instructions.remove(x - 1);
instructions.remove(x - 1);
} else {
instructions.remove(x - 1);
instructions.remove(x - 1);
}
if (maxPriority == 0) {
instructions.add(x - 1, new Tuple(answer, maxPriority, 's'));
} else if (operationApplied) {
instructions.add(x - 1, new Tuple(answer, maxPriority - 1, 's'));
}
break;
}
} else {
// if no right priority find, move not from set to operator, but from set to set
x++;
}
}
if (!priorityFound) {
--maxPriority;
}
}
if (answerIsBoolean) {
return booleanSet;
} else {
try {
return instructions.get(0).getLeft();
} catch (java.lang.IndexOutOfBoundsException ex) {
throw new IncorrectInputSyntaxException("Incorrect Syntax", "Calculate Algorithm");
}
}
}
}
|
EddeDev/RaybyteEngine
|
Raybyte/Source/Raybyte/Math/Math.h
|
#pragma once
namespace Raybyte {
namespace Math {
float Repeat(float t, float length);
float DeltaAngle(float current, float target);
float Angle(const glm::vec3& a, const glm::vec3& b);
bool DecomposeMatrix4(const glm::mat4& matrix, glm::vec3& position);
bool DecomposeMatrix4(const glm::mat4& matrix, glm::vec3& position, glm::vec3& rotation);
bool DecomposeMatrix4(const glm::mat4& matrix, glm::vec3& position, glm::vec3& rotation, glm::vec3& scale);
}
}
|
fboucher9/appl
|
random/appl_random_std_crypto.cpp
|
<gh_stars>0
/* See LICENSE for license details */
/*
*/
#include <stdio.h>
#include <appl_status.h>
#include <appl_types.h>
#include <object/appl_object.h>
#include <random/appl_random.h>
#include <random/appl_random_std_crypto.h>
#include <misc/appl_unused.h>
#include <allocator/appl_allocator_handle.h>
//
//
//
enum appl_status
appl_random_std_crypto::s_create(
struct appl_allocator * const
p_allocator,
struct appl_random * * const
r_random)
{
enum appl_status
e_status;
class appl_random_std_crypto *
p_random_std_crypto;
e_status =
appl_new(
p_allocator,
&(
p_random_std_crypto));
if (
appl_status_ok
== e_status)
{
*(
r_random) =
p_random_std_crypto;
}
return
e_status;
} // s_create()
//
//
//
#if 0
enum appl_status
appl_random_std_crypto::s_destroy(
struct appl_allocator * const
p_allocator,
struct appl_random * const
p_random)
{
return
appl_delete(
p_allocator,
p_random);
} // s_destroy()
#endif
//
//
//
appl_random_std_crypto::appl_random_std_crypto(
struct appl_context * const
p_context) :
appl_random(
p_context)
{
}
//
//
//
appl_random_std_crypto::~appl_random_std_crypto()
{
}
//
//
//
appl_size_t
appl_random_std_crypto::v_cleanup(void)
{
return
sizeof(class appl_random_std_crypto);
} // v_cleanup()
//
//
//
enum appl_status
appl_random_std_crypto::v_pick(
unsigned long int const
i_value_max,
unsigned long int * const
r_value)
{
enum appl_status
e_status;
FILE *
fp;
fp =
fopen(
"/dev/urandom",
"rb");
if (
fp)
{
appl_size_t
i_read_result;
unsigned char
a_data[4u];
i_read_result =
fread(
a_data,
4u,
1u,
fp);
if (
1 == i_read_result)
{
unsigned long int
i_value;
i_value =
(
((a_data[0u] & 0xFFu) << 0u)
| ((a_data[1u] & 0xFFu) << 8u)
| ((a_data[2u] & 0xFFu) << 16u)
| ((a_data[3u] & 0xFFu) << 24u));
if (
i_value_max)
{
*(
r_value) =
i_value % i_value_max;
}
else
{
*(
r_value) =
i_value;
}
e_status =
appl_status_ok;
}
else
{
e_status =
appl_status_fail;
}
fclose(
fp);
}
else
{
e_status =
appl_status_fail;
}
return
e_status;
} // v_pick()
/* end-of-file: appl_random_std_crypto.cpp */
|
josetonyp/elements
|
spec/factories/elements_users.rb
|
FactoryGirl.define do
factory :user, :class => 'Elements::User' do
sequence(:name) {|n| "Name - #{n}"}
sequence(:lastname) {|n| "Lastname - #{n}"}
sequence(:email) {|n| "<EMAIL>"}
password "<PASSWORD>"
end
end
|
appform-io/databuilderframework
|
src/test/java/io/appform/databuilderframework/speed/AdditonRequestData.java
|
<filename>src/test/java/io/appform/databuilderframework/speed/AdditonRequestData.java
package io.appform.databuilderframework.speed;
import io.appform.databuilderframework.model.Data;
public class AdditonRequestData extends Data{
protected AdditonRequestData() {
super("ADD_REQ");
}
}
|
indunet/fastproto
|
src/main/java/org/indunet/fastproto/checksum/Crc16Checker.java
|
<reponame>indunet/fastproto
/*
* Copyright 2019-2021 indunet
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.indunet.fastproto.checksum;
import lombok.val;
import org.indunet.fastproto.EndianPolicy;
import org.indunet.fastproto.annotation.EnableChecksum;
import org.indunet.fastproto.annotation.Endian;
import org.indunet.fastproto.annotation.type.UInteger16Type;
import org.indunet.fastproto.exception.CodecError;
import org.indunet.fastproto.exception.DecodeException;
import org.indunet.fastproto.util.DecodeUtils;
import org.indunet.fastproto.util.EncodeUtils;
import org.indunet.fastproto.util.ReverseUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author <NAME>
* @since 1.6.3
*/
public class Crc16Checker implements Checker {
protected final static int defaultPoly = 0xA001;
protected final static Map<Integer, Crc16Checker> checkers = new ConcurrentHashMap<>();
protected int poly;
protected Crc16Checker(int poly) {
this.poly = poly;
}
public static Crc16Checker getInstance() {
return checkers.computeIfAbsent(defaultPoly, p -> new Crc16Checker(p));
}
public static synchronized Crc16Checker getInstance(int poly) {
if (poly == 0) {
return getInstance();
} else {
return checkers.computeIfAbsent(poly, p -> new Crc16Checker(p));
}
}
@Override
public boolean validate(byte[] datagram, Class<?> protocolClass) {
if (!protocolClass.isAnnotationPresent(EnableChecksum.class)) {
return true;
}
val checkSum = protocolClass.getAnnotation(EnableChecksum.class);
int byteOffset = checkSum.value();
int start = checkSum.start();
int length = checkSum.length();
EndianPolicy policy;
if (checkSum.endianPolicy().length != 0) {
policy = checkSum.endianPolicy()[0];
} else if (protocolClass.isAnnotationPresent(Endian.class)) {
policy = protocolClass.getAnnotation(Endian.class).value();
} else {
policy = EndianPolicy.LITTLE;
}
int actual = this.getValue(datagram, start, length);
int expected = DecodeUtils.uInteger16Type(datagram, byteOffset, policy);
return actual == expected;
}
@Override
public void setValue(byte[] datagram, Class<?> protocolClass) {
if (!protocolClass.isAnnotationPresent(EnableChecksum.class)) {
return;
}
val checkSum = protocolClass.getAnnotation(EnableChecksum.class);
int byteOffset = checkSum.value();
int start = checkSum.start();
int length = checkSum.length();
EndianPolicy policy;
if (checkSum.endianPolicy().length != 0) {
policy = checkSum.endianPolicy()[0];
} else if (protocolClass.isAnnotationPresent(Endian.class)) {
policy = protocolClass.getAnnotation(Endian.class).value();
} else {
policy = EndianPolicy.LITTLE;
}
this.setValue(datagram, byteOffset, start, length, policy);
}
@Override
public int getSize() {
return UInteger16Type.SIZE;
}
public int getValue(byte[] datagram, int start, int length) {
int s = ReverseUtils.byteOffset(datagram.length, start);
int l = ReverseUtils.length(datagram.length, start, length);
if (s < 0) {
throw new DecodeException(CodecError.ILLEGAL_BYTE_OFFSET);
} else if (l <= 0) {
throw new DecodeException(CodecError.ILLEGAL_PARAMETER);
} else if (s + length > datagram.length) {
throw new DecodeException(CodecError.EXCEEDED_DATAGRAM_SIZE);
}
int crc16 = 0xFFFF;
for (int i = 0; i < l; i++) {
crc16 ^= ((int) datagram[s + i] & 0xFF);
for (int j = 0; j < 8; j++) {
if ((crc16 & 0x0001) == 1) {
crc16 >>>= 1;
crc16 ^= poly;
} else {
crc16 >>>= 1;
}
}
}
return crc16;
}
public void setValue(byte[] datagram, int byteOffset, int start, int length, EndianPolicy policy) {
int value = this.getValue(datagram, start, length);
EncodeUtils.uInteger16Type(datagram, byteOffset, policy, value);
}
}
|
manuelecarlini/calamari-clients
|
dashboard/app/bower_components/dygraphs/experimental/palette/tooltip.js
|
// Copyright (c) 2011 Google, Inc.
//
// 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.
/**
* @fileoverview Dygraphs options palette tooltip.
*
* @author <EMAIL> (<NAME>)
*/
"use strict";
function Tooltip(parent) {
if (!parent) {
parent = $("body")[0];
}
this.elem = $("<div>")
.attr("class", "tooltip")
.appendTo(parent);
this.title = $("<div>")
.attr("class", "title")
.appendTo(this.elem);
this.type = $("<div>")
.attr("class", "type")
.appendTo(this.elem);
this.body = $("<div>")
.attr("class", "body")
.appendTo(this.elem);
this.hide();
}
Tooltip.prototype.show = function(source, title, type, body) {
this.title.html(title);
this.body.html(body);
this.type.text(type); // textContent for arrays.
var offset = source.offset();
this.elem.css({
"width" : "280",
"top" : parseInt(offset.top + source[0].offsetHeight) + 'px',
"left" : parseInt(offset.left + 10) + 'px',
"visibility" : "visible"});
}
Tooltip.prototype.hide = function() {
this.elem.css("visibility", "hidden");
}
|
project-sunbird/groups
|
group-actors/src/main/java/org/sunbird/util/DBUtil.java
|
package org.sunbird.util;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.sunbird.common.exception.BaseException;
import org.sunbird.common.util.JsonKey;
import org.sunbird.helper.CassandraConnectionManager;
import org.sunbird.helper.CassandraConnectionMngrFactory;
public class DBUtil {
public static final Map<String, DbInfo> dbInfoMap = new HashMap<>();
public static final String KEY_SPACE_NAME = JsonKey.SUNBIRD_GROUPS;
private static void initializeDBProperty() {
// setting db info (keyspace , table) into static map
// this map will be used during cassandra data base interaction.
// this map will have each DB name and it's corresponding keyspace and table
// name.
dbInfoMap.put(JsonKey.USER_DB, getDbInfoObject(KEY_SPACE_NAME, "group"));
}
/**
* This method will check the cassandra data base connection. first it will try to established the
* data base connection from provided environment variable , if environment variable values are
* not set then connection will be established from property file.
*/
public static void checkCassandraDbConnections() throws BaseException {
CassandraConnectionManager cassandraConnectionManager =
CassandraConnectionMngrFactory.getInstance();
String nodes = System.getenv(JsonKey.SUNBIRD_CASSANDRA_IP);
String[] hosts = null;
if (StringUtils.isNotBlank(nodes)) {
hosts = nodes.split(",");
} else {
hosts = new String[] {"localhost"};
}
cassandraConnectionManager.createConnection(hosts);
}
private static DbInfo getDbInfoObject(String keySpace, String table) {
DbInfo dbInfo = new DbInfo();
dbInfo.setKeySpace(keySpace);
dbInfo.setTableName(table);
return dbInfo;
}
/** class to hold cassandra db info. */
public static class DbInfo {
private String keySpace;
private String tableName;
private String userName;
private String password;
private String ip;
private String port;
/**
* @param keySpace
* @param tableName
* @param userName
* @param password
*/
DbInfo(
String keySpace,
String tableName,
String userName,
String password,
String ip,
String port) {
this.keySpace = keySpace;
this.tableName = tableName;
this.userName = userName;
this.password = password;
this.ip = ip;
this.port = port;
}
/** No-arg constructor */
DbInfo() {}
@Override
public boolean equals(Object obj) {
if (obj instanceof DbInfo) {
DbInfo ob = (DbInfo) obj;
if (this.ip.equals(ob.getIp())
&& this.port.equals(ob.getPort())
&& this.keySpace.equals(ob.getKeySpace())) {
return true;
}
}
return false;
}
@Override
public int hashCode() {
return 1;
}
public String getKeySpace() {
return keySpace;
}
public void setKeySpace(String keySpace) {
this.keySpace = keySpace;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getIp() {
return ip;
}
public String getPort() {
return port;
}
}
}
|
michaeldiogo253/ecommerce-api-rest
|
src/test/java/estudos/ecommerce/cliente/adapter/in/web/ListarTodosOsClientesControllerTestIT.java
|
package estudos.ecommerce.cliente.adapter.in.web;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ListarTodosOsClientesControllerTestIT {
@Autowired
private TestRestTemplate testRestTemplate;
// o retorno é do tipo string, pois o retorno é
@Test
void deveListarTodosOsClientesEDevolverStatus200(){
var clienteResponseEntity = testRestTemplate.getForEntity("/ecommerce-api/cliente/listar-todos",
String.class);
assertThat(clienteResponseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
}
|
mfloresn90/JavaSources
|
vogella/de.vogella.osgi.quoteservice/src/de/vogella/osgi/quoteservice/Activator.java
|
<reponame>mfloresn90/JavaSources<gh_stars>0
package de.vogella.osgi.quoteservice;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import de.vogella.osgi.quote.IQuoteService;
import de.vogella.osgi.quoteservice.internal.QuoteService;
public class Activator implements BundleActivator {
public void start(BundleContext context) throws Exception {
System.out.println("Starting quoteservice bundles");
IQuoteService service = new QuoteService();
// Third parameter is a hashmap which allows to configure the service
// Not required in this example
context.registerService(IQuoteService.class.getName(), service,
null);
System.out.println("IQuoteService is registered");
}
public void stop(BundleContext context) throws Exception {
System.out.println("Stopping quoteservice bundles");
}
}
|
MediaFire/mediafire-java-sdk
|
src/main/java/com/mediafire/sdk/MFActionToken.java
|
package com.mediafire.sdk;
public class MFActionToken extends MFToken implements MediaFireActionToken {
private final int type;
private final long requestTime;
private final int lifespan;
protected MFActionToken(String sessionToken, int type, long requestTime, int lifespan) {
super(sessionToken);
this.type = type;
this.requestTime = requestTime;
this.lifespan = lifespan;
}
@Override
public int getType() {
return type;
}
@Override
public long getRequestTime() {
return requestTime;
}
@Override
public int getLifespan() {
return lifespan;
}
@Override
public String toString() {
return "MFActionToken{" +
"type=" + type +
", requestTime=" + requestTime +
", lifespan=" + lifespan +
"} " + super.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
MFActionToken that = (MFActionToken) o;
if (getType() != that.getType()) return false;
if (getRequestTime() != that.getRequestTime()) return false;
return getLifespan() == that.getLifespan();
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + getType();
result = 31 * result + (int) (getRequestTime() ^ (getRequestTime() >>> 32));
result = 31 * result + getLifespan();
return result;
}
}
|
go2max/java-snake-game
|
src/view/controls/SharedResourcesView.java
|
package view.controls;
import models.board.SharedResources;
import models.palacefestival.Deck;
import view.MediaController;
import javax.swing.*;
import java.awt.*;
//TODO [Sydney] [Jorge]
public class SharedResourcesView extends JPanel {
private final int BORDER = 10;
private final int WIDTH = (int)(Toolkit.getDefaultToolkit().getScreenSize().getWidth()/ 4 - BORDER/2);
private final int HEIGHT = (int)(Toolkit.getDefaultToolkit().getScreenSize().getHeight() - 300 - BORDER*2);
private final String source = "layout_%s.png";
private JLabel threeTiles, irrigationTiles;
private JLabel palace2Tiles, palace4Tiles, palace6Tiles, palace8Tiles, palace10Tiles, palaceDeck, festivalCard;
private JLabel actionSummaryCard;
public SharedResourcesView(){
initLayout();
}
public void initLayout() {
threeTiles = new JLabel();
irrigationTiles = new JLabel();
palace2Tiles = new JLabel();
palace4Tiles = new JLabel();
palace6Tiles = new JLabel();
palace8Tiles = new JLabel();
palace10Tiles = new JLabel();
palaceDeck = new JLabel();
festivalCard = new JLabel();
actionSummaryCard = new JLabel(); //tODo
setBackground(Color.WHITE);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
initializeLayout();
}
private void initializeLayout(){
setLayout(threeTiles, 100, "three");
add(threeTiles);
setLayout(irrigationTiles, 100, "irrigation");
add(irrigationTiles);
setLayout(palaceDeck, 100, "card_back");
add(palaceDeck);
setLayout(festivalCard, 100, "palaceCard_1");
add(festivalCard);
setLayout(palace2Tiles, 75, "palace_2");
add(palace2Tiles);
setLayout(palace4Tiles, 75, "palace_4");
add(palace4Tiles);
setLayout(palace6Tiles, 75, "palace_6");
add(palace6Tiles);
setLayout(palace8Tiles, 75, "palace_8");
add(palace8Tiles);
setLayout(palace10Tiles, 75, "palace_10");
add(palace10Tiles);
}
private void setLayout(JLabel comp, int height, String imageName){
comp.setPreferredSize(new Dimension(WIDTH/5 - BORDER, height));
comp.setHorizontalTextPosition(SwingConstants.CENTER);
comp.setVerticalTextPosition(SwingConstants.BOTTOM);
comp.setVerticalAlignment(SwingConstants.BOTTOM);
comp.setIcon(new ImageIcon(MediaController.getInstance().getImage(String.format(source, imageName))));
}
/* TEXT SETTERS */
public void setNumThreeTiles(int num){
threeTiles.setText(""+num);
}
public void setNumIrrigationTiles(int num){
irrigationTiles.setText(""+num);
}
public void setNumPalace2Tiles(int num){
palace2Tiles.setText(""+num);
}
public void setNumPalace4Tiles(int num){
palace4Tiles.setText(""+num);
}
public void setNumPalace6Tiles(int num){
palace6Tiles.setText(""+num);
}
public void setNumPalace8Tiles(int num){
palace8Tiles.setText(""+num);
}
public void setNumPalace10Tiles(int num){
palace10Tiles.setText(""+num);
}
public void setFestivalCardImage(String imageSource){
System.out.println(String.format(source, imageSource));
festivalCard.setIcon(new ImageIcon(MediaController.getInstance().getImage(String.format(source, imageSource))));
}
public void setNumPalaceCards(int num){
palaceDeck.setText(""+num);
}
public void update(SharedResources resources, Deck deck) {
setNumThreeTiles(resources.getNumThreeTiles());
setNumIrrigationTiles(resources.getNumIrrigationTiles());
setNumPalace2Tiles(resources.getNum2PalaceTiles());
setNumPalace4Tiles(resources.getNum4PalaceTiles());
setNumPalace6Tiles(resources.getNum6PalaceTiles());
setNumPalace8Tiles(resources.getNum8PalaceTiles());
setNumPalace10Tiles(resources.getNum10PalaceTiles());
setFestivalCardImage(deck.getFestivalCard().toString());
setNumPalaceCards(deck.getLibrary().size());
}
}
|
thehyve/civic-server
|
app/presenters/diff_presenter.rb
|
class DiffPresenter
include ERB::Util
def initialize(changes_hash)
@changes_hash = changes_hash
end
def as_json(options = {})
@changes_hash.each_with_object({}) do |(property_name, values), changes|
(old_value, new_value) = if values.is_a?(Array)
values
else
[nil, values]
end
match_data = /(?<association>.+)_ids?$/.match(property_name)
association = match_data[:association] if match_data
association_class = association.camelize.constantize rescue nil if association
if association_class && association_class.new.respond_to?(:display_name)
changes[association] = diff(val_to_diff(association_class, old_value), val_to_diff(association_class, new_value))
elsif new_value.is_a?(Array)
changes[property_name] = diff(old_value.join(', '), new_value.join(', '))
else
changes[property_name] = diff(old_value, new_value)
end
end
end
private
def val_to_diff(association_class, value)
if value.is_a?(Array)
if val = association_class.where(id: value)
val.map { |obj| obj.display_name }.sort.join(', ')
else
[]
end
else
if val = association_class.find_by(:id => value)
val.display_name
else
''
end
end
end
def diff(old_value, new_value)
{
diff: Diffy::Diff.new(old_value, new_value).to_s(:html),
final: new_value
}
end
end
|
terrai/rastercube
|
rastercube/scripts/worldgrid_info.py
|
"""
Print infos about a worldgrid
Example invocation::
python rastercube/scripts/worldgrid_info.py
--grid_root=hdfs:///user/test/ndvi
"""
import argparse
import rastercube.jgrid as jgrid
parser = argparse.ArgumentParser(description='Create NDVI/QA jgrids from HDF')
parser.add_argument('--grid_root', type=str, required=True,
help='grid_root (a fs:// or hdfs://)')
if __name__ == '__main__':
args = parser.parse_args()
grid_root = args.grid_root
header = jgrid.Header.load(grid_root)
fracnums = header.list_available_fracnums()
fractions = header.list_available_fractions()
print 'Header : ', header
print 'fractions shape : ', header.frac_height, header.frac_width
print 'fractions count : ', len(fractions)
print 'fracnum counts : ', len(fracnums)
|
a982338665/customRPC
|
rpc-codec/src/test/java/pers/li/codec/JSONEncoderTest.java
|
<reponame>a982338665/customRPC
package pers.li.codec;
import org.junit.Test;
import static org.junit.Assert.*;
public class JSONEncoderTest {
@Test
public void encode() {
Encoder jsonEncoder = new JSONEncoder();
TestBean testBean = new TestBean();
testBean.setAge(1);
testBean.setName("hhh");
byte[] encode = jsonEncoder.encode(testBean);
System.err.println(encode.length);
}
}
|
hoshiryu/Radium-Engine
|
tests/ExampleApps/SimpleAnimationApp/minimalradium.hpp
|
#pragma once
#include <Core/Animation/KeyFramedValue.hpp>
#include <Core/Animation/KeyFramedValueController.hpp>
#include <Core/Utils/Color.hpp>
#include <Engine/Component/Component.hpp>
#include <Engine/System/System.hpp>
/* This file contains a minimal radium/qt application which shows the
* "Simple Animation" demo, which uses KeyFramedValues to spin a cube with
* time-varying colors. */
namespace Ra::Engine {
class BlinnPhongMaterial;
} // namespace Ra::Engine
/// This is a very basic component which holds a spinning cube.
struct MinimalComponent : public Ra::Engine::Component {
explicit MinimalComponent( Ra::Engine::Entity* entity );
/// This function is called when the component is properly
/// setup, i.e. it has an entity.
void initialize() override;
/// This function uses the keyframes to update the cube to time \p t.
void update( Scalar t );
/// The Keyframes for the cube's tranform.
Ra::Core::Animation::KeyFramedValue<Ra::Core::Transform> m_transform;
/// The Keyframes for the cube's color.
Ra::Core::Animation::KeyFramedValueController m_colorController;
};
/// This system will be added to the engine. Every frame it will
/// add a task to be executed, calling the update function of the component.
/// \note This system makes time loop around.
class MinimalSystem : public Ra::Engine::System
{
public:
virtual void generateTasks( Ra::Core::TaskQueue* q,
const Ra::Engine::FrameInfo& info ) override;
void addComponent( Ra::Engine::Entity* ent, MinimalComponent* comp );
};
|
jianjustin/mini-yeation-mall
|
app/src/main/java/org/mini/yeation/mall/model/GoodsModel.java
|
package org.mini.yeation.mall.model;
import org.mini.yeation.mall.BaseApplication;
import org.mini.yeation.mall.dao.GoodsCategoryDao;
import org.mini.yeation.mall.domain.GoodsCategory;
import org.mini.yeation.mall.model.base.BaseModel;
import org.mini.yeation.mall.model.base.IModel;
import org.mini.yeation.mall.utils.AppDatabaseHelper;
import java.util.List;
import java.util.Map;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
public class GoodsModel extends BaseModel implements IModel {
private final GoodsCategoryDao goodsCategoryDao = AppDatabaseHelper.getInstance(BaseApplication.getInstance()).getGoodsCategoryDao();
/**
* 获取根分类
* @param params
* @param success
* @param error
*/
public void queryRootCategory(Map<String,Object> params, Consumer<List<GoodsCategory>> success, Consumer<Throwable> error){
goodsCategoryDao.getRootCategory("-1")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(success,error);
}
}
|
thomjoy/turftest
|
src/jspm_packages/npm/public-encrypt@2.0.0.js
|
module.exports = require("npm:public-encrypt@2.0.0/browser");
|
advanced-software-engineering/ASE19
|
src/main/java/ch/uzh/ifi/seal/ase19/core/PersistenceManager.java
|
<gh_stars>1-10
package ch.uzh.ifi.seal.ase19.core;
import cc.kave.commons.utils.io.json.JsonUtils;
import ch.uzh.ifi.seal.ase19.core.models.QuerySelection;
import ch.uzh.ifi.seal.ase19.core.models.ResultType;
import ch.uzh.ifi.seal.ase19.core.utils.FileUtils;
import org.apache.commons.lang3.tuple.Pair;
import java.io.File;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
public class PersistenceManager implements IPersistenceManager {
private String modelDirectory;
public PersistenceManager(String modelDirectory) {
this.modelDirectory = modelDirectory;
}
@Override
public void saveModel(QuerySelection model) {
File file = FileUtils.getPersistenceFile(modelDirectory, model.getReceiverType(), model.getResultType());
ReceiverTypeQueries storageFile = load(model.getReceiverType(), model.getResultType());
storageFile.addItem(model);
JsonUtils.toJson(storageFile, file);
}
@Override
public void replaceModels(ReceiverTypeQueries queries) {
QuerySelection firstModel = queries.getItems().get(0);
File file = FileUtils.getPersistenceFile(modelDirectory, firstModel.getReceiverType(), firstModel.getResultType());
JsonUtils.toJson(queries, file);
}
@Override
public ReceiverTypeQueries load(String receiverType, ResultType resultType) {
File file = FileUtils.getPersistenceFile(modelDirectory, receiverType, resultType);
if (file.exists()) {
return JsonUtils.fromJson(file, ReceiverTypeQueries.class);
} else {
return new ReceiverTypeQueries();
}
}
@Override
public Set<Pair<String, ResultType>> getAllModels() {
HashSet<Pair<String, ResultType>> ret = new HashSet<>();
for (ResultType resultType : ResultType.values()) {
File directory = Paths.get(modelDirectory, resultType.toString()).toFile();
if (directory.exists()) {
File[] files = directory.listFiles();
if(files != null) {
for (File fileEntry : files) {
ret.add(Pair.of(fileEntry.getName(), resultType));
}
}
}
}
return ret;
}
}
|
zabi94/Covens-reborn
|
src/main/java/com/covens/api/cauldron/IBrewEffect.java
|
package com.covens.api.cauldron;
import javax.annotation.Nullable;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public interface IBrewEffect {
/**
* Called when a splash brew hits the ground
*
* @param world The world
* @param pos The position on which the splash brew impacted
* @param modifiers The list of modifiers carried by the splash brew entity
* @param thrower The (optional) thrower of the potion
*/
public void applyInWorld(World world, BlockPos pos, EnumFacing side, IBrewModifierList modifiers, @Nullable EntityLivingBase thrower);
/**
* Called when a brew effect gets applied to an entity
*
* @param entity The entity this effect is being applied to
* @param effect The PotionEffect that is about to be applied
* @param modifiers The list of modifiers carried by the brew entity (splash,
* drinkable, arrow or lingering)
* @param thrower the (optional) thrower of the potion
* @return The potion effect to be applied to the entity. If no changes are
* required, just return the one passed as a parameter
*/
public PotionEffect onApplyToEntity(EntityLivingBase entity, PotionEffect effect, IBrewModifierList modifiers, @Nullable Entity thrower);
public boolean hasInWorldEffect();
public int getDefaultDuration();
public int getArrowDuration();
public int getLingeringDuration();
public int getCost();
}
|
khcitizen/tomcat-deployed
|
webapps/jasperserver-pro/scripts/bower_components/js-sdk/src/components/scalableTree/ScalableTree.js
|
<reponame>khcitizen/tomcat-deployed<filename>webapps/jasperserver-pro/scripts/bower_components/js-sdk/src/components/scalableTree/ScalableTree.js<gh_stars>0
/*
* Copyright (C) 2005 - 2014 Jaspersoft Corporation. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author: <NAME>
* @version: $Id$
*/
define(function(require) {
var _ = require("underscore"),
$ = require("jquery"),
Backbone = require("backbone"),
pathUtil = require("components/scalableTree/util/pathUtil"),
nativeMultiSelectionTrait = require("components/scalableList/trait/nativeMultiSelectionTrait"),
List = require("components/scalableList/view/ListWithSelection"),
listModelFactory = require("./factory/listModelFactory"),
getLevelNestingFactory = require("./factory/getLevelNestingFactory"),
defaultItemsTemplate = require("text!./template/defaultItemsTemplate.htm"),
paddingProcessor = require("./processor/paddingProcessor"),
valueProcessor = require("./processor/valueProcessor"),
selectionProcessor = require("./processor/selectionProcessor"),
treeDataFetchStrategyEnum = require("./enum/treeDataFetchStrategyEnum"),
treeDataFetchStrategyFactory = require("./factory/treeDataFetchStrategyFactory"),
TreeDataParallelFetchStrategy = require("./strategy/TreeDataParallelFetchStrategy"),
TreeDataSerialFetchStrategy = require("./strategy/TreeDataSerialFetchStrategy"),
TreeDataConverter = require("./TreeDataConverter"),
TreeViewState = require("./TreeViewState"),
TreeStateController = require("./TreeStateController"),
TreeCache = require("./TreeCache"),
TreeListDataProvider = require("./TreeListDataProvider"),
TreeLevelsToFetchProvider = require("./TreeLevelsToFetchProvider");
var defaultSeparator = "/",
defaultEscapeCharacter = "\\";
var RESTORE_TREE_STATE_DEFAULT_BUFFER_SIZE = 5000;
var eventsEnum = {
SELECT: "select",
EXPAND: "expand",
COLLAPSE: "collapse",
CLEAR_SELECTION: "clearSelection"
};
var pluginsLifeCyclePhaseEnum = {
TREE_INITIALIZED: "treeInitialized",
BEFORE_ITEMS_RENDERED: "beforeItemsRendered",
ITEMS_RENDERED: "itemsRendered",
REMOVE: "treeRemoved"
};
var defaultSelectors = {
collapser : ".jr-jTreeCollapser"
};
// controller
var ScalableTree = Backbone.View.extend({
className: "scalableTree",
initialize: function(options) {
options = options || {};
this._collapserWasClicked = false;
this.fetchStrategy = options.fetchStrategy || treeDataFetchStrategyEnum.PARALLEL_FETCH_STRATEGY;
this.lazy = options.lazy || false;
this.processors = options.processors || [];
this.nodePadding = _.isUndefined(options.nodePadding) ? 10 : options.nodePadding;
this.itemsTemplate = options.itemsTemplate || defaultItemsTemplate;
this.listItemHeight = options.listItemHeight;
this.selection = options.selection || {};
this.collapser = !_.isUndefined(options.collapser)
? options.collapser
: defaultSelectors.collapser;
this._initTreeViewState(options);
this._initTreeCache(options);
this._initTreeLevelsToFetchProvider(options);
this._initTreeDataConverter(options);
this._initTreeListDataProvider(options);
this._initTreeStateController(options);
this._initDefaultProcessors(options);
this._initList(options);
this._initEvents();
this._initPlugins();
if (!this.lazy) {
this.fetch();
}
},
// PUBLIC METHODS
getItem: function(id) {
return this.treeCache.getItem(id);
},
isExpanded: function(id) {
return this.treeViewState.isExpanded(id);
},
getSelection: function() {
var self = this,
items = [];
_.each(this.treeViewState.getSelection(), function(value, key) {
var item = self.treeCache.getItem(key);
item && items.push(item);
});
return items;
},
expand: function(items, options) {
this.treeStateController.expand(items, options);
this._triggerFetchWithEvent(eventsEnum.EXPAND, options, items);
},
expandPath: function (path) {
var self = this,
levelsToExpand = this._getLevelsToExpandByPath(path);
levelsToExpand && this._expandLevels(levelsToExpand).done(function() {
self.fetch();
});
},
collapse: function(items, options) {
this.treeStateController.collapse(items, options);
this._triggerFetchWithEvent(eventsEnum.COLLAPSE, options, items);
},
select: function(items, options) {
items = _.isArray(items) ? items : [items];
options = options || {};
this.clearSelection({silent: true});
this.treeStateController.select(items);
this.list.setValue(items, {
silent: true
});
!options.silent && this.trigger(eventsEnum.SELECT, items);
},
clearSelection: function(options) {
options = options || {};
this.treeStateController.resetSelection();
this.listModel.clearSelection();
!options.silent && this.trigger(eventsEnum.CLEAR_SELECTION);
},
setElement: function() {
Backbone.View.prototype.setElement.apply(this, arguments);
this.list && this.list.setElement(this.$el);
return this;
},
render: function() {
return this;
},
remove: function() {
runPluginsLifeCyclePhase.call(this, pluginsLifeCyclePhaseEnum.REMOVE);
this.list.remove();
this.processors = [];
this.plugins = [];
return Backbone.View.prototype.remove.apply(this, arguments);
},
fetch: function(options, callback) {
options = options || {};
var selection = [],
levels,
self = this,
dfd = $.Deferred();
if (options.clear) {
levels = this.treeViewState.getExpandedLevels();
if (options.keepSelection) {
selection = this._collectCurrentSelectedItemIds();
}
this.clearSelection({silent: true});
this.treeStateController.clearState();
if (options.keepExpanded) {
this._expandLevels(levels).done(function() {
self.treeStateController.select(selection);
dfd.resolve();
});
} else {
self.treeStateController.select(selection);
dfd.resolve();
}
} else {
dfd.resolve();
}
dfd.done(function() {
self.list.fetch(callback, {keepPosition: true});
});
},
// PRIVATE METHODS
_getLevelsToExpandByPath: function (path) {
path = path || "";
var levelsToExpand,
pathFragments = pathUtil.split(path, defaultEscapeCharacter, defaultSeparator)
.filter(function(val) {
return val;
});
if (pathFragments.length > 0) {
levelsToExpand = pathFragments.reduce(function (memo, fragment, index) {
var levelId,
prevLevel = memo[index - 1];
if (prevLevel) {
levelId = prevLevel.id + defaultSeparator + fragment;
} else {
levelId = defaultSeparator + fragment;
}
memo.push({id: levelId});
return memo;
}, []);
}
return levelsToExpand;
},
_collectCurrentSelectedItemIds: function() {
return _.map(this.treeViewState.getSelection(), function(value, key) {
return key;
});
},
_getFetchStrategy: function(options) {
var self = this;
return treeDataFetchStrategyFactory(this.fetchStrategy, {
fetchFunction: options.getData,
escapeCharacter: options.escapeCharacter,
isLevelShouldBeFetched: function(id) {
return (id === "/") || self.treeCache.getItem(id);
}
});
},
_initTreeViewState: function(options) {
this.treeViewState = options.treeViewState || new TreeViewState({
escapeCharacter: options.escapeCharacter
});
},
_initTreeCache: function(options) {
this.treeCache = options.treeCache || new TreeCache({
viewState: this.treeViewState,
escapeCharacter: options.escapeCharacter
});
},
_initTreeLevelsToFetchProvider: function(options) {
this.treeLevelsToFetchProvider = new TreeLevelsToFetchProvider({
viewState: this.treeViewState,
treeCache: this.treeCache
});
},
_initTreeDataConverter: function(options) {
this.treeDataConverter = new TreeDataConverter({
treeCache: this.treeCache,
viewState: this.treeViewState,
escapeCharacter: options.escapeCharacter
});
},
_initTreeListDataProvider: function(options) {
var self = this,
fetchStrategy = this._getFetchStrategy(options);
this.treeListDataProvider = options.treeListDataProvider || new TreeListDataProvider({
processors: this.processors,
itemIdGenerationStrategy: options.itemIdGenerationStrategy,
escapeCharacter: options.escapeCharacter,
fetchStrategy: fetchStrategy,
treeDataConverter: this.treeDataConverter,
processLevelItem: function(item) {
self.treeStateController.addItemToCache(item);
},
onLevelFetched: function(data, options) {
self.treeStateController.updateState(data, options);
},
treeLevelsToFetchProvider: this.treeLevelsToFetchProvider
});
},
_initTreeStateController: function(options) {
this.treeStateController = options.treeStateController || new TreeStateController({
treeCache: this.treeCache,
viewState: this.treeViewState
});
},
_initList: function(options) {
listModelFactory = options.listModelFactory || listModelFactory;
this.listModel = listModelFactory.create({
bufferSize: options.bufferSize,
getData: _.bind(this.treeListDataProvider.getData, this.treeListDataProvider)
});
if (this.selection.multiple) {
List = List.extend(nativeMultiSelectionTrait);
}
this.list = options.list || new List({
el: this.$el,
itemsTemplate: this.itemsTemplate,
listItemHeight: this.listItemHeight,
lazy: true,
selection: this.selection,
model: this.listModel,
selectedClass: options.selectedClass
});
},
_initEvents: function() {
this.listenTo(this.list, "before:render:data", this._onBeforeRenderData);
this.listenTo(this.list, "render:data", this._onRenderData);
this.listenTo(this.list, "selection:change", this._onListSelectionChange);
this.listenTo(this.list, "item:dblclick", this._onItemDblClick);
this.listenTo(this.list, "list:item:contextmenu", this._onContextMenu);
this.listenTo(this.list, "list:item:click", this._onClick);
this.listenTo(this.list, "list:item:mouseover", this._onItemMouseOver);
this.listenTo(this.list, "list:item:mouseout", this._onItemMouseOut);
},
_triggerFetchWithEvent: function(event, options) {
options = options || {};
var args = Array.prototype.slice.call(arguments, 2),
self = this;
!options.silent && this.fetch(options, function() {
args.unshift(event);
self.trigger.apply(self, args);
});
},
_onBeforeRenderData: function() {
this.trigger("before:render:items");
runPluginsLifeCyclePhase.call(this, pluginsLifeCyclePhaseEnum.BEFORE_ITEMS_RENDERED);
},
_onRenderData: function() {
// need to clear collapser flag in case it was set.
this._collapserWasClicked = false;
this.trigger("render:items");
runPluginsLifeCyclePhase.call(this, pluginsLifeCyclePhaseEnum.ITEMS_RENDERED);
},
_initDefaultProcessors: function(options) {
var overriddenPaddingProcessor = this._getOverriddenPaddingProcessor(options),
overriddenSelectionProcessor = this._getOverriddenSelectionProcessor();
this.processors.unshift(overriddenSelectionProcessor);
this.processors.unshift(overriddenPaddingProcessor);
this.processors.unshift(valueProcessor);
},
_getOverriddenPaddingProcessor: function(options) {
var getLevelNesting = getLevelNestingFactory.create(options.escapeCharacter, defaultSeparator);
return {
processItem: _.partial(paddingProcessor.processItem, getLevelNesting, this.nodePadding)
}
},
_getOverriddenSelectionProcessor: function() {
return {
processItem: _.partial(selectionProcessor.processItem,
this.treeViewState, this.treeStateController)
}
},
_initPlugins: function() {
this.plugins = [];
_.each(this._plugins, function(pluginObj) {
var plugin = pluginObj.constr;
this.plugins.push(new plugin(_.extend({}, {
tree: this
}, pluginObj.options)));
runPluginsLifeCyclePhase.call(this, pluginsLifeCyclePhaseEnum.TREE_INITIALIZED);
}, this);
},
_onCollapserClick: function(event) {
// set collapser flag to avoid toggle in case of dblclick
this._collapserWasClicked = true;
var id = $(event.target).parents("li").first().data("id");
id && this._toggleLevel(id);
},
_onListSelectionChange: function(selection) {
this.treeStateController.resetSelection(selection);
this.trigger("selection:change", this.getSelection());
},
_onItemDblClick: function(selection) {
var id = selection && selection[0];
// check collapser flag, if true do not trigger toggle
if (id && !this._collapserWasClicked) {
this._toggleLevel(id);
this.trigger("item:dblclick", this.getSelection());
}
},
_onContextMenu: function(item, event) {
this.trigger("item:contextmenu", item, event);
},
_onItemMouseOver: function(item, event) {
this.trigger("item:mouseover", item, event);
},
_onItemMouseOut: function(item, event) {
this.trigger("item:mouseout", item, event);
},
_isCollapserEventTarget: function(event) {
return $(event.target).is(this.collapser);
},
_onClick: function(item, event) {
if (this._isCollapserEventTarget(event)) {
this._onCollapserClick(event);
}
this.trigger("item:click", item, event);
},
_toggleLevel: function(id) {
this.treeViewState.isExpanded(id)
? this.collapse(id)
: this.expand(id);
},
_expandLevels: function(levels) {
var self = this;
var levelsOptions = this.treeListDataProvider.getLevelsOptions(levels, {
limit: RESTORE_TREE_STATE_DEFAULT_BUFFER_SIZE
});
return this.treeListDataProvider.fetchTreeLevels(levelsOptions, function(data, fetchedLevel) {
self.treeStateController.expand(fetchedLevel.id);
self.treeStateController.updateState(data, fetchedLevel);
});
}
}, {
instance: function(options){
return new this(options);
}
});
return {
use: function(plugin, options){
return (function(constructor){
return {
use: function(plugin, options){
constructor.prototype._plugins.push({
constr: plugin,
options: options
});
return this;
},
create: function(){
return constructor;
}
}
}(ScalableTree.extend({
_plugins: [{
constr: plugin,
options:options
}]
})));
},
create: function(){
return ScalableTree;
},
Selectors : defaultSelectors
};
function runPluginsLifeCyclePhase(pluginLifeCyclePhase) {
_.each(this.plugins, function(plugin) {
plugin[pluginLifeCyclePhase] && plugin[pluginLifeCyclePhase]();
}, this);
}
});
|
duarterafael/Conformitate
|
ArgoUML/argouml-app/src/org/argouml/ui/cmd/ActionAdjustSnap.java
|
<filename>ArgoUML/argouml-app/src/org/argouml/ui/cmd/ActionAdjustSnap.java
/* $Id: ActionAdjustSnap.java 17842 2010-01-12 19:21:22Z linus $
*****************************************************************************
* Copyright (c) 2009 Contributors - see below
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* tfmorris
*****************************************************************************
*
* Some portions of this file was previously release using the BSD License:
*/
// Copyright (c) 2006-2008 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.ui.cmd;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.KeyStroke;
import org.argouml.application.api.Argo;
import org.argouml.configuration.Configuration;
import org.argouml.i18n.Translator;
import org.tigris.gef.base.Editor;
import org.tigris.gef.base.Globals;
import org.tigris.gef.base.Guide;
import org.tigris.gef.base.GuideGrid;
/**
* This action changes the snap (called guide or grid-guide in GEF).
*
* @author Michiel
*/
public class ActionAdjustSnap extends AbstractAction {
private int guideSize;
private static final String DEFAULT_ID = "8";
private static ButtonGroup myGroup;
/**
* @param size the size of the snap in pixels
* @param name the name of the action
*/
public ActionAdjustSnap(int size, String name) {
super();
guideSize = size;
putValue(Action.NAME, name);
}
public void actionPerformed(ActionEvent e) {
Editor ce = Globals.curEditor();
Guide guide = ce.getGuide();
if (guide instanceof GuideGrid) {
((GuideGrid) guide).gridSize(guideSize);
Configuration.setString(Argo.KEY_SNAP, (String) getValue("ID"));
}
}
static void setGroup(ButtonGroup group) {
myGroup = group;
}
/**
* This executes one of the actions,
* based on the stored ArgoUML configuration.
* This function is intended for the initial setting
* of the snap when ArgoUML is started.
*/
static void init() {
String id = Configuration.getString(Argo.KEY_SNAP, DEFAULT_ID);
List<Action> actions = createAdjustSnapActions();
for (Action a : actions) {
if (a.getValue("ID").equals(id)) {
a.actionPerformed(null);
if (myGroup != null) {
for (Enumeration e = myGroup.getElements();
e.hasMoreElements();) {
AbstractButton ab = (AbstractButton) e.nextElement();
Action action = ab.getAction();
if (action instanceof ActionAdjustSnap) {
String currentID = (String) action.getValue("ID");
if (id.equals(currentID)) {
myGroup.setSelected(ab.getModel(), true);
return;
}
}
}
}
return;
}
}
}
/**
* Return a list of actions to adjust the size of the snap grid.
* Current values are 4, 8, 16, and 32.
*
* @return List of Actions which adjust the size of the snap grid
*/
static List<Action> createAdjustSnapActions() {
List<Action> result = new ArrayList<Action>();
Action a;
String name;
name = Translator.localize("menu.item.snap-4");
a = new ActionAdjustSnap(4, name);
a.putValue("ID", "4");
a.putValue("shortcut", KeyStroke.getKeyStroke(
KeyEvent.VK_1, Event.ALT_MASK + Event.CTRL_MASK));
result.add(a);
name = Translator.localize("menu.item.snap-8");
a = new ActionAdjustSnap(8, name);
a.putValue("ID", "8"); /* This ID is used as DEFAULT_ID ! */
a.putValue("shortcut", KeyStroke.getKeyStroke(
KeyEvent.VK_2, Event.ALT_MASK + Event.CTRL_MASK));
result.add(a);
name = Translator.localize("menu.item.snap-16");
a = new ActionAdjustSnap(16, name);
a.putValue("ID", "16");
a.putValue("shortcut", KeyStroke.getKeyStroke(
KeyEvent.VK_3, Event.ALT_MASK + Event.CTRL_MASK));
result.add(a);
name = Translator.localize("menu.item.snap-32");
a = new ActionAdjustSnap(32, name);
a.putValue("ID", "32");
a.putValue("shortcut", KeyStroke.getKeyStroke(
KeyEvent.VK_4, Event.ALT_MASK + Event.CTRL_MASK));
result.add(a);
return result;
}
}
|
kassanmoor/rexray
|
libstorage/api/server/handlers/handlers_errors.go
|
<gh_stars>1-10
package handlers
import (
"encoding/json"
"net/http"
log "github.com/sirupsen/logrus"
"github.com/akutz/goof"
"github.com/thecodeteam/rexray/libstorage/api/context"
"github.com/thecodeteam/rexray/libstorage/api/server/httputils"
"github.com/thecodeteam/rexray/libstorage/api/types"
)
// errorHandler is a global HTTP filter for handlling errors
type errorHandler struct {
handler types.APIFunc
}
// NewErrorHandler returns a new global HTTP filter for handling errors.
func NewErrorHandler() types.Middleware {
return &errorHandler{}
}
func (h *errorHandler) Name() string {
return "error-handler"
}
func (h *errorHandler) Handler(m types.APIFunc) types.APIFunc {
return (&errorHandler{m}).Handle
}
// Handle is the type's Handler function.
func (h *errorHandler) Handle(
ctx types.Context,
w http.ResponseWriter,
req *http.Request,
store types.Store) error {
err := h.handler(ctx, w, req, store)
if err == nil {
return nil
}
gerr := goof.Newe(err)
ctx.WithError(gerr).Error("error: api call failed")
httpErr := goof.NewHTTPError(gerr, getStatus(err))
if isLogAPICallErrJSON(ctx) {
buf, err := json.Marshal(httpErr)
if err != nil {
ctx.WithError(err).Error(
"error marshalling api call err to json")
} else {
ctx.WithField("apiErr", string(buf)).Debug("api call error json")
}
}
httputils.WriteJSON(w, httpErr.Status(), httpErr)
return nil
}
func getStatus(err error) int {
if err == types.ErrMissingStorageService {
return http.StatusInternalServerError
}
switch err.(type) {
case *types.ErrBadAdminToken,
*types.ErrSecTokInvalid:
return http.StatusUnauthorized
case *types.ErrNotFound:
return http.StatusNotFound
case *types.ErrMissingInstanceID,
*types.ErrMissingLocalDevices:
return http.StatusBadRequest
default:
return http.StatusInternalServerError
}
}
func isLogAPICallErrJSON(ctx types.Context) bool {
if types.Debug {
return true
}
if lvl, ok := context.GetLogLevel(ctx); ok && lvl == log.DebugLevel {
return true
}
return false
}
|
r-korchagin/hackerrankJS
|
FairRations.js
|
"use strict";
// hackerrank question
// Fair Rations
/**
*
* @param {Array} B
*/
function fairRations(B) {
if (B.reduce((accum,el)=>accum+el)%2!==0) return 'NO';
let count = 0;
for(let i = 0; i<B.length; i++){
if(B[i] % 2 != 0){
B[i] = B[i] + 1;
B[i+1] = B[i+1] + 1;
count+=2;
}
}
return count;
}
console.log(fairRations([2, 3, 4, 5, 6])); //Expected 4
console.log(fairRations([1, 2])); // Expected "NO"
|
urxp/dRally
|
race___4a25ch.c
|
<reponame>urxp/dRally<gh_stars>10-100
#include "drally.h"
extern byte ___243c60h[];
extern byte ___1e6ed0h[];
extern byte ___1de580h[];
extern byte ___243d08h[];
extern byte ___1de7d0h[];
void ___4a064h_cdecl(dword, dword, dword, dword);
void race___4a25ch(void){
double d_tmp;
dword eax, ebx, ecx, edx, edi, esi, ebp;
byte __esp[0xc+8];
byte * esp = __esp+0xc;
ecx = D(___243c60h);
FPUSH((int)D(___1e6ed0h+0xc));
ST(0) = ST(0)*3.75;
FPUSH(F32(___1e6ed0h+0xb4));
FPUSH(F32(___1e6ed0h+0xb8));
edx = D(___1e6ed0h+0xc);
ebx = D(___1de580h);
d_tmp = ST(0); ST(0) = ST(1); ST(1) = d_tmp;
F32(___1e6ed0h+0x14e) = (float)FPOP();
eax = 4*edx;
F32(___1e6ed0h+0x152) = (float)FPOP();
eax -= edx;
F32(___1e6ed0h+0xac) = (float)FPOP();
eax <<= 3;
FPUSH(F32(___1e6ed0h+0xac));
eax += edx;
F32(___1e6ed0h+0x156) = (float)FPOP();
eax <<= 6;
edx = 0;
D(___1e6ed0h+0x10) = eax;
H(eax) = 1;
D(___1e6ed0h+0x34a) = edx;
B(___1e6ed0h+0x108) = H(eax);
B(___1e6ed0h+0x109) = H(eax);
if(ebx == 6) goto ___4a318h;
esp -= 4;
FPUSH((int)D(___1de580h+0x40));
F32(esp) = (float)FPOP();
esp -= 4;
FPUSH((int)D(___1de580h+0x3c));
F32(esp) = (float)FPOP();
eax = 0xf;
esp -= 4;
FPUSH((int)D(___1de580h+0x38));
F32(esp) = (float)FPOP();
___4a064h_cdecl(eax, D(esp), D(esp+4), D(esp+8));
esp += 0xc;
___4a318h:
FPUSH((int)D(___1e6ed0h+0xc+0x35e));
ST(0) = ST(0)*3.75;
FPUSH(F32(___1e6ed0h+0xb4+0x35e));
FPUSH(F32(___1e6ed0h+0xb8+0x35e));
FPUSH((int)D(___1de580h+0xd4));
esp -= 4;
L(ebx) = 2;
edx = D(___1e6ed0h+0xc+0x35e);
d_tmp = ST(0); ST(0) = ST(2); ST(2) = d_tmp;
F32(___1e6ed0h+0x14e +0x35e) = (float)FPOP();
F32(___1e6ed0h+0x152+0x35e) = (float)FPOP();
ecx = 0;
eax = 4*edx;
B(___1e6ed0h+0x109+0x35e) = L(ebx);
D(___1e6ed0h+0x34a+0x35e) = ecx;
eax -= edx;
d_tmp = ST(0); ST(0) = ST(1); ST(1) = d_tmp;
F32(___1e6ed0h+0xac+0x35e) = (float)FPOP();
eax <<= 3;
FPUSH(F32(___1e6ed0h+0xac+0x35e));
eax += edx;
F32(___1e6ed0h+0x156+0x35e) = (float)FPOP();
eax <<= 6;
H(edx) = 1;
eax += 0x25800;
B(___1e6ed0h+0x108+0x35e) = H(edx);
D(___1e6ed0h+0x10+0x35e) = eax;
F32(esp) = (float)FPOP();
esp -= 4;
FPUSH((int)D(___1de580h+0xd0));
F32(esp) = (float)FPOP();
eax = 0x19;
esp -= 4;
FPUSH((int)D(___1de580h+0xcc));
F32(esp) = (float)FPOP();
___4a064h_cdecl(eax, D(esp), D(esp+4), D(esp+8));
esp += 0xc;
FPUSH((int)D(___1e6ed0h+0xc+2*0x35e));
ST(0) = ST(0)*3.75;
H(ebx) = 1;
FPUSH(F32(___1e6ed0h+0xb4+2*0x35e));
FPUSH(F32(___1e6ed0h+0xb8+2*0x35e));
FPUSH((int)D(___1de580h+0x168));
edx = D(___1e6ed0h+0xc+2*0x35e);
esp -= 4;
eax = 4*edx;
d_tmp = ST(0); ST(0) = ST(2); ST(2) = d_tmp;
F32(___1e6ed0h+0x14e +2*0x35e) = (float)FPOP();
eax -= edx;
F32(___1e6ed0h+0x152+2*0x35e) = (float)FPOP();
eax <<= 3;
B(___1e6ed0h+0x108+2*0x35e) = H(ebx);
eax += edx;
D(___1e6ed0h+0x34a+0x35e) = ecx;
eax <<= 6;
d_tmp = ST(0); ST(0) = ST(1); ST(1) = d_tmp;
F32(___1e6ed0h+0xac+2*0x35e) = (float)FPOP();
eax += 0x4b000;
FPUSH(F32(___1e6ed0h+0xac+2*0x35e));
D(___1e6ed0h+0x10+2*0x35e) = eax;
L(eax) = 3;
F32(___1e6ed0h+0x156+2*0x35e) = (float)FPOP();
B(___1e6ed0h+0x109+2*0x35e) = L(eax);
F32(esp) = (float)FPOP();
esp -= 4;
FPUSH((int)D(___1de580h+0x164));
F32(esp) = (float)FPOP();
eax = 0x23;
esp -= 4;
FPUSH((int)D(___1de580h+0x160));
F32(esp) = (float)FPOP();
___4a064h_cdecl(eax, D(esp), D(esp+4), D(esp+8));
esp += 0xc;
FPUSH((int)D(___1e6ed0h+0xc+3*0x35e));
ST(0) = ST(0)*3.75;
FPUSH(F32(___1e6ed0h+0xb4+3*0x35e));
FPUSH(F32(___1e6ed0h+0xb8+3*0x35e));
FPUSH((int)D(___1de580h+0x1fc));
esp -= 4;
edx = D(___1e6ed0h+0xc+3*0x35e);
d_tmp = ST(0); ST(0) = ST(2); ST(2) = d_tmp;
F32(___1e6ed0h+0x14e +3*0x35e) = (float)FPOP();
F32(___1e6ed0h+0x152+3*0x35e) = (float)FPOP();
B(___1e6ed0h+0x108+3*0x35e) = H(ebx);
eax = 4*edx;
D(___1e6ed0h+0x34a+3*0x35e) = ecx;
eax -= edx;
d_tmp = ST(0); ST(0) = ST(1); ST(1) = d_tmp;
F32(___1e6ed0h+0xac+3*0x35e) = (float)FPOP();
eax <<= 3;
FPUSH(F32(___1e6ed0h+0xac+3*0x35e));
eax += edx;
F32(___1e6ed0h+0x156+3*0x35e) = (float)FPOP();
eax <<= 6;
L(edx) = 4;
eax += 0x70800;
B(___1e6ed0h+0x109+3*0x35e) = L(edx);
D(___1e6ed0h+0x10+3*0x35e) = eax;
F32(esp) = (float)FPOP();
edi = 0x40;
esp -= 4;
FPUSH((int)D(___1de580h+0x1f8));
F32(esp) = (float)FPOP();
eax = 0x2d;
esp -= 4;
FPUSH((int)D(___1de580h+0x1f4));
F32(esp) = (float)FPOP();
esi = 0x3c;
___4a064h_cdecl(eax, D(esp), D(esp+4), D(esp+8));
esp += 0xc;
D(esp) = ecx;
D(esp+4) = ecx;
___4a505h:
eax = 0x35e*ecx;
edx = 0;
D(eax+___1e6ed0h+0x19a) = edx;
edx = D(esp+4);
edx = 0x1388*D(edx+___1de7d0h+0x14);
ebp = 0;
D(eax+___1e6ed0h) = ebp;
D(eax+___1e6ed0h+0xb0) = ebp;
D(eax+___1e6ed0h+0x10a) = ebp;
D(eax+___1e6ed0h+0x18a) = ebp;
D(eax+___1e6ed0h+0x14) = ebp;
D(eax+___1e6ed0h+0x18) = ebp;
edx += 0x3a98;
D(eax+___1e6ed0h+0x19e) = edx;
edx = D(esp);
D(eax+___1e6ed0h+0x1c) = ebp;
ebx = D(edx+___1de580h+0x14);
D(eax+___1e6ed0h+0xa8) = ebx;
edx = edi;
___4a56ah:
ebx = 0;
D(eax+___1e6ed0h+0x20) = ebx;
eax += 4;
if(eax != edx) goto ___4a56ah;
edx = 0x35e*ecx;
ebx = edi;
eax = edx;
___4a583h:
eax += 4;
ebp = 0;
D(eax+___1e6ed0h+0x5c) = ebp;
if(eax != ebx) goto ___4a583h;
D(edx+___1e6ed0h+0xbc) = ebp;
D(edx+___1e6ed0h+0xc0) = ebp;
D(edx+___1e6ed0h+0xfc) = ebp;
D(edx+___1e6ed0h+0x100) = ebp;
D(edx+___1e6ed0h+0x104) = ebp;
D(edx+___1e6ed0h+0x17e) = ebp;
D(edx+___1e6ed0h+0x182) = ebp;
D(edx+___1e6ed0h+0x186) = ebp;
D(edx+___1e6ed0h+0x192) = ebp;
D(edx+___1e6ed0h+0x196) = ebp;
D(edx+___1e6ed0h+0x162) = ebp;
D(edx+___1e6ed0h+0x166) = ebp;
D(edx+___1e6ed0h+0x16a) = ebp;
D(edx+___1e6ed0h+0x16e) = ebp;
D(edx+___1e6ed0h+0x1a6) = ebp;
D(edx+___1e6ed0h+0x1a2) = ebp;
D(edx+___1e6ed0h+0x1aa) = ebp;
D(edx+___1e6ed0h+0x1ae) = ebp;
eax ^= ebx;
D(edx+___1e6ed0h+0x1b2) = ebp;
D(edx+___1e6ed0h+0xa0) = eax;
D(edx+___1e6ed0h+0xa4) = eax;
edx = esi;
eax = 0x35e*ecx;
___4a61ah:
eax += 4;
ebp = 0;
D(eax+___1e6ed0h+0x1de) = ebp;
if(eax != edx) goto ___4a61ah;
ebx = 0x35e*ecx;
edx = esi;
eax = ebx;
___4a633h:
eax += 4;
ebp = 0;
D(eax+___1e6ed0h+0x21a) = ebp;
if(eax != edx) goto ___4a633h;
D(ebx+___1e6ed0h+0x1b6) = ebp;
D(ebx+___1e6ed0h+0x1da) = ebp;
D(ebx+___1e6ed0h+0x1de) = ebp;
eax = 0xf;
D(ebx+___1e6ed0h+0x34e) = ebp;
edi += 0x35e;
D(ebx+___1e6ed0h+0x352) = ebp;
esi += 0x35e;
D(ebx+___1e6ed0h+0x356) = ebp;
ecx++;
D(ebx+___1e6ed0h+0x35a) = ebp;
ebx = D(esp);
ebp = D(esp+4);
D(___243d08h) = eax;
ebx += 0x94;
ebp += 0x54;
D(esp) = ebx;
D(esp+4) = ebp;
if((int)ecx < 4) goto ___4a505h;
D(___243c60h) = ecx;
return;
}
|
1stmateusz/motech
|
platform/mds/mds/src/test/java/org/motechproject/mds/annotations/internal/LookupProcessorTest.java
|
package org.motechproject.mds.annotations.internal;
import com.thoughtworks.paranamer.Paranamer;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.motechproject.commons.api.Range;
import org.motechproject.commons.date.model.Time;
import org.motechproject.mds.annotations.Lookup;
import org.motechproject.mds.annotations.LookupField;
import org.motechproject.mds.annotations.RestExposed;
import org.motechproject.mds.dto.AdvancedSettingsDto;
import org.motechproject.mds.dto.EntityDto;
import org.motechproject.mds.dto.FieldDto;
import org.motechproject.mds.dto.LookupDto;
import org.motechproject.mds.dto.LookupFieldDto;
import org.motechproject.mds.dto.RestOptionsDto;
import org.motechproject.mds.dto.SchemaHolder;
import org.motechproject.mds.dto.TypeDto;
import org.motechproject.mds.exception.lookup.LookupWrongParameterTypeException;
import org.reflections.Reflections;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static ch.lambdaj.Lambda.extract;
import static ch.lambdaj.Lambda.on;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.motechproject.mds.dto.LookupFieldType.RANGE;
import static org.motechproject.mds.dto.LookupFieldType.SET;
import static org.motechproject.mds.dto.LookupFieldType.VALUE;
import static org.motechproject.mds.testutil.FieldTestHelper.lookupFieldDto;
import static org.motechproject.mds.testutil.FieldTestHelper.lookupFieldDtos;
public class LookupProcessorTest {
@Mock
private Reflections reflections;
@Mock
private Paranamer paranamer;
@Mock
private SchemaHolder schemaHolder;
@InjectMocks
private LookupProcessor lookupProcessor;
private String[] argNames = {"arg0", "arg1", "arg2"};
private static final String TEST_CLASS_NAME = TestClass.class.getName();
@Before
public void setUp() throws NoSuchMethodException {
lookupProcessor = new LookupProcessor();
lookupProcessor.setSchemaHolder(schemaHolder);
initMocks(this);
}
private EntityProcessorOutput mockEntityProcessorOutput(EntityDto entity, List<FieldDto> fields) {
EntityProcessorOutput output = new EntityProcessorOutput();
output.setEntityProcessingResult(entity);
output.setFieldProcessingResult(fields);
return output;
}
@Test
public void shouldProcessMethodWithLookupFields() throws NoSuchMethodException {
FieldDto arg1Field = new FieldDto("arg1", "Arg1", TypeDto.INTEGER);
FieldDto secondArgumentField = new FieldDto("secondArgument", "Second Argument", TypeDto.STRING);
lookupProcessor.setEntityProcessingResult
(Arrays.asList(mockEntityProcessorOutput(new EntityDto(TestClass.class.getName()),
Arrays.asList(arg1Field, secondArgumentField))));
when(paranamer.lookupParameterNames(getTestMethod(1))).thenReturn(argNames);
Method method = getTestMethod(1);
lookupProcessor.process(method);
Map<String, List<LookupDto>> elements = lookupProcessor.getProcessingResult();
assertTrue(elements.containsKey(TEST_CLASS_NAME));
List<LookupDto> list = elements.get(TEST_CLASS_NAME);
LookupDto expected = new LookupDto("Test Method 1", true, false,
asList(lookupFieldDto("arg1"), lookupFieldDto("secondArgument", "LIKE")), true, "testMethod1", asList("arg1", "secondArgument"), true);
assertEquals(1, list.size());
assertEquals(expected, list.get(0));
}
@Test (expected = LookupWrongParameterTypeException.class)
public void shouldNotProcessMethodWithLookupFieldsWithWrongType() throws NoSuchMethodException {
FieldDto arg1Field = new FieldDto("arg1", "Arg1", TypeDto.STRING);
FieldDto secondArgumentField = new FieldDto("secondArgument", "Second Argument", TypeDto.STRING);
lookupProcessor.setEntityProcessingResult
(Arrays.asList(mockEntityProcessorOutput(new EntityDto(TestClass.class.getName()),
Arrays.asList(arg1Field, secondArgumentField))));
when(paranamer.lookupParameterNames(getTestMethod(1))).thenReturn(argNames);
Method method = getTestMethod(1);
lookupProcessor.process(method);
}
@Test
public void shouldProcessMethodWithNotAnnotatedParameters() throws NoSuchMethodException {
FieldDto arg1Field = new FieldDto("arg1", "Arg1", TypeDto.INTEGER);
FieldDto secondArgumentField = new FieldDto("secondArgument", "Second Argument", TypeDto.STRING);
lookupProcessor.setEntityProcessingResult
(Arrays.asList(mockEntityProcessorOutput(new EntityDto(TestClass.class.getName()),
Arrays.asList(arg1Field, secondArgumentField))));
when(paranamer.lookupParameterNames(getTestMethod(2))).thenReturn(argNames);
Method method = getTestMethod(2);
lookupProcessor.process(method);
Map<String, List<LookupDto>> elements = lookupProcessor.getElements();
assertTrue(elements.containsKey(TEST_CLASS_NAME));
List<LookupDto> list = elements.get(TEST_CLASS_NAME);
LookupDto expected = new LookupDto("Test Method 2", false, false,
lookupFieldDtos(argNames), true, "testMethod2", asList(argNames), true);
assertEquals(1, list.size());
assertEquals(expected, list.get(0));
}
@Test
public void shouldProcessMethodWithCustomLookupName() throws NoSuchMethodException {
lookupProcessor.setEntityProcessingResult
(Arrays.asList(mockEntityProcessorOutput(new EntityDto(TestClass.class.getName()), Collections.EMPTY_LIST)));
when(paranamer.lookupParameterNames(getTestMethod(3))).thenReturn(argNames);
Method method = getTestMethod(3);
LookupDto dto = new LookupDto("My new custom lookup", false, false,
lookupFieldDtos(argNames), true, "testMethod3", asList(argNames), true);
lookupProcessor.process(method);
Map<String, List<LookupDto>> elements = lookupProcessor.getProcessingResult();
assertTrue(elements.containsKey(TEST_CLASS_NAME));
List<LookupDto> list = elements.get(TEST_CLASS_NAME);
assertEquals(1, list.size());
assertEquals(dto, list.get(0));
}
@Test
public void shouldProcessMethodWithRangeParam() throws NoSuchMethodException {
FieldDto arg0Field = new FieldDto("arg0Field", "Arg 0 Field", TypeDto.BOOLEAN);
FieldDto rangeField = new FieldDto("rangeField", "Range Field", TypeDto.STRING);
FieldDto regularFieldField = new FieldDto("regularField", "Regular Field", TypeDto.BOOLEAN);
FieldDto rangeFieldField = new FieldDto("rangeFieldDouble", "Range Field Double", TypeDto.DOUBLE);
EntityProcessorOutput eop = mockEntityProcessorOutput(new EntityDto(TestClass.class.getName()),
Arrays.asList(arg0Field, rangeField, regularFieldField, rangeFieldField));
lookupProcessor.setEntityProcessingResult(Arrays.asList(eop));
LookupFieldDto[][] expectedFields = {{lookupFieldDto("arg0"), lookupFieldDto("range", RANGE)},
{lookupFieldDto("regularField"), lookupFieldDto("rangeField", RANGE)}};
String [][] expectedFieldsOrder = {{"arg0", "range"}, {"regularField", "rangeField"}};
// test two methods, one with @LookupField annotations, second without
for (int i = 0; i < 2; i++) {
Method method = getTestMethodWithRangeParam(i);
when(paranamer.lookupParameterNames(method)).thenReturn(new String[]{"arg0", "range"});
LookupDto expectedLookup = new LookupDto("Test Method With Range Param " + i, false, false,
asList(expectedFields[i]), true, "testMethodWithRangeParam" + i, asList(expectedFieldsOrder[i]), true);
lookupProcessor.process(method);
Map<String, List<LookupDto>> elements = lookupProcessor.getProcessingResult();
assertTrue(elements.containsKey(TEST_CLASS_NAME));
List<LookupDto> list = elements.get(TEST_CLASS_NAME);
assertEquals(1, list.size());
assertEquals(expectedLookup, list.get(0));
assertEquals(asList(VALUE, RANGE), extract(list.get(0).getLookupFields(), on(LookupFieldDto.class).getType()));
lookupProcessor.clear();
}
}
@Test
public void shouldProcessMethodWithSetParam() throws NoSuchMethodException {
FieldDto arg0Field = new FieldDto("arg0Field", "Arg 0 Field", TypeDto.STRING);
FieldDto setField = new FieldDto("setField", "Range Field", TypeDto.STRING);
FieldDto regularField = new FieldDto("regularField", "Regular Field", TypeDto.STRING);
FieldDto setFieldDouble = new FieldDto("setFieldDouble", "Set Field", TypeDto.DOUBLE);
EntityProcessorOutput eop = mockEntityProcessorOutput(new EntityDto(TestClass.class.getName()),
Arrays.asList(arg0Field, setField, regularField, setFieldDouble));
lookupProcessor.setEntityProcessingResult(Arrays.asList(eop));
LookupFieldDto[][] expectedFields = {{lookupFieldDto("arg0"), lookupFieldDto("set", SET)},
{lookupFieldDto("regularField"), lookupFieldDto("setField", SET)}};
String [][] expectedFieldsOrder = {{"arg0", "range"}, {"regularField", "rangeField"}};
// test two methods, one with @LookupField annotations, second without
for (int i = 0; i < 2; i++) {
Method method = getTestMethodWithSetParam(i);
when(paranamer.lookupParameterNames(method)).thenReturn(new String[]{"arg0", "set"});
LookupDto expectedLookup = new LookupDto("Test Method With Set Param " + i, true, false,
asList(expectedFields[i]), true, "testMethodWithSetParam" + i, asList(expectedFieldsOrder[i]), true);
lookupProcessor.process(method);
Map<String, List<LookupDto>> elements = lookupProcessor.getProcessingResult();
assertTrue(elements.containsKey(TEST_CLASS_NAME));
List<LookupDto> list = elements.get(TEST_CLASS_NAME);
assertEquals(1, list.size());
assertEquals(expectedLookup, list.get(0));
assertEquals(asList(VALUE, SET), extract(list.get(0).getLookupFields(), on(LookupFieldDto.class).getType()));
lookupProcessor.clear();
}
}
@Test
public void shouldBreakProcessingWhenEntityNotFound() throws NoSuchMethodException {
when(paranamer.lookupParameterNames(getTestMethod(4))).thenReturn(argNames);
EntityProcessorOutput eop = mockEntityProcessorOutput(new EntityDto(TestClass.class.getName()),
Arrays.asList(new FieldDto("aaa", "bbb", TypeDto.STRING)));
lookupProcessor.setEntityProcessingResult(Arrays.asList(eop));
Method method = getTestMethod(4);
lookupProcessor.process(method);
assertTrue(lookupProcessor.getProcessingResult().isEmpty());
}
@Test
public void shouldReturnCorrectAnnotation() {
assertEquals(Lookup.class, lookupProcessor.getAnnotationType());
}
@Test
public void shouldProcessMethodWithRestExposedAnnotation() throws Exception {
when(paranamer.lookupParameterNames(getTestMethodExposedViaRest())).thenReturn(argNames);
EntityProcessorOutput eop = mockEntityProcessorOutput(new EntityDto(TestClass.class.getName()),
Arrays.asList(new FieldDto("aaa", "bbb", TypeDto.STRING)));
lookupProcessor.setEntityProcessingResult(Arrays.asList(eop));
Method method = getTestMethodExposedViaRest();
LookupDto dto = new LookupDto("Test Method Exposed Via Rest", true, true,
lookupFieldDtos(argNames), true, "testMethodExposedViaRest", asList(argNames), true);
lookupProcessor.process(method);
Map<String, List<LookupDto>> elements = lookupProcessor.getProcessingResult();
assertTrue(elements.containsKey(TEST_CLASS_NAME));
List<LookupDto> list = elements.get(TEST_CLASS_NAME);
assertEquals(1, list.size());
assertEquals(dto, list.get(0));
}
@Test
public void shouldNotUpdateRestExposedValueForLookupsThatHaveThatModifiedByUser() throws Exception {
when(paranamer.lookupParameterNames(getTestMethodExposedViaRest())).thenReturn(argNames);
AdvancedSettingsDto advanced = mock(AdvancedSettingsDto.class);
RestOptionsDto restOptions = mock(RestOptionsDto.class);
when(schemaHolder.getAdvancedSettings(TEST_CLASS_NAME)).thenReturn(advanced);
when(advanced.getRestOptions()).thenReturn(restOptions);
when(restOptions.isModifiedByUser()).thenReturn(true);
EntityProcessorOutput eop = mockEntityProcessorOutput(new EntityDto(TestClass.class.getName()),
Arrays.asList(new FieldDto("aaa", "bbb", TypeDto.STRING)));
lookupProcessor.setEntityProcessingResult(Arrays.asList(eop));
Method method = getTestMethodExposedViaRest();
LookupDto dto = new LookupDto("Test Method Exposed Via Rest", true, false,
lookupFieldDtos(argNames), true, "testMethodExposedViaRest", asList(argNames), true);
lookupProcessor.process(method);
Map<String, List<LookupDto>> elements = lookupProcessor.getProcessingResult();
assertTrue(elements.containsKey(TEST_CLASS_NAME));
List<LookupDto> list = elements.get(TEST_CLASS_NAME);
assertEquals(1, list.size());
assertEquals(dto, list.get(0));
}
@Test
public void shouldNotCreateIndexForLookup() throws Exception {
FieldDto arg1Field = new FieldDto("arg1", "Arg1", TypeDto.INTEGER);
FieldDto secondArgumentField = new FieldDto("secondArgument", "Second Argument", TypeDto.STRING);
lookupProcessor.setEntityProcessingResult
(Arrays.asList(mockEntityProcessorOutput(new EntityDto(TestClass.class.getName()),
Arrays.asList(arg1Field, secondArgumentField))));
when(paranamer.lookupParameterNames(getTestMethod(5))).thenReturn(argNames);
Method method = getTestMethod(5);
lookupProcessor.process(method);
Map<String, List<LookupDto>> elements = lookupProcessor.getProcessingResult();
assertTrue(elements.containsKey(TEST_CLASS_NAME));
List<LookupDto> list = elements.get(TEST_CLASS_NAME);
LookupDto expected = new LookupDto("Test Method 5", true, false,
asList(lookupFieldDto("arg1"), lookupFieldDto("secondArgument", "LIKE")), true, "testMethod5", new ArrayList<>(), false);
assertEquals(1, list.size());
assertEquals(expected, list.get(0));
}
private Method getTestMethod(int number) throws NoSuchMethodException {
return TestClass.class.getMethod("testMethod" + number, String.class, Integer.class, String.class);
}
private Method getTestMethodWithRangeParam(int number) throws NoSuchMethodException {
return TestClass.class.getMethod("testMethodWithRangeParam" + number, Boolean.class, Range.class);
}
private Method getTestMethodWithSetParam(int number) throws NoSuchMethodException {
return TestClass.class.getMethod("testMethodWithSetParam" + number, String.class, Set.class);
}
private Method getTestMethodExposedViaRest() throws NoSuchMethodException {
return TestClass.class.getMethod("testMethodExposedViaRest", String.class, Integer.class, String.class);
}
private class TestClass {
@Lookup
public TestClass testMethod1(String arg0, @LookupField Integer arg1,
@LookupField(name = "secondArgument", customOperator = "LIKE") String arg2) {
return null;
}
@Lookup
public List<TestClass> testMethod2(String arg0, Integer arg1, String arg2) {
return new ArrayList<>();
}
@Lookup(name = "My new custom lookup")
public List<TestClass> testMethod3(String arg0, Integer arg1, String arg2) {
return new ArrayList<>();
}
@Lookup
public Integer testMethod4(String arg0, Integer arg1, String arg2) {
return 42;
}
@Lookup(indexRequired = false)
public TestClass testMethod5(String arg0, @LookupField Integer arg1,
@LookupField(name = "secondArgument", customOperator = "LIKE") String arg2) {
return null;
}
@Lookup
public List<TestClass> testMethodWithRangeParam0(Boolean arg0, Range<DateTime> range) {
return Collections.emptyList();
}
@Lookup
public List<TestClass> testMethodWithRangeParam1(@LookupField(name = "regularField") Boolean arg0,
@LookupField(name = "rangeField") Range<DateTime> range) {
return Collections.emptyList();
}
@Lookup
public TestClass testMethodWithSetParam0(String arg0, Set<Time> set) {
return null;
}
@Lookup
public TestClass testMethodWithSetParam1(@LookupField(name = "regularField") String arg0,
@LookupField(name = "setField") Set<Time> range) {
return null;
}
@Lookup
@RestExposed
public TestClass testMethodExposedViaRest(String arg0, Integer arg1, String arg2) {
return null;
}
}
}
|
ligoj/bootstrap
|
bootstrap-business/src/main/java/org/ligoj/bootstrap/resource/system/DateVo.java
|
/*
* Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
*/
package org.ligoj.bootstrap.resource.system;
import java.util.Date;
import lombok.Getter;
import lombok.Setter;
/**
* Date information.
*/
@Getter
@Setter
public class DateVo {
/**
* Application timezone identifier.
*/
private String timeZone;
/**
* Default timezone identifier.
*/
private String defaultTimeZone;
/**
* Original default timezone identifier.
*/
private String originalDefaultTimeZone;
/**
* System date regarding the application timezone.
*/
private Date date;
}
|
JordanLongstaff/ian
|
src/main/java/com/walkertribe/ian/enums/OtherMessage.java
|
<filename>src/main/java/com/walkertribe/ian/enums/OtherMessage.java
package com.walkertribe.ian.enums;
/**
* Messages that can be sent to civilian NPCs.
* @author rjwut
*/
public enum OtherMessage implements CommsMessage {
HAIL(0),
TURN_TO_HEADING_0(1),
TURN_TO_HEADING_90(2),
TURN_TO_HEADING_180(3),
TURN_TO_HEADING_270(4),
TURN_LEFT_10_DEGREES(5),
TURN_RIGHT_10_DEGREES(6),
TURN_LEFT_25_DEGREES(15),
TURN_RIGHT_25_DEGREES(16),
ATTACK_NEAREST_ENEMY(7),
PROCEED_TO_YOUR_DESTINATION(8),
GO_DEFEND(9) {
@Override
public boolean hasArgument() {
return true;
}
};
/**
* Returns the OtherMessage that corresponds to the given ID.
*/
public static OtherMessage fromId(int id) {
for (OtherMessage message : values()) {
if (message.id == id) {
return message;
}
}
return null;
}
private int id;
OtherMessage(int id) {
this.id = id;
}
@Override
public boolean hasArgument() {
return false;
}
@Override
public int getId() {
return id;
}
@Override
public CommsRecipientType getRecipientType() {
return CommsRecipientType.OTHER;
}
}
|
MotorFu/SplashActivity
|
src/com/zxq/vo/GroupChat.java
|
<gh_stars>0
package com.zxq.vo;
import com.zxq.db.GroupChatProvider;
import com.zxq.util.TimeUtil;
/**
* Created by zxq on 2014/10/31.
*/
public class GroupChat {
public long dateMilliseconds;
public String date;
public String message;
public int come;
public String jid;
public String roomJid;
}
|
GadgetSeed/gadgetseed
|
uilib/dialogbox/netset/netset.c
|
<reponame>GadgetSeed/gadgetseed<filename>uilib/dialogbox/netset/netset.c
/** @file
@brief ネットワーク設定ダイアログボックス
@date 2019.09.01
@author <NAME>
*/
#include "sysconfig.h"
#include "netset.h"
#include "str.h"
#include "font.h"
#include "tprintf.h"
#include "net.h"
#include "lwip/ip.h"
#include "lwip/dns.h"
#include "ui_style.h"
#include "ui_switch.h"
#include "ui_button.h"
#include "ui_edittext.h"
#include "tenkey.h"
#if GSC_GRAPHICS_DISPLAY_WIDTH >= 800
#define UI_SWITCH_WIDTH 96
#define UI_SWITCH_HEIGHT 32
#define NETSET_FONT "num24x32"
#define EDITCHAR_WIDTH 24
#define DEFCHAR_HEIGHT (24 + 4)
#elif GSC_GRAPHICS_DISPLAY_WIDTH >= 480
#define UI_SWITCH_WIDTH 64
#define UI_SWITCH_HEIGHT 24
#define NETSET_FONT "12x16"
#define EDITCHAR_WIDTH 12
#define DEFCHAR_HEIGHT (16 + 4)
#elif GSC_GRAPHICS_DISPLAY_WIDTH >= 320
#define UI_SWITCH_WIDTH 52
#define UI_SWITCH_HEIGHT 24
#define NETSET_FONT "8x16"
#define EDITCHAR_WIDTH 8
#define DEFCHAR_HEIGHT (16 + 4)
#endif
#if GSC_GRAPHICS_DISPLAY_HEIGHT == 480
#define PANEL_Y 40
#define BUTTON_TOP 0
#define BUTTON_HEIGHT 64
#define EDITCHAR_HEIGHT 40
#define IP_TEXT_Y 64
#define IP_ITEM_HEIGHT 72
#define TEXT_AREA_MARGIN 4
#define BTN_POS_Y_SET 372
#elif GSC_GRAPHICS_DISPLAY_HEIGHT == 320
#define PANEL_Y 24
#define BUTTON_TOP 24
#define BUTTON_HEIGHT 48
#define EDITCHAR_HEIGHT 22
#define IP_TEXT_Y 48
#define IP_ITEM_HEIGHT 48
#define TEXT_AREA_MARGIN 3
#define BTN_POS_Y_SET 244
#elif GSC_GRAPHICS_DISPLAY_HEIGHT == 272
#define PANEL_Y 0
#define BUTTON_TOP 0
#define BUTTON_HEIGHT 48
#define EDITCHAR_HEIGHT 22
#define IP_TEXT_Y 48
#define IP_ITEM_HEIGHT 48
#define TEXT_AREA_MARGIN 3
#define BTN_POS_Y_SET (GSC_GRAPHICS_DISPLAY_HEIGHT - BUTTON_HEIGHT - BUTTON_INTERVAL)
#elif GSC_GRAPHICS_DISPLAY_HEIGHT == 240
#define PANEL_Y 0
#define BUTTON_TOP 0
#define BUTTON_HEIGHT 24
#define EDITCHAR_HEIGHT 20
#define IP_TEXT_Y 48
#define IP_ITEM_HEIGHT 46
#define TEXT_AREA_MARGIN 2
#define BTN_POS_Y_SET (GSC_GRAPHICS_DISPLAY_HEIGHT - BUTTON_HEIGHT - BUTTON_INTERVAL)
#endif
#if GSC_GRAPHICS_DISPLAY_WIDTH == 320
#define PANEL_X 0
#define BUTTON_WIDTH 64
#define IPTEXT_X 0
#elif GSC_GRAPHICS_DISPLAY_WIDTH == 480
#define PANEL_X 8
#define BUTTON_WIDTH 96
#define IPTEXT_X 8
#elif GSC_GRAPHICS_DISPLAY_WIDTH == 800
#define PANEL_X 16
#define BUTTON_WIDTH 128
#define IPTEXT_X 8
#else
#define PANEL_X 0
#define BUTTON_WIDTH 48
#define IPTEXT_X 8
#endif
#define BUTTON_LEFT 160
#define BUTTON_INTERVAL 4
#define SET_BUTTON_WIDTH BUTTON_WIDTH
#define CANCEL_BUTTON_WIDTH BUTTON_WIDTH
#define BUTTON_X 16
#define BTN_POS_X_SET (PANEL_X + BUTTON_X + SET_BUTTON_WIDTH + (BUTTON_INTERVAL*2))
#define BTN_POS_X_CANCEL (PANEL_X + BUTTON_X)
#define BTN_POS_Y_CANCEL (BTN_POS_Y_SET)
static struct st_ui_switch uisw_dhcp = {
.id = 1,
.text_area = {
.pos.x = PANEL_X + IPTEXT_X,
.pos.y = PANEL_Y,
.sur.width = UI_SWITCH_WIDTH,
.sur.height = UI_SWITCH_HEIGHT,
},
.font_name = GSC_FONTS_DEFAULT_FONT,
.name = (unsigned char *)"DHCP",
.status = UI_SWITCH_ST_NORMAL,
.value = 0,
};
#define IP_TEXT_WIDTH (EDITCHAR_WIDTH*3)
#define IP_SUBNETMASK_Y (IP_TEXT_Y + IP_ITEM_HEIGHT)
#define IP_DEFAULTGATEWAY_Y (IP_TEXT_Y + IP_ITEM_HEIGHT*2)
#define IP_DNSSERVER_Y (IP_TEXT_Y + IP_ITEM_HEIGHT*3)
uchar ipaddress_str[4][4] = {
"192", "168", "1", "100"
};
static struct st_ui_edittext te_ipaddress[4] = {
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 0),
.pos.y = PANEL_Y + IP_TEXT_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.flg_active = 1,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = ipaddress_str[0],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 1),
.pos.y = PANEL_Y + IP_TEXT_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = ipaddress_str[1],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 2),
.pos.y = PANEL_Y + IP_TEXT_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = ipaddress_str[2],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 3),
.pos.y = PANEL_Y + IP_TEXT_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = ipaddress_str[3],
.max_text_length = 3,
},
};
uchar subnetmask_str[4][4] = {
"255", "255", "255", "0"
};
static struct st_ui_edittext te_subnetmask[4] = {
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 0),
.pos.y = PANEL_Y + IP_SUBNETMASK_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = subnetmask_str[0],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 1),
.pos.y = PANEL_Y + IP_SUBNETMASK_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = subnetmask_str[1],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 2),
.pos.y = PANEL_Y + IP_SUBNETMASK_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = subnetmask_str[2],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 3),
.pos.y = PANEL_Y + IP_SUBNETMASK_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = subnetmask_str[3],
.max_text_length = 3,
},
};
uchar defaultgateway_str[4][4] = {
"192", "168", "1", "1"
};
static struct st_ui_edittext te_defaultgateway[4] = {
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 0),
.pos.y = PANEL_Y + IP_DEFAULTGATEWAY_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = defaultgateway_str[0],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 1),
.pos.y = PANEL_Y + IP_DEFAULTGATEWAY_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = defaultgateway_str[1],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 2),
.pos.y = PANEL_Y + IP_DEFAULTGATEWAY_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = defaultgateway_str[2],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 3),
.pos.y = PANEL_Y + IP_DEFAULTGATEWAY_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = defaultgateway_str[3],
.max_text_length = 3,
},
};
uchar dnsserver_str[4][4] = {
"192", "168", "1", "1"
};
static struct st_ui_edittext te_dnsserver[4] = {
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 0),
.pos.y = PANEL_Y + IP_DNSSERVER_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = dnsserver_str[0],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 1),
.pos.y = PANEL_Y + IP_DNSSERVER_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = dnsserver_str[1],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 2),
.pos.y = PANEL_Y + IP_DNSSERVER_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = dnsserver_str[2],
.max_text_length = 3,
},
{
.view_area = {
.pos.x = PANEL_X + IPTEXT_X + ((IP_TEXT_WIDTH + EDITCHAR_WIDTH*2) * 3),
.pos.y = PANEL_Y + IP_DNSSERVER_Y,
.sur.width = IP_TEXT_WIDTH + (TEXT_AREA_MARGIN * 2),
.sur.height = EDITCHAR_HEIGHT,
},
.text_area_margin = TEXT_AREA_MARGIN,
.font_name = NETSET_FONT,
.flg_enable_multibyte_select = 1,
.text = dnsserver_str[3],
.max_text_length = 3,
},
};
static struct st_ui_edittext *setip_textedit[] = {
&te_ipaddress[0],
&te_ipaddress[1],
&te_ipaddress[2],
&te_ipaddress[3],
&te_subnetmask[0],
&te_subnetmask[1],
&te_subnetmask[2],
&te_subnetmask[3],
&te_defaultgateway[0],
&te_defaultgateway[1],
&te_defaultgateway[2],
&te_defaultgateway[3],
&te_dnsserver[0],
&te_dnsserver[1],
&te_dnsserver[2],
&te_dnsserver[3],
0
};
#define BTN_ID_SET 12
#define BTN_ID_CANCEL 11
static struct st_ui_button ui_btn_set = {
.id = BTN_ID_SET,
.view_area = {
.pos.x = BTN_POS_X_SET,
.pos.y = BTN_POS_Y_SET,
.sur.width = SET_BUTTON_WIDTH,
.sur.height = BUTTON_HEIGHT,
},
.name = "SET",
.status = UI_BUTTON_ST_NORMAL,
};
static struct st_ui_button ui_btn_cancel = {
.id = BTN_ID_CANCEL,
.view_area = {
.pos.x = BTN_POS_X_CANCEL,
.pos.y = BTN_POS_Y_CANCEL,
.sur.width = CANCEL_BUTTON_WIDTH,
.sur.height = BUTTON_HEIGHT,
},
.name = "CANCEL",
.status = UI_BUTTON_ST_NORMAL,
};
static struct st_ui_button *ui_tenbutton_view[] = {
&ui_btn_set,
&ui_btn_cancel,
0
};
static struct st_rect setting_view_area = {
0, 0, GSC_GRAPHICS_DISPLAY_WIDTH, GSC_GRAPHICS_DISPLAY_HEIGHT
};
static struct st_ui_edittext *last_te = 0;
static int flg_enable_dhcp;
static ip_addr_t ipaddress;
static ip_addr_t subnetmask;
static ip_addr_t default_gateway;
static ip_addr_t dns_server[DNS_MAX_SERVERS];
extern struct netif gv_netif;
static void get_network_setting(void)
{
#ifdef GSC_DEV_ENABLE_ETHER
int i;
const ip4_addr_t *addr;
if(dhcp_status() != NET_DHCP_STAT_DISABLE) {
flg_enable_dhcp = 1;
} else {
flg_enable_dhcp = 0;
}
addr = netif_ip4_addr(&gv_netif);
ipaddress.addr = addr->addr;
addr = netif_ip4_netmask(&gv_netif);
subnetmask.addr = addr->addr;
addr = netif_ip4_gw(&gv_netif);
default_gateway.addr = addr->addr;
for(i=0; i<DNS_MAX_SERVERS; i++) {
addr = dns_getserver(i);
dns_server[i].addr = addr->addr;
//tprintf("DNS%d %08X\n", i+1, dns_server[i].addr);
}
#endif
}
static void set_network_setting(void)
{
if(flg_enable_dhcp != 0) {
enable_dhcp();
} else {
int i;
disable_dhcp();
netif_set_addr(&gv_netif,
&ipaddress,
&subnetmask,
&default_gateway);
for(i=0; i<DNS_MAX_SERVERS; i++) {
dns_setserver(i, &dns_server[i]);
}
}
}
#ifdef GSC_COMP_ENABLE_FATFS
#include "appsetting.h"
#ifndef GSC_UI_NETWORK_CONFFILE
#define GSC_UI_NETWORK_CONFFILE "0:network.cfg" /// $gsc ネットワークコンフィグ設定ファイル名
#endif
static struct st_conf_header network_conf[] = {
{ "DHCP", CFGTYPE_INT, &flg_enable_dhcp },
{ "IPADDRESS", CFGTYPE_IPADDRESS, &ipaddress },
{ "SUBNETMASK", CFGTYPE_IPADDRESS, &subnetmask },
{ "DEFAULTGATEWAY", CFGTYPE_IPADDRESS, &default_gateway },
{ "DNSSERVER1", CFGTYPE_IPADDRESS, &dns_server[0] },
{ "DNSSERVER2", CFGTYPE_IPADDRESS, &dns_server[1] },
{ 0, 0, 0 }
};
int load_network_setting(void)
{
int rt = 0;
rt = load_appsetting((uchar *)GSC_UI_NETWORK_CONFFILE, network_conf);
if(rt < 0) {
save_network_setting();
} else {
set_network_setting();
}
return rt;
}
void save_network_setting(void)
{
save_appsetting((uchar *)GSC_UI_NETWORK_CONFFILE, network_conf);
}
#endif // GSC_COMP_ENABLE_FATFS
void prepare_netset(void)
{
int i;
get_network_setting();
uisw_dhcp.value = flg_enable_dhcp;
for(i=0; i<4; i++) {
te_ipaddress[i].flg_uneditable = uisw_dhcp.value;
te_subnetmask[i].flg_uneditable = uisw_dhcp.value;
te_defaultgateway[i].flg_uneditable = uisw_dhcp.value;
te_dnsserver[i].flg_uneditable = uisw_dhcp.value;
}
for(i=0; i<4; i++) {
tsprintf((char *)ipaddress_str[i], "%d", ip4_addr_get_byte_val(ipaddress, i));
tsprintf((char *)subnetmask_str[i], "%d", ip4_addr_get_byte_val(subnetmask, i));
tsprintf((char *)defaultgateway_str[i], "%d", ip4_addr_get_byte_val(default_gateway, i));
tsprintf((char *)dnsserver_str[i], "%d", ip4_addr_get_byte_val(dns_server[0], i));
}
//tprintf("DNS1 = %s.%s.%s.%s\n", dnsserver_str[0], dnsserver_str[1], dnsserver_str[2], dnsserver_str[3]);
}
void draw_netset(void)
{
int i;
set_mode_tenkey(1);
set_forecolor(UI_BACK_COLOR);
draw_fill_rect(&setting_view_area);
set_backcolor(UI_BACK_COLOR);
set_forecolor(UI_NORMAL_FORE_COLOR);
set_draw_mode(GRP_DRAWMODE_NORMAL);
set_font_by_name(GSC_FONTS_DEFAULT_FONT);
draw_str(PANEL_X + IPTEXT_X, PANEL_Y + IP_TEXT_Y - DEFCHAR_HEIGHT, (uchar *)"IP address", 256);
draw_str(PANEL_X + IPTEXT_X, PANEL_Y + IP_SUBNETMASK_Y - DEFCHAR_HEIGHT, (uchar *)"Subnet mask", 256);
draw_str(PANEL_X + IPTEXT_X, PANEL_Y + IP_DEFAULTGATEWAY_Y - DEFCHAR_HEIGHT, (uchar *)"Default gateway", 256);
draw_str(PANEL_X + IPTEXT_X, PANEL_Y + IP_DNSSERVER_Y - DEFCHAR_HEIGHT, (uchar *)"DNS server", 256);
set_font_by_name(NETSET_FONT);
for(i=0; i<3; i++) {
draw_char(te_ipaddress[i].view_area.pos.x + EDITCHAR_WIDTH*4,
te_ipaddress[i].view_area.pos.y + TEXT_AREA_MARGIN, '.');
draw_char(te_subnetmask[i].view_area.pos.x + EDITCHAR_WIDTH*4,
te_subnetmask[i].view_area.pos.y + TEXT_AREA_MARGIN, '.');
draw_char(te_defaultgateway[i].view_area.pos.x + EDITCHAR_WIDTH*4,
te_defaultgateway[i].view_area.pos.y + TEXT_AREA_MARGIN, '.');
draw_char(te_dnsserver[i].view_area.pos.x + EDITCHAR_WIDTH*4,
te_dnsserver[i].view_area.pos.y + TEXT_AREA_MARGIN, '.');
}
draw_ui_switch(&uisw_dhcp);
draw_ui_edittext_list(setip_textedit);
draw_ui_button_list(ui_tenbutton_view);
draw_tenkey();
}
static int str2addr(ip4_addr_t *addr, uchar str[4][4])
{
char addrstr[16];
int rt = 0;
tsprintf(addrstr, "%s.%s.%s.%s", (char *)str[0], (char *)str[1], (char *)str[2], (char *)str[3]);
rt = ip4addr_aton(addrstr, addr);
return rt;
}
static int check_addrstr(uchar *str)
{
int i = dstoi(str);
if(i > 255) {
return -1;
} else {
return 0;
}
}
static int check_addr(struct st_ui_edittext *te)
{
int i;
for(i=0; i<4; i++) {
if(check_addrstr(te->text) != 0) {
select_all_ui_edittext(te);
return -1;
}
te ++;
}
return 0;
}
int proc_netset(struct st_sysevent *event)
{
struct st_button_event obj_evt;
int rt = 0;
rt = proc_ui_switch(&uisw_dhcp, event);
switch(rt) {
case UI_SWITCH_EVT_ON:
uneditable_ui_edittext_list(setip_textedit);
break;
case UI_SWITCH_EVT_OFF:
editable_ui_edittext_list(setip_textedit);
inactivate_ui_edittext_list(setip_textedit);
select_all_ui_edittext(&te_ipaddress[0]);
break;
case UI_SWITCH_EVT_NULL:
default:
break;
}
if(proc_ui_edittext_list(setip_textedit, event, &last_te) != 0) {
// [TODO]
}
if(proc_ui_button_list(&obj_evt, ui_tenbutton_view, event) != 0) {
switch(obj_evt.id) {
case BTN_ID_SET:
if(obj_evt.what == UI_BUTTON_EVT_PULL) {
unactive_ui_edittext_list(setip_textedit);
if(check_addr(te_ipaddress) != 0) {
return 0;
}
if(check_addr(te_subnetmask) != 0) {
return 0;
}
if(check_addr(te_defaultgateway) != 0) {
return 0;
}
if(check_addr(te_dnsserver) != 0) {
return 0;
}
if(str2addr(&ipaddress, ipaddress_str) == 0) {
return 0;
}
if(str2addr(&subnetmask, subnetmask_str) == 0) {
return 0;
}
if(str2addr(&default_gateway, defaultgateway_str) == 0) {
return 0;
}
if(str2addr(&dns_server[0], dnsserver_str) == 0) {
return 0;
}
flg_enable_dhcp = uisw_dhcp.value;
return 1;
}
break;
case BTN_ID_CANCEL:
if(obj_evt.what == UI_BUTTON_EVT_PULL) {
return -1;
}
break;
default:
break;
}
}
if(proc_tenkey(&obj_evt, event) != 0) {
switch(obj_evt.id) {
case BTN_ID_0:
case BTN_ID_1:
case BTN_ID_2:
case BTN_ID_3:
case BTN_ID_4:
case BTN_ID_5:
case BTN_ID_6:
case BTN_ID_7:
case BTN_ID_8:
case BTN_ID_9:
if(obj_evt.what == UI_BUTTON_EVT_PUSH) {
set_char_ui_edittext_list(setip_textedit, '0' + obj_evt.id - BTN_ID_0, 1);
}
break;
case BTN_ID_BACK:
if(obj_evt.what == UI_BUTTON_EVT_PUSH) {
move_cursor_ui_edittext_list(setip_textedit, -1, 1);
}
break;
case BTN_ID_FORWARD:
if(obj_evt.what == UI_BUTTON_EVT_PUSH) {
move_cursor_ui_edittext_list(setip_textedit, 1, 1);
}
break;
case BTN_ID_BACKSPACE:
if(obj_evt.what == UI_BUTTON_EVT_PUSH) {
backspace_char_ui_edittext_list(setip_textedit);
}
break;
case BTN_ID_DELETE:
if(obj_evt.what == UI_BUTTON_EVT_PUSH) {
delete_char_ui_edittext_list(setip_textedit);
}
break;
default:
break;
}
}
return 0;
}
int do_netset(timeset_proc proc)
{
while(1) {
struct st_sysevent event;
int rt = 0;
get_event(&event, 50);
rt = proc_netset(&event);
if(rt != 0) {
return rt;
}
if(proc !=0) {
rt = proc(&event);
}
if(rt != 0) {
return rt;
}
}
return 0;
}
int open_netset_dialog(timeset_proc proc)
{
int rt = 0;
prepare_netset();
draw_netset();
inactivate_ui_edittext_list(setip_textedit);
select_all_ui_edittext(&te_ipaddress[0]);
rt = do_netset(proc);
if(rt == 1) {
set_network_setting();
save_network_setting();
}
return rt;
}
|
NodeNA/nodena-api
|
core/models/index.js
|
import { extend } from 'lodash';
// enable event listeners
import './base/listeners';
/**
* Expose all models
*/
exports = module.exports;
const models = [
'permission',
'post',
'post-meta',
'role',
'tag',
'user',
'author',
'meetup',
'event',
'token',
'reset-log',
'user-event',
'login-attempt',
'image',
'album',
];
function init() {
exports.Base = require('./base');
models.forEach(function (name) {
extend(exports, require('./' + name));
});
}
/**
* Expose `init`
*/
const _init = init;
export { _init as init };
|
CanterburyRegionalCouncil/wab-widgets
|
widgets/SmartEditorEcan/nls/pt-br/strings.js
|
<filename>widgets/SmartEditorEcan/nls/pt-br/strings.js
define({
"_widgetLabel": "Editor Inteligente",
"noEditPrivileges": "Sua conta não tem permissão para criar ou modificar dados.",
"widgetActive": "Ativo",
"widgetNotActive": "Inativo",
"pressStr": "Pressione ",
"ctrlStr": " CTRL ",
"snapStr": " para habilitar o ajuste",
"noAvailableTempaltes": "Nenhum modelo disponível",
"editorCache": " - Cache de Editor",
"presetFieldAlias": "Campo",
"presetValue": "Valor Pré-Configurado",
"usePresetValues": " Utilizar Valores Pré-Configurados (Novas feições somente)",
"editGeometry": " Editar Geometria",
"savePromptTitle": "Salvar feição",
"savePrompt": "Gostaria de salvar a feição atual?",
"deletePromptTitle": "Excluir feição",
"deletePrompt": "Tem certeza que deseja excluir a feição selecionada?",
"attachmentLoadingError": "Erro ao transferir anexos",
"attachmentSaveDeleteWarning": "Aviso: As alterações dos anexos são salvas automaticamente",
"filterEditor": {
"all": "Todos",
"noAvailableTempaltes": "Nenhum modelo disponível",
"searchTemplates": "Pesquisar Modelos"
},
"invalidConfiguration": "O Widget não está configurado ou as camadas na configuração não estão mais no mapa. Abra o aplicativo no modo do construtor e configure novamente o widget."
});
|
DAIAD/utility-mapreduce-
|
src/main/java/eu/daiad/mapreduce/hbase/model/Group.java
|
package eu.daiad.mapreduce.hbase.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.joda.time.DateTimeZone;
public class Group {
private List<String> serial = new ArrayList<String>();
private List<byte[]> serialHash = new ArrayList<byte[]>();
private EnumGroupType type;
private String key;
private DateTimeZone timezone;
public Group(EnumGroupType type, String key, DateTimeZone timezone) {
this.type = type;
this.key = key;
this.timezone = timezone;
}
public void add(String serial, byte[] serialHash) {
this.serial.add(serial);
this.serialHash.add(serialHash);
}
public int indexOf(byte[] serial) {
return inArray(serialHash, serial);
}
public String getSerial(int index) {
return serial.get(index);
}
public EnumGroupType getType() {
return type;
}
public String getKey() {
return key;
}
public DateTimeZone getTimezone() {
return timezone;
}
/**
* Checks if the a byte array is contained in a list of byte arrays.
*
* @param array the list of arrays to search.
* @param hash the array to find.
* @return if the array is contained in the list.
*/
private int inArray(List<byte[]> array, byte[] hash) {
int index = 0;
for (byte[] entry : array) {
if (Arrays.equals(entry, hash)) {
return index;
}
index++;
}
return -1;
}
}
|
frederikspang/ey-cookbooks-stable-v6
|
custom-cookbooks/thinking_sphinx_3/custom-thinking_sphinx_3/attributes/default.rb
|
<reponame>frederikspang/ey-cookbooks-stable-v6<filename>custom-cookbooks/thinking_sphinx_3/custom-thinking_sphinx_3/attributes/default.rb<gh_stars>1-10
# default['sphinx']['utility_name'] = 'sphinx'
# default['sphinx']['applications'] = ['todo']
# default['sphinx']['version'] = '2.2.11-2'
# default['sphinx']['frequency'] = 15
|
devshank3/Open3D
|
src/Cuda/Common/Palatte.h
|
<gh_stars>100-1000
//
// Created by wei on 4/3/19.
//
#pragma once
#include "Common.h"
#include "LinearAlgebraCuda.h"
namespace open3d {
namespace cuda {
__HOSTDEVICE__
inline Vector3f Jet(float v, float vmin, float vmax) {
Vector3f c = Vector3f::Ones();
const float dv = vmax - vmin;
const float inv_dv = 1.0f / dv;
v = v < vmin ? vmin : v;
v = v > vmax ? vmax : v;
if (v < (vmin + 0.25 * dv)) {
c(0) = 0;
c(1) = 4 * (v - vmin) * inv_dv;
} else if (v < (vmin + 0.5 * dv)) {
c(0) = 0;
c(2) = 1 + 4 * (vmin + 0.25 * dv - v) * inv_dv;
} else if (v < (vmin + 0.75 * dv)) {
c(0) = 4 * (v - vmin - 0.5 * dv) * inv_dv;
c(2) = 0;
} else {
c(1) = 1 + 4 * (vmin + 0.75 * dv - v) * inv_dv;
c(2) = 0;
}
return (c);
}
}
}
|
dmcnamee/snc
|
src/snc/simulation/store_data/json_logging.py
|
import logging
from pythonjsonlogger import jsonlogger
def set_up_json_logging():
logger = logging.getLogger()
log_handler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter()
log_handler.setFormatter(formatter)
logger.addHandler(log_handler)
|
supreethavadhani/metadev
|
fm-all/core/src/main/java/org/simplity/fm/core/datatypes/DateType.java
|
/*
* Copyright (c) 2019 simplity.org
*
* 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 org.simplity.fm.core.datatypes;
import java.time.LocalDate;
/**
* validation parameters for a an integral value
*
* @author <EMAIL>
*
*/
public class DateType extends DataType {
private final int maxPastDays;
private final int maxFutureDays;
/**
* @param name
* @param messageId
*
* @param maxPastDays
* 0 means today is OK. 100 means 100 days before today is the
* min, -100 means 100 days after today is the min
* @param maxFutureDays
* 0 means today is OK. -100 means 100 days before today is the
* max. 100 means 100 days after today is the max
*/
public DateType(final String name, final String messageId, final int maxPastDays, final int maxFutureDays) {
this.valueType = ValueType.Date;
this.name = name;
this.messageId = messageId;
this.maxPastDays = maxPastDays;
this.maxFutureDays = maxFutureDays;
}
@Override
public LocalDate parse(final String text) {
try {
if (text.length() >= 10) {
return this.validate(LocalDate.parse(text.substring(0, 10)));
}
return this.validate(LocalDate.ofEpochDay(Long.parseLong(text)));
} catch (final Exception e) {
return null;
}
}
@Override
public LocalDate parse(final Object object) {
if (object instanceof LocalDate) {
return this.validate((LocalDate) object);
}
if (object instanceof String) {
return this.parse((String) object);
}
return null;
}
private LocalDate validate(final LocalDate date) {
final LocalDate today = LocalDate.now();
if (today.plusDays(-this.maxPastDays).isAfter(date)) {
return null;
}
if (today.plusDays(this.maxFutureDays).isBefore(date)) {
return null;
}
return date;
}
}
|
gov466/Embedded-C
|
C program/bill_soft.c
|
#include<stdio.h>
int main()
{
char fud_name;
int price,qty;
printf("enter the dish name: ");
scanf("%s",&fud_name);
printf("enter the price : ");
scanf("%d",&price);
printf("enter the quantity : ");
scanf("%d",&qty);
int sum= qty*price;
printf("%d",sum);
float hst = 13%sum;
printf("%f",hst);
float total= hst+sum;\
printf("%f",hst);
printf("\n Mr Jones\n");
printf(" 1850 Ellesmere Rd\n");
printf("Scarborough, ONT, M1H 2V5\n");
printf("===========================\n");
printf("===========================\n");
printf("SALE(Here)");
printf("===========================\n");
printf("subtotal = %f", total);
printf("HST= %f", hst);
printf("TOTAL = %f", total);
}
|
rmnbhm/wichtelnng
|
src/main/java/com/romanboehm/wichtelnng/data/MonetaryAmount.java
|
package com.romanboehm.wichtelnng.data;
import lombok.Data;
import org.javamoney.moneta.Money;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.math.BigDecimal;
@Data
@Embeddable
public class MonetaryAmount {
@Column(nullable = false, precision = 10, scale = 2)
private BigDecimal number;
@Column(nullable = false, length = 3)
private String currency;
@Override
public String toString() {
return Money.of(number, currency).toString();
}
}
|
suveng/demo
|
kafka/kafka-spring/src/main/java/com/my/qs/kafkademo/consumer/ConsumerKafka.java
|
<reponame>suveng/demo
package com.my.qs.kafkademo.consumer;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
@Service
public class ConsumerKafka {
private static final String TOPIC_NAME = "testTopic";
@Autowired
private KafkaConsumer<String, String> kafkaConsumer;
/**
* 订阅分区
*/
public void assign() {
TopicPartition p0 = new TopicPartition(TOPIC_NAME, 0);
TopicPartition p1 = new TopicPartition(TOPIC_NAME, 1);
kafkaConsumer.assign(Arrays.asList(p0, p1));
}
/**
* 手动提交
*/
public void poll() {
kafkaConsumer.subscribe(Arrays.asList(TOPIC_NAME));
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(1000));
if (!records.isEmpty()) {
for (ConsumerRecord<String, String> record : records) {
System.out.println("offset is:" + record.offset() + ",partition:" + record.partition() + ",key is:"
+ record.key() + ",value is:" + record.value());
}
kafkaConsumer.commitSync();
}
}
}
/**
* 手动分区提交
*/
public void pollByPartition() {
kafkaConsumer.subscribe(Arrays.asList(TOPIC_NAME));
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(1000));
if (!records.isEmpty()) {
for (TopicPartition partition : records.partitions()) {
List<ConsumerRecord<String, String>> recordList = records.records(partition);
for (ConsumerRecord<String, String> record : recordList) {
System.out.println("offset is:" + record.offset() + ",partition:" + record.partition()
+ ",key is:" + record.key() + ",value is:" + record.value());
}
// 根据分区提交offset
Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>();
long offset = recordList.get(recordList.size() - 1).offset();
TopicPartition topicPartition = new TopicPartition(TOPIC_NAME, partition.partition());
OffsetAndMetadata offsetAndMetadata = new OffsetAndMetadata(offset + 1);
offsets.put(topicPartition, offsetAndMetadata);
kafkaConsumer.commitSync(offsets);
}
}
}
}
/**
* 多consumer模式, 一个consumer group中不同的consumer出来不同的partition 资源消耗更大
*/
public void multiConsumer() throws InterruptedException {
List<Thread> threadList = new ArrayList<>();
List<PartitionInfo> partitionInfos = kafkaConsumer.partitionsFor(TOPIC_NAME);
for (int i = 0; i < partitionInfos.size(); i++) {
Consumer consumer = new Consumer();
Thread thread = new Thread(consumer);
thread.start();
threadList.add(thread);
}
// 等待子线程中最后一个线程结束
threadList.get(threadList.size() - 1).join();
}
private static class Consumer implements Runnable {
private final KafkaConsumer<String, String> kafkaConsumer;
private static final String TOPIC_NAME = "testTopic";
public Consumer() {
Properties properties = new Properties();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "172.16.17.32:9092");
properties.put(ConsumerConfig.GROUP_ID_CONFIG, "testGroup");
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
"org.apache.kafka.common.serialization.StringDeserializer");
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
"org.apache.kafka.common.serialization.StringDeserializer");
kafkaConsumer = new KafkaConsumer<>(properties);
kafkaConsumer.subscribe(Arrays.asList(TOPIC_NAME));
}
@Override
public void run() {
System.out.println("thread" + Thread.currentThread().getId() + " start!");
while (true) {
ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofMillis(1000));
if (!consumerRecords.isEmpty()) {
for (ConsumerRecord<String, String> record : consumerRecords) {
System.out.println(
"Thread " + Thread.currentThread().getId() + "offset:" + record.offset() + ",partition:"
+ record.partition() + ",key:" + record.key() + ",value:" + record.value());
}
kafkaConsumer.commitSync();
}
}
}
}
/**
* 一个consumer提取后,分发worker处理 offset难以控制,不知道哪一条失败
*/
public void multiWorker() {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 8, 60, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(4), Executors.defaultThreadFactory(), new failHandler());
kafkaConsumer.subscribe(Arrays.asList(TOPIC_NAME));
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(500));
for (ConsumerRecord<String, String> record : records) {
threadPoolExecutor.execute(new ConsumerWorker(record));
}
kafkaConsumer.commitSync();
}
}
private static class ConsumerWorker implements Runnable {
private final ConsumerRecord<String, String> record;
public ConsumerWorker(ConsumerRecord<String, String> consumerRecord) {
this.record = consumerRecord;
}
public ConsumerRecord<String, String> getRecord() {
return record;
}
@Override
public void run() {
System.out.println("thread " + Thread.currentThread() + ",partition: " + record.partition() + ",key: "
+ record.key() + ",value: " + record.value());
}
}
/**
* 自定义拒绝策略
*/
private static class failHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
ConsumerWorker worker = (ConsumerWorker) r;
ConsumerRecord<String, String> record = worker.getRecord();
System.out.println("partition:" + record.partition() + ",offset:" + record.offset() + " has been rejected");
}
}
}
|
purple-polar-bear/go-ogc-api
|
core/models/route.go
|
<filename>core/models/route.go
package coremodels
type Route interface {
// Name of the route
Name() string
// List of handlers. The indexing string represents the contenttype
Handlers() map[string]Handler
LandingpageVisible() bool
}
|
CuteShaun/frontend-2019-homeworks
|
submissions/vv2529/js-dom/script.js
|
// "getId" is much easier to write :)
function getId(id){return document.getElementById(id)}
const navbar = getId('navbar');
const main = getId('main');
/*
* Events
*/
getId('navbar-toggle').addEventListener('click', function(){
navbar.classList.toggle('shown');
});
navbar.addEventListener('click', function(event){
// delegate clicks from <li>s to <nav>
const elem = event.target;
if(elem.nodeName != 'LI') return;
const title = elem.textContent;
loadData(title, displayData);
navbar.classList.remove('shown');
});
/*
* Functionality
*/
let currentPage = '';
const savedData = {};
function displayData(title){
if(title == currentPage) return;
const data = savedData[title];
if(data){
main.innerHTML = data;
currentPage = title;
}
else showError();
}
function loadData(title, callback){
// Check if requested data is cached
if(title in savedData) callback(title);
else fetch(`data/${title}.json`)
.then(response => response.json())
.then(data => {
// Now we save a string with ready content
savedData[title] = parseData(data);
callback(title);
}, () => {
showError(title);
});
}
function showError(title){
main.innerHTML = parseData({
heading: 'No content!',
paragraphs: [
`No data could be displayed for <q>${title}</q> query, sorry :(`
]
});
}
function parseData(data){
if(!data) return;
let str = `<h1>${data.heading}</h1>`;
data.paragraphs.forEach(item => {
str += `<p>${item}</p>`;
});
return str;
}
/*
* Initiate
*/
loadData('home', displayData);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.