file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
file_path_generator.py
# Copyright 2018-present Facebook, 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 collections import os from artificialproject.field_generators import ( GenerationFailedException, StringGenerator, ) from artificialproject.random import weighted_choice class FilePathGenerator: BUILD_FILE_NAME = "BUCK" def __init__(self): self._component_generator = StringGenerator() self._file_samples = collections.defaultdict( lambda: collections.defaultdict(set) ) self._file_samples_dirty = False self._package_depths = collections.Counter() self._file_depths_in_package = collections.Counter() self._sizes_by_depth = collections.defaultdict(collections.Counter) self._sizes_by_depth_in_package = collections.defaultdict(collections.Counter) self._build_file_sizes = collections.Counter() self._root = {} self._package_paths = {} self._available_directories = {} self._last_package_path = None self._last_package_remaining_targets = None def analyze_project_data(self, project_data): dir_entries = collections.defaultdict(set) build_file_entries = collections.defaultdict(set) for target_data in project_data.values(): base_path = target_data["buck.base_path"] build_file_entries[base_path].add(target_data["name"]) components = self._split_path_into_components(base_path) # TODO(jakubzika): Targets in the root of the repo are ignored # because _generate_path does not handle depth == 0. if components: self._package_depths.update([len(components)]) for component in components: self._component_generator.add_string_sample(component) for i, name in enumerate(components): prefix = components[:i] dir_entries[tuple(prefix)].add(name) for base_path, names in build_file_entries.items(): self._build_file_sizes.update([len(names)]) for path, entries in dir_entries.items(): self._sizes_by_depth[len(path)].update([len(entries)]) def add_package_file_sample(self, package_path, relative_path): components = self._split_path_into_components(relative_path) self._file_depths_in_package.update([len(components)]) for i, name in enumerate(components): prefix = components[:i] self._file_samples[package_path][tuple(prefix)].add(name) self._file_samples_dirty = True def generate_package_path(self): if self._last_package_path is not None: path = self._last_package_path self._last_package_remaining_targets -= 1 if self._last_package_remaining_targets <= 0: self._last_package_path = None return path depth = weighted_choice(self._package_depths) path, parent_dir = self._generate_path( "//", self._root, depth, self._sizes_by_depth, self._component_generator ) directory = {self.BUILD_FILE_NAME.lower(): None} parent_dir[os.path.basename(path).lower()] = directory self._last_package_path = path self._last_package_remaining_targets = ( weighted_choice(self._build_file_sizes) - 1 ) return path def generate_path_in_package( self, package_path, depth, component_generator, extension ): if depth == 0: return "" if self._file_samples_dirty: self._sizes_by_depth_in_package.clear() for dir_entries in self._file_samples.values(): for path, entries in dir_entries.items(): self._sizes_by_depth_in_package[len(path)].update([len(entries)]) self._file_samples_dirty = False root = self._root components = self._split_path_into_components(package_path) for component in components: root = root[component.lower()] path, parent_dir = self._generate_path( package_path, root, depth, self._sizes_by_depth_in_package, component_generator, extension, ) parent_dir[os.path.basename(path).lower()] = None return path def register_path(self, path): directory = self._root existed = True for component in self._split_path_into_components(path): if component not in directory: directory[component] = {} existed = False directory = directory[component] if directory is None: raise GenerationFailedException() if existed: raise GenerationFailedException() def _split_path_into_components(self, path): components = [] while path: path, component = os.path.split(path) components.append(component) return components[::-1] def _generate_path( self, package_key, root, depth, sizes_by_depth, component_generator, extension=None, ): assert depth >= 1 parent_path, parent_dir = self._generate_parent( package_key, root, depth - 1, sizes_by_depth, component_generator ) name = self._generate_name(parent_dir, component_generator, extension) return os.path.join(parent_path, name), parent_dir def _generate_parent( self, package_key, root, depth, sizes_by_depth, component_generator ): if depth == 0: return "", root key = (package_key, depth) value = self._available_directories.get(key) if value is not None: key_found = True path, directory, size = value else: key_found = False parent_path, parent_dir = self._generate_parent( package_key, root, depth - 1, sizes_by_depth, component_generator ) name = self._generate_name(parent_dir, component_generator) path = os.path.join(parent_path, name) directory = {} parent_dir[name.lower()] = directory size = weighted_choice(sizes_by_depth[depth]) size -= 1 if size > 0: self._available_directories[key] = (path, directory, size)
return path, directory def _generate_name(self, directory, generator, extension=None): for i in range(1000): name = generator.generate_string() if extension is not None: name += extension if ( name.lower() not in directory and name.lower() != self.BUILD_FILE_NAME.lower() ): return name raise GenerationFailedException()
elif key_found: del self._available_directories[key]
random_line_split
file_path_generator.py
# Copyright 2018-present Facebook, 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 collections import os from artificialproject.field_generators import ( GenerationFailedException, StringGenerator, ) from artificialproject.random import weighted_choice class FilePathGenerator: BUILD_FILE_NAME = "BUCK" def __init__(self): self._component_generator = StringGenerator() self._file_samples = collections.defaultdict( lambda: collections.defaultdict(set) ) self._file_samples_dirty = False self._package_depths = collections.Counter() self._file_depths_in_package = collections.Counter() self._sizes_by_depth = collections.defaultdict(collections.Counter) self._sizes_by_depth_in_package = collections.defaultdict(collections.Counter) self._build_file_sizes = collections.Counter() self._root = {} self._package_paths = {} self._available_directories = {} self._last_package_path = None self._last_package_remaining_targets = None def analyze_project_data(self, project_data): dir_entries = collections.defaultdict(set) build_file_entries = collections.defaultdict(set) for target_data in project_data.values(): base_path = target_data["buck.base_path"] build_file_entries[base_path].add(target_data["name"]) components = self._split_path_into_components(base_path) # TODO(jakubzika): Targets in the root of the repo are ignored # because _generate_path does not handle depth == 0. if components: self._package_depths.update([len(components)]) for component in components: self._component_generator.add_string_sample(component) for i, name in enumerate(components): prefix = components[:i] dir_entries[tuple(prefix)].add(name) for base_path, names in build_file_entries.items(): self._build_file_sizes.update([len(names)]) for path, entries in dir_entries.items(): self._sizes_by_depth[len(path)].update([len(entries)]) def add_package_file_sample(self, package_path, relative_path): components = self._split_path_into_components(relative_path) self._file_depths_in_package.update([len(components)]) for i, name in enumerate(components): prefix = components[:i] self._file_samples[package_path][tuple(prefix)].add(name) self._file_samples_dirty = True def generate_package_path(self): if self._last_package_path is not None: path = self._last_package_path self._last_package_remaining_targets -= 1 if self._last_package_remaining_targets <= 0: self._last_package_path = None return path depth = weighted_choice(self._package_depths) path, parent_dir = self._generate_path( "//", self._root, depth, self._sizes_by_depth, self._component_generator ) directory = {self.BUILD_FILE_NAME.lower(): None} parent_dir[os.path.basename(path).lower()] = directory self._last_package_path = path self._last_package_remaining_targets = ( weighted_choice(self._build_file_sizes) - 1 ) return path def generate_path_in_package( self, package_path, depth, component_generator, extension ): if depth == 0: return "" if self._file_samples_dirty: self._sizes_by_depth_in_package.clear() for dir_entries in self._file_samples.values(): for path, entries in dir_entries.items(): self._sizes_by_depth_in_package[len(path)].update([len(entries)]) self._file_samples_dirty = False root = self._root components = self._split_path_into_components(package_path) for component in components: root = root[component.lower()] path, parent_dir = self._generate_path( package_path, root, depth, self._sizes_by_depth_in_package, component_generator, extension, ) parent_dir[os.path.basename(path).lower()] = None return path def register_path(self, path): directory = self._root existed = True for component in self._split_path_into_components(path): if component not in directory: directory[component] = {} existed = False directory = directory[component] if directory is None: raise GenerationFailedException() if existed: raise GenerationFailedException() def _split_path_into_components(self, path): components = [] while path: path, component = os.path.split(path) components.append(component) return components[::-1] def
( self, package_key, root, depth, sizes_by_depth, component_generator, extension=None, ): assert depth >= 1 parent_path, parent_dir = self._generate_parent( package_key, root, depth - 1, sizes_by_depth, component_generator ) name = self._generate_name(parent_dir, component_generator, extension) return os.path.join(parent_path, name), parent_dir def _generate_parent( self, package_key, root, depth, sizes_by_depth, component_generator ): if depth == 0: return "", root key = (package_key, depth) value = self._available_directories.get(key) if value is not None: key_found = True path, directory, size = value else: key_found = False parent_path, parent_dir = self._generate_parent( package_key, root, depth - 1, sizes_by_depth, component_generator ) name = self._generate_name(parent_dir, component_generator) path = os.path.join(parent_path, name) directory = {} parent_dir[name.lower()] = directory size = weighted_choice(sizes_by_depth[depth]) size -= 1 if size > 0: self._available_directories[key] = (path, directory, size) elif key_found: del self._available_directories[key] return path, directory def _generate_name(self, directory, generator, extension=None): for i in range(1000): name = generator.generate_string() if extension is not None: name += extension if ( name.lower() not in directory and name.lower() != self.BUILD_FILE_NAME.lower() ): return name raise GenerationFailedException()
_generate_path
identifier_name
file_path_generator.py
# Copyright 2018-present Facebook, 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 collections import os from artificialproject.field_generators import ( GenerationFailedException, StringGenerator, ) from artificialproject.random import weighted_choice class FilePathGenerator: BUILD_FILE_NAME = "BUCK" def __init__(self): self._component_generator = StringGenerator() self._file_samples = collections.defaultdict( lambda: collections.defaultdict(set) ) self._file_samples_dirty = False self._package_depths = collections.Counter() self._file_depths_in_package = collections.Counter() self._sizes_by_depth = collections.defaultdict(collections.Counter) self._sizes_by_depth_in_package = collections.defaultdict(collections.Counter) self._build_file_sizes = collections.Counter() self._root = {} self._package_paths = {} self._available_directories = {} self._last_package_path = None self._last_package_remaining_targets = None def analyze_project_data(self, project_data): dir_entries = collections.defaultdict(set) build_file_entries = collections.defaultdict(set) for target_data in project_data.values(): base_path = target_data["buck.base_path"] build_file_entries[base_path].add(target_data["name"]) components = self._split_path_into_components(base_path) # TODO(jakubzika): Targets in the root of the repo are ignored # because _generate_path does not handle depth == 0. if components: self._package_depths.update([len(components)]) for component in components: self._component_generator.add_string_sample(component) for i, name in enumerate(components): prefix = components[:i] dir_entries[tuple(prefix)].add(name) for base_path, names in build_file_entries.items(): self._build_file_sizes.update([len(names)]) for path, entries in dir_entries.items(): self._sizes_by_depth[len(path)].update([len(entries)]) def add_package_file_sample(self, package_path, relative_path): components = self._split_path_into_components(relative_path) self._file_depths_in_package.update([len(components)]) for i, name in enumerate(components): prefix = components[:i] self._file_samples[package_path][tuple(prefix)].add(name) self._file_samples_dirty = True def generate_package_path(self): if self._last_package_path is not None: path = self._last_package_path self._last_package_remaining_targets -= 1 if self._last_package_remaining_targets <= 0: self._last_package_path = None return path depth = weighted_choice(self._package_depths) path, parent_dir = self._generate_path( "//", self._root, depth, self._sizes_by_depth, self._component_generator ) directory = {self.BUILD_FILE_NAME.lower(): None} parent_dir[os.path.basename(path).lower()] = directory self._last_package_path = path self._last_package_remaining_targets = ( weighted_choice(self._build_file_sizes) - 1 ) return path def generate_path_in_package( self, package_path, depth, component_generator, extension ): if depth == 0: return "" if self._file_samples_dirty: self._sizes_by_depth_in_package.clear() for dir_entries in self._file_samples.values(): for path, entries in dir_entries.items(): self._sizes_by_depth_in_package[len(path)].update([len(entries)]) self._file_samples_dirty = False root = self._root components = self._split_path_into_components(package_path) for component in components: root = root[component.lower()] path, parent_dir = self._generate_path( package_path, root, depth, self._sizes_by_depth_in_package, component_generator, extension, ) parent_dir[os.path.basename(path).lower()] = None return path def register_path(self, path):
def _split_path_into_components(self, path): components = [] while path: path, component = os.path.split(path) components.append(component) return components[::-1] def _generate_path( self, package_key, root, depth, sizes_by_depth, component_generator, extension=None, ): assert depth >= 1 parent_path, parent_dir = self._generate_parent( package_key, root, depth - 1, sizes_by_depth, component_generator ) name = self._generate_name(parent_dir, component_generator, extension) return os.path.join(parent_path, name), parent_dir def _generate_parent( self, package_key, root, depth, sizes_by_depth, component_generator ): if depth == 0: return "", root key = (package_key, depth) value = self._available_directories.get(key) if value is not None: key_found = True path, directory, size = value else: key_found = False parent_path, parent_dir = self._generate_parent( package_key, root, depth - 1, sizes_by_depth, component_generator ) name = self._generate_name(parent_dir, component_generator) path = os.path.join(parent_path, name) directory = {} parent_dir[name.lower()] = directory size = weighted_choice(sizes_by_depth[depth]) size -= 1 if size > 0: self._available_directories[key] = (path, directory, size) elif key_found: del self._available_directories[key] return path, directory def _generate_name(self, directory, generator, extension=None): for i in range(1000): name = generator.generate_string() if extension is not None: name += extension if ( name.lower() not in directory and name.lower() != self.BUILD_FILE_NAME.lower() ): return name raise GenerationFailedException()
directory = self._root existed = True for component in self._split_path_into_components(path): if component not in directory: directory[component] = {} existed = False directory = directory[component] if directory is None: raise GenerationFailedException() if existed: raise GenerationFailedException()
identifier_body
_text.js
/* global Fae, SimpleMDE, toolbarBuiltInButtons */ /** * Fae form text * @namespace form.text * @memberof form */ Fae.form.text = { init: function() { this.overrideMarkdownDefaults(); this.initMarkdown(); }, /** * Override SimpleMDE's preference for font-awesome icons and use a modal for the guide * @see {@link modals.markdownModal} */ overrideMarkdownDefaults: function() { toolbarBuiltInButtons['bold'].className = 'icon-bold'; toolbarBuiltInButtons['italic'].className = 'icon-italic'; toolbarBuiltInButtons['heading'].className = 'icon-font'; toolbarBuiltInButtons['code'].className = 'icon-code'; toolbarBuiltInButtons['unordered-list'].className = 'icon-list-ul'; toolbarBuiltInButtons['ordered-list'].className = 'icon-list-ol'; toolbarBuiltInButtons['link'].className = 'icon-link'; toolbarBuiltInButtons['image'].className = 'icon-image'; toolbarBuiltInButtons['quote'].className = 'icon-quote'; toolbarBuiltInButtons['fullscreen'].className = 'icon-fullscreen no-disable no-mobile'; toolbarBuiltInButtons['horizontal-rule'].className = 'icon-minus'; toolbarBuiltInButtons['preview'].className = 'icon-eye no-disable'; toolbarBuiltInButtons['side-by-side'].className = 'icon-columns no-disable no-mobile'; toolbarBuiltInButtons['guide'].className = 'icon-question'; // Override SimpleMDE's default guide and use a homegrown modal toolbarBuiltInButtons['guide'].action = Fae.modals.markdownModal; }, /** * Find all markdown fields and initialize them with a markdown GUI * @has_test {features/form_helpers/fae_input_spec.rb} */ initMarkdown: function() { $('.js-markdown-editor:not(.mde-enabled)').each(function() {
var editor = new SimpleMDE({ element: this, autoDownloadFontAwesome: false, status: false, spellChecker: false, hideIcons: ['image', 'side-by-side', 'fullscreen', 'preview'] }); // Disable tabbing within editor editor.codemirror.options.extraKeys['Tab'] = false; editor.codemirror.options.extraKeys['Shift-Tab'] = false; $this.addClass('mde-enabled'); // code mirror events to hook into current form element functions editor.codemirror.on('change', function(){ // updates the original textarea's value for JS validations $this.val(editor.value()); // update length counter Fae.form.validator.length_counter.updateCounter($this); }); editor.codemirror.on('focus', function(){ $this.parent().addClass('mde-focus'); }); editor.codemirror.on('blur', function(){ // trigger blur on the original textarea to trigger JS validations $this.blur(); $this.parent().removeClass('mde-focus'); }); }); } };
var $this = $(this);
random_line_split
print_progressbar.py
# -*- coding: utf-8 -*- import sys def print_progress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) barLength - Optional : character length of bar (Int) copied from: http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console With slight adjustment so that it allows just one iteration (total = 0) """ formatStr = "{0:." + str(decimals) + "f}" percent = formatStr.format(100 * (iteration / float(total))) if not total == 0 else formatStr.format(100) filledLength = int(round(barLength * iteration / float(total))) if not total == 0 else int(round(barLength)) bar = '█' * filledLength + '-' * (barLength - filledLength) sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)), if iteration == total: sy
sys.stdout.flush()
s.stdout.write('\n')
conditional_block
print_progressbar.py
# -*- coding: utf-8 -*- import sys def print_progress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100):
""" Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) barLength - Optional : character length of bar (Int) copied from: http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console With slight adjustment so that it allows just one iteration (total = 0) """ formatStr = "{0:." + str(decimals) + "f}" percent = formatStr.format(100 * (iteration / float(total))) if not total == 0 else formatStr.format(100) filledLength = int(round(barLength * iteration / float(total))) if not total == 0 else int(round(barLength)) bar = '█' * filledLength + '-' * (barLength - filledLength) sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)), if iteration == total: sys.stdout.write('\n') sys.stdout.flush()
identifier_body
print_progressbar.py
# -*- coding: utf-8 -*- import sys def
(iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) barLength - Optional : character length of bar (Int) copied from: http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console With slight adjustment so that it allows just one iteration (total = 0) """ formatStr = "{0:." + str(decimals) + "f}" percent = formatStr.format(100 * (iteration / float(total))) if not total == 0 else formatStr.format(100) filledLength = int(round(barLength * iteration / float(total))) if not total == 0 else int(round(barLength)) bar = '█' * filledLength + '-' * (barLength - filledLength) sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)), if iteration == total: sys.stdout.write('\n') sys.stdout.flush()
print_progress
identifier_name
print_progressbar.py
# -*- coding: utf-8 -*- import sys def print_progress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int)
With slight adjustment so that it allows just one iteration (total = 0) """ formatStr = "{0:." + str(decimals) + "f}" percent = formatStr.format(100 * (iteration / float(total))) if not total == 0 else formatStr.format(100) filledLength = int(round(barLength * iteration / float(total))) if not total == 0 else int(round(barLength)) bar = '█' * filledLength + '-' * (barLength - filledLength) sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)), if iteration == total: sys.stdout.write('\n') sys.stdout.flush()
barLength - Optional : character length of bar (Int) copied from: http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console
random_line_split
chart_of_accounts.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe, os, json from frappe.utils import cstr from unidecode import unidecode from six import iteritems def create_charts(company, chart_template=None, existing_company=None): chart = get_chart(chart_template, existing_company) if chart: accounts = [] def _import_accounts(children, parent, root_type, root_account=False):
_import_accounts(chart, None, None, root_account=True) def add_suffix_if_duplicate(account_name, account_number, accounts): if account_number: account_name_in_db = unidecode(" - ".join([account_number, account_name.strip().lower()])) else: account_name_in_db = unidecode(account_name.strip().lower()) if account_name_in_db in accounts: count = accounts.count(account_name_in_db) account_name = account_name + " " + cstr(count) return account_name, account_name_in_db def identify_is_group(child): if child.get("is_group"): is_group = child.get("is_group") elif len(set(child.keys()) - set(["account_type", "root_type", "is_group", "tax_rate", "account_number"])): is_group = 1 else: is_group = 0 return is_group def get_chart(chart_template, existing_company=None): chart = {} if existing_company: return get_account_tree_from_existing_company(existing_company) elif chart_template == "Standard": from erpnext.accounts.doctype.account.chart_of_accounts.verified import standard_chart_of_accounts return standard_chart_of_accounts.get() elif chart_template == "Standard with Numbers": from erpnext.accounts.doctype.account.chart_of_accounts.verified \ import standard_chart_of_accounts_with_account_number return standard_chart_of_accounts_with_account_number.get() else: folders = ("verified",) if frappe.local.flags.allow_unverified_charts: folders = ("verified", "unverified") for folder in folders: path = os.path.join(os.path.dirname(__file__), folder) for fname in os.listdir(path): fname = frappe.as_unicode(fname) if fname.endswith(".json"): with open(os.path.join(path, fname), "r") as f: chart = f.read() if chart and json.loads(chart).get("name") == chart_template: return json.loads(chart).get("tree") @frappe.whitelist() def get_charts_for_country(country, with_standard=False): charts = [] def _get_chart_name(content): if content: content = json.loads(content) if (content and content.get("disabled", "No") == "No") \ or frappe.local.flags.allow_unverified_charts: charts.append(content["name"]) country_code = frappe.db.get_value("Country", country, "code") if country_code: folders = ("verified",) if frappe.local.flags.allow_unverified_charts: folders = ("verified", "unverified") for folder in folders: path = os.path.join(os.path.dirname(__file__), folder) if not os.path.exists(path): continue for fname in os.listdir(path): fname = frappe.as_unicode(fname) if (fname.startswith(country_code) or fname.startswith(country)) and fname.endswith(".json"): with open(os.path.join(path, fname), "r") as f: _get_chart_name(f.read()) # if more than one charts, returned then add the standard if len(charts) != 1 or with_standard: charts += ["Standard", "Standard with Numbers"] return charts def get_account_tree_from_existing_company(existing_company): all_accounts = frappe.get_all('Account', filters={'company': existing_company}, fields = ["name", "account_name", "parent_account", "account_type", "is_group", "root_type", "tax_rate", "account_number"], order_by="lft, rgt") account_tree = {} # fill in tree starting with root accounts (those with no parent) if all_accounts: build_account_tree(account_tree, None, all_accounts) return account_tree def build_account_tree(tree, parent, all_accounts): # find children parent_account = parent.name if parent else "" children = [acc for acc in all_accounts if cstr(acc.parent_account) == parent_account] # if no children, but a group account if not children and parent.is_group: tree["is_group"] = 1 tree["account_number"] = parent.account_number # build a subtree for each child for child in children: # start new subtree tree[child.account_name] = {} # assign account_type and root_type if child.account_number: tree[child.account_name]["account_number"] = child.account_number if child.account_type: tree[child.account_name]["account_type"] = child.account_type if child.tax_rate: tree[child.account_name]["tax_rate"] = child.tax_rate if not parent: tree[child.account_name]["root_type"] = child.root_type # call recursively to build a subtree for current account build_account_tree(tree[child.account_name], child, all_accounts) @frappe.whitelist() def validate_bank_account(coa, bank_account): accounts = [] chart = get_chart(coa) if chart: def _get_account_names(account_master): for account_name, child in iteritems(account_master): if account_name not in ["account_number", "account_type", "root_type", "is_group", "tax_rate"]: accounts.append(account_name) _get_account_names(child) _get_account_names(chart) return (bank_account in accounts)
for account_name, child in iteritems(children): if root_account: root_type = child.get("root_type") if account_name not in ["account_number", "account_type", "root_type", "is_group", "tax_rate"]: account_number = cstr(child.get("account_number")).strip() account_name, account_name_in_db = add_suffix_if_duplicate(account_name, account_number, accounts) is_group = identify_is_group(child) report_type = "Balance Sheet" if root_type in ["Asset", "Liability", "Equity"] \ else "Profit and Loss" account = frappe.get_doc({ "doctype": "Account", "account_name": account_name, "company": company, "parent_account": parent, "is_group": is_group, "root_type": root_type, "report_type": report_type, "account_number": account_number, "account_type": child.get("account_type"), "account_currency": frappe.db.get_value("Company", company, "default_currency"), "tax_rate": child.get("tax_rate") }) if root_account or frappe.local.flags.allow_unverified_charts: account.flags.ignore_mandatory = True account.flags.ignore_permissions = True account.insert() accounts.append(account_name_in_db) _import_accounts(child, account.name, root_type)
identifier_body
chart_of_accounts.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe, os, json from frappe.utils import cstr from unidecode import unidecode from six import iteritems def create_charts(company, chart_template=None, existing_company=None): chart = get_chart(chart_template, existing_company) if chart: accounts = [] def _import_accounts(children, parent, root_type, root_account=False): for account_name, child in iteritems(children): if root_account: root_type = child.get("root_type") if account_name not in ["account_number", "account_type", "root_type", "is_group", "tax_rate"]: account_number = cstr(child.get("account_number")).strip() account_name, account_name_in_db = add_suffix_if_duplicate(account_name, account_number, accounts) is_group = identify_is_group(child) report_type = "Balance Sheet" if root_type in ["Asset", "Liability", "Equity"] \ else "Profit and Loss" account = frappe.get_doc({ "doctype": "Account", "account_name": account_name, "company": company, "parent_account": parent, "is_group": is_group, "root_type": root_type, "report_type": report_type, "account_number": account_number, "account_type": child.get("account_type"), "account_currency": frappe.db.get_value("Company", company, "default_currency"), "tax_rate": child.get("tax_rate") }) if root_account or frappe.local.flags.allow_unverified_charts: account.flags.ignore_mandatory = True account.flags.ignore_permissions = True account.insert() accounts.append(account_name_in_db) _import_accounts(child, account.name, root_type) _import_accounts(chart, None, None, root_account=True) def add_suffix_if_duplicate(account_name, account_number, accounts): if account_number: account_name_in_db = unidecode(" - ".join([account_number, account_name.strip().lower()])) else: account_name_in_db = unidecode(account_name.strip().lower()) if account_name_in_db in accounts: count = accounts.count(account_name_in_db) account_name = account_name + " " + cstr(count) return account_name, account_name_in_db def identify_is_group(child): if child.get("is_group"): is_group = child.get("is_group")
else: is_group = 0 return is_group def get_chart(chart_template, existing_company=None): chart = {} if existing_company: return get_account_tree_from_existing_company(existing_company) elif chart_template == "Standard": from erpnext.accounts.doctype.account.chart_of_accounts.verified import standard_chart_of_accounts return standard_chart_of_accounts.get() elif chart_template == "Standard with Numbers": from erpnext.accounts.doctype.account.chart_of_accounts.verified \ import standard_chart_of_accounts_with_account_number return standard_chart_of_accounts_with_account_number.get() else: folders = ("verified",) if frappe.local.flags.allow_unverified_charts: folders = ("verified", "unverified") for folder in folders: path = os.path.join(os.path.dirname(__file__), folder) for fname in os.listdir(path): fname = frappe.as_unicode(fname) if fname.endswith(".json"): with open(os.path.join(path, fname), "r") as f: chart = f.read() if chart and json.loads(chart).get("name") == chart_template: return json.loads(chart).get("tree") @frappe.whitelist() def get_charts_for_country(country, with_standard=False): charts = [] def _get_chart_name(content): if content: content = json.loads(content) if (content and content.get("disabled", "No") == "No") \ or frappe.local.flags.allow_unverified_charts: charts.append(content["name"]) country_code = frappe.db.get_value("Country", country, "code") if country_code: folders = ("verified",) if frappe.local.flags.allow_unverified_charts: folders = ("verified", "unverified") for folder in folders: path = os.path.join(os.path.dirname(__file__), folder) if not os.path.exists(path): continue for fname in os.listdir(path): fname = frappe.as_unicode(fname) if (fname.startswith(country_code) or fname.startswith(country)) and fname.endswith(".json"): with open(os.path.join(path, fname), "r") as f: _get_chart_name(f.read()) # if more than one charts, returned then add the standard if len(charts) != 1 or with_standard: charts += ["Standard", "Standard with Numbers"] return charts def get_account_tree_from_existing_company(existing_company): all_accounts = frappe.get_all('Account', filters={'company': existing_company}, fields = ["name", "account_name", "parent_account", "account_type", "is_group", "root_type", "tax_rate", "account_number"], order_by="lft, rgt") account_tree = {} # fill in tree starting with root accounts (those with no parent) if all_accounts: build_account_tree(account_tree, None, all_accounts) return account_tree def build_account_tree(tree, parent, all_accounts): # find children parent_account = parent.name if parent else "" children = [acc for acc in all_accounts if cstr(acc.parent_account) == parent_account] # if no children, but a group account if not children and parent.is_group: tree["is_group"] = 1 tree["account_number"] = parent.account_number # build a subtree for each child for child in children: # start new subtree tree[child.account_name] = {} # assign account_type and root_type if child.account_number: tree[child.account_name]["account_number"] = child.account_number if child.account_type: tree[child.account_name]["account_type"] = child.account_type if child.tax_rate: tree[child.account_name]["tax_rate"] = child.tax_rate if not parent: tree[child.account_name]["root_type"] = child.root_type # call recursively to build a subtree for current account build_account_tree(tree[child.account_name], child, all_accounts) @frappe.whitelist() def validate_bank_account(coa, bank_account): accounts = [] chart = get_chart(coa) if chart: def _get_account_names(account_master): for account_name, child in iteritems(account_master): if account_name not in ["account_number", "account_type", "root_type", "is_group", "tax_rate"]: accounts.append(account_name) _get_account_names(child) _get_account_names(chart) return (bank_account in accounts)
elif len(set(child.keys()) - set(["account_type", "root_type", "is_group", "tax_rate", "account_number"])): is_group = 1
random_line_split
chart_of_accounts.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe, os, json from frappe.utils import cstr from unidecode import unidecode from six import iteritems def create_charts(company, chart_template=None, existing_company=None): chart = get_chart(chart_template, existing_company) if chart: accounts = [] def _import_accounts(children, parent, root_type, root_account=False): for account_name, child in iteritems(children): if root_account: root_type = child.get("root_type") if account_name not in ["account_number", "account_type", "root_type", "is_group", "tax_rate"]: account_number = cstr(child.get("account_number")).strip() account_name, account_name_in_db = add_suffix_if_duplicate(account_name, account_number, accounts) is_group = identify_is_group(child) report_type = "Balance Sheet" if root_type in ["Asset", "Liability", "Equity"] \ else "Profit and Loss" account = frappe.get_doc({ "doctype": "Account", "account_name": account_name, "company": company, "parent_account": parent, "is_group": is_group, "root_type": root_type, "report_type": report_type, "account_number": account_number, "account_type": child.get("account_type"), "account_currency": frappe.db.get_value("Company", company, "default_currency"), "tax_rate": child.get("tax_rate") }) if root_account or frappe.local.flags.allow_unverified_charts: account.flags.ignore_mandatory = True account.flags.ignore_permissions = True account.insert() accounts.append(account_name_in_db) _import_accounts(child, account.name, root_type) _import_accounts(chart, None, None, root_account=True) def add_suffix_if_duplicate(account_name, account_number, accounts): if account_number: account_name_in_db = unidecode(" - ".join([account_number, account_name.strip().lower()])) else: account_name_in_db = unidecode(account_name.strip().lower()) if account_name_in_db in accounts: count = accounts.count(account_name_in_db) account_name = account_name + " " + cstr(count) return account_name, account_name_in_db def identify_is_group(child): if child.get("is_group"): is_group = child.get("is_group") elif len(set(child.keys()) - set(["account_type", "root_type", "is_group", "tax_rate", "account_number"])): is_group = 1 else: is_group = 0 return is_group def get_chart(chart_template, existing_company=None): chart = {} if existing_company: return get_account_tree_from_existing_company(existing_company) elif chart_template == "Standard": from erpnext.accounts.doctype.account.chart_of_accounts.verified import standard_chart_of_accounts return standard_chart_of_accounts.get() elif chart_template == "Standard with Numbers": from erpnext.accounts.doctype.account.chart_of_accounts.verified \ import standard_chart_of_accounts_with_account_number return standard_chart_of_accounts_with_account_number.get() else: folders = ("verified",) if frappe.local.flags.allow_unverified_charts: folders = ("verified", "unverified") for folder in folders: path = os.path.join(os.path.dirname(__file__), folder) for fname in os.listdir(path): fname = frappe.as_unicode(fname) if fname.endswith(".json"): with open(os.path.join(path, fname), "r") as f: chart = f.read() if chart and json.loads(chart).get("name") == chart_template: return json.loads(chart).get("tree") @frappe.whitelist() def get_charts_for_country(country, with_standard=False): charts = [] def _get_chart_name(content): if content: content = json.loads(content) if (content and content.get("disabled", "No") == "No") \ or frappe.local.flags.allow_unverified_charts: charts.append(content["name"]) country_code = frappe.db.get_value("Country", country, "code") if country_code: folders = ("verified",) if frappe.local.flags.allow_unverified_charts: folders = ("verified", "unverified") for folder in folders: path = os.path.join(os.path.dirname(__file__), folder) if not os.path.exists(path): continue for fname in os.listdir(path): fname = frappe.as_unicode(fname) if (fname.startswith(country_code) or fname.startswith(country)) and fname.endswith(".json"): with open(os.path.join(path, fname), "r") as f: _get_chart_name(f.read()) # if more than one charts, returned then add the standard if len(charts) != 1 or with_standard: charts += ["Standard", "Standard with Numbers"] return charts def
(existing_company): all_accounts = frappe.get_all('Account', filters={'company': existing_company}, fields = ["name", "account_name", "parent_account", "account_type", "is_group", "root_type", "tax_rate", "account_number"], order_by="lft, rgt") account_tree = {} # fill in tree starting with root accounts (those with no parent) if all_accounts: build_account_tree(account_tree, None, all_accounts) return account_tree def build_account_tree(tree, parent, all_accounts): # find children parent_account = parent.name if parent else "" children = [acc for acc in all_accounts if cstr(acc.parent_account) == parent_account] # if no children, but a group account if not children and parent.is_group: tree["is_group"] = 1 tree["account_number"] = parent.account_number # build a subtree for each child for child in children: # start new subtree tree[child.account_name] = {} # assign account_type and root_type if child.account_number: tree[child.account_name]["account_number"] = child.account_number if child.account_type: tree[child.account_name]["account_type"] = child.account_type if child.tax_rate: tree[child.account_name]["tax_rate"] = child.tax_rate if not parent: tree[child.account_name]["root_type"] = child.root_type # call recursively to build a subtree for current account build_account_tree(tree[child.account_name], child, all_accounts) @frappe.whitelist() def validate_bank_account(coa, bank_account): accounts = [] chart = get_chart(coa) if chart: def _get_account_names(account_master): for account_name, child in iteritems(account_master): if account_name not in ["account_number", "account_type", "root_type", "is_group", "tax_rate"]: accounts.append(account_name) _get_account_names(child) _get_account_names(chart) return (bank_account in accounts)
get_account_tree_from_existing_company
identifier_name
chart_of_accounts.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt import frappe, os, json from frappe.utils import cstr from unidecode import unidecode from six import iteritems def create_charts(company, chart_template=None, existing_company=None): chart = get_chart(chart_template, existing_company) if chart: accounts = [] def _import_accounts(children, parent, root_type, root_account=False): for account_name, child in iteritems(children): if root_account: root_type = child.get("root_type") if account_name not in ["account_number", "account_type", "root_type", "is_group", "tax_rate"]: account_number = cstr(child.get("account_number")).strip() account_name, account_name_in_db = add_suffix_if_duplicate(account_name, account_number, accounts) is_group = identify_is_group(child) report_type = "Balance Sheet" if root_type in ["Asset", "Liability", "Equity"] \ else "Profit and Loss" account = frappe.get_doc({ "doctype": "Account", "account_name": account_name, "company": company, "parent_account": parent, "is_group": is_group, "root_type": root_type, "report_type": report_type, "account_number": account_number, "account_type": child.get("account_type"), "account_currency": frappe.db.get_value("Company", company, "default_currency"), "tax_rate": child.get("tax_rate") }) if root_account or frappe.local.flags.allow_unverified_charts: account.flags.ignore_mandatory = True account.flags.ignore_permissions = True account.insert() accounts.append(account_name_in_db) _import_accounts(child, account.name, root_type) _import_accounts(chart, None, None, root_account=True) def add_suffix_if_duplicate(account_name, account_number, accounts): if account_number: account_name_in_db = unidecode(" - ".join([account_number, account_name.strip().lower()])) else: account_name_in_db = unidecode(account_name.strip().lower()) if account_name_in_db in accounts: count = accounts.count(account_name_in_db) account_name = account_name + " " + cstr(count) return account_name, account_name_in_db def identify_is_group(child): if child.get("is_group"): is_group = child.get("is_group") elif len(set(child.keys()) - set(["account_type", "root_type", "is_group", "tax_rate", "account_number"])): is_group = 1 else: is_group = 0 return is_group def get_chart(chart_template, existing_company=None): chart = {} if existing_company: return get_account_tree_from_existing_company(existing_company) elif chart_template == "Standard": from erpnext.accounts.doctype.account.chart_of_accounts.verified import standard_chart_of_accounts return standard_chart_of_accounts.get() elif chart_template == "Standard with Numbers": from erpnext.accounts.doctype.account.chart_of_accounts.verified \ import standard_chart_of_accounts_with_account_number return standard_chart_of_accounts_with_account_number.get() else: folders = ("verified",) if frappe.local.flags.allow_unverified_charts: folders = ("verified", "unverified") for folder in folders: path = os.path.join(os.path.dirname(__file__), folder) for fname in os.listdir(path): fname = frappe.as_unicode(fname) if fname.endswith(".json"): with open(os.path.join(path, fname), "r") as f: chart = f.read() if chart and json.loads(chart).get("name") == chart_template: return json.loads(chart).get("tree") @frappe.whitelist() def get_charts_for_country(country, with_standard=False): charts = [] def _get_chart_name(content): if content: content = json.loads(content) if (content and content.get("disabled", "No") == "No") \ or frappe.local.flags.allow_unverified_charts: charts.append(content["name"]) country_code = frappe.db.get_value("Country", country, "code") if country_code: folders = ("verified",) if frappe.local.flags.allow_unverified_charts: folders = ("verified", "unverified") for folder in folders: path = os.path.join(os.path.dirname(__file__), folder) if not os.path.exists(path): continue for fname in os.listdir(path): fname = frappe.as_unicode(fname) if (fname.startswith(country_code) or fname.startswith(country)) and fname.endswith(".json"): with open(os.path.join(path, fname), "r") as f: _get_chart_name(f.read()) # if more than one charts, returned then add the standard if len(charts) != 1 or with_standard: charts += ["Standard", "Standard with Numbers"] return charts def get_account_tree_from_existing_company(existing_company): all_accounts = frappe.get_all('Account', filters={'company': existing_company}, fields = ["name", "account_name", "parent_account", "account_type", "is_group", "root_type", "tax_rate", "account_number"], order_by="lft, rgt") account_tree = {} # fill in tree starting with root accounts (those with no parent) if all_accounts: build_account_tree(account_tree, None, all_accounts) return account_tree def build_account_tree(tree, parent, all_accounts): # find children parent_account = parent.name if parent else "" children = [acc for acc in all_accounts if cstr(acc.parent_account) == parent_account] # if no children, but a group account if not children and parent.is_group: tree["is_group"] = 1 tree["account_number"] = parent.account_number # build a subtree for each child for child in children: # start new subtree tree[child.account_name] = {} # assign account_type and root_type if child.account_number: tree[child.account_name]["account_number"] = child.account_number if child.account_type: tree[child.account_name]["account_type"] = child.account_type if child.tax_rate: tree[child.account_name]["tax_rate"] = child.tax_rate if not parent:
# call recursively to build a subtree for current account build_account_tree(tree[child.account_name], child, all_accounts) @frappe.whitelist() def validate_bank_account(coa, bank_account): accounts = [] chart = get_chart(coa) if chart: def _get_account_names(account_master): for account_name, child in iteritems(account_master): if account_name not in ["account_number", "account_type", "root_type", "is_group", "tax_rate"]: accounts.append(account_name) _get_account_names(child) _get_account_names(chart) return (bank_account in accounts)
tree[child.account_name]["root_type"] = child.root_type
conditional_block
borrowed-c-style-enum.rs
// compile-flags:-g // min-lldb-version: 310 // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print *the_a_ref // gdbg-check:$1 = TheA // gdbr-check:$1 = borrowed_c_style_enum::ABC::TheA // gdb-command:print *the_b_ref // gdbg-check:$2 = TheB // gdbr-check:$2 = borrowed_c_style_enum::ABC::TheB // gdb-command:print *the_c_ref // gdbg-check:$3 = TheC // gdbr-check:$3 = borrowed_c_style_enum::ABC::TheC // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print *the_a_ref // lldbg-check:[...]$0 = TheA // lldbr-check:(borrowed_c_style_enum::ABC) *the_a_ref = borrowed_c_style_enum::ABC::TheA // lldb-command:print *the_b_ref // lldbg-check:[...]$1 = TheB // lldbr-check:(borrowed_c_style_enum::ABC) *the_b_ref = borrowed_c_style_enum::ABC::TheB // lldb-command:print *the_c_ref // lldbg-check:[...]$2 = TheC // lldbr-check:(borrowed_c_style_enum::ABC) *the_c_ref = borrowed_c_style_enum::ABC::TheC #![allow(unused_variables)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] enum ABC { TheA, TheB, TheC } fn
() { let the_a = ABC::TheA; let the_a_ref: &ABC = &the_a; let the_b = ABC::TheB; let the_b_ref: &ABC = &the_b; let the_c = ABC::TheC; let the_c_ref: &ABC = &the_c; zzz(); // #break } fn zzz() {()}
main
identifier_name
borrowed-c-style-enum.rs
// compile-flags:-g // min-lldb-version: 310 // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print *the_a_ref // gdbg-check:$1 = TheA // gdbr-check:$1 = borrowed_c_style_enum::ABC::TheA // gdb-command:print *the_b_ref // gdbg-check:$2 = TheB // gdbr-check:$2 = borrowed_c_style_enum::ABC::TheB // gdb-command:print *the_c_ref // gdbg-check:$3 = TheC // gdbr-check:$3 = borrowed_c_style_enum::ABC::TheC // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print *the_a_ref // lldbg-check:[...]$0 = TheA // lldbr-check:(borrowed_c_style_enum::ABC) *the_a_ref = borrowed_c_style_enum::ABC::TheA // lldb-command:print *the_b_ref // lldbg-check:[...]$1 = TheB // lldbr-check:(borrowed_c_style_enum::ABC) *the_b_ref = borrowed_c_style_enum::ABC::TheB // lldb-command:print *the_c_ref // lldbg-check:[...]$2 = TheC // lldbr-check:(borrowed_c_style_enum::ABC) *the_c_ref = borrowed_c_style_enum::ABC::TheC #![allow(unused_variables)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] enum ABC { TheA, TheB, TheC } fn main() { let the_a = ABC::TheA; let the_a_ref: &ABC = &the_a; let the_b = ABC::TheB; let the_b_ref: &ABC = &the_b; let the_c = ABC::TheC; let the_c_ref: &ABC = &the_c; zzz(); // #break } fn zzz()
{()}
identifier_body
borrowed-c-style-enum.rs
// compile-flags:-g // min-lldb-version: 310 // === GDB TESTS =================================================================================== // gdb-command:run // gdb-command:print *the_a_ref
// gdbr-check:$2 = borrowed_c_style_enum::ABC::TheB // gdb-command:print *the_c_ref // gdbg-check:$3 = TheC // gdbr-check:$3 = borrowed_c_style_enum::ABC::TheC // === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print *the_a_ref // lldbg-check:[...]$0 = TheA // lldbr-check:(borrowed_c_style_enum::ABC) *the_a_ref = borrowed_c_style_enum::ABC::TheA // lldb-command:print *the_b_ref // lldbg-check:[...]$1 = TheB // lldbr-check:(borrowed_c_style_enum::ABC) *the_b_ref = borrowed_c_style_enum::ABC::TheB // lldb-command:print *the_c_ref // lldbg-check:[...]$2 = TheC // lldbr-check:(borrowed_c_style_enum::ABC) *the_c_ref = borrowed_c_style_enum::ABC::TheC #![allow(unused_variables)] #![feature(omit_gdb_pretty_printer_section)] #![omit_gdb_pretty_printer_section] enum ABC { TheA, TheB, TheC } fn main() { let the_a = ABC::TheA; let the_a_ref: &ABC = &the_a; let the_b = ABC::TheB; let the_b_ref: &ABC = &the_b; let the_c = ABC::TheC; let the_c_ref: &ABC = &the_c; zzz(); // #break } fn zzz() {()}
// gdbg-check:$1 = TheA // gdbr-check:$1 = borrowed_c_style_enum::ABC::TheA // gdb-command:print *the_b_ref // gdbg-check:$2 = TheB
random_line_split
ext.rs
use std::io; use std::mem; use std::net::SocketAddr; use std::os::unix::io::RawFd; use libc; use sys::unix::err::cvt; #[inline] #[allow(dead_code)] pub fn pipe() -> io::Result<(RawFd, RawFd)> { let mut fds = [0 as libc::c_int; 2]; cvt(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) })?; Ok((fds[0], fds[1])) } #[inline] pub fn socket_v4() -> io::Result<RawFd>
#[inline] pub fn socket_v6() -> io::Result<RawFd> { let res = unsafe { libc::socket( libc::AF_INET6, libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, 0, ) }; cvt(res) } #[inline] pub fn accept(listener_fd: RawFd) -> io::Result<(RawFd, SocketAddr)> { let mut storage: libc::sockaddr_storage = unsafe { mem::uninitialized() }; let mut len = mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t; let res = unsafe { libc::accept4( listener_fd, &mut storage as *mut _ as *mut _, &mut len, libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, ) }; let sock = cvt(res)?; let addr = super::sockaddr_to_addr(&storage, len as usize)?; Ok((sock, addr)) }
{ let res = unsafe { libc::socket( libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, 0, ) }; cvt(res) }
identifier_body
ext.rs
use std::io; use std::mem; use std::net::SocketAddr; use std::os::unix::io::RawFd; use libc; use sys::unix::err::cvt; #[inline] #[allow(dead_code)] pub fn pipe() -> io::Result<(RawFd, RawFd)> { let mut fds = [0 as libc::c_int; 2]; cvt(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) })?; Ok((fds[0], fds[1])) } #[inline] pub fn
() -> io::Result<RawFd> { let res = unsafe { libc::socket( libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, 0, ) }; cvt(res) } #[inline] pub fn socket_v6() -> io::Result<RawFd> { let res = unsafe { libc::socket( libc::AF_INET6, libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, 0, ) }; cvt(res) } #[inline] pub fn accept(listener_fd: RawFd) -> io::Result<(RawFd, SocketAddr)> { let mut storage: libc::sockaddr_storage = unsafe { mem::uninitialized() }; let mut len = mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t; let res = unsafe { libc::accept4( listener_fd, &mut storage as *mut _ as *mut _, &mut len, libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, ) }; let sock = cvt(res)?; let addr = super::sockaddr_to_addr(&storage, len as usize)?; Ok((sock, addr)) }
socket_v4
identifier_name
ext.rs
use std::net::SocketAddr; use std::os::unix::io::RawFd; use libc; use sys::unix::err::cvt; #[inline] #[allow(dead_code)] pub fn pipe() -> io::Result<(RawFd, RawFd)> { let mut fds = [0 as libc::c_int; 2]; cvt(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) })?; Ok((fds[0], fds[1])) } #[inline] pub fn socket_v4() -> io::Result<RawFd> { let res = unsafe { libc::socket( libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, 0, ) }; cvt(res) } #[inline] pub fn socket_v6() -> io::Result<RawFd> { let res = unsafe { libc::socket( libc::AF_INET6, libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, 0, ) }; cvt(res) } #[inline] pub fn accept(listener_fd: RawFd) -> io::Result<(RawFd, SocketAddr)> { let mut storage: libc::sockaddr_storage = unsafe { mem::uninitialized() }; let mut len = mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t; let res = unsafe { libc::accept4( listener_fd, &mut storage as *mut _ as *mut _, &mut len, libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, ) }; let sock = cvt(res)?; let addr = super::sockaddr_to_addr(&storage, len as usize)?; Ok((sock, addr)) }
use std::io; use std::mem;
random_line_split
datestring_convert.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime def
(s): """Convert datetime string which appears in subversion commit log. """ assert type(s) == str, "Argument must be string" dt = s.split() year, month, day = map(int, dt[0].split("-")) hour, minute, second = map(int, dt[1].split(":")) return datetime.datetime(year, month, day, hour, minute, second) if __name__ == '__main__': TEST_1 = "2012-01-14 07:56:02" TEST_2 = "2012-01-14 04:46:30 +0900" d1 = datestring_convert(TEST_1) d2 = datestring_convert(TEST_2) diff = d1 - d2 print("{} ==> {}".format(TEST_1, TEST_2)) print("DIFF: days={}, seconds={}".format(diff.days, diff.seconds)) # vim: set et ts=4 sw=4 cindent fileencoding=utf-8 :
datestring_convert
identifier_name
datestring_convert.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime def datestring_convert(s): """Convert datetime string which appears in subversion commit log. """ assert type(s) == str, "Argument must be string" dt = s.split() year, month, day = map(int, dt[0].split("-")) hour, minute, second = map(int, dt[1].split(":")) return datetime.datetime(year, month, day, hour, minute, second) if __name__ == '__main__':
# vim: set et ts=4 sw=4 cindent fileencoding=utf-8 :
TEST_1 = "2012-01-14 07:56:02" TEST_2 = "2012-01-14 04:46:30 +0900" d1 = datestring_convert(TEST_1) d2 = datestring_convert(TEST_2) diff = d1 - d2 print("{} ==> {}".format(TEST_1, TEST_2)) print("DIFF: days={}, seconds={}".format(diff.days, diff.seconds))
conditional_block
datestring_convert.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime
"""Convert datetime string which appears in subversion commit log. """ assert type(s) == str, "Argument must be string" dt = s.split() year, month, day = map(int, dt[0].split("-")) hour, minute, second = map(int, dt[1].split(":")) return datetime.datetime(year, month, day, hour, minute, second) if __name__ == '__main__': TEST_1 = "2012-01-14 07:56:02" TEST_2 = "2012-01-14 04:46:30 +0900" d1 = datestring_convert(TEST_1) d2 = datestring_convert(TEST_2) diff = d1 - d2 print("{} ==> {}".format(TEST_1, TEST_2)) print("DIFF: days={}, seconds={}".format(diff.days, diff.seconds)) # vim: set et ts=4 sw=4 cindent fileencoding=utf-8 :
def datestring_convert(s):
random_line_split
datestring_convert.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime def datestring_convert(s):
if __name__ == '__main__': TEST_1 = "2012-01-14 07:56:02" TEST_2 = "2012-01-14 04:46:30 +0900" d1 = datestring_convert(TEST_1) d2 = datestring_convert(TEST_2) diff = d1 - d2 print("{} ==> {}".format(TEST_1, TEST_2)) print("DIFF: days={}, seconds={}".format(diff.days, diff.seconds)) # vim: set et ts=4 sw=4 cindent fileencoding=utf-8 :
"""Convert datetime string which appears in subversion commit log. """ assert type(s) == str, "Argument must be string" dt = s.split() year, month, day = map(int, dt[0].split("-")) hour, minute, second = map(int, dt[1].split(":")) return datetime.datetime(year, month, day, hour, minute, second)
identifier_body
progressbar.js
!function ($) { var ProgressBar = function (element, options) { this.element = $(element); this.position = 0;
this.percent = 0; var hasOptions = typeof options == 'object'; this.dangerMarker = $.fn.progressbar.defaults.dangerMarker; if (hasOptions && typeof options.dangerMarker == 'number') { this.setDangerMarker(options.dangerMarker); } this.warningMarker = $.fn.progressbar.defaults.warningMarker; if (hasOptions && typeof options.warningMarker == 'number') { this.setWarningMarker(options.warningMarker); } this.maximum = $.fn.progressbar.defaults.maximum; if (hasOptions && typeof options.maximum == 'number') { this.setMaximum(options.maximum); } this.step = $.fn.progressbar.defaults.step; if (hasOptions && typeof options.step == 'number') { this.setStep(options.step); } this.element.html($(DRPGlobal.template)); }; ProgressBar.prototype = { constructor: ProgressBar, stepIt: function () { if (this.position < this.maximum) this.position += this.step; this.setPosition(this.position); }, setWarningMarker: function (marker) { marker = parseInt(marker); if (marker > this.dangerMarker) { this.warningMarker = this.dangerMarker; return; } this.warningMarker = marker; }, setDangerMarker: function (marker) { this.dangerMarker = parseInt(marker); }, setMaximum: function (maximum) { this.maximum = parseInt(maximum); }, setStep: function (step) { step = parseInt(step); if (step <= 0) step = 1; this.step = parseInt(step); }, setPosition: function (position) { position = parseInt(position); if (position < 0) position = 0; if (position > this.maximum) position = this.maximum; this.position = position; this.percent = Math.ceil((this.position / this.maximum) * 100); try { if (this.percent <= this.warningMarker) { this.element.find('.bar-success').css('width', this.percent + "%"); this.element.find('.bar-warning').css('width', "0%"); this.element.find('.bar-danger').css('width', "0%"); return; } this.element.find('.bar-success').css('width', this.warningMarker + "%"); if (this.percent > this.warningMarker && this.percent <= this.dangerMarker) { this.element.find('.bar-warning').css('width', (this.percent - this.warningMarker) + "%"); this.element.find('.bar-danger').css('width', "0%"); return; } this.element.find('.bar-warning').css('width', (this.dangerMarker - this.warningMarker) + "%"); this.element.find('.bar-danger').css('width', (this.percent - this.dangerMarker) + "%"); } finally { this._triggerPositionChanged(); } }, reset: function () { this.position = 0; this.percent = 0; this._triggerPositionChanged(); this.element.find('.bar-success').css('width', "0%"); this.element.find('.bar-warning').css('width', "0%"); this.element.find('.bar-danger').css('width', "0%"); }, _triggerPositionChanged: function () { this.element.trigger({ type: "positionChanged", position: this.position, percent: this.percent }); } }; $.fn.progressbar = function (option) { var args = Array.apply(null, arguments); args.shift(); return this.each(function () { var $this = $(this), data = $this.data('progressbar'), options = typeof option == 'object' && option; if (!data) { $this.data('progressbar', new ProgressBar(this, $.extend({}, $.fn.progressbar().defaults, options))); } if (typeof option == 'string' && typeof data[option] == 'function') { data[option].apply(data, args); } }); }; $.fn.progressbar.defaults = { warningMarker: 50, dangerMarker: 90, maximum: 100, step: 1 }; $.fn.progressbar.Constructor = ProgressBar; var DRPGlobal = {}; DRPGlobal.template = '<div class="progress">' + '<div class="bar bar-success progress-bar progress-bar-success" style="width: 0%;"></div>' + '<div class="bar bar-warning progress-bar progress-bar-warning" style="width: 0%;"></div>' + '<div class="bar bar-danger progress-bar progress-bar-danger" style="width: 0%;"></div>' + '</div>'; } (window.jQuery);
random_line_split
logging.js
/** * Copyright (C) 2014 TopCoder Inc., All Rights Reserved. * @version 1.1 * @author Sky_, TCSASSEMBLER * changes in 1.1: * 1. change handleError. Return sql error with unique constrains as Bad Request. * 2. close db when request ends. * 3. don't create transactions for GET requests */ "use strict"; var _ = require('underscore'); var async = require('async'); var winston = require('winston'); var BadRequestError = require("../errors/BadRequestError"); var IllegalArgumentError = require("../errors/IllegalArgumentError"); var NotFoundError = require("../errors/NotFoundError"); var initDb = require("../db"); /** * Api codes */ var apiCodes = { OK: { name: 'OK', value: 200, description: 'Success' }, notModified: { name: 'Not Modified', value: 304, description: 'There was no new data to return.' }, badRequest: { name: 'Bad Request', value: 400, description: 'The request was invalid. An accompanying message will explain why.' }, unauthorized: { name: 'Unauthorized', value: 401, description: 'Authentication credentials were missing or incorrect.' }, forbidden: { name: 'Forbidden', value: 403, description: 'The request is understood, but it has been refused or access is not allowed.' }, notFound: { name: 'Not Found', value: 404, description: 'The URI requested is invalid or the requested resource does not exist.' }, serverError: { name: 'Internal Server Error', value: 500, description: 'Something is broken. Please contact support.' } }; /** * Handle error and return as JSON to the response. * @param {Error} error the error to handle * @param {Object} res the express response object */ function handleError(error, res) { var errdetail, baseError = apiCodes.serverError; if (error.isValidationError || error instanceof IllegalArgumentError || error instanceof BadRequestError) { baseError = apiCodes.badRequest; } else if (error instanceof NotFoundError) { baseError = apiCodes.notFound; } else if (error.code === 'ER_DUP_ENTRY') { baseError = apiCodes.badRequest; if (error.message.indexOf("UC_c_sort") !== -1) { error.message += ". Pair of the columns 'sort' and 'tab' must be unique."; } } errdetail = _.clone(baseError); errdetail.details = error.message; res.statusCode = baseError.value; res.json(errdetail); } /** * This function create a delegate for the express action. * Input and output logging is performed. * Errors are handled also and proper http status code is set. * Wrapped method must always call the callback function, first param is error, second param is object to return. * @param {String} signature the signature of the method caller * @param {Function} fn the express method to call. It must have signature (req, res, callback) or (req, callback). Res * parameter is optional, because he is usually not used. * @param {Boolean} customHandled true if the express action is handling the response. * This is useful for downloading files. Wrapper will render only the error response. * @returns {Function} the wrapped function */ function wrapExpress(signature, fn, customHandled) { if (!_.isString(signature)) { throw new Error("signature should be a string"); } if (!_.isFunction(fn)) { throw new Error("fn should be a function"); } return function (req, res, next) { var paramsToLog, db, transaction, apiResult, canRollback = false, useGlobalDB = req.method === 'GET'; paramsToLog = { body: req.body, params: req.params, query : req.query, url: req.url }; winston.info("ENTER %s %j", signature, paramsToLog, {}); var disposeDB = function () { if (useGlobalDB) { return; } //close db connection //we need this timeout because there is a bug for parallel requests setTimeout(function () { db.driver.close(); }, 1000); }; async.waterfall([ function (cb) { if (useGlobalDB) { db = global.db; cb(); } else { async.waterfall([ function (cb) { initDb(cb, false); }, function (result, cb) { db = result; db.transaction(cb); }, function (t, cb) { transaction = t; canRollback = true; cb(); } ], cb); } }, function (cb) { if (fn.length === 3) { fn(req, db, cb); } else { fn(req, res, db, cb); } }, function (result, cb) { apiResult = result; if (useGlobalDB) { cb(); } else { transaction.commit(cb); } }, function (cb) { if (process.env.NO_LOG_RESPONSE) { paramsToLog.response = "<disabled>"; } else
winston.info("EXIT %s %j", signature, paramsToLog, {}); if (!customHandled) { res.json(apiResult); } disposeDB(); } ], function (error) { if (canRollback && transaction) { transaction.rollback(function () { }); } disposeDB(); winston.error("EXIT %s %j\n", signature, paramsToLog, error.stack); handleError(error, res); }); }; } module.exports = { wrapExpress: wrapExpress, apiCodes: apiCodes, handleError: handleError };
{ paramsToLog.response = apiResult; }
conditional_block
logging.js
/** * Copyright (C) 2014 TopCoder Inc., All Rights Reserved. * @version 1.1 * @author Sky_, TCSASSEMBLER * changes in 1.1: * 1. change handleError. Return sql error with unique constrains as Bad Request. * 2. close db when request ends. * 3. don't create transactions for GET requests */ "use strict"; var _ = require('underscore'); var async = require('async'); var winston = require('winston'); var BadRequestError = require("../errors/BadRequestError"); var IllegalArgumentError = require("../errors/IllegalArgumentError"); var NotFoundError = require("../errors/NotFoundError"); var initDb = require("../db"); /** * Api codes */ var apiCodes = { OK: { name: 'OK', value: 200, description: 'Success' }, notModified: { name: 'Not Modified', value: 304, description: 'There was no new data to return.' }, badRequest: { name: 'Bad Request', value: 400, description: 'The request was invalid. An accompanying message will explain why.' }, unauthorized: { name: 'Unauthorized', value: 401, description: 'Authentication credentials were missing or incorrect.' }, forbidden: { name: 'Forbidden', value: 403, description: 'The request is understood, but it has been refused or access is not allowed.' }, notFound: { name: 'Not Found', value: 404, description: 'The URI requested is invalid or the requested resource does not exist.' }, serverError: { name: 'Internal Server Error', value: 500, description: 'Something is broken. Please contact support.' } }; /** * Handle error and return as JSON to the response. * @param {Error} error the error to handle * @param {Object} res the express response object */ function handleError(error, res) { var errdetail, baseError = apiCodes.serverError; if (error.isValidationError || error instanceof IllegalArgumentError || error instanceof BadRequestError) {
baseError = apiCodes.notFound; } else if (error.code === 'ER_DUP_ENTRY') { baseError = apiCodes.badRequest; if (error.message.indexOf("UC_c_sort") !== -1) { error.message += ". Pair of the columns 'sort' and 'tab' must be unique."; } } errdetail = _.clone(baseError); errdetail.details = error.message; res.statusCode = baseError.value; res.json(errdetail); } /** * This function create a delegate for the express action. * Input and output logging is performed. * Errors are handled also and proper http status code is set. * Wrapped method must always call the callback function, first param is error, second param is object to return. * @param {String} signature the signature of the method caller * @param {Function} fn the express method to call. It must have signature (req, res, callback) or (req, callback). Res * parameter is optional, because he is usually not used. * @param {Boolean} customHandled true if the express action is handling the response. * This is useful for downloading files. Wrapper will render only the error response. * @returns {Function} the wrapped function */ function wrapExpress(signature, fn, customHandled) { if (!_.isString(signature)) { throw new Error("signature should be a string"); } if (!_.isFunction(fn)) { throw new Error("fn should be a function"); } return function (req, res, next) { var paramsToLog, db, transaction, apiResult, canRollback = false, useGlobalDB = req.method === 'GET'; paramsToLog = { body: req.body, params: req.params, query : req.query, url: req.url }; winston.info("ENTER %s %j", signature, paramsToLog, {}); var disposeDB = function () { if (useGlobalDB) { return; } //close db connection //we need this timeout because there is a bug for parallel requests setTimeout(function () { db.driver.close(); }, 1000); }; async.waterfall([ function (cb) { if (useGlobalDB) { db = global.db; cb(); } else { async.waterfall([ function (cb) { initDb(cb, false); }, function (result, cb) { db = result; db.transaction(cb); }, function (t, cb) { transaction = t; canRollback = true; cb(); } ], cb); } }, function (cb) { if (fn.length === 3) { fn(req, db, cb); } else { fn(req, res, db, cb); } }, function (result, cb) { apiResult = result; if (useGlobalDB) { cb(); } else { transaction.commit(cb); } }, function (cb) { if (process.env.NO_LOG_RESPONSE) { paramsToLog.response = "<disabled>"; } else { paramsToLog.response = apiResult; } winston.info("EXIT %s %j", signature, paramsToLog, {}); if (!customHandled) { res.json(apiResult); } disposeDB(); } ], function (error) { if (canRollback && transaction) { transaction.rollback(function () { }); } disposeDB(); winston.error("EXIT %s %j\n", signature, paramsToLog, error.stack); handleError(error, res); }); }; } module.exports = { wrapExpress: wrapExpress, apiCodes: apiCodes, handleError: handleError };
baseError = apiCodes.badRequest; } else if (error instanceof NotFoundError) {
random_line_split
logging.js
/** * Copyright (C) 2014 TopCoder Inc., All Rights Reserved. * @version 1.1 * @author Sky_, TCSASSEMBLER * changes in 1.1: * 1. change handleError. Return sql error with unique constrains as Bad Request. * 2. close db when request ends. * 3. don't create transactions for GET requests */ "use strict"; var _ = require('underscore'); var async = require('async'); var winston = require('winston'); var BadRequestError = require("../errors/BadRequestError"); var IllegalArgumentError = require("../errors/IllegalArgumentError"); var NotFoundError = require("../errors/NotFoundError"); var initDb = require("../db"); /** * Api codes */ var apiCodes = { OK: { name: 'OK', value: 200, description: 'Success' }, notModified: { name: 'Not Modified', value: 304, description: 'There was no new data to return.' }, badRequest: { name: 'Bad Request', value: 400, description: 'The request was invalid. An accompanying message will explain why.' }, unauthorized: { name: 'Unauthorized', value: 401, description: 'Authentication credentials were missing or incorrect.' }, forbidden: { name: 'Forbidden', value: 403, description: 'The request is understood, but it has been refused or access is not allowed.' }, notFound: { name: 'Not Found', value: 404, description: 'The URI requested is invalid or the requested resource does not exist.' }, serverError: { name: 'Internal Server Error', value: 500, description: 'Something is broken. Please contact support.' } }; /** * Handle error and return as JSON to the response. * @param {Error} error the error to handle * @param {Object} res the express response object */ function handleError(error, res)
/** * This function create a delegate for the express action. * Input and output logging is performed. * Errors are handled also and proper http status code is set. * Wrapped method must always call the callback function, first param is error, second param is object to return. * @param {String} signature the signature of the method caller * @param {Function} fn the express method to call. It must have signature (req, res, callback) or (req, callback). Res * parameter is optional, because he is usually not used. * @param {Boolean} customHandled true if the express action is handling the response. * This is useful for downloading files. Wrapper will render only the error response. * @returns {Function} the wrapped function */ function wrapExpress(signature, fn, customHandled) { if (!_.isString(signature)) { throw new Error("signature should be a string"); } if (!_.isFunction(fn)) { throw new Error("fn should be a function"); } return function (req, res, next) { var paramsToLog, db, transaction, apiResult, canRollback = false, useGlobalDB = req.method === 'GET'; paramsToLog = { body: req.body, params: req.params, query : req.query, url: req.url }; winston.info("ENTER %s %j", signature, paramsToLog, {}); var disposeDB = function () { if (useGlobalDB) { return; } //close db connection //we need this timeout because there is a bug for parallel requests setTimeout(function () { db.driver.close(); }, 1000); }; async.waterfall([ function (cb) { if (useGlobalDB) { db = global.db; cb(); } else { async.waterfall([ function (cb) { initDb(cb, false); }, function (result, cb) { db = result; db.transaction(cb); }, function (t, cb) { transaction = t; canRollback = true; cb(); } ], cb); } }, function (cb) { if (fn.length === 3) { fn(req, db, cb); } else { fn(req, res, db, cb); } }, function (result, cb) { apiResult = result; if (useGlobalDB) { cb(); } else { transaction.commit(cb); } }, function (cb) { if (process.env.NO_LOG_RESPONSE) { paramsToLog.response = "<disabled>"; } else { paramsToLog.response = apiResult; } winston.info("EXIT %s %j", signature, paramsToLog, {}); if (!customHandled) { res.json(apiResult); } disposeDB(); } ], function (error) { if (canRollback && transaction) { transaction.rollback(function () { }); } disposeDB(); winston.error("EXIT %s %j\n", signature, paramsToLog, error.stack); handleError(error, res); }); }; } module.exports = { wrapExpress: wrapExpress, apiCodes: apiCodes, handleError: handleError };
{ var errdetail, baseError = apiCodes.serverError; if (error.isValidationError || error instanceof IllegalArgumentError || error instanceof BadRequestError) { baseError = apiCodes.badRequest; } else if (error instanceof NotFoundError) { baseError = apiCodes.notFound; } else if (error.code === 'ER_DUP_ENTRY') { baseError = apiCodes.badRequest; if (error.message.indexOf("UC_c_sort") !== -1) { error.message += ". Pair of the columns 'sort' and 'tab' must be unique."; } } errdetail = _.clone(baseError); errdetail.details = error.message; res.statusCode = baseError.value; res.json(errdetail); }
identifier_body
logging.js
/** * Copyright (C) 2014 TopCoder Inc., All Rights Reserved. * @version 1.1 * @author Sky_, TCSASSEMBLER * changes in 1.1: * 1. change handleError. Return sql error with unique constrains as Bad Request. * 2. close db when request ends. * 3. don't create transactions for GET requests */ "use strict"; var _ = require('underscore'); var async = require('async'); var winston = require('winston'); var BadRequestError = require("../errors/BadRequestError"); var IllegalArgumentError = require("../errors/IllegalArgumentError"); var NotFoundError = require("../errors/NotFoundError"); var initDb = require("../db"); /** * Api codes */ var apiCodes = { OK: { name: 'OK', value: 200, description: 'Success' }, notModified: { name: 'Not Modified', value: 304, description: 'There was no new data to return.' }, badRequest: { name: 'Bad Request', value: 400, description: 'The request was invalid. An accompanying message will explain why.' }, unauthorized: { name: 'Unauthorized', value: 401, description: 'Authentication credentials were missing or incorrect.' }, forbidden: { name: 'Forbidden', value: 403, description: 'The request is understood, but it has been refused or access is not allowed.' }, notFound: { name: 'Not Found', value: 404, description: 'The URI requested is invalid or the requested resource does not exist.' }, serverError: { name: 'Internal Server Error', value: 500, description: 'Something is broken. Please contact support.' } }; /** * Handle error and return as JSON to the response. * @param {Error} error the error to handle * @param {Object} res the express response object */ function handleError(error, res) { var errdetail, baseError = apiCodes.serverError; if (error.isValidationError || error instanceof IllegalArgumentError || error instanceof BadRequestError) { baseError = apiCodes.badRequest; } else if (error instanceof NotFoundError) { baseError = apiCodes.notFound; } else if (error.code === 'ER_DUP_ENTRY') { baseError = apiCodes.badRequest; if (error.message.indexOf("UC_c_sort") !== -1) { error.message += ". Pair of the columns 'sort' and 'tab' must be unique."; } } errdetail = _.clone(baseError); errdetail.details = error.message; res.statusCode = baseError.value; res.json(errdetail); } /** * This function create a delegate for the express action. * Input and output logging is performed. * Errors are handled also and proper http status code is set. * Wrapped method must always call the callback function, first param is error, second param is object to return. * @param {String} signature the signature of the method caller * @param {Function} fn the express method to call. It must have signature (req, res, callback) or (req, callback). Res * parameter is optional, because he is usually not used. * @param {Boolean} customHandled true if the express action is handling the response. * This is useful for downloading files. Wrapper will render only the error response. * @returns {Function} the wrapped function */ function
(signature, fn, customHandled) { if (!_.isString(signature)) { throw new Error("signature should be a string"); } if (!_.isFunction(fn)) { throw new Error("fn should be a function"); } return function (req, res, next) { var paramsToLog, db, transaction, apiResult, canRollback = false, useGlobalDB = req.method === 'GET'; paramsToLog = { body: req.body, params: req.params, query : req.query, url: req.url }; winston.info("ENTER %s %j", signature, paramsToLog, {}); var disposeDB = function () { if (useGlobalDB) { return; } //close db connection //we need this timeout because there is a bug for parallel requests setTimeout(function () { db.driver.close(); }, 1000); }; async.waterfall([ function (cb) { if (useGlobalDB) { db = global.db; cb(); } else { async.waterfall([ function (cb) { initDb(cb, false); }, function (result, cb) { db = result; db.transaction(cb); }, function (t, cb) { transaction = t; canRollback = true; cb(); } ], cb); } }, function (cb) { if (fn.length === 3) { fn(req, db, cb); } else { fn(req, res, db, cb); } }, function (result, cb) { apiResult = result; if (useGlobalDB) { cb(); } else { transaction.commit(cb); } }, function (cb) { if (process.env.NO_LOG_RESPONSE) { paramsToLog.response = "<disabled>"; } else { paramsToLog.response = apiResult; } winston.info("EXIT %s %j", signature, paramsToLog, {}); if (!customHandled) { res.json(apiResult); } disposeDB(); } ], function (error) { if (canRollback && transaction) { transaction.rollback(function () { }); } disposeDB(); winston.error("EXIT %s %j\n", signature, paramsToLog, error.stack); handleError(error, res); }); }; } module.exports = { wrapExpress: wrapExpress, apiCodes: apiCodes, handleError: handleError };
wrapExpress
identifier_name
asha-workers-details.service_20170227130424.ts
import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model'; import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data'; import { AshaWorkerPaymentRulesModel } from '../model/asha-worker-payment-rules-model'; import { JSONMessageModel } from '../model/json-message-model'; @Injectable() export class AshaWorkersDetailsService{ private url: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/getdetails/get_asha_worker_details"; private updateURL: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/ashaActivityRules/updateActivity" constructor(private http: Http){} getAshaWorkersList(): Promise<AshaWorkerBasicDetailsModel[]>{ //return Promise.resolve(AshaWorkersList); return this.http.get(this.url) .toPromise() .then(response => response.json().awAshaDetailsModel as AshaWorkerBasicDetailsModel[]) .catch(this.handleError); } getDummyAshaWorkerDetails(): Promise<AshaWorkerBasicDetailsModel>{ return Promise.resolve(DummyAshaWorkerDetails); } //update the payment rules for rural, urban and help text
(ashaWorkerPaymentRulesModel: AshaWorkerPaymentRulesModel): Promise<JSONMessageModel>{ let body = JSON.stringify(ashaWorkerPaymentRulesModel); console.log("body = "+ body); return this.http.post(this.updateURL,body) .toPromise() .then(response => response.json() as JSONMessageModel) .catch(this.handleError) } private handleError(error: any):Promise<any>{ console.error('An error occured', error); return Promise.reject(error.message || error); } }
updateAshaWorkerPaymentRules
identifier_name
asha-workers-details.service_20170227130424.ts
import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model'; import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data'; import { AshaWorkerPaymentRulesModel } from '../model/asha-worker-payment-rules-model'; import { JSONMessageModel } from '../model/json-message-model'; @Injectable() export class AshaWorkersDetailsService{ private url: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/getdetails/get_asha_worker_details"; private updateURL: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/ashaActivityRules/updateActivity" constructor(private http: Http)
getAshaWorkersList(): Promise<AshaWorkerBasicDetailsModel[]>{ //return Promise.resolve(AshaWorkersList); return this.http.get(this.url) .toPromise() .then(response => response.json().awAshaDetailsModel as AshaWorkerBasicDetailsModel[]) .catch(this.handleError); } getDummyAshaWorkerDetails(): Promise<AshaWorkerBasicDetailsModel>{ return Promise.resolve(DummyAshaWorkerDetails); } //update the payment rules for rural, urban and help text updateAshaWorkerPaymentRules(ashaWorkerPaymentRulesModel: AshaWorkerPaymentRulesModel): Promise<JSONMessageModel>{ let body = JSON.stringify(ashaWorkerPaymentRulesModel); console.log("body = "+ body); return this.http.post(this.updateURL,body) .toPromise() .then(response => response.json() as JSONMessageModel) .catch(this.handleError) } private handleError(error: any):Promise<any>{ console.error('An error occured', error); return Promise.reject(error.message || error); } }
{}
identifier_body
asha-workers-details.service_20170227130424.ts
import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model'; import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data'; import { AshaWorkerPaymentRulesModel } from '../model/asha-worker-payment-rules-model'; import { JSONMessageModel } from '../model/json-message-model';
export class AshaWorkersDetailsService{ private url: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/getdetails/get_asha_worker_details"; private updateURL: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/ashaActivityRules/updateActivity" constructor(private http: Http){} getAshaWorkersList(): Promise<AshaWorkerBasicDetailsModel[]>{ //return Promise.resolve(AshaWorkersList); return this.http.get(this.url) .toPromise() .then(response => response.json().awAshaDetailsModel as AshaWorkerBasicDetailsModel[]) .catch(this.handleError); } getDummyAshaWorkerDetails(): Promise<AshaWorkerBasicDetailsModel>{ return Promise.resolve(DummyAshaWorkerDetails); } //update the payment rules for rural, urban and help text updateAshaWorkerPaymentRules(ashaWorkerPaymentRulesModel: AshaWorkerPaymentRulesModel): Promise<JSONMessageModel>{ let body = JSON.stringify(ashaWorkerPaymentRulesModel); console.log("body = "+ body); return this.http.post(this.updateURL,body) .toPromise() .then(response => response.json() as JSONMessageModel) .catch(this.handleError) } private handleError(error: any):Promise<any>{ console.error('An error occured', error); return Promise.reject(error.message || error); } }
@Injectable()
random_line_split
donate.ts
let dialog: HTMLDivElement = null export function getDialog (title: string, content: string, qrcodes: {src: string, desc: string}[])
{ if (dialog) { return dialog } dialog = document.createElement('div') dialog.className = 'donate-dialog' const wrap = document.createElement('div') wrap.className = 'donate-wrap' const titleEl = document.createElement('h3') titleEl.className = 'donate-title' titleEl.innerText = title const contentEl = document.createElement('div') contentEl.className = 'donate-content' contentEl.innerText = content const qrcodeEl = document.createElement('div') qrcodeEl.className = 'donate-qrcode-bar' for (let i of qrcodes) { const qrcodeBox = document.createElement('div') qrcodeBox.className = 'donate-qrcode-box' const qrcode = document.createElement('img') qrcode.className = 'donate-qrcode-img' qrcode.src = i.src const qrcodeDesc = document.createElement('div') qrcodeDesc.className = 'donate-qrcode-desc' qrcodeDesc.innerText = i.desc qrcodeBox.appendChild(qrcode) qrcodeBox.appendChild(qrcodeDesc) qrcodeEl.appendChild(qrcodeBox) } const closeEl = document.createElement('div') closeEl.className = 'donate-close-btn' const close = () => { dialog.style.display = 'none' } closeEl.addEventListener('click', close) wrap.appendChild(titleEl) wrap.appendChild(contentEl) wrap.appendChild(qrcodeEl) wrap.appendChild(closeEl) dialog.appendChild(wrap) dialog.style.display = 'none' return dialog }
identifier_body
donate.ts
let dialog: HTMLDivElement = null export function getDialog (title: string, content: string, qrcodes: {src: string, desc: string}[]) { if (dialog) { return dialog } dialog = document.createElement('div') dialog.className = 'donate-dialog' const wrap = document.createElement('div') wrap.className = 'donate-wrap' const titleEl = document.createElement('h3') titleEl.className = 'donate-title' titleEl.innerText = title const contentEl = document.createElement('div') contentEl.className = 'donate-content' contentEl.innerText = content const qrcodeEl = document.createElement('div') qrcodeEl.className = 'donate-qrcode-bar' for (let i of qrcodes) { const qrcodeBox = document.createElement('div') qrcodeBox.className = 'donate-qrcode-box' const qrcode = document.createElement('img') qrcode.className = 'donate-qrcode-img' qrcode.src = i.src const qrcodeDesc = document.createElement('div') qrcodeDesc.className = 'donate-qrcode-desc' qrcodeDesc.innerText = i.desc qrcodeBox.appendChild(qrcode) qrcodeBox.appendChild(qrcodeDesc) qrcodeEl.appendChild(qrcodeBox) } const closeEl = document.createElement('div') closeEl.className = 'donate-close-btn' const close = () => { dialog.style.display = 'none' } closeEl.addEventListener('click', close) wrap.appendChild(titleEl) wrap.appendChild(contentEl) wrap.appendChild(qrcodeEl)
}
wrap.appendChild(closeEl) dialog.appendChild(wrap) dialog.style.display = 'none' return dialog
random_line_split
donate.ts
let dialog: HTMLDivElement = null export function
(title: string, content: string, qrcodes: {src: string, desc: string}[]) { if (dialog) { return dialog } dialog = document.createElement('div') dialog.className = 'donate-dialog' const wrap = document.createElement('div') wrap.className = 'donate-wrap' const titleEl = document.createElement('h3') titleEl.className = 'donate-title' titleEl.innerText = title const contentEl = document.createElement('div') contentEl.className = 'donate-content' contentEl.innerText = content const qrcodeEl = document.createElement('div') qrcodeEl.className = 'donate-qrcode-bar' for (let i of qrcodes) { const qrcodeBox = document.createElement('div') qrcodeBox.className = 'donate-qrcode-box' const qrcode = document.createElement('img') qrcode.className = 'donate-qrcode-img' qrcode.src = i.src const qrcodeDesc = document.createElement('div') qrcodeDesc.className = 'donate-qrcode-desc' qrcodeDesc.innerText = i.desc qrcodeBox.appendChild(qrcode) qrcodeBox.appendChild(qrcodeDesc) qrcodeEl.appendChild(qrcodeBox) } const closeEl = document.createElement('div') closeEl.className = 'donate-close-btn' const close = () => { dialog.style.display = 'none' } closeEl.addEventListener('click', close) wrap.appendChild(titleEl) wrap.appendChild(contentEl) wrap.appendChild(qrcodeEl) wrap.appendChild(closeEl) dialog.appendChild(wrap) dialog.style.display = 'none' return dialog }
getDialog
identifier_name
donate.ts
let dialog: HTMLDivElement = null export function getDialog (title: string, content: string, qrcodes: {src: string, desc: string}[]) { if (dialog)
dialog = document.createElement('div') dialog.className = 'donate-dialog' const wrap = document.createElement('div') wrap.className = 'donate-wrap' const titleEl = document.createElement('h3') titleEl.className = 'donate-title' titleEl.innerText = title const contentEl = document.createElement('div') contentEl.className = 'donate-content' contentEl.innerText = content const qrcodeEl = document.createElement('div') qrcodeEl.className = 'donate-qrcode-bar' for (let i of qrcodes) { const qrcodeBox = document.createElement('div') qrcodeBox.className = 'donate-qrcode-box' const qrcode = document.createElement('img') qrcode.className = 'donate-qrcode-img' qrcode.src = i.src const qrcodeDesc = document.createElement('div') qrcodeDesc.className = 'donate-qrcode-desc' qrcodeDesc.innerText = i.desc qrcodeBox.appendChild(qrcode) qrcodeBox.appendChild(qrcodeDesc) qrcodeEl.appendChild(qrcodeBox) } const closeEl = document.createElement('div') closeEl.className = 'donate-close-btn' const close = () => { dialog.style.display = 'none' } closeEl.addEventListener('click', close) wrap.appendChild(titleEl) wrap.appendChild(contentEl) wrap.appendChild(qrcodeEl) wrap.appendChild(closeEl) dialog.appendChild(wrap) dialog.style.display = 'none' return dialog }
{ return dialog }
conditional_block
place.js
define([ 'jquery', 'jquery-ui', 'dialogForm' ], function($, jqueryUi, DialogForm) { return function(id, writer) { var w = writer; var html = ''+ '<div id="'+id+'Dialog" class="annotationDialog">'+
id: id, type: 'place', title: 'Tag Place', height: 150, width: 450, html: html }); dialog.$el.on('beforeShow', function(e, config, dialog) { var cwrcInfo = dialog.currentData.cwrcInfo; if (cwrcInfo !== undefined) { $('#'+id+'_ref').val(cwrcInfo.id); } }); return { show: function(config) { dialog.show(config); } }; }; });
'<input type="hidden" id="'+id+'_ref" data-type="hidden" data-mapping="REF"/>'+ '</div>'; var dialog = new DialogForm({ writer: w,
random_line_split
place.js
define([ 'jquery', 'jquery-ui', 'dialogForm' ], function($, jqueryUi, DialogForm) { return function(id, writer) { var w = writer; var html = ''+ '<div id="'+id+'Dialog" class="annotationDialog">'+ '<input type="hidden" id="'+id+'_ref" data-type="hidden" data-mapping="REF"/>'+ '</div>'; var dialog = new DialogForm({ writer: w, id: id, type: 'place', title: 'Tag Place', height: 150, width: 450, html: html }); dialog.$el.on('beforeShow', function(e, config, dialog) { var cwrcInfo = dialog.currentData.cwrcInfo; if (cwrcInfo !== undefined)
}); return { show: function(config) { dialog.show(config); } }; }; });
{ $('#'+id+'_ref').val(cwrcInfo.id); }
conditional_block
datemath.ts
///<reference path="../../headers/common.d.ts" /> import _ from 'lodash'; import moment from 'moment'; var units = ['y', 'M', 'w', 'd', 'h', 'm', 's']; export function parse(text, roundUp?) { if (!text) { return undefined; } if (moment.isMoment(text)) { return text; } if (_.isDate(text)) { return moment(text); } var time; var mathString = ''; var index; var parseString; if (text.substring(0, 3) === 'now') { time = moment(); mathString = text.substring('now'.length); } else { index = text.indexOf('||'); if (index === -1) { parseString = text; mathString = ''; // nothing else } else { parseString = text.substring(0, index); mathString = text.substring(index + 2); } // We're going to just require ISO8601 timestamps, k? time = moment(parseString, moment.ISO_8601); } if (!mathString.length) { return time; } return parseDateMath(mathString, time, roundUp); } export function isValid(text) { var date = parse(text); if (!date) { return false; } if (moment.isMoment(date)) { return date.isValid(); } return false; } export function parseDateMath(mathString, time, roundUp?) { var dateTime = time; var i = 0; var len = mathString.length; while (i < len) { var c = mathString.charAt(i++); var type; var num; var unit; if (c === '/') { type = 0; } else if (c === '+') { type = 1; } else if (c === '-') { type = 2; } else { return undefined; } if (isNaN(mathString.charAt(i))) { num = 1; } else if (mathString.length === 2) { num = mathString.charAt(i); } else { var numFrom = i; while (!isNaN(mathString.charAt(i))) { i++; if (i > 10) { return undefined; } } num = parseInt(mathString.substring(numFrom, i), 10); } if (type === 0) { // rounding is only allowed on whole, single, units (eg M or 1M, not 0.5M or 2M) if (num !== 1) { return undefined; } } unit = mathString.charAt(i++); if (!_.includes(units, unit)) { return undefined; } else { if (type === 0) { if (roundUp) { dateTime.endOf(unit); } else {
} else if (type === 1) { dateTime.add(num, unit); } else if (type === 2) { dateTime.subtract(num, unit); } } } return dateTime; }
dateTime.startOf(unit); }
random_line_split
datemath.ts
///<reference path="../../headers/common.d.ts" /> import _ from 'lodash'; import moment from 'moment'; var units = ['y', 'M', 'w', 'd', 'h', 'm', 's']; export function parse(text, roundUp?) { if (!text) { return undefined; } if (moment.isMoment(text)) { return text; } if (_.isDate(text)) { return moment(text); } var time; var mathString = ''; var index; var parseString; if (text.substring(0, 3) === 'now') { time = moment(); mathString = text.substring('now'.length); } else { index = text.indexOf('||'); if (index === -1) { parseString = text; mathString = ''; // nothing else } else { parseString = text.substring(0, index); mathString = text.substring(index + 2); } // We're going to just require ISO8601 timestamps, k? time = moment(parseString, moment.ISO_8601); } if (!mathString.length) { return time; } return parseDateMath(mathString, time, roundUp); } export function isValid(text) { var date = parse(text); if (!date) { return false; } if (moment.isMoment(date)) { return date.isValid(); } return false; } export function
(mathString, time, roundUp?) { var dateTime = time; var i = 0; var len = mathString.length; while (i < len) { var c = mathString.charAt(i++); var type; var num; var unit; if (c === '/') { type = 0; } else if (c === '+') { type = 1; } else if (c === '-') { type = 2; } else { return undefined; } if (isNaN(mathString.charAt(i))) { num = 1; } else if (mathString.length === 2) { num = mathString.charAt(i); } else { var numFrom = i; while (!isNaN(mathString.charAt(i))) { i++; if (i > 10) { return undefined; } } num = parseInt(mathString.substring(numFrom, i), 10); } if (type === 0) { // rounding is only allowed on whole, single, units (eg M or 1M, not 0.5M or 2M) if (num !== 1) { return undefined; } } unit = mathString.charAt(i++); if (!_.includes(units, unit)) { return undefined; } else { if (type === 0) { if (roundUp) { dateTime.endOf(unit); } else { dateTime.startOf(unit); } } else if (type === 1) { dateTime.add(num, unit); } else if (type === 2) { dateTime.subtract(num, unit); } } } return dateTime; }
parseDateMath
identifier_name
datemath.ts
///<reference path="../../headers/common.d.ts" /> import _ from 'lodash'; import moment from 'moment'; var units = ['y', 'M', 'w', 'd', 'h', 'm', 's']; export function parse(text, roundUp?)
export function isValid(text) { var date = parse(text); if (!date) { return false; } if (moment.isMoment(date)) { return date.isValid(); } return false; } export function parseDateMath(mathString, time, roundUp?) { var dateTime = time; var i = 0; var len = mathString.length; while (i < len) { var c = mathString.charAt(i++); var type; var num; var unit; if (c === '/') { type = 0; } else if (c === '+') { type = 1; } else if (c === '-') { type = 2; } else { return undefined; } if (isNaN(mathString.charAt(i))) { num = 1; } else if (mathString.length === 2) { num = mathString.charAt(i); } else { var numFrom = i; while (!isNaN(mathString.charAt(i))) { i++; if (i > 10) { return undefined; } } num = parseInt(mathString.substring(numFrom, i), 10); } if (type === 0) { // rounding is only allowed on whole, single, units (eg M or 1M, not 0.5M or 2M) if (num !== 1) { return undefined; } } unit = mathString.charAt(i++); if (!_.includes(units, unit)) { return undefined; } else { if (type === 0) { if (roundUp) { dateTime.endOf(unit); } else { dateTime.startOf(unit); } } else if (type === 1) { dateTime.add(num, unit); } else if (type === 2) { dateTime.subtract(num, unit); } } } return dateTime; }
{ if (!text) { return undefined; } if (moment.isMoment(text)) { return text; } if (_.isDate(text)) { return moment(text); } var time; var mathString = ''; var index; var parseString; if (text.substring(0, 3) === 'now') { time = moment(); mathString = text.substring('now'.length); } else { index = text.indexOf('||'); if (index === -1) { parseString = text; mathString = ''; // nothing else } else { parseString = text.substring(0, index); mathString = text.substring(index + 2); } // We're going to just require ISO8601 timestamps, k? time = moment(parseString, moment.ISO_8601); } if (!mathString.length) { return time; } return parseDateMath(mathString, time, roundUp); }
identifier_body
normalize_projection_ty.rs
use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::TraitEngineExt as _; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::traits::query::{ normalize::NormalizationResult, CanonicalProjectionGoal, NoSolution, }; use rustc_trait_selection::traits::{self, ObligationCause, SelectionContext}; use std::sync::atomic::Ordering; crate fn provide(p: &mut Providers)
fn normalize_projection_ty<'tcx>( tcx: TyCtxt<'tcx>, goal: CanonicalProjectionGoal<'tcx>, ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, NormalizationResult<'tcx>>>, NoSolution> { debug!("normalize_provider(goal={:#?})", goal); tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering::Relaxed); tcx.infer_ctxt().enter_canonical_trait_query( &goal, |infcx, fulfill_cx, ParamEnvAnd { param_env, value: goal }| { let selcx = &mut SelectionContext::new(infcx); let cause = ObligationCause::dummy(); let mut obligations = vec![]; let answer = traits::normalize_projection_type( selcx, param_env, goal, cause, 0, &mut obligations, ); fulfill_cx.register_predicate_obligations(infcx, obligations); Ok(NormalizationResult { normalized_ty: answer }) }, ) }
{ *p = Providers { normalize_projection_ty, ..*p }; }
identifier_body
normalize_projection_ty.rs
use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::TraitEngineExt as _; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::traits::query::{ normalize::NormalizationResult, CanonicalProjectionGoal, NoSolution, }; use rustc_trait_selection::traits::{self, ObligationCause, SelectionContext}; use std::sync::atomic::Ordering; crate fn provide(p: &mut Providers) { *p = Providers { normalize_projection_ty, ..*p }; } fn
<'tcx>( tcx: TyCtxt<'tcx>, goal: CanonicalProjectionGoal<'tcx>, ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, NormalizationResult<'tcx>>>, NoSolution> { debug!("normalize_provider(goal={:#?})", goal); tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering::Relaxed); tcx.infer_ctxt().enter_canonical_trait_query( &goal, |infcx, fulfill_cx, ParamEnvAnd { param_env, value: goal }| { let selcx = &mut SelectionContext::new(infcx); let cause = ObligationCause::dummy(); let mut obligations = vec![]; let answer = traits::normalize_projection_type( selcx, param_env, goal, cause, 0, &mut obligations, ); fulfill_cx.register_predicate_obligations(infcx, obligations); Ok(NormalizationResult { normalized_ty: answer }) }, ) }
normalize_projection_ty
identifier_name
normalize_projection_ty.rs
use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::TraitEngineExt as _; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::traits::query::{ normalize::NormalizationResult, CanonicalProjectionGoal, NoSolution, }; use rustc_trait_selection::traits::{self, ObligationCause, SelectionContext}; use std::sync::atomic::Ordering; crate fn provide(p: &mut Providers) { *p = Providers { normalize_projection_ty, ..*p }; } fn normalize_projection_ty<'tcx>( tcx: TyCtxt<'tcx>, goal: CanonicalProjectionGoal<'tcx>, ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, NormalizationResult<'tcx>>>, NoSolution> { debug!("normalize_provider(goal={:#?})", goal); tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering::Relaxed); tcx.infer_ctxt().enter_canonical_trait_query( &goal, |infcx, fulfill_cx, ParamEnvAnd { param_env, value: goal }| { let selcx = &mut SelectionContext::new(infcx); let cause = ObligationCause::dummy(); let mut obligations = vec![]; let answer = traits::normalize_projection_type( selcx, param_env,
); fulfill_cx.register_predicate_obligations(infcx, obligations); Ok(NormalizationResult { normalized_ty: answer }) }, ) }
goal, cause, 0, &mut obligations,
random_line_split
test_process_mode_boot.py
################################################################################ # 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. ################################################################################ import os import shutil import socket import subprocess import sys import tempfile import time import unittest import grpc from apache_beam.portability.api.beam_provision_api_pb2 import (ProvisionInfo, GetProvisionInfoResponse) from apache_beam.portability.api.beam_provision_api_pb2_grpc import ( ProvisionServiceServicer, add_ProvisionServiceServicer_to_server) from concurrent import futures from google.protobuf import json_format from pyflink.java_gateway import get_gateway from pyflink.pyflink_gateway_server import on_windows from pyflink.testing.test_case_utils import PyFlinkTestCase class PythonBootTests(PyFlinkTestCase): def setUp(self): provision_info = json_format.Parse('{"retrievalToken": "test_token"}', ProvisionInfo()) response = GetProvisionInfoResponse(info=provision_info) def get_unused_port(): sock = socket.socket() sock.bind(('', 0)) port = sock.getsockname()[1] sock.close() return port class ProvisionService(ProvisionServiceServicer): def GetProvisionInfo(self, request, context): return response def start_test_provision_server(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) add_ProvisionServiceServicer_to_server(ProvisionService(), server) port = get_unused_port() server.add_insecure_port('[::]:' + str(port)) server.start() return server, port self.provision_server, self.provision_port = start_test_provision_server() self.env = dict(os.environ) self.env["python"] = sys.executable self.env["FLINK_BOOT_TESTING"] = "1" self.env["BOOT_LOG_DIR"] = os.path.join(self.env["FLINK_HOME"], "log") self.tmp_dir = tempfile.mkdtemp(str(time.time()), dir=self.tempdir) # assume that this file is in flink-python source code directory. flink_python_source_root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) runner_script = "pyflink-udf-runner.bat" if on_windows() else \ "pyflink-udf-runner.sh" self.runner_path = os.path.join( flink_python_source_root, "bin", runner_script) def run_boot_py(self): args = [self.runner_path, "--id", "1", "--logging_endpoint", "localhost:0000", "--artifact_endpoint", "whatever", "--provision_endpoint", "localhost:%d" % self.provision_port, "--control_endpoint", "localhost:0000", "--semi_persist_dir", self.tmp_dir] return subprocess.call(args, env=self.env) def test_python_boot(self): exit_code = self.run_boot_py() self.assertTrue(exit_code == 0, "the boot.py exited with non-zero code.") @unittest.skipIf(on_windows(), "'subprocess.check_output' in Windows always return empty " "string, skip this test.") def test_param_validation(self): args = [self.runner_path] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No id provided.", exit_message) args = [self.runner_path, "--id", "1"] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No logging endpoint provided.", exit_message) args = [self.runner_path, "--id", "1", "--logging_endpoint", "localhost:0000"] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No provision endpoint provided.", exit_message) args = [self.runner_path, "--id", "1",
exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No control endpoint provided.", exit_message) def test_set_working_directory(self): JProcessPythonEnvironmentManager = \ get_gateway().jvm.org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager output_file = os.path.join(self.tmp_dir, "output.txt") pyflink_dir = os.path.join(self.tmp_dir, "pyflink") os.mkdir(pyflink_dir) # just create an empty file open(os.path.join(pyflink_dir, "__init__.py"), 'a').close() fn_execution_dir = os.path.join(pyflink_dir, "fn_execution") os.mkdir(fn_execution_dir) open(os.path.join(fn_execution_dir, "__init__.py"), 'a').close() beam_dir = os.path.join(fn_execution_dir, "beam") os.mkdir(beam_dir) open(os.path.join(beam_dir, "__init__.py"), 'a').close() with open(os.path.join(beam_dir, "beam_boot.py"), "w") as f: f.write("import os\nwith open(r'%s', 'w') as f:\n f.write(os.getcwd())" % output_file) # test if the name of working directory variable of udf runner is consist with # ProcessPythonEnvironmentManager. self.env[JProcessPythonEnvironmentManager.PYTHON_WORKING_DIR] = self.tmp_dir self.env["python"] = sys.executable args = [self.runner_path] subprocess.check_output(args, env=self.env) process_cwd = None if os.path.exists(output_file): with open(output_file, 'r') as f: process_cwd = f.read() self.assertEqual(os.path.realpath(self.tmp_dir), process_cwd, "setting working directory variable is not work!") def tearDown(self): self.provision_server.stop(0) try: if self.tmp_dir is not None: shutil.rmtree(self.tmp_dir) except: pass
"--logging_endpoint", "localhost:0000", "--provision_endpoint", "localhost:%d" % self.provision_port]
random_line_split
test_process_mode_boot.py
################################################################################ # 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. ################################################################################ import os import shutil import socket import subprocess import sys import tempfile import time import unittest import grpc from apache_beam.portability.api.beam_provision_api_pb2 import (ProvisionInfo, GetProvisionInfoResponse) from apache_beam.portability.api.beam_provision_api_pb2_grpc import ( ProvisionServiceServicer, add_ProvisionServiceServicer_to_server) from concurrent import futures from google.protobuf import json_format from pyflink.java_gateway import get_gateway from pyflink.pyflink_gateway_server import on_windows from pyflink.testing.test_case_utils import PyFlinkTestCase class PythonBootTests(PyFlinkTestCase): def setUp(self): provision_info = json_format.Parse('{"retrievalToken": "test_token"}', ProvisionInfo()) response = GetProvisionInfoResponse(info=provision_info) def get_unused_port(): sock = socket.socket() sock.bind(('', 0)) port = sock.getsockname()[1] sock.close() return port class ProvisionService(ProvisionServiceServicer): def GetProvisionInfo(self, request, context): return response def start_test_provision_server(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) add_ProvisionServiceServicer_to_server(ProvisionService(), server) port = get_unused_port() server.add_insecure_port('[::]:' + str(port)) server.start() return server, port self.provision_server, self.provision_port = start_test_provision_server() self.env = dict(os.environ) self.env["python"] = sys.executable self.env["FLINK_BOOT_TESTING"] = "1" self.env["BOOT_LOG_DIR"] = os.path.join(self.env["FLINK_HOME"], "log") self.tmp_dir = tempfile.mkdtemp(str(time.time()), dir=self.tempdir) # assume that this file is in flink-python source code directory. flink_python_source_root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) runner_script = "pyflink-udf-runner.bat" if on_windows() else \ "pyflink-udf-runner.sh" self.runner_path = os.path.join( flink_python_source_root, "bin", runner_script) def run_boot_py(self): args = [self.runner_path, "--id", "1", "--logging_endpoint", "localhost:0000", "--artifact_endpoint", "whatever", "--provision_endpoint", "localhost:%d" % self.provision_port, "--control_endpoint", "localhost:0000", "--semi_persist_dir", self.tmp_dir] return subprocess.call(args, env=self.env) def test_python_boot(self): exit_code = self.run_boot_py() self.assertTrue(exit_code == 0, "the boot.py exited with non-zero code.") @unittest.skipIf(on_windows(), "'subprocess.check_output' in Windows always return empty " "string, skip this test.") def test_param_validation(self):
def test_set_working_directory(self): JProcessPythonEnvironmentManager = \ get_gateway().jvm.org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager output_file = os.path.join(self.tmp_dir, "output.txt") pyflink_dir = os.path.join(self.tmp_dir, "pyflink") os.mkdir(pyflink_dir) # just create an empty file open(os.path.join(pyflink_dir, "__init__.py"), 'a').close() fn_execution_dir = os.path.join(pyflink_dir, "fn_execution") os.mkdir(fn_execution_dir) open(os.path.join(fn_execution_dir, "__init__.py"), 'a').close() beam_dir = os.path.join(fn_execution_dir, "beam") os.mkdir(beam_dir) open(os.path.join(beam_dir, "__init__.py"), 'a').close() with open(os.path.join(beam_dir, "beam_boot.py"), "w") as f: f.write("import os\nwith open(r'%s', 'w') as f:\n f.write(os.getcwd())" % output_file) # test if the name of working directory variable of udf runner is consist with # ProcessPythonEnvironmentManager. self.env[JProcessPythonEnvironmentManager.PYTHON_WORKING_DIR] = self.tmp_dir self.env["python"] = sys.executable args = [self.runner_path] subprocess.check_output(args, env=self.env) process_cwd = None if os.path.exists(output_file): with open(output_file, 'r') as f: process_cwd = f.read() self.assertEqual(os.path.realpath(self.tmp_dir), process_cwd, "setting working directory variable is not work!") def tearDown(self): self.provision_server.stop(0) try: if self.tmp_dir is not None: shutil.rmtree(self.tmp_dir) except: pass
args = [self.runner_path] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No id provided.", exit_message) args = [self.runner_path, "--id", "1"] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No logging endpoint provided.", exit_message) args = [self.runner_path, "--id", "1", "--logging_endpoint", "localhost:0000"] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No provision endpoint provided.", exit_message) args = [self.runner_path, "--id", "1", "--logging_endpoint", "localhost:0000", "--provision_endpoint", "localhost:%d" % self.provision_port] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No control endpoint provided.", exit_message)
identifier_body
test_process_mode_boot.py
################################################################################ # 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. ################################################################################ import os import shutil import socket import subprocess import sys import tempfile import time import unittest import grpc from apache_beam.portability.api.beam_provision_api_pb2 import (ProvisionInfo, GetProvisionInfoResponse) from apache_beam.portability.api.beam_provision_api_pb2_grpc import ( ProvisionServiceServicer, add_ProvisionServiceServicer_to_server) from concurrent import futures from google.protobuf import json_format from pyflink.java_gateway import get_gateway from pyflink.pyflink_gateway_server import on_windows from pyflink.testing.test_case_utils import PyFlinkTestCase class PythonBootTests(PyFlinkTestCase): def setUp(self): provision_info = json_format.Parse('{"retrievalToken": "test_token"}', ProvisionInfo()) response = GetProvisionInfoResponse(info=provision_info) def get_unused_port(): sock = socket.socket() sock.bind(('', 0)) port = sock.getsockname()[1] sock.close() return port class ProvisionService(ProvisionServiceServicer): def GetProvisionInfo(self, request, context): return response def start_test_provision_server(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) add_ProvisionServiceServicer_to_server(ProvisionService(), server) port = get_unused_port() server.add_insecure_port('[::]:' + str(port)) server.start() return server, port self.provision_server, self.provision_port = start_test_provision_server() self.env = dict(os.environ) self.env["python"] = sys.executable self.env["FLINK_BOOT_TESTING"] = "1" self.env["BOOT_LOG_DIR"] = os.path.join(self.env["FLINK_HOME"], "log") self.tmp_dir = tempfile.mkdtemp(str(time.time()), dir=self.tempdir) # assume that this file is in flink-python source code directory. flink_python_source_root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) runner_script = "pyflink-udf-runner.bat" if on_windows() else \ "pyflink-udf-runner.sh" self.runner_path = os.path.join( flink_python_source_root, "bin", runner_script) def run_boot_py(self): args = [self.runner_path, "--id", "1", "--logging_endpoint", "localhost:0000", "--artifact_endpoint", "whatever", "--provision_endpoint", "localhost:%d" % self.provision_port, "--control_endpoint", "localhost:0000", "--semi_persist_dir", self.tmp_dir] return subprocess.call(args, env=self.env) def test_python_boot(self): exit_code = self.run_boot_py() self.assertTrue(exit_code == 0, "the boot.py exited with non-zero code.") @unittest.skipIf(on_windows(), "'subprocess.check_output' in Windows always return empty " "string, skip this test.") def test_param_validation(self): args = [self.runner_path] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No id provided.", exit_message) args = [self.runner_path, "--id", "1"] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No logging endpoint provided.", exit_message) args = [self.runner_path, "--id", "1", "--logging_endpoint", "localhost:0000"] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No provision endpoint provided.", exit_message) args = [self.runner_path, "--id", "1", "--logging_endpoint", "localhost:0000", "--provision_endpoint", "localhost:%d" % self.provision_port] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No control endpoint provided.", exit_message) def test_set_working_directory(self): JProcessPythonEnvironmentManager = \ get_gateway().jvm.org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager output_file = os.path.join(self.tmp_dir, "output.txt") pyflink_dir = os.path.join(self.tmp_dir, "pyflink") os.mkdir(pyflink_dir) # just create an empty file open(os.path.join(pyflink_dir, "__init__.py"), 'a').close() fn_execution_dir = os.path.join(pyflink_dir, "fn_execution") os.mkdir(fn_execution_dir) open(os.path.join(fn_execution_dir, "__init__.py"), 'a').close() beam_dir = os.path.join(fn_execution_dir, "beam") os.mkdir(beam_dir) open(os.path.join(beam_dir, "__init__.py"), 'a').close() with open(os.path.join(beam_dir, "beam_boot.py"), "w") as f: f.write("import os\nwith open(r'%s', 'w') as f:\n f.write(os.getcwd())" % output_file) # test if the name of working directory variable of udf runner is consist with # ProcessPythonEnvironmentManager. self.env[JProcessPythonEnvironmentManager.PYTHON_WORKING_DIR] = self.tmp_dir self.env["python"] = sys.executable args = [self.runner_path] subprocess.check_output(args, env=self.env) process_cwd = None if os.path.exists(output_file):
self.assertEqual(os.path.realpath(self.tmp_dir), process_cwd, "setting working directory variable is not work!") def tearDown(self): self.provision_server.stop(0) try: if self.tmp_dir is not None: shutil.rmtree(self.tmp_dir) except: pass
with open(output_file, 'r') as f: process_cwd = f.read()
conditional_block
test_process_mode_boot.py
################################################################################ # 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. ################################################################################ import os import shutil import socket import subprocess import sys import tempfile import time import unittest import grpc from apache_beam.portability.api.beam_provision_api_pb2 import (ProvisionInfo, GetProvisionInfoResponse) from apache_beam.portability.api.beam_provision_api_pb2_grpc import ( ProvisionServiceServicer, add_ProvisionServiceServicer_to_server) from concurrent import futures from google.protobuf import json_format from pyflink.java_gateway import get_gateway from pyflink.pyflink_gateway_server import on_windows from pyflink.testing.test_case_utils import PyFlinkTestCase class PythonBootTests(PyFlinkTestCase): def setUp(self): provision_info = json_format.Parse('{"retrievalToken": "test_token"}', ProvisionInfo()) response = GetProvisionInfoResponse(info=provision_info) def get_unused_port(): sock = socket.socket() sock.bind(('', 0)) port = sock.getsockname()[1] sock.close() return port class ProvisionService(ProvisionServiceServicer): def GetProvisionInfo(self, request, context): return response def
(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) add_ProvisionServiceServicer_to_server(ProvisionService(), server) port = get_unused_port() server.add_insecure_port('[::]:' + str(port)) server.start() return server, port self.provision_server, self.provision_port = start_test_provision_server() self.env = dict(os.environ) self.env["python"] = sys.executable self.env["FLINK_BOOT_TESTING"] = "1" self.env["BOOT_LOG_DIR"] = os.path.join(self.env["FLINK_HOME"], "log") self.tmp_dir = tempfile.mkdtemp(str(time.time()), dir=self.tempdir) # assume that this file is in flink-python source code directory. flink_python_source_root = os.path.dirname( os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) runner_script = "pyflink-udf-runner.bat" if on_windows() else \ "pyflink-udf-runner.sh" self.runner_path = os.path.join( flink_python_source_root, "bin", runner_script) def run_boot_py(self): args = [self.runner_path, "--id", "1", "--logging_endpoint", "localhost:0000", "--artifact_endpoint", "whatever", "--provision_endpoint", "localhost:%d" % self.provision_port, "--control_endpoint", "localhost:0000", "--semi_persist_dir", self.tmp_dir] return subprocess.call(args, env=self.env) def test_python_boot(self): exit_code = self.run_boot_py() self.assertTrue(exit_code == 0, "the boot.py exited with non-zero code.") @unittest.skipIf(on_windows(), "'subprocess.check_output' in Windows always return empty " "string, skip this test.") def test_param_validation(self): args = [self.runner_path] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No id provided.", exit_message) args = [self.runner_path, "--id", "1"] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No logging endpoint provided.", exit_message) args = [self.runner_path, "--id", "1", "--logging_endpoint", "localhost:0000"] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No provision endpoint provided.", exit_message) args = [self.runner_path, "--id", "1", "--logging_endpoint", "localhost:0000", "--provision_endpoint", "localhost:%d" % self.provision_port] exit_message = subprocess.check_output(args, env=self.env).decode("utf-8") self.assertIn("No control endpoint provided.", exit_message) def test_set_working_directory(self): JProcessPythonEnvironmentManager = \ get_gateway().jvm.org.apache.flink.python.env.beam.ProcessPythonEnvironmentManager output_file = os.path.join(self.tmp_dir, "output.txt") pyflink_dir = os.path.join(self.tmp_dir, "pyflink") os.mkdir(pyflink_dir) # just create an empty file open(os.path.join(pyflink_dir, "__init__.py"), 'a').close() fn_execution_dir = os.path.join(pyflink_dir, "fn_execution") os.mkdir(fn_execution_dir) open(os.path.join(fn_execution_dir, "__init__.py"), 'a').close() beam_dir = os.path.join(fn_execution_dir, "beam") os.mkdir(beam_dir) open(os.path.join(beam_dir, "__init__.py"), 'a').close() with open(os.path.join(beam_dir, "beam_boot.py"), "w") as f: f.write("import os\nwith open(r'%s', 'w') as f:\n f.write(os.getcwd())" % output_file) # test if the name of working directory variable of udf runner is consist with # ProcessPythonEnvironmentManager. self.env[JProcessPythonEnvironmentManager.PYTHON_WORKING_DIR] = self.tmp_dir self.env["python"] = sys.executable args = [self.runner_path] subprocess.check_output(args, env=self.env) process_cwd = None if os.path.exists(output_file): with open(output_file, 'r') as f: process_cwd = f.read() self.assertEqual(os.path.realpath(self.tmp_dir), process_cwd, "setting working directory variable is not work!") def tearDown(self): self.provision_server.stop(0) try: if self.tmp_dir is not None: shutil.rmtree(self.tmp_dir) except: pass
start_test_provision_server
identifier_name
platform-credentials-modal.component.spec.ts
import {async, ComponentFixture, TestBed} from "@angular/core/testing"; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {AuthService} from "../../../auth/auth.service"; import {SystemService} from "../../../platform-providers/system.service"; import {AutoCompleteComponent} from "../../../ui/auto-complete/auto-complete.component"; import {CircularLoaderComponent} from "../../../ui/circular-loader/circular-loader.component"; import {ModalService} from "../../../ui/modal/modal.service"; import {DataGatewayService} from "../../data-gateway/data-gateway.service"; import {GlobalService} from "../../global/global.service"; import {PlatformCredentialsModalComponent} from "./platform-credentials-modal.component"; import {NotificationBarService} from "../../../layout/notification-bar/notification-bar.service"; describe("PlatformCredentialsModalComponent", () => { let component: PlatformCredentialsModalComponent; let fixture: ComponentFixture<PlatformCredentialsModalComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [FormsModule, ReactiveFormsModule], declarations: [PlatformCredentialsModalComponent, AutoCompleteComponent, CircularLoaderComponent], providers: [ { provide: AuthService, useValue: {} }, { provide: GlobalService, useValue: {} }, { provide: SystemService, useValue: {} }, { provide: DataGatewayService, useValue: {} }, { provide: ModalService, useValue: {} }, { provide: NotificationBarService, useValue: {} }] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(PlatformCredentialsModalComponent);
}); it("should create", () => { expect(component).toBeTruthy(); }); });
component = fixture.componentInstance; fixture.detectChanges();
random_line_split
x86_64_linux_android.rs
// https://developer.android.com/ndk/guides/abis.html#86-64 base.features = "+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt".to_string(); base.max_atomic_width = Some(64); base.pre_link_args.entry(LinkerFlavor::Gcc).or_default().push("-m64".to_string()); // don't use probe-stack=inline-asm until rust#83139 and rust#84667 are resolved base.stack_probes = StackProbeType::Call; Target { llvm_target: "x86_64-linux-android".to_string(), pointer_width: 64, data_layout: "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" .to_string(), arch: "x86_64".to_string(), options: base, } }
use crate::spec::{LinkerFlavor, StackProbeType, Target}; pub fn target() -> Target { let mut base = super::android_base::opts(); base.cpu = "x86-64".to_string();
random_line_split
x86_64_linux_android.rs
use crate::spec::{LinkerFlavor, StackProbeType, Target}; pub fn
() -> Target { let mut base = super::android_base::opts(); base.cpu = "x86-64".to_string(); // https://developer.android.com/ndk/guides/abis.html#86-64 base.features = "+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt".to_string(); base.max_atomic_width = Some(64); base.pre_link_args.entry(LinkerFlavor::Gcc).or_default().push("-m64".to_string()); // don't use probe-stack=inline-asm until rust#83139 and rust#84667 are resolved base.stack_probes = StackProbeType::Call; Target { llvm_target: "x86_64-linux-android".to_string(), pointer_width: 64, data_layout: "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" .to_string(), arch: "x86_64".to_string(), options: base, } }
target
identifier_name
x86_64_linux_android.rs
use crate::spec::{LinkerFlavor, StackProbeType, Target}; pub fn target() -> Target
{ let mut base = super::android_base::opts(); base.cpu = "x86-64".to_string(); // https://developer.android.com/ndk/guides/abis.html#86-64 base.features = "+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt".to_string(); base.max_atomic_width = Some(64); base.pre_link_args.entry(LinkerFlavor::Gcc).or_default().push("-m64".to_string()); // don't use probe-stack=inline-asm until rust#83139 and rust#84667 are resolved base.stack_probes = StackProbeType::Call; Target { llvm_target: "x86_64-linux-android".to_string(), pointer_width: 64, data_layout: "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" .to_string(), arch: "x86_64".to_string(), options: base, } }
identifier_body
__init__.py
""" Settings and configuration for Django. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global settings file for a list of all possible variables. """ import importlib import os import time from aiohttp.log import web_logger
class ImproperlyConfigured(BaseException): def __init__(self, reason): self.reason = reason def __str__(self): return self.reason class BaseSettings(object): """ Common logic for settings whether set by a module or by the user. """ def __setattr__(self, name, value): if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'): raise ImproperlyConfigured("If set, %s must end with a slash" % name) object.__setattr__(self, name, value) class Settings(BaseSettings): def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting.isupper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module if self.SETTINGS_MODULE: try: mod = importlib.import_module(self.SETTINGS_MODULE) tuple_settings = ( "APPS", ) self._explicit_settings = set() for setting in dir(mod): if setting.isupper(): setting_value = getattr(mod, setting) if (setting in tuple_settings and not isinstance(setting_value, (list, tuple))): raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting) setattr(self, setting, setting_value) self._explicit_settings.add(setting) except ImportError: web_logger.warn("Failed to import settings module") else: web_logger.warn("No settings module specified") def is_overridden(self, setting): return setting in self._explicit_settings def __repr__(self): return '<%(cls)s "%(settings_module)s">' % { 'cls': self.__class__.__name__, 'settings_module': self.SETTINGS_MODULE, } class UserSettingsHolder(BaseSettings): """ Holder for user configured settings. """ # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. SETTINGS_MODULE = None def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.__dict__['_deleted'] = set() self.default_settings = default_settings def __getattr__(self, name): if name in self._deleted: raise AttributeError return getattr(self.default_settings, name) def __setattr__(self, name, value): self._deleted.discard(name) super(UserSettingsHolder, self).__setattr__(name, value) def __delattr__(self, name): self._deleted.add(name) if hasattr(self, name): super(UserSettingsHolder, self).__delattr__(name) def __dir__(self): return sorted( s for s in list(self.__dict__) + dir(self.default_settings) if s not in self._deleted ) def is_overridden(self, setting): deleted = (setting in self._deleted) set_locally = (setting in self.__dict__) set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting) return (deleted or set_locally or set_on_default) def __repr__(self): return '<%(cls)s>' % { 'cls': self.__class__.__name__, } settings = Settings(os.environ.get(ENVIRONMENT_VARIABLE))
from . import global_settings ENVIRONMENT_VARIABLE = "AIOWEB_SETTINGS_MODULE"
random_line_split
__init__.py
""" Settings and configuration for Django. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global settings file for a list of all possible variables. """ import importlib import os import time from aiohttp.log import web_logger from . import global_settings ENVIRONMENT_VARIABLE = "AIOWEB_SETTINGS_MODULE" class ImproperlyConfigured(BaseException): def __init__(self, reason): self.reason = reason def __str__(self): return self.reason class BaseSettings(object): """ Common logic for settings whether set by a module or by the user. """ def __setattr__(self, name, value): if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'): raise ImproperlyConfigured("If set, %s must end with a slash" % name) object.__setattr__(self, name, value) class Settings(BaseSettings): def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting.isupper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module if self.SETTINGS_MODULE: try: mod = importlib.import_module(self.SETTINGS_MODULE) tuple_settings = ( "APPS", ) self._explicit_settings = set() for setting in dir(mod): if setting.isupper(): setting_value = getattr(mod, setting) if (setting in tuple_settings and not isinstance(setting_value, (list, tuple))): raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting) setattr(self, setting, setting_value) self._explicit_settings.add(setting) except ImportError: web_logger.warn("Failed to import settings module") else: web_logger.warn("No settings module specified") def is_overridden(self, setting): return setting in self._explicit_settings def __repr__(self): return '<%(cls)s "%(settings_module)s">' % { 'cls': self.__class__.__name__, 'settings_module': self.SETTINGS_MODULE, } class
(BaseSettings): """ Holder for user configured settings. """ # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. SETTINGS_MODULE = None def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.__dict__['_deleted'] = set() self.default_settings = default_settings def __getattr__(self, name): if name in self._deleted: raise AttributeError return getattr(self.default_settings, name) def __setattr__(self, name, value): self._deleted.discard(name) super(UserSettingsHolder, self).__setattr__(name, value) def __delattr__(self, name): self._deleted.add(name) if hasattr(self, name): super(UserSettingsHolder, self).__delattr__(name) def __dir__(self): return sorted( s for s in list(self.__dict__) + dir(self.default_settings) if s not in self._deleted ) def is_overridden(self, setting): deleted = (setting in self._deleted) set_locally = (setting in self.__dict__) set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting) return (deleted or set_locally or set_on_default) def __repr__(self): return '<%(cls)s>' % { 'cls': self.__class__.__name__, } settings = Settings(os.environ.get(ENVIRONMENT_VARIABLE))
UserSettingsHolder
identifier_name
__init__.py
""" Settings and configuration for Django. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global settings file for a list of all possible variables. """ import importlib import os import time from aiohttp.log import web_logger from . import global_settings ENVIRONMENT_VARIABLE = "AIOWEB_SETTINGS_MODULE" class ImproperlyConfigured(BaseException): def __init__(self, reason): self.reason = reason def __str__(self): return self.reason class BaseSettings(object): """ Common logic for settings whether set by a module or by the user. """ def __setattr__(self, name, value): if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'): raise ImproperlyConfigured("If set, %s must end with a slash" % name) object.__setattr__(self, name, value) class Settings(BaseSettings): def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting.isupper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module if self.SETTINGS_MODULE: try: mod = importlib.import_module(self.SETTINGS_MODULE) tuple_settings = ( "APPS", ) self._explicit_settings = set() for setting in dir(mod): if setting.isupper(): setting_value = getattr(mod, setting) if (setting in tuple_settings and not isinstance(setting_value, (list, tuple))): raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting) setattr(self, setting, setting_value) self._explicit_settings.add(setting) except ImportError: web_logger.warn("Failed to import settings module") else: web_logger.warn("No settings module specified") def is_overridden(self, setting): return setting in self._explicit_settings def __repr__(self): return '<%(cls)s "%(settings_module)s">' % { 'cls': self.__class__.__name__, 'settings_module': self.SETTINGS_MODULE, } class UserSettingsHolder(BaseSettings): """ Holder for user configured settings. """ # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. SETTINGS_MODULE = None def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.__dict__['_deleted'] = set() self.default_settings = default_settings def __getattr__(self, name): if name in self._deleted: raise AttributeError return getattr(self.default_settings, name) def __setattr__(self, name, value):
def __delattr__(self, name): self._deleted.add(name) if hasattr(self, name): super(UserSettingsHolder, self).__delattr__(name) def __dir__(self): return sorted( s for s in list(self.__dict__) + dir(self.default_settings) if s not in self._deleted ) def is_overridden(self, setting): deleted = (setting in self._deleted) set_locally = (setting in self.__dict__) set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting) return (deleted or set_locally or set_on_default) def __repr__(self): return '<%(cls)s>' % { 'cls': self.__class__.__name__, } settings = Settings(os.environ.get(ENVIRONMENT_VARIABLE))
self._deleted.discard(name) super(UserSettingsHolder, self).__setattr__(name, value)
identifier_body
__init__.py
""" Settings and configuration for Django. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global settings file for a list of all possible variables. """ import importlib import os import time from aiohttp.log import web_logger from . import global_settings ENVIRONMENT_VARIABLE = "AIOWEB_SETTINGS_MODULE" class ImproperlyConfigured(BaseException): def __init__(self, reason): self.reason = reason def __str__(self): return self.reason class BaseSettings(object): """ Common logic for settings whether set by a module or by the user. """ def __setattr__(self, name, value): if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'): raise ImproperlyConfigured("If set, %s must end with a slash" % name) object.__setattr__(self, name, value) class Settings(BaseSettings): def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings):
# store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module if self.SETTINGS_MODULE: try: mod = importlib.import_module(self.SETTINGS_MODULE) tuple_settings = ( "APPS", ) self._explicit_settings = set() for setting in dir(mod): if setting.isupper(): setting_value = getattr(mod, setting) if (setting in tuple_settings and not isinstance(setting_value, (list, tuple))): raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting) setattr(self, setting, setting_value) self._explicit_settings.add(setting) except ImportError: web_logger.warn("Failed to import settings module") else: web_logger.warn("No settings module specified") def is_overridden(self, setting): return setting in self._explicit_settings def __repr__(self): return '<%(cls)s "%(settings_module)s">' % { 'cls': self.__class__.__name__, 'settings_module': self.SETTINGS_MODULE, } class UserSettingsHolder(BaseSettings): """ Holder for user configured settings. """ # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. SETTINGS_MODULE = None def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.__dict__['_deleted'] = set() self.default_settings = default_settings def __getattr__(self, name): if name in self._deleted: raise AttributeError return getattr(self.default_settings, name) def __setattr__(self, name, value): self._deleted.discard(name) super(UserSettingsHolder, self).__setattr__(name, value) def __delattr__(self, name): self._deleted.add(name) if hasattr(self, name): super(UserSettingsHolder, self).__delattr__(name) def __dir__(self): return sorted( s for s in list(self.__dict__) + dir(self.default_settings) if s not in self._deleted ) def is_overridden(self, setting): deleted = (setting in self._deleted) set_locally = (setting in self.__dict__) set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting) return (deleted or set_locally or set_on_default) def __repr__(self): return '<%(cls)s>' % { 'cls': self.__class__.__name__, } settings = Settings(os.environ.get(ENVIRONMENT_VARIABLE))
if setting.isupper(): setattr(self, setting, getattr(global_settings, setting))
conditional_block
munging.js
var d3 = require('d3'); function true_index(arr, config) { // Series.ix[start, end].true().index; if (!config) { config = {}; } if (!config.length) { config.length = arr.length } config.start = config.start ? config.start : 0; config.end = config.end ? config.end : config.length; var valid = new Array(config.length); var j = 0; for (var i=config.start; i <= config.end; i++) { if (arr[i]) { valid[j] = i; j++; } } valid = valid.slice(0, j); return valid; } function where(arr, mask) { var data = arr.slice(0); for (var i=0; i < data.length; i++) { if (!mask[i])
} return data; } module.exports.true_index = true_index; module.exports.where = where; mask = [true, true, false, false, true, false] series = d3.range(mask.length); res = true_index(mask, {}); res = true_index(mask, {'start':1}); res = where(series, mask);
{ data[i] = null; }
conditional_block
munging.js
var d3 = require('d3'); function true_index(arr, config) { // Series.ix[start, end].true().index; if (!config) { config = {}; } if (!config.length) { config.length = arr.length } config.start = config.start ? config.start : 0; config.end = config.end ? config.end : config.length; var valid = new Array(config.length); var j = 0; for (var i=config.start; i <= config.end; i++) {
} valid = valid.slice(0, j); return valid; } function where(arr, mask) { var data = arr.slice(0); for (var i=0; i < data.length; i++) { if (!mask[i]) { data[i] = null; } } return data; } module.exports.true_index = true_index; module.exports.where = where; mask = [true, true, false, false, true, false] series = d3.range(mask.length); res = true_index(mask, {}); res = true_index(mask, {'start':1}); res = where(series, mask);
if (arr[i]) { valid[j] = i; j++; }
random_line_split
munging.js
var d3 = require('d3'); function true_index(arr, config)
function where(arr, mask) { var data = arr.slice(0); for (var i=0; i < data.length; i++) { if (!mask[i]) { data[i] = null; } } return data; } module.exports.true_index = true_index; module.exports.where = where; mask = [true, true, false, false, true, false] series = d3.range(mask.length); res = true_index(mask, {}); res = true_index(mask, {'start':1}); res = where(series, mask);
{ // Series.ix[start, end].true().index; if (!config) { config = {}; } if (!config.length) { config.length = arr.length } config.start = config.start ? config.start : 0; config.end = config.end ? config.end : config.length; var valid = new Array(config.length); var j = 0; for (var i=config.start; i <= config.end; i++) { if (arr[i]) { valid[j] = i; j++; } } valid = valid.slice(0, j); return valid; }
identifier_body
munging.js
var d3 = require('d3'); function
(arr, config) { // Series.ix[start, end].true().index; if (!config) { config = {}; } if (!config.length) { config.length = arr.length } config.start = config.start ? config.start : 0; config.end = config.end ? config.end : config.length; var valid = new Array(config.length); var j = 0; for (var i=config.start; i <= config.end; i++) { if (arr[i]) { valid[j] = i; j++; } } valid = valid.slice(0, j); return valid; } function where(arr, mask) { var data = arr.slice(0); for (var i=0; i < data.length; i++) { if (!mask[i]) { data[i] = null; } } return data; } module.exports.true_index = true_index; module.exports.where = where; mask = [true, true, false, false, true, false] series = d3.range(mask.length); res = true_index(mask, {}); res = true_index(mask, {'start':1}); res = where(series, mask);
true_index
identifier_name
sync.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use ethsync::PeerInfo as SyncPeerInfo; use serde::{Serialize, Serializer}; use v1::types::U256; /// Sync info #[derive(Default, Debug, Serialize, PartialEq)] pub struct SyncInfo { /// Starting block #[serde(rename="startingBlock")] pub starting_block: U256, /// Current block #[serde(rename="currentBlock")] pub current_block: U256, /// Highest block seen so far #[serde(rename="highestBlock")] pub highest_block: U256, } /// Peers info #[derive(Default, Debug, Serialize)] pub struct Peers { /// Number of active peers pub active: usize, /// Number of connected peers pub connected: usize, /// Max number of peers pub max: u32, /// Detailed information on peers pub peers: Vec<PeerInfo>, } /// Peer connection information #[derive(Default, Debug, Serialize)] pub struct PeerInfo { /// Public node id pub id: Option<String>,
/// Network information pub network: PeerNetworkInfo, /// Protocols information pub protocols: PeerProtocolsInfo, } /// Peer network information #[derive(Default, Debug, Serialize)] pub struct PeerNetworkInfo { /// Remote endpoint address #[serde(rename="remoteAddress")] pub remote_address: String, /// Local endpoint address #[serde(rename="localAddress")] pub local_address: String, } /// Peer protocols information #[derive(Default, Debug, Serialize)] pub struct PeerProtocolsInfo { /// Ethereum protocol information pub eth: Option<PeerEthereumProtocolInfo>, } /// Peer Ethereum protocol information #[derive(Default, Debug, Serialize)] pub struct PeerEthereumProtocolInfo { /// Negotiated ethereum protocol version pub version: u32, /// Peer total difficulty if known pub difficulty: Option<U256>, /// SHA3 of peer best block hash pub head: String, } /// Sync status #[derive(Debug, PartialEq)] pub enum SyncStatus { /// Info when syncing Info(SyncInfo), /// Not syncing None } impl Serialize for SyncStatus { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { match *self { SyncStatus::Info(ref info) => info.serialize(serializer), SyncStatus::None => false.serialize(serializer) } } } impl From<SyncPeerInfo> for PeerInfo { fn from(p: SyncPeerInfo) -> PeerInfo { PeerInfo { id: p.id, name: p.client_version, caps: p.capabilities, network: PeerNetworkInfo { remote_address: p.remote_address, local_address: p.local_address, }, protocols: PeerProtocolsInfo { eth: Some(PeerEthereumProtocolInfo { version: p.eth_version, difficulty: p.eth_difficulty.map(|d| d.into()), head: p.eth_head.hex(), }) }, } } } #[cfg(test)] mod tests { use serde_json; use super::{SyncInfo, SyncStatus, Peers}; #[test] fn test_serialize_sync_info() { let t = SyncInfo::default(); let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, r#"{"startingBlock":"0x0","currentBlock":"0x0","highestBlock":"0x0"}"#); } #[test] fn test_serialize_peers() { let t = Peers::default(); let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, r#"{"active":0,"connected":0,"max":0,"peers":[]}"#); } #[test] fn test_serialize_sync_status() { let t = SyncStatus::None; let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, "false"); let t = SyncStatus::Info(SyncInfo::default()); let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, r#"{"startingBlock":"0x0","currentBlock":"0x0","highestBlock":"0x0"}"#); } }
/// Node client ID pub name: String, /// Capabilities pub caps: Vec<String>,
random_line_split
sync.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use ethsync::PeerInfo as SyncPeerInfo; use serde::{Serialize, Serializer}; use v1::types::U256; /// Sync info #[derive(Default, Debug, Serialize, PartialEq)] pub struct SyncInfo { /// Starting block #[serde(rename="startingBlock")] pub starting_block: U256, /// Current block #[serde(rename="currentBlock")] pub current_block: U256, /// Highest block seen so far #[serde(rename="highestBlock")] pub highest_block: U256, } /// Peers info #[derive(Default, Debug, Serialize)] pub struct Peers { /// Number of active peers pub active: usize, /// Number of connected peers pub connected: usize, /// Max number of peers pub max: u32, /// Detailed information on peers pub peers: Vec<PeerInfo>, } /// Peer connection information #[derive(Default, Debug, Serialize)] pub struct PeerInfo { /// Public node id pub id: Option<String>, /// Node client ID pub name: String, /// Capabilities pub caps: Vec<String>, /// Network information pub network: PeerNetworkInfo, /// Protocols information pub protocols: PeerProtocolsInfo, } /// Peer network information #[derive(Default, Debug, Serialize)] pub struct PeerNetworkInfo { /// Remote endpoint address #[serde(rename="remoteAddress")] pub remote_address: String, /// Local endpoint address #[serde(rename="localAddress")] pub local_address: String, } /// Peer protocols information #[derive(Default, Debug, Serialize)] pub struct PeerProtocolsInfo { /// Ethereum protocol information pub eth: Option<PeerEthereumProtocolInfo>, } /// Peer Ethereum protocol information #[derive(Default, Debug, Serialize)] pub struct PeerEthereumProtocolInfo { /// Negotiated ethereum protocol version pub version: u32, /// Peer total difficulty if known pub difficulty: Option<U256>, /// SHA3 of peer best block hash pub head: String, } /// Sync status #[derive(Debug, PartialEq)] pub enum SyncStatus { /// Info when syncing Info(SyncInfo), /// Not syncing None } impl Serialize for SyncStatus { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { match *self { SyncStatus::Info(ref info) => info.serialize(serializer), SyncStatus::None => false.serialize(serializer) } } } impl From<SyncPeerInfo> for PeerInfo { fn from(p: SyncPeerInfo) -> PeerInfo { PeerInfo { id: p.id, name: p.client_version, caps: p.capabilities, network: PeerNetworkInfo { remote_address: p.remote_address, local_address: p.local_address, }, protocols: PeerProtocolsInfo { eth: Some(PeerEthereumProtocolInfo { version: p.eth_version, difficulty: p.eth_difficulty.map(|d| d.into()), head: p.eth_head.hex(), }) }, } } } #[cfg(test)] mod tests { use serde_json; use super::{SyncInfo, SyncStatus, Peers}; #[test] fn test_serialize_sync_info()
#[test] fn test_serialize_peers() { let t = Peers::default(); let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, r#"{"active":0,"connected":0,"max":0,"peers":[]}"#); } #[test] fn test_serialize_sync_status() { let t = SyncStatus::None; let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, "false"); let t = SyncStatus::Info(SyncInfo::default()); let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, r#"{"startingBlock":"0x0","currentBlock":"0x0","highestBlock":"0x0"}"#); } }
{ let t = SyncInfo::default(); let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, r#"{"startingBlock":"0x0","currentBlock":"0x0","highestBlock":"0x0"}"#); }
identifier_body
sync.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use ethsync::PeerInfo as SyncPeerInfo; use serde::{Serialize, Serializer}; use v1::types::U256; /// Sync info #[derive(Default, Debug, Serialize, PartialEq)] pub struct SyncInfo { /// Starting block #[serde(rename="startingBlock")] pub starting_block: U256, /// Current block #[serde(rename="currentBlock")] pub current_block: U256, /// Highest block seen so far #[serde(rename="highestBlock")] pub highest_block: U256, } /// Peers info #[derive(Default, Debug, Serialize)] pub struct Peers { /// Number of active peers pub active: usize, /// Number of connected peers pub connected: usize, /// Max number of peers pub max: u32, /// Detailed information on peers pub peers: Vec<PeerInfo>, } /// Peer connection information #[derive(Default, Debug, Serialize)] pub struct
{ /// Public node id pub id: Option<String>, /// Node client ID pub name: String, /// Capabilities pub caps: Vec<String>, /// Network information pub network: PeerNetworkInfo, /// Protocols information pub protocols: PeerProtocolsInfo, } /// Peer network information #[derive(Default, Debug, Serialize)] pub struct PeerNetworkInfo { /// Remote endpoint address #[serde(rename="remoteAddress")] pub remote_address: String, /// Local endpoint address #[serde(rename="localAddress")] pub local_address: String, } /// Peer protocols information #[derive(Default, Debug, Serialize)] pub struct PeerProtocolsInfo { /// Ethereum protocol information pub eth: Option<PeerEthereumProtocolInfo>, } /// Peer Ethereum protocol information #[derive(Default, Debug, Serialize)] pub struct PeerEthereumProtocolInfo { /// Negotiated ethereum protocol version pub version: u32, /// Peer total difficulty if known pub difficulty: Option<U256>, /// SHA3 of peer best block hash pub head: String, } /// Sync status #[derive(Debug, PartialEq)] pub enum SyncStatus { /// Info when syncing Info(SyncInfo), /// Not syncing None } impl Serialize for SyncStatus { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { match *self { SyncStatus::Info(ref info) => info.serialize(serializer), SyncStatus::None => false.serialize(serializer) } } } impl From<SyncPeerInfo> for PeerInfo { fn from(p: SyncPeerInfo) -> PeerInfo { PeerInfo { id: p.id, name: p.client_version, caps: p.capabilities, network: PeerNetworkInfo { remote_address: p.remote_address, local_address: p.local_address, }, protocols: PeerProtocolsInfo { eth: Some(PeerEthereumProtocolInfo { version: p.eth_version, difficulty: p.eth_difficulty.map(|d| d.into()), head: p.eth_head.hex(), }) }, } } } #[cfg(test)] mod tests { use serde_json; use super::{SyncInfo, SyncStatus, Peers}; #[test] fn test_serialize_sync_info() { let t = SyncInfo::default(); let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, r#"{"startingBlock":"0x0","currentBlock":"0x0","highestBlock":"0x0"}"#); } #[test] fn test_serialize_peers() { let t = Peers::default(); let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, r#"{"active":0,"connected":0,"max":0,"peers":[]}"#); } #[test] fn test_serialize_sync_status() { let t = SyncStatus::None; let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, "false"); let t = SyncStatus::Info(SyncInfo::default()); let serialized = serde_json::to_string(&t).unwrap(); assert_eq!(serialized, r#"{"startingBlock":"0x0","currentBlock":"0x0","highestBlock":"0x0"}"#); } }
PeerInfo
identifier_name
timeline.js
var events = {}; function showEvent(e) { eid = e.getAttribute('data-event-id'); fid = e.getAttribute('data-frame-id'); var url = '?view=event&eid='+eid+'&fid='+fid; url += filterQuery; window.location.href = url; //video element is blocking video elements elsewhere in chrome possible interaction with mouseover event? //FIXME unless an exact cause can be determined should store all video controls and do something to the other controls when we want to load a new video seek etc or whatever may block /*var vid= $('preview'); vid.oncanplay=null; // vid.currentTime=vid.currentTime-0.1; vid.pause();*/ } function
(zm_event, frame) { var eventHtml = new Element('div'); if ( zm_event.Archived > 0 ) { eventHtml.addClass('archived'); } new Element('p').inject(eventHtml).set('text', monitors[zm_event.MonitorId].Name); new Element('p').inject(eventHtml).set('text', zm_event.Name+(frame?('('+frame.FrameId+')'):'')); new Element('p').inject(eventHtml).set('text', zm_event.StartTime+' - '+zm_event.Length+'s'); new Element('p').inject(eventHtml).set('text', zm_event.Cause); if ( event.Notes ) { new Element('p').inject(eventHtml).set('text', event.Notes); } if ( event.Archived > 0 ) { new Element('p').inject(eventHtml).set( 'text', archivedString); } return eventHtml; } function showEventDetail( eventHtml ) { $('instruction').addClass( 'hidden' ); $('eventData').empty(); $('eventData').adopt( eventHtml ); $('eventData').removeClass( 'hidden' ); } function eventDataResponse( respObj, respText ) { var zm_event = respObj.event; if ( !zm_event ) { console.log('Null event'); return; } events[zm_event.Id] = zm_event; if ( respObj.loopback ) { requestFrameData(zm_event.Id, respObj.loopback); } } function frameDataResponse( respObj, respText ) { var frame = respObj.frameimage; if ( !frame.FrameId ) { console.log('Null frame'); return; } var zm_event = events[frame.EventId]; if ( !zm_event ) { console.error('No event '+frame.eventId+' found'); return; } if ( !zm_event['frames'] ) { console.log("No frames data in event response"); console.log(zm_event); console.log(respObj); zm_event['frames'] = {}; } zm_event['frames'][frame.FrameId] = frame; zm_event['frames'][frame.FrameId]['html'] = createEventHtml( zm_event, frame ); showEventData(frame.EventId, frame.FrameId); } function showEventData(eventId, frameId) { if ( events[eventId] ) { var zm_event = events[eventId]; if ( zm_event['frames'] ) { if ( zm_event['frames'][frameId] ) { showEventDetail( zm_event['frames'][frameId]['html'] ); var imagePath = 'index.php?view=image&eid='+eventId+'&fid='+frameId; var videoName = zm_event.DefaultVideo; loadEventImage( imagePath, eventId, frameId, zm_event.Width, zm_event.Height, zm_event.Frames/zm_event.Length, videoName, zm_event.Length, zm_event.StartTime, monitors[zm_event.MonitorId]); return; } else { console.log('No frames for ' + frameId); } } else { console.log('No frames'); } } else { console.log('No event for ' + eventId); } } var eventQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: eventDataResponse }); var frameQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: frameDataResponse }); function requestFrameData( eventId, frameId ) { if ( !events[eventId] ) { eventQuery.options.data = "view=request&request=status&entity=event&id="+eventId+"&loopback="+frameId; eventQuery.send(); } else { frameQuery.options.data = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId; frameQuery.send(); } } function previewEvent(slot) { eventId = slot.getAttribute('data-event-id'); frameId = slot.getAttribute('data-frame-id'); if ( events[eventId] ) { showEventData(eventId, frameId); } else { requestFrameData(eventId, frameId); } } function loadEventImage( imagePath, eid, fid, width, height, fps, videoName, duration, startTime, Monitor ) { var vid = $('preview'); var imageSrc = $('imageSrc'); if ( videoName && vid ) { vid.show(); imageSrc.hide(); var newsource=imagePath.slice(0, imagePath.lastIndexOf('/'))+'/'+videoName; //console.log(newsource); //console.log(sources[0].src.slice(-newsource.length)); if ( newsource != vid.currentSrc.slice(-newsource.length) || vid.readyState == 0 ) { //console.log("loading new"); //it is possible to set a long source list here will that be unworkable? var sources = vid.getElementsByTagName('source'); sources[0].src = newsource; var tracks = vid.getElementsByTagName('track'); if (tracks.length) { tracks[0].parentNode.removeChild(tracks[0]); } vid.load(); addVideoTimingTrack(vid, Monitor.LabelFormat, Monitor.Name, duration, startTime); vid.currentTime = fid/fps; } else { if ( ! vid.seeking ) { vid.currentTime=fid/fps; } } } else { if ( vid ) vid.hide(); imageSrc.show(); imageSrc.setProperty('src', imagePath); imageSrc.setAttribute('data-event-id', eid); imageSrc.setAttribute('data-frame-id', fid); imageSrc.onclick=window['showEvent'].bind(imageSrc, imageSrc); } var eventData = $('eventData'); eventData.removeEvent('click'); eventData.addEvent('click', showEvent.pass()); } function tlZoomBounds( minTime, maxTime ) { location.replace('?view='+currentView+filterQuery+'&minTime='+minTime+'&maxTime='+maxTime); } function tlZoomOut() { location.replace('?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+zoom_range); } function tlPanLeft() { location.replace('?view='+currentView+filterQuery+'&midTime='+minTime+'&range='+range); } function tlPanRight() { location.replace('?view='+currentView+filterQuery+'&midTime='+maxTime+'&range='+range); } window.addEventListener("DOMContentLoaded", function() { document.querySelectorAll("div.event").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); document.querySelectorAll("div.activity").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); });
createEventHtml
identifier_name
timeline.js
var events = {}; function showEvent(e) { eid = e.getAttribute('data-event-id'); fid = e.getAttribute('data-frame-id'); var url = '?view=event&eid='+eid+'&fid='+fid; url += filterQuery; window.location.href = url; //video element is blocking video elements elsewhere in chrome possible interaction with mouseover event? //FIXME unless an exact cause can be determined should store all video controls and do something to the other controls when we want to load a new video seek etc or whatever may block /*var vid= $('preview'); vid.oncanplay=null; // vid.currentTime=vid.currentTime-0.1; vid.pause();*/ } function createEventHtml(zm_event, frame) { var eventHtml = new Element('div'); if ( zm_event.Archived > 0 ) { eventHtml.addClass('archived'); } new Element('p').inject(eventHtml).set('text', monitors[zm_event.MonitorId].Name); new Element('p').inject(eventHtml).set('text', zm_event.Name+(frame?('('+frame.FrameId+')'):'')); new Element('p').inject(eventHtml).set('text', zm_event.StartTime+' - '+zm_event.Length+'s'); new Element('p').inject(eventHtml).set('text', zm_event.Cause); if ( event.Notes ) { new Element('p').inject(eventHtml).set('text', event.Notes); } if ( event.Archived > 0 ) { new Element('p').inject(eventHtml).set( 'text', archivedString); } return eventHtml; } function showEventDetail( eventHtml ) { $('instruction').addClass( 'hidden' ); $('eventData').empty(); $('eventData').adopt( eventHtml ); $('eventData').removeClass( 'hidden' ); } function eventDataResponse( respObj, respText ) { var zm_event = respObj.event; if ( !zm_event ) { console.log('Null event'); return; } events[zm_event.Id] = zm_event; if ( respObj.loopback ) { requestFrameData(zm_event.Id, respObj.loopback); } } function frameDataResponse( respObj, respText ) { var frame = respObj.frameimage; if ( !frame.FrameId ) { console.log('Null frame'); return; } var zm_event = events[frame.EventId]; if ( !zm_event ) { console.error('No event '+frame.eventId+' found'); return; } if ( !zm_event['frames'] ) { console.log("No frames data in event response"); console.log(zm_event); console.log(respObj); zm_event['frames'] = {}; } zm_event['frames'][frame.FrameId] = frame; zm_event['frames'][frame.FrameId]['html'] = createEventHtml( zm_event, frame ); showEventData(frame.EventId, frame.FrameId); } function showEventData(eventId, frameId) { if ( events[eventId] ) { var zm_event = events[eventId]; if ( zm_event['frames'] ) { if ( zm_event['frames'][frameId] ) { showEventDetail( zm_event['frames'][frameId]['html'] ); var imagePath = 'index.php?view=image&eid='+eventId+'&fid='+frameId; var videoName = zm_event.DefaultVideo; loadEventImage( imagePath, eventId, frameId, zm_event.Width, zm_event.Height, zm_event.Frames/zm_event.Length, videoName, zm_event.Length, zm_event.StartTime, monitors[zm_event.MonitorId]); return; } else { console.log('No frames for ' + frameId); } } else { console.log('No frames'); } } else { console.log('No event for ' + eventId); } } var eventQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: eventDataResponse }); var frameQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: frameDataResponse }); function requestFrameData( eventId, frameId )
function previewEvent(slot) { eventId = slot.getAttribute('data-event-id'); frameId = slot.getAttribute('data-frame-id'); if ( events[eventId] ) { showEventData(eventId, frameId); } else { requestFrameData(eventId, frameId); } } function loadEventImage( imagePath, eid, fid, width, height, fps, videoName, duration, startTime, Monitor ) { var vid = $('preview'); var imageSrc = $('imageSrc'); if ( videoName && vid ) { vid.show(); imageSrc.hide(); var newsource=imagePath.slice(0, imagePath.lastIndexOf('/'))+'/'+videoName; //console.log(newsource); //console.log(sources[0].src.slice(-newsource.length)); if ( newsource != vid.currentSrc.slice(-newsource.length) || vid.readyState == 0 ) { //console.log("loading new"); //it is possible to set a long source list here will that be unworkable? var sources = vid.getElementsByTagName('source'); sources[0].src = newsource; var tracks = vid.getElementsByTagName('track'); if (tracks.length) { tracks[0].parentNode.removeChild(tracks[0]); } vid.load(); addVideoTimingTrack(vid, Monitor.LabelFormat, Monitor.Name, duration, startTime); vid.currentTime = fid/fps; } else { if ( ! vid.seeking ) { vid.currentTime=fid/fps; } } } else { if ( vid ) vid.hide(); imageSrc.show(); imageSrc.setProperty('src', imagePath); imageSrc.setAttribute('data-event-id', eid); imageSrc.setAttribute('data-frame-id', fid); imageSrc.onclick=window['showEvent'].bind(imageSrc, imageSrc); } var eventData = $('eventData'); eventData.removeEvent('click'); eventData.addEvent('click', showEvent.pass()); } function tlZoomBounds( minTime, maxTime ) { location.replace('?view='+currentView+filterQuery+'&minTime='+minTime+'&maxTime='+maxTime); } function tlZoomOut() { location.replace('?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+zoom_range); } function tlPanLeft() { location.replace('?view='+currentView+filterQuery+'&midTime='+minTime+'&range='+range); } function tlPanRight() { location.replace('?view='+currentView+filterQuery+'&midTime='+maxTime+'&range='+range); } window.addEventListener("DOMContentLoaded", function() { document.querySelectorAll("div.event").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); document.querySelectorAll("div.activity").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); });
{ if ( !events[eventId] ) { eventQuery.options.data = "view=request&request=status&entity=event&id="+eventId+"&loopback="+frameId; eventQuery.send(); } else { frameQuery.options.data = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId; frameQuery.send(); } }
identifier_body
timeline.js
var events = {}; function showEvent(e) { eid = e.getAttribute('data-event-id'); fid = e.getAttribute('data-frame-id'); var url = '?view=event&eid='+eid+'&fid='+fid; url += filterQuery; window.location.href = url; //video element is blocking video elements elsewhere in chrome possible interaction with mouseover event? //FIXME unless an exact cause can be determined should store all video controls and do something to the other controls when we want to load a new video seek etc or whatever may block /*var vid= $('preview'); vid.oncanplay=null; // vid.currentTime=vid.currentTime-0.1; vid.pause();*/ } function createEventHtml(zm_event, frame) { var eventHtml = new Element('div'); if ( zm_event.Archived > 0 ) { eventHtml.addClass('archived'); } new Element('p').inject(eventHtml).set('text', monitors[zm_event.MonitorId].Name); new Element('p').inject(eventHtml).set('text', zm_event.Name+(frame?('('+frame.FrameId+')'):'')); new Element('p').inject(eventHtml).set('text', zm_event.StartTime+' - '+zm_event.Length+'s'); new Element('p').inject(eventHtml).set('text', zm_event.Cause); if ( event.Notes ) { new Element('p').inject(eventHtml).set('text', event.Notes); } if ( event.Archived > 0 ) { new Element('p').inject(eventHtml).set( 'text', archivedString); } return eventHtml; } function showEventDetail( eventHtml ) { $('instruction').addClass( 'hidden' ); $('eventData').empty(); $('eventData').adopt( eventHtml ); $('eventData').removeClass( 'hidden' ); } function eventDataResponse( respObj, respText ) { var zm_event = respObj.event; if ( !zm_event ) { console.log('Null event'); return; } events[zm_event.Id] = zm_event; if ( respObj.loopback ) { requestFrameData(zm_event.Id, respObj.loopback); } } function frameDataResponse( respObj, respText ) { var frame = respObj.frameimage; if ( !frame.FrameId ) { console.log('Null frame'); return; } var zm_event = events[frame.EventId]; if ( !zm_event ) { console.error('No event '+frame.eventId+' found'); return; } if ( !zm_event['frames'] ) { console.log("No frames data in event response"); console.log(zm_event); console.log(respObj); zm_event['frames'] = {}; } zm_event['frames'][frame.FrameId] = frame; zm_event['frames'][frame.FrameId]['html'] = createEventHtml( zm_event, frame ); showEventData(frame.EventId, frame.FrameId); } function showEventData(eventId, frameId) { if ( events[eventId] ) { var zm_event = events[eventId]; if ( zm_event['frames'] ) { if ( zm_event['frames'][frameId] ) { showEventDetail( zm_event['frames'][frameId]['html'] ); var imagePath = 'index.php?view=image&eid='+eventId+'&fid='+frameId; var videoName = zm_event.DefaultVideo; loadEventImage( imagePath, eventId, frameId, zm_event.Width, zm_event.Height, zm_event.Frames/zm_event.Length, videoName, zm_event.Length, zm_event.StartTime, monitors[zm_event.MonitorId]); return; } else { console.log('No frames for ' + frameId); } } else { console.log('No frames'); } } else { console.log('No event for ' + eventId); } } var eventQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: eventDataResponse }); var frameQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: frameDataResponse }); function requestFrameData( eventId, frameId ) { if ( !events[eventId] ) { eventQuery.options.data = "view=request&request=status&entity=event&id="+eventId+"&loopback="+frameId; eventQuery.send(); } else { frameQuery.options.data = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId; frameQuery.send(); } } function previewEvent(slot) { eventId = slot.getAttribute('data-event-id'); frameId = slot.getAttribute('data-frame-id'); if ( events[eventId] ) { showEventData(eventId, frameId); } else
} function loadEventImage( imagePath, eid, fid, width, height, fps, videoName, duration, startTime, Monitor ) { var vid = $('preview'); var imageSrc = $('imageSrc'); if ( videoName && vid ) { vid.show(); imageSrc.hide(); var newsource=imagePath.slice(0, imagePath.lastIndexOf('/'))+'/'+videoName; //console.log(newsource); //console.log(sources[0].src.slice(-newsource.length)); if ( newsource != vid.currentSrc.slice(-newsource.length) || vid.readyState == 0 ) { //console.log("loading new"); //it is possible to set a long source list here will that be unworkable? var sources = vid.getElementsByTagName('source'); sources[0].src = newsource; var tracks = vid.getElementsByTagName('track'); if (tracks.length) { tracks[0].parentNode.removeChild(tracks[0]); } vid.load(); addVideoTimingTrack(vid, Monitor.LabelFormat, Monitor.Name, duration, startTime); vid.currentTime = fid/fps; } else { if ( ! vid.seeking ) { vid.currentTime=fid/fps; } } } else { if ( vid ) vid.hide(); imageSrc.show(); imageSrc.setProperty('src', imagePath); imageSrc.setAttribute('data-event-id', eid); imageSrc.setAttribute('data-frame-id', fid); imageSrc.onclick=window['showEvent'].bind(imageSrc, imageSrc); } var eventData = $('eventData'); eventData.removeEvent('click'); eventData.addEvent('click', showEvent.pass()); } function tlZoomBounds( minTime, maxTime ) { location.replace('?view='+currentView+filterQuery+'&minTime='+minTime+'&maxTime='+maxTime); } function tlZoomOut() { location.replace('?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+zoom_range); } function tlPanLeft() { location.replace('?view='+currentView+filterQuery+'&midTime='+minTime+'&range='+range); } function tlPanRight() { location.replace('?view='+currentView+filterQuery+'&midTime='+maxTime+'&range='+range); } window.addEventListener("DOMContentLoaded", function() { document.querySelectorAll("div.event").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); document.querySelectorAll("div.activity").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); });
{ requestFrameData(eventId, frameId); }
conditional_block
timeline.js
var events = {}; function showEvent(e) { eid = e.getAttribute('data-event-id'); fid = e.getAttribute('data-frame-id'); var url = '?view=event&eid='+eid+'&fid='+fid; url += filterQuery; window.location.href = url; //video element is blocking video elements elsewhere in chrome possible interaction with mouseover event? //FIXME unless an exact cause can be determined should store all video controls and do something to the other controls when we want to load a new video seek etc or whatever may block /*var vid= $('preview'); vid.oncanplay=null; // vid.currentTime=vid.currentTime-0.1; vid.pause();*/ } function createEventHtml(zm_event, frame) { var eventHtml = new Element('div'); if ( zm_event.Archived > 0 ) { eventHtml.addClass('archived'); } new Element('p').inject(eventHtml).set('text', monitors[zm_event.MonitorId].Name); new Element('p').inject(eventHtml).set('text', zm_event.Name+(frame?('('+frame.FrameId+')'):'')); new Element('p').inject(eventHtml).set('text', zm_event.StartTime+' - '+zm_event.Length+'s'); new Element('p').inject(eventHtml).set('text', zm_event.Cause); if ( event.Notes ) { new Element('p').inject(eventHtml).set('text', event.Notes); } if ( event.Archived > 0 ) { new Element('p').inject(eventHtml).set( 'text', archivedString); } return eventHtml; } function showEventDetail( eventHtml ) { $('instruction').addClass( 'hidden' ); $('eventData').empty(); $('eventData').adopt( eventHtml ); $('eventData').removeClass( 'hidden' ); } function eventDataResponse( respObj, respText ) { var zm_event = respObj.event; if ( !zm_event ) { console.log('Null event'); return; } events[zm_event.Id] = zm_event; if ( respObj.loopback ) { requestFrameData(zm_event.Id, respObj.loopback); } } function frameDataResponse( respObj, respText ) { var frame = respObj.frameimage; if ( !frame.FrameId ) { console.log('Null frame'); return; } var zm_event = events[frame.EventId]; if ( !zm_event ) { console.error('No event '+frame.eventId+' found'); return; } if ( !zm_event['frames'] ) { console.log("No frames data in event response"); console.log(zm_event); console.log(respObj); zm_event['frames'] = {}; } zm_event['frames'][frame.FrameId] = frame; zm_event['frames'][frame.FrameId]['html'] = createEventHtml( zm_event, frame ); showEventData(frame.EventId, frame.FrameId); } function showEventData(eventId, frameId) { if ( events[eventId] ) { var zm_event = events[eventId]; if ( zm_event['frames'] ) { if ( zm_event['frames'][frameId] ) { showEventDetail( zm_event['frames'][frameId]['html'] ); var imagePath = 'index.php?view=image&eid='+eventId+'&fid='+frameId; var videoName = zm_event.DefaultVideo; loadEventImage( imagePath, eventId, frameId, zm_event.Width, zm_event.Height, zm_event.Frames/zm_event.Length, videoName, zm_event.Length, zm_event.StartTime, monitors[zm_event.MonitorId]); return; } else { console.log('No frames for ' + frameId); } } else { console.log('No frames'); } } else { console.log('No event for ' + eventId); } } var eventQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: eventDataResponse }); var frameQuery = new Request.JSON({ url: thisUrl, method: 'get', timeout: AJAX_TIMEOUT, link: 'cancel', onSuccess: frameDataResponse });
eventQuery.options.data = "view=request&request=status&entity=event&id="+eventId+"&loopback="+frameId; eventQuery.send(); } else { frameQuery.options.data = "view=request&request=status&entity=frameimage&id[0]="+eventId+"&id[1]="+frameId; frameQuery.send(); } } function previewEvent(slot) { eventId = slot.getAttribute('data-event-id'); frameId = slot.getAttribute('data-frame-id'); if ( events[eventId] ) { showEventData(eventId, frameId); } else { requestFrameData(eventId, frameId); } } function loadEventImage( imagePath, eid, fid, width, height, fps, videoName, duration, startTime, Monitor ) { var vid = $('preview'); var imageSrc = $('imageSrc'); if ( videoName && vid ) { vid.show(); imageSrc.hide(); var newsource=imagePath.slice(0, imagePath.lastIndexOf('/'))+'/'+videoName; //console.log(newsource); //console.log(sources[0].src.slice(-newsource.length)); if ( newsource != vid.currentSrc.slice(-newsource.length) || vid.readyState == 0 ) { //console.log("loading new"); //it is possible to set a long source list here will that be unworkable? var sources = vid.getElementsByTagName('source'); sources[0].src = newsource; var tracks = vid.getElementsByTagName('track'); if (tracks.length) { tracks[0].parentNode.removeChild(tracks[0]); } vid.load(); addVideoTimingTrack(vid, Monitor.LabelFormat, Monitor.Name, duration, startTime); vid.currentTime = fid/fps; } else { if ( ! vid.seeking ) { vid.currentTime=fid/fps; } } } else { if ( vid ) vid.hide(); imageSrc.show(); imageSrc.setProperty('src', imagePath); imageSrc.setAttribute('data-event-id', eid); imageSrc.setAttribute('data-frame-id', fid); imageSrc.onclick=window['showEvent'].bind(imageSrc, imageSrc); } var eventData = $('eventData'); eventData.removeEvent('click'); eventData.addEvent('click', showEvent.pass()); } function tlZoomBounds( minTime, maxTime ) { location.replace('?view='+currentView+filterQuery+'&minTime='+minTime+'&maxTime='+maxTime); } function tlZoomOut() { location.replace('?view='+currentView+filterQuery+'&midTime='+midTime+'&range='+zoom_range); } function tlPanLeft() { location.replace('?view='+currentView+filterQuery+'&midTime='+minTime+'&range='+range); } function tlPanRight() { location.replace('?view='+currentView+filterQuery+'&midTime='+maxTime+'&range='+range); } window.addEventListener("DOMContentLoaded", function() { document.querySelectorAll("div.event").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); document.querySelectorAll("div.activity").forEach(function(el) { el.onclick = window[el.getAttribute('data-on-click-this')].bind(el, el); el.onmouseover = window[el.getAttribute('data-on-mouseover-this')].bind(el, el); }); });
function requestFrameData( eventId, frameId ) { if ( !events[eventId] ) {
random_line_split
graphviz.py
"""Generate directed and non-directed graphs using Graphviz.""" import asyncio import io import os import subprocess import threading import dot_parser from dot_parser import graph_definition from pyparsing import ParseException from plumeria.command import commands, CommandError from plumeria.message import Response, MemoryAttachment from plumeria.util.message import strip_markdown_code from plumeria.util.ratelimit import rate_limit lock = threading.RLock() def
(s): with lock: dot_parser.top_graphs = [] # Clear list of existing graphs because this module is bad parser = graph_definition() parser.parseWithTabs() tokens = parser.parseString(s) return list(tokens) def render_dot(graph, format="png"): program = 'dot' if os.name == 'nt' and not program.endswith('.exe'): program += '.exe' p = subprocess.Popen( [program, '-T' + format], env={'SERVER_NAME': 'plumeria', 'GV_FILE_PATH': '/dev/null'}, shell=False, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = p.communicate(input=graph.to_string().encode('utf-8')) if p.returncode != 0: raise Exception("Received non-zero return code from grapviz\n\nError: {}".format(stderr.decode('utf-8'))) return stdout async def handle_request(message, type): content = strip_markdown_code(message.content.strip()) def execute(): # Use parser as a rudimentary validator graph = parse_dot_data(type + " G {\n" + content + "\n}")[0] buf = io.BytesIO() buf.write(render_dot(graph, format="png")) return buf try: buf = await asyncio.get_event_loop().run_in_executor(None, execute) return Response("", attachments=[MemoryAttachment(buf, "graph.png", "image/png")]) except ParseException as e: raise CommandError("Parse error: {}".format(str(e))) @commands.create("graph", category="Graphing") @rate_limit() async def graph(message): """ Generates a non-directed graph using DOT syntax and drawn using Graphviz. Example:: /graph a -- b b -- c c -- a """ return await handle_request(message, "graph") @commands.create("digraph", category="Graphing") @rate_limit() async def digraph(message): """ Generates a directed graph using DOT syntax and drawn using Graphviz. Example:: /digraph a -> b b -> c c -> a """ return await handle_request(message, "digraph") def setup(): commands.add(graph) commands.add(digraph)
parse_dot_data
identifier_name
graphviz.py
"""Generate directed and non-directed graphs using Graphviz.""" import asyncio import io import os import subprocess import threading import dot_parser from dot_parser import graph_definition from pyparsing import ParseException from plumeria.command import commands, CommandError from plumeria.message import Response, MemoryAttachment from plumeria.util.message import strip_markdown_code from plumeria.util.ratelimit import rate_limit lock = threading.RLock()
tokens = parser.parseString(s) return list(tokens) def render_dot(graph, format="png"): program = 'dot' if os.name == 'nt' and not program.endswith('.exe'): program += '.exe' p = subprocess.Popen( [program, '-T' + format], env={'SERVER_NAME': 'plumeria', 'GV_FILE_PATH': '/dev/null'}, shell=False, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = p.communicate(input=graph.to_string().encode('utf-8')) if p.returncode != 0: raise Exception("Received non-zero return code from grapviz\n\nError: {}".format(stderr.decode('utf-8'))) return stdout async def handle_request(message, type): content = strip_markdown_code(message.content.strip()) def execute(): # Use parser as a rudimentary validator graph = parse_dot_data(type + " G {\n" + content + "\n}")[0] buf = io.BytesIO() buf.write(render_dot(graph, format="png")) return buf try: buf = await asyncio.get_event_loop().run_in_executor(None, execute) return Response("", attachments=[MemoryAttachment(buf, "graph.png", "image/png")]) except ParseException as e: raise CommandError("Parse error: {}".format(str(e))) @commands.create("graph", category="Graphing") @rate_limit() async def graph(message): """ Generates a non-directed graph using DOT syntax and drawn using Graphviz. Example:: /graph a -- b b -- c c -- a """ return await handle_request(message, "graph") @commands.create("digraph", category="Graphing") @rate_limit() async def digraph(message): """ Generates a directed graph using DOT syntax and drawn using Graphviz. Example:: /digraph a -> b b -> c c -> a """ return await handle_request(message, "digraph") def setup(): commands.add(graph) commands.add(digraph)
def parse_dot_data(s): with lock: dot_parser.top_graphs = [] # Clear list of existing graphs because this module is bad parser = graph_definition() parser.parseWithTabs()
random_line_split
graphviz.py
"""Generate directed and non-directed graphs using Graphviz.""" import asyncio import io import os import subprocess import threading import dot_parser from dot_parser import graph_definition from pyparsing import ParseException from plumeria.command import commands, CommandError from plumeria.message import Response, MemoryAttachment from plumeria.util.message import strip_markdown_code from plumeria.util.ratelimit import rate_limit lock = threading.RLock() def parse_dot_data(s): with lock: dot_parser.top_graphs = [] # Clear list of existing graphs because this module is bad parser = graph_definition() parser.parseWithTabs() tokens = parser.parseString(s) return list(tokens) def render_dot(graph, format="png"): program = 'dot' if os.name == 'nt' and not program.endswith('.exe'): program += '.exe' p = subprocess.Popen( [program, '-T' + format], env={'SERVER_NAME': 'plumeria', 'GV_FILE_PATH': '/dev/null'}, shell=False, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = p.communicate(input=graph.to_string().encode('utf-8')) if p.returncode != 0: raise Exception("Received non-zero return code from grapviz\n\nError: {}".format(stderr.decode('utf-8'))) return stdout async def handle_request(message, type): content = strip_markdown_code(message.content.strip()) def execute(): # Use parser as a rudimentary validator graph = parse_dot_data(type + " G {\n" + content + "\n}")[0] buf = io.BytesIO() buf.write(render_dot(graph, format="png")) return buf try: buf = await asyncio.get_event_loop().run_in_executor(None, execute) return Response("", attachments=[MemoryAttachment(buf, "graph.png", "image/png")]) except ParseException as e: raise CommandError("Parse error: {}".format(str(e))) @commands.create("graph", category="Graphing") @rate_limit() async def graph(message):
@commands.create("digraph", category="Graphing") @rate_limit() async def digraph(message): """ Generates a directed graph using DOT syntax and drawn using Graphviz. Example:: /digraph a -> b b -> c c -> a """ return await handle_request(message, "digraph") def setup(): commands.add(graph) commands.add(digraph)
""" Generates a non-directed graph using DOT syntax and drawn using Graphviz. Example:: /graph a -- b b -- c c -- a """ return await handle_request(message, "graph")
identifier_body
graphviz.py
"""Generate directed and non-directed graphs using Graphviz.""" import asyncio import io import os import subprocess import threading import dot_parser from dot_parser import graph_definition from pyparsing import ParseException from plumeria.command import commands, CommandError from plumeria.message import Response, MemoryAttachment from plumeria.util.message import strip_markdown_code from plumeria.util.ratelimit import rate_limit lock = threading.RLock() def parse_dot_data(s): with lock: dot_parser.top_graphs = [] # Clear list of existing graphs because this module is bad parser = graph_definition() parser.parseWithTabs() tokens = parser.parseString(s) return list(tokens) def render_dot(graph, format="png"): program = 'dot' if os.name == 'nt' and not program.endswith('.exe'): program += '.exe' p = subprocess.Popen( [program, '-T' + format], env={'SERVER_NAME': 'plumeria', 'GV_FILE_PATH': '/dev/null'}, shell=False, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = p.communicate(input=graph.to_string().encode('utf-8')) if p.returncode != 0:
return stdout async def handle_request(message, type): content = strip_markdown_code(message.content.strip()) def execute(): # Use parser as a rudimentary validator graph = parse_dot_data(type + " G {\n" + content + "\n}")[0] buf = io.BytesIO() buf.write(render_dot(graph, format="png")) return buf try: buf = await asyncio.get_event_loop().run_in_executor(None, execute) return Response("", attachments=[MemoryAttachment(buf, "graph.png", "image/png")]) except ParseException as e: raise CommandError("Parse error: {}".format(str(e))) @commands.create("graph", category="Graphing") @rate_limit() async def graph(message): """ Generates a non-directed graph using DOT syntax and drawn using Graphviz. Example:: /graph a -- b b -- c c -- a """ return await handle_request(message, "graph") @commands.create("digraph", category="Graphing") @rate_limit() async def digraph(message): """ Generates a directed graph using DOT syntax and drawn using Graphviz. Example:: /digraph a -> b b -> c c -> a """ return await handle_request(message, "digraph") def setup(): commands.add(graph) commands.add(digraph)
raise Exception("Received non-zero return code from grapviz\n\nError: {}".format(stderr.decode('utf-8')))
conditional_block
glnoise.js
// Seriously awesome GLSL noise functions. (C) Credits and kudos go to // Copyright (C) Stefan Gustavson, Ian McEwan Ashima Arts // MIT License. define(function(require, exports){ exports.permute1 = function(x){ return mod((34.0 * x + 1.0) * x, 289.0) } exports.permute3 = function(x){ return mod((34.0 * x + 1.0) * x, 289.0) } exports.permute4 = function(x){ return mod((34.0 * x + 1.0) * x, 289.0) } exports.isqrtT1 = function(r){ return 1.79284291400159 - 0.85373472095314 * r } exports.isqrtT4 = function(r){ return vec4(1.79284291400159 - 0.85373472095314 * r) } exports.snoise2 = function(x, y){ return snoise2v(vec2(x,y,z)) } exports.noise2d = exports.s2d = exports.snoise2v = function(v){ var C = vec4(0.211324865405187,0.366025403784439,-0.577350269189626,0.024390243902439) var i = floor(v + dot(v, C.yy) ) var x0 = v - i + dot(i, C.xx) var i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0) var x12 = x0.xyxy + C.xxzz x12.xy -= i1 i = mod(i, 289.0) // Avoid truncation effects in permutation var p = permute3(permute3(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0 )) var m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0) m = m*m m = m*m var x = 2.0 * fract(p * C.www) - 1.0 var h = abs(x) - 0.5 var ox = floor(x + 0.5) var a0 = x - ox m *= (1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h )) var g = vec3() g.x = a0.x * x0.x + h.x * x0.y g.yz = a0.yz * x12.xz + h.yz * x12.yw return 130.0 * dot(m, g) } exports.snoise3 = function(x, y, z){ return snoise3v(vec3(x,y,z)) } exports.noise3d = exports.snoise3v = function(v){ var C = vec2(1.0/6.0, 1.0/3.0) var D = vec4(0.0, 0.5, 1.0, 2.0) // First corner var i = floor(v + dot(v, C.yyy)) var x0 = v - i + dot(i, C.xxx) var g = step(x0.yzx, x0.xyz) var l = 1.0 - g var i1 = min(g.xyz, l.zxy) var i2 = max(g.xyz, l.zxy) var x1 = x0 - i1 + 1.0 * C.xxx var x2 = x0 - i2 + 2.0 * C.xxx var x3 = x0 - 1. + 3.0 * C.xxx // Permutations i = mod(i, 289.0) var p = permute4(permute4(permute4( i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + i.x + vec4(0.0, i1.x, i2.x, 1.0)) // ( N*N points uniformly over a square, mapped onto an octahedron.) var n_ = 1.0/7.0 var ns = n_ * D.wyz - D.xzx var j = p - 49.0 * floor(p * ns.z *ns.z) var x_ = floor(j * ns.z) var y_ = floor(j - 7.0 * x_) var x = x_ * ns.x + ns.yyyy var y = y_ * ns.x + ns.yyyy var h = 1.0 - abs(x) - abs(y) var b0 = vec4( x.xy, y.xy ) var b1 = vec4( x.zw, y.zw ) var s0 = floor(b0)*2.0 + 1.0 var s1 = floor(b1)*2.0 + 1.0 var sh = -step(h, vec4(0.0)) var a0 = b0.xzyw + s0.xzyw*sh.xxyy var a1 = b1.xzyw + s1.xzyw*sh.zzww var p0 = vec3(a0.xy, h.x) var p1 = vec3(a0.zw, h.y) var p2 = vec3(a1.xy, h.z) var p3 = vec3(a1.zw, h.w) //Normalise gradients var norm = isqrtT4(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3))) p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w; // Mix final noise value var m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0) m = m * m return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3) ) ) } exports.snoise4_g = function(j, ip){ var p = vec4() p.xyz = floor( fract (vec3(j) * ip.xyz) * 7.0) * ip.z - 1.0 p.w = 1.5 - dot(abs(p.xyz), vec3(1.0,1.0,1.0)) var s = vec4(lessThan(p, vec4(0.0))) p.xyz = p.xyz + (s.xyz*2.0 - 1.0) * s.www return p } exports.snoise4 = function(x, y, z, w){ return snoise4v(vec4(x,y,z,w)) } exports.snoise4v = function(v){ var C = vec4(0.138196601125011,0.276393202250021,0.414589803375032,-0.447213595499958) // First corner var i = floor(v + dot(v, vec4(0.309016994374947451)) ) var x0 = v - i + dot(i, C.xxxx) var i0 = vec4() var isX = step( x0.yzw, x0.xxx ) var isYZ = step( x0.zww, x0.yyz ) i0.x = isX.x + isX.y + isX.z i0.yzw = 1.0 - isX i0.y += isYZ.x + isYZ.y i0.zw += 1.0 - isYZ.xy i0.z += isYZ.z i0.w += 1.0 - isYZ.z var i3 = clamp( i0, 0.0, 1.0 ) var i2 = clamp( i0-1.0, 0.0, 1.0 ) var i1 = clamp( i0-2.0, 0.0, 1.0 ) var x1 = x0 - i1 + C.xxxx var x2 = x0 - i2 + C.yyyy var x3 = x0 - i3 + C.zzzz var x4 = x0 + C.wwww // Permutations i = mod(i, 289.0 ) var j0 = permute1( permute1( permute1( permute1(i.w) + i.z) + i.y) + i.x) var j1 = permute4( permute4( permute4( permute4( i.w + vec4(i1.w, i2.w, i3.w, 1.0 )) + i.z + vec4(i1.z, i2.z, i3.z, 1.0 )) + i.y + vec4(i1.y, i2.y, i3.y, 1.0 )) + i.x + vec4(i1.x, i2.x, i3.x, 1.0 )) // Gradients: 7x7x6 points over a cube, mapped onto a 4-cross polytope // 7*7*6 = 294, which is close to the ring size 17*17 = 289. var ip = vec4(1.0/294.0, 1.0/49.0, 1.0/7.0, 0.0) var p0 = snoise4_g(j0, ip) var p1 = snoise4_g(j1.x, ip) var p2 = snoise4_g(j1.y, ip) var p3 = snoise4_g(j1.z, ip) var p4 = snoise4_g(j1.w, ip) // Normalise gradients var nr = isqrtT4(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3))) p0 *= nr.x p1 *= nr.y p2 *= nr.z p3 *= nr.w p4 *= isqrtT1(dot(p4,p4)) // Mix contributions from the five corners var m0 = max(0.6 - vec3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0) var m1 = max(0.6 - vec2(dot(x3,x3), dot(x4,x4)), 0.0) m0 = m0 * m0 m1 = m1 * m1 return 49.0 * (dot(m0*m0, vec3(dot( p0, x0 ), dot(p1, x1), dot(p2, x2))) + dot(m1*m1, vec2( dot(p3, x3), dot(p4, x4)))) } exports.cell2v = function(v){ return cell3v(vec3(v.x, v.y,0)) } exports.cell3v = function(P){ var K = 0.142857142857 // 1/7 var Ko = 0.428571428571 // 1/2-K/2 var K2 = 0.020408163265306 // 1/(7*7) var Kz = 0.166666666667 // 1/6 var Kzo = 0.416666666667 // 1/2-1/6*2 var ji = 0.8 // smaller jitter gives less errors in F2 var Pi = mod(floor(P), 289.0) var Pf = fract(P) var Pfx = Pf.x + vec4(0.0, -1.0, 0.0, -1.0) var Pfy = Pf.y + vec4(0.0, 0.0, -1.0, -1.0) var p = permute4(Pi.x + vec4(0.0, 1.0, 0.0, 1.0)) p = permute4(p + Pi.y + vec4(0.0, 0.0, 1.0, 1.0)) var p1 = permute4(p + Pi.z) // z+0 var p2 = permute4(p + Pi.z + vec4(1.0)) // z+1 var ox1 = fract(p1*K) - Ko var oy1 = mod(floor(p1*K), 7.0)*K - Ko var oz1 = floor(p1*K2)*Kz - Kzo // p1 < 289 guaranteed var ox2 = fract(p2*K) - Ko var oy2 = mod(floor(p2*K), 7.0)*K - Ko var oz2 = floor(p2*K2)*Kz - Kzo var dx1 = Pfx + ji*ox1 var dy1 = Pfy + ji*oy1 var dz1 = Pf.z + ji*oz1 var dx2 = Pfx + ji*ox2 var dy2 = Pfy + ji*oy2 var dz2 = Pf.z - 1.0 + ji*oz2 var d1 = dx1 * dx1 + dy1 * dy1 + dz1 * dz1 // z+0 var d2 = dx2 * dx2 + dy2 * dy2 + dz2 * dz2 // z+1 var d = min(d1,d2) // F1 is now in d d2 = max(d1,d2) // Make sure we keep all candidates for F2 d.xy = (d.x < d.y) ? d.xy : d.yx // Swap smallest to d.x d.xz = (d.x < d.z) ? d.xz : d.zx d.xw = (d.x < d.w) ? d.xw : d.wx // F1 is now in d.x d.yzw = min(d.yzw, d2.yzw) // F2 now not in d2.yzw d.y = min(d.y, d.z) // nor in d.z d.y = min(d.y, d.w) // nor in d.w d.y = min(d.y, d2.x) // F2 is now in d.y return sqrt(d.xy) // F1 and F2 }, exports.cell3w = function(P){ var K = 0.142857142857 var Ko = 0.428571428571 // 1/2-K/2 var K2 = 0.020408163265306// 1/(7*7) var Kz = 0.166666666667// 1/6 var Kzo = 0.416666666667// 1/2-1/6*2 var ji = 1.0// smaller jitter gives more regular pattern var Pi = mod(floor(P), 289.0) var Pf = fract(P) - 0.5 var Pfx = Pf.x + vec3(1.0, 0.0, -1.0) var Pfy = Pf.y + vec3(1.0, 0.0, -1.0)
var p3 = permute3(p + Pi.y + 1.0) var p11 = permute3(p1 + Pi.z - 1.0) var p12 = permute3(p1 + Pi.z) var p13 = permute3(p1 + Pi.z + 1.0) var p21 = permute3(p2 + Pi.z - 1.0) var p22 = permute3(p2 + Pi.z) var p23 = permute3(p2 + Pi.z + 1.0) var p31 = permute3(p3 + Pi.z - 1.0) var p32 = permute3(p3 + Pi.z) var p33 = permute3(p3 + Pi.z + 1.0) var ox11 = fract(p11*K) - Ko var oy11 = mod(floor(p11*K), 7.0)*K - Ko var oz11 = floor(p11*K2)*Kz - Kzo // p11 < 289 guaranteed var ox12 = fract(p12*K) - Ko var oy12 = mod(floor(p12*K), 7.0)*K - Ko var oz12 = floor(p12*K2)*Kz - Kzo var ox13 = fract(p13*K) - Ko var oy13 = mod(floor(p13*K), 7.0)*K - Ko var oz13 = floor(p13*K2)*Kz - Kzo var ox21 = fract(p21*K) - Ko var oy21 = mod(floor(p21*K), 7.0)*K - Ko var oz21 = floor(p21*K2)*Kz - Kzo var ox22 = fract(p22*K) - Ko var oy22 = mod(floor(p22*K), 7.0)*K - Ko var oz22 = floor(p22*K2)*Kz - Kzo var ox23 = fract(p23*K) - Ko var oy23 = mod(floor(p23*K), 7.0)*K - Ko var oz23 = floor(p23*K2)*Kz - Kzo var ox31 = fract(p31*K) - Ko var oy31 = mod(floor(p31*K), 7.0)*K - Ko var oz31 = floor(p31*K2)*Kz - Kzo var ox32 = fract(p32*K) - Ko var oy32 = mod(floor(p32*K), 7.0)*K - Ko var oz32 = floor(p32*K2)*Kz - Kzo var ox33 = fract(p33*K) - Ko var oy33 = mod(floor(p33*K), 7.0)*K - Ko var oz33 = floor(p33*K2)*Kz - Kzo var dx11 = Pfx + ji*ox11 var dy11 = Pfy.x + ji*oy11 var dz11 = Pfz.x + ji*oz11 var dx12 = Pfx + ji*ox12 var dy12 = Pfy.x + ji*oy12 var dz12 = Pfz.y + ji*oz12 var dx13 = Pfx + ji*ox13 var dy13 = Pfy.x + ji*oy13 var dz13 = Pfz.z + ji*oz13 var dx21 = Pfx + ji*ox21 var dy21 = Pfy.y + ji*oy21 var dz21 = Pfz.x + ji*oz21 var dx22 = Pfx + ji*ox22 var dy22 = Pfy.y + ji*oy22 var dz22 = Pfz.y + ji*oz22 var dx23 = Pfx + ji*ox23 var dy23 = Pfy.y + ji*oy23 var dz23 = Pfz.z + ji*oz23 var dx31 = Pfx + ji*ox31 var dy31 = Pfy.z + ji*oy31 var dz31 = Pfz.x + ji*oz31 var dx32 = Pfx + ji*ox32 var dy32 = Pfy.z + ji*oy32 var dz32 = Pfz.y + ji*oz32 var dx33 = Pfx + ji*ox33 var dy33 = Pfy.z + ji*oy33 var dz33 = Pfz.z + ji*oz33 var d11 = dx11 * dx11 + dy11 * dy11 + dz11 * dz11 var d12 = dx12 * dx12 + dy12 * dy12 + dz12 * dz12 var d13 = dx13 * dx13 + dy13 * dy13 + dz13 * dz13 var d21 = dx21 * dx21 + dy21 * dy21 + dz21 * dz21 var d22 = dx22 * dx22 + dy22 * dy22 + dz22 * dz22 var d23 = dx23 * dx23 + dy23 * dy23 + dz23 * dz23 var d31 = dx31 * dx31 + dy31 * dy31 + dz31 * dz31 var d32 = dx32 * dx32 + dy32 * dy32 + dz32 * dz32 var d33 = dx33 * dx33 + dy33 * dy33 + dz33 * dz33 var d1a = min(d11, d12) d12 = max(d11, d12) d11 = min(d1a, d13) // Smallest now not in d12 or d13 d13 = max(d1a, d13) d12 = min(d12, d13) // 2nd smallest now not in d13 var d2a = min(d21, d22) d22 = max(d21, d22) d21 = min(d2a, d23) // Smallest now not in d22 or d23 d23 = max(d2a, d23) d22 = min(d22, d23) // 2nd smallest now not in d23 var d3a = min(d31, d32) d32 = max(d31, d32) d31 = min(d3a, d33) // Smallest now not in d32 or d33 d33 = max(d3a, d33) d32 = min(d32, d33) // 2nd smallest now not in d33 var da = min(d11, d21) d21 = max(d11, d21) d11 = min(da, d31) // Smallest now in d11 d31 = max(da, d31) // 2nd smallest now not in d31 d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx // d11.x now smallest d12 = min(d12, d21) // 2nd smallest now not in d21 d12 = min(d12, d22) // nor in d22 d12 = min(d12, d31) // nor in d31 d12 = min(d12, d32) // nor in d32 d11.yz = min(d11.yz, d12.xy) // nor in d12.yz d11.y = min(d11.y, d12.z) // Only two more to go d11.y = min(d11.y, d11.z) // Done! (Phew!) return sqrt(d11.xy) // F1, F2 } })
var Pfz = Pf.z + vec3(1.0, 0.0, -1.0) var p = permute3(Pi.x + vec3(-1.0, 0.0, 1.0)) var p1 = permute3(p + Pi.y - 1.0) var p2 = permute3(p + Pi.y)
random_line_split
error.rs
extern crate backtrace; extern crate libc; use std::fmt; use std::ops::Deref; use std::io; use std::string::FromUtf8Error; use self::backtrace::Backtrace; use self::backtrace::BacktraceFrame; #[derive(Debug)] pub struct RError<E> { e: E, bt: Option<Backtrace>, } pub fn is_enoent(e: &io::Error) -> bool { return e.kind() == io::ErrorKind::NotFound; } pub fn try_enoent(e: io::Error) -> Result<bool> { if is_enoent(&e) { return Ok(true); } else { return Err(RError::from(e)); } } pub fn propagate<T>(e: io::Error) -> Result<T> { return Err(RError::propagate(e)); } pub fn errno(e: &RError<io::Error>) -> libc::c_int { if RError::expected(e) { return e.e.raw_os_error().unwrap(); } else { return libc::EIO; } } impl<E> RError<E> { pub fn propagate(e: E) -> RError<E>
pub fn from(e: E) -> RError<E> { let mut bt = Backtrace::new(); let mut i: usize = 0; let mut chop: usize = 0; for f in bt.frames() { if let Some(sym) = f.symbols().first() { if let Some(p) = sym.filename() { if p.file_name().unwrap() == "error.rs" { chop = i; break; } } } i += 1; } if chop != 0 { let mut frames: Vec<BacktraceFrame> = bt.into(); let _: Vec<_> = frames.drain(0..i).collect(); bt = Backtrace::from(frames); } RError { e: e, bt: Some(bt) } } fn expected(&self) -> bool { return self.bt.is_none(); } } impl RError<io::Error> { pub fn errno(&self) -> i32 { return self.e.raw_os_error().unwrap(); } } impl fmt::Display for RError<io::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.bt { Some(ref bt) => write!(f, "{} {:?}", self.e, bt), None => write!(f, "{}", self.e), } } } impl<E> Deref for RError<E> { type Target = E; fn deref(&self) -> &E { &self.e } } // XXX not really a clone impl Clone for RError<io::Error> { fn clone(&self) -> Self { RError { e: io::Error::from_raw_os_error(self.e.raw_os_error().unwrap()), bt: Default::default(), } } } impl From<io::Error> for RError<io::Error> { fn from(e: io::Error) -> RError<io::Error> { RError::from(e) } } impl From<FromUtf8Error> for RError<FromUtf8Error> { fn from(e: FromUtf8Error) -> RError<FromUtf8Error> { RError::from(e) } } pub type Result<T> = ::std::result::Result<T, RError<io::Error>>;
{ RError { e: e, bt: Default::default(), } }
identifier_body
error.rs
extern crate backtrace; extern crate libc; use std::fmt; use std::ops::Deref; use std::io; use std::string::FromUtf8Error; use self::backtrace::Backtrace; use self::backtrace::BacktraceFrame; #[derive(Debug)] pub struct RError<E> { e: E, bt: Option<Backtrace>, } pub fn is_enoent(e: &io::Error) -> bool { return e.kind() == io::ErrorKind::NotFound; } pub fn try_enoent(e: io::Error) -> Result<bool> { if is_enoent(&e) { return Ok(true); } else { return Err(RError::from(e)); } } pub fn propagate<T>(e: io::Error) -> Result<T> { return Err(RError::propagate(e)); } pub fn errno(e: &RError<io::Error>) -> libc::c_int { if RError::expected(e)
else { return libc::EIO; } } impl<E> RError<E> { pub fn propagate(e: E) -> RError<E> { RError { e: e, bt: Default::default(), } } pub fn from(e: E) -> RError<E> { let mut bt = Backtrace::new(); let mut i: usize = 0; let mut chop: usize = 0; for f in bt.frames() { if let Some(sym) = f.symbols().first() { if let Some(p) = sym.filename() { if p.file_name().unwrap() == "error.rs" { chop = i; break; } } } i += 1; } if chop != 0 { let mut frames: Vec<BacktraceFrame> = bt.into(); let _: Vec<_> = frames.drain(0..i).collect(); bt = Backtrace::from(frames); } RError { e: e, bt: Some(bt) } } fn expected(&self) -> bool { return self.bt.is_none(); } } impl RError<io::Error> { pub fn errno(&self) -> i32 { return self.e.raw_os_error().unwrap(); } } impl fmt::Display for RError<io::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.bt { Some(ref bt) => write!(f, "{} {:?}", self.e, bt), None => write!(f, "{}", self.e), } } } impl<E> Deref for RError<E> { type Target = E; fn deref(&self) -> &E { &self.e } } // XXX not really a clone impl Clone for RError<io::Error> { fn clone(&self) -> Self { RError { e: io::Error::from_raw_os_error(self.e.raw_os_error().unwrap()), bt: Default::default(), } } } impl From<io::Error> for RError<io::Error> { fn from(e: io::Error) -> RError<io::Error> { RError::from(e) } } impl From<FromUtf8Error> for RError<FromUtf8Error> { fn from(e: FromUtf8Error) -> RError<FromUtf8Error> { RError::from(e) } } pub type Result<T> = ::std::result::Result<T, RError<io::Error>>;
{ return e.e.raw_os_error().unwrap(); }
conditional_block
error.rs
extern crate backtrace; extern crate libc; use std::fmt; use std::ops::Deref; use std::io; use std::string::FromUtf8Error; use self::backtrace::Backtrace; use self::backtrace::BacktraceFrame; #[derive(Debug)] pub struct RError<E> { e: E, bt: Option<Backtrace>, } pub fn is_enoent(e: &io::Error) -> bool { return e.kind() == io::ErrorKind::NotFound; } pub fn try_enoent(e: io::Error) -> Result<bool> { if is_enoent(&e) { return Ok(true); } else { return Err(RError::from(e)); } } pub fn
<T>(e: io::Error) -> Result<T> { return Err(RError::propagate(e)); } pub fn errno(e: &RError<io::Error>) -> libc::c_int { if RError::expected(e) { return e.e.raw_os_error().unwrap(); } else { return libc::EIO; } } impl<E> RError<E> { pub fn propagate(e: E) -> RError<E> { RError { e: e, bt: Default::default(), } } pub fn from(e: E) -> RError<E> { let mut bt = Backtrace::new(); let mut i: usize = 0; let mut chop: usize = 0; for f in bt.frames() { if let Some(sym) = f.symbols().first() { if let Some(p) = sym.filename() { if p.file_name().unwrap() == "error.rs" { chop = i; break; } } } i += 1; } if chop != 0 { let mut frames: Vec<BacktraceFrame> = bt.into(); let _: Vec<_> = frames.drain(0..i).collect(); bt = Backtrace::from(frames); } RError { e: e, bt: Some(bt) } } fn expected(&self) -> bool { return self.bt.is_none(); } } impl RError<io::Error> { pub fn errno(&self) -> i32 { return self.e.raw_os_error().unwrap(); } } impl fmt::Display for RError<io::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.bt { Some(ref bt) => write!(f, "{} {:?}", self.e, bt), None => write!(f, "{}", self.e), } } } impl<E> Deref for RError<E> { type Target = E; fn deref(&self) -> &E { &self.e } } // XXX not really a clone impl Clone for RError<io::Error> { fn clone(&self) -> Self { RError { e: io::Error::from_raw_os_error(self.e.raw_os_error().unwrap()), bt: Default::default(), } } } impl From<io::Error> for RError<io::Error> { fn from(e: io::Error) -> RError<io::Error> { RError::from(e) } } impl From<FromUtf8Error> for RError<FromUtf8Error> { fn from(e: FromUtf8Error) -> RError<FromUtf8Error> { RError::from(e) } } pub type Result<T> = ::std::result::Result<T, RError<io::Error>>;
propagate
identifier_name
error.rs
extern crate backtrace; extern crate libc; use std::fmt; use std::ops::Deref; use std::io; use std::string::FromUtf8Error; use self::backtrace::Backtrace; use self::backtrace::BacktraceFrame;
pub struct RError<E> { e: E, bt: Option<Backtrace>, } pub fn is_enoent(e: &io::Error) -> bool { return e.kind() == io::ErrorKind::NotFound; } pub fn try_enoent(e: io::Error) -> Result<bool> { if is_enoent(&e) { return Ok(true); } else { return Err(RError::from(e)); } } pub fn propagate<T>(e: io::Error) -> Result<T> { return Err(RError::propagate(e)); } pub fn errno(e: &RError<io::Error>) -> libc::c_int { if RError::expected(e) { return e.e.raw_os_error().unwrap(); } else { return libc::EIO; } } impl<E> RError<E> { pub fn propagate(e: E) -> RError<E> { RError { e: e, bt: Default::default(), } } pub fn from(e: E) -> RError<E> { let mut bt = Backtrace::new(); let mut i: usize = 0; let mut chop: usize = 0; for f in bt.frames() { if let Some(sym) = f.symbols().first() { if let Some(p) = sym.filename() { if p.file_name().unwrap() == "error.rs" { chop = i; break; } } } i += 1; } if chop != 0 { let mut frames: Vec<BacktraceFrame> = bt.into(); let _: Vec<_> = frames.drain(0..i).collect(); bt = Backtrace::from(frames); } RError { e: e, bt: Some(bt) } } fn expected(&self) -> bool { return self.bt.is_none(); } } impl RError<io::Error> { pub fn errno(&self) -> i32 { return self.e.raw_os_error().unwrap(); } } impl fmt::Display for RError<io::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.bt { Some(ref bt) => write!(f, "{} {:?}", self.e, bt), None => write!(f, "{}", self.e), } } } impl<E> Deref for RError<E> { type Target = E; fn deref(&self) -> &E { &self.e } } // XXX not really a clone impl Clone for RError<io::Error> { fn clone(&self) -> Self { RError { e: io::Error::from_raw_os_error(self.e.raw_os_error().unwrap()), bt: Default::default(), } } } impl From<io::Error> for RError<io::Error> { fn from(e: io::Error) -> RError<io::Error> { RError::from(e) } } impl From<FromUtf8Error> for RError<FromUtf8Error> { fn from(e: FromUtf8Error) -> RError<FromUtf8Error> { RError::from(e) } } pub type Result<T> = ::std::result::Result<T, RError<io::Error>>;
#[derive(Debug)]
random_line_split
taskReducer.js
import Immutable from "immutable" import moment from "moment" import {airtableDateFormat} from "api/airtableAPI" const initialState = Immutable.Map({ list: Immutable.List(), tasks: Immutable.List(), habits: Immutable.List(), bucketlist: Immutable.List(), tags: Immutable.List(), contexts: Immutable.List(), projects: Immutable.List(), filters: Immutable.Map({ Type: "task", Done: false, }), formId: null, form: Immutable.Map({ Type: "task", }) }) function tasks(state = initialState, action)
export default tasks
{ switch (action.type) { case "REPLACE_TASKS": let tasks = action.tasks.filter(task => !task.fields.Type || task.fields.Type == "task") let habits = action.tasks.filter(task => task.fields.Type == "habit") let bucketlist = action.tasks.filter(task => task.fields.Type == "bucketlist") return state .set('list', action.tasks) .set('tasks', tasks) .set('habits', habits) .set('bucketlist', bucketlist) case "REPLACE_TAGS": return state.set('tags', action.tags) case "REPLACE_CONTEXTS": return state.set('contexts', action.contexts) case "REPLACE_PROJECTS": return state.set('projects', action.projects) case "REPLACE_FORM": return state .set('form', Immutable.Map(action.fields)) .set('formId', action.id) case "RESET_FORM": return state .set('form', initialState.get('form')) .set('formId', null) case "CHANGE_FILTER": return state.setIn(['filters', action.field], action.newVal) case "REMOVE_FILTER": return state.setIn(['filters', action.field], undefined) case "CHANGE_FORM_FIELD": return state.setIn(['form', action.field], action.newVal) case "CREATE_NEW_OPTION": const newList = { ...state.get(action.field) || [], [action.id]: action.name, } return state.set(action.field, newList) default: return state } }
identifier_body
taskReducer.js
import Immutable from "immutable" import moment from "moment" import {airtableDateFormat} from "api/airtableAPI" const initialState = Immutable.Map({ list: Immutable.List(), tasks: Immutable.List(), habits: Immutable.List(), bucketlist: Immutable.List(), tags: Immutable.List(), contexts: Immutable.List(), projects: Immutable.List(), filters: Immutable.Map({ Type: "task", Done: false, }), formId: null, form: Immutable.Map({ Type: "task", }) }) function tasks(state = initialState, action) { switch (action.type) { case "REPLACE_TASKS": let tasks = action.tasks.filter(task => !task.fields.Type || task.fields.Type == "task")
let habits = action.tasks.filter(task => task.fields.Type == "habit") let bucketlist = action.tasks.filter(task => task.fields.Type == "bucketlist") return state .set('list', action.tasks) .set('tasks', tasks) .set('habits', habits) .set('bucketlist', bucketlist) case "REPLACE_TAGS": return state.set('tags', action.tags) case "REPLACE_CONTEXTS": return state.set('contexts', action.contexts) case "REPLACE_PROJECTS": return state.set('projects', action.projects) case "REPLACE_FORM": return state .set('form', Immutable.Map(action.fields)) .set('formId', action.id) case "RESET_FORM": return state .set('form', initialState.get('form')) .set('formId', null) case "CHANGE_FILTER": return state.setIn(['filters', action.field], action.newVal) case "REMOVE_FILTER": return state.setIn(['filters', action.field], undefined) case "CHANGE_FORM_FIELD": return state.setIn(['form', action.field], action.newVal) case "CREATE_NEW_OPTION": const newList = { ...state.get(action.field) || [], [action.id]: action.name, } return state.set(action.field, newList) default: return state } } export default tasks
random_line_split
taskReducer.js
import Immutable from "immutable" import moment from "moment" import {airtableDateFormat} from "api/airtableAPI" const initialState = Immutable.Map({ list: Immutable.List(), tasks: Immutable.List(), habits: Immutable.List(), bucketlist: Immutable.List(), tags: Immutable.List(), contexts: Immutable.List(), projects: Immutable.List(), filters: Immutable.Map({ Type: "task", Done: false, }), formId: null, form: Immutable.Map({ Type: "task", }) }) function
(state = initialState, action) { switch (action.type) { case "REPLACE_TASKS": let tasks = action.tasks.filter(task => !task.fields.Type || task.fields.Type == "task") let habits = action.tasks.filter(task => task.fields.Type == "habit") let bucketlist = action.tasks.filter(task => task.fields.Type == "bucketlist") return state .set('list', action.tasks) .set('tasks', tasks) .set('habits', habits) .set('bucketlist', bucketlist) case "REPLACE_TAGS": return state.set('tags', action.tags) case "REPLACE_CONTEXTS": return state.set('contexts', action.contexts) case "REPLACE_PROJECTS": return state.set('projects', action.projects) case "REPLACE_FORM": return state .set('form', Immutable.Map(action.fields)) .set('formId', action.id) case "RESET_FORM": return state .set('form', initialState.get('form')) .set('formId', null) case "CHANGE_FILTER": return state.setIn(['filters', action.field], action.newVal) case "REMOVE_FILTER": return state.setIn(['filters', action.field], undefined) case "CHANGE_FORM_FIELD": return state.setIn(['form', action.field], action.newVal) case "CREATE_NEW_OPTION": const newList = { ...state.get(action.field) || [], [action.id]: action.name, } return state.set(action.field, newList) default: return state } } export default tasks
tasks
identifier_name
main.rs
use std::net::SocketAddr; use std::sync::Arc; use hyper::server::Server; use hyper::service::{make_service_fn, service_fn}; use log::{error, info}; use crate::runtime; use crate::server::github_handler::GithubHandlerState; use crate::server::octobot_service::OctobotService; use crate::server::sessions::Sessions; use octobot_lib::config::Config; use octobot_lib::github; use octobot_lib::jira; use octobot_lib::jira::api::JiraSession; use octobot_lib::metrics; pub fn start(config: Config) { let num_http_threads = config.main.num_http_threads.unwrap_or(20); let metrics = metrics::Metrics::new(); runtime::run(num_http_threads, metrics.clone(), async move { run_server(config, metrics).await }); } async fn run_server(config: Config, metrics: Arc<metrics::Metrics>) { let config = Arc::new(config); let github: Arc<dyn github::api::GithubSessionFactory>; if config.github.app_id.is_some() { github = match github::api::GithubApp::new( &config.github.host, config.github.app_id.expect("expected an app_id"), &config.github.app_key().expect("expected an app_key"), Some(metrics.clone()), ) .await { Ok(s) => Arc::new(s), Err(e) => panic!("Error initiating github session: {}", e), }; } else { github = match github::api::GithubOauthApp::new( &config.github.host, config .github .api_token .as_ref() .expect("expected an api_token"), Some(metrics.clone()), )
Ok(s) => Arc::new(s), Err(e) => panic!("Error initiating github session: {}", e), }; } let jira: Option<Arc<dyn jira::api::Session>>; if let Some(ref jira_config) = config.jira { jira = match JiraSession::new(jira_config, Some(metrics.clone())).await { Ok(s) => Some(Arc::new(s)), Err(e) => panic!("Error initiating jira session: {}", e), }; } else { jira = None; } let http_addr: SocketAddr = match config.main.listen_addr { Some(ref addr_and_port) => addr_and_port.parse().unwrap(), None => "0.0.0.0:3000".parse().unwrap(), }; let ui_sessions = Arc::new(Sessions::new()); let github_handler_state = Arc::new(GithubHandlerState::new( config.clone(), github.clone(), jira.clone(), metrics.clone(), )); let octobot = OctobotService::new( config.clone(), ui_sessions.clone(), github_handler_state.clone(), metrics.clone(), ); let main_service = make_service_fn(move |_| { let metrics = metrics.clone(); let _scoped_count = metrics::scoped_inc(&metrics.current_connection_count); let octobot = octobot.clone(); async move { // move the scoped count inside the future let _scoped_count = _scoped_count; let octobot = octobot.clone(); Ok::<_, hyper::Error>(service_fn(move |req| { let octobot = octobot.clone(); octobot.call(req) })) } }); let server = Server::bind(&http_addr).serve(main_service); info!("Listening (HTTP) on {}", http_addr); if let Err(e) = server.await { error!("server error: {}", e); } }
.await {
random_line_split
main.rs
use std::net::SocketAddr; use std::sync::Arc; use hyper::server::Server; use hyper::service::{make_service_fn, service_fn}; use log::{error, info}; use crate::runtime; use crate::server::github_handler::GithubHandlerState; use crate::server::octobot_service::OctobotService; use crate::server::sessions::Sessions; use octobot_lib::config::Config; use octobot_lib::github; use octobot_lib::jira; use octobot_lib::jira::api::JiraSession; use octobot_lib::metrics; pub fn
(config: Config) { let num_http_threads = config.main.num_http_threads.unwrap_or(20); let metrics = metrics::Metrics::new(); runtime::run(num_http_threads, metrics.clone(), async move { run_server(config, metrics).await }); } async fn run_server(config: Config, metrics: Arc<metrics::Metrics>) { let config = Arc::new(config); let github: Arc<dyn github::api::GithubSessionFactory>; if config.github.app_id.is_some() { github = match github::api::GithubApp::new( &config.github.host, config.github.app_id.expect("expected an app_id"), &config.github.app_key().expect("expected an app_key"), Some(metrics.clone()), ) .await { Ok(s) => Arc::new(s), Err(e) => panic!("Error initiating github session: {}", e), }; } else { github = match github::api::GithubOauthApp::new( &config.github.host, config .github .api_token .as_ref() .expect("expected an api_token"), Some(metrics.clone()), ) .await { Ok(s) => Arc::new(s), Err(e) => panic!("Error initiating github session: {}", e), }; } let jira: Option<Arc<dyn jira::api::Session>>; if let Some(ref jira_config) = config.jira { jira = match JiraSession::new(jira_config, Some(metrics.clone())).await { Ok(s) => Some(Arc::new(s)), Err(e) => panic!("Error initiating jira session: {}", e), }; } else { jira = None; } let http_addr: SocketAddr = match config.main.listen_addr { Some(ref addr_and_port) => addr_and_port.parse().unwrap(), None => "0.0.0.0:3000".parse().unwrap(), }; let ui_sessions = Arc::new(Sessions::new()); let github_handler_state = Arc::new(GithubHandlerState::new( config.clone(), github.clone(), jira.clone(), metrics.clone(), )); let octobot = OctobotService::new( config.clone(), ui_sessions.clone(), github_handler_state.clone(), metrics.clone(), ); let main_service = make_service_fn(move |_| { let metrics = metrics.clone(); let _scoped_count = metrics::scoped_inc(&metrics.current_connection_count); let octobot = octobot.clone(); async move { // move the scoped count inside the future let _scoped_count = _scoped_count; let octobot = octobot.clone(); Ok::<_, hyper::Error>(service_fn(move |req| { let octobot = octobot.clone(); octobot.call(req) })) } }); let server = Server::bind(&http_addr).serve(main_service); info!("Listening (HTTP) on {}", http_addr); if let Err(e) = server.await { error!("server error: {}", e); } }
start
identifier_name
main.rs
use std::net::SocketAddr; use std::sync::Arc; use hyper::server::Server; use hyper::service::{make_service_fn, service_fn}; use log::{error, info}; use crate::runtime; use crate::server::github_handler::GithubHandlerState; use crate::server::octobot_service::OctobotService; use crate::server::sessions::Sessions; use octobot_lib::config::Config; use octobot_lib::github; use octobot_lib::jira; use octobot_lib::jira::api::JiraSession; use octobot_lib::metrics; pub fn start(config: Config) { let num_http_threads = config.main.num_http_threads.unwrap_or(20); let metrics = metrics::Metrics::new(); runtime::run(num_http_threads, metrics.clone(), async move { run_server(config, metrics).await }); } async fn run_server(config: Config, metrics: Arc<metrics::Metrics>)
{ let config = Arc::new(config); let github: Arc<dyn github::api::GithubSessionFactory>; if config.github.app_id.is_some() { github = match github::api::GithubApp::new( &config.github.host, config.github.app_id.expect("expected an app_id"), &config.github.app_key().expect("expected an app_key"), Some(metrics.clone()), ) .await { Ok(s) => Arc::new(s), Err(e) => panic!("Error initiating github session: {}", e), }; } else { github = match github::api::GithubOauthApp::new( &config.github.host, config .github .api_token .as_ref() .expect("expected an api_token"), Some(metrics.clone()), ) .await { Ok(s) => Arc::new(s), Err(e) => panic!("Error initiating github session: {}", e), }; } let jira: Option<Arc<dyn jira::api::Session>>; if let Some(ref jira_config) = config.jira { jira = match JiraSession::new(jira_config, Some(metrics.clone())).await { Ok(s) => Some(Arc::new(s)), Err(e) => panic!("Error initiating jira session: {}", e), }; } else { jira = None; } let http_addr: SocketAddr = match config.main.listen_addr { Some(ref addr_and_port) => addr_and_port.parse().unwrap(), None => "0.0.0.0:3000".parse().unwrap(), }; let ui_sessions = Arc::new(Sessions::new()); let github_handler_state = Arc::new(GithubHandlerState::new( config.clone(), github.clone(), jira.clone(), metrics.clone(), )); let octobot = OctobotService::new( config.clone(), ui_sessions.clone(), github_handler_state.clone(), metrics.clone(), ); let main_service = make_service_fn(move |_| { let metrics = metrics.clone(); let _scoped_count = metrics::scoped_inc(&metrics.current_connection_count); let octobot = octobot.clone(); async move { // move the scoped count inside the future let _scoped_count = _scoped_count; let octobot = octobot.clone(); Ok::<_, hyper::Error>(service_fn(move |req| { let octobot = octobot.clone(); octobot.call(req) })) } }); let server = Server::bind(&http_addr).serve(main_service); info!("Listening (HTTP) on {}", http_addr); if let Err(e) = server.await { error!("server error: {}", e); } }
identifier_body
dashboard-controller.js
function DashboardController($scope, $state, $stateParams, dashboardFactory) { var dc = this; dc.playerStats = {}; dc.itemForAuction = {}; dc.auctionStarted = false; // Called on page load to retrieve player data dashboardFactory.getData(dashboardFactory.getName()).then(function(response) { dc.playerStats = response.data; }); var unbindLogout = $scope.$on('logout', function() { dashboardFactory.logout().then(function(response) { if (response.status === 200) { $state.go('login'); } }); }); var unbindStart = $scope.$on('startAuction', function(evt, data) { dc.auctionStarted = true; dc.itemForAuction = data; $scope.$broadcast('roll it'); }); var unbindClose = $scope.$on('auction closed', function(evt, data) { updateData(dc.playerStats, data); dashboardFactory.processBid(data).then(function(response) { if (response.data === 200) { dashboardFactory.getData(dashboardFactory.getName()).then(function(res) { dc.playerStats = res.data; }); } }); }); // Clear events $scope.$on('$destroy', function() { unbindLogout(); unbindStart(); unbindClose(); }); /** * @desc function that updates player dashboard in real-time * @param {Object} playerData - logged in player's data * @param {Object} newData - contains player's recent transaction */ function updateData(playerData, newData)
} module.exports = DashboardController;
{ playerData.coins = playerData.coins - newData.value; angular.forEach(playerData.inventoryItems, function(item) { if (item.name === newData.itemName) { item.quantity = item.quantity - newData.qty; } }); }
identifier_body
dashboard-controller.js
function
($scope, $state, $stateParams, dashboardFactory) { var dc = this; dc.playerStats = {}; dc.itemForAuction = {}; dc.auctionStarted = false; // Called on page load to retrieve player data dashboardFactory.getData(dashboardFactory.getName()).then(function(response) { dc.playerStats = response.data; }); var unbindLogout = $scope.$on('logout', function() { dashboardFactory.logout().then(function(response) { if (response.status === 200) { $state.go('login'); } }); }); var unbindStart = $scope.$on('startAuction', function(evt, data) { dc.auctionStarted = true; dc.itemForAuction = data; $scope.$broadcast('roll it'); }); var unbindClose = $scope.$on('auction closed', function(evt, data) { updateData(dc.playerStats, data); dashboardFactory.processBid(data).then(function(response) { if (response.data === 200) { dashboardFactory.getData(dashboardFactory.getName()).then(function(res) { dc.playerStats = res.data; }); } }); }); // Clear events $scope.$on('$destroy', function() { unbindLogout(); unbindStart(); unbindClose(); }); /** * @desc function that updates player dashboard in real-time * @param {Object} playerData - logged in player's data * @param {Object} newData - contains player's recent transaction */ function updateData(playerData, newData) { playerData.coins = playerData.coins - newData.value; angular.forEach(playerData.inventoryItems, function(item) { if (item.name === newData.itemName) { item.quantity = item.quantity - newData.qty; } }); } } module.exports = DashboardController;
DashboardController
identifier_name
dashboard-controller.js
function DashboardController($scope, $state, $stateParams, dashboardFactory) { var dc = this; dc.playerStats = {}; dc.itemForAuction = {}; dc.auctionStarted = false; // Called on page load to retrieve player data dashboardFactory.getData(dashboardFactory.getName()).then(function(response) { dc.playerStats = response.data; }); var unbindLogout = $scope.$on('logout', function() { dashboardFactory.logout().then(function(response) { if (response.status === 200) { $state.go('login'); } }); }); var unbindStart = $scope.$on('startAuction', function(evt, data) { dc.auctionStarted = true; dc.itemForAuction = data; $scope.$broadcast('roll it'); }); var unbindClose = $scope.$on('auction closed', function(evt, data) { updateData(dc.playerStats, data); dashboardFactory.processBid(data).then(function(response) { if (response.data === 200) { dashboardFactory.getData(dashboardFactory.getName()).then(function(res) { dc.playerStats = res.data; }); } }); }); // Clear events $scope.$on('$destroy', function() { unbindLogout(); unbindStart(); unbindClose(); }); /** * @desc function that updates player dashboard in real-time * @param {Object} playerData - logged in player's data * @param {Object} newData - contains player's recent transaction */ function updateData(playerData, newData) { playerData.coins = playerData.coins - newData.value; angular.forEach(playerData.inventoryItems, function(item) { if (item.name === newData.itemName)
}); } } module.exports = DashboardController;
{ item.quantity = item.quantity - newData.qty; }
conditional_block
dashboard-controller.js
function DashboardController($scope, $state, $stateParams, dashboardFactory) { var dc = this; dc.playerStats = {}; dc.itemForAuction = {}; dc.auctionStarted = false; // Called on page load to retrieve player data dashboardFactory.getData(dashboardFactory.getName()).then(function(response) { dc.playerStats = response.data; }); var unbindLogout = $scope.$on('logout', function() { dashboardFactory.logout().then(function(response) { if (response.status === 200) { $state.go('login'); } }); }); var unbindStart = $scope.$on('startAuction', function(evt, data) { dc.auctionStarted = true; dc.itemForAuction = data; $scope.$broadcast('roll it'); }); var unbindClose = $scope.$on('auction closed', function(evt, data) { updateData(dc.playerStats, data); dashboardFactory.processBid(data).then(function(response) { if (response.data === 200) { dashboardFactory.getData(dashboardFactory.getName()).then(function(res) { dc.playerStats = res.data;
}); }); // Clear events $scope.$on('$destroy', function() { unbindLogout(); unbindStart(); unbindClose(); }); /** * @desc function that updates player dashboard in real-time * @param {Object} playerData - logged in player's data * @param {Object} newData - contains player's recent transaction */ function updateData(playerData, newData) { playerData.coins = playerData.coins - newData.value; angular.forEach(playerData.inventoryItems, function(item) { if (item.name === newData.itemName) { item.quantity = item.quantity - newData.qty; } }); } } module.exports = DashboardController;
}); }
random_line_split
Main.js
Ext.define('TrackApp.view.main.Main', { extend: 'Ext.panel.Panel', requires: [ 'Ext.resizer.Splitter' ], xtype: 'app-main', controller: 'main', viewModel: { type: 'main' }, title: 'Oslo-Bergen til fots', header: { titlePosition: 0, defaults: { xtype: 'button', toggleGroup: 'menu' }, items: [{ text: 'Bilder', id: 'instagram' },{ text: 'Høydeprofil', id: 'profile' },{ text: 'Posisjon', id: 'positions' },{ text: 'Facebook', id: 'facebookUrl', reference: 'facebookBtn' },{ text: 'Instagram', id: 'instagramUrl', reference: 'instagramBtn' }] }, layout: { type: 'vbox', pack: 'start', align: 'stretch' }, items: [{ reference: 'map', xtype: 'map', flex: 3 }, { reference: 'bottom', xtype: 'panel', flex: 2, //split: true, hidden: true, layout: { type: 'fit' }, defaults: { hidden: true },
reference: 'positions', xtype: 'positions' }] }] });
items: [{ reference: 'profile', xtype: 'profile' },{
random_line_split
local_ptr.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Access to a single thread-local pointer. //! //! The runtime will use this for storing ~Task. //! //! FIXME: Add runtime checks for usage of inconsistent pointer types. //! and for overwriting an existing pointer. #![allow(dead_code)] use cast; use ops::{Drop, Deref, DerefMut}; use ptr::RawPtr; #[cfg(windows)] // mingw-w32 doesn't like thread_local things #[cfg(target_os = "android")] // see #10686 pub use self::native::{init, cleanup, put, take, try_take, unsafe_take, exists, unsafe_borrow, try_unsafe_borrow}; #[cfg(not(windows), not(target_os = "android"))] pub use self::compiled::{init, cleanup, put, take, try_take, unsafe_take, exists, unsafe_borrow, try_unsafe_borrow}; /// Encapsulates a borrowed value. When this value goes out of scope, the /// pointer is returned. pub struct Borrowed<T> { val: *(), } #[unsafe_destructor] impl<T> Drop for Borrowed<T> { fn drop(&mut self) { unsafe { if self.val.is_null() { rtabort!("Aiee, returning null borrowed object!"); } let val: ~T = cast::transmute(self.val); put::<T>(val); rtassert!(exists()); } } } impl<T> Deref<T> for Borrowed<T> { fn deref<'a>(&'a self) -> &'a T { unsafe { &*(self.val as *T) } } } impl<T> DerefMut<T> for Borrowed<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *(self.val as *mut T) } } } /// Borrow the thread-local value from thread-local storage. /// While the value is borrowed it is not available in TLS. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn borrow<T>() -> Borrowed<T> { let val: *() = cast::transmute(take::<T>()); Borrowed { val: val, } } /// Compiled implementation of accessing the runtime local pointer. This is /// implemented using LLVM's thread_local attribute which isn't necessarily /// working on all platforms. This implementation is faster, however, so we use /// it wherever possible. #[cfg(not(windows), not(target_os = "android"))] pub mod compiled { use cast; use option::{Option, Some, None}; use ptr::RawPtr; #[cfg(test)] pub use realstd::rt::shouldnt_be_public::RT_TLS_PTR; #[cfg(not(test))] #[thread_local] pub static mut RT_TLS_PTR: *mut u8 = 0 as *mut u8; pub fn init() {} pub unsafe fn cleanup() {} // Rationale for all of these functions being inline(never) // // The #[thread_local] annotation gets propagated all the way through to // LLVM, meaning the global is specially treated by LLVM to lower it to an // efficient sequence of instructions. This also involves dealing with fun // stuff in object files and whatnot. Regardless, it turns out this causes // trouble with green threads and lots of optimizations turned on. The // following case study was done on linux x86_64, but I would imagine that // other platforms are similar. // // On linux, the instruction sequence for loading the tls pointer global // looks like: // // mov %fs:0x0, %rax // mov -0x8(%rax), %rbx // // This code leads me to believe that (%fs:0x0) is a table, and then the // table contains the TLS values for the process. Hence, the slot at offset // -0x8 is the task TLS pointer. This leads us to the conclusion that this // table is the actual thread local part of each thread. The kernel sets up // the fs segment selector to point at the right region of memory for each // thread. // // Optimizations lead me to believe that this code is lowered to these // instructions in the LLVM codegen passes, because you'll see code like // this when everything is optimized: // // mov %fs:0x0, %r14 // mov -0x8(%r14), %rbx // // do something with %rbx, the rust Task pointer // // ... // <- do more things // // mov -0x8(%r14), %rbx // // do something else with %rbx // // Note that the optimization done here is that the first load is not // duplicated during the lower instructions. This means that the %fs:0x0 // memory location is only dereferenced once. // // Normally, this is actually a good thing! With green threads, however, // it's very possible for the code labeled "do more things" to context // switch to another thread. If this happens, then we *must* re-load %fs:0x0 // because it's changed (we're on a different thread). If we don't re-load // the table location, then we'll be reading the original thread's TLS // values, not our thread's TLS values. // // Hence, we never inline these functions. By never inlining, we're // guaranteed that loading the table is a local decision which is forced to // *always* happen. /// Give a pointer to thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn put<T>(sched: ~T) { RT_TLS_PTR = cast::transmute(sched) } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn take<T>() -> ~T { let ptr = RT_TLS_PTR; rtassert!(!ptr.is_null()); let ptr: ~T = cast::transmute(ptr); // can't use `as`, due to type not matching with `cfg(test)` RT_TLS_PTR = cast::transmute(0); ptr } /// Optionally take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn try_take<T>() -> Option<~T> { let ptr = RT_TLS_PTR; if ptr.is_null() { None } else
} /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. /// Leaves the old pointer in TLS for speed. #[inline(never)] // see comments above pub unsafe fn unsafe_take<T>() -> ~T { cast::transmute(RT_TLS_PTR) } /// Check whether there is a thread-local pointer installed. #[inline(never)] // see comments above pub fn exists() -> bool { unsafe { RT_TLS_PTR.is_not_null() } } #[inline(never)] // see comments above pub unsafe fn unsafe_borrow<T>() -> *mut T { if RT_TLS_PTR.is_null() { rtabort!("thread-local pointer is null. bogus!"); } RT_TLS_PTR as *mut T } #[inline(never)] // see comments above pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> { if RT_TLS_PTR.is_null() { None } else { Some(RT_TLS_PTR as *mut T) } } } /// Native implementation of having the runtime thread-local pointer. This /// implementation uses the `thread_local_storage` module to provide a /// thread-local value. pub mod native { use cast; use option::{Option, Some, None}; use ptr; use ptr::RawPtr; use tls = rt::thread_local_storage; static mut RT_TLS_KEY: tls::Key = -1; /// Initialize the TLS key. Other ops will fail if this isn't executed /// first. pub fn init() { unsafe { tls::create(&mut RT_TLS_KEY); } } pub unsafe fn cleanup() { rtassert!(RT_TLS_KEY != -1); tls::destroy(RT_TLS_KEY); } /// Give a pointer to thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn put<T>(sched: ~T) { let key = tls_key(); let void_ptr: *mut u8 = cast::transmute(sched); tls::set(key, void_ptr); } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn take<T>() -> ~T { let key = tls_key(); let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } let ptr: ~T = cast::transmute(void_ptr); tls::set(key, ptr::mut_null()); return ptr; } /// Optionally take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn try_take<T>() -> Option<~T> { match maybe_tls_key() { Some(key) => { let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { None } else { let ptr: ~T = cast::transmute(void_ptr); tls::set(key, ptr::mut_null()); Some(ptr) } } None => None } } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. /// Leaves the old pointer in TLS for speed. #[inline] pub unsafe fn unsafe_take<T>() -> ~T { let key = tls_key(); let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } let ptr: ~T = cast::transmute(void_ptr); return ptr; } /// Check whether there is a thread-local pointer installed. pub fn exists() -> bool { unsafe { match maybe_tls_key() { Some(key) => tls::get(key).is_not_null(), None => false } } } /// Borrow a mutable reference to the thread-local value /// /// # Safety Note /// /// Because this leaves the value in thread-local storage it is possible /// For the Scheduler pointer to be aliased pub unsafe fn unsafe_borrow<T>() -> *mut T { let key = tls_key(); let void_ptr = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } void_ptr as *mut T } pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> { match maybe_tls_key() { Some(key) => { let void_ptr = tls::get(key); if void_ptr.is_null() { None } else { Some(void_ptr as *mut T) } } None => None } } #[inline] fn tls_key() -> tls::Key { match maybe_tls_key() { Some(key) => key, None => rtabort!("runtime tls key not initialized") } } #[inline] #[cfg(not(test))] #[allow(visible_private_types)] pub fn maybe_tls_key() -> Option<tls::Key> { unsafe { // NB: This is a little racy because, while the key is // initialized under a mutex and it's assumed to be initialized // in the Scheduler ctor by any thread that needs to use it, // we are not accessing the key under a mutex. Threads that // are not using the new Scheduler but still *want to check* // whether they are running under a new Scheduler may see a 0 // value here that is in the process of being initialized in // another thread. I think this is fine since the only action // they could take if it was initialized would be to check the // thread-local value and see that it's not set. if RT_TLS_KEY != -1 { return Some(RT_TLS_KEY); } else { return None; } } } #[inline] #[cfg(test)] pub fn maybe_tls_key() -> Option<tls::Key> { use realstd; unsafe { cast::transmute(realstd::rt::shouldnt_be_public::maybe_tls_key()) } } }
{ let ptr: ~T = cast::transmute(ptr); // can't use `as`, due to type not matching with `cfg(test)` RT_TLS_PTR = cast::transmute(0); Some(ptr) }
conditional_block
local_ptr.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Access to a single thread-local pointer. //! //! The runtime will use this for storing ~Task. //! //! FIXME: Add runtime checks for usage of inconsistent pointer types. //! and for overwriting an existing pointer. #![allow(dead_code)] use cast; use ops::{Drop, Deref, DerefMut}; use ptr::RawPtr; #[cfg(windows)] // mingw-w32 doesn't like thread_local things #[cfg(target_os = "android")] // see #10686 pub use self::native::{init, cleanup, put, take, try_take, unsafe_take, exists, unsafe_borrow, try_unsafe_borrow}; #[cfg(not(windows), not(target_os = "android"))] pub use self::compiled::{init, cleanup, put, take, try_take, unsafe_take, exists, unsafe_borrow, try_unsafe_borrow}; /// Encapsulates a borrowed value. When this value goes out of scope, the /// pointer is returned. pub struct Borrowed<T> { val: *(), } #[unsafe_destructor] impl<T> Drop for Borrowed<T> { fn drop(&mut self) { unsafe { if self.val.is_null() { rtabort!("Aiee, returning null borrowed object!"); } let val: ~T = cast::transmute(self.val); put::<T>(val); rtassert!(exists()); } } } impl<T> Deref<T> for Borrowed<T> { fn deref<'a>(&'a self) -> &'a T { unsafe { &*(self.val as *T) } } } impl<T> DerefMut<T> for Borrowed<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *(self.val as *mut T) } } } /// Borrow the thread-local value from thread-local storage. /// While the value is borrowed it is not available in TLS. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn borrow<T>() -> Borrowed<T> { let val: *() = cast::transmute(take::<T>()); Borrowed { val: val, } } /// Compiled implementation of accessing the runtime local pointer. This is /// implemented using LLVM's thread_local attribute which isn't necessarily /// working on all platforms. This implementation is faster, however, so we use /// it wherever possible. #[cfg(not(windows), not(target_os = "android"))] pub mod compiled { use cast; use option::{Option, Some, None}; use ptr::RawPtr; #[cfg(test)] pub use realstd::rt::shouldnt_be_public::RT_TLS_PTR; #[cfg(not(test))] #[thread_local] pub static mut RT_TLS_PTR: *mut u8 = 0 as *mut u8; pub fn init() {} pub unsafe fn cleanup() {} // Rationale for all of these functions being inline(never) // // The #[thread_local] annotation gets propagated all the way through to // LLVM, meaning the global is specially treated by LLVM to lower it to an // efficient sequence of instructions. This also involves dealing with fun // stuff in object files and whatnot. Regardless, it turns out this causes // trouble with green threads and lots of optimizations turned on. The // following case study was done on linux x86_64, but I would imagine that // other platforms are similar. // // On linux, the instruction sequence for loading the tls pointer global // looks like: // // mov %fs:0x0, %rax // mov -0x8(%rax), %rbx // // This code leads me to believe that (%fs:0x0) is a table, and then the // table contains the TLS values for the process. Hence, the slot at offset // -0x8 is the task TLS pointer. This leads us to the conclusion that this // table is the actual thread local part of each thread. The kernel sets up // the fs segment selector to point at the right region of memory for each // thread. // // Optimizations lead me to believe that this code is lowered to these // instructions in the LLVM codegen passes, because you'll see code like // this when everything is optimized: // // mov %fs:0x0, %r14 // mov -0x8(%r14), %rbx // // do something with %rbx, the rust Task pointer // // ... // <- do more things // // mov -0x8(%r14), %rbx // // do something else with %rbx // // Note that the optimization done here is that the first load is not // duplicated during the lower instructions. This means that the %fs:0x0 // memory location is only dereferenced once. // // Normally, this is actually a good thing! With green threads, however, // it's very possible for the code labeled "do more things" to context // switch to another thread. If this happens, then we *must* re-load %fs:0x0 // because it's changed (we're on a different thread). If we don't re-load // the table location, then we'll be reading the original thread's TLS // values, not our thread's TLS values. // // Hence, we never inline these functions. By never inlining, we're // guaranteed that loading the table is a local decision which is forced to // *always* happen. /// Give a pointer to thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn put<T>(sched: ~T) { RT_TLS_PTR = cast::transmute(sched) } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn take<T>() -> ~T { let ptr = RT_TLS_PTR; rtassert!(!ptr.is_null()); let ptr: ~T = cast::transmute(ptr); // can't use `as`, due to type not matching with `cfg(test)` RT_TLS_PTR = cast::transmute(0); ptr } /// Optionally take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn try_take<T>() -> Option<~T> { let ptr = RT_TLS_PTR; if ptr.is_null() { None } else { let ptr: ~T = cast::transmute(ptr); // can't use `as`, due to type not matching with `cfg(test)` RT_TLS_PTR = cast::transmute(0); Some(ptr) } } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. /// Leaves the old pointer in TLS for speed. #[inline(never)] // see comments above pub unsafe fn
<T>() -> ~T { cast::transmute(RT_TLS_PTR) } /// Check whether there is a thread-local pointer installed. #[inline(never)] // see comments above pub fn exists() -> bool { unsafe { RT_TLS_PTR.is_not_null() } } #[inline(never)] // see comments above pub unsafe fn unsafe_borrow<T>() -> *mut T { if RT_TLS_PTR.is_null() { rtabort!("thread-local pointer is null. bogus!"); } RT_TLS_PTR as *mut T } #[inline(never)] // see comments above pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> { if RT_TLS_PTR.is_null() { None } else { Some(RT_TLS_PTR as *mut T) } } } /// Native implementation of having the runtime thread-local pointer. This /// implementation uses the `thread_local_storage` module to provide a /// thread-local value. pub mod native { use cast; use option::{Option, Some, None}; use ptr; use ptr::RawPtr; use tls = rt::thread_local_storage; static mut RT_TLS_KEY: tls::Key = -1; /// Initialize the TLS key. Other ops will fail if this isn't executed /// first. pub fn init() { unsafe { tls::create(&mut RT_TLS_KEY); } } pub unsafe fn cleanup() { rtassert!(RT_TLS_KEY != -1); tls::destroy(RT_TLS_KEY); } /// Give a pointer to thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn put<T>(sched: ~T) { let key = tls_key(); let void_ptr: *mut u8 = cast::transmute(sched); tls::set(key, void_ptr); } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn take<T>() -> ~T { let key = tls_key(); let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } let ptr: ~T = cast::transmute(void_ptr); tls::set(key, ptr::mut_null()); return ptr; } /// Optionally take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn try_take<T>() -> Option<~T> { match maybe_tls_key() { Some(key) => { let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { None } else { let ptr: ~T = cast::transmute(void_ptr); tls::set(key, ptr::mut_null()); Some(ptr) } } None => None } } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. /// Leaves the old pointer in TLS for speed. #[inline] pub unsafe fn unsafe_take<T>() -> ~T { let key = tls_key(); let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } let ptr: ~T = cast::transmute(void_ptr); return ptr; } /// Check whether there is a thread-local pointer installed. pub fn exists() -> bool { unsafe { match maybe_tls_key() { Some(key) => tls::get(key).is_not_null(), None => false } } } /// Borrow a mutable reference to the thread-local value /// /// # Safety Note /// /// Because this leaves the value in thread-local storage it is possible /// For the Scheduler pointer to be aliased pub unsafe fn unsafe_borrow<T>() -> *mut T { let key = tls_key(); let void_ptr = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } void_ptr as *mut T } pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> { match maybe_tls_key() { Some(key) => { let void_ptr = tls::get(key); if void_ptr.is_null() { None } else { Some(void_ptr as *mut T) } } None => None } } #[inline] fn tls_key() -> tls::Key { match maybe_tls_key() { Some(key) => key, None => rtabort!("runtime tls key not initialized") } } #[inline] #[cfg(not(test))] #[allow(visible_private_types)] pub fn maybe_tls_key() -> Option<tls::Key> { unsafe { // NB: This is a little racy because, while the key is // initialized under a mutex and it's assumed to be initialized // in the Scheduler ctor by any thread that needs to use it, // we are not accessing the key under a mutex. Threads that // are not using the new Scheduler but still *want to check* // whether they are running under a new Scheduler may see a 0 // value here that is in the process of being initialized in // another thread. I think this is fine since the only action // they could take if it was initialized would be to check the // thread-local value and see that it's not set. if RT_TLS_KEY != -1 { return Some(RT_TLS_KEY); } else { return None; } } } #[inline] #[cfg(test)] pub fn maybe_tls_key() -> Option<tls::Key> { use realstd; unsafe { cast::transmute(realstd::rt::shouldnt_be_public::maybe_tls_key()) } } }
unsafe_take
identifier_name
local_ptr.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Access to a single thread-local pointer. //! //! The runtime will use this for storing ~Task. //! //! FIXME: Add runtime checks for usage of inconsistent pointer types. //! and for overwriting an existing pointer. #![allow(dead_code)] use cast; use ops::{Drop, Deref, DerefMut}; use ptr::RawPtr; #[cfg(windows)] // mingw-w32 doesn't like thread_local things #[cfg(target_os = "android")] // see #10686 pub use self::native::{init, cleanup, put, take, try_take, unsafe_take, exists, unsafe_borrow, try_unsafe_borrow}; #[cfg(not(windows), not(target_os = "android"))] pub use self::compiled::{init, cleanup, put, take, try_take, unsafe_take, exists, unsafe_borrow, try_unsafe_borrow}; /// Encapsulates a borrowed value. When this value goes out of scope, the /// pointer is returned. pub struct Borrowed<T> { val: *(), } #[unsafe_destructor] impl<T> Drop for Borrowed<T> { fn drop(&mut self) { unsafe { if self.val.is_null() { rtabort!("Aiee, returning null borrowed object!"); } let val: ~T = cast::transmute(self.val); put::<T>(val); rtassert!(exists()); } } } impl<T> Deref<T> for Borrowed<T> { fn deref<'a>(&'a self) -> &'a T { unsafe { &*(self.val as *T) } } } impl<T> DerefMut<T> for Borrowed<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *(self.val as *mut T) } } } /// Borrow the thread-local value from thread-local storage. /// While the value is borrowed it is not available in TLS. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn borrow<T>() -> Borrowed<T> { let val: *() = cast::transmute(take::<T>()); Borrowed { val: val, } } /// Compiled implementation of accessing the runtime local pointer. This is /// implemented using LLVM's thread_local attribute which isn't necessarily /// working on all platforms. This implementation is faster, however, so we use /// it wherever possible. #[cfg(not(windows), not(target_os = "android"))] pub mod compiled { use cast; use option::{Option, Some, None}; use ptr::RawPtr; #[cfg(test)] pub use realstd::rt::shouldnt_be_public::RT_TLS_PTR; #[cfg(not(test))] #[thread_local] pub static mut RT_TLS_PTR: *mut u8 = 0 as *mut u8; pub fn init() {} pub unsafe fn cleanup() {} // Rationale for all of these functions being inline(never) // // The #[thread_local] annotation gets propagated all the way through to // LLVM, meaning the global is specially treated by LLVM to lower it to an // efficient sequence of instructions. This also involves dealing with fun // stuff in object files and whatnot. Regardless, it turns out this causes // trouble with green threads and lots of optimizations turned on. The // following case study was done on linux x86_64, but I would imagine that // other platforms are similar. // // On linux, the instruction sequence for loading the tls pointer global // looks like: // // mov %fs:0x0, %rax // mov -0x8(%rax), %rbx // // This code leads me to believe that (%fs:0x0) is a table, and then the // table contains the TLS values for the process. Hence, the slot at offset // -0x8 is the task TLS pointer. This leads us to the conclusion that this // table is the actual thread local part of each thread. The kernel sets up // the fs segment selector to point at the right region of memory for each // thread. // // Optimizations lead me to believe that this code is lowered to these // instructions in the LLVM codegen passes, because you'll see code like // this when everything is optimized: // // mov %fs:0x0, %r14 // mov -0x8(%r14), %rbx // // do something with %rbx, the rust Task pointer // // ... // <- do more things // // mov -0x8(%r14), %rbx // // do something else with %rbx // // Note that the optimization done here is that the first load is not // duplicated during the lower instructions. This means that the %fs:0x0 // memory location is only dereferenced once. // // Normally, this is actually a good thing! With green threads, however, // it's very possible for the code labeled "do more things" to context // switch to another thread. If this happens, then we *must* re-load %fs:0x0 // because it's changed (we're on a different thread). If we don't re-load // the table location, then we'll be reading the original thread's TLS // values, not our thread's TLS values. // // Hence, we never inline these functions. By never inlining, we're // guaranteed that loading the table is a local decision which is forced to // *always* happen. /// Give a pointer to thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn put<T>(sched: ~T) { RT_TLS_PTR = cast::transmute(sched) } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn take<T>() -> ~T { let ptr = RT_TLS_PTR; rtassert!(!ptr.is_null()); let ptr: ~T = cast::transmute(ptr); // can't use `as`, due to type not matching with `cfg(test)` RT_TLS_PTR = cast::transmute(0); ptr } /// Optionally take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn try_take<T>() -> Option<~T> { let ptr = RT_TLS_PTR; if ptr.is_null() { None } else { let ptr: ~T = cast::transmute(ptr); // can't use `as`, due to type not matching with `cfg(test)` RT_TLS_PTR = cast::transmute(0); Some(ptr) } } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. /// Leaves the old pointer in TLS for speed. #[inline(never)] // see comments above pub unsafe fn unsafe_take<T>() -> ~T { cast::transmute(RT_TLS_PTR) } /// Check whether there is a thread-local pointer installed. #[inline(never)] // see comments above pub fn exists() -> bool { unsafe { RT_TLS_PTR.is_not_null() } } #[inline(never)] // see comments above pub unsafe fn unsafe_borrow<T>() -> *mut T { if RT_TLS_PTR.is_null() { rtabort!("thread-local pointer is null. bogus!"); } RT_TLS_PTR as *mut T } #[inline(never)] // see comments above pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> { if RT_TLS_PTR.is_null() { None } else { Some(RT_TLS_PTR as *mut T) } } } /// Native implementation of having the runtime thread-local pointer. This /// implementation uses the `thread_local_storage` module to provide a /// thread-local value. pub mod native { use cast; use option::{Option, Some, None}; use ptr; use ptr::RawPtr; use tls = rt::thread_local_storage; static mut RT_TLS_KEY: tls::Key = -1; /// Initialize the TLS key. Other ops will fail if this isn't executed /// first. pub fn init() { unsafe { tls::create(&mut RT_TLS_KEY); } } pub unsafe fn cleanup() { rtassert!(RT_TLS_KEY != -1); tls::destroy(RT_TLS_KEY); } /// Give a pointer to thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn put<T>(sched: ~T) { let key = tls_key(); let void_ptr: *mut u8 = cast::transmute(sched); tls::set(key, void_ptr); } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn take<T>() -> ~T { let key = tls_key(); let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } let ptr: ~T = cast::transmute(void_ptr); tls::set(key, ptr::mut_null()); return ptr; } /// Optionally take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn try_take<T>() -> Option<~T>
/// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. /// Leaves the old pointer in TLS for speed. #[inline] pub unsafe fn unsafe_take<T>() -> ~T { let key = tls_key(); let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } let ptr: ~T = cast::transmute(void_ptr); return ptr; } /// Check whether there is a thread-local pointer installed. pub fn exists() -> bool { unsafe { match maybe_tls_key() { Some(key) => tls::get(key).is_not_null(), None => false } } } /// Borrow a mutable reference to the thread-local value /// /// # Safety Note /// /// Because this leaves the value in thread-local storage it is possible /// For the Scheduler pointer to be aliased pub unsafe fn unsafe_borrow<T>() -> *mut T { let key = tls_key(); let void_ptr = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } void_ptr as *mut T } pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> { match maybe_tls_key() { Some(key) => { let void_ptr = tls::get(key); if void_ptr.is_null() { None } else { Some(void_ptr as *mut T) } } None => None } } #[inline] fn tls_key() -> tls::Key { match maybe_tls_key() { Some(key) => key, None => rtabort!("runtime tls key not initialized") } } #[inline] #[cfg(not(test))] #[allow(visible_private_types)] pub fn maybe_tls_key() -> Option<tls::Key> { unsafe { // NB: This is a little racy because, while the key is // initialized under a mutex and it's assumed to be initialized // in the Scheduler ctor by any thread that needs to use it, // we are not accessing the key under a mutex. Threads that // are not using the new Scheduler but still *want to check* // whether they are running under a new Scheduler may see a 0 // value here that is in the process of being initialized in // another thread. I think this is fine since the only action // they could take if it was initialized would be to check the // thread-local value and see that it's not set. if RT_TLS_KEY != -1 { return Some(RT_TLS_KEY); } else { return None; } } } #[inline] #[cfg(test)] pub fn maybe_tls_key() -> Option<tls::Key> { use realstd; unsafe { cast::transmute(realstd::rt::shouldnt_be_public::maybe_tls_key()) } } }
{ match maybe_tls_key() { Some(key) => { let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { None } else { let ptr: ~T = cast::transmute(void_ptr); tls::set(key, ptr::mut_null()); Some(ptr) } } None => None } }
identifier_body
local_ptr.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Access to a single thread-local pointer. //! //! The runtime will use this for storing ~Task. //! //! FIXME: Add runtime checks for usage of inconsistent pointer types. //! and for overwriting an existing pointer. #![allow(dead_code)] use cast; use ops::{Drop, Deref, DerefMut}; use ptr::RawPtr; #[cfg(windows)] // mingw-w32 doesn't like thread_local things #[cfg(target_os = "android")] // see #10686 pub use self::native::{init, cleanup, put, take, try_take, unsafe_take, exists, unsafe_borrow, try_unsafe_borrow}; #[cfg(not(windows), not(target_os = "android"))] pub use self::compiled::{init, cleanup, put, take, try_take, unsafe_take, exists, unsafe_borrow, try_unsafe_borrow}; /// Encapsulates a borrowed value. When this value goes out of scope, the /// pointer is returned. pub struct Borrowed<T> { val: *(), } #[unsafe_destructor] impl<T> Drop for Borrowed<T> { fn drop(&mut self) { unsafe { if self.val.is_null() { rtabort!("Aiee, returning null borrowed object!"); } let val: ~T = cast::transmute(self.val); put::<T>(val); rtassert!(exists()); } } } impl<T> Deref<T> for Borrowed<T> { fn deref<'a>(&'a self) -> &'a T { unsafe { &*(self.val as *T) } } } impl<T> DerefMut<T> for Borrowed<T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *(self.val as *mut T) } } } /// Borrow the thread-local value from thread-local storage. /// While the value is borrowed it is not available in TLS. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn borrow<T>() -> Borrowed<T> { let val: *() = cast::transmute(take::<T>()); Borrowed { val: val, } } /// Compiled implementation of accessing the runtime local pointer. This is /// implemented using LLVM's thread_local attribute which isn't necessarily /// working on all platforms. This implementation is faster, however, so we use /// it wherever possible. #[cfg(not(windows), not(target_os = "android"))] pub mod compiled { use cast; use option::{Option, Some, None}; use ptr::RawPtr; #[cfg(test)] pub use realstd::rt::shouldnt_be_public::RT_TLS_PTR; #[cfg(not(test))] #[thread_local] pub static mut RT_TLS_PTR: *mut u8 = 0 as *mut u8; pub fn init() {} pub unsafe fn cleanup() {} // Rationale for all of these functions being inline(never) // // The #[thread_local] annotation gets propagated all the way through to // LLVM, meaning the global is specially treated by LLVM to lower it to an // efficient sequence of instructions. This also involves dealing with fun // stuff in object files and whatnot. Regardless, it turns out this causes // trouble with green threads and lots of optimizations turned on. The // following case study was done on linux x86_64, but I would imagine that // other platforms are similar. // // On linux, the instruction sequence for loading the tls pointer global // looks like: // // mov %fs:0x0, %rax // mov -0x8(%rax), %rbx // // This code leads me to believe that (%fs:0x0) is a table, and then the // table contains the TLS values for the process. Hence, the slot at offset // -0x8 is the task TLS pointer. This leads us to the conclusion that this // table is the actual thread local part of each thread. The kernel sets up // the fs segment selector to point at the right region of memory for each // thread. // // Optimizations lead me to believe that this code is lowered to these // instructions in the LLVM codegen passes, because you'll see code like // this when everything is optimized: // // mov %fs:0x0, %r14 // mov -0x8(%r14), %rbx // // do something with %rbx, the rust Task pointer // // ... // <- do more things // // mov -0x8(%r14), %rbx // // do something else with %rbx // // Note that the optimization done here is that the first load is not // duplicated during the lower instructions. This means that the %fs:0x0 // memory location is only dereferenced once. // // Normally, this is actually a good thing! With green threads, however, // it's very possible for the code labeled "do more things" to context // switch to another thread. If this happens, then we *must* re-load %fs:0x0 // because it's changed (we're on a different thread). If we don't re-load // the table location, then we'll be reading the original thread's TLS // values, not our thread's TLS values. // // Hence, we never inline these functions. By never inlining, we're // guaranteed that loading the table is a local decision which is forced to // *always* happen. /// Give a pointer to thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn put<T>(sched: ~T) { RT_TLS_PTR = cast::transmute(sched) } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn take<T>() -> ~T { let ptr = RT_TLS_PTR; rtassert!(!ptr.is_null()); let ptr: ~T = cast::transmute(ptr); // can't use `as`, due to type not matching with `cfg(test)` RT_TLS_PTR = cast::transmute(0); ptr } /// Optionally take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn try_take<T>() -> Option<~T> { let ptr = RT_TLS_PTR; if ptr.is_null() { None } else { let ptr: ~T = cast::transmute(ptr); // can't use `as`, due to type not matching with `cfg(test)` RT_TLS_PTR = cast::transmute(0); Some(ptr) } } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. /// Leaves the old pointer in TLS for speed. #[inline(never)] // see comments above pub unsafe fn unsafe_take<T>() -> ~T { cast::transmute(RT_TLS_PTR) } /// Check whether there is a thread-local pointer installed. #[inline(never)] // see comments above pub fn exists() -> bool { unsafe { RT_TLS_PTR.is_not_null() } } #[inline(never)] // see comments above pub unsafe fn unsafe_borrow<T>() -> *mut T { if RT_TLS_PTR.is_null() { rtabort!("thread-local pointer is null. bogus!"); } RT_TLS_PTR as *mut T } #[inline(never)] // see comments above pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> { if RT_TLS_PTR.is_null() { None } else { Some(RT_TLS_PTR as *mut T) } } } /// Native implementation of having the runtime thread-local pointer. This /// implementation uses the `thread_local_storage` module to provide a /// thread-local value. pub mod native { use cast; use option::{Option, Some, None}; use ptr; use ptr::RawPtr; use tls = rt::thread_local_storage; static mut RT_TLS_KEY: tls::Key = -1; /// Initialize the TLS key. Other ops will fail if this isn't executed /// first. pub fn init() { unsafe { tls::create(&mut RT_TLS_KEY); } } pub unsafe fn cleanup() { rtassert!(RT_TLS_KEY != -1); tls::destroy(RT_TLS_KEY); } /// Give a pointer to thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn put<T>(sched: ~T) { let key = tls_key(); let void_ptr: *mut u8 = cast::transmute(sched); tls::set(key, void_ptr); } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn take<T>() -> ~T { let key = tls_key(); let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } let ptr: ~T = cast::transmute(void_ptr); tls::set(key, ptr::mut_null()); return ptr; } /// Optionally take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn try_take<T>() -> Option<~T> { match maybe_tls_key() { Some(key) => { let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { None } else { let ptr: ~T = cast::transmute(void_ptr); tls::set(key, ptr::mut_null()); Some(ptr) } } None => None } } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. /// Leaves the old pointer in TLS for speed. #[inline]
let key = tls_key(); let void_ptr: *mut u8 = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } let ptr: ~T = cast::transmute(void_ptr); return ptr; } /// Check whether there is a thread-local pointer installed. pub fn exists() -> bool { unsafe { match maybe_tls_key() { Some(key) => tls::get(key).is_not_null(), None => false } } } /// Borrow a mutable reference to the thread-local value /// /// # Safety Note /// /// Because this leaves the value in thread-local storage it is possible /// For the Scheduler pointer to be aliased pub unsafe fn unsafe_borrow<T>() -> *mut T { let key = tls_key(); let void_ptr = tls::get(key); if void_ptr.is_null() { rtabort!("thread-local pointer is null. bogus!"); } void_ptr as *mut T } pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> { match maybe_tls_key() { Some(key) => { let void_ptr = tls::get(key); if void_ptr.is_null() { None } else { Some(void_ptr as *mut T) } } None => None } } #[inline] fn tls_key() -> tls::Key { match maybe_tls_key() { Some(key) => key, None => rtabort!("runtime tls key not initialized") } } #[inline] #[cfg(not(test))] #[allow(visible_private_types)] pub fn maybe_tls_key() -> Option<tls::Key> { unsafe { // NB: This is a little racy because, while the key is // initialized under a mutex and it's assumed to be initialized // in the Scheduler ctor by any thread that needs to use it, // we are not accessing the key under a mutex. Threads that // are not using the new Scheduler but still *want to check* // whether they are running under a new Scheduler may see a 0 // value here that is in the process of being initialized in // another thread. I think this is fine since the only action // they could take if it was initialized would be to check the // thread-local value and see that it's not set. if RT_TLS_KEY != -1 { return Some(RT_TLS_KEY); } else { return None; } } } #[inline] #[cfg(test)] pub fn maybe_tls_key() -> Option<tls::Key> { use realstd; unsafe { cast::transmute(realstd::rt::shouldnt_be_public::maybe_tls_key()) } } }
pub unsafe fn unsafe_take<T>() -> ~T {
random_line_split
__init__.py
import os from twisted.trial import unittest from scrapy.contrib.djangoitem import DjangoItem, Field from scrapy import optional_features os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapy.tests.test_djangoitem.settings' if 'django' in optional_features: from .models import Person, IdentifiedPerson class BasePersonItem(DjangoItem): django_model = Person class NewFieldPersonItem(BasePersonItem): other = Field() class OverrideFieldPersonItem(BasePersonItem): age = Field() class IdentifiedPersonItem(DjangoItem): django_model = IdentifiedPerson class DjangoItemTest(unittest.TestCase): def setUp(self): if 'django' not in optional_features: raise unittest.SkipTest("Django is not available") def test_base(self): i = BasePersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) def test_new_fields(self): i = NewFieldPersonItem() self.assertEqual(i.fields.keys(), ['age', 'other', 'name']) def test_override_field(self): i = OverrideFieldPersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) def test_custom_primary_key_field(self): """ Test that if a custom primary key exists, it is in the field list. """ i = IdentifiedPersonItem() self.assertEqual(i.fields.keys(), ['age', 'identifier', 'name']) def test_save(self): i = BasePersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) i['name'] = 'John' i['age'] = '22' person = i.save(commit=False) self.assertEqual(person.name, 'John') self.assertEqual(person.age, '22') def test_override_save(self): i = OverrideFieldPersonItem() i['name'] = 'John' # it is not obvious that "age" should be saved also, since it was # redefined in child class i['age'] = '22' person = i.save(commit=False) self.assertEqual(person.name, 'John') self.assertEqual(person.age, '22') def test_validation(self): long_name = 'z' * 300 i = BasePersonItem(name=long_name) self.assertFalse(i.is_valid()) self.assertEqual(set(i.errors), set(['age', 'name'])) i = BasePersonItem(name='John') self.assertTrue(i.is_valid(exclude=['age'])) self.assertEqual({}, i.errors) # once the item is validated, it does not validate again i['name'] = long_name self.assertTrue(i.is_valid()) def test_override_validation(self): i = OverrideFieldPersonItem() i['name'] = 'John' self.assertFalse(i.is_valid()) i = i = OverrideFieldPersonItem() i['name'] = 'John' i['age'] = '22' self.assertTrue(i.is_valid()) def test_default_field_values(self): i = BasePersonItem()
self.assertEqual(person.name, 'Robot')
person = i.save(commit=False)
random_line_split
__init__.py
import os from twisted.trial import unittest from scrapy.contrib.djangoitem import DjangoItem, Field from scrapy import optional_features os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapy.tests.test_djangoitem.settings' if 'django' in optional_features: from .models import Person, IdentifiedPerson class BasePersonItem(DjangoItem): django_model = Person class NewFieldPersonItem(BasePersonItem): other = Field() class OverrideFieldPersonItem(BasePersonItem): age = Field() class IdentifiedPersonItem(DjangoItem): django_model = IdentifiedPerson class DjangoItemTest(unittest.TestCase): def setUp(self): if 'django' not in optional_features:
def test_base(self): i = BasePersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) def test_new_fields(self): i = NewFieldPersonItem() self.assertEqual(i.fields.keys(), ['age', 'other', 'name']) def test_override_field(self): i = OverrideFieldPersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) def test_custom_primary_key_field(self): """ Test that if a custom primary key exists, it is in the field list. """ i = IdentifiedPersonItem() self.assertEqual(i.fields.keys(), ['age', 'identifier', 'name']) def test_save(self): i = BasePersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) i['name'] = 'John' i['age'] = '22' person = i.save(commit=False) self.assertEqual(person.name, 'John') self.assertEqual(person.age, '22') def test_override_save(self): i = OverrideFieldPersonItem() i['name'] = 'John' # it is not obvious that "age" should be saved also, since it was # redefined in child class i['age'] = '22' person = i.save(commit=False) self.assertEqual(person.name, 'John') self.assertEqual(person.age, '22') def test_validation(self): long_name = 'z' * 300 i = BasePersonItem(name=long_name) self.assertFalse(i.is_valid()) self.assertEqual(set(i.errors), set(['age', 'name'])) i = BasePersonItem(name='John') self.assertTrue(i.is_valid(exclude=['age'])) self.assertEqual({}, i.errors) # once the item is validated, it does not validate again i['name'] = long_name self.assertTrue(i.is_valid()) def test_override_validation(self): i = OverrideFieldPersonItem() i['name'] = 'John' self.assertFalse(i.is_valid()) i = i = OverrideFieldPersonItem() i['name'] = 'John' i['age'] = '22' self.assertTrue(i.is_valid()) def test_default_field_values(self): i = BasePersonItem() person = i.save(commit=False) self.assertEqual(person.name, 'Robot')
raise unittest.SkipTest("Django is not available")
conditional_block
__init__.py
import os from twisted.trial import unittest from scrapy.contrib.djangoitem import DjangoItem, Field from scrapy import optional_features os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapy.tests.test_djangoitem.settings' if 'django' in optional_features: from .models import Person, IdentifiedPerson class BasePersonItem(DjangoItem): django_model = Person class NewFieldPersonItem(BasePersonItem): other = Field() class
(BasePersonItem): age = Field() class IdentifiedPersonItem(DjangoItem): django_model = IdentifiedPerson class DjangoItemTest(unittest.TestCase): def setUp(self): if 'django' not in optional_features: raise unittest.SkipTest("Django is not available") def test_base(self): i = BasePersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) def test_new_fields(self): i = NewFieldPersonItem() self.assertEqual(i.fields.keys(), ['age', 'other', 'name']) def test_override_field(self): i = OverrideFieldPersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) def test_custom_primary_key_field(self): """ Test that if a custom primary key exists, it is in the field list. """ i = IdentifiedPersonItem() self.assertEqual(i.fields.keys(), ['age', 'identifier', 'name']) def test_save(self): i = BasePersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) i['name'] = 'John' i['age'] = '22' person = i.save(commit=False) self.assertEqual(person.name, 'John') self.assertEqual(person.age, '22') def test_override_save(self): i = OverrideFieldPersonItem() i['name'] = 'John' # it is not obvious that "age" should be saved also, since it was # redefined in child class i['age'] = '22' person = i.save(commit=False) self.assertEqual(person.name, 'John') self.assertEqual(person.age, '22') def test_validation(self): long_name = 'z' * 300 i = BasePersonItem(name=long_name) self.assertFalse(i.is_valid()) self.assertEqual(set(i.errors), set(['age', 'name'])) i = BasePersonItem(name='John') self.assertTrue(i.is_valid(exclude=['age'])) self.assertEqual({}, i.errors) # once the item is validated, it does not validate again i['name'] = long_name self.assertTrue(i.is_valid()) def test_override_validation(self): i = OverrideFieldPersonItem() i['name'] = 'John' self.assertFalse(i.is_valid()) i = i = OverrideFieldPersonItem() i['name'] = 'John' i['age'] = '22' self.assertTrue(i.is_valid()) def test_default_field_values(self): i = BasePersonItem() person = i.save(commit=False) self.assertEqual(person.name, 'Robot')
OverrideFieldPersonItem
identifier_name
__init__.py
import os from twisted.trial import unittest from scrapy.contrib.djangoitem import DjangoItem, Field from scrapy import optional_features os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapy.tests.test_djangoitem.settings' if 'django' in optional_features: from .models import Person, IdentifiedPerson class BasePersonItem(DjangoItem): django_model = Person class NewFieldPersonItem(BasePersonItem): other = Field() class OverrideFieldPersonItem(BasePersonItem): age = Field() class IdentifiedPersonItem(DjangoItem): django_model = IdentifiedPerson class DjangoItemTest(unittest.TestCase): def setUp(self): if 'django' not in optional_features: raise unittest.SkipTest("Django is not available") def test_base(self): i = BasePersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) def test_new_fields(self):
def test_override_field(self): i = OverrideFieldPersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) def test_custom_primary_key_field(self): """ Test that if a custom primary key exists, it is in the field list. """ i = IdentifiedPersonItem() self.assertEqual(i.fields.keys(), ['age', 'identifier', 'name']) def test_save(self): i = BasePersonItem() self.assertEqual(i.fields.keys(), ['age', 'name']) i['name'] = 'John' i['age'] = '22' person = i.save(commit=False) self.assertEqual(person.name, 'John') self.assertEqual(person.age, '22') def test_override_save(self): i = OverrideFieldPersonItem() i['name'] = 'John' # it is not obvious that "age" should be saved also, since it was # redefined in child class i['age'] = '22' person = i.save(commit=False) self.assertEqual(person.name, 'John') self.assertEqual(person.age, '22') def test_validation(self): long_name = 'z' * 300 i = BasePersonItem(name=long_name) self.assertFalse(i.is_valid()) self.assertEqual(set(i.errors), set(['age', 'name'])) i = BasePersonItem(name='John') self.assertTrue(i.is_valid(exclude=['age'])) self.assertEqual({}, i.errors) # once the item is validated, it does not validate again i['name'] = long_name self.assertTrue(i.is_valid()) def test_override_validation(self): i = OverrideFieldPersonItem() i['name'] = 'John' self.assertFalse(i.is_valid()) i = i = OverrideFieldPersonItem() i['name'] = 'John' i['age'] = '22' self.assertTrue(i.is_valid()) def test_default_field_values(self): i = BasePersonItem() person = i.save(commit=False) self.assertEqual(person.name, 'Robot')
i = NewFieldPersonItem() self.assertEqual(i.fields.keys(), ['age', 'other', 'name'])
identifier_body
mod.rs
mod arrays; mod strings; use self::strings::unescape; pub use self::{arrays::ArrayMethod, strings::StringMethod}; use super::Expander; use crate::{parser::lexers::ArgumentSplitter, types}; use thiserror::Error; #[derive(Debug, PartialEq, Clone)] pub enum Pattern<'a> { StringPattern(&'a str), Whitespace, } #[derive(Debug)] pub struct MethodArgs<'a, 'b, E: Expander> { args: &'a str,
/// /// Ex: `$join($scalar)` (can't join a scala) or `$unknown(@variable)` (unknown method) #[derive(Debug, Clone, Error)] pub enum MethodError { /// Unknown array method #[error("'{0}' is an unknown array method")] InvalidArrayMethod(String), /// Unknown scalar method #[error("'{0}' is an unknown string method")] InvalidScalarMethod(String), /// A wrong argumeng was given to the method (extra, missing, or wrong type) #[error("{0}: {1}")] WrongArgument(&'static str, &'static str), /// An invalid regex was provided. This is specific to the `matches` method #[error("regex_replace: error in regular expression '{0}': {1}")] InvalidRegex(String, #[source] regex::Error), } impl<'a, 'b, E: 'b + Expander> MethodArgs<'a, 'b, E> { pub fn array(&mut self) -> impl Iterator<Item = types::Str> + '_ { let expand = &mut (*self.expand); ArgumentSplitter::new(self.args) .flat_map(move |x| expand.expand_string(x).unwrap_or_else(|_| types::Args::new())) .map(|s| unescape(&s)) } pub fn join(self, pattern: &str) -> super::Result<types::Str, E::Error> { Ok(unescape(&self.expand.expand_string(self.args)?.join(pattern))) } pub fn new(args: &'a str, expand: &'b mut E) -> MethodArgs<'a, 'b, E> { MethodArgs { args, expand } } }
expand: &'b mut E, } /// Error during method expansion
random_line_split
mod.rs
mod arrays; mod strings; use self::strings::unescape; pub use self::{arrays::ArrayMethod, strings::StringMethod}; use super::Expander; use crate::{parser::lexers::ArgumentSplitter, types}; use thiserror::Error; #[derive(Debug, PartialEq, Clone)] pub enum Pattern<'a> { StringPattern(&'a str), Whitespace, } #[derive(Debug)] pub struct MethodArgs<'a, 'b, E: Expander> { args: &'a str, expand: &'b mut E, } /// Error during method expansion /// /// Ex: `$join($scalar)` (can't join a scala) or `$unknown(@variable)` (unknown method) #[derive(Debug, Clone, Error)] pub enum MethodError { /// Unknown array method #[error("'{0}' is an unknown array method")] InvalidArrayMethod(String), /// Unknown scalar method #[error("'{0}' is an unknown string method")] InvalidScalarMethod(String), /// A wrong argumeng was given to the method (extra, missing, or wrong type) #[error("{0}: {1}")] WrongArgument(&'static str, &'static str), /// An invalid regex was provided. This is specific to the `matches` method #[error("regex_replace: error in regular expression '{0}': {1}")] InvalidRegex(String, #[source] regex::Error), } impl<'a, 'b, E: 'b + Expander> MethodArgs<'a, 'b, E> { pub fn array(&mut self) -> impl Iterator<Item = types::Str> + '_ { let expand = &mut (*self.expand); ArgumentSplitter::new(self.args) .flat_map(move |x| expand.expand_string(x).unwrap_or_else(|_| types::Args::new())) .map(|s| unescape(&s)) } pub fn join(self, pattern: &str) -> super::Result<types::Str, E::Error> { Ok(unescape(&self.expand.expand_string(self.args)?.join(pattern))) } pub fn new(args: &'a str, expand: &'b mut E) -> MethodArgs<'a, 'b, E>
}
{ MethodArgs { args, expand } }
identifier_body
mod.rs
mod arrays; mod strings; use self::strings::unescape; pub use self::{arrays::ArrayMethod, strings::StringMethod}; use super::Expander; use crate::{parser::lexers::ArgumentSplitter, types}; use thiserror::Error; #[derive(Debug, PartialEq, Clone)] pub enum Pattern<'a> { StringPattern(&'a str), Whitespace, } #[derive(Debug)] pub struct MethodArgs<'a, 'b, E: Expander> { args: &'a str, expand: &'b mut E, } /// Error during method expansion /// /// Ex: `$join($scalar)` (can't join a scala) or `$unknown(@variable)` (unknown method) #[derive(Debug, Clone, Error)] pub enum MethodError { /// Unknown array method #[error("'{0}' is an unknown array method")] InvalidArrayMethod(String), /// Unknown scalar method #[error("'{0}' is an unknown string method")] InvalidScalarMethod(String), /// A wrong argumeng was given to the method (extra, missing, or wrong type) #[error("{0}: {1}")] WrongArgument(&'static str, &'static str), /// An invalid regex was provided. This is specific to the `matches` method #[error("regex_replace: error in regular expression '{0}': {1}")] InvalidRegex(String, #[source] regex::Error), } impl<'a, 'b, E: 'b + Expander> MethodArgs<'a, 'b, E> { pub fn array(&mut self) -> impl Iterator<Item = types::Str> + '_ { let expand = &mut (*self.expand); ArgumentSplitter::new(self.args) .flat_map(move |x| expand.expand_string(x).unwrap_or_else(|_| types::Args::new())) .map(|s| unescape(&s)) } pub fn
(self, pattern: &str) -> super::Result<types::Str, E::Error> { Ok(unescape(&self.expand.expand_string(self.args)?.join(pattern))) } pub fn new(args: &'a str, expand: &'b mut E) -> MethodArgs<'a, 'b, E> { MethodArgs { args, expand } } }
join
identifier_name
bitcast_op_test.py
# Copyright 2015 Google Inc. 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. # ============================================================================== """Tests for tf.bitcast.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf class BitcastTest(tf.test.TestCase): def _testBitcast(self, x, datatype, shape):
def testSmaller(self): x = np.random.rand(3, 2) datatype = tf.int8 shape = [3, 2, 8] self._testBitcast(x, datatype, shape) def testLarger(self): x = np.arange(16, dtype=np.int8).reshape([4, 4]) datatype = tf.int32 shape = [4] self._testBitcast(x, datatype, shape) def testSameDtype(self): x = np.random.rand(3, 4) shape = [3, 4] self._testBitcast(x, x.dtype, shape) def testSameSize(self): x = np.random.rand(3, 4) shape = [3, 4] self._testBitcast(x, tf.int64, shape) def testErrors(self): x = np.zeros([1, 1], np.int8) datatype = tf.int32 with self.assertRaisesRegexp(ValueError, "Cannot bitcast due to shape"): tf.bitcast(x, datatype, None) def testEmpty(self): x = np.ones([], np.int32) datatype = tf.int8 shape = [4] self._testBitcast(x, datatype, shape) def testUnknown(self): x = tf.placeholder(tf.float32) datatype = tf.int8 tf.bitcast(x, datatype, None) if __name__ == "__main__": tf.test.main()
with self.test_session(): tf_ans = tf.bitcast(x, datatype) out = tf_ans.eval() buff_after = memoryview(out).tobytes() buff_before = memoryview(x).tobytes() self.assertEqual(buff_before, buff_after) self.assertEqual(tf_ans.get_shape(), shape) self.assertEqual(tf_ans.dtype, datatype)
identifier_body
bitcast_op_test.py
# Copyright 2015 Google Inc. 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. # ============================================================================== """Tests for tf.bitcast.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function
class BitcastTest(tf.test.TestCase): def _testBitcast(self, x, datatype, shape): with self.test_session(): tf_ans = tf.bitcast(x, datatype) out = tf_ans.eval() buff_after = memoryview(out).tobytes() buff_before = memoryview(x).tobytes() self.assertEqual(buff_before, buff_after) self.assertEqual(tf_ans.get_shape(), shape) self.assertEqual(tf_ans.dtype, datatype) def testSmaller(self): x = np.random.rand(3, 2) datatype = tf.int8 shape = [3, 2, 8] self._testBitcast(x, datatype, shape) def testLarger(self): x = np.arange(16, dtype=np.int8).reshape([4, 4]) datatype = tf.int32 shape = [4] self._testBitcast(x, datatype, shape) def testSameDtype(self): x = np.random.rand(3, 4) shape = [3, 4] self._testBitcast(x, x.dtype, shape) def testSameSize(self): x = np.random.rand(3, 4) shape = [3, 4] self._testBitcast(x, tf.int64, shape) def testErrors(self): x = np.zeros([1, 1], np.int8) datatype = tf.int32 with self.assertRaisesRegexp(ValueError, "Cannot bitcast due to shape"): tf.bitcast(x, datatype, None) def testEmpty(self): x = np.ones([], np.int32) datatype = tf.int8 shape = [4] self._testBitcast(x, datatype, shape) def testUnknown(self): x = tf.placeholder(tf.float32) datatype = tf.int8 tf.bitcast(x, datatype, None) if __name__ == "__main__": tf.test.main()
import numpy as np import tensorflow as tf
random_line_split
bitcast_op_test.py
# Copyright 2015 Google Inc. 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. # ============================================================================== """Tests for tf.bitcast.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf class BitcastTest(tf.test.TestCase): def _testBitcast(self, x, datatype, shape): with self.test_session(): tf_ans = tf.bitcast(x, datatype) out = tf_ans.eval() buff_after = memoryview(out).tobytes() buff_before = memoryview(x).tobytes() self.assertEqual(buff_before, buff_after) self.assertEqual(tf_ans.get_shape(), shape) self.assertEqual(tf_ans.dtype, datatype) def testSmaller(self): x = np.random.rand(3, 2) datatype = tf.int8 shape = [3, 2, 8] self._testBitcast(x, datatype, shape) def testLarger(self): x = np.arange(16, dtype=np.int8).reshape([4, 4]) datatype = tf.int32 shape = [4] self._testBitcast(x, datatype, shape) def testSameDtype(self): x = np.random.rand(3, 4) shape = [3, 4] self._testBitcast(x, x.dtype, shape) def testSameSize(self): x = np.random.rand(3, 4) shape = [3, 4] self._testBitcast(x, tf.int64, shape) def testErrors(self): x = np.zeros([1, 1], np.int8) datatype = tf.int32 with self.assertRaisesRegexp(ValueError, "Cannot bitcast due to shape"): tf.bitcast(x, datatype, None) def testEmpty(self): x = np.ones([], np.int32) datatype = tf.int8 shape = [4] self._testBitcast(x, datatype, shape) def testUnknown(self): x = tf.placeholder(tf.float32) datatype = tf.int8 tf.bitcast(x, datatype, None) if __name__ == "__main__":
tf.test.main()
conditional_block
bitcast_op_test.py
# Copyright 2015 Google Inc. 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. # ============================================================================== """Tests for tf.bitcast.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf class BitcastTest(tf.test.TestCase): def
(self, x, datatype, shape): with self.test_session(): tf_ans = tf.bitcast(x, datatype) out = tf_ans.eval() buff_after = memoryview(out).tobytes() buff_before = memoryview(x).tobytes() self.assertEqual(buff_before, buff_after) self.assertEqual(tf_ans.get_shape(), shape) self.assertEqual(tf_ans.dtype, datatype) def testSmaller(self): x = np.random.rand(3, 2) datatype = tf.int8 shape = [3, 2, 8] self._testBitcast(x, datatype, shape) def testLarger(self): x = np.arange(16, dtype=np.int8).reshape([4, 4]) datatype = tf.int32 shape = [4] self._testBitcast(x, datatype, shape) def testSameDtype(self): x = np.random.rand(3, 4) shape = [3, 4] self._testBitcast(x, x.dtype, shape) def testSameSize(self): x = np.random.rand(3, 4) shape = [3, 4] self._testBitcast(x, tf.int64, shape) def testErrors(self): x = np.zeros([1, 1], np.int8) datatype = tf.int32 with self.assertRaisesRegexp(ValueError, "Cannot bitcast due to shape"): tf.bitcast(x, datatype, None) def testEmpty(self): x = np.ones([], np.int32) datatype = tf.int8 shape = [4] self._testBitcast(x, datatype, shape) def testUnknown(self): x = tf.placeholder(tf.float32) datatype = tf.int8 tf.bitcast(x, datatype, None) if __name__ == "__main__": tf.test.main()
_testBitcast
identifier_name