prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>BaseDrawerActivity.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2015 Ngewi Fet <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gnucash.android.ui.common; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.LayoutRes; import android.support.annotation.StringRes; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.uservoice.uservoicesdk.UserVoice; import org.gnucash.android.R; import org.gnucash.android.app.GnuCashApplication; import org.gnucash.android.db.DatabaseSchema; import org.gnucash.android.db.adapter.BooksDbAdapter; import org.gnucash.android.ui.account.AccountsActivity; import org.gnucash.android.ui.passcode.PasscodeLockActivity; import org.gnucash.android.ui.report.ReportsActivity; import org.gnucash.android.ui.settings.PreferenceActivity; import org.gnucash.android.ui.transaction.ScheduledActionsActivity; import butterknife.BindView; import butterknife.ButterKnife; /** * Base activity implementing the navigation drawer, to be extended by all activities requiring one. * <p> * Each activity inheriting from this class has an indeterminate progress bar at the top, * (above the action bar) which can be used to display busy operations. See {@link #getProgressBar()} * </p> * * <p>Sub-classes should simply provide their layout using {@link #getContentView()} and then annotate * any variables they wish to use with {@link ButterKnife#bind(Activity)} annotations. The view * binding will be done in this base abstract class.<br> * The activity layout of the subclass is expected to contain {@code DrawerLayout} and * a {@code NavigationView}.<br> * Sub-class should also consider using the {@code toolbar.xml} or {@code toolbar_with_spinner.xml} * for the action bar in their XML layout. Otherwise provide another which contains widgets for the * toolbar and progress indicator with the IDs {@code R.id.toolbar} and {@code R.id.progress_indicator} respectively. * </p> * @author Ngewi Fet <[email protected]> */ public abstract class BaseDrawerActivity extends PasscodeLockActivity implements PopupMenu.OnMenuItemClickListener { public static final int ID_MANAGE_BOOKS = 0xB00C; @BindView(R.id.drawer_layout) DrawerLayout mDrawerLayout; @BindView(R.id.nav_view) NavigationView mNavigationView; @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.toolbar_progress) ProgressBar mToolbarProgress; protected TextView mBookNameTextView; protected ActionBarDrawerToggle mDrawerToggle; public static final int REQUEST_OPEN_DOCUMENT = 0x20;<|fim▁hole|> @Override public boolean onNavigationItemSelected(MenuItem menuItem) { onDrawerMenuItemClicked(menuItem.getItemId()); return true; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getContentView()); //if a parameter was passed to open an account within a specific book, then switch String bookUID = getIntent().getStringExtra(UxArgument.BOOK_UID); if (bookUID != null && !bookUID.equals(BooksDbAdapter.getInstance().getActiveBookUID())){ GnuCashApplication.activateBook(bookUID); } ButterKnife.bind(this); setSupportActionBar(mToolbar); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null){ actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(getTitleRes()); } mToolbarProgress.getIndeterminateDrawable().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN); View headerView = mNavigationView.getHeaderView(0); headerView.findViewById(R.id.drawer_title).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickAppTitle(v); } }); mBookNameTextView = (TextView) headerView.findViewById(R.id.book_name); mBookNameTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickBook(v); } }); updateActiveBookName(); setUpNavigationDrawer(); } @Override protected void onResume() { super.onResume(); updateActiveBookName(); } /** * Return the layout to inflate for this activity * @return Layout resource identifier */ public abstract @LayoutRes int getContentView(); /** * Return the title for this activity. * This will be displayed in the action bar * @return String resource identifier */ public abstract @StringRes int getTitleRes(); /** * Returns the progress bar for the activity. * <p>This progress bar is displayed above the toolbar and should be used to show busy status * for long operations.<br/> * The progress bar visibility is set to {@link View#GONE} by default. Make visible to use </p> * @return Indeterminate progress bar. */ public ProgressBar getProgressBar(){ return mToolbarProgress; } /** * Sets up the navigation drawer for this activity. */ private void setUpNavigationDrawer() { mNavigationView.setNavigationItemSelectedListener(new DrawerItemClickListener()); mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } }; mDrawerLayout.setDrawerListener(mDrawerToggle); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home){ if (!mDrawerLayout.isDrawerOpen(mNavigationView)) mDrawerLayout.openDrawer(mNavigationView); else mDrawerLayout.closeDrawer(mNavigationView); return true; } return super.onOptionsItemSelected(item); } /** * Update the display name of the currently active book */ protected void updateActiveBookName(){ mBookNameTextView.setText(BooksDbAdapter.getInstance().getActiveBookDisplayName()); } /** * Handler for the navigation drawer items * */ protected void onDrawerMenuItemClicked(int itemId) { switch (itemId){ case R.id.nav_item_open: { //Open... files if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ //use the storage access framework Intent openDocument = new Intent(Intent.ACTION_OPEN_DOCUMENT); openDocument.addCategory(Intent.CATEGORY_OPENABLE); openDocument.setType("*/*"); startActivityForResult(openDocument, REQUEST_OPEN_DOCUMENT); } else { AccountsActivity.startXmlFileChooser(this); } } break; case R.id.nav_item_favorites: { //favorite accounts Intent intent = new Intent(this, AccountsActivity.class); intent.putExtra(AccountsActivity.EXTRA_TAB_INDEX, AccountsActivity.INDEX_FAVORITE_ACCOUNTS_FRAGMENT); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); } break; case R.id.nav_item_reports: { Intent intent = new Intent(this, ReportsActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); } break; /* //todo: Re-enable this when Budget UI is complete case R.id.nav_item_budgets: startActivity(new Intent(this, BudgetsActivity.class)); break; */ case R.id.nav_item_scheduled_actions: { //show scheduled transactions Intent intent = new Intent(this, ScheduledActionsActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); } break; case R.id.nav_item_export: AccountsActivity.openExportFragment(this); break; case R.id.nav_item_settings: //Settings activity startActivity(new Intent(this, PreferenceActivity.class)); break; case R.id.nav_item_help: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.edit().putBoolean(UxArgument.SKIP_PASSCODE_SCREEN, true).apply(); UserVoice.launchUserVoice(this); break; } mDrawerLayout.closeDrawer(mNavigationView); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_CANCELED) { super.onActivityResult(requestCode, resultCode, data); return; } switch (requestCode) { case AccountsActivity.REQUEST_PICK_ACCOUNTS_FILE: AccountsActivity.importXmlFileFromIntent(this, data, null); break; case BaseDrawerActivity.REQUEST_OPEN_DOCUMENT: //this uses the Storage Access Framework final int takeFlags = data.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); AccountsActivity.importXmlFileFromIntent(this, data, null); getContentResolver().takePersistableUriPermission(data.getData(), takeFlags); break; default: super.onActivityResult(requestCode, resultCode, data); break; } } @Override public boolean onMenuItemClick(MenuItem item) { long id = item.getItemId(); if (id == ID_MANAGE_BOOKS){ Intent intent = new Intent(this, PreferenceActivity.class); intent.setAction(PreferenceActivity.ACTION_MANAGE_BOOKS); startActivity(intent); mDrawerLayout.closeDrawer(mNavigationView); return true; } BooksDbAdapter booksDbAdapter = BooksDbAdapter.getInstance(); String bookUID = booksDbAdapter.getUID(id); if (!bookUID.equals(booksDbAdapter.getActiveBookUID())){ GnuCashApplication.loadBook(bookUID); finish(); } AccountsActivity.start(GnuCashApplication.getAppContext()); return true; } public void onClickAppTitle(View view){ mDrawerLayout.closeDrawer(mNavigationView); AccountsActivity.start(this); } public void onClickBook(View view){ PopupMenu popup = new PopupMenu(this, view); popup.setOnMenuItemClickListener(this); Menu menu = popup.getMenu(); int maxRecent = 0; Cursor cursor = BooksDbAdapter.getInstance().fetchAllRecords(null, null, DatabaseSchema.BookEntry.COLUMN_MODIFIED_AT + " DESC"); while (cursor.moveToNext() && maxRecent++ < 5) { long id = cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseSchema.BookEntry._ID)); String name = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseSchema.BookEntry.COLUMN_DISPLAY_NAME)); menu.add(0, (int)id, maxRecent, name); } menu.add(0, ID_MANAGE_BOOKS, maxRecent, R.string.menu_manage_books); popup.show(); } }<|fim▁end|>
private class DrawerItemClickListener implements NavigationView.OnNavigationItemSelectedListener {
<|file_name|>IConnectorAction.java<|end_file_name|><|fim▁begin|>package org.mo.jfa.face.database.connector; import org.mo.web.core.container.AContainer; import org.mo.web.core.webform.IFormPage; import org.mo.web.protocol.context.IWebContext; public interface IConnectorAction { String catalog(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String list(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String sort(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String insert(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String update(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String delete(IWebContext context,<|fim▁hole|><|fim▁end|>
@AContainer(name = IFormPage.Page) FConnectorPage page); }
<|file_name|>content-paste.js<|end_file_name|><|fim▁begin|>'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); <|fim▁hole|> var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ContentContentPaste = function ContentContentPaste(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M19 2h-4.18C14.4.84 13.3 0 12 0c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm7 18H5V4h2v3h10V4h2v16z' }) ); }; ContentContentPaste = (0, _pure2.default)(ContentContentPaste); ContentContentPaste.displayName = 'ContentContentPaste'; ContentContentPaste.muiName = 'SvgIcon'; exports.default = ContentContentPaste;<|fim▁end|>
var _SvgIcon = require('../../SvgIcon');
<|file_name|>blank_line_after_class_required.py<|end_file_name|><|fim▁begin|># pylint:disable=missing-docstring,invalid-name,too-few-public-methods,old-style-class class SomeClass: # [blank-line-after-class-required] def __init__(self):<|fim▁hole|><|fim▁end|>
pass
<|file_name|>elf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from elftools.elf.elffile import ELFFile from elftools.common.exceptions import ELFError from elftools.elf.segments import NoteSegment class ReadELF(object): def __init__(self, file): self.elffile = ELFFile(file)<|fim▁hole|> for segment in self.elffile.iter_segments(): if isinstance(segment, NoteSegment): for note in segment.iter_notes(): print note def main(): if(len(sys.argv) < 2): print "Missing argument" sys.exit(1) with open(sys.argv[1], 'rb') as file: try: readelf = ReadELF(file) readelf.get_build() except ELFError as err: sys.stderr.write('ELF error: %s\n' % err) sys.exit(1) if __name__ == '__main__': main()<|fim▁end|>
def get_build(self):
<|file_name|>sfp_template.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # ------------------------------------------------------------------------------- # Name: sfp_XXX # Purpose: Description of the plug-in. # # Author: Name and e-mail address # # Created: Date # Copyright: (c) Name # Licence: GPL # ------------------------------------------------------------------------------- from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent class sfp_XXX(SpiderFootPlugin): """Name:Description""" # Default options opts = {} # Option descriptions optdescs = { # For each option in opts you should have a key/value pair here # describing it. It will end up in the UI to explain the option # to the end-user. } # Be sure to completely clear any class variables in setup() # or you run the risk of data persisting between scan runs. # Target results = dict() def setup(self, sfc, userOpts=dict()): self.sf = sfc self.results = dict() # Clear / reset any other class member variables here # or you risk them persisting between threads. for opt in userOpts.keys(): self.opts[opt] = userOpts[opt] # What events is this module interested in for input # * = be notified about all events. def watchedEvents(self): return ["*"] # What events this module produces # This is to support the end user in selecting modules based on events # produced. def producedEvents(self): return None # Handle events sent to this module def handleEvent(self, event): eventName = event.eventType srcModuleName = event.module eventData = event.data # If you are processing TARGET_WEB_CONTENT from sfp_spider, this is how you # would get the source of that raw data (e.g. a URL.) eventSource = event.sourceEvent.data self.sf.debug("Received event, " + eventName + ", from " + srcModuleName) # DO SOMETHING HERE # Notify other modules of what you've found evt = SpiderFootEvent("EVENT_CODE_HERE", "data here", self.__name__, event.sourceEvent) self.notifyListeners(evt) return None <|fim▁hole|> # politely asked by the controller to stop your activities (user abort.) # End of sfp_XXX class<|fim▁end|>
# If you intend for this module to act on its own (e.g. not solely rely # on events from other modules, then you need to have a start() method # and within that method call self.checkForStop() to see if you've been
<|file_name|>angular-leaflet-directive.js<|end_file_name|><|fim▁begin|>var leafletDirective = angular.module("leaflet-directive", []); leafletDirective.directive('leaflet', [ '$http', '$log', '$parse', '$rootScope', function ($http, $log, $parse, $rootScope) { var defaults = { maxZoom: 14, minZoom: 1, doubleClickZoom: true, tileLayer: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', tileLayerOptions: { attribution: 'Tiles &copy; Open Street Maps' }, icon: { url: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-icon.png', retinaUrl: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/[email protected]', size: [25, 41], anchor: [12, 40], popup: [0, -40], shadow: { url: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-shadow.png', retinaUrl: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-shadow.png', size: [41, 41], anchor: [12, 40] } }, path: { weight: 10, opacity: 1, color: '#0000ff' } }; var str_inspect_hint = 'Add testing="testing" to <leaflet> tag to inspect this object'; return { restrict: "E", replace: true, transclude: true, scope: { center: '=center',<|fim▁hole|> marker: '=marker', markers: '=markers', defaults: '=defaults', paths: '=paths', tiles: '=tiles', events: '=events' }, template: '<div class="angular-leaflet-map"></div>', link: function ($scope, element, attrs /*, ctrl */) { var centerModel = { lat:$parse("center.lat"), lng:$parse("center.lng"), zoom:$parse("center.zoom") }; if (attrs.width) { element.css('width', attrs.width); } if (attrs.height) { element.css('height', attrs.height); } $scope.leaflet = {}; $scope.leaflet.maxZoom = !!(attrs.defaults && $scope.defaults && $scope.defaults.maxZoom) ? parseInt($scope.defaults.maxZoom, 10) : defaults.maxZoom; $scope.leaflet.minZoom = !!(attrs.defaults && $scope.defaults && $scope.defaults.minZoom) ? parseInt($scope.defaults.minZoom, 10) : defaults.minZoom; $scope.leaflet.doubleClickZoom = !!(attrs.defaults && $scope.defaults && (typeof($scope.defaults.doubleClickZoom) == "boolean") ) ? $scope.defaults.doubleClickZoom : defaults.doubleClickZoom; var map = new L.Map(element[0], { maxZoom: $scope.leaflet.maxZoom, minZoom: $scope.leaflet.minZoom, doubleClickZoom: $scope.leaflet.doubleClickZoom }); map.setView([0, 0], 1); $scope.leaflet.tileLayer = !!(attrs.defaults && $scope.defaults && $scope.defaults.tileLayer) ? $scope.defaults.tileLayer : defaults.tileLayer; $scope.leaflet.map = !!attrs.testing ? map : str_inspect_hint; setupTiles(); setupCenter(); setupMaxBounds(); setupBounds(); setupMainMaerker(); setupMarkers(); setupPaths(); setupEvents(); // use of leafletDirectiveSetMap event is not encouraged. only use // it when there is no easy way to bind data to the directive $scope.$on('leafletDirectiveSetMap', function(event, message) { var meth = message.shift(); map[meth].apply(map, message); }); $scope.safeApply = function(fn) { var phase = this.$root.$$phase; if (phase == '$apply' || phase == '$digest') { $scope.$eval(fn); } else { $scope.$apply(fn); } }; /* * Event setup watches for callbacks set in the parent scope * * $scope.events = { * dblclick: function(){ * // doThis() * }, * click: function(){ * // doThat() * } * } * */ function setupEvents(){ if ( typeof($scope.events) != 'object'){ return false; }else{ for (var bind_to in $scope.events){ map.on(bind_to,$scope.events[bind_to]); } } } function setupTiles(){ // TODO build custom object for tiles, actually only the tile string if ($scope.defaults && $scope.defaults.tileLayerOptions) { for (var key in $scope.defaults.tileLayerOptions) { defaults.tileLayerOptions[key] = $scope.defaults.tileLayerOptions[key]; } } if ($scope.tiles) { if ($scope.tiles.tileLayer) { $scope.leaflet.tileLayer = $scope.tiles.tileLayer; } if ($scope.tiles.tileLayerOptions.attribution) { defaults.tileLayerOptions.attribution = $scope.tiles.tileLayerOptions.attribution; } } var tileLayerObj = L.tileLayer( $scope.leaflet.tileLayer, defaults.tileLayerOptions); tileLayerObj.addTo(map); $scope.leaflet.tileLayerObj = !!attrs.testing ? tileLayerObj : str_inspect_hint; } function setupMaxBounds() { if (!$scope.maxBounds) { return; } if ($scope.maxBounds.southWest && $scope.maxBounds.southWest.lat && $scope.maxBounds.southWest.lng && $scope.maxBounds.northEast && $scope.maxBounds.northEast.lat && $scope.maxBounds.northEast.lng) { map.setMaxBounds( new L.LatLngBounds( new L.LatLng($scope.maxBounds.southWest.lat, $scope.maxBounds.southWest.lng), new L.LatLng($scope.maxBounds.northEast.lat, $scope.maxBounds.northEast.lng) ) ); $scope.$watch("maxBounds", function (maxBounds) { if (maxBounds.southWest && maxBounds.northEast && maxBounds.southWest.lat && maxBounds.southWest.lng && maxBounds.northEast.lat && maxBounds.northEast.lng) { map.setMaxBounds( new L.LatLngBounds( new L.LatLng(maxBounds.southWest.lat, maxBounds.southWest.lng), new L.LatLng(maxBounds.northEast.lat, maxBounds.northEast.lng) ) ); } }); } } function tryFitBounds(bounds) { if (bounds) { var southWest = bounds.southWest; var northEast = bounds.northEast; if (southWest && northEast && southWest.lat && southWest.lng && northEast.lat && northEast.lng) { var sw_latlng = new L.LatLng(southWest.lat, southWest.lng); var ne_latlng = new L.LatLng(northEast.lat, northEast.lng); map.fitBounds(new L.LatLngBounds(sw_latlng, ne_latlng)); } } } function setupBounds() { if (!$scope.bounds) { return; } $scope.$watch('bounds', function (new_bounds) { tryFitBounds(new_bounds); }); } function setupCenter() { $scope.$watch("center", function (center) { if (!center) { $log.warn("[AngularJS - Leaflet] 'center' is undefined in the current scope, did you forget to initialize it?"); return; } if (center.lat && center.lng && center.zoom) { map.setView([center.lat, center.lng], center.zoom); } else if (center.autoDiscover === true) { map.locate({ setView: true, maxZoom: $scope.leaflet.maxZoom }); } }, true); map.on("dragend", function (/* event */) { $scope.safeApply(function (scope) { centerModel.lat.assign(scope, map.getCenter().lat); centerModel.lng.assign(scope, map.getCenter().lng); }); }); map.on("zoomend", function (/* event */) { if(angular.isUndefined($scope.center)){ $log.warn("[AngularJS - Leaflet] 'center' is undefined in the current scope, did you forget to initialize it?"); } if (angular.isUndefined($scope.center) || $scope.center.zoom !== map.getZoom()) { $scope.safeApply(function (s) { centerModel.zoom.assign(s, map.getZoom()); centerModel.lat.assign(s, map.getCenter().lat); centerModel.lng.assign(s, map.getCenter().lng); }); } }); } function setupMainMaerker() { var main_marker; if (!$scope.marker) { return; } main_marker = createMarker('marker', $scope.marker, map); $scope.leaflet.marker = !!attrs.testing ? main_marker : str_inspect_hint; main_marker.on('click', function(e) { $rootScope.$broadcast('leafletDirectiveMainMarkerClick'); }); } function setupMarkers() { var markers = {}; $scope.leaflet.markers = !!attrs.testing ? markers : str_inspect_hint; if (!$scope.markers) { return; } function genMultiMarkersClickCallback(m_name) { return function(e) { $rootScope.$broadcast('leafletDirectiveMarkersClick', m_name); }; } for (var name in $scope.markers) { markers[name] = createMarker( 'markers.'+name, $scope.markers[name], map); markers[name].on('click', genMultiMarkersClickCallback(name)); } $scope.$watch('markers', function(newMarkers) { // Delete markers from the array for (var name in markers) { if (newMarkers[name] === undefined) { delete markers[name]; } } // add new markers for (var new_name in newMarkers) { if (markers[new_name] === undefined) { markers[new_name] = createMarker( 'markers.'+new_name, newMarkers[new_name], map); markers[new_name].on('click', genMultiMarkersClickCallback(new_name)); } } }, true); } function createMarker(scope_watch_name, marker_data, map) { var marker = buildMarker(marker_data); map.addLayer(marker); if (marker_data.focus === true) { marker.openPopup(); } marker.on("dragend", function () { $scope.safeApply(function (scope) { marker_data.lat = marker.getLatLng().lat; marker_data.lng = marker.getLatLng().lng; }); if (marker_data.message) { marker.openPopup(); } }); var clearWatch = $scope.$watch(scope_watch_name, function (data, old_data) { if (!data) { map.removeLayer(marker); clearWatch(); return; } if (old_data) { if (data.draggable !== undefined && data.draggable !== old_data.draggable) { if (data.draggable === true) { marker.dragging.enable(); } else { marker.dragging.disable(); } } if (data.focus !== undefined && data.focus !== old_data.focus) { if (data.focus === true) { marker.openPopup(); } else { marker.closePopup(); } } if (data.message !== undefined && data.message !== old_data.message) { marker.bindPopup(data); } if (data.lat !== old_data.lat || data.lng !== old_data.lng) { marker.setLatLng(new L.LatLng(data.lat, data.lng)); } if (data.icon && data.icon !== old_data.icon) { marker.setIcon(data.icon); } } }, true); return marker; } function buildMarker(data) { var micon = null; if (data.icon) { micon = data.icon; } else { micon = buildIcon(); } var marker = new L.marker(data, { icon: micon, draggable: data.draggable ? true : false } ); if (data.message) { marker.bindPopup(data.message); } return marker; } function buildIcon() { return L.icon({ iconUrl: defaults.icon.url, iconRetinaUrl: defaults.icon.retinaUrl, iconSize: defaults.icon.size, iconAnchor: defaults.icon.anchor, popupAnchor: defaults.icon.popup, shadowUrl: defaults.icon.shadow.url, shadowRetinaUrl: defaults.icon.shadow.retinaUrl, shadowSize: defaults.icon.shadow.size, shadowAnchor: defaults.icon.shadow.anchor }); } function setupPaths() { var paths = {}; $scope.leaflet.paths = !!attrs.testing ? paths : str_inspect_hint; if (!$scope.paths) { return; } $log.warn("[AngularJS - Leaflet] Creating polylines and adding them to the map will break the directive's scope's inspection in AngularJS Batarang"); for (var name in $scope.paths) { paths[name] = createPath(name, $scope.paths[name], map); } $scope.$watch("paths", function (newPaths) { for (var new_name in newPaths) { if (paths[new_name] === undefined) { paths[new_name] = createPath(new_name, newPaths[new_name], map); } } // Delete paths from the array for (var name in paths) { if (newPaths[name] === undefined) { delete paths[name]; } } }, true); } function createPath(name, scopePath, map) { var polyline = new L.Polyline([], { weight: defaults.path.weight, color: defaults.path.color, opacity: defaults.path.opacity }); if (scopePath.latlngs !== undefined) { var latlngs = convertToLeafletLatLngs(scopePath.latlngs); polyline.setLatLngs(latlngs); } if (scopePath.weight !== undefined) { polyline.setStyle({ weight: scopePath.weight }); } if (scopePath.color !== undefined) { polyline.setStyle({ color: scopePath.color }); } if (scopePath.opacity !== undefined) { polyline.setStyle({ opacity: scopePath.opacity }); } map.addLayer(polyline); var clearWatch = $scope.$watch('paths.' + name, function (data, oldData) { if (!data) { map.removeLayer(polyline); clearWatch(); return; } if (oldData) { if (data.latlngs !== undefined && data.latlngs !== oldData.latlngs) { var latlngs = convertToLeafletLatLngs(data.latlngs); polyline.setLatLngs(latlngs); } if (data.weight !== undefined && data.weight !== oldData.weight) { polyline.setStyle({ weight: data.weight }); } if (data.color !== undefined && data.color !== oldData.color) { polyline.setStyle({ color: data.color }); } if (data.opacity !== undefined && data.opacity !== oldData.opacity) { polyline.setStyle({ opacity: data.opacity }); } } }, true); return polyline; } function convertToLeafletLatLngs(latlngs) { var leafletLatLngs = latlngs.filter(function (latlng) { return !!latlng.lat && !!latlng.lng; }).map(function (latlng) { return new L.LatLng(latlng.lat, latlng.lng); }); return leafletLatLngs; } } }; }]);<|fim▁end|>
maxBounds: '=maxbounds', bounds: '=bounds',
<|file_name|>websiteParser.py<|end_file_name|><|fim▁begin|>from IPython.display import HTML from bs4 import BeautifulSoup import urllib f = open('chars.txt', 'w') r = urllib.urlopen('http://www.eventhubs.com/tiers/ssb4/').read() soup = BeautifulSoup(r, "lxml") characters = soup.find_all("td", class_="tierstdnorm") count = 1 tierCharList=[] for element in characters: if count==1: tier = element.get_text() elif count==2: character = element.get_text() tierChar = tier + "," + character<|fim▁hole|> tier = element.get_text() elif count%12==2: character = element.get_text() tierChar = tier + "," + character tierCharList.append(tierChar) count+=1 tierCharList.remove(tierCharList[len(tierCharList)-1]) for x in range(0,len(tierCharList)): f.write(tierCharList[x]) f.write("\n")<|fim▁end|>
tierCharList.append(tierChar) elif count%12==1:
<|file_name|>slick.js<|end_file_name|><|fim▁begin|>/* _ _ _ _ ___| (_) ___| | __ (_)___ / __| | |/ __| |/ / | / __| \__ \ | | (__| < _ | \__ \ |___/_|_|\___|_|\_(_)/ |___/ |__/ Version: 1.5.0 Author: Ken Wheeler Website: http://kenwheeler.github.io Docs: http://kenwheeler.github.io/slick Repo: http://github.com/kenwheeler/slick Issues: http://github.com/kenwheeler/slick/issues */ /* global window, document, define, jQuery, setInterval, clearInterval */ (function(factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof exports !== 'undefined') { module.exports = factory(require('jquery')); } else { factory(jQuery); } }(function($) { 'use strict'; var Slick = window.Slick || {}; Slick = (function() { var instanceUid = 0; function Slick(element, settings) { var _ = this, dataSettings, responsiveSettings, breakpoint; _.defaults = { accessibility: true, adaptiveHeight: false, appendArrows: $(element), appendDots: $(element), arrows: true, asNavFor: null, prevArrow: '<button type="button" data-role="none" class="carousel-control left" aria-label="previous"></button>', nextArrow: '<button type="button" data-role="none" class="carousel-control right" aria-label="next"></button>', autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', //customPaging: function(slider, i) { // return '<button type="button" data-role="none">' + (i + 1) + '</button>'; //}, customPaging: function(slider, i) { return '<button type="button" data-role="none"></button>'; }, dots: true, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, infinite: true, initialSlide: 0, lazyLoad: 'ondemand', mobileFirst: false, pauseOnHover: true, pauseOnDotsHover: false, respondTo: 'window', responsive: null, rows: 1, rtl: false, slide: '', slidesPerRow: 1, slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, useCSS: true, variableWidth: false, vertical: false, verticalSwiping: false, waitForAnimate: true }; _.initials = { animating: false, dragging: false, autoPlayTimer: null, currentDirection: 0, currentLeft: null, currentSlide: 0, direction: 1, $dots: null, listWidth: null, listHeight: null, loadIndex: 0, $nextArrow: null, $prevArrow: null, slideCount: null, slideWidth: null, $slideTrack: null, $slides: null, sliding: false, slideOffset: 0, swipeLeft: null, $list: null, touchObject: {}, transformsEnabled: false }; $.extend(_, _.initials); _.activeBreakpoint = null; _.animType = null; _.animProp = null; _.breakpoints = []; _.breakpointSettings = []; _.cssTransitions = false; _.hidden = 'hidden'; _.paused = false; _.positionProp = null; _.respondTo = null; _.rowCount = 1; _.shouldClick = true; _.$slider = $(element); _.$slidesCache = null; _.transformType = null; _.transitionType = null; _.visibilityChange = 'visibilitychange'; _.windowWidth = 0; _.windowTimer = null; dataSettings = $(element).data('slick') || {}; _.options = $.extend({}, _.defaults, dataSettings, settings); _.currentSlide = _.options.initialSlide; _.originalSettings = _.options; responsiveSettings = _.options.responsive || null; if (responsiveSettings && responsiveSettings.length > -1) { _.respondTo = _.options.respondTo || 'window'; for (breakpoint in responsiveSettings) { if (responsiveSettings.hasOwnProperty(breakpoint)) { _.breakpoints.push(responsiveSettings[ breakpoint].breakpoint); _.breakpointSettings[responsiveSettings[ breakpoint].breakpoint] = responsiveSettings[breakpoint].settings; } } _.breakpoints.sort(function(a, b) { if (_.options.mobileFirst === true) { return a - b; } else { return b - a; } }); } if (typeof document.mozHidden !== 'undefined') { _.hidden = 'mozHidden'; _.visibilityChange = 'mozvisibilitychange'; } else if (typeof document.msHidden !== 'undefined') { _.hidden = 'msHidden'; _.visibilityChange = 'msvisibilitychange'; } else if (typeof document.webkitHidden !== 'undefined') { _.hidden = 'webkitHidden'; _.visibilityChange = 'webkitvisibilitychange'; } _.autoPlay = $.proxy(_.autoPlay, _); _.autoPlayClear = $.proxy(_.autoPlayClear, _); _.changeSlide = $.proxy(_.changeSlide, _); _.clickHandler = $.proxy(_.clickHandler, _); _.selectHandler = $.proxy(_.selectHandler, _); _.setPosition = $.proxy(_.setPosition, _); _.swipeHandler = $.proxy(_.swipeHandler, _); _.dragHandler = $.proxy(_.dragHandler, _); _.keyHandler = $.proxy(_.keyHandler, _); _.autoPlayIterator = $.proxy(_.autoPlayIterator, _); _.instanceUid = instanceUid++; // A simple way to check for HTML strings // Strict HTML recognition (must start with <) // Extracted from jQuery v1.11 source _.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/; _.init(); _.checkResponsive(true); } return Slick; }()); Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) { var _ = this; if (typeof(index) === 'boolean') { addBefore = index; index = null; } else if (index < 0 || (index >= _.slideCount)) { return false; } _.unload(); if (typeof(index) === 'number') { if (index === 0 && _.$slides.length === 0) { $(markup).appendTo(_.$slideTrack); } else if (addBefore) { $(markup).insertBefore(_.$slides.eq(index)); } else { $(markup).insertAfter(_.$slides.eq(index)); } } else { if (addBefore === true) { $(markup).prependTo(_.$slideTrack); } else { $(markup).appendTo(_.$slideTrack); } } _.$slides = _.$slideTrack.children(this.options.slide); _.$slideTrack.children(this.options.slide).detach(); _.$slideTrack.append(_.$slides); _.$slides.each(function(index, element) { $(element).attr('data-slick-index', index); }); _.$slidesCache = _.$slides; _.reinit(); }; Slick.prototype.animateHeight = function() { var _ = this; if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) { var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true); _.$list.animate({ height: targetHeight }, _.options.speed); } }; Slick.prototype.animateSlide = function(targetLeft, callback) { var animProps = {}, _ = this; _.animateHeight(); if (_.options.rtl === true && _.options.vertical === false) { targetLeft = -targetLeft; } if (_.transformsEnabled === false) { if (_.options.vertical === false) { _.$slideTrack.animate({ left: targetLeft }, _.options.speed, _.options.easing, callback); } else { _.$slideTrack.animate({ top: targetLeft }, _.options.speed, _.options.easing, callback); } } else { if (_.cssTransitions === false) { if (_.options.rtl === true) { _.currentLeft = -(_.currentLeft); } $({ animStart: _.currentLeft }).animate({ animStart: targetLeft }, { duration: _.options.speed, easing: _.options.easing, step: function(now) { now = Math.ceil(now); if (_.options.vertical === false) { animProps[_.animType] = 'translate(' + now + 'px, 0px)'; _.$slideTrack.css(animProps); } else { animProps[_.animType] = 'translate(0px,' + now + 'px)'; _.$slideTrack.css(animProps); } }, complete: function() { if (callback) { callback.call(); } } }); } else { _.applyTransition(); targetLeft = Math.ceil(targetLeft); if (_.options.vertical === false) { animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)'; } else { animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)'; } _.$slideTrack.css(animProps); if (callback) { setTimeout(function() { _.disableTransition(); callback.call(); }, _.options.speed); } } } }; Slick.prototype.asNavFor = function(index) { var _ = this, asNavFor = _.options.asNavFor !== null ? $(_.options.asNavFor).slick('getSlick') : null; if (asNavFor !== null) asNavFor.slideHandler(index, true); }; Slick.prototype.applyTransition = function(slide) { var _ = this, transition = {}; if (_.options.fade === false) { transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase; } else { transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase; } if (_.options.fade === false) { _.$slideTrack.css(transition); } else { _.$slides.eq(slide).css(transition); } }; Slick.prototype.autoPlay = function() { var _ = this; if (_.autoPlayTimer) { clearInterval(_.autoPlayTimer); } if (_.slideCount > _.options.slidesToShow && _.paused !== true) { _.autoPlayTimer = setInterval(_.autoPlayIterator, _.options.autoplaySpeed); } }; Slick.prototype.autoPlayClear = function() { var _ = this; if (_.autoPlayTimer) { clearInterval(_.autoPlayTimer); } }; Slick.prototype.autoPlayIterator = function() { var _ = this; if (_.options.infinite === false) { if (_.direction === 1) { if ((_.currentSlide + 1) === _.slideCount - 1) { _.direction = 0; } _.slideHandler(_.currentSlide + _.options.slidesToScroll); } else { if ((_.currentSlide - 1 === 0)) { _.direction = 1; } _.slideHandler(_.currentSlide - _.options.slidesToScroll); } } else { _.slideHandler(_.currentSlide + _.options.slidesToScroll); } }; Slick.prototype.buildArrows = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow = $(_.options.prevArrow); _.$nextArrow = $(_.options.nextArrow); if (_.htmlExpr.test(_.options.prevArrow)) { _.$prevArrow.appendTo(_.options.appendArrows); } if (_.htmlExpr.test(_.options.nextArrow)) { _.$nextArrow.appendTo(_.options.appendArrows); } if (_.options.infinite !== true) { _.$prevArrow.addClass('slick-disabled'); } } }; Slick.prototype.buildDots = function() { var _ = this, i, dotString; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { dotString = '<ul class="' + _.options.dotsClass + '">'; for (i = 0; i <= _.getDotCount(); i += 1) { dotString += '<li>' + _.options.customPaging.call(this, _, i) + '</li>'; } dotString += '</ul>'; _.$dots = $(dotString).appendTo( _.options.appendDots); _.$dots.find('li').first().addClass('slick-active').attr('aria-hidden', 'false'); } }; Slick.prototype.buildOut = function() { var _ = this; _.$slides = _.$slider.children( ':not(.slick-cloned)').addClass( 'slick-slide'); _.slideCount = _.$slides.length; _.$slides.each(function(index, element) { $(element).attr('data-slick-index', index); }); _.$slidesCache = _.$slides; _.$slider.addClass('slick-slider'); _.$slideTrack = (_.slideCount === 0) ? $('<div class="slick-track"/>').appendTo(_.$slider) : _.$slides.wrapAll('<div class="slick-track"/>').parent(); _.$list = _.$slideTrack.wrap( '<div aria-live="polite" class="slick-list"/>').parent(); _.$slideTrack.css('opacity', 0); if (_.options.centerMode === true || _.options.swipeToSlide === true) { _.options.slidesToScroll = 1; } $('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading'); _.setupInfinite(); _.buildArrows(); _.buildDots(); _.updateDots(); if (_.options.accessibility === true) { _.$list.prop('tabIndex', 0); } _.setSlideClasses(typeof this.currentSlide === 'number' ? this.currentSlide : 0); if (_.options.draggable === true) { _.$list.addClass('draggable'); } }; Slick.prototype.buildRows = function() { var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection; newSlides = document.createDocumentFragment(); originalSlides = _.$slider.children(); if(_.options.rows > 1) { slidesPerSection = _.options.slidesPerRow * _.options.rows; numOfSlides = Math.ceil( originalSlides.length / slidesPerSection ); for(a = 0; a < numOfSlides; a++){ var slide = document.createElement('div'); for(b = 0; b < _.options.rows; b++) { var row = document.createElement('div'); for(c = 0; c < _.options.slidesPerRow; c++) { var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c)); if (originalSlides.get(target)) { row.appendChild(originalSlides.get(target)); } } slide.appendChild(row); } newSlides.appendChild(slide); } _.$slider.html(newSlides); _.$slider.children().children().children() .width((100 / _.options.slidesPerRow) + "%") .css({'display': 'inline-block'}); } }; Slick.prototype.checkResponsive = function(initial) { var _ = this, breakpoint, targetBreakpoint, respondToWidth; var sliderWidth = _.$slider.width(); var windowWidth = window.innerWidth || $(window).width(); if (_.respondTo === 'window') { respondToWidth = windowWidth; } else if (_.respondTo === 'slider') { respondToWidth = sliderWidth; } else if (_.respondTo === 'min') { respondToWidth = Math.min(windowWidth, sliderWidth); } if (_.originalSettings.responsive && _.originalSettings .responsive.length > -1 && _.originalSettings.responsive !== null) { targetBreakpoint = null; for (breakpoint in _.breakpoints) { if (_.breakpoints.hasOwnProperty(breakpoint)) { if (_.originalSettings.mobileFirst === false) { if (respondToWidth < _.breakpoints[breakpoint]) { targetBreakpoint = _.breakpoints[breakpoint]; } } else { if (respondToWidth > _.breakpoints[breakpoint]) { targetBreakpoint = _.breakpoints[breakpoint]; } } } } if (targetBreakpoint !== null) { if (_.activeBreakpoint !== null) { if (targetBreakpoint !== _.activeBreakpoint) { _.activeBreakpoint = targetBreakpoint; if (_.breakpointSettings[targetBreakpoint] === 'unslick') { _.unslick(); } else { _.options = $.extend({}, _.originalSettings, _.breakpointSettings[ targetBreakpoint]); if (initial === true) _.currentSlide = _.options.initialSlide; _.refresh(); } } } else { _.activeBreakpoint = targetBreakpoint; if (_.breakpointSettings[targetBreakpoint] === 'unslick') { _.unslick(); } else { _.options = $.extend({}, _.originalSettings, _.breakpointSettings[ targetBreakpoint]); if (initial === true) _.currentSlide = _.options.initialSlide; _.refresh(); } } } else { if (_.activeBreakpoint !== null) { _.activeBreakpoint = null; _.options = _.originalSettings; if (initial === true) _.currentSlide = _.options.initialSlide; _.refresh(); } } } }; Slick.prototype.changeSlide = function(event, dontAnimate) { var _ = this, $target = $(event.target), indexOffset, slideOffset, unevenOffset; // If target is a link, prevent default action. $target.is('a') && event.preventDefault(); unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0); indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll; switch (event.data.message) { case 'previous': slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset; if (_.slideCount > _.options.slidesToShow) { _.slideHandler(_.currentSlide - slideOffset, false, dontAnimate); } break; case 'next': slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset; if (_.slideCount > _.options.slidesToShow) { _.slideHandler(_.currentSlide + slideOffset, false, dontAnimate); } break; case 'index': var index = event.data.index === 0 ? 0 : event.data.index || $(event.target).parent().index() * _.options.slidesToScroll; _.slideHandler(_.checkNavigable(index), false, dontAnimate); break; default: return; } }; Slick.prototype.checkNavigable = function(index) { var _ = this, navigables, prevNavigable; navigables = _.getNavigableIndexes(); prevNavigable = 0; if (index > navigables[navigables.length - 1]) { index = navigables[navigables.length - 1]; } else { for (var n in navigables) { if (index < navigables[n]) { index = prevNavigable; break; } prevNavigable = navigables[n]; } } return index; }; Slick.prototype.cleanUpEvents = function() { var _ = this; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { $('li', _.$dots).off('click.slick', _.changeSlide); } if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.options.autoplay === true) { $('li', _.$dots) .off('mouseenter.slick', _.setPaused.bind(_, true)) .off('mouseleave.slick', _.setPaused.bind(_, false)); } if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide); _.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide); } _.$list.off('touchstart.slick mousedown.slick', _.swipeHandler); _.$list.off('touchmove.slick mousemove.slick', _.swipeHandler); _.$list.off('touchend.slick mouseup.slick', _.swipeHandler); _.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler); _.$list.off('click.slick', _.clickHandler); if (_.options.autoplay === true) { $(document).off(_.visibilityChange, _.visibility); } _.$list.off('mouseenter.slick', _.setPaused.bind(_, true)); _.$list.off('mouseleave.slick', _.setPaused.bind(_, false)); if (_.options.accessibility === true) { _.$list.off('keydown.slick', _.keyHandler); } if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().off('click.slick', _.selectHandler); } $(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange); $(window).off('resize.slick.slick-' + _.instanceUid, _.resize); $('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault); $(window).off('load.slick.slick-' + _.instanceUid, _.setPosition); $(document).off('ready.slick.slick-' + _.instanceUid, _.setPosition); }; Slick.prototype.cleanUpRows = function() { var _ = this, originalSlides; if(_.options.rows > 1) { originalSlides = _.$slides.children().children(); originalSlides.removeAttr('style'); _.$slider.html(originalSlides); } }; Slick.prototype.clickHandler = function(event) { var _ = this; if (_.shouldClick === false) { event.stopImmediatePropagation(); event.stopPropagation(); event.preventDefault(); } }; Slick.prototype.destroy = function() { var _ = this; _.autoPlayClear(); _.touchObject = {}; _.cleanUpEvents(); $('.slick-cloned', _.$slider).remove(); if (_.$dots) { _.$dots.remove(); } if (_.$prevArrow && (typeof _.options.prevArrow !== 'object')) { _.$prevArrow.remove(); } if (_.$nextArrow && (typeof _.options.nextArrow !== 'object')) { _.$nextArrow.remove(); } if (_.$slides) { _.$slides.removeClass('slick-slide slick-active slick-center slick-visible') .attr('aria-hidden', 'true') .removeAttr('data-slick-index') .css({ position: '', left: '', top: '', zIndex: '', opacity: '', width: '' }); _.$slider.html(_.$slides); } _.cleanUpRows(); _.$slider.removeClass('slick-slider'); _.$slider.removeClass('slick-initialized'); }; Slick.prototype.disableTransition = function(slide) { var _ = this, transition = {}; transition[_.transitionType] = ''; if (_.options.fade === false) { _.$slideTrack.css(transition); } else { _.$slides.eq(slide).css(transition); } }; Slick.prototype.fadeSlide = function(slideIndex, callback) { var _ = this; if (_.cssTransitions === false) { _.$slides.eq(slideIndex).css({ zIndex: 1000 }); _.$slides.eq(slideIndex).animate({ opacity: 1 }, _.options.speed, _.options.easing, callback); } else { _.applyTransition(slideIndex); _.$slides.eq(slideIndex).css({ opacity: 1, zIndex: 1000 }); if (callback) { setTimeout(function() { _.disableTransition(slideIndex); callback.call(); }, _.options.speed); } } }; Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) { var _ = this; if (filter !== null) { _.unload(); _.$slideTrack.children(this.options.slide).detach(); _.$slidesCache.filter(filter).appendTo(_.$slideTrack); _.reinit(); } }; Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() { var _ = this; return _.currentSlide; }; Slick.prototype.getDotCount = function() { var _ = this; var breakPoint = 0; var counter = 0; var pagerQty = 0; if (_.options.infinite === true) { pagerQty = Math.ceil(_.slideCount / _.options.slidesToScroll); } else if (_.options.centerMode === true) { pagerQty = _.slideCount; } else { while (breakPoint < _.slideCount) { ++pagerQty; breakPoint = counter + _.options.slidesToShow; counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow; } } return pagerQty - 1; }; Slick.prototype.getLeft = function(slideIndex) { var _ = this, targetLeft, verticalHeight, verticalOffset = 0, targetSlide; _.slideOffset = 0; verticalHeight = _.$slides.first().outerHeight(); if (_.options.infinite === true) { if (_.slideCount > _.options.slidesToShow) { _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1; verticalOffset = (verticalHeight * _.options.slidesToShow) * -1; } if (_.slideCount % _.options.slidesToScroll !== 0) { if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) { if (slideIndex > _.slideCount) { _.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1; verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1; } else { _.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1; verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1; } } } } else { if (slideIndex + _.options.slidesToShow > _.slideCount) { _.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth; verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight; } } if (_.slideCount <= _.options.slidesToShow) { _.slideOffset = 0; verticalOffset = 0; } if (_.options.centerMode === true && _.options.infinite === true) { _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth; } else if (_.options.centerMode === true) { _.slideOffset = 0; _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2); } if (_.options.vertical === false) { targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset; } else { targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset; } if (_.options.variableWidth === true) { if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex); } else { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow); } targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0; if (_.options.centerMode === true) { if (_.options.infinite === false) { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex); } else { targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1); } targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0; targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2; } } return targetLeft; }; Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) { var _ = this; return _.options[option]; }; Slick.prototype.getNavigableIndexes = function() { var _ = this, breakPoint = 0, counter = 0, indexes = [], max; if (_.options.infinite === false) { max = _.slideCount - _.options.slidesToShow + 1; if (_.options.centerMode === true) max = _.slideCount; } else { breakPoint = _.options.slidesToScroll * -1; counter = _.options.slidesToScroll * -1; max = _.slideCount * 2; } while (breakPoint < max) { indexes.push(breakPoint); breakPoint = counter + _.options.slidesToScroll; counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow; } return indexes; }; Slick.prototype.getSlick = function() { return this; }; Slick.prototype.getSlideCount = function() { var _ = this, slidesTraversed, swipedSlide, centerOffset; centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0; if (_.options.swipeToSlide === true) { _.$slideTrack.find('.slick-slide').each(function(index, slide) { if (slide.offsetLeft - centerOffset + ($(slide).outerWidth() / 2) > (_.swipeLeft * -1)) { swipedSlide = slide; return false; } }); slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1; return slidesTraversed; } else { return _.options.slidesToScroll; } }; Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) { var _ = this; _.changeSlide({ data: { message: 'index', index: parseInt(slide) } }, dontAnimate); }; Slick.prototype.init = function() { var _ = this; if (!$(_.$slider).hasClass('slick-initialized')) { $(_.$slider).addClass('slick-initialized'); _.buildRows(); _.buildOut(); _.setProps(); _.startLoad(); _.loadSlider(); _.initializeEvents(); _.updateArrows(); _.updateDots(); }<|fim▁hole|> _.$slider.trigger('init', [_]); }; Slick.prototype.initArrowEvents = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.on('click.slick', { message: 'previous' }, _.changeSlide); _.$nextArrow.on('click.slick', { message: 'next' }, _.changeSlide); } }; Slick.prototype.initDotEvents = function() { var _ = this; if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { $('li', _.$dots).on('click.slick', { message: 'index' }, _.changeSlide); } if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.options.autoplay === true) { $('li', _.$dots) .on('mouseenter.slick', _.setPaused.bind(_, true)) .on('mouseleave.slick', _.setPaused.bind(_, false)); } }; Slick.prototype.initializeEvents = function() { var _ = this; _.initArrowEvents(); _.initDotEvents(); _.$list.on('touchstart.slick mousedown.slick', { action: 'start' }, _.swipeHandler); _.$list.on('touchmove.slick mousemove.slick', { action: 'move' }, _.swipeHandler); _.$list.on('touchend.slick mouseup.slick', { action: 'end' }, _.swipeHandler); _.$list.on('touchcancel.slick mouseleave.slick', { action: 'end' }, _.swipeHandler); _.$list.on('click.slick', _.clickHandler); if (_.options.autoplay === true) { $(document).on(_.visibilityChange, _.visibility.bind(_)); } _.$list.on('mouseenter.slick', _.setPaused.bind(_, true)); _.$list.on('mouseleave.slick', _.setPaused.bind(_, false)); if (_.options.accessibility === true) { _.$list.on('keydown.slick', _.keyHandler); } if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().on('click.slick', _.selectHandler); } $(window).on('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange.bind(_)); $(window).on('resize.slick.slick-' + _.instanceUid, _.resize.bind(_)); $('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault); $(window).on('load.slick.slick-' + _.instanceUid, _.setPosition); $(document).on('ready.slick.slick-' + _.instanceUid, _.setPosition); }; Slick.prototype.initUI = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.show(); _.$nextArrow.show(); } if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { _.$dots.show(); } if (_.options.autoplay === true) { _.autoPlay(); } }; Slick.prototype.keyHandler = function(event) { var _ = this; if (event.keyCode === 37 && _.options.accessibility === true) { _.changeSlide({ data: { message: 'previous' } }); } else if (event.keyCode === 39 && _.options.accessibility === true) { _.changeSlide({ data: { message: 'next' } }); } }; Slick.prototype.lazyLoad = function() { var _ = this, loadRange, cloneRange, rangeStart, rangeEnd; function loadImages(imagesScope) { $('img[data-lazy]', imagesScope).each(function() { var image = $(this), imageSource = $(this).attr('data-lazy'), imageToLoad = document.createElement('img'); imageToLoad.onload = function() { image.animate({ opacity: 1 }, 200); }; imageToLoad.src = imageSource; image .css({ opacity: 0 }) .attr('src', imageSource) .removeAttr('data-lazy') .removeClass('slick-loading'); }); } if (_.options.centerMode === true) { if (_.options.infinite === true) { rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1); rangeEnd = rangeStart + _.options.slidesToShow + 2; } else { rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1)); rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide; } } else { rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide; rangeEnd = rangeStart + _.options.slidesToShow; if (_.options.fade === true) { if (rangeStart > 0) rangeStart--; if (rangeEnd <= _.slideCount) rangeEnd++; } } loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd); loadImages(loadRange); if (_.slideCount <= _.options.slidesToShow) { cloneRange = _.$slider.find('.slick-slide'); loadImages(cloneRange); } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow) { cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow); loadImages(cloneRange); } else if (_.currentSlide === 0) { cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1); loadImages(cloneRange); } }; Slick.prototype.loadSlider = function() { var _ = this; _.setPosition(); _.$slideTrack.css({ opacity: 1 }); _.$slider.removeClass('slick-loading'); _.initUI(); if (_.options.lazyLoad === 'progressive') { _.progressiveLazyLoad(); } }; Slick.prototype.next = Slick.prototype.slickNext = function() { var _ = this; _.changeSlide({ data: { message: 'next' } }); }; Slick.prototype.orientationChange = function() { var _ = this; _.checkResponsive(); _.setPosition(); }; Slick.prototype.pause = Slick.prototype.slickPause = function() { var _ = this; _.autoPlayClear(); _.paused = true; }; Slick.prototype.play = Slick.prototype.slickPlay = function() { var _ = this; _.paused = false; _.autoPlay(); }; Slick.prototype.postSlide = function(index) { var _ = this; _.$slider.trigger('afterChange', [_, index]); _.animating = false; _.setPosition(); _.swipeLeft = null; if (_.options.autoplay === true && _.paused === false) { _.autoPlay(); } }; Slick.prototype.prev = Slick.prototype.slickPrev = function() { var _ = this; _.changeSlide({ data: { message: 'previous' } }); }; Slick.prototype.preventDefault = function(e) { e.preventDefault(); }; Slick.prototype.progressiveLazyLoad = function() { var _ = this, imgCount, targetImage; imgCount = $('img[data-lazy]', _.$slider).length; if (imgCount > 0) { targetImage = $('img[data-lazy]', _.$slider).first(); targetImage.attr('src', targetImage.attr('data-lazy')).removeClass('slick-loading').load(function() { targetImage.removeAttr('data-lazy'); _.progressiveLazyLoad(); if (_.options.adaptiveHeight === true) { _.setPosition(); } }) .error(function() { targetImage.removeAttr('data-lazy'); _.progressiveLazyLoad(); }); } }; Slick.prototype.refresh = function() { var _ = this, currentSlide = _.currentSlide; _.destroy(); $.extend(_, _.initials); _.init(); _.changeSlide({ data: { message: 'index', index: currentSlide } }, false); }; Slick.prototype.reinit = function() { var _ = this; _.$slides = _.$slideTrack.children(_.options.slide).addClass( 'slick-slide'); _.slideCount = _.$slides.length; if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) { _.currentSlide = _.currentSlide - _.options.slidesToScroll; } if (_.slideCount <= _.options.slidesToShow) { _.currentSlide = 0; } _.setProps(); _.setupInfinite(); _.buildArrows(); _.updateArrows(); _.initArrowEvents(); _.buildDots(); _.updateDots(); _.initDotEvents(); if (_.options.focusOnSelect === true) { $(_.$slideTrack).children().on('click.slick', _.selectHandler); } _.setSlideClasses(0); _.setPosition(); _.$slider.trigger('reInit', [_]); }; Slick.prototype.resize = function() { var _ = this; if ($(window).width() !== _.windowWidth) { clearTimeout(_.windowDelay); _.windowDelay = window.setTimeout(function() { _.windowWidth = $(window).width(); _.checkResponsive(); _.setPosition(); }, 50); } }; Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) { var _ = this; if (typeof(index) === 'boolean') { removeBefore = index; index = removeBefore === true ? 0 : _.slideCount - 1; } else { index = removeBefore === true ? --index : index; } if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) { return false; } _.unload(); if (removeAll === true) { _.$slideTrack.children().remove(); } else { _.$slideTrack.children(this.options.slide).eq(index).remove(); } _.$slides = _.$slideTrack.children(this.options.slide); _.$slideTrack.children(this.options.slide).detach(); _.$slideTrack.append(_.$slides); _.$slidesCache = _.$slides; _.reinit(); }; Slick.prototype.setCSS = function(position) { var _ = this, positionProps = {}, x, y; if (_.options.rtl === true) { position = -position; } x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px'; y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px'; positionProps[_.positionProp] = position; if (_.transformsEnabled === false) { _.$slideTrack.css(positionProps); } else { positionProps = {}; if (_.cssTransitions === false) { positionProps[_.animType] = 'translate(' + x + ', ' + y + ')'; _.$slideTrack.css(positionProps); } else { positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)'; _.$slideTrack.css(positionProps); } } }; Slick.prototype.setDimensions = function() { var _ = this; if (_.options.vertical === false) { if (_.options.centerMode === true) { _.$list.css({ padding: ('0px ' + _.options.centerPadding) }); } } else { _.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow); if (_.options.centerMode === true) { _.$list.css({ padding: (_.options.centerPadding + ' 0px') }); } } _.listWidth = _.$list.width(); _.listHeight = _.$list.height(); if (_.options.vertical === false && _.options.variableWidth === false) { _.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow); _.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length))); } else if (_.options.variableWidth === true) { _.$slideTrack.width(5000 * _.slideCount); } else { _.slideWidth = Math.ceil(_.listWidth); _.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length))); } var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width(); if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset); }; Slick.prototype.setFade = function() { var _ = this, targetLeft; _.$slides.each(function(index, element) { targetLeft = (_.slideWidth * index) * -1; if (_.options.rtl === true) { $(element).css({ position: 'relative', right: targetLeft, top: 0, zIndex: 800, opacity: 0 }); } else { $(element).css({ position: 'relative', left: targetLeft, top: 0, zIndex: 800, opacity: 0 }); } }); _.$slides.eq(_.currentSlide).css({ zIndex: 900, opacity: 1 }); }; Slick.prototype.setHeight = function() { var _ = this; if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) { var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true); _.$list.css('height', targetHeight); } }; Slick.prototype.setOption = Slick.prototype.slickSetOption = function(option, value, refresh) { var _ = this; _.options[option] = value; if (refresh === true) { _.unload(); _.reinit(); } }; Slick.prototype.setPosition = function() { var _ = this; _.setDimensions(); _.setHeight(); if (_.options.fade === false) { _.setCSS(_.getLeft(_.currentSlide)); } else { _.setFade(); } _.$slider.trigger('setPosition', [_]); }; Slick.prototype.setProps = function() { var _ = this, bodyStyle = document.body.style; _.positionProp = _.options.vertical === true ? 'top' : 'left'; if (_.positionProp === 'top') { _.$slider.addClass('slick-vertical'); } else { _.$slider.removeClass('slick-vertical'); } if (bodyStyle.WebkitTransition !== undefined || bodyStyle.MozTransition !== undefined || bodyStyle.msTransition !== undefined) { if (_.options.useCSS === true) { _.cssTransitions = true; } } if (bodyStyle.OTransform !== undefined) { _.animType = 'OTransform'; _.transformType = '-o-transform'; _.transitionType = 'OTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false; } if (bodyStyle.MozTransform !== undefined) { _.animType = 'MozTransform'; _.transformType = '-moz-transform'; _.transitionType = 'MozTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false; } if (bodyStyle.webkitTransform !== undefined) { _.animType = 'webkitTransform'; _.transformType = '-webkit-transform'; _.transitionType = 'webkitTransition'; if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false; } if (bodyStyle.msTransform !== undefined) { _.animType = 'msTransform'; _.transformType = '-ms-transform'; _.transitionType = 'msTransition'; if (bodyStyle.msTransform === undefined) _.animType = false; } if (bodyStyle.transform !== undefined && _.animType !== false) { _.animType = 'transform'; _.transformType = 'transform'; _.transitionType = 'transition'; } _.transformsEnabled = (_.animType !== null && _.animType !== false); }; Slick.prototype.setSlideClasses = function(index) { var _ = this, centerOffset, allSlides, indexOffset, remainder; _.$slider.find('.slick-slide').removeClass('slick-active').attr('aria-hidden', 'true').removeClass('slick-center'); allSlides = _.$slider.find('.slick-slide'); if (_.options.centerMode === true) { centerOffset = Math.floor(_.options.slidesToShow / 2); if (_.options.infinite === true) { if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) { _.$slides.slice(index - centerOffset, index + centerOffset + 1).addClass('slick-active').attr('aria-hidden', 'false'); } else { indexOffset = _.options.slidesToShow + index; allSlides.slice(indexOffset - centerOffset + 1, indexOffset + centerOffset + 2).addClass('slick-active').attr('aria-hidden', 'false'); } if (index === 0) { allSlides.eq(allSlides.length - 1 - _.options.slidesToShow).addClass('slick-center'); } else if (index === _.slideCount - 1) { allSlides.eq(_.options.slidesToShow).addClass('slick-center'); } } _.$slides.eq(index).addClass('slick-center'); } else { if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) { _.$slides.slice(index, index + _.options.slidesToShow).addClass('slick-active').attr('aria-hidden', 'false'); } else if (allSlides.length <= _.options.slidesToShow) { allSlides.addClass('slick-active').attr('aria-hidden', 'false'); } else { remainder = _.slideCount % _.options.slidesToShow; indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index; if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) { allSlides.slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder).addClass('slick-active').attr('aria-hidden', 'false'); } else { allSlides.slice(indexOffset, indexOffset + _.options.slidesToShow).addClass('slick-active').attr('aria-hidden', 'false'); } } } if (_.options.lazyLoad === 'ondemand') { _.lazyLoad(); } }; Slick.prototype.setupInfinite = function() { var _ = this, i, slideIndex, infiniteCount; if (_.options.fade === true) { _.options.centerMode = false; } if (_.options.infinite === true && _.options.fade === false) { slideIndex = null; if (_.slideCount > _.options.slidesToShow) { if (_.options.centerMode === true) { infiniteCount = _.options.slidesToShow + 1; } else { infiniteCount = _.options.slidesToShow; } for (i = _.slideCount; i > (_.slideCount - infiniteCount); i -= 1) { slideIndex = i - 1; $(_.$slides[slideIndex]).clone(true).attr('id', '') .attr('data-slick-index', slideIndex - _.slideCount) .prependTo(_.$slideTrack).addClass('slick-cloned'); } for (i = 0; i < infiniteCount; i += 1) { slideIndex = i; $(_.$slides[slideIndex]).clone(true).attr('id', '') .attr('data-slick-index', slideIndex + _.slideCount) .appendTo(_.$slideTrack).addClass('slick-cloned'); } _.$slideTrack.find('.slick-cloned').find('[id]').each(function() { $(this).attr('id', ''); }); } } }; Slick.prototype.setPaused = function(paused) { var _ = this; if (_.options.autoplay === true && _.options.pauseOnHover === true) { _.paused = paused; _.autoPlayClear(); } }; Slick.prototype.selectHandler = function(event) { var _ = this; var targetElement = $(event.target).is('.slick-slide') ? $(event.target) : $(event.target).parents('.slick-slide'); var index = parseInt(targetElement.attr('data-slick-index')); if (!index) index = 0; if (_.slideCount <= _.options.slidesToShow) { _.$slider.find('.slick-slide').removeClass('slick-active').attr('aria-hidden', 'true'); _.$slides.eq(index).addClass('slick-active').attr("aria-hidden", "false"); if (_.options.centerMode === true) { _.$slider.find('.slick-slide').removeClass('slick-center'); _.$slides.eq(index).addClass('slick-center'); } _.asNavFor(index); return; } _.slideHandler(index); }; Slick.prototype.slideHandler = function(index, sync, dontAnimate) { var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null, _ = this; sync = sync || false; if (_.animating === true && _.options.waitForAnimate === true) { return; } if (_.options.fade === true && _.currentSlide === index) { return; } if (_.slideCount <= _.options.slidesToShow) { return; } if (sync === false) { _.asNavFor(index); } targetSlide = index; targetLeft = _.getLeft(targetSlide); slideLeft = _.getLeft(_.currentSlide); _.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft; if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) { if (_.options.fade === false) { targetSlide = _.currentSlide; if (dontAnimate !== true) { _.animateSlide(slideLeft, function() { _.postSlide(targetSlide); }); } else { _.postSlide(targetSlide); } } return; } else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) { if (_.options.fade === false) { targetSlide = _.currentSlide; if (dontAnimate !== true) { _.animateSlide(slideLeft, function() { _.postSlide(targetSlide); }); } else { _.postSlide(targetSlide); } } return; } if (_.options.autoplay === true) { clearInterval(_.autoPlayTimer); } if (targetSlide < 0) { if (_.slideCount % _.options.slidesToScroll !== 0) { animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll); } else { animSlide = _.slideCount + targetSlide; } } else if (targetSlide >= _.slideCount) { if (_.slideCount % _.options.slidesToScroll !== 0) { animSlide = 0; } else { animSlide = targetSlide - _.slideCount; } } else { animSlide = targetSlide; } _.animating = true; _.$slider.trigger("beforeChange", [_, _.currentSlide, animSlide]); oldSlide = _.currentSlide; _.currentSlide = animSlide; _.setSlideClasses(_.currentSlide); _.updateDots(); _.updateArrows(); if (_.options.fade === true) { if (dontAnimate !== true) { _.fadeSlide(animSlide, function() { _.postSlide(animSlide); }); } else { _.postSlide(animSlide); } _.animateHeight(); return; } if (dontAnimate !== true) { _.animateSlide(targetLeft, function() { _.postSlide(animSlide); }); } else { _.postSlide(animSlide); } }; Slick.prototype.startLoad = function() { var _ = this; if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.hide(); _.$nextArrow.hide(); } if (_.options.dots === true && _.slideCount > _.options.slidesToShow) { _.$dots.hide(); } _.$slider.addClass('slick-loading'); }; Slick.prototype.swipeDirection = function() { var xDist, yDist, r, swipeAngle, _ = this; xDist = _.touchObject.startX - _.touchObject.curX; yDist = _.touchObject.startY - _.touchObject.curY; r = Math.atan2(yDist, xDist); swipeAngle = Math.round(r * 180 / Math.PI); if (swipeAngle < 0) { swipeAngle = 360 - Math.abs(swipeAngle); } if ((swipeAngle <= 45) && (swipeAngle >= 0)) { return (_.options.rtl === false ? 'left' : 'right'); } if ((swipeAngle <= 360) && (swipeAngle >= 315)) { return (_.options.rtl === false ? 'left' : 'right'); } if ((swipeAngle >= 135) && (swipeAngle <= 225)) { return (_.options.rtl === false ? 'right' : 'left'); } if (_.options.verticalSwiping === true) { if ((swipeAngle >= 35) && (swipeAngle <= 135)) { return 'left'; } else { return 'right'; } } return 'vertical'; }; Slick.prototype.swipeEnd = function(event) { var _ = this, slideCount; _.dragging = false; _.shouldClick = (_.touchObject.swipeLength > 10) ? false : true; if (_.touchObject.curX === undefined) { return false; } if (_.touchObject.edgeHit === true) { _.$slider.trigger("edge", [_, _.swipeDirection()]); } if (_.touchObject.swipeLength >= _.touchObject.minSwipe) { switch (_.swipeDirection()) { case 'left': slideCount = _.options.swipeToSlide ? _.checkNavigable(_.currentSlide + _.getSlideCount()) : _.currentSlide + _.getSlideCount(); _.slideHandler(slideCount); _.currentDirection = 0; _.touchObject = {}; _.$slider.trigger("swipe", [_, "left"]); break; case 'right': slideCount = _.options.swipeToSlide ? _.checkNavigable(_.currentSlide - _.getSlideCount()) : _.currentSlide - _.getSlideCount(); _.slideHandler(slideCount); _.currentDirection = 1; _.touchObject = {}; _.$slider.trigger("swipe", [_, "right"]); break; } } else { if (_.touchObject.startX !== _.touchObject.curX) { _.slideHandler(_.currentSlide); _.touchObject = {}; } } }; Slick.prototype.swipeHandler = function(event) { var _ = this; if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) { return; } else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) { return; } _.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ? event.originalEvent.touches.length : 1; _.touchObject.minSwipe = _.listWidth / _.options .touchThreshold; if (_.options.verticalSwiping === true) { _.touchObject.minSwipe = _.listHeight / _.options .touchThreshold; } switch (event.data.action) { case 'start': _.swipeStart(event); break; case 'move': _.swipeMove(event); break; case 'end': _.swipeEnd(event); break; } }; Slick.prototype.swipeMove = function(event) { var _ = this, edgeWasHit = false, curLeft, swipeDirection, swipeLength, positionOffset, touches; touches = event.originalEvent !== undefined ? event.originalEvent.touches : null; if (!_.dragging || touches && touches.length !== 1) { return false; } curLeft = _.getLeft(_.currentSlide); _.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX; _.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY; _.touchObject.swipeLength = Math.round(Math.sqrt( Math.pow(_.touchObject.curX - _.touchObject.startX, 2))); if (_.options.verticalSwiping === true) { _.touchObject.swipeLength = Math.round(Math.sqrt( Math.pow(_.touchObject.curY - _.touchObject.startY, 2))); } swipeDirection = _.swipeDirection(); if (swipeDirection === 'vertical') { return; } if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) { event.preventDefault(); } positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1); if (_.options.verticalSwiping === true) { positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1; } swipeLength = _.touchObject.swipeLength; _.touchObject.edgeHit = false; if (_.options.infinite === false) { if ((_.currentSlide === 0 && swipeDirection === "right") || (_.currentSlide >= _.getDotCount() && swipeDirection === "left")) { swipeLength = _.touchObject.swipeLength * _.options.edgeFriction; _.touchObject.edgeHit = true; } } if (_.options.vertical === false) { _.swipeLeft = curLeft + swipeLength * positionOffset; } else { _.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset; } if (_.options.verticalSwiping === true) { _.swipeLeft = curLeft + swipeLength * positionOffset; } if (_.options.fade === true || _.options.touchMove === false) { return false; } if (_.animating === true) { _.swipeLeft = null; return false; } _.setCSS(_.swipeLeft); }; Slick.prototype.swipeStart = function(event) { var _ = this, touches; if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) { _.touchObject = {}; return false; } if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) { touches = event.originalEvent.touches[0]; } _.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX; _.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY; _.dragging = true; }; Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() { var _ = this; if (_.$slidesCache !== null) { _.unload(); _.$slideTrack.children(this.options.slide).detach(); _.$slidesCache.appendTo(_.$slideTrack); _.reinit(); } }; Slick.prototype.unload = function() { var _ = this; $('.slick-cloned', _.$slider).remove(); if (_.$dots) { _.$dots.remove(); } if (_.$prevArrow && (typeof _.options.prevArrow !== 'object')) { _.$prevArrow.remove(); } if (_.$nextArrow && (typeof _.options.nextArrow !== 'object')) { _.$nextArrow.remove(); } _.$slides.removeClass('slick-slide slick-active slick-visible').attr("aria-hidden", "true").css('width', ''); }; Slick.prototype.unslick = function() { var _ = this; _.destroy(); }; Slick.prototype.updateArrows = function() { var _ = this, centerOffset; centerOffset = Math.floor(_.options.slidesToShow / 2); if (_.options.arrows === true && _.options.infinite !== true && _.slideCount > _.options.slidesToShow) { _.$prevArrow.removeClass('slick-disabled'); _.$nextArrow.removeClass('slick-disabled'); if (_.currentSlide === 0) { _.$prevArrow.addClass('slick-disabled'); _.$nextArrow.removeClass('slick-disabled'); } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) { _.$nextArrow.addClass('slick-disabled'); _.$prevArrow.removeClass('slick-disabled'); } else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) { _.$nextArrow.addClass('slick-disabled'); _.$prevArrow.removeClass('slick-disabled'); } } }; Slick.prototype.updateDots = function() { var _ = this; if (_.$dots !== null) { _.$dots.find('li').removeClass('slick-active').attr("aria-hidden", "true"); _.$dots.find('li').eq(Math.floor(_.currentSlide / _.options.slidesToScroll)).addClass('slick-active').attr("aria-hidden", "false"); } }; Slick.prototype.visibility = function() { var _ = this; if (document[_.hidden]) { _.paused = true; _.autoPlayClear(); } else { _.paused = false; _.autoPlay(); } }; $.fn.slick = function() { var _ = this, opt = arguments[0], args = Array.prototype.slice.call(arguments, 1), l = _.length, i = 0, ret; for (i; i < l; i++) { if (typeof opt == 'object' || typeof opt == 'undefined') _[i].slick = new Slick(_[i], opt); else ret = _[i].slick[opt].apply(_[i].slick, args); if (typeof ret != 'undefined') return ret; } return _; }; }));<|fim▁end|>
<|file_name|>ex5.rs<|end_file_name|><|fim▁begin|>use std; //============================================================================== struct Complex { real : f32, imag : f32 } impl Complex { fn new(real: f32, imag: f32) -> Complex { Complex { real: real, imag: imag } } fn to_string(&self) -> String { format!("{}{:+}i", self.real, self.imag) } fn add(&self, v: Complex) -> Complex { Complex { real: self.real + v.real, imag: self.imag + v.imag } } fn times_ten(&mut self) { self.real *= 10.0; self.imag *= 10.0; } fn abs(&self) -> f32 { (self.real * self.real + self.imag * self.imag).sqrt() } } fn ex_5_1() { println!("\n========== 1 =========="); let a = Complex::new(1.0, 2.0); println!("a = {}", a.to_string()); let b = Complex::new(2.0, 4.0); println!("b = {}", b.to_string()); let mut c = a.add(b); println!("c = {}", c.to_string()); c.times_ten(); println!("c*10 = {}", c.to_string()); let d = Complex::new(-3.0, -4.0); println!("d = {}", d.to_string()); println!("abs(d) = {}", d.abs()); } //============================================================================== trait Draw { fn draw(&self); } struct S1 { val : u32 } struct S2 { val : f32 } impl Draw for S1 { fn draw(&self) { println!("*** {} ***", self.val); } } impl Draw for S2 { fn draw(&self) { println!("*** {} ***", self.val); } } fn draw_object(obj : &Draw) { obj.draw(); } fn ex_5_2() { println!("\n========== 2 =========="); let s1 = S1 { val : 10 }; draw_object(&s1); let s2 = S2 { val : 3.14 }; draw_object(&s2); } //============================================================================== // Eq, Ord, Clone, Debug, Default and Add traits for struct #[derive(Eq)] #[derive(Default)] struct Position { x : u32, y : u32 } impl PartialEq for Position { fn eq(&self, other: &Position) -> bool { self.x == other.x && self.y == other.y } } impl std::cmp::Ord for Position { fn cmp(&self, other: &Position) -> std::cmp::Ordering { let abs = self.x * self.x + self.y * self.y; let abs_other = other.x * other.x + other.y * other.y; abs.cmp(&abs_other) } } impl std::cmp::PartialOrd for Position { fn partial_cmp(&self, other: &Position) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl std::clone::Clone for Position { fn clone(&self) -> Position { Position { x : self.x, y: self.y } // Or, derive Copy at Position and return *self here. } } impl std::ops::Add for Position { type Output = Position; fn add(self, other: Position) -> Position { Position { x: self.x + other.x, y: self.y + other.y } } } impl std::fmt::Debug for Position { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Position{{ x:{}, y:{} }}", self.x, self.y) } } fn ex_5_3() { println!("\n========== 3 =========="); let pos1 = Position { x: 10, y: 20 }; let pos2 = Position { x: 10, y: 20 }; let pos3 = Position { x: 20, y: 40 }; let pos4 = Position { x: 20, y: 10 }; println!("pos1 == pos2 : {}", pos1 == pos2); println!("pos1 == pos3 : {}", pos1 == pos3); println!("pos1 != pos3 : {}", pos1 != pos3);<|fim▁hole|> println!("pos1 < pos3 : {}", pos1 < pos3); println!("pos1 > pos3 : {}", pos1 > pos3); let pos5 = pos4.clone(); println!("pos4 == pos5 : {}", pos4 > pos5); println!("pos1 + pos2 : {:?}", pos1 + pos2); let pos0 : Position = Default::default(); println!("pos0 : {:?}", pos0); } //============================================================================== // Default and Debug traits for enum enum ButtonState { CLICKED, RELEASED } impl Default for ButtonState { fn default() -> ButtonState { ButtonState::CLICKED } } impl std::fmt::Debug for ButtonState { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let state = match *self { ButtonState::CLICKED => "CLICKED", ButtonState::RELEASED => "RELEASED", }; write!(f, "{}", state) } } fn ex_5_4() { println!("\n========== 4 =========="); let mut btn : ButtonState = Default::default(); println!("btn = {:?}", btn); btn = ButtonState::RELEASED; println!("btn = {:?}", btn); } //============================================================================== pub fn ex5() { println!("\n########## Example 5 ##########"); ex_5_1(); ex_5_2(); ex_5_3(); ex_5_4(); }<|fim▁end|>
println!("pos1 == pos4 : {}", pos1 == pos4);
<|file_name|>textureanimationtranslation.hpp<|end_file_name|><|fim▁begin|>/*************************************************************************** * Copyright (C) 2009 by Tamino Dauth * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *<|fim▁hole|> #include "mdlxtranslation.hpp" #include "textureanimationtranslations.hpp" namespace wc3lib { namespace mdlx { class TextureAnimationTranslation : public MdlxTranslation { public: TextureAnimationTranslation(class TextureAnimationTranslations *translations); class TextureAnimationTranslations* translations() const; }; inline class TextureAnimationTranslations* TextureAnimationTranslation::translations() const { return boost::polymorphic_cast<class TextureAnimationTranslations*>(this->mdlxScalings()); } } } #endif<|fim▁end|>
***************************************************************************/ #ifndef WC3LIB_MDLX_TEXTUREANIMATIONTRANSLATION_HPP #define WC3LIB_MDLX_TEXTUREANIMATIONTRANSLATION_HPP
<|file_name|>server.js<|end_file_name|><|fim▁begin|>/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'babel-polyfill'; import path from 'path'; import express from 'express'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import expressJwt from 'express-jwt'; import expressGraphQL from 'express-graphql'; import jwt from 'jsonwebtoken'; import ReactDOM from 'react-dom/server'; import { match } from 'universal-router'; import PrettyError from 'pretty-error'; import passport from './core/passport'; import models from './data/models'; import schema from './data/schema'; import routes from './routes'; import assets from './assets'; import { port, auth, analytics } from './config'; const app = express(); // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; // // Register Node.js middleware // ----------------------------------------------------------------------------- app.use(express.static(path.join(__dirname, 'public'))); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // // Authentication // ----------------------------------------------------------------------------- app.use(expressJwt({ secret: auth.jwt.secret, credentialsRequired: false, /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */ getToken: req => req.cookies.id_token, /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */ })); app.use(passport.initialize()); app.get('/login/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false }) ); app.get('/login/facebook/return', passport.authenticate('facebook', { failureRedirect: '/login', session: false }), (req, res) => { const expiresIn = 60 * 60 * 24 * 180; // 180 days const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn }); res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true }); res.redirect('/'); } ); // // Register API middleware // ----------------------------------------------------------------------------- app.use('/graphql', expressGraphQL(req => ({ schema, graphiql: true, rootValue: { request: req }, pretty: process.env.NODE_ENV !== 'production', }))); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- app.get('*', async (req, res, next) => { try { let css = []; let statusCode = 200; const template = require('./views/index.jade'); const data = { title: '', description: '', css: '', body: '', entry: assets.main.js }; if (process.env.NODE_ENV === 'production') { data.trackingId = analytics.google.trackingId; } await match(routes, { path: req.path, query: req.query, context: { insertCss: styles => css.push(styles._getCss()), setTitle: value => (data.title = value), setMeta: (key, value) => (data[key] = value), }, render(component, status = 200) { css = []; statusCode = status; data.body = ReactDOM.renderToString(component); data.css = css.join(''); return true; }, }); res.status(statusCode); res.send(template(data)); } catch (err) { next(err); } }); // // Error handling // ----------------------------------------------------------------------------- const pe = new PrettyError(); pe.skipNodeFiles(); pe.skipPackage('express'); <|fim▁hole|> const template = require('./views/error.jade'); const statusCode = err.status || 500; res.status(statusCode); res.send(template({ message: err.message, stack: process.env.NODE_ENV === 'production' ? '' : err.stack, })); }); // // Launch the server // ----------------------------------------------------------------------------- /* eslint-disable no-console */ models.sync().catch(err => console.error(err.stack)).then(() => { app.listen(port, () => { console.log(`The server is running at http://localhost:${port}/`); }); }); /* eslint-enable no-console */<|fim▁end|>
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars console.log(pe.render(err)); // eslint-disable-line no-console
<|file_name|>OrdersSetLineItemMetadataResponse.java<|end_file_name|><|fim▁begin|>/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.content.model;<|fim▁hole|> * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class OrdersSetLineItemMetadataResponse extends com.google.api.client.json.GenericJson { /** * The status of the execution. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String executionStatus; /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * The status of the execution. * @return value or {@code null} for none */ public java.lang.String getExecutionStatus() { return executionStatus; } /** * The status of the execution. * @param executionStatus executionStatus or {@code null} for none */ public OrdersSetLineItemMetadataResponse setExecutionStatus(java.lang.String executionStatus) { this.executionStatus = executionStatus; return this; } /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * Identifies what kind of resource this is. Value: the fixed string * "content#ordersSetLineItemMetadataResponse". * @param kind kind or {@code null} for none */ public OrdersSetLineItemMetadataResponse setKind(java.lang.String kind) { this.kind = kind; return this; } @Override public OrdersSetLineItemMetadataResponse set(String fieldName, Object value) { return (OrdersSetLineItemMetadataResponse) super.set(fieldName, value); } @Override public OrdersSetLineItemMetadataResponse clone() { return (OrdersSetLineItemMetadataResponse) super.clone(); } }<|fim▁end|>
/** * Model definition for OrdersSetLineItemMetadataResponse.
<|file_name|>color.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Specified color values. use cssparser::{AngleOrNumber, Color as CSSParserColor, Parser, RGBA, Token}; use cssparser::{BasicParseErrorKind, NumberOrPercentage, ParseErrorKind}; #[cfg(feature = "gecko")] use gecko_bindings::structs::nscolor; use itoa; use parser::{ParserContext, Parse}; #[cfg(feature = "gecko")] use properties::longhands::system_colors::SystemColor; use std::fmt::{self, Write}; use std::io::Write as IoWrite; use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss, ValueParseErrorKind}; use super::AllowQuirks; use values::computed::{Color as ComputedColor, Context, ToComputedValue}; use values::specified::calc::CalcNode; /// Specified color value #[derive(Clone, Debug, MallocSizeOf, PartialEq)] pub enum Color { /// The 'currentColor' keyword CurrentColor, /// A specific RGBA color Numeric { /// Parsed RGBA color parsed: RGBA, /// Authored representation authored: Option<Box<str>>, }, /// A complex color value from computed value Complex(ComputedColor), /// A system color #[cfg(feature = "gecko")] System(SystemColor), /// A special color keyword value used in Gecko #[cfg(feature = "gecko")] Special(gecko::SpecialColorKeyword), /// Quirksmode-only rule for inheriting color from the body #[cfg(feature = "gecko")] InheritFromBodyQuirk, } #[cfg(feature = "gecko")] mod gecko { define_css_keyword_enum! { SpecialColorKeyword: "-moz-default-color" => MozDefaultColor, "-moz-default-background-color" => MozDefaultBackgroundColor, "-moz-hyperlinktext" => MozHyperlinktext, "-moz-activehyperlinktext" => MozActiveHyperlinktext, "-moz-visitedhyperlinktext" => MozVisitedHyperlinktext, } } impl From<RGBA> for Color { fn from(value: RGBA) -> Self { Color::rgba(value) } } struct ColorComponentParser<'a, 'b: 'a>(&'a ParserContext<'b>); impl<'a, 'b: 'a, 'i: 'a> ::cssparser::ColorComponentParser<'i> for ColorComponentParser<'a, 'b> { type Error = StyleParseErrorKind<'i>; fn parse_angle_or_number<'t>( &self, input: &mut Parser<'i, 't>, ) -> Result<AngleOrNumber, ParseError<'i>> { #[allow(unused_imports)] use std::ascii::AsciiExt; use values::specified::Angle; let location = input.current_source_location(); let token = input.next()?.clone(); match token { Token::Dimension { value, ref unit, .. } => { let angle = Angle::parse_dimension( value, unit, /* from_calc = */ false, ); let degrees = match angle { Ok(angle) => angle.degrees(), Err(()) => return Err(location.new_unexpected_token_error(token.clone())), }; Ok(AngleOrNumber::Angle { degrees }) } Token::Number { value, .. } => { Ok(AngleOrNumber::Number { value }) } Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_angle_or_number(self.0, i)) } t => return Err(location.new_unexpected_token_error(t)), } } fn parse_percentage<'t>( &self, input: &mut Parser<'i, 't>, ) -> Result<f32, ParseError<'i>> { use values::specified::Percentage; Ok(Percentage::parse(self.0, input)?.get()) } fn parse_number<'t>( &self, input: &mut Parser<'i, 't>, ) -> Result<f32, ParseError<'i>> { use values::specified::Number; Ok(Number::parse(self.0, input)?.get()) } fn parse_number_or_percentage<'t>( &self, input: &mut Parser<'i, 't>, ) -> Result<NumberOrPercentage, ParseError<'i>> { #[allow(unused_imports)] use std::ascii::AsciiExt; let location = input.current_source_location(); match input.next()?.clone() { Token::Number { value, .. } => Ok(NumberOrPercentage::Number { value }), Token::Percentage { unit_value, .. } => { Ok(NumberOrPercentage::Percentage { unit_value }) }, Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { input.parse_nested_block(|i| CalcNode::parse_number_or_percentage(self.0, i)) } t => return Err(location.new_unexpected_token_error(t)) } } } impl Parse for Color { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { #[allow(unused_imports)] use std::ascii::AsciiExt; // Currently we only store authored value for color keywords, // because all browsers serialize those values as keywords for // specified value. let start = input.state(); let authored = input.expect_ident_cloned().ok(); input.reset(&start); let compontent_parser = ColorComponentParser(&*context); match input.try(|i| CSSParserColor::parse_with(&compontent_parser, i)) { Ok(value) => { Ok(match value { CSSParserColor::CurrentColor => Color::CurrentColor,<|fim▁hole|> }) } Err(e) => { #[cfg(feature = "gecko")] { if let Ok(system) = input.try(SystemColor::parse) { return Ok(Color::System(system)); } if let Ok(c) = gecko::SpecialColorKeyword::parse(input) { return Ok(Color::Special(c)); } } match e.kind { ParseErrorKind::Basic(BasicParseErrorKind::UnexpectedToken(t)) => { Err(e.location.new_custom_error( StyleParseErrorKind::ValueError(ValueParseErrorKind::InvalidColor(t)) )) } _ => Err(e) } } } } } impl ToCss for Color { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { match *self { Color::CurrentColor => CSSParserColor::CurrentColor.to_css(dest), Color::Numeric { authored: Some(ref authored), .. } => dest.write_str(authored), Color::Numeric { parsed: ref rgba, .. } => rgba.to_css(dest), Color::Complex(_) => Ok(()), #[cfg(feature = "gecko")] Color::System(system) => system.to_css(dest), #[cfg(feature = "gecko")] Color::Special(special) => special.to_css(dest), #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => Ok(()), } } } /// A wrapper of cssparser::Color::parse_hash. /// /// That function should never return CurrentColor, so it makes no sense to /// handle a cssparser::Color here. This should really be done in cssparser /// directly rather than here. fn parse_hash_color(value: &[u8]) -> Result<RGBA, ()> { CSSParserColor::parse_hash(value).map(|color| { match color { CSSParserColor::RGBA(rgba) => rgba, CSSParserColor::CurrentColor => unreachable!("parse_hash should never return currentcolor"), } }) } impl Color { /// Returns currentcolor value. #[inline] pub fn currentcolor() -> Color { Color::CurrentColor } /// Returns transparent value. #[inline] pub fn transparent() -> Color { // We should probably set authored to "transparent", but maybe it doesn't matter. Color::rgba(RGBA::transparent()) } /// Returns a numeric RGBA color value. #[inline] pub fn rgba(rgba: RGBA) -> Self { Color::Numeric { parsed: rgba, authored: None, } } /// Parse a color, with quirks. /// /// <https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk> pub fn parse_quirky<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, allow_quirks: AllowQuirks, ) -> Result<Self, ParseError<'i>> { input.try(|i| Self::parse(context, i)).or_else(|e| { if !allow_quirks.allowed(context.quirks_mode) { return Err(e); } Color::parse_quirky_color(input) .map(Color::rgba) .map_err(|_| e) }) } /// Parse a <quirky-color> value. /// /// <https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk> fn parse_quirky_color<'i, 't>(input: &mut Parser<'i, 't>) -> Result<RGBA, ParseError<'i>> { let location = input.current_source_location(); let (value, unit) = match *input.next()? { Token::Number { int_value: Some(integer), .. } => { (integer, None) }, Token::Dimension { int_value: Some(integer), ref unit, .. } => { (integer, Some(unit)) }, Token::Ident(ref ident) => { if ident.len() != 3 && ident.len() != 6 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } return parse_hash_color(ident.as_bytes()) .map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } ref t => { return Err(location.new_unexpected_token_error(t.clone())); }, }; if value < 0 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let length = if value <= 9 { 1 } else if value <= 99 { 2 } else if value <= 999 { 3 } else if value <= 9999 { 4 } else if value <= 99999 { 5 } else if value <= 999999 { 6 } else { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)) }; let total = length + unit.as_ref().map_or(0, |d| d.len()); if total > 6 { return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } let mut serialization = [b'0'; 6]; let space_padding = 6 - total; let mut written = space_padding; written += itoa::write(&mut serialization[written..], value).unwrap(); if let Some(unit) = unit { written += (&mut serialization[written..]).write(unit.as_bytes()).unwrap(); } debug_assert!(written == 6); parse_hash_color(&serialization).map_err(|()| { location.new_custom_error(StyleParseErrorKind::UnspecifiedError) }) } /// Returns false if the color is completely transparent, and /// true otherwise. pub fn is_non_transparent(&self) -> bool { match *self { Color::Numeric { ref parsed, .. } => parsed.alpha != 0, _ => true, } } } #[cfg(feature = "gecko")] fn convert_nscolor_to_computedcolor(color: nscolor) -> ComputedColor { use gecko::values::convert_nscolor_to_rgba; ComputedColor::rgba(convert_nscolor_to_rgba(color)) } impl Color { /// Converts this Color into a ComputedColor. /// /// If `context` is `None`, and the specified color requires data from /// the context to resolve, then `None` is returned. pub fn to_computed_color( &self, _context: Option<&Context>, ) -> Option<ComputedColor> { match *self { Color::CurrentColor => { Some(ComputedColor::currentcolor()) } Color::Numeric { ref parsed, .. } => { Some(ComputedColor::rgba(*parsed)) } Color::Complex(ref complex) => { Some(*complex) } #[cfg(feature = "gecko")] Color::System(system) => { _context.map(|context| { convert_nscolor_to_computedcolor( system.to_computed_value(context) ) }) } #[cfg(feature = "gecko")] Color::Special(special) => { use self::gecko::SpecialColorKeyword as Keyword; _context.map(|context| { let pres_context = context.device().pres_context(); convert_nscolor_to_computedcolor(match special { Keyword::MozDefaultColor => pres_context.mDefaultColor, Keyword::MozDefaultBackgroundColor => pres_context.mBackgroundColor, Keyword::MozHyperlinktext => pres_context.mLinkColor, Keyword::MozActiveHyperlinktext => pres_context.mActiveLinkColor, Keyword::MozVisitedHyperlinktext => pres_context.mVisitedLinkColor, }) }) } #[cfg(feature = "gecko")] Color::InheritFromBodyQuirk => { _context.map(|context| { ComputedColor::rgba(context.device().body_text_color()) }) }, } } } impl ToComputedValue for Color { type ComputedValue = ComputedColor; fn to_computed_value(&self, context: &Context) -> ComputedColor { let result = self.to_computed_color(Some(context)).unwrap(); if result.foreground_ratio != 0 { if let Some(longhand) = context.for_non_inherited_property { if longhand.stores_complex_colors_lossily() { context.rule_cache_conditions.borrow_mut().set_uncacheable(); } } } result } fn from_computed_value(computed: &ComputedColor) -> Self { if computed.is_numeric() { Color::rgba(computed.color) } else if computed.is_currentcolor() { Color::currentcolor() } else { Color::Complex(*computed) } } } /// Specified color value, but resolved to just RGBA for computed value /// with value from color property at the same context. #[derive(Clone, Debug, MallocSizeOf, PartialEq, ToCss)] pub struct RGBAColor(pub Color); impl Parse for RGBAColor { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { Color::parse(context, input).map(RGBAColor) } } impl ToComputedValue for RGBAColor { type ComputedValue = RGBA; fn to_computed_value(&self, context: &Context) -> RGBA { self.0.to_computed_value(context) .to_rgba(context.style().get_color().clone_color()) } fn from_computed_value(computed: &RGBA) -> Self { RGBAColor(Color::rgba(*computed)) } } impl From<Color> for RGBAColor { fn from(color: Color) -> RGBAColor { RGBAColor(color) } } /// Specified value for the "color" property, which resolves the `currentcolor` /// keyword to the parent color instead of self's color. #[cfg_attr(feature = "gecko", derive(MallocSizeOf))] #[derive(Clone, Debug, PartialEq, ToCss)] pub struct ColorPropertyValue(pub Color); impl ToComputedValue for ColorPropertyValue { type ComputedValue = RGBA; #[inline] fn to_computed_value(&self, context: &Context) -> RGBA { self.0.to_computed_value(context) .to_rgba(context.builder.get_parent_color().clone_color()) } #[inline] fn from_computed_value(computed: &RGBA) -> Self { ColorPropertyValue(Color::rgba(*computed).into()) } } impl Parse for ColorPropertyValue { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { Color::parse_quirky(context, input, AllowQuirks::Yes).map(ColorPropertyValue) } }<|fim▁end|>
CSSParserColor::RGBA(rgba) => Color::Numeric { parsed: rgba, authored: authored.map(|s| s.to_ascii_lowercase().into_boxed_str()), },
<|file_name|>ping.rs<|end_file_name|><|fim▁begin|>extern crate mqttc; extern crate netopt; #[macro_use] extern crate log; extern crate env_logger; use std::env; use std::process::exit; use std::time::Duration; use netopt::NetworkOptions; use mqttc::{Client, ClientOptions, ReconnectMethod}; fn main() { env_logger::init(); let mut args: Vec<_> = env::args().collect(); if args.len() < 2 { println!("Usage: cargo run --example ping -- 127.0.0.1:1883"); exit(0); } let ref address = args[1]; info!("Display logs"); println!("Establish connection to {}", address); // Connect to broker, send CONNECT then wait CONNACK let netopt = NetworkOptions::new(); let mut opts = ClientOptions::new();<|fim▁hole|> opts.set_reconnect(ReconnectMethod::ReconnectAfter(Duration::new(5,0))); let mut client = opts.connect(address.as_str(), netopt).unwrap(); loop { match client.await().unwrap() { Some(message) => println!("{:?}", message), None => { println!("."); } } } }<|fim▁end|>
opts.set_keep_alive(15);
<|file_name|>ListProvider.ts<|end_file_name|><|fim▁begin|>import {Model} from '../../models/base/Model'; import {Subject} from 'rxjs/Subject'; import {BaseService} from '../BaseService'; import {ActivatedRoute, Router} from '@angular/router'; import {UserRights, UserService} from '../../services/UserService'; import {ListTableColumn} from './ListTableColumn'; import {BehaviorSubject} from 'rxjs/BehaviorSubject'; import {SortDirection} from '../SortDirection'; import {ListTableColumnActionType, ListTableColumnType} from './ListEnums'; export class ListProvider<T extends Model> { public currentPage = 1; public itemsPerPage = 10; public totalItems = 0; public dataLoaded = false; public items: Subject<T[]>; public cardTitle = ''; public cardIcon = ''; public columns: ListTableColumn<T>[]; public sortDirection = SortDirection; public columnTypes = ListTableColumnType; public actionTypes = ListTableColumnActionType; protected title = 'Список'; private sort = '-id'; public getRowClass: (model: T) => { [key: string]: boolean }; private static getSortKey(column: string, desc: boolean = false): string { let sortKey = column; if (desc) { sortKey = '-' + sortKey; } return sortKey; } constructor(private service: BaseService<T>, private router: Router, private route: ActivatedRoute, private _userService: UserService) { } public init() { this.items = new BehaviorSubject<T[]>([]); this.route.queryParamMap.subscribe(params => { const pageNumber = parseInt(params.get('page'), 10); if (pageNumber >= 1) { this.currentPage = pageNumber; } const sort = params.get('sort'); if (sort != null) { this.sort = sort; const key = this.sort.replace('-', ''); const sortDirection = this.sort.indexOf('-') > -1 ? SortDirection.Desc : SortDirection.Asc; this.columns.forEach(col => { col.setSorted(col.Key === key ? sortDirection : null); }); } this.load(this.currentPage); }); } public applySort(column: string) { let sortKey; if (this.sort === column) { sortKey = ListProvider.getSortKey(column, true); } else { sortKey = ListProvider.getSortKey(column); } this.sort = sortKey; this.reload(); } public changePage(page: number) { this.currentPage = page; this.reload(); } public load(page?: number) { page = page ? page : this.currentPage; this.service.getList(page, this.itemsPerPage, this.sort).subscribe((res) => { this.items.next(res.data); this.totalItems = res.totalItems;<|fim▁hole|> } private reload() { this.router.navigate([], {queryParams: {page: this.currentPage, sort: this.sort}, relativeTo: this.route}); } public can(right: UserRights): boolean { return this._userService.hasRight(right); } }<|fim▁end|>
this.currentPage = page; this.dataLoaded = true; });
<|file_name|>reppoints_moment_dcn_r101v1b_fpn_multiscale_2x.py<|end_file_name|><|fim▁begin|>from models.RepPoints.builder import RepPoints as Detector from models.dcn.builder import DCNResNetFPN as Backbone from models.RepPoints.builder import RepPointsNeck as Neck from models.RepPoints.builder import RepPointsHead as Head from mxnext.complicate import normalizer_factory def get_config(is_train): class General: log_frequency = 10 name = __name__.rsplit("/")[-1].rsplit(".")[-1] batch_image = 2 if is_train else 1 fp16 = False class KvstoreParam: kvstore = "nccl" batch_image = General.batch_image gpus = [0, 1, 2, 3, 4, 5, 6, 7] fp16 = General.fp16 class NormalizeParam: # normalizer = normalizer_factory(type="syncbn", ndev=8, wd_mult=1.0) normalizer = normalizer_factory(type="gn") class BackboneParam: fp16 = General.fp16 # normalizer = NormalizeParam.normalizer normalizer = normalizer_factory(type="fixbn") depth = 101 num_c3_block = 0 num_c4_block = 3 class NeckParam: fp16 = General.fp16 normalizer = NormalizeParam.normalizer class HeadParam: num_class = 1 + 80 fp16 = General.fp16 normalizer = NormalizeParam.normalizer batch_image = General.batch_image class point_generate: num_points = 9 scale = 4 stride = (8, 16, 32, 64, 128) transform = "moment" class head: conv_channel = 256 point_conv_channel = 256 mean = None std = None class proposal: pre_nms_top_n = 1000 post_nms_top_n = None nms_thr = None min_bbox_side = None class point_target: target_scale = 4 num_pos = 1 class bbox_target: pos_iou_thr = 0.5 neg_iou_thr = 0.5 min_pos_iou = 0.0 class focal_loss: alpha = 0.25 gamma = 2.0 class BboxParam: fp16 = General.fp16 normalizer = NormalizeParam.normalizer num_class = None image_roi = None batch_image = None class regress_target: class_agnostic = None mean = None std = None class RoiParam: fp16 = General.fp16 normalizer = NormalizeParam.normalizer out_size = None stride = None class DatasetParam:<|fim▁hole|> image_set = ("coco_val2017", ) backbone = Backbone(BackboneParam) neck = Neck(NeckParam) head = Head(HeadParam) detector = Detector() if is_train: train_sym = detector.get_train_symbol(backbone, neck, head) test_sym = None else: train_sym = None test_sym = detector.get_test_symbol(backbone, neck, head) class ModelParam: train_symbol = train_sym test_symbol = test_sym from_scratch = False random = True memonger = False memonger_until = "stage3_unit21_plus" class pretrain: prefix = "pretrain_model/resnet%s_v1b" % BackboneParam.depth epoch = 0 fixed_param = ["conv0", "stage1", "gamma", "beta"] excluded_param = ["gn"] class OptimizeParam: class optimizer: type = "sgd" lr = 0.005 / 8 * len(KvstoreParam.gpus) * KvstoreParam.batch_image momentum = 0.9 wd = 0.0001 clip_gradient = 35 class schedule: begin_epoch = 0 end_epoch = 12 lr_iter = [120000 * 16 // (len(KvstoreParam.gpus) * KvstoreParam.batch_image), 160000 * 16 // (len(KvstoreParam.gpus) * KvstoreParam.batch_image)] class warmup: type = "gradual" lr = 0.005 / 8 * len(KvstoreParam.gpus) * KvstoreParam.batch_image / 3 iter = 2000 class TestScaleParam: short_ranges = [600, 800, 1000, 1200] long_ranges = [2000, 2000, 2000, 2000] @staticmethod def add_resize_info(roidb): ms_roidb = [] for r_ in roidb: for short, long in zip(TestScaleParam.short_ranges, TestScaleParam.long_ranges): r = r_.copy() r["resize_long"] = long r["resize_short"] = short ms_roidb.append(r) return ms_roidb class TestParam: min_det_score = 0.05 # filter appended boxes max_det_per_image = 100 process_roidb = TestScaleParam.add_resize_info def process_output(x, y): return x class model: prefix = "experiments/{}/checkpoint".format(General.name) epoch = OptimizeParam.schedule.end_epoch class nms: type = "nms" thr = 0.5 class coco: annotation = "data/coco/annotations/instances_minival2014.json" # data processing class NormParam: mean = tuple(i * 255 for i in (0.485, 0.456, 0.406)) # RGB order std = tuple(i * 255 for i in (0.229, 0.224, 0.225)) class RandResizeParam: short = None # generate on the fly long = None short_ranges = [600, 800, 1000, 1200] long_ranges = [2000, 2000, 2000, 2000] class RandCropParam: mode = "center" # random or center short = 800 long = 1333 class ResizeParam: short = 800 long = 1333 class PadParam: short = 800 long = 1333 max_num_gt = 100 class RandPadParam: short = 1200 long = 2000 max_num_gt = 100 class RenameParam: mapping = dict(image="data") from core.detection_input import ReadRoiRecord, \ RandResize2DImageBbox, RandCrop2DImageBbox, Resize2DImageByRoidb, \ ConvertImageFromHwcToChw, Flip2DImageBbox, Pad2DImageBbox, \ RenameRecord from models.retinanet.input import Norm2DImage if is_train: transform = [ ReadRoiRecord(None), Norm2DImage(NormParam), # Resize2DImageBbox(ResizeParam), RandResize2DImageBbox(RandResizeParam), RandCrop2DImageBbox(RandCropParam), Flip2DImageBbox(), Pad2DImageBbox(PadParam), ConvertImageFromHwcToChw(), RenameRecord(RenameParam.mapping) ] data_name = ["data"] label_name = ["gt_bbox"] else: transform = [ ReadRoiRecord(None), Norm2DImage(NormParam), # Resize2DImageBbox(ResizeParam), Resize2DImageByRoidb(), Pad2DImageBbox(RandPadParam), ConvertImageFromHwcToChw(), RenameRecord(RenameParam.mapping) ] data_name = ["data", "im_info", "im_id", "rec_id"] label_name = [] from models.retinanet import metric as cls_metric import core.detection_metric as box_metric cls_acc_metric = cls_metric.FGAccMetric( "FGAcc", ["cls_loss_output", "point_refine_labels_output"], [] ) box_init_l1_metric = box_metric.L1( "InitL1", ["pts_init_loss_output", "points_init_labels_output"], [] ) box_refine_l1_metric = box_metric.L1( "RefineL1", ["pts_refine_loss_output", "point_refine_labels_output"], [] ) metric_list = [cls_acc_metric, box_init_l1_metric, box_refine_l1_metric] return General, KvstoreParam, HeadParam, RoiParam, BboxParam, DatasetParam, \ ModelParam, OptimizeParam, TestParam, \ transform, data_name, label_name, metric_list<|fim▁end|>
if is_train: image_set = ("coco_train2017", ) else:
<|file_name|>category_test.js<|end_file_name|><|fim▁begin|>import { expect } from 'chai' import {List, Map} from 'immutable' import categories from '../src/reducer.js' describe("Category Test", () => { it("should add a category", () => { let initialState = Map({ user: 'Skye' }) let expectedState = Map({ user: 'Skye', categories: Map({ 'Love': 0 }) }) let result = categories(initialState, {type:'ADD_CATEGORY', value:'Love'}) expect(result).to.eql(expectedState) }) it("adding a category does not modify previous state", () => { let initialState = Map({ user: 'Skye', categories: Map({ 'Love': 90 }) }) let expectedState = Map({ user: 'Skye', categories: Map({ 'Love': 90, 'Communication': 0 }) }) let result = categories(initialState, {type:'ADD_CATEGORY', value:'Communication'}) expect(result).to.eql(expectedState) expect(initialState).to.eql(Map({ user: 'Skye', categories: Map({ 'Love': 90 }) })) }) it("should rate a category", () => { let initialState = Map({ user: 'Skye', categories: Map({ 'Love': 0 }) }) let expectedState = Map({ user: 'Skye', categories: Map({ 'Love': 90 }) }) let result = categories(initialState, { type:'RATE_CATEGORY', name:'Love', value:90 }) expect(result).to.eql(Map({ user: 'Skye', categories: Map({ 'Love': 90<|fim▁hole|> })) }) it("should stop adding categories", () => { let initialState = Map({ user: 'Skye', categories: Map({ 'Love': 90, 'Communication': 80, 'Fun' : 100 }) }) let expectedState = Map({ user: 'Skye', categories: Map({ 'Love': 90, 'Communication': 80, 'Fun' : 100 }), categories_finished: true }) let result = categories(initialState, {type:'FINISH_CATEGORIES', value: true}) expect(result).to.eql(expectedState) }) })<|fim▁end|>
})
<|file_name|>u_boot_spl_nodtb.py<|end_file_name|><|fim▁begin|># SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2016 Google, Inc # Written by Simon Glass <[email protected]> # # Entry-type module for 'u-boot-nodtb.bin' # from entry import Entry from blob import Entry_blob class Entry_u_boot_spl_nodtb(Entry_blob): def __init__(self, image, etype, node):<|fim▁hole|> def GetDefaultFilename(self): return 'spl/u-boot-spl-nodtb.bin'<|fim▁end|>
Entry_blob.__init__(self, image, etype, node)
<|file_name|>secret.go<|end_file_name|><|fim▁begin|>/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package internalversion import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" rest "k8s.io/client-go/rest" api "k8s.io/kubernetes/pkg/api" ) // SecretsGetter has a method to return a SecretInterface. // A group's client should implement this interface. type SecretsGetter interface { Secrets(namespace string) SecretInterface } // SecretInterface has methods to work with Secret resources. type SecretInterface interface { Create(*api.Secret) (*api.Secret, error) Update(*api.Secret) (*api.Secret, error) Delete(name string, options *v1.DeleteOptions) error DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error Get(name string, options v1.GetOptions) (*api.Secret, error) List(opts v1.ListOptions) (*api.SecretList, error) Watch(opts v1.ListOptions) (watch.Interface, error) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *api.Secret, err error) SecretExpansion } // secrets implements SecretInterface type secrets struct { client rest.Interface ns string } // newSecrets returns a Secrets func newSecrets(c *CoreClient, namespace string) *secrets { return &secrets{ client: c.RESTClient(), ns: namespace, } } // Create takes the representation of a secret and creates it. Returns the server's representation of the secret, and an error, if there is any. func (c *secrets) Create(secret *api.Secret) (result *api.Secret, err error) { result = &api.Secret{} err = c.client.Post(). Namespace(c.ns). Resource("secrets"). Body(secret). Do(). Into(result) return } // Update takes the representation of a secret and updates it. Returns the server's representation of the secret, and an error, if there is any. func (c *secrets) Update(secret *api.Secret) (result *api.Secret, err error) { result = &api.Secret{}<|fim▁hole|> Namespace(c.ns). Resource("secrets"). Name(secret.Name). Body(secret). Do(). Into(result) return } // Delete takes name of the secret and deletes it. Returns an error if one occurs. func (c *secrets) Delete(name string, options *v1.DeleteOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("secrets"). Name(name). Body(options). Do(). Error() } // DeleteCollection deletes a collection of objects. func (c *secrets) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { return c.client.Delete(). Namespace(c.ns). Resource("secrets"). VersionedParams(&listOptions, api.ParameterCodec). Body(options). Do(). Error() } // Get takes name of the secret, and returns the corresponding secret object, and an error if there is any. func (c *secrets) Get(name string, options v1.GetOptions) (result *api.Secret, err error) { result = &api.Secret{} err = c.client.Get(). Namespace(c.ns). Resource("secrets"). Name(name). VersionedParams(&options, api.ParameterCodec). Do(). Into(result) return } // List takes label and field selectors, and returns the list of Secrets that match those selectors. func (c *secrets) List(opts v1.ListOptions) (result *api.SecretList, err error) { result = &api.SecretList{} err = c.client.Get(). Namespace(c.ns). Resource("secrets"). VersionedParams(&opts, api.ParameterCodec). Do(). Into(result) return } // Watch returns a watch.Interface that watches the requested secrets. func (c *secrets) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.client.Get(). Prefix("watch"). Namespace(c.ns). Resource("secrets"). VersionedParams(&opts, api.ParameterCodec). Watch() } // Patch applies the patch and returns the patched secret. func (c *secrets) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *api.Secret, err error) { result = &api.Secret{} err = c.client.Patch(pt). Namespace(c.ns). Resource("secrets"). SubResource(subresources...). Name(name). Body(data). Do(). Into(result) return }<|fim▁end|>
err = c.client.Put().
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>pub mod liblz4; pub mod decoder; pub mod encoder; pub use decoder::Decoder; pub use encoder::Encoder; pub use encoder::EncoderBuilder;<|fim▁hole|>pub use liblz4::ContentChecksum; pub use liblz4::version;<|fim▁end|>
pub use liblz4::BlockSize; pub use liblz4::BlockMode;
<|file_name|>undef.rs<|end_file_name|><|fim▁begin|>// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/.<|fim▁hole|>pub use lrs_base::undef::{UndefState};<|fim▁end|>
<|file_name|>message_dialog.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_char; use ffi; use glib::translate::*; use glib::object::{Cast, IsA}; use std::ptr; use ButtonsType; use DialogFlags; use MessageDialog; use MessageType; use Widget; use Window; impl MessageDialog { pub fn new<T: IsA<Window>>(parent: Option<&T>, flags: DialogFlags, type_: MessageType, buttons: ButtonsType, message: &str) -> MessageDialog { assert_initialized_main_thread!(); unsafe { let message: Stash<*const c_char, _> = message.to_glib_none(); Widget::from_glib_none( ffi::gtk_message_dialog_new(parent.map(|p| p.as_ref()).to_glib_none().0, flags.to_glib(), type_.to_glib(), buttons.to_glib(), b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>())) .unsafe_cast() } } } pub trait MessageDialogExt: 'static { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I); fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I); } impl<O: IsA<MessageDialog>> MessageDialogExt for O { fn set_secondary_markup<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_markup(<|fim▁hole|> ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } } fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0, ptr::null::<c_char>()) }, None => unsafe { ffi::gtk_message_dialog_format_secondary_text( self.as_ref().to_glib_none().0, ptr::null::<c_char>()) }, } } }<|fim▁end|>
self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char, message.0,
<|file_name|>update_device.rs<|end_file_name|><|fim▁begin|>//! `PUT /_matrix/client/*/devices/{deviceId}` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3devicesdeviceid<|fim▁hole|> use ruma_common::{api::ruma_api, DeviceId}; ruma_api! { metadata: { description: "Update metadata for a device.", method: PUT, name: "update_device", r0_path: "/_matrix/client/r0/devices/:device_id", stable_path: "/_matrix/client/v3/devices/:device_id", rate_limited: false, authentication: AccessToken, added: 1.0, } request: { /// The device to update. #[ruma_api(path)] pub device_id: &'a DeviceId, /// The new display name for this device. /// /// If this is `None`, the display name won't be changed. #[serde(skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, } #[derive(Default)] response: {} error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given device ID. pub fn new(device_id: &'a DeviceId) -> Self { Self { device_id, display_name: None } } } impl Response { /// Creates an empty `Response`. pub fn new() -> Self { Self {} } } }<|fim▁end|>
<|file_name|>views.py<|end_file_name|><|fim▁begin|>"""HTTP end-points for the User API. """ import copy from opaque_keys import InvalidKeyError from django.conf import settings from django.contrib.auth.models import User from django.http import HttpResponse from django.core.urlresolvers import reverse from django.core.exceptions import ImproperlyConfigured, NON_FIELD_ERRORS, ValidationError from django.utils.translation import ugettext as _ from django.utils.decorators import method_decorator from django.views.decorators.csrf import ensure_csrf_cookie, csrf_protect, csrf_exempt from opaque_keys.edx import locator from rest_framework import authentication from rest_framework import filters from rest_framework import generics from rest_framework import status from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.exceptions import ParseError from django_countries import countries from opaque_keys.edx.locations import SlashSeparatedCourseKey from openedx.core.lib.api.permissions import ApiKeyHeaderPermission import third_party_auth from django_comment_common.models import Role from edxmako.shortcuts import marketing_link from student.views import create_account_with_params from student.cookies import set_logged_in_cookies from openedx.core.lib.api.authentication import SessionAuthenticationAllowInactiveUser from util.json_request import JsonResponse from .preferences.api import update_email_opt_in from .helpers import FormDescription, shim_student_view, require_post_params from .models import UserPreference, UserProfile from .accounts import ( NAME_MAX_LENGTH, EMAIL_MIN_LENGTH, EMAIL_MAX_LENGTH, PASSWORD_MIN_LENGTH, PASSWORD_MAX_LENGTH, USERNAME_MIN_LENGTH, USERNAME_MAX_LENGTH ) from .accounts.api import check_account_exists from .serializers import UserSerializer, UserPreferenceSerializer class LoginSessionView(APIView): """HTTP end-points for logging in users. """ # This end-point is available to anonymous users, # so do not require authentication. authentication_classes = [] @method_decorator(ensure_csrf_cookie) def get(self, request): """Return a description of the login form. This decouples clients from the API definition: if the API decides to modify the form, clients won't need to be updated. See `user_api.helpers.FormDescription` for examples of the JSON-encoded form description. Returns: HttpResponse """ form_desc = FormDescription("post", reverse("user_api_login_session")) # Translators: This label appears above a field on the login form # meant to hold the user's email address. email_label = _(u"Email") # Translators: This example email address is used as a placeholder in # a field on the login form meant to hold the user's email address. email_placeholder = _(u"[email protected]") # Translators: These instructions appear on the login form, immediately # below a field meant to hold the user's email address. email_instructions = _( u"The email address you used to register with {platform_name}" ).format(platform_name=settings.PLATFORM_NAME) form_desc.add_field( "email", field_type="email", label=email_label, placeholder=email_placeholder, instructions=email_instructions, restrictions={ "min_length": EMAIL_MIN_LENGTH, "max_length": EMAIL_MAX_LENGTH, } ) # Translators: This label appears above a field on the login form # meant to hold the user's password. password_label = _(u"Password") form_desc.add_field( "password", label=password_label, field_type="password", restrictions={ "min_length": PASSWORD_MIN_LENGTH, "max_length": PASSWORD_MAX_LENGTH, } ) form_desc.add_field( "remember", field_type="checkbox", label=_("Remember me"), default=False, required=False, ) return HttpResponse(form_desc.to_json(), content_type="application/json") @method_decorator(require_post_params(["email", "password"])) @method_decorator(csrf_protect) def post(self, request): """Log in a user. You must send all required form fields with the request. You can optionally send an `analytics` param with a JSON-encoded object with additional info to include in the login analytics event. Currently, the only supported field is "enroll_course_id" to indicate that the user logged in while enrolling in a particular course. Arguments: request (HttpRequest) Returns: HttpResponse: 200 on success HttpResponse: 400 if the request is not valid. HttpResponse: 403 if authentication failed. 403 with content "third-party-auth" if the user has successfully authenticated with a third party provider but does not have a linked account. HttpResponse: 302 if redirecting to another page. Example Usage: POST /user_api/v1/login_session with POST params `email`, `password`, and `remember`. 200 OK """ # For the initial implementation, shim the existing login view # from the student Django app. from student.views import login_user return shim_student_view(login_user, check_logged_in=True)(request) class RegistrationView(APIView): """HTTP end-points for creating a new user. """ DEFAULT_FIELDS = ["email", "name", "username", "password"] EXTRA_FIELDS = [ "city", "country", "gender", "year_of_birth", "level_of_education", "mailing_address", "goals", "honor_code", "terms_of_service", ] # This end-point is available to anonymous users, # so do not require authentication. authentication_classes = [] def _is_field_visible(self, field_name): """Check whether a field is visible based on Django settings. """ return self._extra_fields_setting.get(field_name) in ["required", "optional"] def _is_field_required(self, field_name): """Check whether a field is required based on Django settings. """ return self._extra_fields_setting.get(field_name) == "required" def __init__(self, *args, **kwargs): super(RegistrationView, self).__init__(*args, **kwargs) # Backwards compatibility: Honor code is required by default, unless # explicitly set to "optional" in Django settings. self._extra_fields_setting = copy.deepcopy(settings.REGISTRATION_EXTRA_FIELDS) self._extra_fields_setting["honor_code"] = self._extra_fields_setting.get("honor_code", "required") # Check that the setting is configured correctly for field_name in self.EXTRA_FIELDS: if self._extra_fields_setting.get(field_name, "hidden") not in ["required", "optional", "hidden"]: msg = u"Setting REGISTRATION_EXTRA_FIELDS values must be either required, optional, or hidden." raise ImproperlyConfigured(msg) # Map field names to the instance method used to add the field to the form self.field_handlers = {} for field_name in self.DEFAULT_FIELDS + self.EXTRA_FIELDS: handler = getattr(self, "_add_{field_name}_field".format(field_name=field_name)) self.field_handlers[field_name] = handler @method_decorator(ensure_csrf_cookie) def get(self, request): """Return a description of the registration form. This decouples clients from the API definition: if the API decides to modify the form, clients won't need to be updated. This is especially important for the registration form, since different edx-platform installations might collect different demographic information. See `user_api.helpers.FormDescription` for examples of the JSON-encoded form description. Arguments: request (HttpRequest) Returns: HttpResponse """ form_desc = FormDescription("post", reverse("user_api_registration")) self._apply_third_party_auth_overrides(request, form_desc) # Default fields are always required for field_name in self.DEFAULT_FIELDS: self.field_handlers[field_name](form_desc, required=True) # Extra fields configured in Django settings # may be required, optional, or hidden for field_name in self.EXTRA_FIELDS: if self._is_field_visible(field_name): self.field_handlers[field_name]( form_desc, required=self._is_field_required(field_name) ) return HttpResponse(form_desc.to_json(), content_type="application/json") @method_decorator(csrf_exempt) def post(self, request): """Create the user's account. You must send all required form fields with the request. You can optionally send a "course_id" param to indicate in analytics events that the user registered while enrolling in a particular course. Arguments: request (HTTPRequest) Returns: HttpResponse: 200 on success HttpResponse: 400 if the request is not valid. HttpResponse: 409 if an account with the given username or email address already exists """ data = request.POST.copy() email = data.get('email') username = data.get('username') # Handle duplicate email/username conflicts = check_account_exists(email=email, username=username) if conflicts: conflict_messages = { # Translators: This message is shown to users who attempt to create a new # account using an email address associated with an existing account. "email": _( u"It looks like {email_address} belongs to an existing account. Try again with a different email address." # pylint: disable=line-too-long ).format(email_address=email), # Translators: This message is shown to users who attempt to create a new # account using a username associated with an existing account. "username": _( u"It looks like {username} belongs to an existing account. Try again with a different username." ).format(username=username), } errors = { field: [{"user_message": conflict_messages[field]}] for field in conflicts } return JsonResponse(errors, status=409) # Backwards compatibility: the student view expects both # terms of service and honor code values. Since we're combining # these into a single checkbox, the only value we may get # from the new view is "honor_code". # Longer term, we will need to make this more flexible to support # open source installations that may have separate checkboxes # for TOS, privacy policy, etc. if data.get("honor_code") and "terms_of_service" not in data: data["terms_of_service"] = data["honor_code"] try: user = create_account_with_params(request, data) except ValidationError as err: # Should only get non-field errors from this function assert NON_FIELD_ERRORS not in err.message_dict # Only return first error for each field errors = { field: [{"user_message": error} for error in error_list] for field, error_list in err.message_dict.items() } return JsonResponse(errors, status=400) response = JsonResponse({"success": True}) set_logged_in_cookies(request, response, user) return response def _add_email_field(self, form_desc, required=True): """Add an email field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form # meant to hold the user's email address. email_label = _(u"Email") # Translators: This example email address is used as a placeholder in # a field on the registration form meant to hold the user's email address. email_placeholder = _(u"[email protected]") form_desc.add_field( "email", field_type="email", label=email_label, placeholder=email_placeholder, restrictions={ "min_length": EMAIL_MIN_LENGTH, "max_length": EMAIL_MAX_LENGTH, }, required=required ) def _add_name_field(self, form_desc, required=True): """Add a name field to a form description. Arguments: form_desc: A form description Keyword Arguments:<|fim▁hole|> """ # Translators: This label appears above a field on the registration form # meant to hold the user's full name. name_label = _(u"Full name") # Translators: This example name is used as a placeholder in # a field on the registration form meant to hold the user's name. name_placeholder = _(u"Jane Doe") # Translators: These instructions appear on the registration form, immediately # below a field meant to hold the user's full name. name_instructions = _(u"Your legal name, used for any certificates you earn.") form_desc.add_field( "name", label=name_label, placeholder=name_placeholder, instructions=name_instructions, restrictions={ "max_length": NAME_MAX_LENGTH, }, required=required ) def _add_username_field(self, form_desc, required=True): """Add a username field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form # meant to hold the user's public username. username_label = _(u"Public username") # Translators: These instructions appear on the registration form, immediately # below a field meant to hold the user's public username. username_instructions = _( u"The name that will identify you in your courses - " "{bold_start}(cannot be changed later){bold_end}" ).format(bold_start=u'<strong>', bold_end=u'</strong>') # Translators: This example username is used as a placeholder in # a field on the registration form meant to hold the user's username. username_placeholder = _(u"JaneDoe") form_desc.add_field( "username", label=username_label, instructions=username_instructions, placeholder=username_placeholder, restrictions={ "min_length": USERNAME_MIN_LENGTH, "max_length": USERNAME_MAX_LENGTH, }, required=required ) def _add_password_field(self, form_desc, required=True): """Add a password field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form # meant to hold the user's password. password_label = _(u"Password") form_desc.add_field( "password", label=password_label, field_type="password", restrictions={ "min_length": PASSWORD_MIN_LENGTH, "max_length": PASSWORD_MAX_LENGTH, }, required=required ) def _add_level_of_education_field(self, form_desc, required=True): """Add a level of education field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a dropdown menu on the registration # form used to select the user's highest completed level of education. education_level_label = _(u"Highest level of education completed") # The labels are marked for translation in UserProfile model definition. options = [(name, _(label)) for name, label in UserProfile.LEVEL_OF_EDUCATION_CHOICES] # pylint: disable=translation-of-non-string form_desc.add_field( "level_of_education", label=education_level_label, field_type="select", options=options, include_default_option=True, required=required ) def _add_gender_field(self, form_desc, required=True): """Add a gender field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a dropdown menu on the registration # form used to select the user's gender. gender_label = _(u"Gender") # The labels are marked for translation in UserProfile model definition. options = [(name, _(label)) for name, label in UserProfile.GENDER_CHOICES] # pylint: disable=translation-of-non-string form_desc.add_field( "gender", label=gender_label, field_type="select", options=options, include_default_option=True, required=required ) def _add_year_of_birth_field(self, form_desc, required=True): """Add a year of birth field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a dropdown menu on the registration # form used to select the user's year of birth. yob_label = _(u"Year of birth") options = [(unicode(year), unicode(year)) for year in UserProfile.VALID_YEARS] form_desc.add_field( "year_of_birth", label=yob_label, field_type="select", options=options, include_default_option=True, required=required ) def _add_mailing_address_field(self, form_desc, required=True): """Add a mailing address field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form # meant to hold the user's mailing address. mailing_address_label = _(u"Mailing address") form_desc.add_field( "mailing_address", label=mailing_address_label, field_type="textarea", required=required ) def _add_goals_field(self, form_desc, required=True): """Add a goals field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This phrase appears above a field on the registration form # meant to hold the user's reasons for registering with edX. goals_label = _( u"Tell us why you're interested in {platform_name}" ).format(platform_name=settings.PLATFORM_NAME) form_desc.add_field( "goals", label=goals_label, field_type="textarea", required=required ) def _add_city_field(self, form_desc, required=True): """Add a city field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a field on the registration form # which allows the user to input the city in which they live. city_label = _(u"City") form_desc.add_field( "city", label=city_label, required=required ) def _add_country_field(self, form_desc, required=True): """Add a country field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This label appears above a dropdown menu on the registration # form used to select the country in which the user lives. country_label = _(u"Country") error_msg = _(u"Please select your Country.") form_desc.add_field( "country", label=country_label, field_type="select", options=list(countries), include_default_option=True, required=required, error_messages={ "required": error_msg } ) def _add_honor_code_field(self, form_desc, required=True): """Add an honor code field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Separate terms of service and honor code checkboxes if self._is_field_visible("terms_of_service"): terms_text = _(u"Honor Code") # Combine terms of service and honor code checkboxes else: # Translators: This is a legal document users must agree to # in order to register a new account. terms_text = _(u"Terms of Service and Honor Code") terms_link = u"<a href=\"{url}\">{terms_text}</a>".format( url=marketing_link("HONOR"), terms_text=terms_text ) # Translators: "Terms of Service" is a legal document users must agree to # in order to register a new account. label = _( u"I agree to the {platform_name} {terms_of_service}." ).format( platform_name=settings.PLATFORM_NAME, terms_of_service=terms_link ) # Translators: "Terms of Service" is a legal document users must agree to # in order to register a new account. error_msg = _( u"You must agree to the {platform_name} {terms_of_service}." ).format( platform_name=settings.PLATFORM_NAME, terms_of_service=terms_link ) form_desc.add_field( "honor_code", label=label, field_type="checkbox", default=False, required=required, error_messages={ "required": error_msg } ) def _add_terms_of_service_field(self, form_desc, required=True): """Add a terms of service field to a form description. Arguments: form_desc: A form description Keyword Arguments: required (bool): Whether this field is required; defaults to True """ # Translators: This is a legal document users must agree to # in order to register a new account. terms_text = _(u"Terms of Service") terms_link = u"<a href=\"{url}\">{terms_text}</a>".format( url=marketing_link("TOS"), terms_text=terms_text ) # Translators: "Terms of service" is a legal document users must agree to # in order to register a new account. label = _( u"I agree to the {platform_name} {terms_of_service}." ).format( platform_name=settings.PLATFORM_NAME, terms_of_service=terms_link ) # Translators: "Terms of service" is a legal document users must agree to # in order to register a new account. error_msg = _( u"You must agree to the {platform_name} {terms_of_service}." ).format( platform_name=settings.PLATFORM_NAME, terms_of_service=terms_link ) form_desc.add_field( "terms_of_service", label=label, field_type="checkbox", default=False, required=required, error_messages={ "required": error_msg } ) def _apply_third_party_auth_overrides(self, request, form_desc): """Modify the registration form if the user has authenticated with a third-party provider. If a user has successfully authenticated with a third-party provider, but does not yet have an account with EdX, we want to fill in the registration form with any info that we get from the provider. This will also hide the password field, since we assign users a default (random) password on the assumption that they will be using third-party auth to log in. Arguments: request (HttpRequest): The request for the registration form, used to determine if the user has successfully authenticated with a third-party provider. form_desc (FormDescription): The registration form description """ if third_party_auth.is_enabled(): running_pipeline = third_party_auth.pipeline.get(request) if running_pipeline: current_provider = third_party_auth.provider.Registry.get_from_pipeline(running_pipeline) if current_provider: # Override username / email / full name field_overrides = current_provider.get_register_form_data( running_pipeline.get('kwargs') ) for field_name in self.DEFAULT_FIELDS: if field_name in field_overrides: form_desc.override_field_properties( field_name, default=field_overrides[field_name] ) # Hide the password field form_desc.override_field_properties( "password", default="", field_type="hidden", required=False, label="", instructions="", restrictions={} ) class PasswordResetView(APIView): """HTTP end-point for GETting a description of the password reset form. """ # This end-point is available to anonymous users, # so do not require authentication. authentication_classes = [] @method_decorator(ensure_csrf_cookie) def get(self, request): """Return a description of the password reset form. This decouples clients from the API definition: if the API decides to modify the form, clients won't need to be updated. See `user_api.helpers.FormDescription` for examples of the JSON-encoded form description. Returns: HttpResponse """ form_desc = FormDescription("post", reverse("password_change_request")) # Translators: This label appears above a field on the password reset # form meant to hold the user's email address. email_label = _(u"Email") # Translators: This example email address is used as a placeholder in # a field on the password reset form meant to hold the user's email address. email_placeholder = _(u"[email protected]") # Translators: These instructions appear on the password reset form, # immediately below a field meant to hold the user's email address. email_instructions = _( u"The email address you used to register with {platform_name}" ).format(platform_name=settings.PLATFORM_NAME) form_desc.add_field( "email", field_type="email", label=email_label, placeholder=email_placeholder, instructions=email_instructions, restrictions={ "min_length": EMAIL_MIN_LENGTH, "max_length": EMAIL_MAX_LENGTH, } ) return HttpResponse(form_desc.to_json(), content_type="application/json") class UserViewSet(viewsets.ReadOnlyModelViewSet): """ DRF class for interacting with the User ORM object """ authentication_classes = (authentication.SessionAuthentication,) permission_classes = (ApiKeyHeaderPermission,) queryset = User.objects.all().prefetch_related("preferences") serializer_class = UserSerializer paginate_by = 10 paginate_by_param = "page_size" class ForumRoleUsersListView(generics.ListAPIView): """ Forum roles are represented by a list of user dicts """ authentication_classes = (authentication.SessionAuthentication,) permission_classes = (ApiKeyHeaderPermission,) serializer_class = UserSerializer paginate_by = 10 paginate_by_param = "page_size" def get_queryset(self): """ Return a list of users with the specified role/course pair """ name = self.kwargs['name'] course_id_string = self.request.query_params.get('course_id') if not course_id_string: raise ParseError('course_id must be specified') course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id_string) role = Role.objects.get_or_create(course_id=course_id, name=name)[0] users = role.users.all() return users class UserPreferenceViewSet(viewsets.ReadOnlyModelViewSet): """ DRF class for interacting with the UserPreference ORM """ authentication_classes = (authentication.SessionAuthentication,) permission_classes = (ApiKeyHeaderPermission,) queryset = UserPreference.objects.all() filter_backends = (filters.DjangoFilterBackend,) filter_fields = ("key", "user") serializer_class = UserPreferenceSerializer paginate_by = 10 paginate_by_param = "page_size" class PreferenceUsersListView(generics.ListAPIView): """ DRF class for listing a user's preferences """ authentication_classes = (authentication.SessionAuthentication,) permission_classes = (ApiKeyHeaderPermission,) serializer_class = UserSerializer paginate_by = 10 paginate_by_param = "page_size" def get_queryset(self): return User.objects.filter(preferences__key=self.kwargs["pref_key"]).prefetch_related("preferences") class UpdateEmailOptInPreference(APIView): """View for updating the email opt in preference. """ authentication_classes = (SessionAuthenticationAllowInactiveUser,) @method_decorator(require_post_params(["course_id", "email_opt_in"])) @method_decorator(ensure_csrf_cookie) def post(self, request): """ Post function for updating the email opt in preference. Allows the modification or creation of the email opt in preference at an organizational level. Args: request (Request): The request should contain the following POST parameters: * course_id: The slash separated course ID. Used to determine the organization for this preference setting. * email_opt_in: "True" or "False" to determine if the user is opting in for emails from this organization. If the string does not match "True" (case insensitive) it will assume False. """ course_id = request.data['course_id'] try: org = locator.CourseLocator.from_string(course_id).org except InvalidKeyError: return HttpResponse( status=400, content="No course '{course_id}' found".format(course_id=course_id), content_type="text/plain" ) # Only check for true. All other values are False. email_opt_in = request.data['email_opt_in'].lower() == 'true' update_email_opt_in(request.user, org, email_opt_in) return HttpResponse(status=status.HTTP_200_OK)<|fim▁end|>
required (bool): Whether this field is required; defaults to True
<|file_name|>itembox.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright (C) 2014-2019 khalim19 # # 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. """ This module defines a custom widget holding an array of GUI elements. The widget is used as the default GUI for `setting.ArraySetting` instances. """ from __future__ import absolute_import, division, print_function, unicode_literals from future.builtins import * import collections import contextlib import pygtk pygtk.require("2.0") import gtk import gobject from .. import utils as pgutils from . import draganddropcontext as draganddropcontext_ __all__ = [ "ItemBox", "ArrayBox", "ItemBoxItem", ] class ItemBox(gtk.ScrolledWindow): """ This base class defines a scrollable box holding a vertical list of items. Each item is an instance of `_ItemBoxItem` class or one of its subclasses. """ ITEM_SPACING = 4 VBOX_SPACING = 4 def __init__(self, item_spacing=ITEM_SPACING, *args, **kwargs): super().__init__(*args, **kwargs) self._item_spacing = item_spacing self._drag_and_drop_context = draganddropcontext_.DragAndDropContext() self._items = [] self._vbox_items = gtk.VBox(homogeneous=False) self._vbox_items.set_spacing(self._item_spacing) self._vbox = gtk.VBox(homogeneous=False) self._vbox.set_spacing(self.VBOX_SPACING) self._vbox.pack_start(self._vbox_items, expand=False, fill=False) self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.add_with_viewport(self._vbox) self.get_child().set_shadow_type(gtk.SHADOW_NONE) def add_item(self, item): self._vbox_items.pack_start(item.widget, expand=False, fill=False) item.button_remove.connect("clicked", self._on_item_button_remove_clicked, item) item.widget.connect("key-press-event", self._on_item_widget_key_press_event, item) self._setup_drag(item) self._items.append(item) return item def reorder_item(self, item, position): new_position = min(max(position, 0), len(self._items) - 1) self._items.pop(self._get_item_position(item)) self._items.insert(new_position, item) self._vbox_items.reorder_child(item.widget, new_position) return new_position def remove_item(self, item): item_position = self._get_item_position(item) if item_position < len(self._items) - 1: next_item_position = item_position + 1 self._items[next_item_position].item_widget.grab_focus() self._vbox_items.remove(item.widget) item.remove_item_widget() self._items.remove(item) def clear(self): for unused_ in range(len(self._items)): self.remove_item(self._items[0]) def _setup_drag(self, item): self._drag_and_drop_context.setup_drag( item.item_widget, self._get_drag_data, self._on_drag_data_received, [item], [item], self) def _get_drag_data(self, dragged_item): return str(self._items.index(dragged_item)) def _on_drag_data_received(self, dragged_item_index_str, destination_item): dragged_item = self._items[int(dragged_item_index_str)] self.reorder_item(dragged_item, self._get_item_position(destination_item)) def _on_item_widget_key_press_event(self, widget, event, item): if event.state & gtk.gdk.MOD1_MASK: # Alt key key_name = gtk.gdk.keyval_name(event.keyval) if key_name in ["Up", "KP_Up"]: self.reorder_item( item, self._get_item_position(item) - 1) elif key_name in ["Down", "KP_Down"]: self.reorder_item( item, self._get_item_position(item) + 1) def _on_item_button_remove_clicked(self, button, item): self.remove_item(item) def _get_item_position(self, item): return self._items.index(item) class ItemBoxItem(object): _HBOX_BUTTONS_SPACING = 3 _HBOX_SPACING = 3 def __init__(self, item_widget): self._item_widget = item_widget self._hbox = gtk.HBox(homogeneous=False) self._hbox.set_spacing(self._HBOX_SPACING) self._hbox_buttons = gtk.HBox(homogeneous=False) self._hbox_buttons.set_spacing(self._HBOX_BUTTONS_SPACING) self._event_box_buttons = gtk.EventBox() self._event_box_buttons.add(self._hbox_buttons) self._hbox.pack_start(self._item_widget, expand=True, fill=True) self._hbox.pack_start(self._event_box_buttons, expand=False, fill=False) self._event_box = gtk.EventBox() self._event_box.add(self._hbox) self._has_hbox_buttons_focus = False self._button_remove = gtk.Button() self._setup_item_button(self._button_remove, gtk.STOCK_CLOSE) self._event_box.connect("enter-notify-event", self._on_event_box_enter_notify_event) self._event_box.connect("leave-notify-event", self._on_event_box_leave_notify_event) self._is_event_box_allocated_size = False self._buttons_allocation = None self._event_box.connect("size-allocate", self._on_event_box_size_allocate) self._event_box_buttons.connect( "size-allocate", self._on_event_box_buttons_size_allocate) self._event_box.show_all() self._hbox_buttons.set_no_show_all(True) @property def widget(self): return self._event_box<|fim▁hole|> def item_widget(self): return self._item_widget @property def button_remove(self): return self._button_remove def remove_item_widget(self): self._hbox.remove(self._item_widget) def _setup_item_button(self, item_button, icon, position=None): item_button.set_relief(gtk.RELIEF_NONE) button_icon = gtk.image_new_from_pixbuf( item_button.render_icon(icon, gtk.ICON_SIZE_MENU)) item_button.add(button_icon) self._hbox_buttons.pack_start(item_button, expand=False, fill=False) if position is not None: self._hbox_buttons.reorder_child(item_button, position) item_button.show_all() def _on_event_box_enter_notify_event(self, event_box, event): if event.detail != gtk.gdk.NOTIFY_INFERIOR: self._hbox_buttons.show() def _on_event_box_leave_notify_event(self, event_box, event): if event.detail != gtk.gdk.NOTIFY_INFERIOR: self._hbox_buttons.hide() def _on_event_box_size_allocate(self, event_box, allocation): if self._is_event_box_allocated_size: return self._is_event_box_allocated_size = True # Assign enough height to the HBox to make sure it does not resize when # showing buttons. if self._buttons_allocation.height >= allocation.height: self._hbox.set_property("height-request", allocation.height) def _on_event_box_buttons_size_allocate(self, event_box, allocation): if self._buttons_allocation is not None: return self._buttons_allocation = allocation # Make sure the width allocated to the buttons remains the same even if # buttons are hidden. This avoids a problem with unreachable buttons when # the horizontal scrollbar is displayed. self._event_box_buttons.set_property( "width-request", self._buttons_allocation.width) self._hbox_buttons.hide() class ArrayBox(ItemBox): """ This class can be used to edit `setting.ArraySetting` instances interactively. Signals: * `"array-box-changed"` - An item was added, reordered or removed by the user. * `"array-box-item-changed"` - The contents of an item was modified by the user. Currently, this signal is not invoked in this widget and can only be invoked explicitly by calling `ArrayBox.emit("array-box-item-changed")`. """ __gsignals__ = { b"array-box-changed": (gobject.SIGNAL_RUN_FIRST, None, ()), b"array-box-item-changed": (gobject.SIGNAL_RUN_FIRST, None, ())} _SIZE_HBOX_SPACING = 6 def __init__( self, new_item_default_value, min_size=0, max_size=None, item_spacing=ItemBox.ITEM_SPACING, max_width=None, max_height=None, *args, **kwargs): """ Parameters: * `new_item_default_value` - default value for new items. * `min_size` - minimum number of elements. * `max_size` - maximum number of elements. If `None`, the number of elements is unlimited. * `item_spacing` - vertical spacing in pixels between items. * `max_width` - maximum width of the array box before the horizontal scrollbar is displayed. The array box will resize automatically until the maximum width is reached. If `max_width` is `None`, the width is fixed to whatever width is provided by `gtk.ScrolledWindow`. If `max_width` is zero or negative, the width is unlimited. * `max_height` - maximum height of the array box before the vertical scrollbar is displayed. For more information, see `max_width`. """ super().__init__(item_spacing=item_spacing, *args, **kwargs) self._new_item_default_value = new_item_default_value self._min_size = min_size if min_size >= 0 else 0 if max_size is None: self._max_size = 2**32 else: self._max_size = max_size if max_size >= min_size else min_size self.max_width = max_width self.max_height = max_height self.on_add_item = pgutils.empty_func self.on_reorder_item = pgutils.empty_func self.on_remove_item = pgutils.empty_func self._items_total_width = None self._items_total_height = None self._items_allocations = {} self._locker = _ActionLocker() self._init_gui() def _init_gui(self): self._size_spin_button = gtk.SpinButton( gtk.Adjustment( value=0, lower=self._min_size, upper=self._max_size, step_incr=1, page_incr=10, ), digits=0) self._size_spin_button.set_numeric(True) self._size_spin_button.set_value(0) self._size_spin_button_label = gtk.Label(_("Size")) self._size_hbox = gtk.HBox() self._size_hbox.set_spacing(self._SIZE_HBOX_SPACING) self._size_hbox.pack_start(self._size_spin_button_label, expand=False, fill=False) self._size_hbox.pack_start(self._size_spin_button, expand=False, fill=False) self._vbox.pack_start(self._size_hbox, expand=False, fill=False) self._vbox.reorder_child(self._size_hbox, 0) self._size_spin_button.connect( "value-changed", self._on_size_spin_button_value_changed) def add_item(self, item_value=None, index=None): if item_value is None: item_value = self._new_item_default_value item_widget = self.on_add_item(item_value, index) item = _ArrayBoxItem(item_widget) super().add_item(item) item.widget.connect("size-allocate", self._on_item_widget_size_allocate, item) if index is None: item.label.set_label(self._get_item_name(len(self._items))) if index is not None: with self._locker.lock_temp("emit_array_box_changed_on_reorder"): self.reorder_item(item, index) if self._locker.is_unlocked("update_spin_button"): with self._locker.lock_temp("emit_size_spin_button_value_changed"): self._size_spin_button.spin(gtk.SPIN_STEP_FORWARD, increment=1) return item def reorder_item(self, item, new_position): orig_position = self._get_item_position(item) processed_new_position = super().reorder_item(item, new_position) self.on_reorder_item(orig_position, processed_new_position) self._rename_item_names(min(orig_position, processed_new_position)) if self._locker.is_unlocked("emit_array_box_changed_on_reorder"): self.emit("array-box-changed") def remove_item(self, item): if (self._locker.is_unlocked("prevent_removal_below_min_size") and len(self._items) == self._min_size): return if self._locker.is_unlocked("update_spin_button"): with self._locker.lock_temp("emit_size_spin_button_value_changed"): self._size_spin_button.spin(gtk.SPIN_STEP_BACKWARD, increment=1) item_position = self._get_item_position(item) super().remove_item(item) if item in self._items_allocations: self._update_height(-(self._items_allocations[item].height + self._item_spacing)) del self._items_allocations[item] self.on_remove_item(item_position) self._rename_item_names(item_position) def set_values(self, values): self._locker.lock("emit_size_spin_button_value_changed") self._locker.lock("prevent_removal_below_min_size") orig_on_remove_item = self.on_remove_item self.on_remove_item = pgutils.empty_func self.clear() # This fixes an issue of items being allocated height of 1 when the array # size was previously 0. self.set_property("height-request", -1) for index, value in enumerate(values): self.add_item(value, index) self.on_remove_item = orig_on_remove_item self._size_spin_button.set_value(len(values)) self._locker.unlock("prevent_removal_below_min_size") self._locker.unlock("emit_size_spin_button_value_changed") def _setup_drag(self, item): self._drag_and_drop_context.setup_drag( # Using the entire item allows dragging only by the label rather than the # widget itself. This avoids problems with widgets such as spin buttons # that do not behave correctly when reordering and also avoids accidental # clicking and modifying the widget by the user. item.widget, self._get_drag_data, self._on_drag_data_received, [item], [item], self) def _on_size_spin_button_value_changed(self, size_spin_button): if self._locker.is_unlocked("emit_size_spin_button_value_changed"): self._locker.lock("update_spin_button") new_size = size_spin_button.get_value_as_int() if new_size > len(self._items): num_elements_to_add = new_size - len(self._items) for unused_ in range(num_elements_to_add): self.add_item() elif new_size < len(self._items): num_elements_to_remove = len(self._items) - new_size for unused_ in range(num_elements_to_remove): self.remove_item(self._items[-1]) self.emit("array-box-changed") self._locker.unlock("update_spin_button") def _on_item_button_remove_clicked(self, button, item): self._locker.lock("emit_size_spin_button_value_changed") should_emit_signal = ( len(self._items) > self._min_size or self._locker.is_locked("prevent_removal_below_min_size")) super()._on_item_button_remove_clicked(button, item) if should_emit_signal: self.emit("array-box-changed") self._locker.unlock("emit_size_spin_button_value_changed") def _on_item_widget_size_allocate(self, item_widget, allocation, item): if item in self._items_allocations: self._update_width(allocation.width - self._items_allocations[item].width) self._update_height(allocation.height - self._items_allocations[item].height) else: self._update_width(allocation.width) self._update_height(allocation.height + self._item_spacing) self._items_allocations[item] = allocation def _update_width(self, width_diff): if self._items_total_width is None: self._items_total_width = self.get_allocation().width if width_diff != 0: self._update_dimension( width_diff, self._items_total_width, self.max_width, "width-request") self._items_total_width = self._items_total_width + width_diff def _update_height(self, height_diff): if self._items_total_height is None: self._items_total_height = self.get_allocation().height if height_diff != 0: self._update_dimension( height_diff, self._items_total_height, self.max_height, "height-request") self._items_total_height = self._items_total_height + height_diff def _update_dimension( self, size_diff, total_size, max_visible_size, dimension_request_property): if max_visible_size is None: is_max_visible_size_unlimited = True else: is_max_visible_size_unlimited = max_visible_size <= 0 if not is_max_visible_size_unlimited: visible_size = min(total_size, max_visible_size) else: visible_size = total_size if (is_max_visible_size_unlimited or (visible_size + size_diff <= max_visible_size and total_size < max_visible_size)): new_size = visible_size + size_diff elif total_size >= max_visible_size and size_diff < 0: if total_size + size_diff < max_visible_size: new_size = total_size + size_diff else: new_size = max_visible_size else: new_size = max_visible_size if max_visible_size is not None: self.set_property(dimension_request_property, new_size) def _rename_item_names(self, start_index): for index, item in enumerate(self._items[start_index:]): item.label.set_label(self._get_item_name(index + 1 + start_index)) @staticmethod def _get_item_name(index): return _("Element") + " " + str(index) class _ArrayBoxItem(ItemBoxItem): def __init__(self, item_widget): super().__init__(item_widget) self._label = gtk.Label() self._label.show() self._hbox.pack_start(self._label, expand=False, fill=False) self._hbox.reorder_child(self._label, 0) @property def label(self): return self._label class _ActionLocker(object): def __init__(self): self._tokens = collections.defaultdict(int) @contextlib.contextmanager def lock_temp(self, key): self.lock(key) try: yield finally: self.unlock(key) def lock(self, key): self._tokens[key] += 1 def unlock(self, key): if self._tokens[key] > 0: self._tokens[key] -= 1 def is_locked(self, key): return self._tokens[key] > 0 def is_unlocked(self, key): return self._tokens[key] == 0 gobject.type_register(ArrayBox)<|fim▁end|>
@property
<|file_name|>ForestryFabricatorRecipeAccessor.java<|end_file_name|><|fim▁begin|>/* * This file is part of ThermalRecycling, licensed under the MIT License (MIT). * * Copyright (c) OreCruncher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,<|fim▁hole|> * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.blockartistry.mod.ThermalRecycling.support.recipe.accessor; import java.util.List; import forestry.api.recipes.IFabricatorRecipe; import net.minecraft.item.ItemStack; public class ForestryFabricatorRecipeAccessor extends RecipeAccessorBase { @Override public ItemStack getInput(final Object recipe) { final IFabricatorRecipe r = (IFabricatorRecipe) recipe; return r.getRecipeOutput().copy(); } @Override public List<ItemStack> getOutput(final Object recipe) { final IFabricatorRecipe r = (IFabricatorRecipe) recipe; return RecipeUtil.projectForgeRecipeList(r.getIngredients()); } }<|fim▁end|>
<|file_name|>httpoutput.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Output classes for ETL. # # Author: Just van den Broecke # from stetl.output import Output from stetl.util import Util from stetl.packet import FORMAT import httplib import base64 log = Util.get_log('httpoutput') class HttpOutput(Output): """ Output via HTTP protocol, usually via POST. consumes=FORMAT.etree_doc """ def __init__(self, configdict, section, consumes=FORMAT.any): Output.__init__(self, configdict, section, consumes) self.host = self.cfg.get('host') self.port = self.cfg.get('port', '80') self.path = self.cfg.get('path') self.method = self.cfg.get('method', 'POST') self.user = self.cfg.get('user', None) self.password = self.cfg.get('password', None) self.content_type = self.cfg.get('content_type', 'text/xml') # self.accept_type = self.cfg.get('accept_type', self.content_type) # If we receive a list(), should we create a HTTP req for each member? self.list_fanout = self.cfg.get_bool('list_fanout', True) self.req_nr = 0 def create_payload(self, packet): return packet.data def post(self, packet, payload): self.req_nr += 1 webservice = httplib.HTTP(self.host) # write your headers<|fim▁hole|> webservice.putrequest(self.method, self.path) webservice.putheader("Host", self.host) webservice.putheader("User-Agent", "Stetl Python http") webservice.putheader("Content-Type", self.content_type) # webservice.putheader("Accept", self.accept_type) webservice.putheader("Content-Length", "%d" % len(payload)) # basic auth: http://mozgovipc.blogspot.nl/2012/06/python-http-basic-authentication-with.html # base64 encode the username and password # write the Authorization header like: 'Basic base64encode(username + ':' + password) if self.user is not None: auth = base64.encodestring('%s:%s' % (self.user, self.password)).replace('\n', '') webservice.putheader("Authorization", "Basic %s" % auth) webservice.endheaders() webservice.send(payload) # get the response statuscode, statusmessage, header = webservice.getreply() log.info("Req nr %d - response status: code=%d msg=%s" % (self.req_nr, statuscode, statusmessage)) if statuscode != 200: log.error("Headers: %s" % str(header)) res = webservice.getfile().read() log.info('Content: %s' % res) # conn = httplib.HTTPConnection(self.host, self.port) # conn.request(self.method, self.path, payload, headers) # response = conn.getresponse() # log.info('status=%s msg=%s' % (response.status, response.msg)) # log.info('response=%s' % response.read(1024)) # conn.close() return packet def write(self, packet): if packet.data is None: return packet if type(packet.data) is list and self.list_fanout is True: # Multiple records in list, save original original_data = packet.data for data_elm in original_data: packet.data = data_elm self.post(packet, self.create_payload(packet)) packet.data = original_data else: # Regular, single data element or list_fanout is False self.post(packet, self.create_payload(packet)) return packet<|fim▁end|>
<|file_name|>direct_irq.rs<|end_file_name|><|fim▁begin|>// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor}; use data_model::vec_with_array_field; use std::fs::{File, OpenOptions}; use std::io; use std::mem::size_of; use remain::sorted; use thiserror::Error; use vfio_sys::*; #[sorted] #[derive(Error, Debug)] pub enum DirectIrqError { #[error("failed to enable direct irq")] Enable, #[error("failed to open /dev/plat-irq-forward: {0}")] Open(io::Error), } pub struct DirectIrq { dev: File, trigger: Event, resample: Option<Event>, } impl DirectIrq { /// Create DirectIrq object to access hardware triggered interrupts. pub fn new(trigger: Event, resample: Option<Event>) -> Result<Self, DirectIrqError> { let dev = OpenOptions::new() .read(true) .write(true) .open("/dev/plat-irq-forward") .map_err(DirectIrqError::Open)?; Ok(DirectIrq { dev, trigger, resample, }) } /// Enable hardware triggered interrupt handling. /// /// Note: this feature is not part of VFIO, but provides /// missing IRQ forwarding functionality. /// /// # Arguments /// /// * `irq_num` - host interrupt number (GSI). /// pub fn irq_enable(&self, irq_num: u32) -> Result<(), DirectIrqError> { if let Some(resample) = &self.resample { self.plat_irq_ioctl( irq_num, PLAT_IRQ_FORWARD_SET_LEVEL_TRIGGER_EVENTFD, self.trigger.as_raw_descriptor(), )?; self.plat_irq_ioctl( irq_num, PLAT_IRQ_FORWARD_SET_LEVEL_UNMASK_EVENTFD, resample.as_raw_descriptor(), )?; } else { self.plat_irq_ioctl( irq_num, PLAT_IRQ_FORWARD_SET_EDGE_TRIGGER, self.trigger.as_raw_descriptor(), )?; }; Ok(()) } fn plat_irq_ioctl( &self, irq_num: u32, action: u32, fd: RawDescriptor, ) -> Result<(), DirectIrqError> { let count = 1;<|fim▁hole|> irq_set[0].argsz = (size_of::<plat_irq_forward_set>() + count * u32_size) as u32; irq_set[0].action_flags = action; irq_set[0].count = count as u32; irq_set[0].irq_number_host = irq_num; // Safe as we are the owner of irq_set and allocation provides enough space for // eventfd array. let data = unsafe { irq_set[0].eventfd.as_mut_slice(count * u32_size) }; let (left, _right) = data.split_at_mut(u32_size); left.copy_from_slice(&fd.to_ne_bytes()[..]); // Safe as we are the owner of plat_irq_forward and irq_set which are valid value let ret = unsafe { ioctl_with_ref(self, PLAT_IRQ_FORWARD_SET(), &irq_set[0]) }; if ret < 0 { Err(DirectIrqError::Enable) } else { Ok(()) } } } impl AsRawDescriptor for DirectIrq { fn as_raw_descriptor(&self) -> i32 { self.dev.as_raw_descriptor() } }<|fim▁end|>
let u32_size = size_of::<u32>(); let mut irq_set = vec_with_array_field::<plat_irq_forward_set, u32>(count);
<|file_name|>Users.js<|end_file_name|><|fim▁begin|>/** * @param {Object} options * @param {Number} options.size Max size of array to return * @param {Number} options.page Location in pagination * @param {String} options.first_name first name of user * @param {String} options.last_name last name of user * @param {Boolean} options.is_collaborator is &#x60;User&#x60;a collaborator? * @param {Boolean} options.is_creator is &#x60;User&#x60;a creator? * @param {String} options.city city location of user * @param {String} options.state state location of user * @param {Array} options.university_ids universities a &#x60;User&#x60;is associated with * @param {String} options.project_id project_id the &#x60;User&#x60;is associated with * @param {String} options.created_date date the &#x60;User&#x60;was created * @param {String} options.modified_date date the &#x60;User&#x60;was modified * @param {Array} options.keywords keyword * @param {Array} options.skills skills to search for * @param {Function} callback */ import models from '../../../../../model'; import bcrypt from 'bcrypt'; const Grant = models.grant; const Post = models.post; const Project = models.project; const Review = models.review; const Skill = models.skill; const University = models.University; const User = models.User; const UserSkill = models.userkSkill; export function getUsers (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.university_id ID of &#x27;User&#x27; to fetch * @param {Number} options.max max num of &#x27;User&#x27; to fetch * @param {Number} options.page page in pagination * @param {Function} callback */ export function getUsersByUniversityId (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.project_id ID of &#x27;Project&#x27; to fetch * @param {Number} options.max max num of &#x27;User&#x27; to fetch * @param {Number} options.page page in pagination * @param {Function} callback */ export function getUsersByProjectId (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.created_date Date that &#x60;User&#x60; object was created * @param {Function} callback */ export function getUsersByCreatedDate (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.created_date Date that &#x60;User&#x60; object was created * @param {Function} callback */ export function getUsersByCreatedDateForm (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.modified_date Date that &#x60;User&#x60; object was modified * @param {Function} callback */ export function getUsersByModifiedDate (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {String} options.modified_date Date that &#x60;User&#x60; object was modified * @param {Function} callback */ export function getUsersByModifiedDateForm (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {Array} options.keywords Keywords when searching for user * @param {Function} callback */ export function getUsersByKeywords (options, callback) { // Implement you business logic here... } /** * @param {Object} options * @param {Array} options.skills Skills when searching for user * @param {Function} callback */ export function getUsersBySkills (options, callback) { // Implement you business logic here...<|fim▁hole|><|fim▁end|>
}
<|file_name|>uint.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 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. #[cfg(target_word_size = "32")]<|fim▁hole|>} #[cfg(target_word_size = "64")] #[inline(always)] pub fn add_with_overflow(x: uint, y: uint) -> (uint, bool) { let (a, b) = ::u64::add_with_overflow(x as u64, y as u64); (a as uint, b) } #[cfg(target_word_size = "32")] #[inline(always)] pub fn sub_with_overflow(x: uint, y: uint) -> (uint, bool) { let (a, b) = ::u32::sub_with_overflow(x as u32, y as u32); (a as uint, b) } #[cfg(target_word_size = "64")] #[inline(always)] pub fn sub_with_overflow(x: uint, y: uint) -> (uint, bool) { let (a, b) = ::u64::sub_with_overflow(x as u64, y as u64); (a as uint, b) } #[cfg(target_word_size = "32")] #[inline(always)] pub fn mul_with_overflow(x: uint, y: uint) -> (uint, bool) { let (a, b) = ::u32::mul_with_overflow(x as u32, y as u32); (a as uint, b) } #[cfg(target_word_size = "64")] #[inline(always)] pub fn mul_with_overflow(x: uint, y: uint) -> (uint, bool) { let (a, b) = ::u64::mul_with_overflow(x as u64, y as u64); (a as uint, b) } #[cfg(target_word_size = "32")] pub fn bswap(x: uint) -> uint { ::i32::bswap(x as i32) as uint } #[cfg(target_word_size = "64")] pub fn bswap(x: uint) -> uint { ::i64::bswap(x as u64) as uint } #[cfg(target_endian = "big")] pub fn to_be(x: uint) -> uint { x } #[cfg(target_endian = "little")] pub fn to_be(x: uint) -> uint { bswap(x) } #[cfg(target_endian = "big")] pub fn to_le(x: uint) -> uint { bswap(x) } #[cfg(target_endian = "little")] pub fn to_le(x: uint) -> uint { x }<|fim▁end|>
#[inline(always)] pub fn add_with_overflow(x: uint, y: uint) -> (uint, bool) { let (a, b) = ::u32::add_with_overflow(x as u32, y as u32); (a as uint, b)
<|file_name|>matrix-coverage.js<|end_file_name|><|fim▁begin|>version https://git-lfs.github.com/spec/v1 oid sha256:d1ae7db9f7928706e5601ba8c7d71d4c9fbd1c4463c6b6465b502115eae45c07<|fim▁hole|><|fim▁end|>
size 77153
<|file_name|>p2.py<|end_file_name|><|fim▁begin|># Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million, find the sum of the even-valued terms. <|fim▁hole|> previous, current = 0, 1 while True: previous, current = current, previous + current yield current def problem2(bound): sum = 0 for n in fibs(): if n >= bound: break if n % 2 == 0: sum += n return sum print problem2(4000000)<|fim▁end|>
def fibs():
<|file_name|>BulkRequest.java<|end_file_name|><|fim▁begin|>/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.bulk; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.CompositeIndicesRequest; import org.elasticsearch.action.DocWriteRequest; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.support.ActiveShardCount; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.action.support.replication.ReplicationRequest; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.lucene.uid.Versions; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.XContent; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.VersionType; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import static org.elasticsearch.action.ValidateActions.addValidationError; /** * A bulk request holds an ordered {@link IndexRequest}s, {@link DeleteRequest}s and {@link UpdateRequest}s * and allows to executes it in a single batch. * * Note that we only support refresh on the bulk request not per item. * @see org.elasticsearch.client.Client#bulk(BulkRequest) */ public class BulkRequest extends ActionRequest implements CompositeIndicesRequest, WriteRequest<BulkRequest> { private static final DeprecationLogger DEPRECATION_LOGGER = new DeprecationLogger(Loggers.getLogger(BulkRequest.class)); private static final int REQUEST_OVERHEAD = 50; /**<|fim▁hole|> */ final List<DocWriteRequest> requests = new ArrayList<>(); private final Set<String> indices = new HashSet<>(); List<Object> payloads = null; protected TimeValue timeout = BulkShardRequest.DEFAULT_TIMEOUT; private ActiveShardCount waitForActiveShards = ActiveShardCount.DEFAULT; private RefreshPolicy refreshPolicy = RefreshPolicy.NONE; private long sizeInBytes = 0; public BulkRequest() { } /** * Adds a list of requests to be executed. Either index or delete requests. */ public BulkRequest add(DocWriteRequest... requests) { for (DocWriteRequest request : requests) { add(request, null); } return this; } public BulkRequest add(DocWriteRequest request) { return add(request, null); } /** * Add a request to the current BulkRequest. * @param request Request to add * @param payload Optional payload * @return the current bulk request */ public BulkRequest add(DocWriteRequest request, @Nullable Object payload) { if (request instanceof IndexRequest) { add((IndexRequest) request, payload); } else if (request instanceof DeleteRequest) { add((DeleteRequest) request, payload); } else if (request instanceof UpdateRequest) { add((UpdateRequest) request, payload); } else { throw new IllegalArgumentException("No support for request [" + request + "]"); } indices.add(request.index()); return this; } /** * Adds a list of requests to be executed. Either index or delete requests. */ public BulkRequest add(Iterable<DocWriteRequest> requests) { for (DocWriteRequest request : requests) { add(request); } return this; } /** * Adds an {@link IndexRequest} to the list of actions to execute. Follows the same behavior of {@link IndexRequest} * (for example, if no id is provided, one will be generated, or usage of the create flag). */ public BulkRequest add(IndexRequest request) { return internalAdd(request, null); } public BulkRequest add(IndexRequest request, @Nullable Object payload) { return internalAdd(request, payload); } BulkRequest internalAdd(IndexRequest request, @Nullable Object payload) { Objects.requireNonNull(request, "'request' must not be null"); requests.add(request); addPayload(payload); // lack of source is validated in validate() method sizeInBytes += (request.source() != null ? request.source().length() : 0) + REQUEST_OVERHEAD; indices.add(request.index()); return this; } /** * Adds an {@link UpdateRequest} to the list of actions to execute. */ public BulkRequest add(UpdateRequest request) { return internalAdd(request, null); } public BulkRequest add(UpdateRequest request, @Nullable Object payload) { return internalAdd(request, payload); } BulkRequest internalAdd(UpdateRequest request, @Nullable Object payload) { Objects.requireNonNull(request, "'request' must not be null"); requests.add(request); addPayload(payload); if (request.doc() != null) { sizeInBytes += request.doc().source().length(); } if (request.upsertRequest() != null) { sizeInBytes += request.upsertRequest().source().length(); } if (request.script() != null) { sizeInBytes += request.script().getIdOrCode().length() * 2; } indices.add(request.index()); return this; } /** * Adds an {@link DeleteRequest} to the list of actions to execute. */ public BulkRequest add(DeleteRequest request) { return add(request, null); } public BulkRequest add(DeleteRequest request, @Nullable Object payload) { Objects.requireNonNull(request, "'request' must not be null"); requests.add(request); addPayload(payload); sizeInBytes += REQUEST_OVERHEAD; indices.add(request.index()); return this; } private void addPayload(Object payload) { if (payloads == null) { if (payload == null) { return; } payloads = new ArrayList<>(requests.size() + 10); // add requests#size-1 elements to the payloads if it null (we add for an *existing* request) for (int i = 1; i < requests.size(); i++) { payloads.add(null); } } payloads.add(payload); } /** * The list of requests in this bulk request. */ public List<DocWriteRequest> requests() { return this.requests; } /** * The list of optional payloads associated with requests in the same order as the requests. Note, elements within * it might be null if no payload has been provided. * <p> * Note, if no payloads have been provided, this method will return null (as to conserve memory overhead). */ @Nullable public List<Object> payloads() { return this.payloads; } /** * The number of actions in the bulk request. */ public int numberOfActions() { return requests.size(); } /** * The estimated size in bytes of the bulk request. */ public long estimatedSizeInBytes() { return sizeInBytes; } /** * Adds a framed data in binary format */ public BulkRequest add(byte[] data, int from, int length) throws IOException { return add(data, from, length, null, null); } /** * Adds a framed data in binary format */ public BulkRequest add(byte[] data, int from, int length, @Nullable String defaultIndex, @Nullable String defaultType) throws IOException { return add(new BytesArray(data, from, length), defaultIndex, defaultType); } /** * Adds a framed data in binary format */ public BulkRequest add(BytesReference data, @Nullable String defaultIndex, @Nullable String defaultType) throws IOException { return add(data, defaultIndex, defaultType, null, null, null, null, null, true); } /** * Adds a framed data in binary format */ public BulkRequest add(BytesReference data, @Nullable String defaultIndex, @Nullable String defaultType, boolean allowExplicitIndex) throws IOException { return add(data, defaultIndex, defaultType, null, null, null, null, null, allowExplicitIndex); } public BulkRequest add(BytesReference data, @Nullable String defaultIndex, @Nullable String defaultType, @Nullable String defaultRouting, @Nullable String[] defaultFields, @Nullable FetchSourceContext defaultFetchSourceContext, @Nullable String defaultPipeline, @Nullable Object payload, boolean allowExplicitIndex) throws IOException { XContent xContent = XContentFactory.xContent(data); int line = 0; int from = 0; int length = data.length(); byte marker = xContent.streamSeparator(); while (true) { int nextMarker = findNextMarker(marker, from, data, length); if (nextMarker == -1) { break; } line++; // now parse the action // EMPTY is safe here because we never call namedObject try (XContentParser parser = xContent.createParser(NamedXContentRegistry.EMPTY, data.slice(from, nextMarker - from))) { // move pointers from = nextMarker + 1; // Move to START_OBJECT XContentParser.Token token = parser.nextToken(); if (token == null) { continue; } assert token == XContentParser.Token.START_OBJECT; // Move to FIELD_NAME, that's the action token = parser.nextToken(); assert token == XContentParser.Token.FIELD_NAME; String action = parser.currentName(); String index = defaultIndex; String type = defaultType; String id = null; String routing = defaultRouting; String parent = null; FetchSourceContext fetchSourceContext = defaultFetchSourceContext; String[] fields = defaultFields; String opType = null; long version = Versions.MATCH_ANY; VersionType versionType = VersionType.INTERNAL; int retryOnConflict = 0; String pipeline = defaultPipeline; // at this stage, next token can either be END_OBJECT (and use default index and type, with auto generated id) // or START_OBJECT which will have another set of parameters token = parser.nextToken(); if (token == XContentParser.Token.START_OBJECT) { String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if ("_index".equals(currentFieldName)) { if (!allowExplicitIndex) { throw new IllegalArgumentException("explicit index in bulk is not allowed"); } index = parser.text(); } else if ("_type".equals(currentFieldName)) { type = parser.text(); } else if ("_id".equals(currentFieldName)) { id = parser.text(); } else if ("_routing".equals(currentFieldName) || "routing".equals(currentFieldName)) { routing = parser.text(); } else if ("_parent".equals(currentFieldName) || "parent".equals(currentFieldName)) { parent = parser.text(); } else if ("op_type".equals(currentFieldName) || "opType".equals(currentFieldName)) { opType = parser.text(); } else if ("_version".equals(currentFieldName) || "version".equals(currentFieldName)) { version = parser.longValue(); } else if ("_version_type".equals(currentFieldName) || "_versionType".equals(currentFieldName) || "version_type".equals(currentFieldName) || "versionType".equals(currentFieldName)) { versionType = VersionType.fromString(parser.text()); } else if ("_retry_on_conflict".equals(currentFieldName) || "_retryOnConflict".equals(currentFieldName)) { retryOnConflict = parser.intValue(); } else if ("pipeline".equals(currentFieldName)) { pipeline = parser.text(); } else if ("fields".equals(currentFieldName)) { throw new IllegalArgumentException("Action/metadata line [" + line + "] contains a simple value for parameter [fields] while a list is expected"); } else if ("_source".equals(currentFieldName)) { fetchSourceContext = FetchSourceContext.parse(parser); } else { throw new IllegalArgumentException("Action/metadata line [" + line + "] contains an unknown parameter [" + currentFieldName + "]"); } } else if (token == XContentParser.Token.START_ARRAY) { if ("fields".equals(currentFieldName)) { DEPRECATION_LOGGER.deprecated("Deprecated field [fields] used, expected [_source] instead"); List<Object> values = parser.list(); fields = values.toArray(new String[values.size()]); } else { throw new IllegalArgumentException("Malformed action/metadata line [" + line + "], expected a simple value for field [" + currentFieldName + "] but found [" + token + "]"); } } else if (token == XContentParser.Token.START_OBJECT && "_source".equals(currentFieldName)) { fetchSourceContext = FetchSourceContext.parse(parser); } else if (token != XContentParser.Token.VALUE_NULL) { throw new IllegalArgumentException("Malformed action/metadata line [" + line + "], expected a simple value for field [" + currentFieldName + "] but found [" + token + "]"); } } } else if (token != XContentParser.Token.END_OBJECT) { throw new IllegalArgumentException("Malformed action/metadata line [" + line + "], expected " + XContentParser.Token.START_OBJECT + " or " + XContentParser.Token.END_OBJECT + " but found [" + token + "]"); } if ("delete".equals(action)) { add(new DeleteRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType), payload); } else { nextMarker = findNextMarker(marker, from, data, length); if (nextMarker == -1) { break; } line++; // order is important, we set parent after routing, so routing will be set to parent if not set explicitly // we use internalAdd so we don't fork here, this allows us not to copy over the big byte array to small chunks // of index request. if ("index".equals(action)) { if (opType == null) { internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType) .setPipeline(pipeline).source(data.slice(from, nextMarker - from)), payload); } else { internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType) .create("create".equals(opType)).setPipeline(pipeline) .source(data.slice(from, nextMarker - from)), payload); } } else if ("create".equals(action)) { internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType) .create(true).setPipeline(pipeline) .source(data.slice(from, nextMarker - from)), payload); } else if ("update".equals(action)) { UpdateRequest updateRequest = new UpdateRequest(index, type, id).routing(routing).parent(parent).retryOnConflict(retryOnConflict) .version(version).versionType(versionType) .routing(routing) .parent(parent); // EMPTY is safe here because we never call namedObject try (XContentParser sliceParser = xContent.createParser(NamedXContentRegistry.EMPTY, data.slice(from, nextMarker - from))) { updateRequest.fromXContent(sliceParser); } if (fetchSourceContext != null) { updateRequest.fetchSource(fetchSourceContext); } if (fields != null) { updateRequest.fields(fields); } IndexRequest upsertRequest = updateRequest.upsertRequest(); if (upsertRequest != null) { upsertRequest.version(version); upsertRequest.versionType(versionType); } IndexRequest doc = updateRequest.doc(); if (doc != null) { doc.version(version); doc.versionType(versionType); } internalAdd(updateRequest, payload); } // move pointers from = nextMarker + 1; } } } return this; } /** * Sets the number of shard copies that must be active before proceeding with the write. * See {@link ReplicationRequest#waitForActiveShards(ActiveShardCount)} for details. */ public BulkRequest waitForActiveShards(ActiveShardCount waitForActiveShards) { this.waitForActiveShards = waitForActiveShards; return this; } /** * A shortcut for {@link #waitForActiveShards(ActiveShardCount)} where the numerical * shard count is passed in, instead of having to first call {@link ActiveShardCount#from(int)} * to get the ActiveShardCount. */ public BulkRequest waitForActiveShards(final int waitForActiveShards) { return waitForActiveShards(ActiveShardCount.from(waitForActiveShards)); } public ActiveShardCount waitForActiveShards() { return this.waitForActiveShards; } @Override public BulkRequest setRefreshPolicy(RefreshPolicy refreshPolicy) { this.refreshPolicy = refreshPolicy; return this; } @Override public RefreshPolicy getRefreshPolicy() { return refreshPolicy; } /** * A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>. */ public final BulkRequest timeout(TimeValue timeout) { this.timeout = timeout; return this; } /** * A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>. */ public final BulkRequest timeout(String timeout) { return timeout(TimeValue.parseTimeValue(timeout, null, getClass().getSimpleName() + ".timeout")); } public TimeValue timeout() { return timeout; } private int findNextMarker(byte marker, int from, BytesReference data, int length) { for (int i = from; i < length; i++) { if (data.get(i) == marker) { return i; } } return -1; } /** * @return Whether this bulk request contains index request with an ingest pipeline enabled. */ public boolean hasIndexRequestsWithPipelines() { for (DocWriteRequest actionRequest : requests) { if (actionRequest instanceof IndexRequest) { IndexRequest indexRequest = (IndexRequest) actionRequest; if (Strings.hasText(indexRequest.getPipeline())) { return true; } } } return false; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (requests.isEmpty()) { validationException = addValidationError("no requests added", validationException); } for (DocWriteRequest request : requests) { // We first check if refresh has been set if (((WriteRequest<?>) request).getRefreshPolicy() != RefreshPolicy.NONE) { validationException = addValidationError( "RefreshPolicy is not supported on an item request. Set it on the BulkRequest instead.", validationException); } ActionRequestValidationException ex = ((WriteRequest<?>) request).validate(); if (ex != null) { if (validationException == null) { validationException = new ActionRequestValidationException(); } validationException.addValidationErrors(ex.validationErrors()); } } return validationException; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); waitForActiveShards = ActiveShardCount.readFrom(in); int size = in.readVInt(); for (int i = 0; i < size; i++) { requests.add(DocWriteRequest.readDocumentRequest(in)); } refreshPolicy = RefreshPolicy.readFrom(in); timeout = new TimeValue(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); waitForActiveShards.writeTo(out); out.writeVInt(requests.size()); for (DocWriteRequest request : requests) { DocWriteRequest.writeDocumentRequest(out, request); } refreshPolicy.writeTo(out); timeout.writeTo(out); } @Override public String getDescription() { return "requests[" + requests.size() + "], indices[" + Strings.collectionToDelimitedString(indices, ", ") + "]"; } }<|fim▁end|>
* Requests that are part of this request. It is only possible to add things that are both {@link ActionRequest}s and * {@link WriteRequest}s to this but java doesn't support syntax to declare that everything in the array has both types so we declare * the one with the least casts.
<|file_name|>bindings.py<|end_file_name|><|fim▁begin|>from pulp.bindings import auth, consumer, consumer_groups, repo_groups, repository from pulp.bindings.actions import ActionsAPI from pulp.bindings.content import OrphanContentAPI, ContentSourceAPI, ContentCatalogAPI from pulp.bindings.event_listeners import EventListenerAPI from pulp.bindings.server_info import ServerInfoAPI, ServerStatusAPI from pulp.bindings.tasks import TasksAPI, TaskSearchAPI from pulp.bindings.upload import UploadAPI class Bindings(object): def __init__(self, pulp_connection): """ @type: pulp_connection: pulp.bindings.server.PulpConnection """ # Please keep the following in alphabetical order to ease reading self.actions = ActionsAPI(pulp_connection) self.bind = consumer.BindingsAPI(pulp_connection) self.bindings = consumer.BindingSearchAPI(pulp_connection) self.profile = consumer.ProfilesAPI(pulp_connection) self.consumer = consumer.ConsumerAPI(pulp_connection) self.consumer_content = consumer.ConsumerContentAPI(pulp_connection) self.consumer_content_schedules = consumer.ConsumerContentSchedulesAPI(pulp_connection) self.consumer_group = consumer_groups.ConsumerGroupAPI(pulp_connection) self.consumer_group_search = consumer_groups.ConsumerGroupSearchAPI(pulp_connection) self.consumer_group_actions = consumer_groups.ConsumerGroupActionAPI(pulp_connection) self.consumer_group_bind = consumer_groups.ConsumerGroupBindAPI(pulp_connection) self.consumer_group_content = consumer_groups.ConsumerGroupContentAPI(pulp_connection) self.consumer_history = consumer.ConsumerHistoryAPI(pulp_connection) self.consumer_search = consumer.ConsumerSearchAPI(pulp_connection) self.content_orphan = OrphanContentAPI(pulp_connection) self.content_source = ContentSourceAPI(pulp_connection)<|fim▁hole|> self.event_listener = EventListenerAPI(pulp_connection) self.permission = auth.PermissionAPI(pulp_connection) self.repo = repository.RepositoryAPI(pulp_connection) self.repo_actions = repository.RepositoryActionsAPI(pulp_connection) self.repo_distributor = repository.RepositoryDistributorAPI(pulp_connection) self.repo_group = repo_groups.RepoGroupAPI(pulp_connection) self.repo_group_actions = repo_groups.RepoGroupActionAPI(pulp_connection) self.repo_group_distributor = repo_groups.RepoGroupDistributorAPI(pulp_connection) self.repo_group_distributor_search = repo_groups.RepoGroupSearchAPI(pulp_connection) self.repo_group_search = repo_groups.RepoGroupSearchAPI(pulp_connection) self.repo_history = repository.RepositoryHistoryAPI(pulp_connection) self.repo_importer = repository.RepositoryImporterAPI(pulp_connection) self.repo_publish_schedules = repository.RepositoryPublishSchedulesAPI(pulp_connection) self.repo_search = repository.RepositorySearchAPI(pulp_connection) self.repo_sync_schedules = repository.RepositorySyncSchedulesAPI(pulp_connection) self.repo_unit = repository.RepositoryUnitAPI(pulp_connection) self.role = auth.RoleAPI(pulp_connection) self.server_info = ServerInfoAPI(pulp_connection) self.server_status = ServerStatusAPI(pulp_connection) self.tasks = TasksAPI(pulp_connection) self.tasks_search = TaskSearchAPI(pulp_connection) self.uploads = UploadAPI(pulp_connection) self.user = auth.UserAPI(pulp_connection) self.user_search = auth.UserSearchAPI(pulp_connection)<|fim▁end|>
self.content_catalog = ContentCatalogAPI(pulp_connection)
<|file_name|>PDFTimestampServiceTest.java<|end_file_name|><|fim▁begin|>/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.pades.timestamp; import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature; import org.junit.jupiter.api.Test; import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.InMemoryDocument; import eu.europa.esig.dss.pades.PAdESTimestampParameters; import eu.europa.esig.dss.pades.signature.PAdESService; import eu.europa.esig.dss.test.signature.PKIFactoryAccess; public class PDFTimestampServiceTest extends PKIFactoryAccess { @Test<|fim▁hole|> public void timestampAlone() throws IOException { PAdESService service = new PAdESService(getCompleteCertificateVerifier()); service.setTspSource(getGoodTsa()); PAdESTimestampParameters parameters = new PAdESTimestampParameters(); DSSDocument document = new InMemoryDocument(getClass().getResourceAsStream("/sample.pdf")); DSSDocument timestamped = service.timestamp(document, parameters); try (InputStream is = timestamped.openStream(); PDDocument doc = PDDocument.load(is)) { List<PDSignature> signatureDictionaries = doc.getSignatureDictionaries(); assertEquals(1, signatureDictionaries.size()); PDSignature pdSignature = signatureDictionaries.get(0); assertNotNull(pdSignature); assertEquals("Adobe.PPKLite", pdSignature.getFilter()); assertEquals("ETSI.RFC3161", pdSignature.getSubFilter()); } } @Override protected String getSigningAlias() { return null; } }<|fim▁end|>
<|file_name|>osstringext.rs<|end_file_name|><|fim▁begin|>use std::ffi::OsStr; #[cfg(not(target_os = "windows"))] use std::os::unix::ffi::OsStrExt; #[cfg(target_os = "windows")] use INVALID_UTF8; #[cfg(target_os = "windows")] trait OsStrExt3 { fn from_bytes(b: &[u8]) -> &Self; fn as_bytes(&self) -> &[u8]; } #[doc(hidden)] pub trait OsStrExt2 { fn starts_with(&self, s: &[u8]) -> bool; fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr); fn split_at(&self, i: usize) -> (&OsStr, &OsStr); fn trim_left_matches(&self, b: u8) -> &OsStr; fn len_(&self) -> usize; fn contains_byte(&self, b: u8) -> bool; fn is_empty_(&self) -> bool; fn split(&self, b: u8) -> OsSplit; } #[cfg(target_os = "windows")] impl OsStrExt3 for OsStr { fn from_bytes(b: &[u8]) -> &Self { use ::std::mem; unsafe { mem::transmute(b) } } fn as_bytes(&self) -> &[u8] { self.to_str().map(|s| s.as_bytes()).expect(INVALID_UTF8) } } impl OsStrExt2 for OsStr { fn starts_with(&self, s: &[u8]) -> bool { self.as_bytes().starts_with(s) } fn is_empty_(&self) -> bool { self.as_bytes().is_empty() } fn contains_byte(&self, byte: u8) -> bool { for b in self.as_bytes() { if b == &byte { return true; } } false } fn split_at_byte(&self, byte: u8) -> (&OsStr, &OsStr) { for (i, b) in self.as_bytes().iter().enumerate() { if b == &byte { return (&OsStr::from_bytes(&self.as_bytes()[..i]), &OsStr::from_bytes(&self.as_bytes()[i+1..])); } } (&*self, &OsStr::from_bytes(&self.as_bytes()[self.len_()..self.len_()])) }<|fim▁hole|> for (i, b) in self.as_bytes().iter().enumerate() { if b != &byte { return &OsStr::from_bytes(&self.as_bytes()[i..]); } } &*self } fn split_at(&self, i: usize) -> (&OsStr, &OsStr) { (&OsStr::from_bytes(&self.as_bytes()[..i]), &OsStr::from_bytes(&self.as_bytes()[i..])) } fn len_(&self) -> usize { self.as_bytes().len() } fn split(&self, b: u8) -> OsSplit { OsSplit { sep: b, val: self.as_bytes(), pos: 0 } } } #[doc(hidden)] #[derive(Clone, Debug)] pub struct OsSplit<'a> { sep: u8, val: &'a [u8], pos: usize, } impl<'a> Iterator for OsSplit<'a> { type Item = &'a OsStr; fn next(&mut self) -> Option<&'a OsStr> { debugln!("fn=OsSplit::next;"); debugln!("OsSplit: {:?}", self); if self.pos == self.val.len() { return None; } let start = self.pos; for b in &self.val[start..] { self.pos += 1; if *b == self.sep { return Some(&OsStr::from_bytes(&self.val[start..self.pos - 1])); } } Some(&OsStr::from_bytes(&self.val[start..])) } fn size_hint(&self) -> (usize, Option<usize>) { let mut count = 0; for b in &self.val[self.pos..] { if *b == self.sep { count += 1; } } if count > 0 { return (count, Some(count)); } (0, None) } } impl<'a> DoubleEndedIterator for OsSplit<'a> { fn next_back(&mut self) -> Option<&'a OsStr> { if self.pos == 0 { return None; } let start = self.pos; for b in self.val[..self.pos].iter().rev() { self.pos -= 1; if *b == self.sep { return Some(&OsStr::from_bytes(&self.val[self.pos + 1..start])); } } Some(&OsStr::from_bytes(&self.val[..start])) } }<|fim▁end|>
fn trim_left_matches(&self, byte: u8) -> &OsStr {
<|file_name|>definitions.rs<|end_file_name|><|fim▁begin|>// Copyright 2017 Google 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 // // https://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. use rustc_hir; use rustc_hir::intravisit; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::symbol::Symbol; #[derive(Copy, Clone)] pub(crate) struct RerastDefinitions<'tcx> { pub(crate) statements: ty::Ty<'tcx>, pub(crate) expr_rule_marker: ty::Ty<'tcx>, pub(crate) pattern_rule_marker: ty::Ty<'tcx>, pub(crate) type_rule_marker: ty::Ty<'tcx>, pub(crate) trait_ref_rule_marker: ty::Ty<'tcx>, pub(crate) search_symbol: Symbol, pub(crate) replace_symbol: Symbol, } // Visits the code in the rerast module, finding definitions we care about for later use. pub(crate) struct RerastDefinitionsFinder<'tcx> {<|fim▁hole|> rerast_types_symbol: Symbol, inside_rerast_mod: bool, definitions: Option<RerastDefinitions<'tcx>>, } impl<'tcx> RerastDefinitionsFinder<'tcx> { /// Finds rerast's internal definitions. Returns none if they cannot be found. This happens for /// example if the root source file has a #![cfg(feature = "something")] where the "something" /// feature is not enabled. pub(crate) fn find_definitions( tcx: TyCtxt<'tcx>, krate: &'tcx rustc_hir::Crate, ) -> Option<RerastDefinitions<'tcx>> { let mut finder = RerastDefinitionsFinder { tcx, rerast_mod_symbol: Symbol::intern(super::RERAST_INTERNAL_MOD_NAME), rerast_types_symbol: Symbol::intern("rerast_types"), inside_rerast_mod: false, definitions: None, }; intravisit::walk_crate(&mut finder, krate); finder.definitions } } // This would be a little easier if there were a way to find functions by name. There's probably // something I've missed, but so far I haven't found one. impl<'tcx> intravisit::Visitor<'tcx> for RerastDefinitionsFinder<'tcx> { type Map = rustc_middle::hir::map::Map<'tcx>; fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> { intravisit::NestedVisitorMap::All(self.tcx.hir()) } fn visit_item(&mut self, item: &'tcx rustc_hir::Item) { if self.inside_rerast_mod { intravisit::walk_item(self, item); } else if let rustc_hir::ItemKind::Mod(_) = item.kind { if item.ident.name == self.rerast_mod_symbol { self.inside_rerast_mod = true; intravisit::walk_item(self, item); self.inside_rerast_mod = false; } } } fn visit_body(&mut self, body: &'tcx rustc_hir::Body) { let fn_id = self.tcx.hir().body_owner_def_id(body.id()); if self.tcx.item_name(fn_id.to_def_id()) == self.rerast_types_symbol { let tables = self.tcx.typeck_tables_of(fn_id); let mut types = body.params.iter().map(|arg| tables.node_type(arg.hir_id)); self.definitions = Some(RerastDefinitions { statements: types .next() .expect("Internal error - missing type: statements"), expr_rule_marker: types .next() .expect("Internal error - missing type: expr_rule_marker"), pattern_rule_marker: types .next() .expect("Internal error - missing type: pattern_rule_marker"), type_rule_marker: types .next() .expect("Internal error - missing type: type_rule_marker"), trait_ref_rule_marker: types .next() .expect("Internal error - missing type: trait_ref_rule_marker"), search_symbol: Symbol::intern("Search"), replace_symbol: Symbol::intern("Replace"), }) } } }<|fim▁end|>
tcx: TyCtxt<'tcx>, rerast_mod_symbol: Symbol,
<|file_name|>PcapTimeline.py<|end_file_name|><|fim▁begin|>from scapy.all import * import plotly from datetime import datetime import pandas as pd #Read the packets from file packets=rdpcap('mypcap.pcap') #lists to hold packetinfo pktBytes=[] pktTimes=[] #Read each packet and append to the lists for pkt in packets: if IP in pkt: try: pktBytes.append(pkt[IP].len) pktTime=datetime.fromtimestamp(pkt.time) pktTimes.append(pktTime.strftime("%Y-%m-%d %H:%M:%S.%f")) except: pass # convert list to series bytes=pd.Series(pktBytes).astype(int) times=pd.to_datetime(pd.Series(pktTimes).astype(str), errors='coerce') #Create the dateframe df=pd.DataFrame({"Bytes": bytes, "Times":times}) #Set the date to a timestamp df=df.set_index('Times') df2=df.resample('2S').sum() print(df2) #Create the graph <|fim▁hole|> xaxis=dict(title="Time"), yaxis=dict(title="Bytes"))}) Output<|fim▁end|>
plotly.offline.plot({ "data":[plotly.graph_objs.Scatter(x=df2.index, y=df2['Bytes'])], "layout":plotly.graph_objs.Layout(title="Bytes over Time ",
<|file_name|>forms.py<|end_file_name|><|fim▁begin|># # farmwork/forms.py # from django import forms from django.utils.text import slugify from .models import Farmwork # ======================================================== # FARMWORK FORM # ======================================================== class FarmworkForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(FarmworkForm, self).__init__(*args, **kwargs) class Meta: model = Farmwork fields = [ 'job_role', 'job_fruit', 'job_pay', 'job_pay_type', 'job_start_date', 'job_duration', 'job_duration_type', 'job_description', 'con_first_name', 'con_surname', 'con_number', 'con_email', 'con_description', 'acc_variety', 'acc_price', 'acc_price_type', 'acc_description', 'loc_street_address', 'loc_city', 'loc_state', 'loc_post_code', ] # -- # AUTO GENERATE SLUG ON SAVE # Credit: https://keyerror.com/blog/automatically-generating-unique-slugs-in-django # --<|fim▁hole|> if self.instance.pk: return super(FarmworkForm, self).save() instance = super(FarmworkForm, self).save(commit=False) instance.slug = slugify(instance.get_job_fruit_display() + '-' + instance.get_job_role_display() + '-in-' + instance.loc_city) instance.save() return instance<|fim▁end|>
def save(self):
<|file_name|>test_echo_server.rs<|end_file_name|><|fim▁begin|>use mio::*; use mio::tcp::*; use bytes::{Buf, ByteBuf, MutByteBuf, SliceBuf}; use mio::util::Slab; use std::io; use super::localhost; const SERVER: Token = Token(0); const CLIENT: Token = Token(1); struct EchoConn { sock: TcpStream, buf: Option<ByteBuf>, mut_buf: Option<MutByteBuf>, token: Option<Token>, interest: EventSet } impl EchoConn { fn new(sock: TcpStream) -> EchoConn { EchoConn { sock: sock, buf: None, mut_buf: Some(ByteBuf::mut_with_capacity(2048)), token: None, interest: EventSet::hup() } } fn writable(&mut self, event_loop: &mut EventLoop<Echo>) -> io::Result<()> { let mut buf = self.buf.take().unwrap(); match self.sock.try_write_buf(&mut buf) { Ok(None) => { debug!("client flushing buf; WOULDBLOCK"); self.buf = Some(buf); self.interest.insert(EventSet::writable()); } Ok(Some(r)) => { debug!("CONN : we wrote {} bytes!", r); self.mut_buf = Some(buf.flip()); self.interest.insert(EventSet::readable()); self.interest.remove(EventSet::writable()); } Err(e) => debug!("not implemented; client err={:?}", e), } event_loop.reregister(&self.sock, self.token.unwrap(), self.interest, PollOpt::edge() | PollOpt::oneshot()) } fn readable(&mut self, event_loop: &mut EventLoop<Echo>) -> io::Result<()> { let mut buf = self.mut_buf.take().unwrap(); <|fim▁hole|> self.mut_buf = Some(buf); } Ok(Some(r)) => { debug!("CONN : we read {} bytes!", r); // prepare to provide this to writable self.buf = Some(buf.flip()); self.interest.remove(EventSet::readable()); self.interest.insert(EventSet::writable()); } Err(e) => { debug!("not implemented; client err={:?}", e); self.interest.remove(EventSet::readable()); } }; event_loop.reregister(&self.sock, self.token.unwrap(), self.interest, PollOpt::edge()) } } struct EchoServer { sock: TcpListener, conns: Slab<EchoConn> } impl EchoServer { fn accept(&mut self, event_loop: &mut EventLoop<Echo>) -> io::Result<()> { debug!("server accepting socket"); let sock = self.sock.accept().unwrap().unwrap().0; let conn = EchoConn::new(sock,); let tok = self.conns.insert(conn) .ok().expect("could not add connection to slab"); // Register the connection self.conns[tok].token = Some(tok); event_loop.register(&self.conns[tok].sock, tok, EventSet::readable(), PollOpt::edge() | PollOpt::oneshot()) .ok().expect("could not register socket with event loop"); Ok(()) } fn conn_readable(&mut self, event_loop: &mut EventLoop<Echo>, tok: Token) -> io::Result<()> { debug!("server conn readable; tok={:?}", tok); self.conn(tok).readable(event_loop) } fn conn_writable(&mut self, event_loop: &mut EventLoop<Echo>, tok: Token) -> io::Result<()> { debug!("server conn writable; tok={:?}", tok); self.conn(tok).writable(event_loop) } fn conn<'a>(&'a mut self, tok: Token) -> &'a mut EchoConn { &mut self.conns[tok] } } struct EchoClient { sock: TcpStream, msgs: Vec<&'static str>, tx: SliceBuf<'static>, rx: SliceBuf<'static>, mut_buf: Option<MutByteBuf>, token: Token, interest: EventSet } // Sends a message and expects to receive the same exact message, one at a time impl EchoClient { fn new(sock: TcpStream, tok: Token, mut msgs: Vec<&'static str>) -> EchoClient { let curr = msgs.remove(0); EchoClient { sock: sock, msgs: msgs, tx: SliceBuf::wrap(curr.as_bytes()), rx: SliceBuf::wrap(curr.as_bytes()), mut_buf: Some(ByteBuf::mut_with_capacity(2048)), token: tok, interest: EventSet::none() } } fn readable(&mut self, event_loop: &mut EventLoop<Echo>) -> io::Result<()> { debug!("client socket readable"); let mut buf = self.mut_buf.take().unwrap(); match self.sock.try_read_buf(&mut buf) { Ok(None) => { debug!("CLIENT : spurious read wakeup"); self.mut_buf = Some(buf); } Ok(Some(r)) => { debug!("CLIENT : We read {} bytes!", r); // prepare for reading let mut buf = buf.flip(); while buf.has_remaining() { let actual = buf.read_byte().unwrap(); let expect = self.rx.read_byte().unwrap(); assert!(actual == expect, "actual={}; expect={}", actual, expect); } self.mut_buf = Some(buf.flip()); self.interest.remove(EventSet::readable()); if !self.rx.has_remaining() { self.next_msg(event_loop).unwrap(); } } Err(e) => { panic!("not implemented; client err={:?}", e); } }; event_loop.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot()) } fn writable(&mut self, event_loop: &mut EventLoop<Echo>) -> io::Result<()> { debug!("client socket writable"); match self.sock.try_write_buf(&mut self.tx) { Ok(None) => { debug!("client flushing buf; WOULDBLOCK"); self.interest.insert(EventSet::writable()); } Ok(Some(r)) => { debug!("CLIENT : we wrote {} bytes!", r); self.interest.insert(EventSet::readable()); self.interest.remove(EventSet::writable()); } Err(e) => debug!("not implemented; client err={:?}", e) } event_loop.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot()) } fn next_msg(&mut self, event_loop: &mut EventLoop<Echo>) -> io::Result<()> { if self.msgs.is_empty() { event_loop.shutdown(); return Ok(()); } let curr = self.msgs.remove(0); debug!("client prepping next message"); self.tx = SliceBuf::wrap(curr.as_bytes()); self.rx = SliceBuf::wrap(curr.as_bytes()); self.interest.insert(EventSet::writable()); event_loop.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot()) } } struct Echo { server: EchoServer, client: EchoClient, } impl Echo { fn new(srv: TcpListener, client: TcpStream, msgs: Vec<&'static str>) -> Echo { Echo { server: EchoServer { sock: srv, conns: Slab::new_starting_at(Token(2), 128) }, client: EchoClient::new(client, CLIENT, msgs) } } } impl Handler for Echo { type Timeout = usize; type Message = (); fn ready(&mut self, event_loop: &mut EventLoop<Echo>, token: Token, events: EventSet) { debug!("ready {:?} {:?}", token, events); if events.is_readable() { match token { SERVER => self.server.accept(event_loop).unwrap(), CLIENT => self.client.readable(event_loop).unwrap(), i => self.server.conn_readable(event_loop, i).unwrap() } } if events.is_writable() { match token { SERVER => panic!("received writable for token 0"), CLIENT => self.client.writable(event_loop).unwrap(), _ => self.server.conn_writable(event_loop, token).unwrap() }; } } } #[test] pub fn test_echo_server() { debug!("Starting TEST_ECHO_SERVER"); let mut event_loop = EventLoop::new().unwrap(); let addr = localhost(); let srv = TcpListener::bind(&addr).unwrap(); info!("listen for connections"); event_loop.register(&srv, SERVER, EventSet::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); let sock = TcpStream::connect(&addr).unwrap(); // Connect to the server event_loop.register(&sock, CLIENT, EventSet::writable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); // Start the event loop event_loop.run(&mut Echo::new(srv, sock, vec!["foo", "bar"])).unwrap(); }<|fim▁end|>
match self.sock.try_read_buf(&mut buf) { Ok(None) => { debug!("CONN : spurious read wakeup");
<|file_name|>Main.cpp<|end_file_name|><|fim▁begin|>/*============================================================================= Copyright (c) 2002-2003 Joel de Guzman http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ //////////////////////////////////////////////////////////////////////////// // // Full calculator example demonstrating Phoenix // This is discussed in the "Closures" chapter in the Spirit User's Guide. // // [ JDG 6/29/2002 ] // //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <boost/spirit/core.hpp> #include <boost/spirit/attribute.hpp> #include <boost/spirit/phoenix/functions.hpp> #include <iostream> #include <string> #include "Main.h" //#include "bigfp.h" //////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; using namespace phoenix; //////////////////////////////////////////////////////////////////////////// <|fim▁hole|>// to the calculator grammar self.val closure member which is // then visible outside the grammar (i.e. since self.val is the // member1 of the closure, it becomes the attribute passed by // the calculator to an attached semantic action. See the // driver code that uses the calculator below). // //////////////////////////////////////////////////////////////////////////// struct calc_closure : boost::spirit::closure<calc_closure, double> { member1 val; }; struct pow_ { template <typename X, typename Y> struct result { typedef X type; }; template <typename X, typename Y> X operator()(X x, Y y) const { using namespace std; return pow(x, y); } }; // Notice how power(x, y) is lazily implemented using Phoenix function. function<pow_> power; struct calculator : public grammar<calculator, calc_closure::context_t> { template <typename ScannerT> struct definition { definition(calculator const& self) { top = expression[self.val = arg1]; expression = term[expression.val = arg1] >> *( ('+' >> term[expression.val += arg1]) | ('-' >> term[expression.val -= arg1]) ) ; term = factor[term.val = arg1] >> *( ('*' >> factor[term.val *= arg1]) | ('/' >> factor[term.val /= arg1]) ) ; factor = ureal_p[factor.val = arg1] | '(' >> expression[factor.val = arg1] >> ')' | ('-' >> factor[factor.val = -arg1]) | ('+' >> factor[factor.val = arg1]) ; } // const uint_parser<bigint, 10, 1, -1> bigint_parser; typedef rule<ScannerT, calc_closure::context_t> rule_t; rule_t expression, term, factor; rule<ScannerT> top; rule<ScannerT> const& start() const { return top; } }; }; bool DoCalculation(const TCHAR* str, double& result) { // Our parser calculator calc; double n = 0; parse_info<const wchar_t *> info = parse(str, calc[var(n) = arg1], space_p); if (info.full) { result = n; return true; } return false; }<|fim▁end|>
// // Our calculator grammar using phoenix to do the semantics // // Note: The top rule propagates the expression result (value) upwards
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.shortcuts import render, get_object_or_404 # import the custom context processor from vehicles.context_processor import global_context_processor from vehicles.models import Vehicle, VehicleMake, Category from settings.models import SliderImage from django.core.paginator import Paginator, InvalidPage, EmptyPage from dynamic_preferences.registries import global_preferences_registry def home_page(request): # instanciate a manager for global preferences global_preferences = global_preferences_registry.manager() MAX_VEHICLES_TO_SHOW = global_preferences['homepage__number_of_vehicles'] MAX_CATEGORIES_TO_SHOW = 4 # get list of slider objects sliders = SliderImage.objects.all() # get categories to show on homepage top_categories = Category.objects.get_home_page_categories() if top_categories: top_categories = top_categories[:MAX_CATEGORIES_TO_SHOW] # get recently added vehicles top_vehicles = Vehicle.objects.all().order_by( '-timestamp').prefetch_related('images') if top_vehicles: top_vehicles = top_vehicles[:MAX_VEHICLES_TO_SHOW] context = global_context_processor(locals()) return render(request, "home_page.html", context) def exports_page(request): context = global_context_processor(locals()) return render(request, "exports_page.html", context) def how_to_buy(request): context = global_context_processor(locals()) return render(request, "how_to_buy.html", context) def category_page(request, slug): # check if make slug parameter is passed into the url vehicle_make_slug = request.GET.get('make', None) # get category by slug category = Category.objects.get_category_by_slug(slug) # get all the vehicles by the category and make (if provided) if vehicle_make_slug: # get make by slug make = VehicleMake.objects.get_make_by_slug(vehicle_make_slug) if category: vehicles_list = Vehicle.objects.get_vehicles_by_category_and_make( category, make ).prefetch_related('images') else: vehicles_list = Vehicle.objects.get_vehicles_by_make( make ).prefetch_related('images') else: # if category is not found then get all of the vehicles if category: vehicles_list = Vehicle.objects.get_vehicles_by_category( category ).prefetch_related('images') else: vehicles_list = Vehicle.objects.all().prefetch_related('images') # paginate vehicle list for 10 items per page paginator = Paginator(vehicles_list, 16) try: page = int(request.GET.get("page", '1')) except ValueError: page = 1 try: vehicles = paginator.page(page) except (InvalidPage, EmptyPage): vehicles = paginator.page(paginator.num_pages) makes = get_makes_in_category(category) context = global_context_processor(locals()) return render(request, "categories_page.html", context) <|fim▁hole|>def vehicle_detail_page(request, category_slug, vehicle_id, vehicle_slug): # get vehicle details by vehicle_id vehicle = get_object_or_404(Vehicle, id=vehicle_id) related_vehicles = Vehicle.objects.get_vehicles_by_category( vehicle.category) return render(request, "detail_page.html", global_context_processor(locals())) def get_makes_in_category(category): makes_in_category = [] # get all the vehicle objects by category vehicles_in_category = Vehicle.objects.get_vehicles_by_category( category=category) for vehicle in vehicles_in_category: makes_in_category.append(vehicle.make) # remove duplicate makes from the list makes_in_category = list(set(makes_in_category)) makes_in_category = sorted(makes_in_category, key=lambda x: x.v_make) return makes_in_category<|fim▁end|>
<|file_name|>zmqrpc.py<|end_file_name|><|fim▁begin|>import traceback from datetime import datetime from itertools import count import zmq def serve(procs, port=None, addr='tcp://*', context=None, debug=False): """Make some procedures available for remote calls via ØMQ.""" if context is None: context = zmq.Context.instance() with context.socket(zmq.REP) as socket: if port is None: port = socket.bind_to_random_port(addr) else: socket.bind('{}:{}'.format(addr, port))<|fim▁hole|> for i in count(1): idle = datetime.now() print('{}: waiting for request #{}...'.format(idle, i)) message = socket.poll() start = datetime.now() print('{}: received request #{} after {}' .format(start, i, start - idle)) try: request = socket.recv_json() name, *args = request result = procs[name](*args) reply = {'result': result} print(reply) socket.send_json(reply) except Exception as exc: if debug: traceback.print_exc() message = '{}: {}'.format(exc.__class__.__name__, exc) reply = {'error': message} print(reply) socket.send_json(reply) end = datetime.now() print('{}: replied to #{} after {}' .format(end, i, end - start)) if __name__ == '__main__': data = {} procs = { 'GET': data.__getitem__, 'SET': data.__setitem__, 'DEL': data.__delitem__, } serve(procs, 6379) # Look Ma, Redis!<|fim▁end|>
print('Serving at {}:{}'.format(addr, port)) print('sending and receiving JSON')
<|file_name|>module.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- <|fim▁hole|># # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This weboob module is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this weboob module. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from weboob.capabilities.bank import CapBankWealth, AccountNotFound, Account from weboob.capabilities.base import find_object from weboob.capabilities.profile import CapProfile from weboob.tools.backend import Module, BackendConfig from weboob.tools.value import ValueBackendPassword, Value from .bred import BredBrowser from .dispobank import DispoBankBrowser __all__ = ['BredModule'] class BredModule(Module, CapBankWealth, CapProfile): NAME = 'bred' MAINTAINER = u'Romain Bignon' EMAIL = '[email protected]' VERSION = '2.1' DESCRIPTION = u'Bred' LICENSE = 'LGPLv3+' CONFIG = BackendConfig( ValueBackendPassword('login', label='Identifiant', masked=False), ValueBackendPassword('password', label='Mot de passe'), Value('website', label="Site d'accès", default='bred', choices={'bred': 'BRED', 'dispobank': 'DispoBank'}), Value('accnum', label='Numéro du compte bancaire (optionnel)', default='', masked=False), ) BROWSERS = { 'bred': BredBrowser, 'dispobank': DispoBankBrowser, } def create_default_browser(self): self.BROWSER = self.BROWSERS[self.config['website'].get()] return self.create_browser( self.config['accnum'].get().replace(' ', '').zfill(11), self.config['login'].get(), self.config['password'].get(), weboob=self.weboob, ) def iter_accounts(self): return self.browser.get_accounts_list() def get_account(self, _id): return find_object(self.browser.get_accounts_list(), id=_id, error=AccountNotFound) def iter_history(self, account): return self.browser.get_history(account) def iter_coming(self, account): return self.browser.get_history(account, coming=True) def iter_investment(self, account): return self.browser.get_investment(account) def get_profile(self): return self.browser.get_profile() def fill_account(self, account, fields): if self.config['website'].get() != 'bred': return self.browser.fill_account(account, fields) OBJECTS = { Account: fill_account, }<|fim▁end|>
# Copyright(C) 2012-2014 Romain Bignon # # This file is part of a weboob module.
<|file_name|>modal.js<|end_file_name|><|fim▁begin|>/** * @ngdoc service * @name $ionicModal * @module ionic * @codepen gblny * @description * * Related: {@link ionic.controller:ionicModal ionicModal controller}. * * The Modal is a content pane that can go over the user's main view * temporarily. Usually used for making a choice or editing an item. * * Put the content of the modal inside of an `<ion-modal-view>` element. * * **Notes:** * - A modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating * scope, passing in itself as an event argument. Both the modal.removed and modal.hidden events are * called when the modal is removed. * * - This example assumes your modal is in your main index file or another template file. If it is in its own * template file, remove the script tags and call it by file name. * * @usage * ```html * <script id="my-modal.html" type="text/ng-template"> * <ion-modal-view> * <ion-header-bar> * <h1 class="title">My Modal title</h1> * </ion-header-bar> * <ion-content> * Hello! * </ion-content> * </ion-modal-view> * </script> * ``` * ```js * angular.module('testApp', ['ionic']) * .controller('MyController', function($scope, $ionicModal) { * $ionicModal.fromTemplateUrl('my-modal.html', { * scope: $scope, * animation: 'slide-in-up' * }).then(function(modal) { * $scope.modal = modal; * }); * $scope.openModal = function() { * $scope.modal.show(); * }; * $scope.closeModal = function() { * $scope.modal.hide(); * }; * // Cleanup the modal when we're done with it! * $scope.$on('$destroy', function() { * $scope.modal.remove(); * }); * // Execute action on hide modal * $scope.$on('modal.hidden', function() { * // Execute action * }); * // Execute action on remove modal * $scope.$on('modal.removed', function() { * // Execute action * }); * }); * ``` */ IonicModule .factory('$ionicModal', [ '$rootScope', '$ionicBody', '$compile', '$timeout', '$ionicPlatform', '$ionicTemplateLoader', '$$q', '$log', '$ionicClickBlock', '$window', 'IONIC_BACK_PRIORITY', function($rootScope, $ionicBody, $compile, $timeout, $ionicPlatform, $ionicTemplateLoader, $$q, $log, $ionicClickBlock, $window, IONIC_BACK_PRIORITY) { /** * @ngdoc controller * @name ionicModal * @module ionic * @description * Instantiated by the {@link ionic.service:$ionicModal} service. * * Be sure to call [remove()](#remove) when you are done with each modal * to clean it up and avoid memory leaks. * * Note: a modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating * scope, passing in itself as an event argument. Note: both modal.removed and modal.hidden are * called when the modal is removed. */ var ModalView = ionic.views.Modal.inherit({ /** * @ngdoc method * @name ionicModal#initialize * @description Creates a new modal controller instance. * @param {object} options An options object with the following properties: * - `{object=}` `scope` The scope to be a child of. * Default: creates a child of $rootScope. * - `{string=}` `animation` The animation to show & hide with. * Default: 'slide-in-up' * - `{boolean=}` `focusFirstInput` Whether to autofocus the first input of * the modal when shown. Will only show the keyboard on iOS, to force the keyboard to show * on Android, please use the [Ionic keyboard plugin](https://github.com/driftyco/ionic-plugin-keyboard#keyboardshow). * Default: false. * - `{boolean=}` `backdropClickToClose` Whether to close the modal on clicking the backdrop. * Default: true. * - `{boolean=}` `hardwareBackButtonClose` Whether the modal can be closed using the hardware * back button on Android and similar devices. Default: true. */ initialize: function(opts) { ionic.views.Modal.prototype.initialize.call(this, opts); this.animation = opts.animation || 'slide-in-up'; }, /** * @ngdoc method * @name ionicModal#show * @description Show this modal instance. * @returns {promise} A promise which is resolved when the modal is finished animating in. */ show: function(target) { var self = this; if (self.scope.$$destroyed) { $log.error('Cannot call ' + self.viewType + '.show() after remove(). Please create a new ' + self.viewType + ' instance.'); return $$q.when(); } // on iOS, clicks will sometimes bleed through/ghost click on underlying // elements $ionicClickBlock.show(600); stack.add(self); var modalEl = jqLite(self.modalEl); self.el.classList.remove('hide'); $timeout(function() {<|fim▁hole|> if (!self._isShown) return; $ionicBody.addClass(self.viewType + '-open'); }, 400, false); if (!self.el.parentElement) { modalEl.addClass(self.animation); $ionicBody.append(self.el); } // if modal was closed while the keyboard was up, reset scroll view on // next show since we can only resize it once it's visible var scrollCtrl = modalEl.data('$$ionicScrollController'); scrollCtrl && scrollCtrl.resize(); if (target && self.positionView) { self.positionView(target, modalEl); // set up a listener for in case the window size changes self._onWindowResize = function() { if (self._isShown) self.positionView(target, modalEl); }; ionic.on('resize', self._onWindowResize, window); } modalEl.addClass('ng-enter active') .removeClass('ng-leave ng-leave-active'); self._isShown = true; self._deregisterBackButton = $ionicPlatform.registerBackButtonAction( self.hardwareBackButtonClose ? angular.bind(self, self.hide) : noop, IONIC_BACK_PRIORITY.modal ); ionic.views.Modal.prototype.show.call(self); $timeout(function() { if (!self._isShown) return; modalEl.addClass('ng-enter-active'); ionic.trigger('resize'); self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.shown', self); self.el.classList.add('active'); self.scope.$broadcast('$ionicHeader.align'); self.scope.$broadcast('$ionicFooter.align'); }, 20); return $timeout(function() { if (!self._isShown) return; self.$el.on('touchmove', function(e) { //Don't allow scrolling while open by dragging on backdrop var isInScroll = ionic.DomUtil.getParentOrSelfWithClass(e.target, 'scroll'); if (!isInScroll) { e.preventDefault(); } }); //After animating in, allow hide on backdrop click self.$el.on('click', function(e) { if (self.backdropClickToClose && e.target === self.el && stack.isHighest(self)) { self.hide(); } }); }, 400); }, /** * @ngdoc method * @name ionicModal#hide * @description Hide this modal instance. * @returns {promise} A promise which is resolved when the modal is finished animating out. */ hide: function() { var self = this; var modalEl = jqLite(self.modalEl); // on iOS, clicks will sometimes bleed through/ghost click on underlying // elements $ionicClickBlock.show(600); stack.remove(self); self.el.classList.remove('active'); modalEl.addClass('ng-leave'); $timeout(function() { if (self._isShown) return; modalEl.addClass('ng-leave-active') .removeClass('ng-enter ng-enter-active active'); }, 20, false); self.$el.off('click'); self._isShown = false; self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.hidden', self); self._deregisterBackButton && self._deregisterBackButton(); ionic.views.Modal.prototype.hide.call(self); // clean up event listeners if (self.positionView) { ionic.off('resize', self._onWindowResize, window); } return $timeout(function() { $ionicBody.removeClass(self.viewType + '-open'); self.el.classList.add('hide'); }, self.hideDelay || 320); }, /** * @ngdoc method * @name ionicModal#remove * @description Remove this modal instance from the DOM and clean up. * @returns {promise} A promise which is resolved when the modal is finished animating out. */ remove: function() { var self = this; self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.removed', self); return self.hide().then(function() { self.scope.$destroy(); self.$el.remove(); }); }, /** * @ngdoc method * @name ionicModal#isShown * @returns boolean Whether this modal is currently shown. */ isShown: function() { return !!this._isShown; } }); var createModal = function(templateString, options) { // Create a new scope for the modal var scope = options.scope && options.scope.$new() || $rootScope.$new(true); options.viewType = options.viewType || 'modal'; extend(scope, { $hasHeader: false, $hasSubheader: false, $hasFooter: false, $hasSubfooter: false, $hasTabs: false, $hasTabsTop: false }); // Compile the template var element = $compile('<ion-' + options.viewType + '>' + templateString + '</ion-' + options.viewType + '>')(scope); options.$el = element; options.el = element[0]; options.modalEl = options.el.querySelector('.' + options.viewType); var modal = new ModalView(options); modal.scope = scope; // If this wasn't a defined scope, we can assign the viewType to the isolated scope // we created if (!options.scope) { scope[ options.viewType ] = modal; } return modal; }; var modalStack = []; var stack = { add: function(modal) { modalStack.push(modal); }, remove: function(modal) { var index = modalStack.indexOf(modal); if (index > -1 && index < modalStack.length) { modalStack.splice(index, 1); } }, isHighest: function(modal) { var index = modalStack.indexOf(modal); return (index > -1 && index === modalStack.length - 1); } }; return { /** * @ngdoc method * @name $ionicModal#fromTemplate * @param {string} templateString The template string to use as the modal's * content. * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method. * @returns {object} An instance of an {@link ionic.controller:ionicModal} * controller. */ fromTemplate: function(templateString, options) { var modal = createModal(templateString, options || {}); return modal; }, /** * @ngdoc method * @name $ionicModal#fromTemplateUrl * @param {string} templateUrl The url to load the template from. * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method. * options object. * @returns {promise} A promise that will be resolved with an instance of * an {@link ionic.controller:ionicModal} controller. */ fromTemplateUrl: function(url, options, _) { var cb; //Deprecated: allow a callback as second parameter. Now we return a promise. if (angular.isFunction(options)) { cb = options; options = _; } return $ionicTemplateLoader.load(url).then(function(templateString) { var modal = createModal(templateString, options || {}); cb && cb(modal); return modal; }); }, stack: stack }; }]);<|fim▁end|>
<|file_name|>TemplateService.java<|end_file_name|><|fim▁begin|>/* * IIIFProducer * Copyright (C) 2017 Leipzig University Library <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package de.ubleipzig.iiifproducer.template; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import de.ubleipzig.iiif.vocabulary.IIIFEnum; /** * TemplateService. * * @author christopher-johnson */ @JsonPropertyOrder({"@context", "@id", "profile"}) public class TemplateService { @JsonProperty("@context") private String context = IIIFEnum.IMAGE_CONTEXT.IRIString(); @JsonProperty("@id") private String id; @JsonProperty private String profile = IIIFEnum.SERVICE_PROFILE.IRIString(); /** * @param id String */ public TemplateService(final String id) {<|fim▁hole|><|fim▁end|>
this.id = id; } }
<|file_name|>main.py<|end_file_name|><|fim▁begin|>import sys import argparse import time sys.path.append('./bin/moabc') import optimizer #引数の処理 #parserの初期化 parser = argparse.ArgumentParser(description='This script optimizes bayesian network graph structure by MOABC') #強化成功率表 parser.add_argument("infile_pt", type=str) #一回の強化費用 parser.add_argument("-pg","--pricegrind", type=int) #強化シミュレータの実行回数<|fim▁hole|># OK: test, ./test # NG: test/, ./test/ parser.add_argument("out_dir", type=str) #学習中の結果の保存 group_sp = parser.add_mutually_exclusive_group() group_sp.add_argument('-sp', '--saveprogress', action='store_true') group_sp.add_argument('-n-sp', '--no-saveprogress', action='store_false') parser.set_defaults(saveprogress=False) #並列化のプロセス数 parser.add_argument("-np","--num_proc", type=int, default=1) #画像出力の有無 # sshログインとかだと無理なので、Falseを入れる group_wi = parser.add_mutually_exclusive_group() group_wi.add_argument('-wi', '--withimage', action='store_true') group_wi.add_argument('-n-wi', '--no-with_image', action='store_false') parser.set_defaults(withimage=True) #蜂の数 parser.add_argument('-me', '--m_employed', type=int, help='収穫蜂の数', default=40) parser.add_argument('-mo', '--m_onlooker',type=int, help='追従蜂の数', default=40) parser.add_argument('-li', '--limit',type=int, help='偵察蜂の閾値', default=3) #ループ数 parser.add_argument('-n', type=int, help='ループ数', default=50) #ALPHA parser.add_argument('-a', '--alpha', type=float, help='ALPHAの値', default=1) #変数のparse # 下のやり方でdictになるっぽい args = vars(parser.parse_args()) print("parsed argments from argparse\n%s\n" % str(args)) #出力先ディレクトリ out_dir = args['out_dir'] #実行中の結果保存 save_progress = args['saveprogress'] #インスタンスの作成 infile_pt = args['infile_pt'] input_price_grind = args['pricegrind'] op = optimizer.MOABC(infile_pt, input_price_grind) #ハイパーパラメータの設定 op.M_employed = args['m_employed'] op.M_onlooker = args['m_onlooker'] op.LIMIT = args['limit'] op.N = args['n'] op.weight_h = args['alpha'] op.proc = args['num_proc'] op.num_average = args['num_average'] #パラメータを適用 op.gen.calculate_weights() #学習の処理 dir_save_progress = '' if save_progress: dir_save_progress = out_dir start = time.time() op.learn(out_dirname=dir_save_progress) end = time.time() #経過時間の出力 str_time = "time: ", "{0}".format(end - start) print(str_time) f = open('%s/time.log' % out_dir, 'w') f.writelines(str_time) f.close() #学習結果の出力 op.save_result(out_dir, prefix='total', with_image=args['withimage'])<|fim▁end|>
parser.add_argument("-na","--num_average", type=int, default=100) #結果の出力先 # 最後のスラッシュいらない
<|file_name|>ParallelCriterion.py<|end_file_name|><|fim▁begin|>import torch from .Criterion import Criterion from .utils import recursiveResizeAs, recursiveFill, recursiveAdd class ParallelCriterion(Criterion): def __init__(self, repeatTarget=False): super(ParallelCriterion, self).__init__() self.criterions = [] self.weights = [] self.gradInput = [] self.repeatTarget = repeatTarget def add(self, criterion, weight=1): self.criterions.append(criterion) self.weights.append(weight) return self def updateOutput(self, input, target): self.output = 0 for i, criterion in enumerate(self.criterions): current_target = target if self.repeatTarget else target[i] self.output += self.weights[i] * criterion.updateOutput(input[i], current_target) <|fim▁hole|> def updateGradInput(self, input, target): self.gradInput = recursiveResizeAs(self.gradInput, input)[0] recursiveFill(self.gradInput, 0) for i, criterion in enumerate(self.criterions): current_target = target if self.repeatTarget else target[i] recursiveAdd(self.gradInput[i], self.weights[i], criterion.updateGradInput(input[i], current_target)) return self.gradInput def type(self, type=None, tensorCache=None): self.gradInput = [] return super(ParallelCriterion, self).type(type, tensorCache)<|fim▁end|>
return self.output
<|file_name|>svd-pgm-avg.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse import numpy import math class Image: def __init__(self, matrix=[[]], width=0, height=0, depth=0): self.matrix = matrix self.width = width self.height = height self.depth = depth def set_width_and_height(self, width, height): self.width = width self.height = height self.matrix = [[0 for j in xrange(height)] for i in xrange(width)] def multiply_matrices(matrixU, matrixS, matrixVt, kmin, kmax, depth, rescale=False, contrast=False): matrixScopy = matrixS.copy() # when kmax is not 0 use the provided kmax if kmax > 0: i = 0 contrast_factor = (1.0 + (1 - (math.log(kmax, 2) / 10))) for t in numpy.nditer(matrixScopy, op_flags=["readwrite"]): if i < kmin or i >= kmax: t[...] = 0 else: if contrast: t[...] = t * contrast_factor #* math.pi / 2 i += 1 # when kmax is 0 then drop eigen values less than 1.0E-14 else: for t in numpy.nditer(matrixScopy, op_flags=["readwrite"]): if round(t, 14) <= 0: t[...] = 0 # recompose the trimmed SVD matrices back into matrix matrixComposed matrixComposed = numpy.dot(numpy.dot(matrixU, numpy.diag(matrixScopy)), matrixVt) # attempt the handle out of range values (TODO: pull out to own function) if rescale: curMin = 0 curMax = 0 # find min and max values for n in numpy.nditer(matrixComposed): if int(round(n)) < curMin: curMin = int(round(n)) if int(round(n)) > curMax: curMax = int(round(n)) # shift values up if curMax < depth and curMin < 0: shiftVal = depth - curMax for t in numpy.nditer(matrixComposed, op_flags=["readwrite"]): t[...] = int(round(t + shiftVal)) if t > depth: t[...] = depth elif t < 0: t[...] = 0 # shift values down elif curMax > depth and curMin > 0: shiftVal = curMin for t in numpy.nditer(matrixComposed, op_flags=["readwrite"]): t[...] = int(round(t - shiftVal)) if t > depth: t[...] = depth elif t < 0: t[...] = 0 # no chance to shift, just chop (TODO: perform some sort of scaling) else: for t in numpy.nditer(matrixComposed, op_flags=["readwrite"]): t[...] = int(round(t)) if t > depth: t[...] = depth elif t < 0: t[...] = 0 if contrast: depth_limit = depth # int(depth - (depth * .01)) for t in numpy.nditer(matrixComposed, op_flags=["readwrite"]): if t < depth_limit: t[...] = 0 return matrixComposed def write_matrices_to_file(matrixU, matrixS, matrixVt, kmin, kmax, file_handle, width, height, depth, rescale=False, contrast=False):<|fim▁hole|> Keyword Arguments: matrixU -- the U portion of the SVD matrixS -- the S (sigma) portion of the SVD matrixVt -- the V transpose portion of the SVD kmin -- the minimum k value to use for compresion (ignored if kmax = 0) kmax -- the maximum kvalue to use for compresion (find optimal if zero) filename -- the file to write to (stdout if blank) width -- the image width height -- the image height depth -- the maximum grey scale value (normally 255) rescale -- True to shift resulting image into 0 < n < depth bounds """ A = multiply_matrices(matrixU, matrixS, matrixVt, kmin, kmax, depth, rescale, contrast) pixelate_count = 4 for x in xrange(1, pixelate_count): U, s, Vt = numpy.linalg.svd(A, full_matrices=True) A = multiply_matrices(U, s, Vt, kmin, kmax, depth, rescale, contrast) file_handle.write("P2\n") file_handle.write("# Generated by Stoll \n") file_handle.write(str(width)) file_handle.write(" ") file_handle.write(str(height)) file_handle.write("\n") file_handle.write(str(depth)) file_handle.write("\n") for n in numpy.nditer(A): file_handle.write(str(int(round(n)))) file_handle.write(" ") file_handle.write("\n") def read_matrix_from_file(file_handle): """ Read an ASCII PGM file and create an Image object from it """ row = 0 col = 0 rownull = True image = Image() for line in file_handle: if line[0] == '#': pass elif line[0] == 'P' and line[1] == '2': pass elif image.width == 0 and image.height == 0: x = 0 y = 0 x, y = [int(n) for n in line.split()] image.set_width_and_height(x, y) elif image.depth == 0: image.depth = int(line) else: for value in line.split(): if col >= image.width: row += 1 col = 0 # rows which are all black become all white if rownull: for x in xrange(0, image.width): image.matrix[row][x] = image.depth rownull = True image.matrix[row][col] = value if int(value) != 0: rownull = False col += 1 # columns which are all black become all white for x in xrange(0, image.width): colnull = True for y in xrange(0, image.height): if int(image.matrix[y][x]) != 0: colnull = False if colnull: for y in xrange(0, image.height): image.matrix[y][x] = image.depth return image def process_svd(source_file_a, source_file_b, destination_file, kmin, kmax, rescale, contrast): """ Read from file provided on the command line or from stdin then save uncompressed representations of the SVD compressed version """ """ imagea = read_matrix_from_file(source_file_a) Ma = numpy.asmatrix(imagea.matrix) U, s, Vt = numpy.linalg.svd(Ma, full_matrices=True) """ pixelate_count = 2 + int(kmax / 2) imagea = read_matrix_from_file(source_file_a) Ma = numpy.asmatrix(imagea.matrix) # for x in xrange(1, pixelate_count): # Ua, sa, Vta = numpy.linalg.svd(Ma, full_matrices=True) # Ma = multiply_matrices(Ua, sa, Vta, kmin, kmax, imagea.depth, rescale, contrast) Ua, sa, Vta = numpy.linalg.svd(Ma, full_matrices=True) imageb = read_matrix_from_file(source_file_b) Mb = numpy.asmatrix(imageb.matrix) for x in xrange(1, pixelate_count): Ub, sb, Vtb = numpy.linalg.svd(Mb, full_matrices=True) Mb = multiply_matrices(Ub, sb, Vtb, kmin, kmax, imageb.depth, rescale, contrast) U = Ua for (x,y), value in numpy.ndenumerate(Ua): inta = Ua[x, y] intb = Ub[x, y] #intc = ((inta * 1.618) + (intb * 0.3)) / 1.9 #intc = (inta + intb) / 2.0 #intc = ((inta * 2) + intb) / 3.0 #intc = ((inta * 3) + intb) / 4.0 #intc = ((inta * 4) + intb) / 5.0 intc = ((inta * 5) + intb) / 6.0 #intc = ((inta * 6) + intb) / 7.0 #intc = ((inta * 7) + intb) / 8.0 U[x, y] = intc s = sa for (x,), value in numpy.ndenumerate(sa): inta = sa[x] intb = sb[x] #intc = ((inta * 1.618) + (intb * 0.3)) / 1.9 #intc = (inta + intb) / 2.0 #intc = ((inta * 2) + intb) / 3.0 #intc = ((inta * 3) + intb) / 4.0 #intc = ((inta * 4) + intb) / 5.0 intc = ((inta * 5) + intb) / 6.0 #intc = ((inta * 6) + intb) / 7.0 #intc = ((inta * 7) + intb) / 8.0 s[x] = intc Vt = Vta for (x,y), value in numpy.ndenumerate(Vta): inta = Vta[x, y] intb = Vtb[x, y] #intc = ((inta * 1.618) + (intb * 0.3)) / 1.9 #intc = (inta + intb) / 2.0 #intc = ((inta * 2) + intb) / 3.0 #intc = ((inta * 3) + intb) / 4.0 #intc = ((inta * 4) + intb) / 5.0 intc = ((inta * 5) + intb) / 6.0 #intc = ((inta * 6) + intb) / 7.0 #intc = ((inta * 7) + intb) / 8.0 Vt[x, y] = intc write_matrices_to_file(U, s, Vt, kmin, kmax, destination_file, imagea.width, imagea.height, imagea.depth, rescale, contrast) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("infile1", nargs='?', help="The source ASCII PGM file", type=argparse.FileType('r'), default=sys.stdin) parser.add_argument("infile2", nargs='?', help="The source ASCII PGM file", type=argparse.FileType('r'), default=sys.stdin) parser.add_argument("outfile", nargs='?', help="The destination ASCII PGM file", type=argparse.FileType('w'), default=sys.stdout) parser.add_argument("-j", "--kmin", help="The number of high k values to exlude", type=int, default=0) parser.add_argument("-k", "--kmax", help="The number k values to use", type=int, default=0) parser.add_argument("-s", "--scale", help="Fit resulting image depth into '0 < n < depth' bounds", action="store_true") parser.add_argument("-c", "--contrast", help="Improve high contrast images", action="store_true") args = parser.parse_args() try: process_svd(args.infile1, args.infile2, args.outfile, args.kmin, args.kmax, args.scale, args.contrast) except KeyboardInterrupt: exit(0)<|fim▁end|>
""" Write a decomposed matrix to file uncompressed as it would show compressed
<|file_name|>index.js<|end_file_name|><|fim▁begin|>var eejs = require('ep_etherpad-lite/node/eejs') /* * Handle incoming delete requests from clients */ exports.handleMessage = function(hook_name, context, callback){ var Pad = require('ep_etherpad-lite/node/db/Pad.js').Pad // Firstly ignore any request that aren't about chat var isDeleteRequest = false; if(context) { if(context.message && context.message){ if(context.message.type === 'COLLABROOM'){ if(context.message.data){ if(context.message.data.type){ if(context.message.data.type === 'ep_push2delete'){ isDeleteRequest = true; } } } } } } if(!isDeleteRequest){ callback(false); return false; } <|fim▁hole|> console.log('DELETION REQUEST!') var packet = context.message.data; /*** What's available in a packet? * action -- The action IE chatPosition * padId -- The padId of the pad both authors are on ***/ if(packet.action === 'deletePad'){ var pad = new Pad(packet.padId) pad.remove(function(er) { if(er) console.warn('ep_push2delete', er) callback([null]); }) } } exports.eejsBlock_editbarMenuRight = function(hook_name, args, cb) { if(!args.renderContext.req.url.match(/^\/(p\/r\..{16})/)) { args.content = eejs.require('ep_push2delete/templates/delete_button.ejs') + args.content; } cb(); };<|fim▁end|>
<|file_name|>generated_expansion.go<|end_file_name|><|fim▁begin|>/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */<|fim▁hole|> // Code generated by client-gen. DO NOT EDIT. package v1beta1 type CustomResourceDefinitionExpansion interface{}<|fim▁end|>
<|file_name|>subsystem.go<|end_file_name|><|fim▁begin|>package subsystems // ResourceConfig is configs of resources. type ResourceConfig struct { MemoryLimit string CPUShare string CPUSet string } // SubSystem is cgourp subsystem, and path is a cgroup. type SubSystem interface { Name() string Set(path string, res *ResourceConfig) error Apply(path string, pid int) error Remove(path string) error } // Initialize a instance using subsystems. var ( SubSystemsIns = []SubSystem{ // &CpusetSubSystem{},<|fim▁hole|><|fim▁end|>
&MemorySubSystem{}, // &CpuSubSystem{}, } )
<|file_name|>decoding.rs<|end_file_name|><|fim▁begin|>// 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. #![feature(test)] extern crate parquet; extern crate rand; extern crate test; use test::Bencher; #[allow(dead_code)] #[path = "common.rs"] mod common; use common::*; use std::rc::Rc; use parquet::{ basic::*, data_type::*, decoding::*, encoding::*, memory::{ByteBufferPtr, MemTracker}, }; macro_rules! plain { ($fname:ident, $num_values:expr, $batch_size:expr, $ty:ident, $pty:expr, $gen_data_fn:expr) => { #[bench] fn $fname(bench: &mut Bencher) { let mem_tracker = Rc::new(MemTracker::new()); let mut encoder = PlainEncoder::<$ty>::new(Rc::new(col_desc(0, $pty)), mem_tracker, vec![]); let (_, values) = $gen_data_fn($num_values); encoder.put(&values[..]).expect("put() should be OK"); let buffer = encoder.flush_buffer().expect("flush_buffer() should be OK"); let decoder = PlainDecoder::<$ty>::new(0); bench_decoding(bench, $num_values, $batch_size, buffer, Box::new(decoder)); } }; } macro_rules! dict { ($fname:ident, $num_values:expr, $batch_size:expr, $ty:ident, $pty:expr, $gen_data_fn:expr) => { #[bench] fn $fname(bench: &mut Bencher) { let mem_tracker = Rc::new(MemTracker::new()); let mut encoder = DictEncoder::<$ty>::new(Rc::new(col_desc(0, $pty)), mem_tracker); let (_, values) = $gen_data_fn($num_values); encoder.put(&values[..]).expect("put() should be OK"); let mut dict_decoder = PlainDecoder::<$ty>::new(0); dict_decoder .set_data( encoder.write_dict().expect("write_dict() should be OK"), encoder.num_entries(), ) .expect("set_data() should be OK"); let buffer = encoder.flush_buffer().expect("flush_buffer() should be OK"); let mut decoder = DictDecoder::<$ty>::new(); decoder .set_dict(Box::new(dict_decoder)) .expect("set_dict() should be OK"); bench_decoding(bench, $num_values, $batch_size, buffer, Box::new(decoder)); } }; } macro_rules! delta_bit_pack { ($fname:ident, $num_values:expr, $batch_size:expr, $ty:ident, $gen_data_fn:expr) => { #[bench] fn $fname(bench: &mut Bencher) { let mut encoder = DeltaBitPackEncoder::<$ty>::new(); let (_, values) = $gen_data_fn($num_values); encoder.put(&values[..]).expect("put() should be OK"); let buffer = encoder.flush_buffer().expect("flush_buffer() should be OK"); let decoder = DeltaBitPackDecoder::<$ty>::new(); bench_decoding(bench, $num_values, $batch_size, buffer, Box::new(decoder)); } }; } fn bench_decoding<T: DataType>( bench: &mut Bencher, num_values: usize, batch_size: usize, buffer: ByteBufferPtr, mut decoder: Box<Decoder<T>>, ) { bench.bytes = buffer.len() as u64; bench.iter(|| { decoder .set_data(buffer.clone(), num_values) .expect("set_data() should be OK"); let mut values = vec![T::T::default(); batch_size]; loop { if decoder.get(&mut values[..]).expect("get() should be OK") < batch_size { break; } } }) } plain!(plain_i32_1k_32, 1024, 32, Int32Type, Type::INT32, gen_1000); plain!(plain_i32_1k_64, 1024, 64, Int32Type, Type::INT32, gen_1000); plain!( plain_i32_1k_128, 1024, 128, Int32Type, Type::INT32, gen_1000 ); plain!(plain_i32_1m_32, 1024, 32, Int32Type, Type::INT32, gen_1000); plain!(plain_i32_1m_64, 1024, 64, Int32Type, Type::INT32, gen_1000);<|fim▁hole|>plain!( plain_i32_1m_128, 1024, 128, Int32Type, Type::INT32, gen_1000 ); plain!( plain_str_1m_128, 1024, 128, ByteArrayType, Type::BYTE_ARRAY, gen_test_strs ); dict!(dict_i32_1k_32, 1024, 32, Int32Type, Type::INT32, gen_1000); dict!(dict_i32_1k_64, 1024, 64, Int32Type, Type::INT32, gen_1000); dict!(dict_i32_1k_128, 1024, 128, Int32Type, Type::INT32, gen_1000); dict!( dict_i32_1m_32, 1024 * 1024, 32, Int32Type, Type::INT32, gen_1000 ); dict!( dict_i32_1m_64, 1024 * 1024, 64, Int32Type, Type::INT32, gen_1000 ); dict!( dict_i32_1m_128, 1024 * 1024, 128, Int32Type, Type::INT32, gen_1000 ); dict!( dict_str_1m_128, 1024 * 1024, 128, ByteArrayType, Type::BYTE_ARRAY, gen_test_strs ); delta_bit_pack!(delta_bit_pack_i32_1k_32, 1024, 32, Int32Type, gen_1000); delta_bit_pack!(delta_bit_pack_i32_1k_64, 1024, 64, Int32Type, gen_1000); delta_bit_pack!(delta_bit_pack_i32_1k_128, 1024, 128, Int32Type, gen_1000); delta_bit_pack!( delta_bit_pack_i32_1m_32, 1024 * 1024, 32, Int32Type, gen_1000 ); delta_bit_pack!( delta_bit_pack_i32_1m_64, 1024 * 1024, 64, Int32Type, gen_1000 ); delta_bit_pack!( delta_bit_pack_i32_1m_128, 1024 * 1024, 128, Int32Type, gen_1000 );<|fim▁end|>
<|file_name|>sqlite1.py<|end_file_name|><|fim▁begin|>import sqlite3 import os.path import sys import random def makeDatabase(databaseName): if databaseName[-3:] != ".db": databaseName = databaseName + ".db" conn = sqlite3.connect(databaseName) conn.commit() conn.close() def listToString(list): string = "" for i in list: string += str(i)+"\t" return string[:-1] def stringToList(string): list = [str(line) for line in string.split('\t')] return list #class for connecting, inserting, and retrieving information from a sqlite3 database class SqliteDB: #connects to the database, alters its name if named incorrectly def __init__(self, databaseName): if databaseName[-3:] != ".db": databaseName = databaseName + ".db" if os.path.isfile(databaseName): self.databaseName = databaseName; self.conn = sqlite3.connect(self.databaseName) self.cursor = self.conn.cursor() else: #sees if database name is unique, so it doesn't overwrite anything sys.exit("This database does not exist, use the makeDatabase(databaseName) to create it") def createTables(self): #creates tables if they do not exist self.cursor.execute("CREATE TABLE IF NOT EXISTS students (wID text, email text, UNIQUE(wID, email) ON CONFLICT ABORT)") self.cursor.execute("CREATE TABLE IF NOT EXISTS submissions (labNumber int, wID text, URL text, metadata text, URLsToGrade text)") self.cursor.execute("CREATE TABLE IF NOT EXISTS uniqueStudentURL (labNumber int, wID text, URL text, UNIQUE(URL) ON CONFLICT ABORT)") self.cursor.execute("CREATE TABLE IF NOT EXISTS experts (labNumber int, URL text, grade text, hidden int, PRIMARY KEY(labNumber, URL, hidden))") self.cursor.execute("CREATE TABLE IF NOT EXISTS responses (labNumber int, URL text, wID text, response text, practice boolean, PRIMARY KEY(labNumber, URL, response))") self.cursor.execute("CREATE TABLE IF NOT EXISTS questions (labNumber int, questionNumber int, questionWebassignNumber int, practice boolean)") weightString = '' for i in range(6): weightString += ', weight'+str(i+1)+' num' self.cursor.execute("CREATE TABLE IF NOT EXISTS weightsBIBI (labNumber int, wID text"+weightString+", weightSum num)") self.cursor.execute("CREATE TABLE IF NOT EXISTS rubrics (labNumber int, itemIndex int, itemType text, itemValues text, graded boolean, itemPrompt text)") self.cursor.execute("CREATE TABLE IF NOT EXISTS grades(labNumber int, wID text, URL text, finalGrade number, finalGradeVector text, rawGrade number, rawGradeVector text)") ##check to see if the tables have already been created #creates columns in tables for each lab specified self.conn.commit() #adds a person into the database, works for both new users and existing ones def addEntry(self, wID, URL, labNumber, metadata = None): if self.databaseName != None and self.conn != None and self.cursor !=None: #If the student did not submit a URL (aka the inputted URL is '') if URL == '': self.cursor.execute("INSERT INTO submissions VALUES(?,?,?,?,?)", [labNumber, wID, URL,metadata,'']) #try putting the student and its URL into the uniqueStudentURL database to check if the URL is unique else: try: self.cursor.execute("INSERT INTO uniqueStudentURL VALUES (?,?,?)", [labNumber, wID, URL]) #if there is no error in inserting to a table where URL has to be unique, put it in the actual student database self.cursor.execute("INSERT INTO submissions VALUES(?,?,?,?,?)", [labNumber, wID, URL,metadata,'']) #if the try fails, that means that the URL is already in the db, duplicate URL found! except: self.cursor.execute("SELECT wID FROM uniqueStudentURL WHERE URL=?", [URL]) print "URL: " + URL + " was initially submitted by: " + self.cursor.fetchall()[0][0] URL = "DUPLICATEURL" self.cursor.execute("INSERT INTO submissions VALUES(?,?,?,?,?)", [labNumber, wID, URL,metadata,'']) self.conn.commit() def addEmail(self, wID, email): try: self.cursor.execute("INSERT INTO students VALUES (?,?,?)", [wID, email]) except: print "wID: " + wID + " or email: " + email + " already in database." #retrieves URL for a specific student and specific lab number def getURL(self, wID, labNumber): self.cursor.execute("SELECT URL FROM submissions WHERE labNumber=? AND wID=?", [labNumber, wID]) URL = self.cursor.fetchone(); if URL is not None: return (URL[0]) else: return None def addExpertURL(self, labNumber, URL, grade, hidden): self.cursor.execute("SELECT * FROM experts WHERE URL = ?", [URL]) #adds in a user if not in database already presentURL = self.cursor.fetchone() if presentURL == None: self.cursor.execute("INSERT INTO experts VALUES (?, ?, ?, ?)", [labNumber, URL, listToString(grade), hidden]) self.conn.commit() elif presentURL == URL: print "The URL " + URL + " is already in the expert database" else: sys.exit("Trying to overrite") ##find a way to make seperate expert tables for each lab, and then join them together to prevent the staggaring of grades in the excel sheet #self.cursor.execute("SELECT * FROM expert WHERE Lab1Grade") #print self.cursor.fetchall() #query = ("SELECT {0} FROM expert WHERE wID def getExpertURLs(self, labNumber): self.cursor.execute("SElECT URL, grade FROM experts where labNumber=?", [labNumber]) URLsAndGrades = {} for d in self.cursor.fetchall(): URLsAndGrades[str(d[0])] = stringToList(str(d[1])) return URLsAndGrades def finalize(self, labNumber, seed, N, MOOC=False): ##randomize the youtube URLs #for each wID #put that into the databse under the student ID self.cursor.execute("SELECT URL FROM experts WHERE labNumber=? and hidden=0", [labNumber]) expertURL = [str(d[0]) for d in self.cursor.fetchall()] # find all the hidden expert videos self.cursor.execute("SELECT URL FROM experts WHERE labNumber=? and hidden=1", [labNumber]) hiddenURL = [str(d[0]) for d in self.cursor.fetchall()] #get all the studnet URLs self.cursor.execute("SELECT URL from submissions WHERE labNumber=?", [labNumber]) data = [str(d[0]) for d in self.cursor.fetchall()] #assign the students whos videos are designated expert graded URLs to grade, and remove them from the URL pool retrieved above if len(expertURL) + N + 1 <= len(data): pseudoURL = {} for d in expertURL: #if the expertURL is not in the data list, then it is a video that is not submitted by a student this sem #semester, in which case, we skip it if d in data: self.cursor.execute("SELECT wID FROM submissions WHERE URL=?", [d]) indice = (data.index(d) + 1) % len(data) while data[indice] in expertURL or data[indice] in hiddenURL: indice = (indice + 1) % len(data) pseudoURL[d] = data[indice] data.remove(d) for d in hiddenURL: if d in data: indice = (data.index(d) + 1) % len(data) while data[indice] in expertURL or data[indice] in hiddenURL: indice = (indice + 1) % len(data) pseudoURL[d] = data[indice] data.remove(d) self.cursor.execute("SELECT wID FROM submissions WHERE labNumber=? and URL is ''", [labNumber]) noURLSubmitted = [str(d[0]) for d in self.cursor.fetchall()] wIDPseudoURL = {} if(data.count('') > 0) and not MOOC: for d in noURLSubmitted: indice = (data.index('') + 1) % len(data) while data[indice] == '': indice = (indice + 1) % len(data) wIDPseudoURL[d] = data[indice] data.remove('') else: while '' in data: data.remove('') self.cursor.execute("SELECT wID FROM submissions WHERE labNumber=? AND URL=?", [labNumber, "DUPLICATEURL"]) noURLSubmitted = [str(d[0]) for d in self.cursor.fetchall()] if(data.count("DUPLICATEURL") > 0) and not MOOC: for d in noURLSubmitted: indice = (data.index("DUPLICATEURL") + 1) % len(data) while data[indice] == "DUPLICATEURL": indice = (indice + 1) % len(data) wIDPseudoURL[d] = data[indice] data.remove("DUPLICATEURL") else: while '' in data: data.remove('') #self.cursor.execute(query) random.shuffle(data) selectFrom = data + data[:N + len(expertURL) + 1] if len(pseudoURL.keys()) > 0: # params = ("Lab" + str(labNumber) + "URLSToGrade", "Lab" + str(labNumber) + "URL") for key in pseudoURL.keys(): startIndex = selectFrom.index(pseudoURL[key]) URLSToGrade = selectFrom[startIndex: startIndex+N+1] for i in hiddenURL: URLSToGrade.append(i) random.shuffle(URLSToGrade) self.cursor.execute("UPDATE submissions SET URLsToGrade=? WHERE URL=?", [listToString(expertURL + URLSToGrade), key]) self.conn.commit() if len(wIDPseudoURL.keys()) > 0: for key in wIDPseudoURL.keys(): startIndex = selectFrom.index(wIDPseudoURL[key]) URLSToGrade = selectFrom[startIndex: startIndex+N+1] for i in hiddenURL: URLSToGrade.append(i) random.shuffle(URLSToGrade) self.cursor.execute("UPDATE submissions SET URLsToGrade=? WHERE wID=?", [listToString(expertURL + URLSToGrade), key]) self.conn.commit() if len(data) > N: for d in data: startIndex = selectFrom.index(d) URLSToGrade = selectFrom[startIndex:startIndex+N+1] for i in hiddenURL: URLSToGrade.append(i) random.shuffle(URLSToGrade) # params = ("Lab" + str(labNumber) + "URLSToGrade", "Lab" + str(labNumber) + "URL") self.cursor.execute("UPDATE submissions SET URLsToGrade=? WHERE URL=? and labNumber=?", [listToString(expertURL + URLSToGrade), d, labNumber]) self.conn.commit() def getURLsToGrade(self, wID, labNumber): self.cursor.execute("Select URLsToGrade FROM submissions WHERE wID=? and labNumber=?", [wID, labNumber]) dbExtract = self.cursor.fetchone() if dbExtract == None:<|fim▁hole|> return [i for i in stringToList(dbExtract[0])] def addGrade(self, wID, labNumber, URL, grade , practice = False): URLsToGrade = self.getURLsToGrade(wID, labNumber) if URLsToGrade != False: if URL in URLsToGrade: self.cursor.execute("INSERT INTO responses VALUES(?, ?, ?, ?, ?)", [labNumber, URL, wID, listToString(grade), practice]) self.conn.commit() else: print "wID: " + wID + " was not assigned to grade URL: " + URL else: print("wID: " + wID + " not in the submissions table") def wIDGradesSubmitted(self, wID, labNumber): URLsToGrade = self.getURLsToGrade(wID, labNumber) gradesSubmitted = {} for URL in URLsToGrade: self.cursor.execute("SElECT grade FROM grades WHERE wID = ? AND URL = ?",[wID, URL]) dbExtract = self.cursor.fetchall() #if they did not grade the URL assigned to them if dbExtract!=[]: gradesSubmitted[URL] = stringToList(str(dbExtract[0][0])) else: gradesSubmitted[URL] = None return gradesSubmitted def compareToExpert(self, wID, labNumber): expertURLsAndGrades = self.getExpertURLs(labNumber) userSubmittedGrades = self.wIDGradesSubmitted(wID, labNumber) URLsGraded = userSubmittedGrades.keys() for key in expertURLsAndGrades.keys(): if key in URLsGraded: print expertURLsAndGrades[key] print userSubmittedGrades[key] def getGrades(self, wID, labNumber): URL = self.getURL(wID, labNumber) self.cursor.execute("SELECT grade,wID FROM grades WHERE URL=?", [URL]) grades = {} for d in self.cursor.fetchall(): grades[str(d[1])] = str(d[0]) return grades def check(self, labNumber): # params = ("Lab" + str(labNumber) + "URL", "Lab" + str(labNumber) + "URLsToGrade", None) self.cursor.execute("Select URL, URLsToGrade FROM submissions WHERE URL!= ''") fetch = self.cursor.fetchall() individualURL = [str(d[0]) for d in fetch] URLList = listToString([str(d[1]) for d in fetch]) for i in range(1, len(individualURL)-1): if individualURL[i] not in stringToList(URLList[i]): print individualURL[i] return False return True if False: os.remove("test.db") makeDatabase("test.db") sqldb = SqliteDB("test.db") sqldb.createTables() sqldb.addEntry("1", "1lkjsdf", 1) sqldb.addEntry("2", "1lkjsdf", 1) sqldb.addEntry("3", "1lkjsdf", 1) sqldb.addEntry("4", "4lkjsdf", 1) # sqldb.addEntry("4a",None , 2) sqldb.addEntry("5", "5lkjsdf", 1) sqldb.addEntry("6", "6lkjsdf", 1) sqldb.addEntry("7", "7lkjsdf", 1) sqldb.getURL("1", 1) sqldb.getURL("2", 1) sqldb.addExpertURL(1, "5lkjsdf",[1, 2, 3, 4, 5, 6, 7], 0) sqldb.addExpertURL(1, "2lkjsdf", [1, 7, 3, 1, 6, 3], 0) # sqldb.addEntry("8", None, 2) sqldb.addEntry("8", '', 1) sqldb.addEntry(9, "hidden", 1) sqldb.addExpertURL(1, "hidden", [1, 2, 3], 1) print "testing below" sqldb.finalize(1, 1, 3) print sqldb.getURLsToGrade("1", 1) sqldb.addGrade("1",1, "5lkjsdf", [1, 2, 3, 4]) sqldb.addGrade("12",1, "asdf", 1) sqldb.addGrade("1", 1, "2kjla", 1) sqldb.addGrade("2", "1", "5lkjsdf", [4, 3, 2, 1]) sqldb.wIDGradesSubmitted("1", 1) sqldb.getGrades("5", 1) sqldb.getExpertURLs(1) sqldb.compareToExpert("1",1) sqldb.check(1) # sqldb.addExpert("expertVideo", 1, 1) # sqldb.addExpert("test2", 2, 2)<|fim▁end|>
return False else:
<|file_name|>fetch.rs<|end_file_name|><|fim▁begin|>use bit_set::BitSet; use byteorder::{ByteOrder, BigEndian, WriteBytesExt}; use futures::Stream; use futures::sync::{oneshot, mpsc}; use futures::{Poll, Async, Future}; use std::cmp::min; use std::fs; use std::io::{self, Read, Write, Seek, SeekFrom}; use std::sync::{Arc, Condvar, Mutex}; use tempfile::NamedTempFile; use core::channel::{Channel, ChannelData, ChannelError, ChannelHeaders}; use core::session::Session; use core::util::FileId; const CHUNK_SIZE: usize = 0x20000; pub enum AudioFile { Cached(fs::File), Streaming(AudioFileStreaming), } pub enum AudioFileOpen { Cached(Option<fs::File>), Streaming(AudioFileOpenStreaming), } pub struct AudioFileOpenStreaming { session: Session, data_rx: Option<ChannelData>, headers: ChannelHeaders, file_id: FileId, complete_tx: Option<oneshot::Sender<NamedTempFile>>, } pub struct AudioFileStreaming { read_file: fs::File, position: u64, seek: mpsc::UnboundedSender<u64>, shared: Arc<AudioFileShared>, } struct AudioFileShared { file_id: FileId, chunk_count: usize, cond: Condvar, bitmap: Mutex<BitSet>, } impl AudioFileOpenStreaming { fn finish(&mut self, size: usize) -> AudioFileStreaming { let chunk_count = (size + CHUNK_SIZE - 1) / CHUNK_SIZE; let shared = Arc::new(AudioFileShared { file_id: self.file_id, chunk_count: chunk_count, cond: Condvar::new(), bitmap: Mutex::new(BitSet::with_capacity(chunk_count)), }); let mut write_file = NamedTempFile::new().unwrap(); write_file.set_len(size as u64).unwrap(); write_file.seek(SeekFrom::Start(0)).unwrap(); let read_file = write_file.reopen().unwrap(); let data_rx = self.data_rx.take().unwrap(); let complete_tx = self.complete_tx.take().unwrap(); let (seek_tx, seek_rx) = mpsc::unbounded(); let fetcher = AudioFileFetch::new( self.session.clone(), shared.clone(), data_rx, write_file, seek_rx, complete_tx ); self.session.spawn(move |_| fetcher); AudioFileStreaming { read_file: read_file, position: 0, seek: seek_tx, shared: shared, } } } impl Future for AudioFileOpen { type Item = AudioFile; type Error = ChannelError; fn poll(&mut self) -> Poll<AudioFile, ChannelError> { match *self { AudioFileOpen::Streaming(ref mut open) => { let file = try_ready!(open.poll()); Ok(Async::Ready(AudioFile::Streaming(file))) } AudioFileOpen::Cached(ref mut file) => { let file = file.take().unwrap(); Ok(Async::Ready(AudioFile::Cached(file))) } } } } impl Future for AudioFileOpenStreaming { type Item = AudioFileStreaming; type Error = ChannelError; fn poll(&mut self) -> Poll<AudioFileStreaming, ChannelError> { loop { let (id, data) = try_ready!(self.headers.poll()).unwrap(); if id == 0x3 { let size = BigEndian::read_u32(&data) as usize * 4; let file = self.finish(size); return Ok(Async::Ready(file)); } } } } impl AudioFile { pub fn open(session: &Session, file_id: FileId) -> AudioFileOpen { let cache = session.cache().cloned(); if let Some(file) = cache.as_ref().and_then(|cache| cache.file(file_id)) { debug!("File {} already in cache", file_id); return AudioFileOpen::Cached(Some(file)); } debug!("Downloading file {}", file_id); let (complete_tx, complete_rx) = oneshot::channel(); let (headers, data) = request_chunk(session, file_id, 0).split(); let open = AudioFileOpenStreaming { session: session.clone(), file_id: file_id, headers: headers, data_rx: Some(data), complete_tx: Some(complete_tx), }; let session_ = session.clone(); session.spawn(move |_| { complete_rx.map(move |mut file| { if let Some(cache) = session_.cache() { cache.save_file(file_id, &mut file); debug!("File {} complete, saving to cache", file_id); } else { debug!("File {} complete", file_id); } }).or_else(|oneshot::Canceled| Ok(())) }); AudioFileOpen::Streaming(open) } } fn request_chunk(session: &Session, file: FileId, index: usize) -> Channel { trace!("requesting chunk {}", index); let start = (index * CHUNK_SIZE / 4) as u32; let end = ((index + 1) * CHUNK_SIZE / 4) as u32; let (id, channel) = session.channel().allocate(); let mut data: Vec<u8> = Vec::new(); data.write_u16::<BigEndian>(id).unwrap(); data.write_u8(0).unwrap(); data.write_u8(1).unwrap(); data.write_u16::<BigEndian>(0x0000).unwrap(); data.write_u32::<BigEndian>(0x00000000).unwrap(); data.write_u32::<BigEndian>(0x00009C40).unwrap(); data.write_u32::<BigEndian>(0x00020000).unwrap(); data.write(&file.0).unwrap(); data.write_u32::<BigEndian>(start).unwrap(); data.write_u32::<BigEndian>(end).unwrap(); session.send_packet(0x8, data); channel } struct AudioFileFetch { session: Session, shared: Arc<AudioFileShared>, output: Option<NamedTempFile>, index: usize, data_rx: ChannelData, seek_rx: mpsc::UnboundedReceiver<u64>, complete_tx: Option<oneshot::Sender<NamedTempFile>>, } impl AudioFileFetch { fn new(session: Session, shared: Arc<AudioFileShared>, data_rx: ChannelData, output: NamedTempFile, seek_rx: mpsc::UnboundedReceiver<u64>, complete_tx: oneshot::Sender<NamedTempFile>) -> AudioFileFetch { AudioFileFetch { session: session, shared: shared, output: Some(output), index: 0, data_rx: data_rx, seek_rx: seek_rx, complete_tx: Some(complete_tx), } } fn download(&mut self, mut new_index: usize) {<|fim▁hole|> while bitmap.contains(new_index) { new_index = (new_index + 1) % self.shared.chunk_count; } } if self.index != new_index { self.index = new_index; let offset = self.index * CHUNK_SIZE; self.output.as_mut().unwrap() .seek(SeekFrom::Start(offset as u64)).unwrap(); let (_headers, data) = request_chunk(&self.session, self.shared.file_id, self.index).split(); self.data_rx = data; } } fn finish(&mut self) { let mut output = self.output.take().unwrap(); let complete_tx = self.complete_tx.take().unwrap(); output.seek(SeekFrom::Start(0)).unwrap(); let _ = complete_tx.send(output); } } impl Future for AudioFileFetch { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { loop { let mut progress = false; match self.seek_rx.poll() { Ok(Async::Ready(None)) => { return Ok(Async::Ready(())); } Ok(Async::Ready(Some(offset))) => { progress = true; let index = offset as usize / CHUNK_SIZE; self.download(index); } Ok(Async::NotReady) => (), Err(()) => unreachable!(), } match self.data_rx.poll() { Ok(Async::Ready(Some(data))) => { progress = true; self.output.as_mut().unwrap() .write_all(data.as_ref()).unwrap(); } Ok(Async::Ready(None)) => { progress = true; trace!("chunk {} / {} complete", self.index, self.shared.chunk_count); let full = { let mut bitmap = self.shared.bitmap.lock().unwrap(); bitmap.insert(self.index as usize); self.shared.cond.notify_all(); bitmap.len() >= self.shared.chunk_count }; if full { self.finish(); return Ok(Async::Ready(())); } let new_index = (self.index + 1) % self.shared.chunk_count; self.download(new_index); } Ok(Async::NotReady) => (), Err(ChannelError) => { warn!("error from channel"); return Ok(Async::Ready(())); }, } if !progress { return Ok(Async::NotReady); } } } } impl Read for AudioFileStreaming { fn read(&mut self, output: &mut [u8]) -> io::Result<usize> { let index = self.position as usize / CHUNK_SIZE; let offset = self.position as usize % CHUNK_SIZE; let len = min(output.len(), CHUNK_SIZE - offset); let mut bitmap = self.shared.bitmap.lock().unwrap(); while !bitmap.contains(index) { bitmap = self.shared.cond.wait(bitmap).unwrap(); } drop(bitmap); let read_len = try!(self.read_file.read(&mut output[..len])); self.position += read_len as u64; Ok(read_len) } } impl Seek for AudioFileStreaming { fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { self.position = try!(self.read_file.seek(pos)); // Notify the fetch thread to get the correct block // This can fail if fetch thread has completed, in which case the // block is ready. Just ignore the error. let _ = self.seek.send(self.position); Ok(self.position) } } impl Read for AudioFile { fn read(&mut self, output: &mut [u8]) -> io::Result<usize> { match *self { AudioFile::Cached(ref mut file) => file.read(output), AudioFile::Streaming(ref mut file) => file.read(output), } } } impl Seek for AudioFile { fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> { match *self { AudioFile::Cached(ref mut file) => file.seek(pos), AudioFile::Streaming(ref mut file) => file.seek(pos), } } }<|fim▁end|>
assert!(new_index < self.shared.chunk_count); { let bitmap = self.shared.bitmap.lock().unwrap();
<|file_name|>report_converter.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python from xml.sax.saxutils import escape import re def ConvertDiagnosticLineToSonqarqube(item): try: id, line, message, source_file = GetDiagnosticFieldsFromDiagnosticLine(item) WriteDiagnosticFieldsToFile(id, line, message, source_file) except: print 'Cant parse line {}'.format(item) def GetDiagnosticFieldsFromDiagnosticLine(item): source_file = re.search('\/(.*?):', item).group(0).replace(':', '') line = re.search(':\d*:', item).group(0).replace(':', '') id = re.search('\[.*\]', item).group(0).replace('[', '').replace(']', '') + '-clang-compiler' message = re.search('warning: (.*)\[', item).group(0).replace('[', '').replace('warning: ', '') return id, line, message, source_file def WriteDiagnosticFieldsToFile(id, line, message, source_file): clang_sonar_report.write(" <error file=\"" + str(source_file) + "\" line=\"" + str(line) + "\" id=\"" + str(id) + "\" msg=\"" + escape(str(message)) + "\"/>\n") def CreateOutputFile(): file_to_write = open('clang_compiler_report.xml', 'w') file_to_write.write('<?xml version="1.0" encoding="UTF-8"?>\n') file_to_write.write('<results>\n') return file_to_write def ReadCompilerReportFile(): file = open('clang_compiler_report_formatted', 'r') messages_xml = file.readlines() return messages_xml def CloseOutputFile(): clang_sonar_report.write('</results>\n') clang_sonar_report.close() def WriteSonarRulesToOutputFile(): item_list = clang_compiler_report<|fim▁hole|> ConvertDiagnosticLineToSonqarqube(item) if __name__ == '__main__': clang_sonar_report = CreateOutputFile() clang_compiler_report = ReadCompilerReportFile() WriteSonarRulesToOutputFile() CloseOutputFile()<|fim▁end|>
for item in item_list:
<|file_name|>DiffDialog.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'DiffDialog.ui' # # Created: Tue Aug 30 12:04:37 2011 # by: PyQt4 UI code generator 4.8.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_DiffDialog(object): def setupUi(self, DiffDialog): DiffDialog.setObjectName(_fromUtf8("DiffDialog")) DiffDialog.resize(802, 557) self.verticalLayout = QtGui.QVBoxLayout(DiffDialog) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))<|fim▁hole|> icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/images/diff-icon-16.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.customButton.setIcon(icon) self.customButton.setObjectName(_fromUtf8("customButton")) self.horizontalLayout_2.addWidget(self.customButton) spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem) self.verticalLayout.addLayout(self.horizontalLayout_2) self.splitter_2 = QtGui.QSplitter(DiffDialog) self.splitter_2.setOrientation(QtCore.Qt.Vertical) self.splitter_2.setObjectName(_fromUtf8("splitter_2")) self.splitter = QtGui.QSplitter(self.splitter_2) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setObjectName(_fromUtf8("splitter")) self.leftTree = QtGui.QTreeWidget(self.splitter) self.leftTree.setObjectName(_fromUtf8("leftTree")) self.rightTree = QtGui.QTreeWidget(self.splitter) self.rightTree.setObjectName(_fromUtf8("rightTree")) self.diffView = QtWebKit.QWebView(self.splitter_2) self.diffView.setUrl(QtCore.QUrl(_fromUtf8("about:blank"))) self.diffView.setObjectName(_fromUtf8("diffView")) self.verticalLayout.addWidget(self.splitter_2) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem1) self.clearButton = QtGui.QPushButton(DiffDialog) self.clearButton.setObjectName(_fromUtf8("clearButton")) self.horizontalLayout.addWidget(self.clearButton) self.closeButton = QtGui.QPushButton(DiffDialog) self.closeButton.setObjectName(_fromUtf8("closeButton")) self.horizontalLayout.addWidget(self.closeButton) self.verticalLayout.addLayout(self.horizontalLayout) self.retranslateUi(DiffDialog) QtCore.QObject.connect(self.closeButton, QtCore.SIGNAL(_fromUtf8("clicked()")), DiffDialog.close) QtCore.QMetaObject.connectSlotsByName(DiffDialog) def retranslateUi(self, DiffDialog): DiffDialog.setWindowTitle(QtGui.QApplication.translate("DiffDialog", "Diff Dialog", None, QtGui.QApplication.UnicodeUTF8)) self.customButton.setText(QtGui.QApplication.translate("DiffDialog", "...", None, QtGui.QApplication.UnicodeUTF8)) self.leftTree.headerItem().setText(0, QtGui.QApplication.translate("DiffDialog", "Id", None, QtGui.QApplication.UnicodeUTF8)) self.leftTree.headerItem().setText(1, QtGui.QApplication.translate("DiffDialog", "URL", None, QtGui.QApplication.UnicodeUTF8)) self.rightTree.headerItem().setText(0, QtGui.QApplication.translate("DiffDialog", "Id", None, QtGui.QApplication.UnicodeUTF8)) self.rightTree.headerItem().setText(1, QtGui.QApplication.translate("DiffDialog", "URL", None, QtGui.QApplication.UnicodeUTF8)) self.clearButton.setText(QtGui.QApplication.translate("DiffDialog", "Clear", None, QtGui.QApplication.UnicodeUTF8)) self.closeButton.setText(QtGui.QApplication.translate("DiffDialog", "Close", None, QtGui.QApplication.UnicodeUTF8)) from PyQt4 import QtWebKit from . import resources_rc<|fim▁end|>
self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.customButton = QtGui.QToolButton(DiffDialog)
<|file_name|>tag.go<|end_file_name|><|fim▁begin|>package logging import ( "time" "github.com/urandom/readeef/content" "github.com/urandom/readeef/content/repo" "github.com/urandom/readeef/log" ) type tagRepo struct { repo.Tag log log.Log } func (r tagRepo) Get(id content.TagID, user content.User) (content.Tag, error) { start := time.Now()<|fim▁hole|> tag, err := r.Tag.Get(id, user) r.log.Infof("repo.Tag.Get took %s", time.Now().Sub(start)) return tag, err } func (r tagRepo) ForUser(user content.User) ([]content.Tag, error) { start := time.Now() tags, err := r.Tag.ForUser(user) r.log.Infof("repo.Tag.ForUser took %s", time.Now().Sub(start)) return tags, err } func (r tagRepo) ForFeed(feed content.Feed, user content.User) ([]content.Tag, error) { start := time.Now() tags, err := r.Tag.ForFeed(feed, user) r.log.Infof("repo.Tag.ForFeed took %s", time.Now().Sub(start)) return tags, err } func (r tagRepo) FeedIDs(tag content.Tag, user content.User) ([]content.FeedID, error) { start := time.Now() ids, err := r.Tag.FeedIDs(tag, user) r.log.Infof("repo.Tag.FeedIDs took %s", time.Now().Sub(start)) return ids, err }<|fim▁end|>
<|file_name|>bitcoin_en_GB.ts<|end_file_name|><|fim▁begin|><TS language="en_GB" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Right-click to edit address or label</translation> </message> <message> <source>Create a new address</source> <translation>Create a new address</translation> </message> <message> <source>&amp;New</source> <translation>&amp;New</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Copy the currently selected address to the system clipboard</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Copy</translation> </message> <message> <source>C&amp;lose</source> <translation>C&amp;lose</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Delete the currently selected address from the list</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Export the data in the current tab to a file</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Export</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Delete</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Choose the address to send coins to</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Choose the address to receive coins with</translation> </message> <message> <source>C&amp;hoose</source> <translation>C&amp;hoose</translation> </message> <message> <source>Sending addresses</source> <translation>Sending addresses</translation> </message> <message> <source>Receiving addresses</source> <translation>Receiving addresses</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Copy Address</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Copy &amp;Label</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Edit</translation> </message> <message> <source>Export Address List</source> <translation>Export Address List</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation>Exporting Failed</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Label</translation> </message> <message> <source>Address</source> <translation>Address</translation> </message> <message> <source>(no label)</source> <translation>(no label)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Passphrase Dialog</translation> </message> <message> <source>Enter passphrase</source> <translation>Enter passphrase</translation> </message> <message> <source>New passphrase</source> <translation>New passphrase</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Repeat new passphrase</translation> </message> <message> <source>Encrypt wallet</source> <translation>Encrypt wallet</translation> </message> </context> <context> <name>BanTableModel</name> <message> <source>IP/Netmask</source> <translation>IP/Netmask</translation> </message> <message> <source>Banned Until</source> <translation>Banned Until</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Sign &amp;message...</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Synchronising with network...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Overview</translation> </message> <message> <source>Node</source> <translation>Node</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Show general overview of wallet</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transactions</translation> </message> <message> <source>Browse transaction history</source> <translation>Browse transaction history</translation> </message> <message> <source>E&amp;xit</source> <translation>E&amp;xit</translation> </message> <message> <source>Quit application</source> <translation>Quit application</translation> </message> <message> <source>&amp;About %1</source> <translation>&amp;About %1</translation> </message> <message> <source>Show information about %1</source> <translation>Show information about %1</translation> </message> <message> <source>About &amp;Qt</source> <translation>About &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Show information about Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Options...</translation> </message> <message> <source>Modify configuration options for %1</source> <translation>Modify configuration options for %1</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Encrypt Wallet...</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Wallet...</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Change Passphrase...</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>&amp;Sending addresses...</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>&amp;Receiving addresses...</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Open &amp;URI...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Reindexing blocks on disk...</translation> </message> <message> <source>Send coins to a Viacoin address</source> <translation>Send coins to a Viacoin address</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Backup wallet to another location</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Change the passphrase used for wallet encryption</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Debug window</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Open debugging and diagnostic console</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Verify message...</translation> </message> <message> <source>Viacoin</source> <translation>Viacoin</translation> </message> <message> <source>Wallet</source> <translation>Wallet</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Send</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Receive</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Show / Hide</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Show or hide the main Window</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Encrypt the private keys that belong to your wallet</translation> </message> <message> <source>Sign messages with your Viacoin addresses to prove you own them</source> <translation>Sign messages with your Viacoin addresses to prove you own them</translation> </message> <message> <source>Verify messages to ensure they were signed with specified Viacoin addresses</source> <translation>Verify messages to ensure they were signed with specified Viacoin addresses</translation> </message> <message> <source>&amp;File</source> <translation>&amp;File</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Settings</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Help</translation> </message> <message> <source>Tabs toolbar</source> <translation>Tabs toolbar</translation> </message> <message> <source>Request payments (generates QR codes and viacoin: URIs)</source> <translation>Request payments (generates QR codes and viacoin: URIs)</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>Show the list of used sending addresses and labels</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>Show the list of used receiving addresses and labels</translation> </message> <message> <source>Open a viacoin: URI or payment request</source> <translation>Open a viacoin: URI or payment request</translation> </message> <message> <source>&amp;Command-line options</source> <translation>&amp;Command-line options</translation> </message> <message numerus="yes"> <source>%n active connection(s) to Viacoin network</source> <translation><numerusform>%n active connection to Viacoin network</numerusform><numerusform>%n active connections to Viacoin network</numerusform></translation> </message> <message> <source>Indexing blocks on disk...</source> <translation>Indexing blocks on disk...</translation> </message> <message> <source>Processing blocks on disk...</source> <translation>Processing blocks on disk...</translation> </message> <message> <source>No block source available...</source> <translation>No block source available...</translation> </message> <message numerus="yes"> <source>Processed %n block(s) of transaction history.</source> <translation><numerusform>Processed %n block of transaction history.</numerusform><numerusform>Processed %n blocks of transaction history.</numerusform></translation> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation><numerusform>%n hour</numerusform><numerusform>%n hours</numerusform></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation><numerusform>%n day</numerusform><numerusform>%n days</numerusform></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation><numerusform>%n week</numerusform><numerusform>%n weeks</numerusform></translation> </message> <message> <source>%1 and %2</source> <translation>%1 and %2</translation> </message> <message numerus="yes"> <source>%n year(s)</source> <translation><numerusform>%n year</numerusform><numerusform>%n years</numerusform></translation> </message> <message> <source>%1 behind</source> <translation>%1 behind</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>Last received block was generated %1 ago.</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>Transactions after this will not yet be visible.</translation> </message> <message> <source>Error</source> <translation>Error</translation> </message> <message> <source>Warning</source> <translation>Warning</translation> </message> <message> <source>Information</source> <translation>Information</translation> </message> <message> <source>Up to date</source> <translation>Up to date</translation> </message> <message> <source>Show the %1 help message to get a list with possible Viacoin command-line options</source> <translation>Show the %1 help message to get a list with possible Viacoin command-line options</translation> </message> <message> <source>%1 client</source> <translation>%1 client</translation> </message> <message> <source>Catching up...</source> <translation>Catching up...</translation> </message> <message> <source>Date: %1 </source> <translation>Date: %1 </translation> </message> <message> <source>Amount: %1 </source> <translation>Amount: %1 </translation> </message> <message> <source>Type: %1 </source> <translation>Type: %1 </translation> </message> <message> <source>Label: %1 </source> <translation>Label: %1 </translation> </message> <message> <source>Address: %1 </source> <translation>Address: %1 </translation> </message> <message> <source>Sent transaction</source> <translation>Sent transaction</translation> </message> <message> <source>Incoming transaction</source> <translation>Incoming transaction</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Selection</source> <translation>Coin Selection</translation> </message> <message> <source>Quantity:</source> <translation>Quantity:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Amount:</translation> </message> <message> <source>Priority:</source> <translation>Priority:</translation> </message> <message> <source>Fee:</source> <translation>Fee:</translation> </message> <message> <source>Dust:</source> <translation>Dust:</translation> </message> <message> <source>After Fee:</source> <translation>After Fee:</translation> </message> <message> <source>Change:</source> <translation>Change:</translation> </message> <message> <source>(un)select all</source> <translation>(un)select all</translation> </message> <message> <source>Tree mode</source> <translation>Tree mode</translation> </message> <message> <source>List mode</source> <translation>List mode</translation> </message> <message> <source>Amount</source> <translation>Amount</translation> </message> <message> <source>Received with label</source> <translation>Received with label</translation> </message> <message> <source>Received with address</source> <translation>Received with address</translation> </message> <message> <source>Date</source> <translation>Date</translation> </message> <message> <source>Confirmations</source> <translation>Confirmations</translation> </message> <message> <source>Confirmed</source> <translation>Confirmed</translation> </message> <message> <source>Priority</source> <translation>Priority</translation> </message> <message> <source>(no label)</source> <translation>(no label)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Edit Address</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Label</translation> </message> <message> <source>The label associated with this address list entry</source> <translation>The label associated with this address list entry</translation> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation>The address associated with this address list entry. This can only be modified for sending addresses.</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Address</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>A new data directory will be created.</translation> </message> <message> <source>name</source> <translation>name</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>Directory already exists. Add %1 if you intend to create a new directory here.</translation> </message> <message> <source>Path already exists, and is not a directory.</source> <translation>Path already exists, and is not a directory.</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>Cannot create data directory here.</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>version</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>About %1</source> <translation>About %1</translation> </message> <message> <source>Command-line options</source> <translation>Command-line options</translation> </message> <message> <source>Usage:</source> <translation>Usage:</translation> </message> <message> <source>command-line options</source> <translation>command-line options</translation> </message> <message> <source>UI Options:</source> <translation>UI Options:</translation> </message> <message> <source>Choose data directory on startup (default: %u)</source> <translation>Choose data directory on startup (default: %u)</translation> </message> <message> <source>Set language, for example "de_DE" (default: system locale)</source> <translation>Set language, for example "de_DE" (default: system locale)</translation> </message> <message> <source>Start minimized</source> <translation>Start minimised</translation> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation>Set SSL root certificates for payment request (default: -system-)</translation> </message> <message> <source>Show splash screen on startup (default: %u)</source> <translation>Show splash screen on startup (default: %u)</translation> </message> <message> <source>Reset all settings changed in the GUI</source> <translation>Reset all settings changed in the GUI</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Welcome</translation> </message> <message> <source>Welcome to %1.</source> <translation>Welcome to %1.</translation> </message> <message> <source>As this is the first time the program is launched, you can choose where %1 will store its data.</source> <translation>As this is the first time the program is launched, you can choose where %1 will store its data.</translation> </message> <message> <source>%1 will download and store a copy of the Viacoin block chain. At least %2GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation>%1 will download and store a copy of the Viacoin block chain. At least %2GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</translation> </message> <message> <source>Use the default data directory</source> <translation>Use the default data directory</translation> </message> <message> <source>Use a custom data directory:</source> <translation>Use a custom data directory:</translation> </message> <message> <source>Error: Specified data directory "%1" cannot be created.</source> <translation>Error: Specified data directory "%1" cannot be created.</translation> </message> <message> <source>Error</source> <translation>Error</translation> </message> <message numerus="yes"> <source>%n GB of free space available</source> <translation><numerusform>%n GB of free space available</numerusform><numerusform>%n GB of free space available</numerusform></translation> </message> <message numerus="yes"> <source>(of %n GB needed)</source> <translation><numerusform>(of %n GB needed)</numerusform><numerusform>(of %n GB needed)</numerusform></translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>Open URI</translation> </message> <message> <source>Open payment request from URI or file</source> <translation>Open payment request from URI or file</translation> </message> <message> <source>URI:</source> <translation>URI:</translation> </message> <message> <source>Select payment request file</source> <translation>Select payment request file</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Options</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;Main</translation> </message> <message> <source>Automatically start %1 after logging in to the system.</source> <translation>Automatically start %1 after logging in to the system.</translation> </message> <message> <source>&amp;Start %1 on system login</source> <translation>&amp;Start %1 on system login</translation> </message> <message> <source>Size of &amp;database cache</source> <translation>Size of &amp;database cache</translation> </message> <message> <source>MB</source> <translation>MB</translation> </message> <message> <source>Number of script &amp;verification threads</source> <translation>Number of script &amp;verification threads</translation> </message> <message> <source>Accept connections from outside</source> <translation>Accept connections from outside</translation> </message> <message> <source>Allow incoming connections</source> <translation>Allow incoming connections</translation> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</translation> </message> <message> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Exit in the menu.</source> <translation>Minimise instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Exit in the menu.</translation> </message> <message> <source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source> <translation>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</translation> </message> <message> <source>Third party transaction URLs</source> <translation>Third party transaction URLs</translation> </message> <message> <source>Active command-line options that override above options:</source> <translation>Active command-line options that override above options:</translation> </message> <message> <source>Reset all client options to default.</source> <translation>Reset all client options to default.</translation> </message> <message> <source>&amp;Reset Options</source> <translation>&amp;Reset Options</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;Network</translation> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation>(0 = auto, &lt;0 = leave that many cores free)</translation> </message> <message> <source>W&amp;allet</source> <translation>W&amp;allet</translation> </message> <message> <source>Expert</source> <translation>Expert</translation> </message> <message> <source>Enable coin &amp;control features</source> <translation>Enable coin &amp;control features</translation> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <translation>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</translation> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation>&amp;Spend unconfirmed change</translation> </message> <message> <source>Automatically open the Viacoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatically open the Viacoin client port on the router. This only works when your router supports UPnP and it is enabled.</translation> </message> <message> <source>Map port using &amp;UPnP</source> <translation>Map port using &amp;UPnP</translation> </message> <message> <source>Connect to the Viacoin network through a SOCKS5 proxy.</source> <translation>Connect to the Viacoin network through a SOCKS5 proxy.</translation> </message> <message> <source>&amp;Connect through SOCKS5 proxy (default proxy):</source> <translation>&amp;Connect through SOCKS5 proxy (default proxy):</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Port of the proxy (e.g. 9050)</translation> </message> <message> <source>Used for reaching peers via:</source> <translation>Used for reaching peers via:</translation> </message> <message> <source>Shows, if the supplied default SOCKS5 proxy is used to reach peers via this network type.</source> <translation>Shows, if the supplied default SOCKS5 proxy is used to reach peers via this network type.</translation> </message> <message> <source>IPv4</source> <translation>IPv4</translation> </message> <message> <source>IPv6</source> <translation>IPv6</translation> </message> <message> <source>Tor</source> <translation>Tor</translation> </message> <message> <source>Connect to the Viacoin network through a separate SOCKS5 proxy for Tor hidden services.</source> <translation>Connect to the Viacoin network through a separate SOCKS5 proxy for Tor hidden services.</translation> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services:</source> <translation>Use separate SOCKS5 proxy to reach peers via Tor hidden services:</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;Window</translation> </message> <message> <source>&amp;Hide the icon from the system tray.</source> <translation>&amp;Hide the icon from the system tray.</translation> </message> <message> <source>Hide tray icon</source> <translation>Hide tray icon</translation> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation>Show on a tray icon after minimising the window.</translation> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimise to the tray instead of the task bar</translation> </message> <message> <source>M&amp;inimize on close</source> <translation>M&amp;inimise on close</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;Display</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>User Interface &amp;language:</translation> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting %1.</source> <translation>The user interface language can be set here. This setting will take effect after restarting %1.</translation> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unit to show amounts in:</translation> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Choose the default subdivision unit to show in the interface and when sending coins.</translation> </message> <message> <source>Whether to show coin control features or not.</source> <translation>Whether to show coin control features or not.</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;Cancel</translation> </message> <message> <source>default</source> <translation>default</translation> </message> <message> <source>none</source> <translation>none</translation> </message> <message> <source>Confirm options reset</source> <translation>Confirm options reset</translation> </message> <message> <source>Client restart required to activate changes.</source> <translation>Client restart required to activate changes.</translation> </message> <message> <source>Client will be shut down. Do you want to proceed?</source> <translation>Client will be shut down. Do you want to proceed?</translation> </message> <message> <source>This change would require a client restart.</source> <translation>This change would require a client restart.</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>The supplied proxy address is invalid.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Form</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Viacoin network after a connection is established, but this process has not completed yet.</source> <translation>The displayed information may be out of date. Your Wallet automatically synchronises with the Viacoin Network after a connection is established, but this process has not been completed yet.</translation> </message> <message> <source>Watch-only:</source> <translation>Watch-only:</translation> </message> <message> <source>Available:</source> <translation>Available:</translation> </message> <message> <source>Your current spendable balance</source> <translation>Your current spendable balance</translation> </message> <message> <source>Pending:</source> <translation>Pending:</translation> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</translation> </message> <message> <source>Immature:</source> <translation>Immature:</translation> </message> <message> <source>Mined balance that has not yet matured</source> <translation>Mined balance that has not yet matured</translation> </message> <message> <source>Balances</source> <translation>Balances</translation> </message> <message> <source>Total:</source> <translation>Total:</translation> </message> <message> <source>Your current total balance</source> <translation>Your current total balance</translation> </message> <message> <source>Your current balance in watch-only addresses</source> <translation>Your current balance in watch-only addresses</translation> </message> <message> <source>Spendable:</source> <translation>Spendable:</translation> </message> <message> <source>Recent transactions</source> <translation>Recent transactions</translation> </message> <message> <source>Unconfirmed transactions to watch-only addresses</source> <translation>Unconfirmed transactions to watch-only addresses</translation> </message> <message> <source>Mined balance in watch-only addresses that has not yet matured</source> <translation>Mined balance in watch-only addresses that has not yet matured</translation> </message> <message> <source>Current total balance in watch-only addresses</source> <translation>Current total balance in watch-only addresses</translation> </message> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> <message> <source>User Agent</source> <translation>User Agent</translation> </message> <message> <source>Node/Service</source> <translation>Node/Service</translation> </message> <message> <source>Ping Time</source> <translation>Ping Time</translation> </message> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Amount</translation> </message> <message> <source>Enter a Viacoin address (e.g. %1)</source> <translation>Enter a Viacoin address (e.g. %1)</translation> </message> <message> <source>%1 d</source> <translation>%1 d</translation> </message> <message> <source>%1 h</source> <translation>%1 h</translation> </message> <message> <source>%1 m</source> <translation>%1 m</translation> </message> <message> <source>%1 s</source> <translation>%1 s</translation> </message> <message> <source>None</source> <translation>None</translation> </message> <message> <source>N/A</source> <translation>N/A</translation> </message> <message> <source>%1 ms</source> <translation>%1 ms</translation> </message> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>N/A</source> <translation>N/A</translation> </message> <message> <source>Client version</source> <translation>Client version</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Information</translation> </message> <message> <source>Debug window</source> <translation>Debug window</translation> </message> <message> <source>General</source> <translation>General</translation> </message> <message> <source>Using BerkeleyDB version</source> <translation>Using BerkeleyDB version</translation> </message> <message> <source>Datadir</source> <translation>Datadir</translation> </message> <message> <source>Startup time</source> <translation>Startup time</translation> </message> <message> <source>Network</source> <translation>Network</translation> </message> <message> <source>Name</source> <translation>Name</translation> </message> <message> <source>Number of connections</source> <translation>Number of connections</translation> </message> <message> <source>Block chain</source> <translation>Block chain</translation> </message> <message> <source>Current number of blocks</source> <translation>Current number of blocks</translation> </message> <message> <source>Memory Pool</source> <translation>Memory Pool</translation> </message> <message> <source>Current number of transactions</source> <translation>Current number of transactions</translation> </message> <message> <source>Memory usage</source> <translation>Memory usage</translation> </message> <message> <source>Received</source> <translation>Received</translation> </message> <message> <source>Sent</source> <translation>Sent</translation> </message> <message> <source>&amp;Peers</source> <translation>&amp;Peers</translation> </message> <message> <source>Banned peers</source> <translation>Banned peers</translation> </message> <message> <source>Select a peer to view detailed information.</source> <translation>Select a peer to view detailed information.</translation> </message> <message> <source>Whitelisted</source> <translation>Whitelisted</translation> </message> <message> <source>Direction</source> <translation>Direction</translation> </message> <message> <source>Version</source> <translation>Version</translation> </message> <message> <source>Starting Block</source> <translation>Starting Block</translation> </message> <message> <source>Synced Headers</source> <translation>Synced Headers</translation> </message> <message> <source>Synced Blocks</source> <translation>Synced Blocks</translation> </message> <message> <source>User Agent</source> <translation>User Agent</translation> </message> <message> <source>Open the %1 debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Open the %1 debug log file from the current data directory. This can take a few seconds for large log files.</translation> </message> <message> <source>Decrease font size</source> <translation>Decrease font size</translation> </message> <message> <source>Increase font size</source> <translation>Increase font size</translation> </message> <message> <source>Services</source> <translation>Services</translation> </message> <message> <source>Ban Score</source> <translation>Ban Score</translation> </message> <message> <source>Connection Time</source> <translation>Connection Time</translation> </message> <message> <source>Last Send</source> <translation>Last Send</translation> </message> <message> <source>Last Receive</source> <translation>Last Receive</translation> </message> <message> <source>Ping Time</source> <translation>Ping Time</translation> </message> <message> <source>The duration of a currently outstanding ping.</source> <translation>The duration of a currently outstanding ping.</translation> </message> <message> <source>Ping Wait</source> <translation>Ping Wait</translation> </message> <message> <source>Time Offset</source> <translation>Time Offset</translation> </message> <message> <source>Last block time</source> <translation>Last block time</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Open</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <source>&amp;Network Traffic</source> <translation>&amp;Network Traffic</translation> </message> <message> <source>&amp;Clear</source> <translation>&amp;Clear</translation> </message> <message> <source>Totals</source> <translation>Totals</translation> </message> <message> <source>In:</source> <translation>In:</translation> </message> <message> <source>Out:</source> <translation>Out:</translation> </message> <message> <source>Debug log file</source> <translation>Debug log file</translation> </message> <message> <source>Clear console</source> <translation>Clear console</translation> </message> <message> <source>&amp;Disconnect Node</source> <translation>&amp;Disconnect Node</translation> </message> <message> <source>Ban Node for</source> <translation>Ban Node for</translation> </message> <message> <source>1 &amp;hour</source> <translation>1 &amp;hour</translation> </message> <message> <source>1 &amp;day</source> <translation>1 &amp;day</translation> </message> <message> <source>1 &amp;week</source> <translation>1 &amp;week</translation> </message> <message> <source>1 &amp;year</source> <translation>1 &amp;year</translation> </message> <message> <source>&amp;Unban Node</source> <translation>&amp;Unban Node</translation> </message> <message> <source>Welcome to the %1 RPC console.</source> <translation>Welcome to the %1 RPC console.</translation> </message> <message> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</translation> </message> <message> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</translation> </message> <message> <source>%1 B</source> <translation>%1 B</translation> </message> <message> <source>%1 KB</source> <translation>%1 KB</translation> </message> <message> <source>%1 MB</source> <translation>%1 MB</translation> </message> <message> <source>%1 GB</source> <translation>%1 GB</translation> </message> <message> <source>(node id: %1)</source> <translation>(node id: %1)</translation> </message> <message> <source>via %1</source> <translation>via %1</translation> </message> <message> <source>never</source> <translation>never</translation> </message> <message> <source>Inbound</source> <translation>Inbound</translation> </message> <message> <source>Outbound</source> <translation>Outbound</translation> </message> <message> <source>Yes</source> <translation>Yes</translation> </message> <message> <source>No</source> <translation>No</translation> </message> <message> <source>Unknown</source> <translation>Unknown</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>&amp;Amount:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Label:</translation> </message> <message> <source>&amp;Message:</source> <translation>&amp;Message:</translation> </message> <message> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</translation> </message> <message> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation>R&amp;euse an existing receiving address (not recommended)</translation> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Viacoin network.</source> <translation>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Viacoin network.</translation> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation>An optional label to associate with the new receiving address.</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>An optional amount to request. Leave this empty or zero to not request a specific amount.</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Clear all fields of the form.</translation> </message> <message> <source>Clear</source> <translation>Clear</translation> </message> <message> <source>Requested payments history</source> <translation>Requested payments history</translation> </message> <message> <source>&amp;Request payment</source> <translation>&amp;Request payment</translation> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation>Show the selected request (does the same as double clicking an entry)</translation> </message> <message> <source>Show</source> <translation>Show</translation> </message> <message> <source>Remove the selected entries from the list</source> <translation>Remove the selected entries from the list</translation> </message> <message> <source>Remove</source> <translation>Remove</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>QR Code</translation> </message> <message> <source>Copy &amp;URI</source> <translation>Copy &amp;URI</translation> </message> <message> <source>Copy &amp;Address</source> <translation>Copy &amp;Address</translation> </message> <message> <source>&amp;Save Image...</source> <translation>&amp;Save Image...</translation> </message> <message> <source>Address</source> <translation>Address</translation> </message> <message> <source>Label</source> <translation>Label</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Label</source> <translation>Label</translation> </message> <message> <source>(no label)</source> <translation>(no label)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Send Coins</translation> </message> <message> <source>Coin Control Features</source> <translation>Coin Control Features</translation> </message> <message> <source>Inputs...</source> <translation>Inputs...</translation> </message> <message> <source>automatically selected</source> <translation>automatically selected</translation> </message> <message> <source>Insufficient funds!</source> <translation>Insufficient funds!</translation> </message> <message> <source>Quantity:</source> <translation>Quantity:</translation> </message> <message> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <source>Amount:</source> <translation>Amount:</translation> </message> <message> <source>Priority:</source> <translation>Priority:</translation> </message> <message> <source>Fee:</source> <translation>Fee:</translation> </message> <message> <source>After Fee:</source> <translation>After Fee:</translation> </message> <message> <source>Change:</source> <translation>Change:</translation> </message> <message> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</translation> </message> <message> <source>Custom change address</source> <translation>Custom change address</translation> </message> <message> <source>Transaction Fee:</source> <translation>Transaction Fee:</translation> </message> <message> <source>Choose...</source> <translation>Choose...</translation> </message> <message> <source>collapse fee-settings</source> <translation>collapse fee-settings</translation> </message> <message> <source>per kilobyte</source> <translation>per kilobyte</translation> </message> <message> <source>If the custom fee is set to 1000 satoshis and the transaction is only 250 bytes, then "per kilobyte" only pays 250 satoshis in fee, while "total at least" pays 1000 satoshis. For transactions bigger than a kilobyte both pay by kilobyte.</source> <translation>If the custom fee is set to 1000 satoshis and the transaction is only 250 bytes, then "per kilobyte" only pays 250 satoshis in fee, while "total at least" pays 1000 satoshis. For transactions bigger than a kilobyte both pay by kilobyte.</translation> </message> <message> <source>Hide</source> <translation>Hide</translation> </message> <message> <source>total at least</source> <translation>total at least</translation> </message> <message> <source>Paying only the minimum fee is just fine as long as there is less transaction volume than space in the blocks. But be aware that this can end up in a never confirming transaction once there is more demand for viacoin transactions than the network can process.</source> <translation>Paying only the minimum fee is just fine as long as there is less transaction volume than space in the blocks. But be aware that this can end up in a never confirming transaction once there is more demand for viacoin transactions than the network can process.</translation> </message> <message> <source>(read the tooltip)</source> <translation>(read the tooltip)</translation> </message> <message> <source>Recommended:</source> <translation>Recommended:</translation> </message> <message> <source>Custom:</source> <translation>Custom:</translation> </message> <message> <source>(Smart fee not initialized yet. This usually takes a few blocks...)</source> <translation>(Smart fee not initialised yet. This usually takes a few blocks...)</translation> </message> <message> <source>Confirmation time:</source> <translation>Confirmation time:</translation> </message> <message> <source>normal</source> <translation>normal</translation> </message> <message> <source>fast</source> <translation>fast</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Send to multiple recipients at once</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>Add &amp;Recipient</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Clear all fields of the form.</translation> </message> <message> <source>Dust:</source> <translation>Dust:</translation> </message> <message> <source>Clear &amp;All</source> <translation>Clear &amp;All</translation> </message> <message> <source>Balance:</source> <translation>Balance:</translation> </message> <message> <source>Confirm the send action</source> <translation>Confirm the send action</translation> </message> <message> <source>S&amp;end</source> <translation>S&amp;end</translation> </message> <message> <source>(no label)</source> <translation>(no label)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>A&amp;mount:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Pay &amp;To:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Label:</translation> </message> <message> <source>Choose previously used address</source> <translation>Choose previously used address</translation> </message> <message> <source>This is a normal payment.</source> <translation>This is a normal payment.</translation> </message> <message> <source>The Viacoin address to send the payment to</source> <translation>The Viacoin address to send the payment to</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Paste address from clipboard</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Remove this entry</translation> </message> <message> <source>The fee will be deducted from the amount being sent. The recipient will receive less viacoins than you enter in the amount field. If multiple recipients are selected, the fee is split equally.</source> <translation>The fee will be deducted from the amount being sent. The recipient will receive less viacoins than you enter in the amount field. If multiple recipients are selected, the fee is split equally.</translation> </message> <message> <source>S&amp;ubtract fee from amount</source> <translation>S&amp;ubtract fee from amount</translation> </message> <message> <source>Message:</source> <translation>Message:</translation> </message> <message> <source>This is an unauthenticated payment request.</source> <translation>This is an unauthenticated payment request.</translation> </message> <message> <source>This is an authenticated payment request.</source> <translation>This is an authenticated payment request.</translation> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation>Enter a label for this address to add it to the list of used addresses</translation> </message> <message> <source>A message that was attached to the viacoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Viacoin network.</source> <translation>A message that was attached to the viacoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Viacoin network.</translation> </message> <message> <source>Pay To:</source> <translation>Pay To:</translation> </message> <message> <source>Memo:</source> <translation>Memo:</translation> </message> </context> <context> <name>SendConfirmationDialog</name> </context> <context> <name>ShutdownWindow</name> <message> <source>%1 is shutting down...</source> <translation>%1 is shutting down...</translation> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>Do not shut down the computer until this window disappears.</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>Signatures - Sign / Verify a Message</translation> </message> <message> <source>&amp;Sign Message</source> <translation>&amp;Sign Message</translation> </message> <message> <source>You can sign messages/agreements with your addresses to prove you can receive viacoins sent to them. Be careful not to sign anything vague or random, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>You can sign messages/agreements with your addresses to prove you can receive viacoins sent to them. Be careful not to sign anything vague or random, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</translation> </message> <message> <source>The Viacoin address to sign the message with</source> <translation>The Viacoin address to sign the message with</translation> </message> <message> <source>Choose previously used address</source> <translation>Choose previously used address</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Paste address from clipboard</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation>Enter the message you want to sign here</translation> </message> <message> <source>Signature</source> <translation>Signature</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>Copy the current signature to the system clipboard</translation> </message> <message> <source>Sign the message to prove you own this Viacoin address</source> <translation>Sign the message to prove you own this Viacoin address</translation> </message> <message> <source>Sign &amp;Message</source> <translation>Sign &amp;Message</translation> </message> <message> <source>Reset all sign message fields</source> <translation>Reset all sign message fields</translation> </message> <message> <source>Clear &amp;All</source> <translation>Clear &amp;All</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;Verify Message</translation> </message> <message> <source>Enter the receiver's address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack. Note that this only proves the signing party receives with the address, it cannot prove sendership of any transaction!</source> <translation>Enter the receiver's address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack. Note that this only proves the signing party receives with the address, it cannot prove sendership of any transaction!</translation> </message> <message> <source>The Viacoin address the message was signed with</source> <translation>The Viacoin address the message was signed with</translation> </message> <message> <source>Verify the message to ensure it was signed with the specified Viacoin address</source> <translation>Verify the message to ensure it was signed with the specified Viacoin address</translation> </message> <message> <source>Verify &amp;Message</source> <translation>Verify &amp;Message</translation> </message> <message> <source>Reset all verify message fields</source> <translation>Reset all verify message fields</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[testnet]</translation><|fim▁hole|> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation>KB/s</translation> </message> </context> <context> <name>TransactionDesc</name> </context> <context> <name>TransactionDescDialog</name> <message> <source>This pane shows a detailed description of the transaction</source> <translation>This pane shows a detailed description of the transaction</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Label</source> <translation>Label</translation> </message> <message> <source>(no label)</source> <translation>(no label)</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <source>Label</source> <translation>Label</translation> </message> <message> <source>Address</source> <translation>Address</translation> </message> <message> <source>Exporting Failed</source> <translation>Exporting Failed</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> <message> <source>Unit to show amounts in. Click to select another unit.</source> <translation>Unit to show amounts in. Click to select another unit.</translation> </message> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> </context> <context> <name>bitcoin-core</name> <message> <source>Options:</source> <translation>Options:</translation> </message> <message> <source>Specify data directory</source> <translation>Specify data directory</translation> </message> <message> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Connect to a node to retrieve peer addresses, and disconnect</translation> </message> <message> <source>Specify your own public address</source> <translation>Specify your own public address</translation> </message> <message> <source>Accept command line and JSON-RPC commands</source> <translation>Accept command line and JSON-RPC commands</translation> </message> <message> <source>If &lt;category&gt; is not supplied or if &lt;category&gt; = 1, output all debugging information.</source> <translation>If &lt;category&gt; is not supplied or if &lt;category&gt; = 1, output all debugging information.</translation> </message> <message> <source>Prune configured below the minimum of %d MiB. Please use a higher number.</source> <translation>Prune configured below the minimum of %d MiB. Please use a higher number.</translation> </message> <message> <source>Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)</source> <translation>Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)</translation> </message> <message> <source>Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. Warning: Reverting this setting requires re-downloading the entire blockchain. (default: 0 = disable pruning blocks, &gt;%u = target size in MiB to use for block files)</source> <translation>Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. Warning: Reverting this setting requires re-downloading the entire blockchain. (default: 0 = disable pruning blocks, &gt;%u = target size in MiB to use for block files)</translation> </message> <message> <source>Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.</source> <translation>Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.</translation> </message> <message> <source>Error: A fatal internal error occurred, see debug.log for details</source> <translation>Error: A fatal internal error occurred, see debug.log for details</translation> </message> <message> <source>Fee (in %s/kB) to add to transactions you send (default: %s)</source> <translation>Fee (in %s/kB) to add to transactions you send (default: %s)</translation> </message> <message> <source>Pruning blockstore...</source> <translation>Pruning blockstore...</translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>Run in the background as a daemon and accept commands</translation> </message> <message> <source>Unable to start HTTP server. See debug log for details.</source> <translation>Unable to start HTTP server. See debug log for details.</translation> </message> <message> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accept connections from outside (default: 1 if no -proxy or -connect)</translation> </message> <message> <source>Viacoin Core</source> <translation>Viacoin Core</translation> </message> <message> <source>The %s developers</source> <translation>The %s developers</translation> </message> <message> <source>-fallbackfee is set very high! This is the transaction fee you may pay when fee estimates are not available.</source> <translation>-fallbackfee is set very high! This is the transaction fee you may pay when fee estimates are not available.</translation> </message> <message> <source>A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)</source> <translation>A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)</translation> </message> <message> <source>Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)</source> <translation>Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)</translation> </message> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Bind to given address and always listen on it. Use [host]:port notation for IPv6</translation> </message> <message> <source>Cannot obtain a lock on data directory %s. %s is probably already running.</source> <translation>Cannot obtain a lock on data directory %s. %s is probably already running.</translation> </message> <message> <source>Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup</source> <translation>Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup</translation> </message> <message> <source>Distributed under the MIT software license, see the accompanying file COPYING or &lt;http://www.opensource.org/licenses/mit-license.php&gt;.</source> <translation>Distributed under the MIT software license, see the accompanying file COPYING or &lt;http://www.opensource.org/licenses/mit-license.php&gt;.</translation> </message> <message> <source>Equivalent bytes per sigop in transactions for relay and mining (default: %u)</source> <translation>Equivalent bytes per sigop in transactions for relay and mining (default: %u)</translation> </message> <message> <source>Error loading %s: You can't enable HD on a already existing non-HD wallet</source> <translation>Error loading %s: You can't enable HD on a already existing non-HD wallet</translation> </message> <message> <source>Error reading %s! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Error reading %s! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</translation> </message> <message> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</translation> </message> <message> <source>Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)</source> <translation>Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)</translation> </message> <message> <source>Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)</source> <translation>Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)</translation> </message> <message> <source>Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.</source> <translation>Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.</translation> </message> <message> <source>Please contribute if you find %s useful. Visit %s for further information about the software.</source> <translation>Please contribute if you find %s useful. Visit %s for further information about the software.</translation> </message> <message> <source>Set the number of script verification threads (%u to %d, 0 = auto, &lt;0 = leave that many cores free, default: %d)</source> <translation>Set the number of script verification threads (%u to %d, 0 = auto, &lt;0 = leave that many cores free, default: %d)</translation> </message> <message> <source>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</source> <translation>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</translation> </message> <message> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</translation> </message> <message> <source>Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain</source> <translation>Unable to rewind the database to a pre-fork state. You will need to re-download the blockchain</translation> </message> <message> <source>Use UPnP to map the listening port (default: 1 when listening and no -proxy)</source> <translation>Use UPnP to map the listening port (default: 1 when listening and no -proxy)</translation> </message> <message> <source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source> <translation>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</translation> </message> <message> <source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</translation> </message> <message> <source>Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.</source> <translation>Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.</translation> </message> <message> <source>You need to rebuild the database using -reindex-chainstate to change -txindex</source> <translation>You need to rebuild the database using -reindex-chainstate to change -txindex</translation> </message> <message> <source>%s corrupt, salvage failed</source> <translation>%s corrupt, salvage failed</translation> </message> <message> <source>-maxmempool must be at least %d MB</source> <translation>-maxmempool must be at least %d MB</translation> </message> <message> <source>&lt;category&gt; can be:</source> <translation>&lt;category&gt; can be:</translation> </message> <message> <source>Append comment to the user agent string</source> <translation>Append comment to the user agent string</translation> </message> <message> <source>Attempt to recover private keys from a corrupt wallet on startup</source> <translation>Attempt to recover private keys from a corrupt wallet on startup</translation> </message> <message> <source>Block creation options:</source> <translation>Block creation options:</translation> </message> <message> <source>Cannot resolve -%s address: '%s'</source> <translation>Cannot resolve -%s address: '%s'</translation> </message> <message> <source>Change index out of range</source> <translation>Change index out of range</translation> </message> <message> <source>Connect only to the specified node(s)</source> <translation>Connect only to the specified node(s)</translation> </message> <message> <source>Connection options:</source> <translation>Connection options:</translation> </message> <message> <source>Copyright (C) %i-%i</source> <translation>Copyright (C) %i-%i</translation> </message> <message> <source>Corrupted block database detected</source> <translation>Corrupted block database detected</translation> </message> <message> <source>Debugging/Testing options:</source> <translation>Debugging/Testing options:</translation> </message> <message> <source>Do not load the wallet and disable wallet RPC calls</source> <translation>Do not load the wallet and disable wallet RPC calls</translation> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation>Do you want to rebuild the block database now?</translation> </message> <message> <source>Enable publish hash block in &lt;address&gt;</source> <translation>Enable publish hash block in &lt;address&gt;</translation> </message> <message> <source>Enable publish hash transaction in &lt;address&gt;</source> <translation>Enable publish hash transaction in &lt;address&gt;</translation> </message> <message> <source>Enable publish raw block in &lt;address&gt;</source> <translation>Enable publish raw block in &lt;address&gt;</translation> </message> <message> <source>Enable publish raw transaction in &lt;address&gt;</source> <translation>Enable publish raw transaction in &lt;address&gt;</translation> </message> <message> <source>Enable transaction replacement in the memory pool (default: %u)</source> <translation>Enable transaction replacement in the memory pool (default: %u)</translation> </message> <message> <source>Error initializing block database</source> <translation>Error initialising block database</translation> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation>Error initialising wallet database environment %s!</translation> </message> <message> <source>Error loading %s</source> <translation>Error loading %s</translation> </message> <message> <source>Error loading %s: Wallet corrupted</source> <translation>Error loading %s: Wallet corrupted</translation> </message> <message> <source>Error loading %s: Wallet requires newer version of %s</source> <translation>Error loading %s: Wallet requires newer version of %s</translation> </message> <message> <source>Error loading %s: You can't disable HD on a already existing HD wallet</source> <translation>Error loading %s: You can't disable HD on a already existing HD wallet</translation> </message> <message> <source>Error loading block database</source> <translation>Error loading block database</translation> </message> <message> <source>Error opening block database</source> <translation>Error opening block database</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>Error: Disk space is low!</translation> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Failed to listen on any port. Use -listen=0 if you want this.</translation> </message> <message> <source>Importing...</source> <translation>Importing...</translation> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>Incorrect or no genesis block found. Wrong datadir for network?</translation> </message> <message> <source>Initialization sanity check failed. %s is shutting down.</source> <translation>Initialisation sanity check failed. %s is shutting down.</translation> </message> <message> <source>Invalid -onion address: '%s'</source> <translation>Invalid -onion address: '%s'</translation> </message> <message> <source>Invalid amount for -%s=&lt;amount&gt;: '%s'</source> <translation>Invalid amount for -%s=&lt;amount&gt;: '%s'</translation> </message> <message> <source>Invalid amount for -fallbackfee=&lt;amount&gt;: '%s'</source> <translation>Invalid amount for -fallbackfee=&lt;amount&gt;: '%s'</translation> </message> <message> <source>Keep the transaction memory pool below &lt;n&gt; megabytes (default: %u)</source> <translation>Keep the transaction memory pool below &lt;n&gt; megabytes (default: %u)</translation> </message> <message> <source>Loading banlist...</source> <translation>Loading banlist...</translation> </message> <message> <source>Location of the auth cookie (default: data dir)</source> <translation>Location of the auth cookie (default: data dir)</translation> </message> <message> <source>Not enough file descriptors available.</source> <translation>Not enough file descriptors available.</translation> </message> <message> <source>Only connect to nodes in network &lt;net&gt; (ipv4, ipv6 or onion)</source> <translation>Only connect to nodes in network &lt;net&gt; (ipv4, ipv6 or onion)</translation> </message> <message> <source>Print this help message and exit</source> <translation>Print this help message and exit</translation> </message> <message> <source>Print version and exit</source> <translation>Print version and exit</translation> </message> <message> <source>Prune cannot be configured with a negative value.</source> <translation>Prune cannot be configured with a negative value.</translation> </message> <message> <source>Prune mode is incompatible with -txindex.</source> <translation>Prune mode is incompatible with -txindex.</translation> </message> <message> <source>Rebuild chain state and block index from the blk*.dat files on disk</source> <translation>Rebuild chain state and block index from the blk*.dat files on disk</translation> </message> <message> <source>Rebuild chain state from the currently indexed blocks</source> <translation>Rebuild chain state from the currently indexed blocks</translation> </message> <message> <source>Rewinding blocks...</source> <translation>Rewinding blocks...</translation> </message> <message> <source>Set database cache size in megabytes (%d to %d, default: %d)</source> <translation>Set database cache size in megabytes (%d to %d, default: %d)</translation> </message> <message> <source>Set maximum BIP141 block weight (default: %d)</source> <translation>Set maximum BIP141 block weight (default: %d)</translation> </message> <message> <source>Set maximum block size in bytes (default: %d)</source> <translation>Set maximum block size in bytes (default: %d)</translation> </message> <message> <source>Specify wallet file (within data directory)</source> <translation>Specify wallet file (within data directory)</translation> </message> <message> <source>The source code is available from %s.</source> <translation>The source code is available from %s.</translation> </message> <message> <source>Unable to bind to %s on this computer. %s is probably already running.</source> <translation>Unable to bind to %s on this computer. %s is probably already running.</translation> </message> <message> <source>Unsupported argument -benchmark ignored, use -debug=bench.</source> <translation>Unsupported argument -benchmark ignored, use -debug=bench.</translation> </message> <message> <source>Unsupported argument -debugnet ignored, use -debug=net.</source> <translation>Unsupported argument -debugnet ignored, use -debug=net.</translation> </message> <message> <source>Unsupported argument -tor found, use -onion.</source> <translation>Unsupported argument -tor found, use -onion.</translation> </message> <message> <source>Use UPnP to map the listening port (default: %u)</source> <translation>Use UPnP to map the listening port (default: %u)</translation> </message> <message> <source>User Agent comment (%s) contains unsafe characters.</source> <translation>User Agent comment (%s) contains unsafe characters.</translation> </message> <message> <source>Verifying blocks...</source> <translation>Verifying blocks...</translation> </message> <message> <source>Verifying wallet...</source> <translation>Verifying wallet...</translation> </message> <message> <source>Wallet %s resides outside data directory %s</source> <translation>Wallet %s resides outside data directory %s</translation> </message> <message> <source>Wallet debugging/testing options:</source> <translation>Wallet debugging/testing options:</translation> </message> <message> <source>Wallet needed to be rewritten: restart %s to complete</source> <translation>Wallet needed to be rewritten: restart %s to complete</translation> </message> <message> <source>Wallet options:</source> <translation>Wallet options:</translation> </message> <message> <source>Allow JSON-RPC connections from specified source. Valid for &lt;ip&gt; are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times</source> <translation>Allow JSON-RPC connections from specified source. Valid for &lt;ip&gt; are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times</translation> </message> <message> <source>Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6</source> <translation>Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6</translation> </message> <message> <source>Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)</source> <translation>Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)</translation> </message> <message> <source>Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)</source> <translation>Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)</translation> </message> <message> <source>Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)</source> <translation>Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)</translation> </message> <message> <source>Error: Listening for incoming connections failed (listen returned error %s)</source> <translation>Error: Listening for incoming connections failed (listen returned error %s)</translation> </message> <message> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</translation> </message> <message> <source>Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)</source> <translation>Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)</translation> </message> <message> <source>If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)</source> <translation>If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)</translation> </message> <message> <source>Invalid amount for -maxtxfee=&lt;amount&gt;: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)</source> <translation>Invalid amount for -maxtxfee=&lt;amount&gt;: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)</translation> </message> <message> <source>Maximum size of data in data carrier transactions we relay and mine (default: %u)</source> <translation>Maximum size of data in data carrier transactions we relay and mine (default: %u)</translation> </message> <message> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</translation> </message> <message> <source>Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)</source> <translation>Randomise credentials for every proxy connection. This enables Tor stream isolation (default: %u)</translation> </message> <message> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</translation> </message> <message> <source>The transaction amount is too small to send after the fee has been deducted</source> <translation>The transaction amount is too small to send after the fee has been deducted</translation> </message> <message> <source>This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit &lt;https://www.openssl.org/&gt; and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.</source> <translation>This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit &lt;https://www.openssl.org/&gt; and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.</translation> </message> <message> <source>Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start</source> <translation>Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start</translation> </message> <message> <source>Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway</source> <translation>Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway</translation> </message> <message> <source>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</source> <translation>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</translation> </message> <message> <source>(default: %u)</source> <translation>(default: %u)</translation> </message> <message> <source>Accept public REST requests (default: %u)</source> <translation>Accept public REST requests (default: %u)</translation> </message> <message> <source>Automatically create Tor hidden service (default: %d)</source> <translation>Automatically create Tor hidden service (default: %d)</translation> </message> <message> <source>Connect through SOCKS5 proxy</source> <translation>Connect through SOCKS5 proxy</translation> </message> <message> <source>Error reading from database, shutting down.</source> <translation>Error reading from database, shutting down.</translation> </message> <message> <source>Imports blocks from external blk000??.dat file on startup</source> <translation>Imports blocks from external blk000??.dat file on startup</translation> </message> <message> <source>Information</source> <translation>Information</translation> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: '%s' (must be at least %s)</source> <translation>Invalid amount for -paytxfee=&lt;amount&gt;: '%s' (must be at least %s)</translation> </message> <message> <source>Invalid netmask specified in -whitelist: '%s'</source> <translation>Invalid netmask specified in -whitelist: '%s'</translation> </message> <message> <source>Keep at most &lt;n&gt; unconnectable transactions in memory (default: %u)</source> <translation>Keep at most &lt;n&gt; unconnectable transactions in memory (default: %u)</translation> </message> <message> <source>Need to specify a port with -whitebind: '%s'</source> <translation>Need to specify a port with -whitebind: '%s'</translation> </message> <message> <source>Node relay options:</source> <translation>Node relay options:</translation> </message> <message> <source>RPC server options:</source> <translation>RPC server options:</translation> </message> <message> <source>Reducing -maxconnections from %d to %d, because of system limitations.</source> <translation>Reducing -maxconnections from %d to %d, because of system limitations.</translation> </message> <message> <source>Rescan the block chain for missing wallet transactions on startup</source> <translation>Rescan the block chain for missing wallet transactions on startup</translation> </message> <message> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Send trace/debug info to console instead of debug.log file</translation> </message> <message> <source>Send transactions as zero-fee transactions if possible (default: %u)</source> <translation>Send transactions as zero-fee transactions if possible (default: %u)</translation> </message> <message> <source>Show all debugging options (usage: --help -help-debug)</source> <translation>Show all debugging options (usage: --help -help-debug)</translation> </message> <message> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Shrink debug.log file on client startup (default: 1 when no -debug)</translation> </message> <message> <source>Signing transaction failed</source> <translation>Signing transaction failed</translation> </message> <message> <source>The transaction amount is too small to pay the fee</source> <translation>The transaction amount is too small to pay the fee</translation> </message> <message> <source>This is experimental software.</source> <translation>This is experimental software.</translation> </message> <message> <source>Tor control port password (default: empty)</source> <translation>Tor control port password (default: empty)</translation> </message> <message> <source>Tor control port to use if onion listening enabled (default: %s)</source> <translation>Tor control port to use if onion listening enabled (default: %s)</translation> </message> <message> <source>Transaction amount too small</source> <translation>Transaction amount too small</translation> </message> <message> <source>Transaction amounts must be positive</source> <translation>Transaction amounts must be positive</translation> </message> <message> <source>Transaction too large for fee policy</source> <translation>Transaction too large for fee policy</translation> </message> <message> <source>Transaction too large</source> <translation>Transaction too large</translation> </message> <message> <source>Unable to bind to %s on this computer (bind returned error %s)</source> <translation>Unable to bind to %s on this computer (bind returned error %s)</translation> </message> <message> <source>Upgrade wallet to latest format on startup</source> <translation>Upgrade wallet to latest format on startup</translation> </message> <message> <source>Username for JSON-RPC connections</source> <translation>Username for JSON-RPC connections</translation> </message> <message> <source>Warning</source> <translation>Warning</translation> </message> <message> <source>Warning: unknown new rules activated (versionbit %i)</source> <translation>Warning: unknown new rules activated (versionbit %i)</translation> </message> <message> <source>Whether to operate in a blocks only mode (default: %u)</source> <translation>Whether to operate in a blocks only mode (default: %u)</translation> </message> <message> <source>Zapping all transactions from wallet...</source> <translation>Zapping all transactions from wallet...</translation> </message> <message> <source>ZeroMQ notification options:</source> <translation>ZeroMQ notification options:</translation> </message> <message> <source>Password for JSON-RPC connections</source> <translation>Password for JSON-RPC connections</translation> </message> <message> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Execute command when the best block changes (%s in cmd is replaced by block hash)</translation> </message> <message> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Allow DNS lookups for -addnode, -seednode and -connect</translation> </message> <message> <source>Loading addresses...</source> <translation>Loading addresses...</translation> </message> <message> <source>(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)</source> <translation>(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)</translation> </message> <message> <source>-maxtxfee is set very high! Fees this large could be paid on a single transaction.</source> <translation>-maxtxfee is set very high! Fees this large could be paid on a single transaction.</translation> </message> <message> <source>-paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>-paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</translation> </message> <message> <source>Do not keep transactions in the mempool longer than &lt;n&gt; hours (default: %u)</source> <translation>Do not keep transactions in the mempool longer than &lt;n&gt; hours (default: %u)</translation> </message> <message> <source>Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)</source> <translation>Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)</translation> </message> <message> <source>How thorough the block verification of -checkblocks is (0-4, default: %u)</source> <translation>How thorough the block verification of -checkblocks is (0-4, default: %u)</translation> </message> <message> <source>Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)</source> <translation>Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)</translation> </message> <message> <source>Number of seconds to keep misbehaving peers from reconnecting (default: %u)</source> <translation>Number of seconds to keep misbehaving peers from reconnecting (default: %u)</translation> </message> <message> <source>Output debugging information (default: %u, supplying &lt;category&gt; is optional)</source> <translation>Output debugging information (default: %u, supplying &lt;category&gt; is optional)</translation> </message> <message> <source>Support filtering of blocks and transaction with bloom filters (default: %u)</source> <translation>Support filtering of blocks and transaction with bloom filters (default: %u)</translation> </message> <message> <source>Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.</source> <translation>Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.</translation> </message> <message> <source>Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)</source> <translation>Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)</translation> </message> <message> <source>Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source> <translation>Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</translation> </message> <message> <source>Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay.</source> <translation>Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay.</translation> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)</source> <translation>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)</translation> </message> <message> <source>Username and hashed password for JSON-RPC connections. The field &lt;userpw&gt; comes in the format: &lt;USERNAME&gt;:&lt;SALT&gt;$&lt;HASH&gt;. A canonical python script is included in share/rpcuser. This option can be specified multiple times</source> <translation>Username and hashed password for JSON-RPC connections. The field &lt;userpw&gt; comes in the format: &lt;USERNAME&gt;:&lt;SALT&gt;$&lt;HASH&gt;. A canonical python script is included in share/rpcuser. This option can be specified multiple times</translation> </message> <message> <source>Warning: Unknown block versions being mined! It's possible unknown rules are in effect</source> <translation>Warning: Unknown block versions being mined! It's possible unknown rules are in effect</translation> </message> <message> <source>Warning: Wallet file corrupt, data salvaged! Original %s saved as %s in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Warning: Wallet file corrupt, data salvaged! Original %s saved as %s in %s; if your balance or transactions are incorrect you should restore from a backup.</translation> </message> <message> <source>(default: %s)</source> <translation>(default: %s)</translation> </message> <message> <source>Always query for peer addresses via DNS lookup (default: %u)</source> <translation>Always query for peer addresses via DNS lookup (default: %u)</translation> </message> <message> <source>How many blocks to check at startup (default: %u, 0 = all)</source> <translation>How many blocks to check at startup (default: %u, 0 = all)</translation> </message> <message> <source>Include IP addresses in debug output (default: %u)</source> <translation>Include IP addresses in debug output (default: %u)</translation> </message> <message> <source>Invalid -proxy address: '%s'</source> <translation>Invalid -proxy address: '%s'</translation> </message> <message> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: %u or testnet: %u)</source> <translation>Listen for JSON-RPC connections on &lt;port&gt; (default: %u or testnet: %u)</translation> </message> <message> <source>Listen for connections on &lt;port&gt; (default: %u or testnet: %u)</source> <translation>Listen for connections on &lt;port&gt; (default: %u or testnet: %u)</translation> </message> <message> <source>Maintain at most &lt;n&gt; connections to peers (default: %u)</source> <translation>Maintain at most &lt;n&gt; connections to peers (default: %u)</translation> </message> <message> <source>Make the wallet broadcast transactions</source> <translation>Make the wallet broadcast transactions</translation> </message> <message> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: %u)</source> <translation>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: %u)</translation> </message> <message> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: %u)</source> <translation>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: %u)</translation> </message> <message> <source>Prepend debug output with timestamp (default: %u)</source> <translation>Prepend debug output with timestamp (default: %u)</translation> </message> <message> <source>Relay and mine data carrier transactions (default: %u)</source> <translation>Relay and mine data carrier transactions (default: %u)</translation> </message> <message> <source>Relay non-P2SH multisig (default: %u)</source> <translation>Relay non-P2SH multisig (default: %u)</translation> </message> <message> <source>Set key pool size to &lt;n&gt; (default: %u)</source> <translation>Set key pool size to &lt;n&gt; (default: %u)</translation> </message> <message> <source>Set the number of threads to service RPC calls (default: %d)</source> <translation>Set the number of threads to service RPC calls (default: %d)</translation> </message> <message> <source>Specify configuration file (default: %s)</source> <translation>Specify configuration file (default: %s)</translation> </message> <message> <source>Specify connection timeout in milliseconds (minimum: 1, default: %d)</source> <translation>Specify connection timeout in milliseconds (minimum: 1, default: %d)</translation> </message> <message> <source>Specify pid file (default: %s)</source> <translation>Specify pid file (default: %s)</translation> </message> <message> <source>Spend unconfirmed change when sending transactions (default: %u)</source> <translation>Spend unconfirmed change when sending transactions (default: %u)</translation> </message> <message> <source>Threshold for disconnecting misbehaving peers (default: %u)</source> <translation>Threshold for disconnecting misbehaving peers (default: %u)</translation> </message> <message> <source>Unknown network specified in -onlynet: '%s'</source> <translation>Unknown network specified in -onlynet: '%s'</translation> </message> <message> <source>Insufficient funds</source> <translation>Insufficient funds</translation> </message> <message> <source>Loading block index...</source> <translation>Loading block index...</translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Add a node to connect to and attempt to keep the connection open</translation> </message> <message> <source>Loading wallet...</source> <translation>Loading wallet...</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>Cannot downgrade wallet</translation> </message> <message> <source>Cannot write default address</source> <translation>Cannot write default address</translation> </message> <message> <source>Rescanning...</source> <translation>Rescanning...</translation> </message> <message> <source>Done loading</source> <translation>Done loading</translation> </message> <message> <source>Error</source> <translation>Error</translation> </message> </context> </TS><|fim▁end|>
</message> </context> <context>
<|file_name|>calculator.py<|end_file_name|><|fim▁begin|># # calculator.py : A calculator module for the deskbar applet. # # Copyright (C) 2008 by Johannes Buchner # Copyright (C) 2007 by Michael Hofmann # Copyright (C) 2006 by Callum McKenzie # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Authors: # Callum McKenzie <[email protected]> - Original author # Michael Hofmann <[email protected]> - compatibility changes for deskbar 2.20 # Johannes Buchner <[email protected]> - Made externally usable # # This version of calculator can be used with converter # read how at http://twoday.tuwien.ac.at/jo/search?q=calculator+converter+deskbar # from __future__ import division from deskbar.handlers.actions.CopyToClipboardAction import CopyToClipboardAction from deskbar.defs import VERSION from gettext import gettext as _ import deskbar.core.Utils import deskbar.interfaces.Match import deskbar.interfaces.Module import logging import math import re LOGGER = logging.getLogger(__name__) HANDLERS = ["CalculatorModule"] def bin (n): """A local binary equivalent of the hex and oct builtins.""" if (n == 0): return "0b0" s = "" if (n < 0): while n != -1: s = str (n & 1) + s n >>= 1 return "0b" + "...111" + s else: while n != 0: s = str (n & 1) + s n >>= 1 return "0b" + s # These next three make sure {hex, oct, bin} can handle floating point, # by rounding. This makes sure things like hex(255/2) behave as a # programmer would expect while allowing 255/2 to equal 127.5 for normal # people. Abstracting out the body of these into a single function which # takes hex, oct or bin as an argument seems to run into problems with # those functions not being defined correctly in the resticted eval (?). def lenient_hex (c): try: return hex (c) except TypeError: return hex (int (c)) def lenient_oct (c): try: return oct (c) except TypeError: return oct (int (c)) def lenient_bin (c): try: return bin (c) except TypeError: return bin (int (c)) class CalculatorAction (CopyToClipboardAction): def __init__ (self, text, answer): CopyToClipboardAction.__init__ (self, answer, answer) self.text = text def get_verb(self): return _("Copy <b>%(origtext)s = %(name)s</b> to clipboard") def get_name(self, text = None): """Because the text variable for history entries contains the text typed for the history search (and not the text of the orginal action), we store the original text seperately.""" result = CopyToClipboardAction.get_name (self, text) result["origtext"] = self.text return result def get_tooltip(self, text=None): return self._name class CalculatorMatch (deskbar.interfaces.Match): def __init__ (self, text, answer, **kwargs): deskbar.interfaces.Match.__init__ (self, name = text, icon = "gtk-add", category = "calculator", **kwargs) self.answer = str (answer) self.add_action (CalculatorAction (text, self.answer)) def get_hash (self): return self.answer class CalculatorModule (deskbar.interfaces.Module): INFOS = {"icon": deskbar.core.Utils.load_icon ("gtk-add"), "name": _("Calculator"), "description": _("Calculate simple equations"), "version" : VERSION, "categories" : { "calculator" : { "name" : _("Calculator") }}} def __init__ (self): deskbar.interfaces.Module.__init__ (self) self.hexre = re.compile ("0[Xx][0-9a-fA-F_]*[0-9a-fA-F]") self.binre = re.compile ("0[bB][01_]*[01]") def _number_parser (self, match, base): """A generic number parser, regardless of base. It also ignores the '_' character so it can be used as a separator. Note how we skip the first two characters since we assume it is something like '0x' or '0b' and identifies the base.""" table = { '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, 'a' : 10, 'b' : 11, 'c' : 12, 'd' : 13, 'e' : 14, 'f' : 15 } d = 0 for c in match.group()[2:]: if c != "_": d = d * base + table[c] return str (d) def _binsub (self, match): """Because python doesn't handle binary literals, we parse it ourselves and replace it with a decimal representation.""" return self._number_parser (match, 2) def _hexsub (self, match): """Parse the hex literal ourselves. We could let python do it, but<|fim▁hole|> def run_query (self, query): """We evaluate the equation by first replacing hex and binary literals with their decimal representation. (We need to check hex, so we can distinguish 0x10b1 as a hex number, not 0x1 followed by 0b1.) We severely restrict the eval environment. Any errors are ignored.""" restricted_dictionary = { "__builtins__" : None, "abs" : abs, "acos" : math.acos, "asin" : math.asin, "atan" : math.atan, "atan2" : math.atan2, "bin" : lenient_bin,"ceil" : math.ceil, "cos" : math.cos, "cosh" : math.cosh, "degrees" : math.degrees, "exp" : math.exp, "floor" : math.floor, "hex" : lenient_hex, "int" : int, "log" : math.log, "pow" : math.pow, "log10" : math.log10, "oct" : lenient_oct, "pi" : math.pi, "radians" : math.radians, "round": round, "sin" : math.sin, "sinh" : math.sinh, "sqrt" : math.sqrt, "tan" : math.tan, "tanh" : math.tanh} try: scrubbedquery = query.lower() scrubbedquery = self.hexre.sub (self._hexsub, scrubbedquery) scrubbedquery = self.binre.sub (self._binsub, scrubbedquery) for (c1, c2) in (("[", "("), ("{", "("), ("]", ")"), ("}", ")")): scrubbedquery = scrubbedquery.replace (c1, c2) answer = eval (scrubbedquery, restricted_dictionary) # Try and avoid echoing back simple numbers. Note that this # doesn't work well for floating point, e.g. '3.' behaves badly. if str (answer) == query: return None # We need this check because the eval can return function objects # when we are halfway through typing the expression. if isinstance (answer, (float, int, long, str)): return answer else: return None except Exception, e: LOGGER.debug (str(e)) return None def query (self, query): answer = self.run_query(query) if answer != None: result = [CalculatorMatch (query, answer)] self._emit_query_ready (query, result) return answer else: return []<|fim▁end|>
since we have a generic parser we use that instead.""" return self._number_parser (match, 16)
<|file_name|>test_instructor_dashboard.py<|end_file_name|><|fim▁begin|>""" End to end tests for Instructor Dashboard. """ from bok_choy.web_app_test import WebAppTest from regression.pages.lms.course_page_lms import CourseHomePageExtended from regression.pages.lms.dashboard_lms import DashboardPageExtended<|fim▁hole|>from regression.pages.lms.instructor_dashboard import InstructorDashboardPageExtended from regression.pages.lms.utils import get_course_key from regression.tests.helpers.api_clients import LmsLoginApi from regression.tests.helpers.utils import get_course_display_name, get_course_info class AnalyticsTest(WebAppTest): """ Regression tests on Analytics on Instructor Dashboard """ def setUp(self): super().setUp() login_api = LmsLoginApi() login_api.authenticate(self.browser) course_info = get_course_info() self.dashboard_page = DashboardPageExtended(self.browser) self.instructor_dashboard = InstructorDashboardPageExtended( self.browser, get_course_key(course_info) ) self.course_page = CourseHomePageExtended( self.browser, get_course_key(course_info) ) self.dashboard_page.visit() self.dashboard_page.select_course(get_course_display_name()) self.course_page.wait_for_page() self.instructor_dashboard.visit()<|fim▁end|>
<|file_name|>_color.py<|end_file_name|><|fim▁begin|><|fim▁hole|> def __init__( self, plotly_name="color", parent_name="histogram2dcontour.textfont", **kwargs ): super(ColorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), **kwargs )<|fim▁end|>
import _plotly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
<|file_name|>user.rs<|end_file_name|><|fim▁begin|>use conduit::{Handler, Request, Method}; use cargo_registry::Model; use cargo_registry::krate::EncodableCrate; use cargo_registry::user::{User, EncodableUser}; use cargo_registry::db::RequestTransaction; use cargo_registry::version::EncodableVersion; #[derive(RustcDecodable)] struct AuthResponse { url: String, state: String } #[derive(RustcDecodable)] struct MeResponse { user: EncodableUser, api_token: String } #[test] fn auth_gives_a_token() { let (_b, app, middle) = ::app(); let mut req = ::req(app, Method::Get, "/authorize_url"); let mut response = ok_resp!(middle.call(&mut req)); let json: AuthResponse = ::json(&mut response); assert!(json.url.contains(&json.state)); } #[test] fn access_token_needs_data() { let (_b, app, middle) = ::app(); let mut req = ::req(app, Method::Get, "/authorize"); let mut response = ok_resp!(middle.call(&mut req)); let json: ::Bad = ::json(&mut response); assert!(json.errors[0].detail.contains("invalid state")); } #[test] fn user_insert() { let (_b, app, _middle) = ::app(); let conn = t!(app.database.get()); let tx = t!(conn.transaction()); let user = t!(User::find_or_insert(&tx, 1, "foo", None, None, None, "bar", "baz")); assert_eq!(t!(User::find_by_api_token(&tx, "baz")), user); assert_eq!(t!(User::find(&tx, user.id)), user); assert_eq!(t!(User::find_or_insert(&tx, 1, "foo", None, None, None, "bar", "api")), user); let user2 = t!(User::find_or_insert(&tx, 1, "foo", None, None, None, "baz", "api")); assert!(user != user2); assert_eq!(user.id, user2.id); assert_eq!(user2.gh_access_token, "baz"); let user3 = t!(User::find_or_insert(&tx, 1, "bar", None, None, None, "baz", "api")); assert!(user != user3); assert_eq!(user.id, user3.id); assert_eq!(user3.gh_login, "bar"); } #[test]<|fim▁hole|> let mut req = ::req(app, Method::Get, "/me"); let response = t_resp!(middle.call(&mut req)); assert_eq!(response.status.0, 403); let user = ::user("foo"); ::mock_user(&mut req, user.clone()); let mut response = ok_resp!(middle.call(&mut req)); let json: MeResponse = ::json(&mut response); assert_eq!(json.user.email, user.email); assert_eq!(json.api_token, user.api_token); } #[test] fn reset_token() { let (_b, app, middle) = ::app(); let mut req = ::req(app, Method::Put, "/me/reset_token"); let user = { let tx = RequestTransaction::tx(&mut req as &mut Request); User::find_or_insert(tx.unwrap(), 1, "foo", None, None, None, "bar", "baz").unwrap() }; ::mock_user(&mut req, user.clone()); ok_resp!(middle.call(&mut req)); let tx = RequestTransaction::tx(&mut req as &mut Request); let u2 = User::find(tx.unwrap(), user.id).unwrap(); assert!(u2.api_token != user.api_token); } #[test] fn my_packages() { let (_b, app, middle) = ::app(); let mut req = ::req(app, Method::Get, "/api/v1/crates"); let u = ::mock_user(&mut req, ::user("foo")); ::mock_crate(&mut req, ::krate("foo")); req.with_query(&format!("user_id={}", u.id)); let mut response = ok_resp!(middle.call(&mut req)); #[derive(RustcDecodable)] struct Response { crates: Vec<EncodableCrate> } let response: Response = ::json(&mut response); assert_eq!(response.crates.len(), 1); } #[test] fn following() { #[derive(RustcDecodable)] struct R { versions: Vec<EncodableVersion>, meta: Meta, } #[derive(RustcDecodable)] struct Meta { more: bool } let (_b, app, middle) = ::app(); let mut req = ::req(app, Method::Get, "/"); ::mock_user(&mut req, ::user("foo")); ::mock_crate(&mut req, ::krate("foo")); ::mock_crate(&mut req, ::krate("bar")); let mut response = ok_resp!(middle.call(req.with_path("/me/updates") .with_method(Method::Get))); let r = ::json::<R>(&mut response); assert_eq!(r.versions.len(), 0); assert_eq!(r.meta.more, false); ok_resp!(middle.call(req.with_path("/api/v1/crates/foo/follow") .with_method(Method::Put))); ok_resp!(middle.call(req.with_path("/api/v1/crates/bar/follow") .with_method(Method::Put))); let mut response = ok_resp!(middle.call(req.with_path("/me/updates") .with_method(Method::Get))); let r = ::json::<R>(&mut response); assert_eq!(r.versions.len(), 2); assert_eq!(r.meta.more, false); let mut response = ok_resp!(middle.call(req.with_path("/me/updates") .with_method(Method::Get) .with_query("per_page=1"))); let r = ::json::<R>(&mut response); assert_eq!(r.versions.len(), 1); assert_eq!(r.meta.more, true); ok_resp!(middle.call(req.with_path("/api/v1/crates/bar/follow") .with_method(Method::Delete))); let mut response = ok_resp!(middle.call(req.with_path("/me/updates") .with_method(Method::Get) .with_query("page=2&per_page=1"))); let r = ::json::<R>(&mut response); assert_eq!(r.versions.len(), 0); assert_eq!(r.meta.more, false); bad_resp!(middle.call(req.with_query("page=0"))); }<|fim▁end|>
fn me() { let (_b, app, middle) = ::app();
<|file_name|>AP_Compass_LSM303D.cpp<|end_file_name|><|fim▁begin|>/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <AP_Math/AP_Math.h> #include <AP_HAL/AP_HAL.h> #include "AP_Compass_LSM303D.h" extern const AP_HAL::HAL& hal; #if CONFIG_HAL_BOARD == HAL_BOARD_LINUX #include <AP_HAL_Linux/GPIO.h> #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_RASPILOT #define LSM303D_DRDY_M_PIN RPI_GPIO_27 #endif #endif #ifndef LSM303D_DRDY_M_PIN #define LSM303D_DRDY_M_PIN -1 #endif /* SPI protocol address bits */ #define DIR_READ (1<<7) #define DIR_WRITE (0<<7) #define ADDR_INCREMENT (1<<6) /* register addresses: A: accel, M: mag, T: temp */ #define ADDR_WHO_AM_I 0x0F #define WHO_I_AM 0x49 #define ADDR_OUT_TEMP_L 0x05 #define ADDR_OUT_TEMP_H 0x06 #define ADDR_STATUS_M 0x07 #define ADDR_OUT_X_L_M 0x08 #define ADDR_OUT_X_H_M 0x09 #define ADDR_OUT_Y_L_M 0x0A #define ADDR_OUT_Y_H_M 0x0B #define ADDR_OUT_Z_L_M 0x0C #define ADDR_OUT_Z_H_M 0x0D #define ADDR_INT_CTRL_M 0x12 #define ADDR_INT_SRC_M 0x13 #define ADDR_REFERENCE_X 0x1c #define ADDR_REFERENCE_Y 0x1d #define ADDR_REFERENCE_Z 0x1e #define ADDR_STATUS_A 0x27 #define ADDR_OUT_X_L_A 0x28 #define ADDR_OUT_X_H_A 0x29 #define ADDR_OUT_Y_L_A 0x2A #define ADDR_OUT_Y_H_A 0x2B #define ADDR_OUT_Z_L_A 0x2C #define ADDR_OUT_Z_H_A 0x2D #define ADDR_CTRL_REG0 0x1F #define ADDR_CTRL_REG1 0x20 #define ADDR_CTRL_REG2 0x21 #define ADDR_CTRL_REG3 0x22 #define ADDR_CTRL_REG4 0x23 #define ADDR_CTRL_REG5 0x24 #define ADDR_CTRL_REG6 0x25 #define ADDR_CTRL_REG7 0x26 #define ADDR_FIFO_CTRL 0x2e #define ADDR_FIFO_SRC 0x2f #define ADDR_IG_CFG1 0x30 #define ADDR_IG_SRC1 0x31 #define ADDR_IG_THS1 0x32 #define ADDR_IG_DUR1 0x33 #define ADDR_IG_CFG2 0x34 #define ADDR_IG_SRC2 0x35 #define ADDR_IG_THS2 0x36 #define ADDR_IG_DUR2 0x37 #define ADDR_CLICK_CFG 0x38 #define ADDR_CLICK_SRC 0x39 #define ADDR_CLICK_THS 0x3a #define ADDR_TIME_LIMIT 0x3b #define ADDR_TIME_LATENCY 0x3c #define ADDR_TIME_WINDOW 0x3d #define ADDR_ACT_THS 0x3e #define ADDR_ACT_DUR 0x3f #define REG1_RATE_BITS_A ((1<<7) | (1<<6) | (1<<5) | (1<<4)) #define REG1_POWERDOWN_A ((0<<7) | (0<<6) | (0<<5) | (0<<4)) #define REG1_RATE_3_125HZ_A ((0<<7) | (0<<6) | (0<<5) | (1<<4)) #define REG1_RATE_6_25HZ_A ((0<<7) | (0<<6) | (1<<5) | (0<<4)) #define REG1_RATE_12_5HZ_A ((0<<7) | (0<<6) | (1<<5) | (1<<4)) #define REG1_RATE_25HZ_A ((0<<7) | (1<<6) | (0<<5) | (0<<4)) #define REG1_RATE_50HZ_A ((0<<7) | (1<<6) | (0<<5) | (1<<4)) #define REG1_RATE_100HZ_A ((0<<7) | (1<<6) | (1<<5) | (0<<4)) #define REG1_RATE_200HZ_A ((0<<7) | (1<<6) | (1<<5) | (1<<4)) #define REG1_RATE_400HZ_A ((1<<7) | (0<<6) | (0<<5) | (0<<4)) #define REG1_RATE_800HZ_A ((1<<7) | (0<<6) | (0<<5) | (1<<4)) #define REG1_RATE_1600HZ_A ((1<<7) | (0<<6) | (1<<5) | (0<<4)) #define REG1_BDU_UPDATE (1<<3) #define REG1_Z_ENABLE_A (1<<2) #define REG1_Y_ENABLE_A (1<<1) #define REG1_X_ENABLE_A (1<<0) #define REG2_ANTIALIAS_FILTER_BW_BITS_A ((1<<7) | (1<<6)) #define REG2_AA_FILTER_BW_773HZ_A ((0<<7) | (0<<6)) #define REG2_AA_FILTER_BW_194HZ_A ((0<<7) | (1<<6)) #define REG2_AA_FILTER_BW_362HZ_A ((1<<7) | (0<<6)) #define REG2_AA_FILTER_BW_50HZ_A ((1<<7) | (1<<6)) #define REG2_FULL_SCALE_BITS_A ((1<<5) | (1<<4) | (1<<3)) #define REG2_FULL_SCALE_2G_A ((0<<5) | (0<<4) | (0<<3)) #define REG2_FULL_SCALE_4G_A ((0<<5) | (0<<4) | (1<<3)) #define REG2_FULL_SCALE_6G_A ((0<<5) | (1<<4) | (0<<3)) #define REG2_FULL_SCALE_8G_A ((0<<5) | (1<<4) | (1<<3)) #define REG2_FULL_SCALE_16G_A ((1<<5) | (0<<4) | (0<<3)) #define REG5_ENABLE_T (1<<7) #define REG5_RES_HIGH_M ((1<<6) | (1<<5)) #define REG5_RES_LOW_M ((0<<6) | (0<<5)) #define REG5_RATE_BITS_M ((1<<4) | (1<<3) | (1<<2)) #define REG5_RATE_3_125HZ_M ((0<<4) | (0<<3) | (0<<2)) #define REG5_RATE_6_25HZ_M ((0<<4) | (0<<3) | (1<<2)) #define REG5_RATE_12_5HZ_M ((0<<4) | (1<<3) | (0<<2)) #define REG5_RATE_25HZ_M ((0<<4) | (1<<3) | (1<<2)) #define REG5_RATE_50HZ_M ((1<<4) | (0<<3) | (0<<2)) #define REG5_RATE_100HZ_M ((1<<4) | (0<<3) | (1<<2)) #define REG5_RATE_DO_NOT_USE_M ((1<<4) | (1<<3) | (0<<2)) #define REG6_FULL_SCALE_BITS_M ((1<<6) | (1<<5)) #define REG6_FULL_SCALE_2GA_M ((0<<6) | (0<<5)) #define REG6_FULL_SCALE_4GA_M ((0<<6) | (1<<5)) #define REG6_FULL_SCALE_8GA_M ((1<<6) | (0<<5)) #define REG6_FULL_SCALE_12GA_M ((1<<6) | (1<<5)) #define REG7_CONT_MODE_M ((0<<1) | (0<<0)) #define INT_CTRL_M 0x12 #define INT_SRC_M 0x13 /* default values for this device */ #define LSM303D_ACCEL_DEFAULT_RANGE_G 8 #define LSM303D_ACCEL_DEFAULT_RATE 800 #define LSM303D_ACCEL_DEFAULT_ONCHIP_FILTER_FREQ 50 #define LSM303D_ACCEL_DEFAULT_DRIVER_FILTER_FREQ 30 #define LSM303D_MAG_DEFAULT_RANGE_GA 2 #define LSM303D_MAG_DEFAULT_RATE 100 #define LSM303D_DEBUG 0 #if LSM303D_DEBUG #include <stdio.h> #define error(...) fprintf(stderr, __VA_ARGS__) #define debug(...) hal.console->printf(__VA_ARGS__) #define ASSERT(x) assert(x) #else #define error(...) #define debug(...) #define ASSERT(x) #endif // constructor AP_Compass_LSM303D::AP_Compass_LSM303D(Compass &compass): AP_Compass_Backend(compass) {} // detect the sensor AP_Compass_Backend *AP_Compass_LSM303D::detect_spi(Compass &compass) { AP_Compass_LSM303D *sensor = new AP_Compass_LSM303D(compass); if (sensor == NULL) { return NULL; } if (!sensor->init()) { delete sensor; return NULL; } return sensor; } uint8_t AP_Compass_LSM303D::_register_read(uint8_t reg) { uint8_t addr = reg | 0x80; // Set most significant bit<|fim▁hole|> tx[0] = addr; tx[1] = 0; _spi->transaction(tx, rx, 2); return rx[1]; } void AP_Compass_LSM303D::_register_write(uint8_t reg, uint8_t val) { uint8_t tx[2]; uint8_t rx[2]; tx[0] = reg; tx[1] = val; _spi->transaction(tx, rx, 2); } void AP_Compass_LSM303D::_register_modify(uint8_t reg, uint8_t clearbits, uint8_t setbits) { uint8_t val; val = _register_read(reg); val &= ~clearbits; val |= setbits; _register_write(reg, val); } /** * Return true if the LSM303D has new data available for both the mag and * the accels. */ bool AP_Compass_LSM303D::_data_ready() { return (_drdy_pin_m->read()) != 0; } // Read Sensor data bool AP_Compass_LSM303D::_read_raw() { if (_register_read(ADDR_CTRL_REG7) != _reg7_expected) { hal.console->println_P( PSTR("LSM303D _read_data_transaction_accel: _reg7_expected unexpected")); // reset(); return false; } if (!_data_ready()) { return false; } struct PACKED { uint8_t cmd; uint8_t status; int16_t x; int16_t y; int16_t z; } raw_mag_report_tx; struct PACKED { uint8_t cmd; uint8_t status; int16_t x; int16_t y; int16_t z; } raw_mag_report_rx; /* fetch data from the sensor */ memset(&raw_mag_report_tx, 0, sizeof(raw_mag_report_tx)); memset(&raw_mag_report_rx, 0, sizeof(raw_mag_report_rx)); raw_mag_report_tx.cmd = ADDR_STATUS_M | DIR_READ | ADDR_INCREMENT; _spi->transaction((uint8_t *)&raw_mag_report_tx, (uint8_t *)&raw_mag_report_rx, sizeof(raw_mag_report_tx)); _mag_x = raw_mag_report_rx.x; _mag_y = raw_mag_report_rx.y; _mag_z = raw_mag_report_rx.z; if (is_zero(_mag_x) && is_zero(_mag_y) && is_zero(_mag_z)) { return false; } return true; } // Public Methods ////////////////////////////////////////////////////////////// bool AP_Compass_LSM303D::init() { // TODO: support users without data ready pin if (LSM303D_DRDY_M_PIN < 0) return false; hal.scheduler->suspend_timer_procs(); _spi = hal.spi->device(AP_HAL::SPIDevice_LSM303D); _spi_sem = _spi->get_semaphore(); _drdy_pin_m = hal.gpio->channel(LSM303D_DRDY_M_PIN); _drdy_pin_m->mode(HAL_GPIO_INPUT); // Test WHOAMI uint8_t whoami = _register_read(ADDR_WHO_AM_I); if (whoami != WHO_I_AM) { hal.console->printf("LSM303D: unexpected WHOAMI 0x%x\n", (unsigned)whoami); hal.scheduler->panic(PSTR("LSM303D: bad WHOAMI")); } uint8_t tries = 0; do { // TODO: don't try to init 25 times bool success = _hardware_init(); if (success) { hal.scheduler->delay(5+2); if (!_spi_sem->take(100)) { hal.scheduler->panic(PSTR("LSM303D: Unable to get semaphore")); } if (_data_ready()) { _spi_sem->give(); break; } else { hal.console->println_P( PSTR("LSM303D startup failed: no data ready")); } _spi_sem->give(); } if (tries++ > 5) { hal.scheduler->panic(PSTR("PANIC: failed to boot LSM303D 5 times")); } } while (1); _scaling[0] = 1.0; _scaling[1] = 1.0; _scaling[2] = 1.0; /* register the compass instance in the frontend */ _compass_instance = register_compass(); set_dev_id(_compass_instance, get_dev_id()); #if CONFIG_HAL_BOARD == HAL_BOARD_LINUX && CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_RASPILOT set_external(_compass_instance, false); #endif hal.scheduler->register_timer_process(FUNCTOR_BIND_MEMBER(&AP_Compass_LSM303D::_update, void)); set_milligauss_ratio(_compass_instance, 1.0f); _spi_sem->give(); hal.scheduler->resume_timer_procs(); _initialised = true; return _initialised; } uint32_t AP_Compass_LSM303D::get_dev_id() { return AP_COMPASS_TYPE_LSM303D; } bool AP_Compass_LSM303D::_hardware_init(void) { if (!_spi_sem->take(100)) { hal.scheduler->panic(PSTR("LSM303D: Unable to get semaphore")); } // initially run the bus at low speed _spi->set_bus_speed(AP_HAL::SPIDeviceDriver::SPI_SPEED_LOW); // ensure the chip doesn't interpret any other bus traffic as I2C _disable_i2c(); /* enable mag */ _reg7_expected = REG7_CONT_MODE_M; _register_write(ADDR_CTRL_REG7, _reg7_expected); _register_write(ADDR_CTRL_REG5, REG5_RES_HIGH_M); _register_write(ADDR_CTRL_REG4, 0x04); // DRDY on MAG on INT2 _mag_set_range(LSM303D_MAG_DEFAULT_RANGE_GA); _mag_set_samplerate(LSM303D_MAG_DEFAULT_RATE); // TODO: Software filtering // now that we have initialised, we set the SPI bus speed to high _spi->set_bus_speed(AP_HAL::SPIDeviceDriver::SPI_SPEED_HIGH); _spi_sem->give(); return true; } void AP_Compass_LSM303D::_update() { if (hal.scheduler->micros() - _last_update_timestamp < 10000) { return; } if (!_spi_sem->take_nonblocking()) { return; } _collect_samples(); _last_update_timestamp = hal.scheduler->micros(); _spi_sem->give(); } void AP_Compass_LSM303D::_collect_samples() { if (!_initialised) { return; } if (!_read_raw()) { error("_read_raw() failed\n"); } else { Vector3f raw_field = Vector3f(_mag_x, _mag_y, _mag_z) * _mag_range_scale; uint32_t time_us = hal.scheduler->micros(); // rotate raw_field from sensor frame to body frame rotate_field(raw_field, _compass_instance); // publish raw_field (uncorrected point sample) for _scaling use publish_raw_field(raw_field, time_us, _compass_instance); // correct raw_field for known errors correct_field(raw_field, _compass_instance); // publish raw_field (corrected point sample) for EKF use publish_unfiltered_field(raw_field, time_us, _compass_instance); _mag_x_accum += raw_field.x; _mag_y_accum += raw_field.y; _mag_z_accum += raw_field.z; _accum_count++; if (_accum_count == 10) { _mag_x_accum /= 2; _mag_y_accum /= 2; _mag_z_accum /= 2; _accum_count = 5; } } } // Read Sensor data void AP_Compass_LSM303D::read() { if (!_initialised) { // someone has tried to enable a compass for the first time // mid-flight .... we can't do that yet (especially as we won't // have the right orientation!) return; } if (_accum_count == 0) { /* We're not ready to publish*/ return; } hal.scheduler->suspend_timer_procs(); Vector3f field(_mag_x_accum * _scaling[0], _mag_y_accum * _scaling[1], _mag_z_accum * _scaling[2]); field /= _accum_count; _accum_count = 0; _mag_x_accum = _mag_y_accum = _mag_z_accum = 0; hal.scheduler->resume_timer_procs(); publish_filtered_field(field, _compass_instance); } void AP_Compass_LSM303D::_disable_i2c(void) { // TODO: use the register names uint8_t a = _register_read(0x02); _register_write(0x02, (0x10 | a)); a = _register_read(0x02); _register_write(0x02, (0xF7 & a)); a = _register_read(0x15); _register_write(0x15, (0x80 | a)); a = _register_read(0x02); _register_write(0x02, (0xE7 & a)); } uint8_t AP_Compass_LSM303D::_mag_set_range(uint8_t max_ga) { uint8_t setbits = 0; uint8_t clearbits = REG6_FULL_SCALE_BITS_M; float new_scale_ga_digit = 0.0f; if (max_ga == 0) max_ga = 12; if (max_ga <= 2) { _mag_range_ga = 2; setbits |= REG6_FULL_SCALE_2GA_M; new_scale_ga_digit = 0.080f; } else if (max_ga <= 4) { _mag_range_ga = 4; setbits |= REG6_FULL_SCALE_4GA_M; new_scale_ga_digit = 0.160f; } else if (max_ga <= 8) { _mag_range_ga = 8; setbits |= REG6_FULL_SCALE_8GA_M; new_scale_ga_digit = 0.320f; } else if (max_ga <= 12) { _mag_range_ga = 12; setbits |= REG6_FULL_SCALE_12GA_M; new_scale_ga_digit = 0.479f; } else { return -1; } _mag_range_scale = new_scale_ga_digit; _register_modify(ADDR_CTRL_REG6, clearbits, setbits); return 0; } uint8_t AP_Compass_LSM303D::_mag_set_samplerate(uint16_t frequency) { uint8_t setbits = 0; uint8_t clearbits = REG5_RATE_BITS_M; if (frequency == 0) frequency = 100; if (frequency <= 25) { setbits |= REG5_RATE_25HZ_M; _mag_samplerate = 25; } else if (frequency <= 50) { setbits |= REG5_RATE_50HZ_M; _mag_samplerate = 50; } else if (frequency <= 100) { setbits |= REG5_RATE_100HZ_M; _mag_samplerate = 100; } else { return -1; } _register_modify(ADDR_CTRL_REG5, clearbits, setbits); return 0; }<|fim▁end|>
uint8_t tx[2]; uint8_t rx[2];
<|file_name|>xhr_impl.js<|end_file_name|><|fim▁begin|>'use strict';var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var di_1 = require('angular2/src/core/di'); var serializer_1 = require('angular2/src/web_workers/shared/serializer'); var messaging_api_1 = require('angular2/src/web_workers/shared/messaging_api'); var xhr_1 = require('angular2/src/core/compiler/xhr'); var service_message_broker_1 = require('angular2/src/web_workers/shared/service_message_broker'); var bind_1 = require('./bind'); var MessageBasedXHRImpl = (function () { function MessageBasedXHRImpl(_brokerFactory, _xhr) { this._brokerFactory = _brokerFactory; this._xhr = _xhr; } MessageBasedXHRImpl.prototype.start = function () { var broker = this._brokerFactory.createMessageBroker(messaging_api_1.XHR_CHANNEL); broker.registerMethod("get", [serializer_1.PRIMITIVE], bind_1.bind(this._xhr.get, this._xhr), serializer_1.PRIMITIVE); }; MessageBasedXHRImpl = __decorate([ di_1.Injectable(), __metadata('design:paramtypes', [service_message_broker_1.ServiceMessageBrokerFactory, xhr_1.XHR]) ], MessageBasedXHRImpl); return MessageBasedXHRImpl;<|fim▁hole|>})(); exports.MessageBasedXHRImpl = MessageBasedXHRImpl; //# sourceMappingURL=xhr_impl.js.map<|fim▁end|>
<|file_name|>show.d.ts<|end_file_name|><|fim▁begin|>/// <reference types="hapi__joi" /> import Joi from '@hapi/joi'; import { Status as Tweet } from 'twitter-d'; import { AuthenticatedTwitterCallHandler } from '../../twitter-call-handler'; <|fim▁hole|> include_entities: boolean; include_ext_alt_text: boolean; include_card_uri: boolean; } export declare type ShowResults = Tweet; export declare const optionsSchema: Joi.ObjectSchema<any>; export declare function show(callHandler: AuthenticatedTwitterCallHandler, options: ShowOptions): Promise<ShowResults>;<|fim▁end|>
export interface ShowOptions { id: string; trim_user: boolean; include_my_retweet: boolean;
<|file_name|>grid-tile.ts<|end_file_name|><|fim▁begin|>/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Component, ViewEncapsulation, ElementRef, Input, Optional, ContentChildren, QueryList, AfterContentInit, Directive, ChangeDetectionStrategy, Inject, } from '@angular/core'; import {MatLine, setLines} from '@angular/material/core'; import {coerceNumberProperty} from '@angular/cdk/coercion'; import {MAT_GRID_LIST, MatGridListBase} from './grid-list-base'; @Component({ moduleId: module.id, selector: 'mat-grid-tile', exportAs: 'matGridTile', host: { 'class': 'mat-grid-tile', }, templateUrl: 'grid-tile.html', styleUrls: ['grid-list.css'], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatGridTile { _rowspan: number = 1; _colspan: number = 1; constructor( private _element: ElementRef<HTMLElement>, @Optional() @Inject(MAT_GRID_LIST) public _gridList?: MatGridListBase) {} /** Amount of rows that the grid tile takes up. */ @Input() get rowspan(): number { return this._rowspan; } set rowspan(value: number) { this._rowspan = Math.round(coerceNumberProperty(value)); } /** Amount of columns that the grid tile takes up. */ @Input() get colspan(): number { return this._colspan; } set colspan(value: number) { this._colspan = Math.round(coerceNumberProperty(value)); } /** * Sets the style of the grid-tile element. Needs to be set manually to avoid * "Changed after checked" errors that would occur with HostBinding. */ _setStyle(property: string, value: any): void { (this._element.nativeElement.style as any)[property] = value; } } @Component({ moduleId: module.id, selector: 'mat-grid-tile-header, mat-grid-tile-footer', templateUrl: 'grid-tile-text.html', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class MatGridTileText implements AfterContentInit { @ContentChildren(MatLine) _lines: QueryList<MatLine>; constructor(private _element: ElementRef<HTMLElement>) {} ngAfterContentInit() { setLines(this._lines, this._element); } } /** * Directive whose purpose is to add the mat- CSS styling to this selector. * @docs-private */ @Directive({ selector: '[mat-grid-avatar], [matGridAvatar]', host: {'class': 'mat-grid-avatar'} }) export class MatGridAvatarCssMatStyler {} /** * Directive whose purpose is to add the mat- CSS styling to this selector. * @docs-private */ @Directive({ selector: 'mat-grid-tile-header', host: {'class': 'mat-grid-tile-header'} }) export class MatGridTileHeaderCssMatStyler {} /** * Directive whose purpose is to add the mat- CSS styling to this selector.<|fim▁hole|> * @docs-private */ @Directive({ selector: 'mat-grid-tile-footer', host: {'class': 'mat-grid-tile-footer'} }) export class MatGridTileFooterCssMatStyler {}<|fim▁end|>
<|file_name|>data_wrangle_total.py<|end_file_name|><|fim▁begin|>import json from pprint import pprint import time import io # from http://www.codigomanso.com/en/2011/05/trucomanso-transformar-el-tiempo-en-formato-24h-a-formato-12h-python/ def ampmformat (hhmmss): """ This method converts time in 24h format to 12h format Example: "00:32" is "12:32 AM" "13:33" is "01:33 PM"<|fim▁hole|> """ ampm = hhmmss.split (":") if (len(ampm) == 0) or (len(ampm) > 3): return hhmmss # is AM? from [00:00, 12:00[ hour = int(ampm[0]) % 24 isam = (hour >= 0) and (hour < 12) # 00:32 should be 12:32 AM not 00:32 if isam: ampm[0] = ('12' if (hour == 0) else "%02d" % (hour)) else: ampm[0] = ('12' if (hour == 12) else "%02d" % (hour-12)) return ':'.join (ampm) + (' AM' if isam else ' PM') json_data=open('allData2003_2004.json') data = json.load(json_data) json_data.close() # k ='690150' # print data['690150'] output = {} for k in data.keys(): for d in data[k]: date = time.strptime(d['date'], "%b %d, %Y %I:%M:%S %p") if k in output: t = ampmformat('%02d:%02d:%02d' % (date.tm_hour, date.tm_min, date.tm_sec)) h = date.tm_hour output[k]['sum'] += d['value'] output[k]['hourly'][h] += d['value'] else: output[k] = { "sum": 0, "hourly": [0]*24 } t = ampmformat('%02d:%02d:%02d' % (date.tm_hour, date.tm_min, date.tm_sec)) h = date.tm_hour output[k]['sum'] += d['value'] output[k]['hourly'][h] += d['value'] f = io.open('data.json', 'w', encoding='utf-8') f.write(unicode(json.dumps(output, ensure_ascii=False))) f.close() json_output=open('data.json') output_data = json.load(json_output) pprint(output_data) json_output.close()<|fim▁end|>
<|file_name|>201_ice_mismatch_1.py<|end_file_name|><|fim▁begin|># $Id: 201_ice_mismatch_1.py 2392 2008-12-22 18:54:58Z bennylp $ import inc_sip as sip import inc_sdp as sdp<|fim▁hole|>v=0 o=- 0 0 IN IP4 127.0.0.1 s=pjmedia c=IN IP4 127.0.0.1 t=0 0 m=audio 4000 RTP/AVP 0 101 a=ice-ufrag:1234 a=ice-pwd:5678 a=rtpmap:0 PCMU/8000 a=sendrecv a=rtpmap:101 telephone-event/8000 a=fmtp:101 0-15 a=candidate:XX 1 UDP 1 1.1.1.1 2222 typ host """ args = "--null-audio --use-ice --auto-answer 200 --max-calls 1" include = ["a=ice-mismatch"] exclude = [] sendto_cfg = sip.SendtoCfg( "caller sends mismatched offer for comp 1", pjsua_args=args, sdp=sdp, resp_code=200, resp_inc=include, resp_exc=exclude)<|fim▁end|>
sdp = \ """
<|file_name|>signature.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 3.0.0.11832 (http://hl7.org/fhir/StructureDefinition/Signature) on 2017-03-22. # 2017, SMART Health IT. from . import element class Signature(element.Element): """ A digital Signature - XML DigSig, JWT, Graphical image of signature, etc.. A digital signature along with supporting context. The signature may be<|fim▁hole|> """ resource_type = "Signature" def __init__(self, jsondict=None, strict=True): """ Initialize all valid properties. :raises: FHIRValidationError on validation errors, unless strict is False :param dict jsondict: A JSON dictionary to use for initialization :param bool strict: If True (the default), invalid variables will raise a TypeError """ self.blob = None """ The actual signature content (XML DigSig. JWT, picture, etc.). Type `str`. """ self.contentType = None """ The technical format of the signature. Type `str`. """ self.onBehalfOfReference = None """ The party represented. Type `FHIRReference` referencing `Practitioner, RelatedPerson, Patient, Device, Organization` (represented as `dict` in JSON). """ self.onBehalfOfUri = None """ The party represented. Type `str`. """ self.type = None """ Indication of the reason the entity signed the object(s). List of `Coding` items (represented as `dict` in JSON). """ self.when = None """ When the signature was created. Type `FHIRDate` (represented as `str` in JSON). """ self.whoReference = None """ Who signed. Type `FHIRReference` referencing `Practitioner, RelatedPerson, Patient, Device, Organization` (represented as `dict` in JSON). """ self.whoUri = None """ Who signed. Type `str`. """ super(Signature, self).__init__(jsondict=jsondict, strict=strict) def elementProperties(self): js = super(Signature, self).elementProperties() js.extend([ ("blob", "blob", str, False, None, False), ("contentType", "contentType", str, False, None, False), ("onBehalfOfReference", "onBehalfOfReference", fhirreference.FHIRReference, False, "onBehalfOf", False), ("onBehalfOfUri", "onBehalfOfUri", str, False, "onBehalfOf", False), ("type", "type", coding.Coding, True, None, True), ("when", "when", fhirdate.FHIRDate, False, None, True), ("whoReference", "whoReference", fhirreference.FHIRReference, False, "who", True), ("whoUri", "whoUri", str, False, "who", True), ]) return js import sys try: from . import coding except ImportError: coding = sys.modules[__package__ + '.coding'] try: from . import fhirdate except ImportError: fhirdate = sys.modules[__package__ + '.fhirdate'] try: from . import fhirreference except ImportError: fhirreference = sys.modules[__package__ + '.fhirreference']<|fim▁end|>
electronic/cryptographic in nature, or a graphical image representing a hand-written signature, or a signature process. Different signature approaches have different utilities.
<|file_name|>main.cpp<|end_file_name|><|fim▁begin|>/*! \file main.cpp \author Standa Kubín \date 31.03.2016 \brief server aplikace pro řízení okenních rolet */ #include <QCoreApplication> #include <QSharedPointer> #include <QThread> #include <QFile> #include <QUdpSocket> #include <QDebug> #include <QSemaphore> class GPIO_CONTROL : public QObject { Q_OBJECT public: enum class GPIO_Type { INPUT, //!< vstup OUTPUT //!< výstup }; GPIO_CONTROL(QObject *pParent, quint16 nGPIO, GPIO_Type eType); virtual ~GPIO_CONTROL(); //! vrátí hodnotu GPIO bool GetValue(); //! nastaví hodnotu GPIO void SetValue(bool bValue); private: QFile m_oFile; //!< soubor pro zápis do nebo čtení z GPIO GPIO_Type m_eGPIO_Type; //!< typ přístupu na GPIO }; class BLIND_THREAD : public QThread { Q_OBJECT public: BLIND_THREAD(quint16 nGPIO_Pulse, quint16 nGPIO_Direction, quint16 nGPIO_FB, QSharedPointer<QSemaphore> Semaphore); virtual ~BLIND_THREAD(); //! ukončí thread void Stop() { m_bStop = true; } //! vrací true, pokud thread běží bool IsRunning() const { return m_bRunning; } //! vrátí pozici rolety qint32 GetValuePercent() const { return (m_nTargetPosition * 100) / m_sc_nMaximumPositionValue; } //! nastaví pozici rolety void SetValuePercent(qint32 nValuePercent) { m_nTargetPosition = (m_sc_nMaximumPositionValue * nValuePercent) / 100; } //! spustí kalibraci void Calibre() { m_bCalibre = true; } protected: //! vstupní bod nového threadu<|fim▁hole|> virtual void run(); private: enum class ACTION { None, //!< neprobíhá žádná akce Calibration, //!< probíhá kalibrace Movement //!< probíhá standardní pohyb na nastavenou pozici }; enum class DIRECTION { DOWN, //!< roleta pojede nahoru UP //!< roleta pojede dolu }; static const quint32 m_sc_nMaximumPositionValue = 10240; //!< počet impulsů krokového motoru pro sjetí rotety ze shora dolů QScopedPointer<GPIO_CONTROL> m_oPulse; //!< GPIO pro řízení otáčení QScopedPointer<GPIO_CONTROL> m_oDirection; //!< GPIO pro nastavení směru otáčení QScopedPointer<GPIO_CONTROL> m_oFB; //!< GPIO pro získání stavu rulety QSharedPointer<QSemaphore> m_Semaphore; //!< it controls access to the common HW resources bool m_bRunning; //!< příznak běžícího threadu bool m_bStop; //!< příznak pro ukončení threadu bool m_bCalibre; //!< požadavek na spuštění kalibrace rolety quint32 m_nActualPosition; //!< aktuální pozice rolety quint32 m_nTargetPosition; //!< cílová pozice rolety quint32 m_nTargetPositionWorkingThread; //!< cílová pozice rolety pro m_eAction == ACTION::Movement ACTION m_eAction; //!< aktuální práce threadu //! nastaví směr pohybu void SetDirection(DIRECTION eDirection); //! vygeneruje impuls void GeneratePulse(); //! vrací true, pokud je roleta úplně nahoře bool IsBlindUp(); }; class BLIND : public QObject { Q_OBJECT public: BLIND(QObject *pParent, quint16 nGPIO_Pulse, quint16 nGPIO_Direction, quint16 nGPIO_FB, QSharedPointer<QSemaphore> Semaphore); virtual ~BLIND() {} //! vrátí pozici rolety qint32 GetValuePercent() const; //! nastaví pozici rolety void SetValuePercent(qint32 nValuePercent); private: QScopedPointer<BLIND_THREAD> m_oWorkingThread; //!< thread řídící motor QSharedPointer<QSemaphore> m_Semaphore; //!< it controls access to the common HW resources }; class BLINDS_CONTROLLER : public QObject { Q_OBJECT public: BLINDS_CONTROLLER(QObject *pParent = Q_NULLPTR); virtual ~BLINDS_CONTROLLER() {} private: struct Client { Client() : m_nPort(-1) {} Client(QHostAddress Address, qint32 nPort) : m_Address(Address), m_nPort(nPort) {} QHostAddress m_Address; //!< client address qint32 m_nPort; //!< client port inline bool operator==(const Client& X){ return X.m_Address == m_Address && X.m_nPort == m_nPort; } inline bool operator!=(const Client& X){ return X.m_Address != m_Address || X.m_nPort != m_nPort; } }; QHash<qint32, QSharedPointer<BLIND> > m_arrBlinds; //!< pole tříd pro řízení rolet QUdpSocket m_oUDP_SocketForReceiving; //!< UDP socket bound to the specific port intended for window blind settings receiving QUdpSocket m_oUDP_SocketForSending; //!< UDP socket intended for clients information about the new states QSharedPointer<QSemaphore> m_Semaphore; //!< it controls access to the common HW resources (it limites the number of simultaneously driven window blinds) QList<Client> m_arrClients; //!< list of registered clients (these clients are informed about the changes) private slots: // reakce na příjem UDP paketu void OnUDP_ProcessPendingMessage(); }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QScopedPointer<BLINDS_CONTROLLER> oBLINDS_CONTROLLER(new BLINDS_CONTROLLER()); return a.exec(); } GPIO_CONTROL::GPIO_CONTROL(QObject *pParent, quint16 nGPIO, GPIO_Type eType) : QObject(pParent), m_eGPIO_Type(eType) { // inicializujeme IO QFile oFile("/sys/class/gpio/export"); if(oFile.open(QIODevice::WriteOnly)) { QString strGPIO = QString::number(nGPIO); QString strDirection = "in"; QIODevice::OpenModeFlag eOpenModeFlag = QIODevice::ReadOnly; if(eType == GPIO_Type::OUTPUT) { strDirection = "out"; eOpenModeFlag = QIODevice::WriteOnly; } oFile.write(strGPIO.toLatin1()); oFile.flush(); oFile.close(); oFile.setFileName("/sys/class/gpio/gpio" + strGPIO + "/direction"); forever { if(oFile.open(QIODevice::WriteOnly)) { oFile.write(QString(strDirection).toLatin1()); oFile.flush(); oFile.close(); // otevřeme soubor pro nastavování nebo čtení hodnot m_oFile.setFileName("/sys/class/gpio/gpio" + strGPIO + "/value"); if(!m_oFile.open(eOpenModeFlag)) { qDebug() << "cannot open file" << m_oFile.fileName(); } break; } else { qDebug() << "cannot open file" << oFile.fileName(); } } } else { qDebug() << "cannot open file" << oFile.fileName(); } } GPIO_CONTROL::~GPIO_CONTROL() { m_oFile.close(); } bool GPIO_CONTROL::GetValue() { if(m_oFile.isOpen()) { QByteArray arrData = m_oFile.read(1); if(arrData.count()) { return arrData.at(0) == '1'; } } return false; } void GPIO_CONTROL::SetValue(bool bValue) { if(m_eGPIO_Type == GPIO_Type::OUTPUT) { if(m_oFile.isOpen()) { m_oFile.write(QString(bValue ? "1" : "0").toLatin1()); m_oFile.flush(); } } } BLIND_THREAD::BLIND_THREAD(quint16 nGPIO_Pulse, quint16 nGPIO_Direction, quint16 nGPIO_FB, QSharedPointer<QSemaphore> Semaphore) : QThread() { m_oPulse.reset(new GPIO_CONTROL(this, nGPIO_Pulse, GPIO_CONTROL::GPIO_Type::OUTPUT)); m_oDirection.reset(new GPIO_CONTROL(this, nGPIO_Direction, GPIO_CONTROL::GPIO_Type::OUTPUT)); m_oFB.reset(new GPIO_CONTROL(this, nGPIO_FB, GPIO_CONTROL::GPIO_Type::INPUT)); m_Semaphore = Semaphore; m_bRunning = false; m_bStop = false; m_bCalibre = false; m_nActualPosition = 0; m_nTargetPosition = 0; m_nTargetPositionWorkingThread = 0; m_eAction = ACTION::None; // spustíme kalibraci Calibre(); } BLIND_THREAD::~BLIND_THREAD() { if(IsRunning()) { Stop(); for(qint32 nTimeoutCounter = 0; nTimeoutCounter < 1000 && IsRunning(); nTimeoutCounter++) { QThread::msleep(1); } Q_ASSERT(!IsRunning()); } } void BLIND_THREAD::run() { m_bRunning = true; while(!m_bStop) { switch(m_eAction) { case ACTION::Calibration: if(IsBlindUp()) { // hotovo m_eAction = ACTION::None; m_nActualPosition = 0; m_bCalibre = false; // it releases HW resource m_Semaphore.data()->release(); } else { GeneratePulse(); } break; case ACTION::Movement: if(m_nActualPosition == m_nTargetPositionWorkingThread) { // hotovo m_eAction = ACTION::None; // it releases HW resource m_Semaphore.data()->release(); } if(m_nActualPosition < m_nTargetPositionWorkingThread) { GeneratePulse(); m_nActualPosition++; } if(m_nActualPosition > m_nTargetPositionWorkingThread) { GeneratePulse(); m_nActualPosition--; } break; case ACTION::None: if(m_bCalibre) { // it tries to acquire HW resource if(m_Semaphore.isNull() || !m_Semaphore.data()->tryAcquire()) { break; } // kalibrace m_eAction = ACTION::Calibration; SetDirection(DIRECTION::UP); break; } if(m_nActualPosition != m_nTargetPosition) { // it tries to acquire HW resource if(m_Semaphore.isNull() || !m_Semaphore.data()->tryAcquire()) { break; } // pohyb m_eAction = ACTION::Movement; m_nTargetPositionWorkingThread = m_nTargetPosition; SetDirection(m_nActualPosition < m_nTargetPositionWorkingThread ? DIRECTION::DOWN : DIRECTION::UP); break; } QThread::msleep(1); break; } } m_bRunning = false; } void BLIND_THREAD::SetDirection(BLIND_THREAD::DIRECTION eDirection) { if(!m_oDirection.isNull()) { m_oDirection.data()->SetValue(eDirection == DIRECTION::DOWN ? 1 : 0); } } void BLIND_THREAD::GeneratePulse() { // maximální rychlost = 1 KHz if(!m_oPulse.isNull()) { m_oPulse.data()->SetValue(true); QThread::usleep(500); m_oPulse.data()->SetValue(false); QThread::usleep(500); } } bool BLIND_THREAD::IsBlindUp() { if(!m_oFB.isNull()) { return m_oFB.data()->GetValue(); } return false; } BLIND::BLIND(QObject *pParent, quint16 nGPIO_Pulse, quint16 nGPIO_Direction, quint16 nGPIO_FB, QSharedPointer<QSemaphore> Semaphore) : QObject(pParent) { m_oWorkingThread.reset(new BLIND_THREAD(nGPIO_Pulse, nGPIO_Direction, nGPIO_FB, Semaphore)); // odstartujeme thread m_oWorkingThread.data()->start(); } qint32 BLIND::GetValuePercent() const { if(!m_oWorkingThread.isNull()) { return m_oWorkingThread.data()->GetValuePercent(); } return 0; } void BLIND::SetValuePercent(qint32 nValuePercent) { if(!m_oWorkingThread.isNull()) { m_oWorkingThread.data()->SetValuePercent(nValuePercent); } } BLINDS_CONTROLLER::BLINDS_CONTROLLER(QObject *pParent) : QObject(pParent) { // it sets the maximum count of simultaneously driven window blinds m_Semaphore.reset(new QSemaphore(2)); // nastavíme rolety m_arrBlinds[1] = QSharedPointer<BLIND>(new BLIND(this, 178, 193, 199, m_Semaphore)); // nastavíme UDP soket pro příjem požaadvků connect(&m_oUDP_SocketForReceiving, SIGNAL(readyRead()), this, SLOT(OnUDP_ProcessPendingMessage()), Qt::UniqueConnection); if(!m_oUDP_SocketForReceiving.bind(5674)) { qDebug() << "cannot bind UDP communication port"; } } void BLINDS_CONTROLLER::OnUDP_ProcessPendingMessage() { QByteArray arrDatagram; QHostAddress SenderAddress; quint16 nSenderPort = 0; while(m_oUDP_SocketForReceiving.hasPendingDatagrams()) { arrDatagram.resize(m_oUDP_SocketForReceiving.pendingDatagramSize()); if(m_oUDP_SocketForReceiving.readDatagram(arrDatagram.data(), arrDatagram.size(), &SenderAddress, &nSenderPort) == -1) { qDebug() << "unable to read UDP datagram"; } else { QStringList arr_strMessages = QString(arrDatagram).split("#"); foreach(QString strMessage, arr_strMessages) { QStringList arr_strMessageData = strMessage.split(";"); if(arr_strMessageData.count() >= 1) { if(arr_strMessageData.at(0) == "set_blind") { if(arr_strMessageData.count() >= 4) { qint32 nID = arr_strMessageData.at(1).toInt(); qint32 nPercentValue = arr_strMessageData.at(2).toInt(); if(m_arrBlinds.contains(nID)) { if(nPercentValue > 100) { nPercentValue = 100; } if(nPercentValue < 0) { nPercentValue = 0; } qDebug() << "blind ID" << nID << "value" << nPercentValue; if(!m_arrBlinds[nID].isNull()) { m_arrBlinds[nID].data()->SetValuePercent(nPercentValue); // send the new value to the other clients Client ClientHasSetTheValue(SenderAddress, arr_strMessageData.at(3).toInt()); foreach(Client ClientToBeInformed, m_arrClients) { if(ClientToBeInformed != ClientHasSetTheValue) { if(!m_oUDP_SocketForSending.writeDatagram(QByteArray(QString("blind_position;" + arr_strMessageData.at(1) + ";" + arr_strMessageData.at(2)).toLatin1() + "#"), ClientToBeInformed.m_Address, ClientToBeInformed.m_nPort) == -1) { qDebug() << "error while sending the new window blind position"; } } } } } else { qDebug() << "unknown blind ID"; } } else { qDebug() << "unknown UDP data format"; } } if(arr_strMessageData.at(0) == "register") { if(arr_strMessageData.count() >= 2) { Client NewClientToBeRegistrated(SenderAddress, arr_strMessageData.at(1).toInt()); qDebug() << "new client registration attempt, client address" << NewClientToBeRegistrated.m_Address << "port" << NewClientToBeRegistrated.m_nPort; if(!m_arrClients.contains(NewClientToBeRegistrated)) { m_arrClients.append(NewClientToBeRegistrated); // refresh the client by the actual window blind positions QHashIterator<qint32, QSharedPointer<BLIND> > iBlinds(m_arrBlinds); while(iBlinds.hasNext()) { iBlinds.next(); if(!m_oUDP_SocketForSending.writeDatagram(QByteArray(QString("blind_position;" + QString::number(iBlinds.key()) + ";" + QString::number(iBlinds.value().data()->GetValuePercent()) + "#").toLatin1()), NewClientToBeRegistrated.m_Address, NewClientToBeRegistrated.m_nPort) == -1) { qDebug() << "error while sending the new window blind position"; } } } } else { qDebug() << "unknown UDP data format"; } } } else { qDebug() << "unknown UDP data format"; } } } } } #include "main.moc"<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># $Filename$ # $Authors$ # # Last Changed: $Date$ $Committer$ $Revision-Id$ # # Copyright (c) 2003-2011, German Aerospace Center (DLR) # All rights reserved. # #Redistribution and use in source and binary forms, with or without #modification, are permitted provided that the following conditions are #met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the # distribution. # # * Neither the name of the German Aerospace Center nor the names of # its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # #THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <|fim▁hole|>Implements privileges. """ __version__ = "$Revision-Id:$"<|fim▁end|>
"""
<|file_name|>message.rs<|end_file_name|><|fim▁begin|>use linked_hash_map::LinkedHashMap; use std::borrow::Cow; use uuid::Uuid; use chrono::{DateTime, UTC}; #[derive(Debug, Clone, PartialEq)] pub struct Message<'a> { timestamp: Option<Timestamp>, expiration: Option<Timestamp>, correlation_id: Option<Uuid>, headers: Map<'a>, body: Option<Value<'a>>, } impl<'a> Message<'a> { pub fn new() -> Message<'a> { Message { timestamp: None, expiration: None, correlation_id: None, headers: Map::new(), body: None } } pub fn timestamp(&self) -> Option<Timestamp> { self.timestamp } pub fn set_timestamp(&mut self, value: Option<Timestamp>) { self.timestamp = value; } pub fn expiration(&self) -> Option<Timestamp> { self.expiration } pub fn set_expiration(&mut self, value: Option<Timestamp>) { self.expiration = value; } pub fn correlation_id(&self) -> Option<Uuid> { self.correlation_id } pub fn set_correlation_id(&mut self, value: Option<Uuid>) { self.correlation_id = value; } pub fn headers(&self) -> &Map<'a> { &self.headers } pub fn headers_mut(&mut self) -> &mut Map<'a> { &mut self.headers } pub fn body(&self) -> Option<&Value<'a>> { match self.body { Some(ref value) => Some(value), None => None, } } pub fn set_body<V: Into<Value<'a>>>(&mut self, value: Option<V>) { self.body = value.map(|v| v.into()).or(None); } } pub struct MessageBuilder<'a> { message: Message<'a>, } impl<'a> MessageBuilder<'a> { pub fn new() -> MessageBuilder<'a> { MessageBuilder { message: Message::new() } } pub fn with_timestamp(mut self, timestamp: Timestamp) -> MessageBuilder<'a> { self.message.set_timestamp(Some(timestamp)); self } pub fn with_expiration(mut self, expiration: Timestamp) -> MessageBuilder<'a> { self.message.set_expiration(Some(expiration)); self } pub fn with_correlation_id(mut self, correlation_id: Uuid) -> MessageBuilder<'a> { self.message.set_correlation_id(Some(correlation_id)); self } pub fn with_header<K, V>(mut self, key: K, value: V) -> MessageBuilder<'a> where K: Into<Key<'a>>, V: Into<Value<'a>>, { self.message.headers_mut().insert(key.into(), value.into()); self } pub fn with_body<V>(mut self, body: V) -> MessageBuilder<'a> where V: Into<Value<'a>>, { self.message.set_body(Some(body.into())); self } pub fn build(self) -> Message<'a> { self.message } } #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub enum Key<'a> { Str(Cow<'a, str>), I32(i32), } impl<'a> From<&'a str> for Key<'a> { fn from(key: &'a str) -> Self { Key::Str(Cow::Borrowed(key)) } } impl<'a> From<String> for Key<'a> { fn from(key: String) -> Self { Key::Str(Cow::Owned(key)) } } impl<'a> From<i32> for Key<'a> { fn from(key: i32) -> Self { Key::I32(key) } } #[derive(Debug, Clone, PartialEq)] pub struct List<'a> { inner: Vec<Value<'a>>, } impl<'a> List<'a> { pub fn new() -> List<'a> { List { inner: Vec::new() } } pub fn builder() -> ListBuilder<'a> { ListBuilder::new() } pub fn iter(&self) -> std::slice::Iter<Value<'a>> { self.inner.iter() } pub fn push<V: Into<Value<'a>>>(&mut self, value: V) { self.inner.push(value.into()); } pub fn len(&self) -> usize { self.inner.len() } } pub struct ListBuilder<'a> { list: List<'a>, } impl<'a> ListBuilder<'a> { pub fn new() -> ListBuilder<'a> { ListBuilder{ list: List::new() } } pub fn push<V>(mut self, value: V) -> ListBuilder<'a> where V: Into<Value<'a>>, { self.list.push(value.into()); self } pub fn push_mut<V>(&mut self, value: V) where V: Into<Value<'a>>, { self.list.push(value.into()); } pub fn build(self) -> List<'a> { self.list } } #[derive(Debug, Clone, PartialEq)] pub struct Map<'a> { inner: LinkedHashMap<Key<'a>, Value<'a>>, } impl<'a> Map<'a> { pub fn new() -> Map<'a> { Map{ inner: LinkedHashMap::new() } } pub fn insert<K: Into<Key<'a>>, V: Into<Value<'a>>>(&mut self, key: K, value: V) { self.inner.insert(key.into(), value.into()); } pub fn get(&self, key: &Key<'a>) -> Option<&Value<'a>> { self.inner.get(key) } pub fn iter(&self) -> linked_hash_map::Iter<Key<'a>, Value<'a>> { self.inner.iter() } pub fn len(&self) -> usize { self.inner.len() } pub fn contains_key(&self, key: &Key<'a>) -> bool { self.inner.contains_key(key) } } pub struct MapBuilder<'a> { map: Map<'a>, } impl<'a> MapBuilder<'a> { pub fn new() -> MapBuilder<'a> { MapBuilder{ map: Map::new() } } pub fn insert<K, V>(mut self, key: K, value: V) -> MapBuilder<'a> where K: Into<Key<'a>>, V: Into<Value<'a>>, { self.map.insert(key.into(), value.into()); self } pub fn insert_mut<K, V>(&mut self, key: K, value: V) where K: Into<Key<'a>>, V: Into<Value<'a>>, { self.map.insert(key.into(), value.into()); } pub fn build(self) -> Map<'a> { self.map } } #[derive(Debug, Clone, PartialEq)] pub enum Value<'a> { Null, Str(Cow<'a, str>), I32(i32), I64(i64), F32(f32), F64(f64), Bool(bool), Bytes(Cow<'a, [u8]>), List(List<'a>), Map(Map<'a>), Uuid(Uuid), Timestamp(Timestamp), // Key(Key<'a>), } impl<'a> From<&'a str> for Value<'a> { fn from(value: &'a str) -> Self { Value::Str(Cow::Borrowed(value)) } } impl<'a> From<String> for Value<'a> { fn from(value: String) -> Self { Value::Str(Cow::Owned(value)) } } impl<'a> From<i32> for Value<'a> { fn from(value: i32) -> Self { Value::I32(value) } } impl<'a> From<i64> for Value<'a> { fn from(value: i64) -> Self { Value::I64(value) } } impl<'a> From<f32> for Value<'a> { fn from(value: f32) -> Self { Value::F32(value) } } impl<'a> From<f64> for Value<'a> { fn from(value: f64) -> Self { Value::F64(value) } } impl<'a> From<bool> for Value<'a> { fn from(value: bool) -> Self { Value::Bool(value) } } impl<'a> From<Map<'a>> for Value<'a> { fn from(value: Map<'a>) -> Self { Value::Map(value) } } impl<'a> From<List<'a>> for Value<'a> { fn from(value: List<'a>) -> Self { Value::List(value) } } impl<'a> From<Timestamp> for Value<'a> { fn from(value: Timestamp) -> Self { Value::Timestamp(value) } } pub type Timestamp = DateTime<UTC>; #[cfg(test)] mod tests { use super::*; #[test] fn construct_simple_mesage() { let mut message = Message::new(); message.set_body(Some("value")); assert_eq!(message.body(), Some(&Value::from("value"))); message.headers_mut().insert("Null", Value::Null); message.headers_mut().insert("Str", "string"); message.headers_mut().insert("I32", 32); message.headers_mut().insert("I64", 64i64); message.headers_mut().insert("F32", 32.32f32); message.headers_mut().insert("F64", 64.64f64); message.headers_mut().insert("Bool(true)", true); message.headers_mut().insert("Bool(false)", false); <|fim▁hole|> assert_eq!(message.headers().get(&Key::from("Str")), Some(&Value::from("string"))); assert_eq!(message.headers().get(&Key::from("I32")), Some(&Value::from(32i32))); assert_eq!(message.headers().get(&Key::from("I64")), Some(&Value::from(64i64))); assert_eq!(message.headers().get(&Key::from("F32")), Some(&Value::from(32.32f32))); assert_eq!(message.headers().get(&Key::from("F64")), Some(&Value::from(64.64f64))); assert_eq!(message.headers().get(&Key::from("Bool(true)")), Some(&Value::from(true))); assert_eq!(message.headers().get(&Key::from("Bool(false)")), Some(&Value::from(false))); assert_eq!(message.headers().get(&Key::from("Missing")), None); for (key, value) in message.headers().iter() { println!("{:?}: {:?}", key, value); } } }<|fim▁end|>
assert_eq!(message.headers().len(), 8); assert_eq!(message.headers().get(&Key::from("Null")), Some(&Value::Null));
<|file_name|>helpers.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
export * from './helpers/ChaiModel';
<|file_name|>test_pbsea.py<|end_file_name|><|fim▁begin|>import numpy as np import os import pandas as pa import scipy.stats as stats import unittest from pbsea import PandasBasedEnrichmentAnalysis, EnrichmentAnalysisExperimental, preprocessing_files from unittest.mock import patch test_data_directory = 'test_data/' test_data_directory_cdf = test_data_directory + 'test_cdf/' test_data_directory_sf = test_data_directory + 'test_sf/' test_data_directory_multiple = test_data_directory + 'test_multiple/' test_data_directory_enrichment = test_data_directory + 'test_enrichment/' class enrichmentAnalysis_test(unittest.TestCase): def setUp(self): df, column_interest, column_reference = preprocessing_files('GOs', test_data_directory_enrichment+'counting_objects_in_interest.tsv', test_data_directory_enrichment+'counting_objects_in_genome.tsv') self.obj = PandasBasedEnrichmentAnalysis(df, column_interest, column_reference, 122, 1293, 0.05, 10000) self.class_sgof_test = EnrichmentAnalysisExperimental(df, column_interest, column_reference, 122, 1293, 0.05, 10000) def tearDown(self): del self.obj def test_hypergeometric_on_dataframe(self): ''' Datas are from : https://fr.mathworks.com/help/stats/hygecdf.html?s_tid=gn_loc_drop<|fim▁hole|> counts_df.set_index('Genes', inplace = True) counts_df_reference.set_index('Genes', inplace = True) df_joined = counts_df.join(counts_df_reference) df_joined_wih_results = pa.read_csv(test_data_directory_sf + 'result_test_sf_hypergeometric' + ".tsv", sep = "\t") df_joined_wih_results.set_index('Genes', inplace = True) enrichment_analysis_test = PandasBasedEnrichmentAnalysis(df_joined, 'Counts', 'CountsReference', 300, 10000, 0.05, 10000) df_joined = enrichment_analysis_test.test_on_dataframe(df_joined) np.testing.assert_array_almost_equal(df_joined['pvalue_hypergeometric'].tolist(), df_joined_wih_results['pvalue_hypergeometric'].tolist(), decimal = 4) def test_normal_approximation_on_dataframe(self): ''' Datas have been invented for the test. Results for the hypergeometric test are from : https://www.geneprof.org/GeneProf/tools/hypergeometric.jsp pvalue_hypergeometric found : 4.834533775884863e-8 ''' print("\nTesting normal approximation sf on dataframe ") counts_df = pa.read_csv(test_data_directory_sf + 'data_interest_test_sf_normal' + ".tsv", sep = "\t") counts_df_reference = pa.read_csv(test_data_directory_sf + 'data_reference_test_sf_normal' + ".tsv", sep = "\t") counts_df.set_index('Genes', inplace = True) counts_df_reference.set_index('Genes', inplace = True) df_joined = counts_df.join(counts_df_reference) df_joined_wih_results = pa.read_csv(test_data_directory_sf + 'result_test_sf_normal' + ".tsv", sep = "\t") df_joined_wih_results.set_index('Genes', inplace = True) enrichment_analysis_test = PandasBasedEnrichmentAnalysis(df_joined, 'Counts', 'CountsReference', 10000, 100000, 0.05, 1000) df_joined = enrichment_analysis_test.test_on_dataframe(df_joined) np.testing.assert_array_almost_equal(df_joined_wih_results['pvalue_normal'].tolist(), df_joined['pvalue_normal_approximation'].tolist(), decimal = 4) def test_correction_bonferroni(self): ''' Datas are from : http://www.pmean.com/05/MultipleComparisons.asp ''' print("\nTesting Bonferroni multiple testing correction ") pvalue_df = pa.read_csv(test_data_directory_multiple + 'multiple_test_data_pmean' + ".tsv", sep = "\t") self.obj.statistic_method = "pvalue_hypergeometric" pvalue_df = self.obj.correction_bonferroni(pvalue_df) pvalue_truth_df = pa.read_csv(test_data_directory_multiple + 'multiple_test_result_pmean' + ".tsv", sep = "\t") np.testing.assert_array_almost_equal(pvalue_df['pValueBonferroni'].tolist(), pvalue_truth_df['PvalueBonferroni'].tolist(), decimal = 4) def test_correction_holm(self): ''' Datas are from : http://www.pmean.com/05/MultipleComparisons.asp ''' print("\nTesting Holm multiple testing correction ") pvalue_df = pa.read_csv(test_data_directory_multiple + 'multiple_test_data_pmean' + ".tsv", sep = "\t") self.obj.statistic_method = "pvalue_hypergeometric" pvalue_df = self.obj.correction_holm(pvalue_df) pvalue_truth_df = pa.read_csv(test_data_directory_multiple + 'multiple_test_result_pmean' + ".tsv", sep = "\t") pvalue_truth_df = pvalue_truth_df.sort_values(by = "pvalue_hypergeometric") np.testing.assert_array_almost_equal(pvalue_df['pValueHolm'].tolist(), pvalue_truth_df['PvalueHolm'].tolist(), decimal = 4) def test_correction_benjamini_hochberg(self): ''' Datas and results are from : www.biostathandbook.com/multiplecomparisons.html Data are from the article : onlinelibrary.wiley.com/doi/10.1002/ijc.28513/full ''' print("\nTesting Benjamini and Hochberg multiple testing correction ") df_data = pa.read_csv(test_data_directory_multiple + 'multiple_test_data_BH.tsv', sep='\t') self.obj.statistic_method = "pvalue_hypergeometric" df_data = self.obj.correction_benjamini_hochberg(df_data) pvalue_truth_df = pa.read_csv(test_data_directory_multiple + 'multiple_test_result_BH.tsv', sep='\t') np.testing.assert_array_almost_equal(df_data['pValueBenjaminiHochberg'].tolist(), pvalue_truth_df['pValueBenjaminiHochberg'].tolist(), decimal = 4) def test_correction_sgof_G(self): ''' Datas have been created for the example. To obtain the results, they have been used on MATLAB script for SGoF here : http://acraaj.webs.uvigo.es/software/matlab_sgof.m ''' print("\nTesting SGoF multiple testing correction using G test") pvalue_df = pa.read_csv(test_data_directory_multiple + 'multiple_test_data_sgof_G_test' + ".tsv", sep = "\t") self.class_sgof_test.statistic_method = "pvalue_hypergeometric" self.class_sgof_test.object_to_analyze= "pvalue_hypergeometric" pvalue_df = self.class_sgof_test.correction_sgof(pvalue_df) pvalue_truth_df = pa.read_csv(test_data_directory_multiple + 'multiple_test_result_sgof_G_test' + ".tsv", sep = "\t") pvalue_truth_df = pvalue_truth_df.sort_values(by = "pvalue_hypergeometric") np.testing.assert_array_equal(pvalue_df['pValueSGoF'].tolist(), pvalue_truth_df['pValueSGoF'].tolist()) def test_correction_sgof_bino(self): ''' Datas have been created for the example. To obtain the results, they have been used on MATLAB script for SGoF here : http://acraaj.webs.uvigo.es/software/matlab_sgof.m ''' print("\nTesting SGoF multiple testing correction using binomial test ") pvalue_df = pa.read_csv(test_data_directory_multiple + 'multiple_test_data_sgof_binomial' + ".tsv", sep = "\t") self.class_sgof_test.statistic_method = "pvalue_hypergeometric" self.class_sgof_test.object_to_analyze= "pvalue_hypergeometric" pvalue_df = self.class_sgof_test.correction_sgof(pvalue_df) pvalue_truth_df = pa.read_csv(test_data_directory_multiple + 'multiple_test_result_sgof_binomial' + ".tsv", sep = "\t") pvalue_truth_df = pvalue_truth_df.sort_values(by = "pvalue_hypergeometric") np.testing.assert_array_equal(pvalue_df['pValueSGoF'].tolist(), pvalue_truth_df['pValueSGoF'].tolist()) def test_error_rate_adjustement_bonferroni(self): ''' Datas and results are from : www.biostathandbook.com/multiplecomparisons.html ''' print("\nTesting error rate adjustement Bonferroni ") datas = {'pvalue_hypergeometric':[0.001,0.008,0.039,0.041,0.042,0.06,0.074,0.205,0.212,0.216,0.222, 0.251,0.269,0.275,0.34,0.341,0.384,0.569,0.594,0.696,0.762,0.94,0.942,0.975,0.986]} df = pa.DataFrame(datas) error_rate_adjusted = self.obj.error_rate_adjustement_bonferroni(df) self.assertEqual(error_rate_adjusted, 0.002) def test_error_rate_adjustement_sidak(self): ''' Datas have been created for the example (the only important thing here is the numver of pvalue). The example and the result are from : www.spc.univ-lyon1.fr/polycop/comparaisons multiples.htm ''' print("\nTesting error rate adjustement Sidak ") datas_10 = {'pvalue_hypergeometric_10':[0.01,0.02,0.3,0.02,0.05,0.07,0.9,0.001,0.09,0.008]} df_10_pvalue = pa.DataFrame(datas_10) error_rate_adjusted_10 = self.obj.error_rate_adjustement_sidak(df_10_pvalue) datas_20 = {'pvalue_hypergeometric_20':[0.01,0.02,0.05,0.04,0.2,0.04,0.9,0.05,0.06,0.0545, 0.048766,0.02,0.04,0.03,0.365,0.21,0.0234,0.2,0.156]} df_20_pvalue = pa.DataFrame(datas_20) error_rate_adjusted_20 = self.obj.error_rate_adjustement_sidak(df_20_pvalue) np.testing.assert_array_almost_equal([error_rate_adjusted_10, error_rate_adjusted_20], [0.0051, 0.0026], decimal = 4) if __name__ == '__main__': unittest.main()<|fim▁end|>
''' print("\nTesting hypergeometric sf on dataframe ") counts_df = pa.read_csv(test_data_directory_sf + 'data_interest_test_sf_hypergeometric' + ".tsv", sep = "\t") counts_df_reference = pa.read_csv(test_data_directory_sf + 'data_reference_test_sf_hypergeometric' + ".tsv", sep = "\t")
<|file_name|>bug847425.js<|end_file_name|><|fim▁begin|>// |jit-test| allow-oom; allow-unhandlable-oom gcparam("maxBytes", gcparam("gcBytes") + 4*1024); var max = 400; function f(b) { if (b) { f(b - 1); } else { g = { apply:function(x,y) { } };<|fim▁hole|>} f(max - 1);<|fim▁end|>
} g.apply(null, arguments);
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import logger from "./logger"; <|fim▁hole|>const middlewares = { logger, }; export default middlewares;<|fim▁end|>
<|file_name|>MacOSXCanvasImplementation.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2002-2008 LWJGL Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: <|fim▁hole|> * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'LWJGL' nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.lwjgl.opengl; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.Canvas; import org.lwjgl.LWJGLException; /** * * @author elias_naur <[email protected]> * @version $Revision: 3632 $ * $Id: MacOSXCanvasImplementation.java 3632 2011-09-03 18:52:45Z spasi $ */ final class MacOSXCanvasImplementation implements AWTCanvasImplementation { public PeerInfo createPeerInfo(Canvas component, PixelFormat pixel_format, ContextAttribs attribs) throws LWJGLException { try { return new MacOSXAWTGLCanvasPeerInfo(component, pixel_format, attribs, true); } catch (LWJGLException e) { return new MacOSXAWTGLCanvasPeerInfo(component, pixel_format, attribs, false); } } /** * Find a proper GraphicsConfiguration from the given GraphicsDevice and PixelFormat. * * @return The GraphicsConfiguration corresponding to a visual that matches the pixel format. */ public GraphicsConfiguration findConfiguration(GraphicsDevice device, PixelFormat pixel_format) throws LWJGLException { /* * It seems like the best way is to simply return null */ return null; } }<|fim▁end|>
*
<|file_name|>script.js<|end_file_name|><|fim▁begin|>// requestAnim shim layer by Paul Irish window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function */ callback, /* DOMElement */ element){ window.setTimeout(callback, 1000 / 60); }; })(); // example code from mr doob : http://mrdoob.com/lab/javascript/requestanimationframe/ //var canvas = document.getElementById("myCanvas"); //var context = canvas.getContext("2d"); var canvas, context, toggle; var y= 220; var x= 284; var y2=-10; var x2= 10; var y3=-10; var x3= 400; var mid = 128; var dirX = 1; var dirY = 1; var destX ; var destY ; var i; var state ; var inbounds='true'; var status = -1; // -1: stopped , 0 In play var imageObj = new Image(); var imageObj2 = new Image(); var imageObj3 = new Image(); var background_obj= new Image(); background_obj.src = "deep-space.jpg"; imageObj.src = "spshipsprite.png"; imageObj2.src = "spacestation.png"; imageObj3.src = "blueship4.png"; var jump = 'rest'; var backg_x = 0; var backg_y = 0; var floating =false; var degrees = 0; var str; var name; //init(); var dir = 1; var monster = {}; var origin = {}; // Bullet image var bulletReady = false; var bulletImage = new Image(); bulletImage.onload = function () { //bulletReady = true; }; bulletImage.src = "images/bullet.png"; var bullet = { speed: 256 // movement in pixels per second }; //function init() { canvas = document.createElement( 'canvas' ); canvas.width = 568; canvas.height = 400; context = canvas.getContext( '2d' ); //context.font = "40pt Calibri"; //context.fillStyle = "white"; // align text horizontally center context.textAlign = "center"; // align text vertically center context.textBaseline = "middle"; //context.font = "12pt Calibri"; //canvas.width = 8248; context.drawImage(background_obj, backg_x, backg_y); //imageData = context.getImageData(0,0,8248,400); //fnord //var x = document; // canvas.width = 568; $( "#container" ).append( canvas ); //} animate(); // shoot addition var shoot = function(modifier){ if (dir==1){ bullet.y -= bullet.speed * modifier * 4; } if (dir==2){ bullet.y += bullet.speed * modifier * 4; } if (dir==3){ bullet.x -= bullet.speed * modifier * 4; } if (dir==4){ bullet.x += bullet.speed * modifier * 4; } // Are they touching2? if ( bullet.x <= (monster.x + 32) && monster.x <= (bullet.x + 32) && hero.y <= (bullet.y + 32) && monster.y <= (bullet.y + 32) ) { ++monstersShot; reset(); } //distance = square root sqrt of ( (x2-x1)^2 + (y2-y1)^2) var distance = Math.sqrt( Math.pow(bullet.x-origin.x, 2) + Math.pow(bullet.y - origin.y,2) ); if (distance > 200) { bulletReady = false; first = true } } if (bulletReady) { context.drawImage(bulletImage, bullet.x, bullet.y); } // shoot addition function shoot() { if (dir==1){ bullet.y -= bullet.speed * 4; } if (dir==2){ bullet.y += bullet.speed * 4; } if (dir==3){ bullet.x -= bullet.speed * 4; } if (dir==4){ bullet.x += bullet.speed * 4; } //distance = square root sqrt of ( (x2-x1)^2 + (y2-y1)^2) var distance = Math.sqrt( Math.pow(bullet.x - x, 2) + Math.pow(bullet.y - y,2) ); if (distance > 200) { bulletReady = false; first = true } } function animate() { update(); requestAnimFrame( animate ); shoot(); draw(); } function update() { y2++; x2++; y3++; x3--; if (y2==400) { y2=0; } if (x2==598) { x2=0; } if (y3==400) { y3=0; } if (x3==0) { x3=598; } } function draw() { context.fillText( state + ":" , canvas.width / 2 , canvas.height / 2 ); $(document).keyup(function(e) { if (e.keyCode == 37) { state= "stop"; dirX=1; dir=3; } if (e.keyCode == 39) { state= "stop"; dirX=1; dir=4; } if (e.keyCode == 38) { jump = 'descend'; } }); $(document).keydown(function(e) { //alert (e.keyCode); //if space start/stop gameloop //var time = new Date().getTime() * 0.002; if(e.keyCode == 32) { status = 0 - status; bulletReady = true; bullet.x = x; bullet.y = y; } // if (jump != 'descend') // { if (e.keyCode == 38 ) { jump = 'ascend'; } // } if (e.keyCode == 40){ // down } if (e.keyCode == 37){ state = 'left'; } if (e.keyCode == 39){ state = 'right'; } }); /////////////////////////////////////////////////////////////////////////////// if (state == 'left') { //x = x-(1 * dirX); // backg_x = backg_x + 1 ; degrees = degrees - 1; // context.setTransform(1,0.5,-0.5,10,10); } if (state == 'right') { //x = x + (1 * dirX); // backg_x = backg_x - 1 ; degrees = degrees +1 ; // context.setTransform(1,0.5,-0.5,1,10,10); } if (jump == 'ascend') { } if (jump == 'descend') { y = y - 1; if (y == 0) { jump = 'rest'; } } if (jump == 'rest') { y = 0; dirY = -1; }<|fim▁hole|> // destX = (canvas.width / 2 ) + x; // destY = canvas.height - 30 - y ;// 60 pixels offset from centre }//end if inbounds if (destX > canvas.width || destX < 0) { // dirX =-dirX; } if (destY > canvas.width || destY < 0) { // dirY =-dirY; } //canvas.width = 8248; context.clearRect(0,0 , canvas.width, canvas.height); context.drawImage(background_obj, backg_x, backg_y); context.save(); context.beginPath(); context.translate( 290,210 ); // rotate the rect context.rotate(degrees*Math.PI/180); context.drawImage(imageObj, -37, -50); context.restore(); context.drawImage(imageObj2, x2, y2); context.drawImage(imageObj3, x3, y3); str = "width=" + imageData.width + " height=" + imageData.height + " red :" + red + " green :" + green + " blue :" + blue + " destX :" + parseInt(0-backg_x) + " destY :" +destY + " inbounds:" + inbounds + " float: " + floating + " jump : " + jump; context.fillText(str, 20, 14); str2 = "x: " + x + "y :" + y; context.fillText(str2, 20, 34); context.fillStyle = 'white'; }<|fim▁end|>
if (inbounds=='true') {
<|file_name|>_XDataPilotTables.java<|end_file_name|><|fim▁begin|>/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ package ifc.sheet; import lib.MultiMethodTest; import lib.Status; import lib.StatusException; <|fim▁hole|>import com.sun.star.sheet.XSpreadsheet; import com.sun.star.table.CellAddress; /** * Testing <code>com.sun.star.sheet.XDataPilotTables</code> * interface methods : * <ul> * <li><code> createDataPilotDescriptor()</code></li> * <li><code> insertNewByName()</code></li> * <li><code> removeByName()</code></li> * </ul> <p> * This test needs the following object relations : * <ul> * <li> <code>'SHEET'</code> (of type <code>XSpreadsheet</code>): * to have a spreadsheet document for document content checking</li> * <ul> <p> * @see com.sun.star.sheet.XDataPilotTables */ public class _XDataPilotTables extends MultiMethodTest { public XDataPilotTables oObj = null; XDataPilotDescriptor DPDscr = null; String name = "XDataPilotTables"; CellAddress CA = new CellAddress((short)0, 9, 8); XSpreadsheet oSheet = null; /** * Retrieves object relations. * @throws StatusException If one of relations not found. */ protected void before() { oSheet = (XSpreadsheet)tEnv.getObjRelation("SHEET"); if (oSheet == null) throw new StatusException(Status.failed ("Relation 'SHEET' not found")); } /** * Test calls the method, stores returned value and checks returned value. * <p>Has <b> OK </b> status if returned value isn't null. <p> */ public void _createDataPilotDescriptor(){ DPDscr = oObj.createDataPilotDescriptor(); tRes.tested("createDataPilotDescriptor()", DPDscr != null); } /** * Test calls the method inserting new table with new name and then calls * the method inserting table with existent name. <p> * Has <b> OK </b> status if the cell content where table was inserted is * equal to 'Filter' after first call and exception was thrown during * second call. <p> * The following method tests are to be completed successfully before : * <ul> * <li> <code> createDataPilotDescriptor() </code> : to have * <code>XDataPilotDescriptor</code> created by this method</li> * </ul> */ public void _insertNewByName(){ requiredMethod("createDataPilotDescriptor()"); boolean bResult = true; log.println("Inserting new Table \"" + name + "\""); try { oObj.insertNewByName(name, CA, DPDscr); bResult &= oSheet.getCellByPosition (CA.Column, CA.Row).getFormula().equals("Filter"); } catch (com.sun.star.uno.Exception e) { log.println("Exception occurred! " + e); bResult = false; } log.println(bResult ? "OK" : "FAILED"); log.println("Trying to insert element with existent name"); try { oObj.insertNewByName(name,new CellAddress((short)0, 7, 7), DPDscr); log.println("No exception! - FAILED"); bResult = false; } catch (com.sun.star.uno.RuntimeException e) { log.println("Expected exception - OK " + e); } log.println("Inserting new table " + (bResult ? "OK" : "FAILED")); tRes.tested("insertNewByName()", bResult); } /** * Test calls the method for existent table and for unexistent table. <p> * Has <b> OK </b> status if the cell where table was removed from is empty * after first call and exception was thrown during second call. <p> * The following method tests are to be completed successfully before : * <ul> * <li> <code>insertNewByName()</code>: to have name of existent table</li> * </ul> */ public void _removeByName(){ requiredMethod("insertNewByName()"); boolean bResult = true; log.println("Remove table with name " + name); try { oObj.removeByName(name); bResult &= oSheet.getCellByPosition (CA.Column, CA.Row).getFormula().equals(""); } catch (com.sun.star.uno.Exception e) { log.println("Exception occurred ! " + e); bResult = false; } log.println(bResult ? "OK" : "FAILED"); log.println("Removing unexistent element"); try { oObj.removeByName(name); log.println("No exception! - FAILED"); bResult = false; } catch (com.sun.star.uno.RuntimeException e) { log.println("Expected exception - OK " + e); } log.println("Removing a table " + (bResult ? "OK" : "FAILED")); tRes.tested("removeByName()", bResult); } }<|fim▁end|>
import com.sun.star.sheet.XDataPilotDescriptor; import com.sun.star.sheet.XDataPilotTables;
<|file_name|>test.js<|end_file_name|><|fim▁begin|>"use strict"; var marvelNameGenerator = require('./index.js');<|fim▁hole|><|fim▁end|>
console.log("Expect to see a cool name:\n"+marvelNameGenerator());
<|file_name|>fluent-bmp180.js<|end_file_name|><|fim▁begin|>"use strict"; var Cylon = require("cylon"); Cylon .robot() .connection("arduino", { adaptor: "firmata", port: "/dev/ttyACM0" }) .device("bmp180", { driver: "bmp180" }) .on("ready", function(bot) { bot.bmp180.getTemperature(function(err, val) { if (err) { console.log(err); } else { console.log("getTemperature call:"); console.log("\tTemp: " + val.temp + " C"); } }); setTimeout(function() { bot.bmp180.getPressure(1, function(err, val) { if (err) { console.log(err); } else { console.log("getPressure call:"); console.log("\tTemperature: " + val.temp + " C"); console.log("\tPressure: " + val.press + " Pa"); } }); }, 1000); setTimeout(function() { bot.bmp180.getAltitude(1, null, function(err, val) { if (err) { console.log(err); } else { console.log("getAltitude call:"); console.log("\tTemperature: " + val.temp + " C"); console.log("\tPressure: " + val.press + " Pa"); console.log("\tAltitude: " + val.alt + " m");<|fim▁hole|> }, 2000); }); Cylon.start();<|fim▁end|>
} });
<|file_name|>geo.py<|end_file_name|><|fim▁begin|>from django.conf import settings from geopy import distance, geocoders<|fim▁hole|> def get_geodata_by_ip(addr): gi = pygeoip.GeoIP(settings.GEO_CITY_FILE, pygeoip.MEMORY_CACHE) geodata = gi.record_by_addr(addr) return geodata def get_geodata_by_region(*args): gn = geocoders.GeoNames() return gn.geocode(' '.join(args), exactly_one=False)[0] def get_distance(location1, location2): """ Calculate distance between two locations, given the (lat, long) of each. Required Arguments: location1 A tuple of (lat, long). location2 A tuple of (lat, long). """ return distance.distance(location1, location2).miles<|fim▁end|>
import pygeoip
<|file_name|>manifest.rs<|end_file_name|><|fim▁begin|>use std::fmt; use std::path::{PathBuf, Path}; use semver::Version; use rustc_serialize::{Encoder, Encodable}; use core::{Dependency, PackageId, PackageIdSpec, Summary}; use core::package_id::Metadata; use util::{CargoResult, human}; /// Contains all the information about a package, as loaded from a Cargo.toml. #[derive(Clone, Debug)] pub struct Manifest { summary: Summary, targets: Vec<Target>, links: Option<String>, warnings: Vec<String>, exclude: Vec<String>, include: Vec<String>, metadata: ManifestMetadata, profiles: Profiles, publish: bool, replace: Vec<(PackageIdSpec, Dependency)>, } /// General metadata about a package which is just blindly uploaded to the /// registry. /// /// Note that many of these fields can contain invalid values such as the /// homepage, repository, documentation, or license. These fields are not /// validated by cargo itself, but rather it is up to the registry when uploaded /// to validate these fields. Cargo will itself accept any valid TOML /// specification for these values. #[derive(PartialEq, Clone, Debug)] pub struct ManifestMetadata { pub authors: Vec<String>, pub keywords: Vec<String>, pub license: Option<String>, pub license_file: Option<String>, pub description: Option<String>, // not markdown pub readme: Option<String>, // file, not contents pub homepage: Option<String>, // url pub repository: Option<String>, // url pub documentation: Option<String>, // url } #[derive(Debug, Clone, PartialEq, Eq, Hash, RustcEncodable, Copy)] pub enum LibKind { Lib, Rlib, Dylib, StaticLib } impl LibKind { pub fn from_str(string: &str) -> CargoResult<LibKind> { match string { "lib" => Ok(LibKind::Lib), "rlib" => Ok(LibKind::Rlib), "dylib" => Ok(LibKind::Dylib), "staticlib" => Ok(LibKind::StaticLib), _ => Err(human(format!("crate-type \"{}\" was not one of lib|rlib|dylib|staticlib", string))) } } /// Returns the argument suitable for `--crate-type` to pass to rustc. pub fn crate_type(&self) -> &'static str { match *self { LibKind::Lib => "lib", LibKind::Rlib => "rlib", LibKind::Dylib => "dylib", LibKind::StaticLib => "staticlib" } } } #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub enum TargetKind { Lib(Vec<LibKind>), Bin, Test, Bench, Example, CustomBuild, } impl Encodable for TargetKind { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { match *self { TargetKind::Lib(ref kinds) => { kinds.iter().map(|k| k.crate_type()).collect() } TargetKind::Bin => vec!["bin"], TargetKind::Example => vec!["example"], TargetKind::Test => vec!["test"], TargetKind::CustomBuild => vec!["custom-build"], TargetKind::Bench => vec!["bench"], }.encode(s) } } #[derive(RustcEncodable, RustcDecodable, Clone, PartialEq, Eq, Debug, Hash)] pub struct Profile { pub opt_level: u32, pub lto: bool, pub codegen_units: Option<u32>, // None = use rustc default pub rustc_args: Option<Vec<String>>, pub rustdoc_args: Option<Vec<String>>, pub debuginfo: bool, pub debug_assertions: bool, pub rpath: bool, pub test: bool, pub doc: bool, pub run_custom_build: bool, } #[derive(Default, Clone, Debug)] pub struct Profiles { pub release: Profile, pub dev: Profile, pub test: Profile, pub bench: Profile, pub doc: Profile, pub custom_build: Profile, } /// Information about a binary, a library, an example, etc. that is part of the /// package. #[derive(Clone, Hash, PartialEq, Eq, Debug)] pub struct Target { kind: TargetKind, name: String, src_path: PathBuf, metadata: Option<Metadata>, tested: bool, benched: bool, doc: bool, doctest: bool, harness: bool, // whether to use the test harness (--test) for_host: bool, } #[derive(RustcEncodable)] struct SerializedTarget<'a> { kind: &'a TargetKind, name: &'a str, src_path: &'a str, } impl Encodable for Target { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { SerializedTarget { kind: &self.kind, name: &self.name, src_path: &self.src_path.display().to_string(), }.encode(s) } } impl Manifest { pub fn new(summary: Summary, targets: Vec<Target>, exclude: Vec<String>, include: Vec<String>, links: Option<String>, metadata: ManifestMetadata, profiles: Profiles, publish: bool, replace: Vec<(PackageIdSpec, Dependency)>) -> Manifest { Manifest { summary: summary, targets: targets, warnings: Vec::new(), exclude: exclude, include: include, links: links, metadata: metadata, profiles: profiles, publish: publish, replace: replace, } } pub fn dependencies(&self) -> &[Dependency] { self.summary.dependencies() } pub fn exclude(&self) -> &[String] { &self.exclude } pub fn include(&self) -> &[String] { &self.include } pub fn metadata(&self) -> &ManifestMetadata { &self.metadata } pub fn name(&self) -> &str { self.package_id().name() } pub fn package_id(&self) -> &PackageId { self.summary.package_id() } pub fn summary(&self) -> &Summary { &self.summary } pub fn targets(&self) -> &[Target] { &self.targets } pub fn version(&self) -> &Version { self.package_id().version() } pub fn warnings(&self) -> &[String] { &self.warnings } pub fn profiles(&self) -> &Profiles { &self.profiles } pub fn publish(&self) -> bool { self.publish } pub fn replace(&self) -> &[(PackageIdSpec, Dependency)] { &self.replace } pub fn links(&self) -> Option<&str> { self.links.as_ref().map(|s| &s[..]) } pub fn add_warning(&mut self, s: String) { self.warnings.push(s) } pub fn set_summary(&mut self, summary: Summary) { self.summary = summary; } } impl Target { fn blank() -> Target { Target { kind: TargetKind::Bin, name: String::new(), src_path: PathBuf::new(), metadata: None, doc: false, doctest: false, harness: true, for_host: false, tested: true, benched: true, } } pub fn lib_target(name: &str, crate_targets: Vec<LibKind>, src_path: &Path, metadata: Metadata) -> Target { Target { kind: TargetKind::Lib(crate_targets), name: name.to_string(), src_path: src_path.to_path_buf(), metadata: Some(metadata), doctest: true, doc: true, ..Target::blank() } } pub fn bin_target(name: &str, src_path: &Path, metadata: Option<Metadata>) -> Target { Target { kind: TargetKind::Bin, name: name.to_string(), src_path: src_path.to_path_buf(), metadata: metadata, doc: true, ..Target::blank() } } /// Builds a `Target` corresponding to the `build = "build.rs"` entry. pub fn custom_build_target(name: &str, src_path: &Path, metadata: Option<Metadata>) -> Target { Target { kind: TargetKind::CustomBuild, name: name.to_string(), src_path: src_path.to_path_buf(), metadata: metadata, for_host: true, benched: false, tested: false, ..Target::blank() } } pub fn example_target(name: &str, src_path: &Path) -> Target { Target { kind: TargetKind::Example, name: name.to_string(), src_path: src_path.to_path_buf(), benched: false, ..Target::blank() } } pub fn test_target(name: &str, src_path: &Path, metadata: Metadata) -> Target { Target { kind: TargetKind::Test, name: name.to_string(), src_path: src_path.to_path_buf(), metadata: Some(metadata), benched: false, ..Target::blank() } } pub fn bench_target(name: &str, src_path: &Path, metadata: Metadata) -> Target { Target { kind: TargetKind::Bench, name: name.to_string(), src_path: src_path.to_path_buf(), metadata: Some(metadata), tested: false, ..Target::blank() } } pub fn name(&self) -> &str { &self.name } pub fn crate_name(&self) -> String { self.name.replace("-", "_") } pub fn src_path(&self) -> &Path { &self.src_path } pub fn metadata(&self) -> Option<&Metadata> { self.metadata.as_ref() } pub fn kind(&self) -> &TargetKind { &self.kind } pub fn tested(&self) -> bool { self.tested } pub fn harness(&self) -> bool { self.harness } pub fn documented(&self) -> bool { self.doc } pub fn for_host(&self) -> bool { self.for_host } pub fn benched(&self) -> bool { self.benched } pub fn doctested(&self) -> bool { self.doctest && match self.kind { TargetKind::Lib(ref kinds) => { kinds.contains(&LibKind::Rlib) || kinds.contains(&LibKind::Lib) } _ => false, } } pub fn allows_underscores(&self) -> bool { self.is_bin() || self.is_example() || self.is_custom_build() } pub fn is_lib(&self) -> bool { match self.kind { TargetKind::Lib(_) => true, _ => false } } pub fn linkable(&self) -> bool { match self.kind { TargetKind::Lib(ref kinds) => { kinds.iter().any(|k| { match *k { LibKind::Lib | LibKind::Rlib | LibKind::Dylib => true, LibKind::StaticLib => false, } }) } _ => false } } pub fn is_bin(&self) -> bool { self.kind == TargetKind::Bin } pub fn is_example(&self) -> bool { self.kind == TargetKind::Example } pub fn is_test(&self) -> bool { self.kind == TargetKind::Test } pub fn is_bench(&self) -> bool { self.kind == TargetKind::Bench } pub fn is_custom_build(&self) -> bool { self.kind == TargetKind::CustomBuild } /// Returns the arguments suitable for `--crate-type` to pass to rustc. pub fn rustc_crate_types(&self) -> Vec<&'static str> { match self.kind { TargetKind::Lib(ref kinds) => { kinds.iter().map(|kind| kind.crate_type()).collect() }, TargetKind::CustomBuild | TargetKind::Bench | TargetKind::Test | TargetKind::Example | TargetKind::Bin => vec!["bin"], } } pub fn can_lto(&self) -> bool { match self.kind { TargetKind::Lib(ref v) => *v == [LibKind::StaticLib], _ => true, } } pub fn set_tested(&mut self, tested: bool) -> &mut Target { self.tested = tested; self } pub fn set_benched(&mut self, benched: bool) -> &mut Target { self.benched = benched; self } pub fn set_doctest(&mut self, doctest: bool) -> &mut Target { self.doctest = doctest; self } pub fn set_for_host(&mut self, for_host: bool) -> &mut Target { self.for_host = for_host; self } pub fn set_harness(&mut self, harness: bool) -> &mut Target { self.harness = harness; self } pub fn set_doc(&mut self, doc: bool) -> &mut Target { self.doc = doc; self } } impl fmt::Display for Target { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.kind { TargetKind::Lib(..) => write!(f, "Target(lib)"), TargetKind::Bin => write!(f, "Target(bin: {})", self.name), TargetKind::Test => write!(f, "Target(test: {})", self.name), TargetKind::Bench => write!(f, "Target(bench: {})", self.name), TargetKind::Example => write!(f, "Target(example: {})", self.name), TargetKind::CustomBuild => write!(f, "Target(script)"), } } } impl Profile { pub fn default_dev() -> Profile { Profile { debuginfo: true, debug_assertions: true, ..Profile::default() } } pub fn default_release() -> Profile { Profile { opt_level: 3, debuginfo: false, ..Profile::default() } } pub fn default_test() -> Profile { Profile { test: true, ..Profile::default_dev() } } pub fn default_bench() -> Profile { Profile { test: true, ..Profile::default_release() } } pub fn default_doc() -> Profile { Profile { doc: true, ..Profile::default_dev() } } pub fn default_custom_build() -> Profile { Profile { run_custom_build: true, ..Profile::default_dev() } } } impl Default for Profile {<|fim▁hole|> Profile { opt_level: 0, lto: false, codegen_units: None, rustc_args: None, rustdoc_args: None, debuginfo: false, debug_assertions: false, rpath: false, test: false, doc: false, run_custom_build: false, } } } impl fmt::Display for Profile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.test { write!(f, "Profile(test)") } else if self.doc { write!(f, "Profile(doc)") } else if self.run_custom_build { write!(f, "Profile(run)") } else { write!(f, "Profile(build)") } } }<|fim▁end|>
fn default() -> Profile {
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import platform import glob from .io import DxlIO, Dxl320IO, DxlError from .error import BaseErrorHandler from .controller import BaseDxlController from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor from ..robot import Robot def _get_available_ports(): """ Tries to find the available usb2serial port on your system. """ if platform.system() == 'Darwin': return glob.glob('/dev/tty.usb*') elif platform.system() == 'Linux': return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*') elif platform.system() == 'Windows': import _winreg import itertools ports = [] path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path) for i in itertools.count(): try: ports.append(str(_winreg.EnumValue(key, i)[1])) except WindowsError: return ports return [] def get_available_ports(only_free=False): ports = _get_available_ports() if only_free: ports = list(set(ports) - set(DxlIO.get_used_ports())) return ports def find_port(ids, strict=True): """ Find the port with the specified attached motor ids. :param list ids: list of motor ids to find :param bool strict: specify if all ids should be find (when set to False, only half motor must be found) .. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned. """ for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): try: with DxlIOCls(port) as dxl: founds = len(dxl.scan(ids)) if strict and founds == len(ids): return port if not strict and founds >= len(ids) / 2: return port except DxlError: continue raise IndexError('No suitable port found for ids {}!'.format(ids)) def autodetect_robot(): """ Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """ motor_controllers = [] for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): dxl_io = DxlIOCls(port) ids = dxl_io.scan() if not ids: dxl_io.close() continue models = dxl_io.get_model(ids) motorcls = { 'MX': DxlMXMotor, 'RX': DxlAXRXMotor, 'AX': DxlAXRXMotor, 'XL': DxlXL320Motor } <|fim▁hole|> motors = [motorcls[model[:2]](id, model=model) for id, model in zip(ids, models)] c = BaseDxlController(dxl_io, motors) motor_controllers.append(c) return Robot(motor_controllers)<|fim▁end|>
<|file_name|>CurveController.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2003-2009 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme.curve; import java.io.IOException; import com.jme.math.Vector3f; import com.jme.scene.Controller; import com.jme.scene.Spatial; import com.jme.util.export.InputCapsule; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.OutputCapsule; /** * <code>CurveController</code> defines a controller that moves a supplied * <code>Spatial</code> object along a curve. Attributes of the curve are set * such as the up vector (if not set, the spacial object will roll along the * curve), the orientation precision defines how accurate the orientation of the * spatial will be. * @author Mark Powell * @version $Id: CurveController.java 4131 2009-03-19 20:15:28Z blaine.dev $ */ public class CurveController extends Controller { private static final long serialVersionUID = 1L; private Spatial mover;<|fim▁hole|> private Curve curve; private Vector3f up; private float orientationPrecision = 0.1f; private float currentTime = 0.0f; private float deltaTime = 0.0f; private boolean cycleForward = true; private boolean autoRotation = false; /** * Constructor instantiates a new <code>CurveController</code> object. * The curve object that the controller operates on and the spatial object * that is moved is specified during construction. * @param curve the curve to operate on. * @param mover the spatial to move. */ public CurveController(Curve curve, Spatial mover) { this.curve = curve; this.mover = mover; setUpVector(new Vector3f(0,1,0)); setMinTime(0); setMaxTime(Float.MAX_VALUE); setRepeatType(Controller.RT_CLAMP); setSpeed(1.0f); } /** * Constructor instantiates a new <code>CurveController</code> object. * The curve object that the controller operates on and the spatial object * that is moved is specified during construction. The game time to * start and the game time to finish is also supplied. * @param curve the curve to operate on. * @param mover the spatial to move. * @param minTime the time to start the controller. * @param maxTime the time to end the controller. */ public CurveController( Curve curve, Spatial mover, float minTime, float maxTime) { this.curve = curve; this.mover = mover; setMinTime(minTime); setMaxTime(maxTime); setRepeatType(Controller.RT_CLAMP); } /** * * <code>setUpVector</code> sets the locking vector for the spatials up * vector. This prevents rolling along the curve and allows for a better * tracking. * @param up the vector to lock as the spatials up vector. */ public void setUpVector(Vector3f up) { this.up = up; } /** * * <code>setOrientationPrecision</code> sets a precision value for the * spatials orientation. The smaller the number the higher the precision. * By default 0.1 is used, and typically does not require changing. * @param value the precision value of the spatial's orientation. */ public void setOrientationPrecision(float value) { orientationPrecision = value; } /** * * <code>setAutoRotation</code> determines if the object assigned to * the controller will rotate with the curve or just following the * curve. * @param value true if the object is to rotate with the curve, false * otherwise. */ public void setAutoRotation(boolean value) { autoRotation = value; } /** * * <code>isAutoRotating</code> returns true if the object is rotating with * the curve and false if it is not. * @return true if the object is following the curve, false otherwise. */ public boolean isAutoRotating() { return autoRotation; } /** * <code>update</code> moves a spatial along the given curve for along a * time period. * @see com.jme.scene.Controller#update(float) */ public void update(float time) { if(mover == null || curve == null || up == null) { return; } currentTime += time * getSpeed(); if (currentTime >= getMinTime() && currentTime <= getMaxTime()) { if (getRepeatType() == RT_CLAMP) { deltaTime = currentTime - getMinTime(); mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( deltaTime, orientationPrecision, up)); } } else if (getRepeatType() == RT_WRAP) { deltaTime = (currentTime - getMinTime()) % 1.0f; if (deltaTime > 1) { currentTime = 0; deltaTime = 0; } mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( deltaTime, orientationPrecision, up)); } } else if (getRepeatType() == RT_CYCLE) { float prevTime = deltaTime; deltaTime = (currentTime - getMinTime()) % 1.0f; if (prevTime > deltaTime) { cycleForward = !cycleForward; } if (cycleForward) { mover.setLocalTranslation(curve.getPoint(deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( deltaTime, orientationPrecision, up)); } } else { mover.setLocalTranslation( curve.getPoint(1.0f - deltaTime,mover.getLocalTranslation())); if(autoRotation) { mover.setLocalRotation( curve.getOrientation( 1.0f - deltaTime, orientationPrecision, up)); } } } else { return; } } } public void reset() { this.currentTime = 0; } public void write(JMEExporter e) throws IOException { super.write(e); OutputCapsule capsule = e.getCapsule(this); capsule.write(mover, "mover", null); capsule.write(curve, "Curve", null); capsule.write(up, "up", null); capsule.write(orientationPrecision, "orientationPrecision", 0.1f); capsule.write(cycleForward, "cycleForward", true); capsule.write(autoRotation, "autoRotation", false); } public void read(JMEImporter e) throws IOException { super.read(e); InputCapsule capsule = e.getCapsule(this); mover = (Spatial)capsule.readSavable("mover", null); curve = (Curve)capsule.readSavable("curve", null); up = (Vector3f)capsule.readSavable("up", null); orientationPrecision = capsule.readFloat("orientationPrecision", 0.1f); cycleForward = capsule.readBoolean("cycleForward", true); autoRotation = capsule.readBoolean("autoRotation", false); } }<|fim▁end|>
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>fn main() { println!(r"cargo:rustc-link-search=."); println!(r"cargo:rustc-link-search=/media/cb_Silverbox-OS/lib/libc"); println!(r"cargo:rustc-link-search=/media/cb_Silverbox-OS/lib/libos"); println!(r"cargo:rustc-link-lib=c"); <|fim▁hole|><|fim▁end|>
println!(r"cargo:rustc-link-lib=os_init"); }
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>#![feature(mpsc_select)] extern crate time; use std::thread; use std::sync::mpsc; use std::sync::mpsc::{SyncSender, Receiver}; use std::sync::mpsc::Select; use std::io::prelude::*; use std::fs::File; use std::vec::Vec; use time::PreciseTime; struct StressedPacket { writer : i32, n : i32, } fn writer(out : SyncSender<StressedPacket>, writer : i32, writes : i32) { for i in 0..writes { out.send(StressedPacket{writer : writer, n : i}).unwrap(); } } fn save_results(N : usize, results : Vec<u64>) { let mut buffer = File::create(format!("st-rust-{}.csv", N)).unwrap(); for r in results { write!(buffer, "{}\n", r); } buffer.flush(); } fn do_select1(in0 : &Receiver<StressedPacket>) { select! { _ = in0.recv() => println!("") } } fn do_select2(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>) { select! { _ = in0.recv() => (), _ = in1.recv() => () } } fn do_select4(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>) { select! { _ = in0.recv() => (), _ = in1.recv() => (), _ = in2.recv() => (), _ = in3.recv() => () } } fn do_select8(in0 : &Receiver<StressedPacket>, in1 : &Receiver<StressedPacket>, in2 : &Receiver<StressedPacket>, in3 : &Receiver<StressedPacket>, in4 : &Receiver<StressedPacket>, in5 : &Receiver<StressedPacket>, in6 : &Receiver<StressedPacket>, in7 : &Receiver<StressedPacket>) { select! { _ = in0.recv() => (), _ = in1.recv() => (), _ = in2.recv() => (), _ = in3.recv() => (), _ = in4.recv() => (), _ = in5.recv() => (), _ = in6.recv() => (), _ = in7.recv() => () } } fn do_select(N : i32, input : &Vec<Receiver<StressedPacket>>) { match N { 1 => do_select1(&input[0]), 2 => do_select2(&input[0], &input[1]), 4 => do_select4(&input[0], &input[1], &input[2], &input[3]), 8 => do_select8(&input[0], &input[1], &input[2], &input[3], &input[4], &input[5], &input[6], &input[7]), _ => () } } fn reader(N : i32, input : Vec<Receiver<StressedPacket>>, total : i32) { let mut results = Vec::new(); let mut start = time::precise_time_ns(); let mut i = 0; for count in 0..total { if count % 65536 == 0 { let total = (time::precise_time_ns() - start) / 65536; results.push(total); println!("{}", i); println!("{} ns", total); start = time::precise_time_ns(); i += 1; } do_select(N, &input); } save_results(input.len(), results); } fn experiment(iterations : i32, threads : i32) { let mut chans = Vec::new(); for i in 0..threads {<|fim▁hole|> let (tx, rx) : (SyncSender<StressedPacket>, Receiver<StressedPacket>) = mpsc::sync_channel(0); chans.push(rx); thread::spawn(move || { writer(tx, i, iterations / threads); } ); } reader(threads, chans, iterations); } fn main() { let x : i32 = 2; experiment(x.pow(24), 1); experiment(x.pow(24), 2); experiment(x.pow(24), 4); experiment(x.pow(24), 8); }<|fim▁end|>
<|file_name|>name.js<|end_file_name|><|fim▁begin|>// Copyright (C) 2015 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es6id: 23.2.3.2 description: > Set.prototype.clear ( ) 17 ECMAScript Standard Built-in Objects includes: [propertyHelper.js] ---*/ <|fim▁hole|>verifyNotWritable(Set.prototype.clear, "name"); verifyConfigurable(Set.prototype.clear, "name");<|fim▁end|>
assert.sameValue(Set.prototype.clear.name, "clear", "The value of `Set.prototype.clear.name` is `'clear'`"); verifyNotEnumerable(Set.prototype.clear, "name");
<|file_name|>error_test.go<|end_file_name|><|fim▁begin|>package api import ( "errors" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Error", func() { Context("Marshalling", func() { It("will be marshalled correctly with a wrapped error", func() { apiErr := WrapErr(errors.New("boom!"), 500) result := []byte(apiErr.HTTPBody()) expected := []byte(`{"errors":[{"status":"500","title":"boom!"}]}`) Expect(result).To(MatchJSON(expected)) }) It("will be marshalled correctly with one error", func() { apiErr := &Error{Title: "Bad Request", Status: "400"} result := []byte(apiErr.HTTPBody()) expected := []byte(`{"errors":[{"status":"400","title":"Bad Request"}]}`) Expect(result).To(MatchJSON(expected)) }) It("will be marshalled correctly with several errors", func() { errorOne := &Error{Title: "Bad Request", Status: "400"} errorTwo := &Error{ ID: "001", Href: "http://bla/blub", Status: "500", Code: "001", Title: "Title must not be empty", Detail: "Never occures in real life", Path: "#titleField", } apiErr := errorOne.Add(errorTwo) result := []byte(apiErr.HTTPBody())<|fim▁hole|> {"status":"400","title":"Bad Request"}, {"id":"001","href":"http://bla/blub","status":"500","code":"001","title":"Title must not be empty","detail":"Never occures in real life","path":"#titleField"} ]}`) Expect(result).To(MatchJSON(expected)) }) }) })<|fim▁end|>
expected := []byte(`{"errors":[
<|file_name|>solitaire15.test.py<|end_file_name|><|fim▁begin|>input = """ 1 2 0 0 1 3 0 0 1 4 0 0 1 5 0 0 1 6 0 0 1 7 0 0 1 8 0 0 1 9 0 0 1 10 0 0 1 11 0 0 1 12 0 0 1 13 0 0 1 14 0 0 1 15 0 0 1 16 0 0 1 17 0 0 1 18 0 0 1 19 0 0 1 20 0 0 1 21 0 0 1 22 0 0 1 23 0 0 1 24 0 0 1 25 0 0 1 26 0 0 1 27 0 0 1 28 0 0 1 29 0 0 1 30 0 0 1 31 0 0 1 32 0 0 1 33 0 0 1 34 0 0 1 35 0 0 1 36 0 0 1 37 0 0 1 38 0 0 1 39 0 0 1 40 0 0 1 41 0 0 1 42 0 0 1 43 0 0 1 44 0 0 1 45 0 0 1 46 0 0 1 47 0 0 1 48 0 0 1 49 0 0 1 50 0 0 1 51 0 0 1 52 0 0 1 53 0 0 1 54 0 0 1 55 0 0 3 132 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 1 0 188 2 189 132 0 1 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 1 1 2 1 189 188 2 190 132 0 2 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 1 1 2 0 190 188 1 188 0 0 3 132 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 1 0 323 2 324 132 0 1 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 1 1 2 1 324 323 2 325 132 0 2 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 1 1 2 0 325 323 1 323 0 0 1 326 1 0 187 1 327 1 0 186 1 328 1 0 185 1 329 1 0 184 1 330 1 0 183 1 331 1 0 182 1 332 1 0 181 1 333 1 0 180 1 334 1 0 179 1 335 1 0 178 1 336 1 0 177 1 337 1 0 176 1 338 1 0 175 1 339 1 0 174 1 340 1 0 173 1 341 1 0 172 1 342 1 0 171 1 343 1 0 170 1 344 1 0 169 1 345 1 0 168 1 346 1 0 167 1 347 1 0 166 1 348 1 0 165 1 349 1 0 164 1 350 1 0 163 1 351 1 0 162 1 352 1 0 161 1 353 1 0 160 1 354 1 0 159 1 355 1 0 158 1 356 1 0 157 1 357 1 0 156 1 358 1 0 155 1 359 1 0 322 1 360 1 0 321 1 361 1 0 320 1 362 1 0 319 1 363 1 0 318 1 364 1 0 317 1 365 1 0 316 1 366 1 0 315 1 367 1 0 314 1 368 1 0 313 1 369 1 0 312 1 370 1 0 311 1 371 1 0 310 1 372 1 0 309 1 373 1 0 308 1 374 1 0 307 1 375 1 0 306 1 376 1 0 305 1 377 1 0 304 1 378 1 0 303 1 379 1 0 302 1 380 1 0 301 1 381 1 0 300 1 382 1 0 299 1 383 1 0 298 1 384 1 0 297 1 385 1 0 296 1 386 1 0 295 1 387 1 0 294 1 388 1 0 293 1 389 1 0 292 1 390 1 0 291 1 391 1 0 290 1 327 1 0 187 1 328 1 0 186 1 330 1 0 184 1 331 1 0 183 1 333 1 0 181 1 334 1 0 180 1 335 1 0 179 1 336 1 0 178 1 337 1 0 177 1 338 1 0 176 1 340 1 0 174 1 341 1 0 173 1 342 1 0 172 1 343 1 0 171 1 344 1 0 170 1 345 1 0 169 1 347 1 0 167 1 348 1 0 166 1 349 1 0 165 1 350 1 0 164 1 351 1 0 163 1 352 1 0 162 1 354 1 0 160 1 355 1 0 159 1 357 1 0 157 1 358 1 0 156 1 360 1 0 322 1 361 1 0 321 1 363 1 0 319 1 364 1 0 318 1 366 1 0 316 1 367 1 0 315 1 368 1 0 314 1 369 1 0 313 1 370 1 0 312 1 371 1 0 311 1 373 1 0 309 1 374 1 0 308 1 375 1 0 307 1 376 1 0 306 1 377 1 0 305 1 378 1 0 304 1 380 1 0 302 1 381 1 0 301 1 382 1 0 300 1 383 1 0 299 1 384 1 0 298 1 385 1 0 297 1 387 1 0 295 1 388 1 0 294 1 390 1 0 292 1 391 1 0 291 1 392 1 0 187 1 393 1 0 184 1 394 1 0 181 1 395 1 0 180 1 396 1 0 179 1 397 1 0 178 1 398 1 0 177 1 399 1 0 174 1 400 1 0 173 1 401 1 0 172 1 402 1 0 171 1 403 1 0 170 1 404 1 0 167 1 405 1 0 166 1 406 1 0 165 1 407 1 0 164 1 408 1 0 163 1 409 1 0 160 1 410 1 0 157 1 411 1 0 322 1 412 1 0 319 1 413 1 0 316 1 414 1 0 315 1 415 1 0 314 1 416 1 0 313 1 417 1 0 312 1 418 1 0 309 1 419 1 0 308 1 420 1 0 307 1 421 1 0 306 1 422 1 0 305 1 423 1 0 302 1 424 1 0 301 1 425 1 0 300 1 426 1 0 299 1 427 1 0 298 1 428 1 0 295 1 429 1 0 292 1 326 1 0 154 1 327 1 0 153 1 328 1 0 152 1 329 1 0 151 1 330 1 0 150 1 331 1 0 149 1 332 1 0 148 1 333 1 0 147 1 334 1 0 146 1 335 1 0 145 1 336 1 0 144 1 337 1 0 143 1 338 1 0 142 1 339 1 0 141 1 340 1 0 140 1 341 1 0 139 1 342 1 0 138 1 343 1 0 137 1 344 1 0 136 1 345 1 0 135 1 346 1 0 134 1 347 1 0 133 1 348 1 0 132 1 349 1 0 131 1 350 1 0 130 1 351 1 0 129 1 352 1 0 128 1 353 1 0 127 1 354 1 0 126 1 355 1 0 125 1 356 1 0 124 1 357 1 0 123 1 358 1 0 122 1 359 1 0 289 1 360 1 0 288 1 361 1 0 287 1 362 1 0 286 1 363 1 0 285 1 364 1 0 284 1 365 1 0 283 1 366 1 0 282 1 367 1 0 281 1 368 1 0 280 1 369 1 0 279 1 370 1 0 278 1 371 1 0 277 1 372 1 0 276 1 373 1 0 275 1 374 1 0 274 1 375 1 0 273 1 376 1 0 272 1 377 1 0 271 1 378 1 0 270 1 379 1 0 269 1 380 1 0 268 1 381 1 0 267 1 382 1 0 266 1 383 1 0 265 1 384 1 0 264 1 385 1 0 263 1 386 1 0 262 1 387 1 0 261 1 388 1 0 260 1 389 1 0 259 1 390 1 0 258 1 391 1 0 257 1 326 1 0 153 1 327 1 0 152 1 329 1 0 150 1 330 1 0 149 1 332 1 0 147 1 333 1 0 146 1 334 1 0 145 1 335 1 0 144 1 336 1 0 143 1 337 1 0 142 1 339 1 0 140 1 340 1 0 139 1 341 1 0 138 1 342 1 0 137 1 343 1 0 136 1 344 1 0 135 1 346 1 0 133 1 347 1 0 132 1 348 1 0 131 1 349 1 0 130 1 350 1 0 129 1 351 1 0 128 1 353 1 0 126 1 354 1 0 125 1 356 1 0 123 1 357 1 0 122 1 359 1 0 288 1 360 1 0 287 1 362 1 0 285 1 363 1 0 284 1 365 1 0 282 1 366 1 0 281 1 367 1 0 280 1 368 1 0 279 1 369 1 0 278 1 370 1 0 277 1 372 1 0 275 1 373 1 0 274 1 374 1 0 273 1 375 1 0 272 1 376 1 0 271 1 377 1 0 270 1 379 1 0 268 1 380 1 0 267 1 381 1 0 266 1 382 1 0 265 1 383 1 0 264 1 384 1 0 263 1 386 1 0 261 1 387 1 0 260 1 389 1 0 258 1 390 1 0 257 1 430 1 0 152 1 431 1 0 149 1 432 1 0 146 1 433 1 0 145 1 394 1 0 144 1 395 1 0 143 1 396 1 0 142 1 434 1 0 139 1 435 1 0 138 1 399 1 0 137 1 400 1 0 136 1 401 1 0 135 1 436 1 0 132 1 437 1 0 131 1 404 1 0 130 1 405 1 0 129 1 406 1 0 128 1 438 1 0 125 1 439 1 0 122 1 440 1 0 287 1 441 1 0 284 1 442 1 0 281 1 443 1 0 280 1 413 1 0 279 1 414 1 0 278 1 415 1 0 277 1 444 1 0 274 1 445 1 0 273 1 418 1 0 272 1 419 1 0 271 1 420 1 0 270 1 446 1 0 267 1 447 1 0 266 1 423 1 0 265 1 424 1 0 264 1 425 1 0 263 1 448 1 0 260 1 449 1 0 257 1 326 1 0 121 1 327 1 0 120 1 328 1 0 119 1 329 1 0 118 1 330 1 0 117 1 331 1 0 116 1 332 1 0 115 1 333 1 0 114 1 334 1 0 113 1 335 1 0 112 1 336 1 0 111 1 337 1 0 110 1 338 1 0 109 1 339 1 0 108 1 340 1 0 107 1 341 1 0 106 1 342 1 0 105 1 343 1 0 104 1 344 1 0 103 1 345 1 0 102 1 346 1 0 101 1 347 1 0 100 1 348 1 0 99 1 349 1 0 98 1 350 1 0 97 1 351 1 0 96 1 352 1 0 95 1 353 1 0 94 1 354 1 0 93 1 355 1 0 92 1 356 1 0 91 1 357 1 0 90 1 358 1 0 89 1 359 1 0 256 1 360 1 0 255 1 361 1 0 254 1 362 1 0 253 1 363 1 0 252 1 364 1 0 251 1 365 1 0 250 1 366 1 0 249 1 367 1 0 248 1 368 1 0 247 1 369 1 0 246 1 370 1 0 245 1 371 1 0 244 1 372 1 0 243 1 373 1 0 242 1 374 1 0 241 1 375 1 0 240 1 376 1 0 239 1 377 1 0 238 1 378 1 0 237 1 379 1 0 236 1 380 1 0 235 1 381 1 0 234 1 382 1 0 233 1 383 1 0 232 1 384 1 0 231 1 385 1 0 230 1 386 1 0 229 1 387 1 0 228 1 388 1 0 227 1 389 1 0 226 1 390 1 0 225 1 391 1 0 224 1 326 1 0 118 1 327 1 0 117 1 328 1 0 116 1 339 1 0 115 1 340 1 0 114 1 341 1 0 113 1 342 1 0 112 1 343 1 0 111 1 344 1 0 110 1 345 1 0 109 1 346 1 0 108 1 347 1 0 107 1 348 1 0 106 1 349 1 0 105 1 350 1 0 104 1 351 1 0 103 1 352 1 0 102 1 329 1 0 99 1 330 1 0 98 1 331 1 0 97 1 334 1 0 94 1 335 1 0 93 1 336 1 0 92 1 353 1 0 91 1 354 1 0 90 1 355 1 0 89 1 359 1 0 253 1 360 1 0 252 1 361 1 0 251 1 372 1 0 250 1 373 1 0 249 1 374 1 0 248 1 375 1 0 247 1 376 1 0 246 1 377 1 0 245 1 378 1 0 244 1 379 1 0 243 1 380 1 0 242 1 381 1 0 241 1 382 1 0 240 1 383 1 0 239 1 384 1 0 238 1 385 1 0 237 1 362 1 0 234 1 363 1 0 233 1 364 1 0 232 1 367 1 0 229 1 368 1 0 228 1 369 1 0 227 1 386 1 0 226 1 387 1 0 225 1 388 1 0 224 1 436 1 0 115 1 437 1 0 114 1 404 1 0 113 1 405 1 0 112 1 406 1 0 111 1 407 1 0 110 1 408 1 0 109 1 431 1 0 106 1 450 1 0 105 1 393 1 0 104 1 430 1 0 99 1 451 1 0 98 1 392 1 0 97 1 399 1 0 94 1 400 1 0 93 1 401 1 0 92 1 394 1 0 91 1 395 1 0 90 1 396 1 0 89 1 446 1 0 250 1 447 1 0 249 1 423 1 0 248 1 424 1 0 247 1 425 1 0 246 1 426 1 0 245 1 427 1 0 244 1 441 1 0 241 1 452 1 0 240 1 412 1 0 239 1 440 1 0 234 1 453 1 0 233 1 411 1 0 232 1 418 1 0 229 1 419 1 0 228 1 420 1 0 227 1 413 1 0 226 1 414 1 0 225 1 415 1 0 224 1 326 1 0 88 1 327 1 0 87 1 328 1 0 86 1 329 1 0 85 1 330 1 0 84 1 331 1 0 83 1 332 1 0 82 1 333 1 0 81 1 334 1 0 80 1 335 1 0 79 1 336 1 0 78 1 337 1 0 77 1 338 1 0 76 1 339 1 0 75 1 340 1 0 74 1 341 1 0 73 1 342 1 0 72 1 343 1 0 71 1 344 1 0 70 1 345 1 0 69 1 346 1 0 68 1 347 1 0 67 1 348 1 0 66 1 349 1 0 65 1 350 1 0 64 1 351 1 0 63 1 352 1 0 62 1 353 1 0 61 1 354 1 0 60 1 355 1 0 59 1 356 1 0 58 1 357 1 0 57 1 358 1 0 56 1 359 1 0 223 1 360 1 0 222 1 361 1 0 221 1 362 1 0 220 1 363 1 0 219 1 364 1 0 218 1 365 1 0 217 1 366 1 0 216 1 367 1 0 215 1 368 1 0 214 1 369 1 0 213 1 370 1 0 212 1 371 1 0 211 1 372 1 0 210 1 373 1 0 209 1 374 1 0 208 1 375 1 0 207 1 376 1 0 206 1 377 1 0 205 1 378 1 0 204 1 379 1 0 203 1 380 1 0 202 1 381 1 0 201 1 382 1 0 200 1 383 1 0 199 1 384 1 0 198 1 385 1 0 197 1 386 1 0 196 1 387 1 0 195 1 388 1 0 194 1 389 1 0 193 1 390 1 0 192 1 391 1 0 191 1 329 1 0 88 1 330 1 0 87 1 331 1 0 86 1 348 1 0 85 1 349 1 0 84 1 350 1 0 83 1 353 1 0 80 1 354 1 0 79 1 355 1 0 78 1 332 1 0 75 1 333 1 0 74 1 334 1 0 73 1 335 1 0 72 1 336 1 0 71 1 337 1 0 70 1 338 1 0 69 1 339 1 0 68 1 340 1 0 67 1 341 1 0 66 1 342 1 0 65 1 343 1 0 64 1 344 1 0 63 1 345 1 0 62 1 356 1 0 61 1 357 1 0 60 1 358 1 0 59 1 362 1 0 223 1 363 1 0 222 1 364 1 0 221 1 381 1 0 220 1 382 1 0 219 1 383 1 0 218 1 386 1 0 215 1 387 1 0 214 1 388 1 0 213 1 365 1 0 210 1 366 1 0 209 1 367 1 0 208 1 368 1 0 207 1 369 1 0 206 1 370 1 0 205 1 371 1 0 204 1 372 1 0 203 1 373 1 0 202 1 374 1 0 201 1 375 1 0 200 1 376 1 0 199 1 377 1 0 198 1 378 1 0 197 1 389 1 0 196 1 390 1 0 195 1 391 1 0 194 1 404 1 0 88 1 405 1 0 87 1 406 1 0 86 1 399 1 0 85 1 400 1 0 84 1 401 1 0 83 1 439 1 0 80 1 454 1 0 79 1 410 1 0 78 1 438 1 0 73 1 455 1 0 72 1 409 1 0 71 1 432 1 0 68 1 433 1 0 67 1 394 1 0 66 1 395 1 0 65 1 396 1 0 64 1 397 1 0 63 1 398 1 0 62 1 423 1 0 223 1 424 1 0 222 1 425 1 0 221 1 418 1 0 220 1 419 1 0 219 1 420 1 0 218 1 449 1 0 215 1 456 1 0 214 1 429 1 0 213 1 448 1 0 208 1 457 1 0 207 1 428 1 0 206 1 442 1 0 203 1 443 1 0 202 1 413 1 0 201 1 414 1 0 200 1 415 1 0 199 1 416 1 0 198 1 417 1 0 197 1 458 1 0 187 1 459 1 0 186 1 460 1 0 185 1 461 1 0 184 1 462 1 0 183 1 463 1 0 182 1 464 1 0 181 1 465 1 0 180 1 466 1 0 179 1 467 1 0 178 1 468 1 0 177 1 469 1 0 176 1 470 1 0 175 1 471 1 0 174 1 472 1 0 173 1 473 1 0 172 1 474 1 0 171 1 475 1 0 170 1 476 1 0 169 1 477 1 0 168 1 478 1 0 167 1 479 1 0 166 1 480 1 0 165 1 481 1 0 164 1 482 1 0 163 1 483 1 0 162 1 484 1 0 161 1 485 1 0 160 1 486 1 0 159 1 487 1 0 158 1 488 1 0 157 1 489 1 0 156 1 490 1 0 155 1 491 1 0 322 1 492 1 0 321 1 493 1 0 320 1 494 1 0 319 1 495 1 0 318 1 496 1 0 317 1 497 1 0 316 1 498 1 0 315 1 499 1 0 314 1 500 1 0 313 1 501 1 0 312 1 502 1 0 311 1 503 1 0 310 1 504 1 0 309 1 505 1 0 308 1 506 1 0 307 1 507 1 0 306 1 508 1 0 305 1 509 1 0 304 1 510 1 0 303 1 511 1 0 302 1 512 1 0 301 1 513 1 0 300 1 514 1 0 299 1 515 1 0 298 1 516 1 0 297 1 517 1 0 296 1 518 1 0 295 1 519 1 0 294 1 520 1 0 293 1 521 1 0 292 1 522 1 0 291 1 523 1 0 290 1 459 1 0 187 1 460 1 0 186 1 462 1 0 184 1 463 1 0 183 1 465 1 0 181 1 466 1 0 180 1 467 1 0 179 1 468 1 0 178 1 469 1 0 177 1 470 1 0 176 1 472 1 0 174 1 473 1 0 173 1 474 1 0 172 1 475 1 0 171 1 476 1 0 170 1 477 1 0 169 1 479 1 0 167 1 480 1 0 166 1 481 1 0 165 1 482 1 0 164 1 483 1 0 163 1 484 1 0 162 1 486 1 0 160 1 487 1 0 159 1 489 1 0 157 1 490 1 0 156 1 492 1 0 322 1 493 1 0 321 1 495 1 0 319 1 496 1 0 318 1 498 1 0 316 1 499 1 0 315 1 500 1 0 314 1 501 1 0 313 1 502 1 0 312 1 503 1 0 311 1 505 1 0 309 1 506 1 0 308 1 507 1 0 307 1 508 1 0 306 1 509 1 0 305 1 510 1 0 304 1 512 1 0 302 1 513 1 0 301 1 514 1 0 300 1 515 1 0 299 1 516 1 0 298 1 517 1 0 297 1 519 1 0 295 1 520 1 0 294 1 522 1 0 292 1 523 1 0 291 1 460 1 0 187 1 463 1 0 184 1 466 1 0 181 1 467 1 0 180 1 468 1 0 179 1 469 1 0 178 1 470 1 0 177 1 473 1 0 174 1 474 1 0 173 1 475 1 0 172 1 476 1 0 171 1 477 1 0 170 1 480 1 0 167 1 481 1 0 166 1 482 1 0 165 1 483 1 0 164 1 484 1 0 163 1 487 1 0 160 1 490 1 0 157 1 493 1 0 322 1 496 1 0 319 1 499 1 0 316 1 500 1 0 315 1 501 1 0 314 1 502 1 0 313 1 503 1 0 312 1 506 1 0 309 1 507 1 0 308 1 508 1 0 307 1 509 1 0 306 1 510 1 0 305 1 513 1 0 302 1 514 1 0 301 1 515 1 0 300 1 516 1 0 299 1 517 1 0 298 1 520 1 0 295 1 523 1 0 292 1 458 1 0 154 1 459 1 0 153 1 460 1 0 152 1 461 1 0 151 1 462 1 0 150 1 463 1 0 149 1 464 1 0 148 1 465 1 0 147 1 466 1 0 146 1 467 1 0 145 1 468 1 0 144 1 469 1 0 143 1 470 1 0 142 1 471 1 0 141 1 472 1 0 140 1 473 1 0 139 1 474 1 0 138 1 475 1 0 137 1 476 1 0 136 1 477 1 0 135 1 478 1 0 134 1 479 1 0 133 1 480 1 0 132 1 481 1 0 131 1 482 1 0 130 1 483 1 0 129 1 484 1 0 128 1 485 1 0 127 1 486 1 0 126 1 487 1 0 125 1 488 1 0 124 1 489 1 0 123 1 490 1 0 122 1 491 1 0 289 1 492 1 0 288 1 493 1 0 287 1 494 1 0 286 1 495 1 0 285 1 496 1 0 284 1 497 1 0 283 1 498 1 0 282 1 499 1 0 281 1 500 1 0 280 1 501 1 0 279 1 502 1 0 278 1 503 1 0 277 1 504 1 0 276 1 505 1 0 275 1 506 1 0 274 1 507 1 0 273 1 508 1 0 272 1 509 1 0 271 1 510 1 0 270 1 511 1 0 269 1 512 1 0 268 1 513 1 0 267 1 514 1 0 266 1 515 1 0 265 1 516 1 0 264 1 517 1 0 263 1 518 1 0 262 1 519 1 0 261 1 520 1 0 260 1 521 1 0 259 1 522 1 0 258 1 523 1 0 257 1 458 1 0 153 1 459 1 0 152 1 461 1 0 150 1 462 1 0 149 1 464 1 0 147 1 465 1 0 146 1 466 1 0 145 1 467 1 0 144 1 468 1 0 143 1 469 1 0 142 1 471 1 0 140 1 472 1 0 139 1 473 1 0 138 1 474 1 0 137 1 475 1 0 136 1 476 1 0 135 1 478 1 0 133 1 479 1 0 132 1 480 1 0 131 1 481 1 0 130 1 482 1 0 129 1 483 1 0 128 1 485 1 0 126 1 486 1 0 125 1 488 1 0 123 1 489 1 0 122 1 491 1 0 288 1 492 1 0 287 1 494 1 0 285 1 495 1 0 284 1 497 1 0 282 1 498 1 0 281 1 499 1 0 280 1 500 1 0 279 1 501 1 0 278 1 502 1 0 277 1 504 1 0 275 1 505 1 0 274 1 506 1 0 273 1 507 1 0 272 1 508 1 0 271 1 509 1 0 270 1 511 1 0 268 1 512 1 0 267 1 513 1 0 266 1 514 1 0 265 1 515 1 0 264 1 516 1 0 263 1 518 1 0 261 1 519 1 0 260 1 521 1 0 258 1 522 1 0 257 1 458 1 0 152 1 461 1 0 149 1 464 1 0 146 1 465 1 0 145 1 466 1 0 144 1 467 1 0 143 1 468 1 0 142 1 471 1 0 139 1 472 1 0 138 1 473 1 0 137 1 474 1 0 136 1 475 1 0 135 1 478 1 0 132 1 479 1 0 131 1 480 1 0 130 1 481 1 0 129 1 482 1 0 128 1 485 1 0 125 1 488 1 0 122 1 491 1 0 287 1 494 1 0 284 1 497 1 0 281 1 498 1 0 280 1 499 1 0 279 1 500 1 0 278 1 501 1 0 277 1 504 1 0 274 1 505 1 0 273 1 506 1 0 272 1 507 1 0 271 1 508 1 0 270 1 511 1 0 267 1 512 1 0 266 1 513 1 0 265 1 514 1 0 264 1 515 1 0 263 1 518 1 0 260 1 521 1 0 257 1 458 1 0 121 1 459 1 0 120 1 460 1 0 119 1 461 1 0 118 1 462 1 0 117 1 463 1 0 116 1 464 1 0 115 1 465 1 0 114 1 466 1 0 113 1 467 1 0 112 1 468 1 0 111 1 469 1 0 110 1 470 1 0 109 1 471 1 0 108 1 472 1 0 107 1 473 1 0 106 1 474 1 0 105 1 475 1 0 104 1 476 1 0 103 1 477 1 0 102 1 478 1 0 101 1 479 1 0 100 1 480 1 0 99 1 481 1 0 98 1 482 1 0 97 1 483 1 0 96 1 484 1 0 95 1 485 1 0 94 1 486 1 0 93 1 487 1 0 92 1 488 1 0 91 1 489 1 0 90 1 490 1 0 89 1 491 1 0 256 1 492 1 0 255 1 493 1 0 254 1 494 1 0 253 1 495 1 0 252 1 496 1 0 251 1 497 1 0 250 1 498 1 0 249 1 499 1 0 248 1 500 1 0 247 1 501 1 0 246 1 502 1 0 245 1 503 1 0 244 1 504 1 0 243 1 505 1 0 242 1 506 1 0 241 1 507 1 0 240 1 508 1 0 239 1 509 1 0 238 1 510 1 0 237 1 511 1 0 236 1 512 1 0 235 1 513 1 0 234 1 514 1 0 233 1 515 1 0 232 1 516 1 0 231 1 517 1 0 230 1 518 1 0 229 1 519 1 0 228 1 520 1 0 227 1 521 1 0 226 1 522 1 0 225 1 523 1 0 224 1 458 1 0 118 1 459 1 0 117 1 460 1 0 116 1 471 1 0 115 1 472 1 0 114 1 473 1 0 113 1 474 1 0 112 1 475 1 0 111 1 476 1 0 110 1 477 1 0 109 1 478 1 0 108 1 479 1 0 107 1 480 1 0 106 1 481 1 0 105 1 482 1 0 104 1 483 1 0 103 1 484 1 0 102 1 461 1 0 99 1 462 1 0 98 1 463 1 0 97 1 466 1 0 94 1 467 1 0 93 1 468 1 0 92 1 485 1 0 91 1 486 1 0 90 1 487 1 0 89 1 491 1 0 253 1 492 1 0 252 1 493 1 0 251 1 504 1 0 250 1 505 1 0 249 1 506 1 0 248 1 507 1 0 247 1 508 1 0 246 1 509 1 0 245 1 510 1 0 244 1 511 1 0 243 1 512 1 0 242 1 513 1 0 241 1 514 1 0 240 1 515 1 0 239 1 516 1 0 238 1 517 1 0 237 1 494 1 0 234 1 495 1 0 233 1 496 1 0 232 1 499 1 0 229 1 500 1 0 228 1 501 1 0 227 1 518 1 0 226 1 519 1 0 225 1 520 1 0 224 1 478 1 0 115 1 479 1 0 114 1 480 1 0 113 1 481 1 0 112 1 482 1 0 111 1 483 1 0 110 1 484 1 0 109 1 461 1 0 106 1 462 1 0 105 1 463 1 0 104 1 458 1 0 99 1 459 1 0 98 1 460 1 0 97 1 473 1 0 94 1 474 1 0 93 1 475 1 0 92 1 466 1 0 91 1 467 1 0 90 1 468 1 0 89 1 511 1 0 250 1 512 1 0 249 1 513 1 0 248 1 514 1 0 247 1 515 1 0 246 1 516 1 0 245 1 517 1 0 244 1 494 1 0 241 1 495 1 0 240 1 496 1 0 239 1 491 1 0 234 1 492 1 0 233 1 493 1 0 232 1 506 1 0 229 1 507 1 0 228 1 508 1 0 227 1 499 1 0 226 1 500 1 0 225 1 501 1 0 224 1 458 1 0 88 1 459 1 0 87 1 460 1 0 86 1 461 1 0 85 1 462 1 0 84 1 463 1 0 83 1 464 1 0 82 1 465 1 0 81 1 466 1 0 80 1 467 1 0 79 1 468 1 0 78 1 469 1 0 77 1 470 1 0 76 1 471 1 0 75 1 472 1 0 74 1 473 1 0 73 1 474 1 0 72 1 475 1 0 71 1 476 1 0 70 1 477 1 0 69 1 478 1 0 68 1 479 1 0 67 1 480 1 0 66 1 481 1 0 65 1 482 1 0 64 1 483 1 0 63 1 484 1 0 62 1 485 1 0 61 1 486 1 0 60 1 487 1 0 59 1 488 1 0 58 1 489 1 0 57 1 490 1 0 56 1 491 1 0 223 1 492 1 0 222 1 493 1 0 221 1 494 1 0 220 1 495 1 0 219 1 496 1 0 218 1 497 1 0 217 1 498 1 0 216 1 499 1 0 215 1 500 1 0 214 1 501 1 0 213 1 502 1 0 212 1 503 1 0 211 1 504 1 0 210 1 505 1 0 209 1 506 1 0 208 1 507 1 0 207 1 508 1 0 206 1 509 1 0 205 1 510 1 0 204 1 511 1 0 203 1 512 1 0 202 1 513 1 0 201 1 514 1 0 200 1 515 1 0 199 1 516 1 0 198 1 517 1 0 197 1 518 1 0 196 1 519 1 0 195 1 520 1 0 194 1 521 1 0 193 1 522 1 0 192 1 523 1 0 191 1 461 1 0 88 1 462 1 0 87 1 463 1 0 86 1 480 1 0 85 1 481 1 0 84 1 482 1 0 83 1 485 1 0 80 1 486 1 0 79 1 487 1 0 78 1 464 1 0 75 1 465 1 0 74 1 466 1 0 73 1 467 1 0 72 1 468 1 0 71 1 469 1 0 70 1 470 1 0 69 1 471 1 0 68 1 472 1 0 67 1 473 1 0 66 1 474 1 0 65 1 475 1 0 64 1 476 1 0 63 1 477 1 0 62 1 488 1 0 61 1 489 1 0 60 1 490 1 0 59 1 494 1 0 223 1 495 1 0 222 1 496 1 0 221 1 513 1 0 220 1 514 1 0 219 1 515 1 0 218 1 518 1 0 215 1 519 1 0 214 1 520 1 0 213 1 497 1 0 210 1 498 1 0 209 1 499 1 0 208 1 500 1 0 207 1 501 1 0 206 1 502 1 0 205 1 503 1 0 204 1 504 1 0 203 1 505 1 0 202 1 506 1 0 201 1 507 1 0 200 1 508 1 0 199 1 509 1 0 198 1 510 1 0 197 1 521 1 0 196 1 522 1 0 195 1 523 1 0 194 1 480 1 0 88 1 481 1 0 87 1 482 1 0 86 1 473 1 0 85 1 474 1 0 84 1 475 1 0 83 1 488 1 0 80 1 489 1 0 79 1 490 1 0 78 1 485 1 0 73 1 486 1 0 72 1 487 1 0 71 1 464 1 0 68 1 465 1 0 67 1 466 1 0 66 1 467 1 0 65 1 468 1 0 64 1 469 1 0 63 1 470 1 0 62 1 513 1 0 223 1 514 1 0 222 1 515 1 0 221 1 506 1 0 220 1 507 1 0 219 1 508 1 0 218 1 521 1 0 215 1 522 1 0 214 1 523 1 0 213 1 518 1 0 208 1 519 1 0 207 1 520 1 0 206 1 497 1 0 203 1 498 1 0 202 1 499 1 0 201 1 500 1 0 200 1 501 1 0 199 1 502 1 0 198 1 503 1 0 197 1 524 0 0 1 525 0 0 1 526 0 0 1 527 0 0 1 528 0 0 1 529 0 0 1 358 2 1 490 391 1 357 2 1 489 390 1 356 2 1 488 389 1 355 2 1 487 388 1 354 2 1 486 387 1 353 2 1 485 386 1 352 2 1 484 385 1 351 2 1 483 384 1 350 2 1 482 383 1 349 2 1 481 382 1 348 2 1 480 381 1 347 2 1 479 380 1 346 2 1 478 379 1 345 2 1 477 378 1 344 2 1 476 377 1 343 2 1 475 376 1 342 2 1 474 375 1 341 2 1 473 374 1 340 2 1 472 373 1 339 2 1 471 372 1 338 2 1 470 371 1 337 2 1 469 370 1 336 2 1 468 369 1 335 2 1 467 368 1 334 2 1 466 367 1 333 2 1 465 366 1 332 2 1 464 365 1 331 2 1 463 364 1 330 2 1 462 363 1 329 2 1 461 362 1 328 2 1 460 361 1 327 2 1 459 360 1 326 2 1 458 359 1 375 1 1 507 1 455 2 1 486 457 1 454 2 1 489 456 1 451 2 1 459 453 1 450 2 1 462 452 1 439 2 1 488 449 1 438 2 1 485 448 1 437 2 1 479 447 1 436 2 1 478 446 1 435 2 1 472 445 1 434 2 1 471 444 1 433 2 1 465 443 1 432 2 1 464 442 1 431 2 1 461 441 1 430 2 1 458 440 1 410 2 1 490 429 1 409 2 1 487 428 1 408 2 1 484 427 1 407 2 1 483 426 1 406 2 1 482 425 1 405 2 1 481 424 1 404 2 1 480 423 1 403 2 1 477 422 1 402 2 1 476 421 1 401 2 1 475 420 1 400 2 1 474 419 1 399 2 1 473 418 1 398 2 1 470 417 1 397 2 1 469 416 1 396 2 1 468 415 1 395 2 1 467 414 1 394 2 1 466 413 1 393 2 1 463 412 1 392 2 1 460 411 1 421 1 1 509 1 425 1 1 515 1 420 1 1 508 1 452 1 1 495 1 424 1 1 514 1 530 3 0 449 456 391 1 531 3 0 448 457 388 1 532 3 0 425 426 385 1 533 3 0 424 425 384 1 534 3 0 423 424 383 1 535 3 0 447 423 382 1 536 3 0 446 447 381 1 537 3 0 420 421 378 1 538 3 0 419 420 377 1 539 3 0 418 419 376 1 540 3 0 445 418 375 1 541 3 0 444 445 374 1 542 3 0 415 416 371 1 543 3 0 414 415 370 1 544 3 0 413 414 369 1 545 3 0 443 413 368 1 546 3 0 442 443 367 1 547 3 0 441 452 364 1 548 3 0 440 453 361 1 549 3 0 429 456 389 1 550 3 0 428 457 386 1 551 3 0 427 426 383 1 552 3 0 426 425 382 1 553 3 0 425 424 381 1 554 3 0 424 423 380 1 555 3 0 423 447 379 1 556 3 0 422 421 376 1 557 3 0 421 420 375 1 558 3 0 420 419 374 1 559 3 0 419 418 373 1 560 3 0 418 445 372 1 561 3 0 417 416 369 1 562 3 0 416 415 368 1 563 3 0 415 414 367 1 564 3 0 414 413 366 1 565 3 0 413 443 365 1 566 3 0 412 452 362 1 567 3 0 411 453 359 1 568 0 0 1 569 3 0 417 422 385 1 570 3 0 416 421 384 1 571 3 0 415 420 383 1 572 3 0 414 419 382 1 573 3 0 413 418 381 1 574 3 0 443 445 380 1 575 3 0 442 444 379 1 576 3 0 428 415 376 1 577 3 0 457 414 375 1 578 3 0 448 413 374 1 579 3 0 429 428 369 1 580 3 0 456 457 368 1 581 3 0 449 448 367 1 582 3 0 420 425 364 1 583 3 0 419 424 363 1 584 3 0 418 423 362 1 585 3 0 425 412 361 1 586 3 0 424 452 360 1 587 3 0 423 441 359 1 588 3 0 415 428 391 1 589 3 0 414 457 390 1 590 3 0 413 448 389 1 591 3 0 420 415 388 1 592 3 0 419 414 387 1 593 3 0 418 413 386 1 594 3 0 411 412 383 1 595 3 0 453 452 382 1 596 3 0 440 441 381 1 597 3 0 412 425 376 1 598 3 0 452 424 375 1 599 3 0 441 423 374 1 600 3 0 427 422 371 1 601 3 0 426 421 370 1 602 3 0 425 420 369 1 603 3 0 424 419 368 1 604 3 0 423 418 367 1 605 3 0 447 445 366 1 606 3 0 446 444 365 1 607 0 0 1 1 2 1 596 88 1 1 2 1 595 87 1 1 2 1 594 86 1 1 2 1 599 85 1 1 2 1 598 84 1 1 2 1 597 83 1 1 1 0 82 1 1 1 0 81 1 1 2 1 590 80 1 1 2 1 589 79 1 1 2 1 588 78 1 1 1 0 77 1 1 1 0 76 1 1 1 0 75 1 1 1 0 74 1 1 2 1 593 73 1 1 2 1 592 72 1 1 2 1 591 71 1 1 1 0 70 1 1 1 0 69 1 1 2 1 606 68 1 1 2 1 605 67 1 1 2 1 604 66 1 1 2 1 603 65 1 1 2 1 602 64 1 1 2 1 601 63 1 1 2 1 600 62 1 1 1 0 61 1 1 1 0 60 1 1 1 0 59 1 1 1 0 58 1 1 1 0 57 1 1 1 0 56 1 1 1 0 121 1 1 1 0 120 1 1 1 0 119 1 1 1 0 118 1 1 1 0 117 1 1 1 0 116 1 1 2 1 575 115 1 1 2 1 574 114 1 1 2 1 573 113 1 1 2 1 572 112 1 1 2 1 571 111 1 1 2 1 570 110 1 1 2 1 569 109 1 1 1 0 108 1 1 1 0 107 1 1 2 1 584 106 1 1 2 1 583 105 1 1 2 1 582 104 1 1 1 0 103 1 1 1 0 102 1 1 1 0 101 1 1 1 0 100 1 1 2 1 587 99 1 1 2 1 586 98 1 1 2 1 585 97 1 1 1 0 96 1 1 1 0 95 1 1 2 1 578 94 1 1 2 1 577 93 1 1 2 1 576 92 1 1 2 1 581 91 1 1 2 1 580 90 1 1 2 1 579 89 1 1 1 0 154 1 1 1 0 153 1 1 2 1 567 152 1 1 1 0 151 1 1 1 0 150 1 1 2 1 566 149 1 1 1 0 148 1 1 1 0 147 1 1 2 1 565 146 1 1 2 1 564 145 1 1 2 1 563 144 1 1 2 1 562 143 1 1 2 1 561 142 1 1 1 0 141 1 1 1 0 140 1 1 2 1 560 139 1 1 2 1 559 138 1 1 2 1 558 137 1 1 2 1 557 136 1 1 2 1 556 135 1 1 1 0 134 1 1 1 0 133 1 1 2 1 555 132 1 1 2 1 554 131 1 1 2 1 553 130 1 1 2 1 552 129 1 1 2 1 551 128 1 1 1 0 127 1 1 1 0 126 1 1 2 1 550 125 1 1 1 0 124 1 1 1 0 123 1 1 2 1 549 122 1 1 2 1 548 187<|fim▁hole|>1 1 2 1 547 184 1 1 1 0 183 1 1 1 0 182 1 1 2 1 546 181 1 1 2 1 545 180 1 1 2 1 544 179 1 1 2 1 543 178 1 1 2 1 542 177 1 1 1 0 176 1 1 1 0 175 1 1 2 1 541 174 1 1 2 1 540 173 1 1 2 1 539 172 1 1 2 1 538 171 1 1 2 1 537 170 1 1 1 0 169 1 1 1 0 168 1 1 2 1 536 167 1 1 2 1 535 166 1 1 2 1 534 165 1 1 2 1 533 164 1 1 2 1 532 163 1 1 1 0 162 1 1 1 0 161 1 1 2 1 531 160 1 1 1 0 159 1 1 1 0 158 1 1 2 1 530 157 1 1 1 0 156 1 1 1 0 155 1 1 1 0 223 1 1 1 0 222 1 1 1 0 221 1 1 1 0 220 1 1 1 0 218 1 1 1 0 217 1 1 1 0 216 1 1 1 0 215 1 1 1 0 214 1 1 1 0 213 1 1 1 0 212 1 1 1 0 211 1 1 1 0 210 1 1 1 0 209 1 1 1 0 208 1 1 1 0 207 1 1 1 0 206 1 1 1 0 205 1 1 1 0 204 1 1 1 0 203 1 1 1 0 202 1 1 1 0 201 1 1 1 0 200 1 1 1 0 199 1 1 1 0 198 1 1 1 0 197 1 1 1 0 196 1 1 1 0 195 1 1 1 0 194 1 1 1 0 193 1 1 1 0 192 1 1 1 0 191 1 1 1 0 256 1 1 1 0 255 1 1 1 0 254 1 1 1 0 253 1 1 1 0 252 1 1 1 0 251 1 1 1 0 250 1 1 1 0 249 1 1 1 0 248 1 1 1 0 247 1 1 1 0 246 1 1 1 0 245 1 1 1 0 244 1 1 1 0 243 1 1 1 0 242 1 1 1 0 241 1 1 1 0 240 1 1 1 0 239 1 1 1 0 238 1 1 1 0 237 1 1 1 0 236 1 1 1 0 235 1 1 1 0 234 1 1 1 0 233 1 1 1 0 232 1 1 1 0 231 1 1 1 0 230 1 1 1 0 229 1 1 1 0 228 1 1 1 0 227 1 1 1 0 226 1 1 1 0 225 1 1 1 0 224 1 1 1 0 289 1 1 1 0 288 1 1 1 0 287 1 1 1 0 286 1 1 1 0 285 1 1 1 0 284 1 1 1 0 283 1 1 1 0 282 1 1 1 0 281 1 1 1 0 280 1 1 1 0 279 1 1 1 0 278 1 1 1 0 277 1 1 1 0 276 1 1 1 0 275 1 1 1 0 274 1 1 1 0 273 1 1 1 0 272 1 1 1 0 270 1 1 1 0 269 1 1 1 0 268 1 1 1 0 267 1 1 1 0 266 1 1 1 0 265 1 1 1 0 264 1 1 1 0 263 1 1 1 0 262 1 1 1 0 261 1 1 1 0 260 1 1 1 0 259 1 1 1 0 258 1 1 1 0 257 1 1 1 0 322 1 1 1 0 321 1 1 1 0 320 1 1 1 0 319 1 1 1 0 318 1 1 1 0 317 1 1 1 0 316 1 1 1 0 315 1 1 1 0 314 1 1 1 0 313 1 1 1 0 312 1 1 1 0 311 1 1 1 0 310 1 1 1 0 309 1 1 1 0 308 1 1 1 0 307 1 1 1 0 306 1 1 1 0 305 1 1 1 0 304 1 1 1 0 303 1 1 1 0 302 1 1 1 0 301 1 1 1 0 300 1 1 1 0 299 1 1 1 0 298 1 1 1 0 297 1 1 1 0 296 1 1 1 0 295 1 1 1 0 294 1 1 1 0 293 1 1 1 0 292 1 1 1 0 291 1 1 1 0 290 0 2 range(1) 15 range(2) 16 range(3) 17 range(4) 18 range(5) 19 range(6) 20 range(7) 56 move(2,right,7,3) 57 move(2,right,7,4) 58 move(2,right,7,5) 59 move(2,right,6,3) 60 move(2,right,6,4) 61 move(2,right,6,5) 62 move(2,right,3,1) 63 move(2,right,3,2) 64 move(2,right,3,3) 65 move(2,right,3,4) 66 move(2,right,3,5) 67 move(2,right,3,6) 68 move(2,right,3,7) 69 move(2,right,4,1) 70 move(2,right,4,2) 71 move(2,right,4,3) 72 move(2,right,4,4) 73 move(2,right,4,5) 74 move(2,right,4,6) 75 move(2,right,4,7) 76 move(2,right,5,1) 77 move(2,right,5,2) 78 move(2,right,5,3) 79 move(2,right,5,4) 80 move(2,right,5,5) 81 move(2,right,5,6) 82 move(2,right,5,7) 83 move(2,right,2,3) 84 move(2,right,2,4) 85 move(2,right,2,5) 86 move(2,right,1,3) 87 move(2,right,1,4) 88 move(2,right,1,5) 89 move(2,left,7,3) 90 move(2,left,7,4) 91 move(2,left,7,5) 92 move(2,left,6,3) 93 move(2,left,6,4) 94 move(2,left,6,5) 95 move(2,left,3,1) 96 move(2,left,3,2) 97 move(2,left,3,3) 98 move(2,left,3,4) 99 move(2,left,3,5) 100 move(2,left,3,6) 101 move(2,left,3,7) 102 move(2,left,4,1) 103 move(2,left,4,2) 104 move(2,left,4,3) 105 move(2,left,4,4) 106 move(2,left,4,5) 107 move(2,left,4,6) 108 move(2,left,4,7) 109 move(2,left,5,1) 110 move(2,left,5,2) 111 move(2,left,5,3) 112 move(2,left,5,4) 113 move(2,left,5,5) 114 move(2,left,5,6) 115 move(2,left,5,7) 116 move(2,left,2,3) 117 move(2,left,2,4) 118 move(2,left,2,5) 119 move(2,left,1,3) 120 move(2,left,1,4) 121 move(2,left,1,5) 122 move(2,down,7,3) 123 move(2,down,7,4) 124 move(2,down,7,5) 125 move(2,down,6,3) 126 move(2,down,6,4) 127 move(2,down,6,5) 128 move(2,down,3,1) 129 move(2,down,3,2) 130 move(2,down,3,3) 131 move(2,down,3,4) 132 move(2,down,3,5) 133 move(2,down,3,6) 134 move(2,down,3,7) 135 move(2,down,4,1) 136 move(2,down,4,2) 137 move(2,down,4,3) 138 move(2,down,4,4) 139 move(2,down,4,5) 140 move(2,down,4,6) 141 move(2,down,4,7) 142 move(2,down,5,1) 143 move(2,down,5,2) 144 move(2,down,5,3) 145 move(2,down,5,4) 146 move(2,down,5,5) 147 move(2,down,5,6) 148 move(2,down,5,7) 149 move(2,down,2,3) 150 move(2,down,2,4) 151 move(2,down,2,5) 152 move(2,down,1,3) 153 move(2,down,1,4) 154 move(2,down,1,5) 155 move(2,up,7,3) 156 move(2,up,7,4) 157 move(2,up,7,5) 158 move(2,up,6,3) 159 move(2,up,6,4) 160 move(2,up,6,5) 161 move(2,up,3,1) 162 move(2,up,3,2) 163 move(2,up,3,3) 164 move(2,up,3,4) 165 move(2,up,3,5) 166 move(2,up,3,6) 167 move(2,up,3,7) 168 move(2,up,4,1) 169 move(2,up,4,2) 170 move(2,up,4,3) 171 move(2,up,4,4) 172 move(2,up,4,5) 173 move(2,up,4,6) 174 move(2,up,4,7) 175 move(2,up,5,1) 176 move(2,up,5,2) 177 move(2,up,5,3) 178 move(2,up,5,4) 179 move(2,up,5,5) 180 move(2,up,5,6) 181 move(2,up,5,7) 182 move(2,up,2,3) 183 move(2,up,2,4) 184 move(2,up,2,5) 185 move(2,up,1,3) 186 move(2,up,1,4) 187 move(2,up,1,5) 191 move(1,right,7,3) 192 move(1,right,7,4) 193 move(1,right,7,5) 194 move(1,right,6,3) 195 move(1,right,6,4) 196 move(1,right,6,5) 197 move(1,right,3,1) 198 move(1,right,3,2) 199 move(1,right,3,3) 200 move(1,right,3,4) 201 move(1,right,3,5) 202 move(1,right,3,6) 203 move(1,right,3,7) 204 move(1,right,4,1) 205 move(1,right,4,2) 206 move(1,right,4,3) 207 move(1,right,4,4) 208 move(1,right,4,5) 209 move(1,right,4,6) 210 move(1,right,4,7) 211 move(1,right,5,1) 212 move(1,right,5,2) 213 move(1,right,5,3) 214 move(1,right,5,4) 215 move(1,right,5,5) 216 move(1,right,5,6) 217 move(1,right,5,7) 218 move(1,right,2,3) 219 move(1,right,2,4) 220 move(1,right,2,5) 221 move(1,right,1,3) 222 move(1,right,1,4) 223 move(1,right,1,5) 224 move(1,left,7,3) 225 move(1,left,7,4) 226 move(1,left,7,5) 227 move(1,left,6,3) 228 move(1,left,6,4) 229 move(1,left,6,5) 230 move(1,left,3,1) 231 move(1,left,3,2) 232 move(1,left,3,3) 233 move(1,left,3,4) 234 move(1,left,3,5) 235 move(1,left,3,6) 236 move(1,left,3,7) 237 move(1,left,4,1) 238 move(1,left,4,2) 239 move(1,left,4,3) 240 move(1,left,4,4) 241 move(1,left,4,5) 242 move(1,left,4,6) 243 move(1,left,4,7) 244 move(1,left,5,1) 245 move(1,left,5,2) 246 move(1,left,5,3) 247 move(1,left,5,4) 248 move(1,left,5,5) 249 move(1,left,5,6) 250 move(1,left,5,7) 251 move(1,left,2,3) 252 move(1,left,2,4) 253 move(1,left,2,5) 254 move(1,left,1,3) 255 move(1,left,1,4) 256 move(1,left,1,5) 257 move(1,down,7,3) 258 move(1,down,7,4) 259 move(1,down,7,5) 260 move(1,down,6,3) 261 move(1,down,6,4) 262 move(1,down,6,5) 263 move(1,down,3,1) 264 move(1,down,3,2) 265 move(1,down,3,3) 266 move(1,down,3,4) 267 move(1,down,3,5) 268 move(1,down,3,6) 269 move(1,down,3,7) 270 move(1,down,4,1) 271 move(1,down,4,2) 272 move(1,down,4,3) 273 move(1,down,4,4) 274 move(1,down,4,5) 275 move(1,down,4,6) 276 move(1,down,4,7) 277 move(1,down,5,1) 278 move(1,down,5,2) 279 move(1,down,5,3) 280 move(1,down,5,4) 281 move(1,down,5,5) 282 move(1,down,5,6) 283 move(1,down,5,7) 284 move(1,down,2,3) 285 move(1,down,2,4) 286 move(1,down,2,5) 287 move(1,down,1,3) 288 move(1,down,1,4) 289 move(1,down,1,5) 290 move(1,up,7,3) 291 move(1,up,7,4) 292 move(1,up,7,5) 293 move(1,up,6,3) 294 move(1,up,6,4) 295 move(1,up,6,5) 296 move(1,up,3,1) 297 move(1,up,3,2) 298 move(1,up,3,3) 299 move(1,up,3,4) 300 move(1,up,3,5) 301 move(1,up,3,6) 302 move(1,up,3,7) 303 move(1,up,4,1) 304 move(1,up,4,2) 305 move(1,up,4,3) 306 move(1,up,4,4) 307 move(1,up,4,5) 308 move(1,up,4,6) 309 move(1,up,4,7) 310 move(1,up,5,1) 311 move(1,up,5,2) 312 move(1,up,5,3) 313 move(1,up,5,4) 314 move(1,up,5,5) 315 move(1,up,5,6) 316 move(1,up,5,7) 317 move(1,up,2,3) 318 move(1,up,2,4) 319 move(1,up,2,5) 320 move(1,up,1,3) 321 move(1,up,1,4) 322 move(1,up,1,5) 3 direction(up) 4 direction(down) 5 direction(left) 6 direction(right) 9 full(4,2) 10 full(3,3) 11 full(4,3) 12 full(2,4) 13 full(3,4) 326 state(3,empty,1,5) 327 state(3,empty,1,4) 328 state(3,empty,1,3) 329 state(3,empty,2,5) 330 state(3,empty,2,4) 331 state(3,empty,2,3) 332 state(3,empty,5,7) 333 state(3,empty,5,6) 334 state(3,empty,5,5) 335 state(3,empty,5,4) 336 state(3,empty,5,3) 337 state(3,empty,5,2) 338 state(3,empty,5,1) 339 state(3,empty,4,7) 340 state(3,empty,4,6) 341 state(3,empty,4,5) 342 state(3,empty,4,4) 343 state(3,empty,4,3) 344 state(3,empty,4,2) 345 state(3,empty,4,1) 346 state(3,empty,3,7) 347 state(3,empty,3,6) 348 state(3,empty,3,5) 349 state(3,empty,3,4) 350 state(3,empty,3,3) 351 state(3,empty,3,2) 352 state(3,empty,3,1) 353 state(3,empty,6,5) 354 state(3,empty,6,4) 355 state(3,empty,6,3) 356 state(3,empty,7,5) 357 state(3,empty,7,4) 358 state(3,empty,7,3) 359 state(2,empty,1,5) 360 state(2,empty,1,4) 361 state(2,empty,1,3) 362 state(2,empty,2,5) 363 state(2,empty,2,4) 364 state(2,empty,2,3) 365 state(2,empty,5,7) 366 state(2,empty,5,6) 367 state(2,empty,5,5) 368 state(2,empty,5,4) 369 state(2,empty,5,3) 370 state(2,empty,5,2) 371 state(2,empty,5,1) 372 state(2,empty,4,7) 373 state(2,empty,4,6) 374 state(2,empty,4,5) 375 state(2,empty,4,4) 376 state(2,empty,4,3) 377 state(2,empty,4,2) 378 state(2,empty,4,1) 379 state(2,empty,3,7) 380 state(2,empty,3,6) 381 state(2,empty,3,5) 382 state(2,empty,3,4) 383 state(2,empty,3,3) 384 state(2,empty,3,2) 385 state(2,empty,3,1) 386 state(2,empty,6,5) 387 state(2,empty,6,4) 388 state(2,empty,6,3) 389 state(2,empty,7,5) 390 state(2,empty,7,4) 391 state(2,empty,7,3) 392 state(3,full,1,3) 393 state(3,full,2,3) 394 state(3,full,5,5) 395 state(3,full,5,4) 396 state(3,full,5,3) 397 state(3,full,5,2) 398 state(3,full,5,1) 399 state(3,full,4,5) 400 state(3,full,4,4) 401 state(3,full,4,3) 402 state(3,full,4,2) 403 state(3,full,4,1) 404 state(3,full,3,5) 405 state(3,full,3,4) 406 state(3,full,3,3) 407 state(3,full,3,2) 408 state(3,full,3,1) 409 state(3,full,6,3) 410 state(3,full,7,3) 411 state(2,full,1,3) 412 state(2,full,2,3) 413 state(2,full,5,5) 414 state(2,full,5,4) 415 state(2,full,5,3) 416 state(2,full,5,2) 417 state(2,full,5,1) 418 state(2,full,4,5) 419 state(2,full,4,4) 420 state(2,full,4,3) 421 state(2,full,4,2) 422 state(2,full,4,1) 423 state(2,full,3,5) 424 state(2,full,3,4) 425 state(2,full,3,3) 426 state(2,full,3,2) 427 state(2,full,3,1) 428 state(2,full,6,3) 429 state(2,full,7,3) 430 state(3,full,1,5) 431 state(3,full,2,5) 432 state(3,full,5,7) 433 state(3,full,5,6) 434 state(3,full,4,7) 435 state(3,full,4,6) 436 state(3,full,3,7) 437 state(3,full,3,6) 438 state(3,full,6,5) 439 state(3,full,7,5) 440 state(2,full,1,5) 441 state(2,full,2,5) 442 state(2,full,5,7) 443 state(2,full,5,6) 444 state(2,full,4,7) 445 state(2,full,4,6) 446 state(2,full,3,7) 447 state(2,full,3,6) 448 state(2,full,6,5) 449 state(2,full,7,5) 450 state(3,full,2,4) 451 state(3,full,1,4) 452 state(2,full,2,4) 453 state(2,full,1,4) 454 state(3,full,7,4) 455 state(3,full,6,4) 456 state(2,full,7,4) 457 state(2,full,6,4) 524 state(1,full,3,4) 525 state(1,full,2,4) 526 state(1,full,4,3) 527 state(1,full,3,3) 528 state(1,full,4,2) 529 state(1,empty,4,4) 7 status(full) 8 status(empty) 458 changed(3,1,5) 459 changed(3,1,4) 460 changed(3,1,3) 461 changed(3,2,5) 462 changed(3,2,4) 463 changed(3,2,3) 464 changed(3,5,7) 465 changed(3,5,6) 466 changed(3,5,5) 467 changed(3,5,4) 468 changed(3,5,3) 469 changed(3,5,2) 470 changed(3,5,1) 471 changed(3,4,7) 472 changed(3,4,6) 473 changed(3,4,5) 474 changed(3,4,4) 475 changed(3,4,3) 476 changed(3,4,2) 477 changed(3,4,1) 478 changed(3,3,7) 479 changed(3,3,6) 480 changed(3,3,5) 481 changed(3,3,4) 482 changed(3,3,3) 483 changed(3,3,2) 484 changed(3,3,1) 485 changed(3,6,5) 486 changed(3,6,4) 487 changed(3,6,3) 488 changed(3,7,5) 489 changed(3,7,4) 490 changed(3,7,3) 491 changed(2,1,5) 492 changed(2,1,4) 493 changed(2,1,3) 494 changed(2,2,5) 495 changed(2,2,4) 496 changed(2,2,3) 497 changed(2,5,7) 498 changed(2,5,6) 499 changed(2,5,5) 500 changed(2,5,4) 501 changed(2,5,3) 502 changed(2,5,2) 503 changed(2,5,1) 504 changed(2,4,7) 505 changed(2,4,6) 506 changed(2,4,5) 507 changed(2,4,4) 508 changed(2,4,3) 509 changed(2,4,2) 510 changed(2,4,1) 511 changed(2,3,7) 512 changed(2,3,6) 513 changed(2,3,5) 514 changed(2,3,4) 515 changed(2,3,3) 516 changed(2,3,2) 517 changed(2,3,1) 518 changed(2,6,5) 519 changed(2,6,4) 520 changed(2,6,3) 521 changed(2,7,5) 522 changed(2,7,4) 523 changed(2,7,3) 54 time(1) 55 time(2) 14 empty(4,4) 530 possibleMove(2,up,7,5) 531 possibleMove(2,up,6,5) 532 possibleMove(2,up,3,3) 533 possibleMove(2,up,3,4) 534 possibleMove(2,up,3,5) 535 possibleMove(2,up,3,6) 536 possibleMove(2,up,3,7) 537 possibleMove(2,up,4,3) 538 possibleMove(2,up,4,4) 539 possibleMove(2,up,4,5) 540 possibleMove(2,up,4,6) 541 possibleMove(2,up,4,7) 542 possibleMove(2,up,5,3) 543 possibleMove(2,up,5,4) 544 possibleMove(2,up,5,5) 545 possibleMove(2,up,5,6) 546 possibleMove(2,up,5,7) 547 possibleMove(2,up,2,5) 548 possibleMove(2,up,1,5) 549 possibleMove(2,down,7,3) 550 possibleMove(2,down,6,3) 551 possibleMove(2,down,3,1) 552 possibleMove(2,down,3,2) 553 possibleMove(2,down,3,3) 554 possibleMove(2,down,3,4) 555 possibleMove(2,down,3,5) 556 possibleMove(2,down,4,1) 557 possibleMove(2,down,4,2) 558 possibleMove(2,down,4,3) 559 possibleMove(2,down,4,4) 560 possibleMove(2,down,4,5) 561 possibleMove(2,down,5,1) 562 possibleMove(2,down,5,2) 563 possibleMove(2,down,5,3) 564 possibleMove(2,down,5,4) 565 possibleMove(2,down,5,5) 566 possibleMove(2,down,2,3) 567 possibleMove(2,down,1,3) 568 possibleMove(1,down,4,2) 569 possibleMove(2,left,5,1) 570 possibleMove(2,left,5,2) 571 possibleMove(2,left,5,3) 572 possibleMove(2,left,5,4) 573 possibleMove(2,left,5,5) 574 possibleMove(2,left,5,6) 575 possibleMove(2,left,5,7) 576 possibleMove(2,left,6,3) 577 possibleMove(2,left,6,4) 578 possibleMove(2,left,6,5) 579 possibleMove(2,left,7,3) 580 possibleMove(2,left,7,4) 581 possibleMove(2,left,7,5) 582 possibleMove(2,left,4,3) 583 possibleMove(2,left,4,4) 584 possibleMove(2,left,4,5) 585 possibleMove(2,left,3,3) 586 possibleMove(2,left,3,4) 587 possibleMove(2,left,3,5) 588 possibleMove(2,right,5,3) 589 possibleMove(2,right,5,4) 590 possibleMove(2,right,5,5) 591 possibleMove(2,right,4,3) 592 possibleMove(2,right,4,4) 593 possibleMove(2,right,4,5) 594 possibleMove(2,right,1,3) 595 possibleMove(2,right,1,4) 596 possibleMove(2,right,1,5) 597 possibleMove(2,right,2,3) 598 possibleMove(2,right,2,4) 599 possibleMove(2,right,2,5) 600 possibleMove(2,right,3,1) 601 possibleMove(2,right,3,2) 602 possibleMove(2,right,3,3) 603 possibleMove(2,right,3,4) 604 possibleMove(2,right,3,5) 605 possibleMove(2,right,3,6) 606 possibleMove(2,right,3,7) 607 possibleMove(1,right,2,4) 21 location(1,5) 22 location(1,4) 23 location(1,3) 24 location(2,5) 25 location(2,4) 26 location(2,3) 27 location(5,7) 28 location(5,6) 29 location(5,5) 30 location(5,4) 31 location(5,3) 32 location(5,2) 33 location(5,1) 34 location(4,7) 35 location(4,6) 36 location(4,5) 37 location(4,4) 38 location(4,3) 39 location(4,2) 40 location(4,1) 41 location(3,7) 42 location(3,6) 43 location(3,5) 44 location(3,4) 45 location(3,3) 46 location(3,2) 47 location(3,1) 48 location(6,5) 49 location(6,4) 50 location(6,3) 51 location(7,5) 52 location(7,4) 53 location(7,3) 0 B+ 0 B- 1 0 1 """ output = """ """<|fim▁end|>
1 1 1 0 186 1 1 1 0 185
<|file_name|>Custom Message Tones.user.js<|end_file_name|><|fim▁begin|>// ==UserScript== // @name Custom Message Tones // @namespace pxgamer // @version 0.5 // @description Adds options to load in custom tones when a message is received. // @author pxgamer // @include *kat.cr/* // @grant none // ==/UserScript== (function() { var AUDIO_FILE = ""; // URL of audio file (MP3, WAV, OGG) var AUDIO_LENGTH = 5000; // Length in Ticks // Do Not Edit Below Here var acMethod = jQuery.fn.addClass; var audio1; jQuery.fn.addClass = function() { var result = acMethod.apply(this, arguments); jQuery(this).trigger('cssClassChanged'); return result; }; $('body').append('<span id="chatMsgHandler"></span>'); $('#chatMsgHandler').css('display', 'none'); $(document).on('cssClassChanged', function() { var msgBarElem = $('.chat-bar-new'); if (msgBarElem.length > 0) { audio1.play(); setTimeout(function() { audio1.pause(); audio1.currentTime = 0; }, AUDIO_LENGTH); } }); var audioTypes = { "mp3": "audio/mpeg", "ogg": "audio/ogg", "wav": "audio/wav" }; function pxS(sound) { var audio_element = document.createElement('audio'); if (audio_element.canPlayType) { for (var i = 0; i < arguments.length; i++) { var source_element = document.createElement('source'); source_element.setAttribute('src', arguments[i]); if (arguments[i].match(/\.(\w+)$/i)) { source_element.setAttribute('type', audioTypes[RegExp.$1]); } audio_element.appendChild(source_element); } audio_element.load(); audio_element.pFunc = function() {<|fim▁hole|> audio_element.play(); }; return audio_element; } } audio1 = pxS(AUDIO_FILE); })();<|fim▁end|>
audio_element.pause(); audio_element.currentTime = 0;
<|file_name|>app.routes.js<|end_file_name|><|fim▁begin|>/** * Created by josip on 20.1.2017.. */ angular.module('mainModule').config(function($routeProvider, $locationProvider){ $routeProvider .when('/', { templateUrl: '/home/home.view.html', controller: 'homeCtrl', controllerAs: 'vm' }) .when('/register', { templateUrl: '/register/register.view.html', controller: 'registerCtrl', controllerAs: 'vm' }) .when('/login', { templateUrl: '/login/login.view.html', controller: 'loginCtrl', controllerAs: 'vm' }) .when('/profile', { templateUrl: '/profile/profile.view.html', controller: 'profileCtrl', controllerAs: 'vm' }) .when('/forgot-password', { templateUrl: '/forgot-password/forgot.password.view.html', controller: 'forgotPassCtrl', controllerAs: 'vm' }) .when('/measurement',{ templateUrl:'/measurement/measurement.view.html', controller: 'measurementCtrl', controllerAs: 'vm' }) .otherwise({redirectTo: '/'}); <|fim▁hole|><|fim▁end|>
// use the HTML5 History API $locationProvider.html5Mode(true); });
<|file_name|>WalkableList.ts<|end_file_name|><|fim▁begin|>///<reference path='../definitions/JQuery.d.ts'/> ///<reference path='GetNextFreeId.ts'/> ///<reference path='IEntity.ts'/> ///<reference path='IWalkableList.ts'/> ///<reference path='IObservableRepository.ts'/> module VjsPluginComponents { //This Walkable list implementation includes everything stored in the underlying repository. export class WalkableList implements IWalkableList { _objects: IEntity[]; _index: number; _repository: IObservableRepository; _sortFunction: (a, b) => number; _filterFunction: (a: any) => boolean; constructor(sortFunction: (a, b) => number, filterFunction: (a: any) => boolean, repository: IObservableRepository) { this._index = 0; this._objects = []; this._repository = repository; this._sortFunction = sortFunction; this._filterFunction = filterFunction; this.updateLocalArray(); this._repository.on("create", () => { this.updateLocalArray(); }); this._repository.on("remove", () => { this.updateLocalArray(); }); } updateLocalArray() { this._objects = jQuery.grep(this._repository.toList(),this._filterFunction).sort(this._sortFunction); } getCurrent() { return this._objects[this._index]; } moveNext() { this._index++; } hasNext() { return (this._index < this._objects.length) } isFinished() { return (this._index >= this._objects.length) } /** * resets the list to the first point upon which the condition is met. * @param {function(object:any) => number} condition * @param {(args) => void} handler * @param {string} boundaryType describes when the event should be triggered. * Valid inputs are: "point","approach" and "depart". "point" * triggers whenever the time is played. "approach" only * triggers when the time up to that point is played. * "depart" only triggers when the time after the point is * played. * @param {integer} maxCallCount */ reset(condition: (object) => boolean) { this._index = 0; while (this.hasNext() && !condition(this._objects[this._index])) { this.moveNext(); } } add(object: IEntity) { return this._repository.create(object); } removeCurrent() { this._repository.remove(this._objects[this._index].id) } update(object: IEntity) { this._repository.update(object); }<|fim▁hole|> } /* Look into using this instead of general updates if performance is slow. As always, code optization later. private insertSingleEvent(event: ISinglePointEvent) { this._handlersToTrigger = this.insert(event, this._handlersToTrigger, (a, b) => { //A appears after B when positive if ((a.time - b.time) == 0) { return this.getBoundaryOrdering(a.boundaryType) - this.getBoundaryOrdering(b.boundaryType); } else { return a.time - b.time; } }); } private getBoundaryOrdering(boundaryType: string): number { switch(boundaryType.toLowerCase()) { case "approach": return 0; case "point": return 1; case "depart": return 2; default: throw Error("Invalid boundary type entered: " + boundaryType); } } private insert(element, array, comparer) { array.splice(this.locationOf(element, array, comparer), 0, element); return array; } private locationOf(element, array, comparer, start?: number = 0, end?: number): number { if (typeof (end) === 'undefined') { end = array.length - 1; } var pivot: number = Math.floor(start + (end - start) / 2); if (!(array[pivot]) || comparer(element, array[pivot]) == 0) return pivot; if (comparer(element, array[pivot]) > 0) { if (pivot == end) return (pivot + 1); return this.locationOf(element, array, comparer, pivot + 1, end); } else { if (pivot == start) return (pivot); return this.locationOf(element, array, comparer, start, pivot - 1); } } */ } }<|fim▁end|>
remove(id: number) { return this._repository.remove(id);
<|file_name|>monitors_util.py<|end_file_name|><|fim▁begin|># Shared utility functions across monitors scripts. import fcntl, os, re, select, signal, subprocess, sys, time TERM_MSG = 'Console connection unexpectedly lost. Terminating monitor.' class Error(Exception): pass class InvalidTimestampFormat(Error): pass def prepend_timestamp(msg, format): """Prepend timestamp to a message in a standard way. Args: msg: str; Message to prepend timestamp to. format: str or callable; Either format string that can be passed to time.strftime or a callable that will generate the timestamp string. Returns: str; 'timestamp\tmsg' """ if type(format) is str: timestamp = time.strftime(format, time.localtime()) elif callable(format): timestamp = str(format()) else: raise InvalidTimestampFormat return '%s\t%s' % (timestamp, msg) def write_logline(logfile, msg, timestamp_format=None): """Write msg, possibly prepended with a timestamp, as a terminated line. Args: logfile: file; File object to .write() msg to. msg: str; Message to write. timestamp_format: str or callable; If specified will be passed into prepend_timestamp along with msg. """ msg = msg.rstrip('\n') if timestamp_format: msg = prepend_timestamp(msg, timestamp_format) logfile.write(msg + '\n') def make_alert(warnfile, msg_type, msg_template, timestamp_format=None): """Create an alert generation function that writes to warnfile. Args: warnfile: file; File object to write msg's to. msg_type: str; String describing the message type msg_template: str; String template that function params are passed through. timestamp_format: str or callable; If specified will be passed into prepend_timestamp along with msg.<|fim▁hole|> """ if timestamp_format is None: timestamp_format = lambda: int(time.time()) def alert(*params): formatted_msg = msg_type + "\t" + msg_template % params timestamped_msg = prepend_timestamp(formatted_msg, timestamp_format) print >> warnfile, timestamped_msg return alert def build_alert_hooks(patterns_file, warnfile): """Parse data in patterns file and transform into alert_hook list. Args: patterns_file: file; File to read alert pattern definitions from. warnfile: file; File to configure alert function to write warning to. Returns: list; Regex to alert function mapping. [(regex, alert_function), ...] """ pattern_lines = patterns_file.readlines() # expected pattern format: # <msgtype> <newline> <regex> <newline> <alert> <newline> <newline> # msgtype = a string categorizing the type of the message - used for # enabling/disabling specific categories of warnings # regex = a python regular expression # alert = a string describing the alert message # if the regex matches the line, this displayed warning will # be the result of (alert % match.groups()) patterns = zip(pattern_lines[0::4], pattern_lines[1::4], pattern_lines[2::4]) # assert that the patterns are separated by empty lines if sum(len(line.strip()) for line in pattern_lines[3::4]) > 0: raise ValueError('warning patterns are not separated by blank lines') hooks = [] for msgtype, regex, alert in patterns: regex = re.compile(regex.rstrip('\n')) alert_function = make_alert(warnfile, msgtype.rstrip('\n'), alert.rstrip('\n')) hooks.append((regex, alert_function)) return hooks def process_input( input, logfile, log_timestamp_format=None, alert_hooks=()): """Continuously read lines from input stream and: - Write them to log, possibly prefixed by timestamp. - Watch for alert patterns. Args: input: file; Stream to read from. logfile: file; Log file to write to log_timestamp_format: str; Format to use for timestamping entries. No timestamp is added if None. alert_hooks: list; Generated from build_alert_hooks. [(regex, alert_function), ...] """ while True: line = input.readline() if len(line) == 0: # this should only happen if the remote console unexpectedly # goes away. terminate this process so that we don't spin # forever doing 0-length reads off of input write_logline(logfile, TERM_MSG, log_timestamp_format) break if line == '\n': # If it's just an empty line we discard and continue. continue write_logline(logfile, line, log_timestamp_format) for regex, callback in alert_hooks: match = re.match(regex, line.strip()) if match: callback(*match.groups()) def lookup_lastlines(lastlines_dirpath, path): """Retrieve last lines seen for path. Open corresponding lastline file for path If there isn't one or isn't a match return None Args: lastlines_dirpath: str; Dirpath to store lastlines files to. path: str; Filepath to source file that lastlines came from. Returns: str; Last lines seen if they exist - Or - None; Otherwise """ underscored = path.replace('/', '_') try: lastlines_file = open(os.path.join(lastlines_dirpath, underscored)) except (OSError, IOError): return lastlines = lastlines_file.read() lastlines_file.close() os.remove(lastlines_file.name) if not lastlines: return try: target_file = open(path) except (OSError, IOError): return # Load it all in for now target_data = target_file.read() target_file.close() # Get start loc in the target_data string, scanning from right loc = target_data.rfind(lastlines) if loc == -1: return # Then translate this into a reverse line number # (count newlines that occur afterward) reverse_lineno = target_data.count('\n', loc + len(lastlines)) return reverse_lineno def write_lastlines_file(lastlines_dirpath, path, data): """Write data to lastlines file for path. Args: lastlines_dirpath: str; Dirpath to store lastlines files to. path: str; Filepath to source file that data comes from. data: str; Returns: str; Filepath that lastline data was written to. """ underscored = path.replace('/', '_') dest_path = os.path.join(lastlines_dirpath, underscored) open(dest_path, 'w').write(data) return dest_path def nonblocking(pipe): """Set python file object to nonblocking mode. This allows us to take advantage of pipe.read() where we don't have to specify a buflen. Cuts down on a few lines we'd have to maintain. Args: pipe: file; File object to modify Returns: pipe """ flags = fcntl.fcntl(pipe, fcntl.F_GETFL) fcntl.fcntl(pipe, fcntl.F_SETFL, flags| os.O_NONBLOCK) return pipe def launch_tails(follow_paths, lastlines_dirpath=None): """Launch a tail process for each follow_path. Args: follow_paths: list; lastlines_dirpath: str; Returns: tuple; (procs, pipes) or ({path: subprocess.Popen, ...}, {file: path, ...}) """ if lastlines_dirpath and not os.path.exists(lastlines_dirpath): os.makedirs(lastlines_dirpath) tail_cmd = ('/usr/bin/tail', '--retry', '--follow=name') procs = {} # path -> tail_proc pipes = {} # tail_proc.stdout -> path for path in follow_paths: cmd = list(tail_cmd) if lastlines_dirpath: reverse_lineno = lookup_lastlines(lastlines_dirpath, path) if reverse_lineno is None: reverse_lineno = 1 cmd.append('--lines=%d' % reverse_lineno) cmd.append(path) tail_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) procs[path] = tail_proc pipes[nonblocking(tail_proc.stdout)] = path return procs, pipes def poll_tail_pipes(pipes, lastlines_dirpath=None, waitsecs=5): """Wait on tail pipes for new data for waitsecs, return any new lines. Args: pipes: dict; {subprocess.Popen: follow_path, ...} lastlines_dirpath: str; Path to write lastlines to. waitsecs: int; Timeout to pass to select Returns: tuple; (lines, bad_pipes) or ([line, ...], [subprocess.Popen, ...]) """ lines = [] bad_pipes = [] # Block until at least one is ready to read or waitsecs elapses ready, _, _ = select.select(pipes.keys(), (), (), waitsecs) for fi in ready: path = pipes[fi] data = fi.read() if len(data) == 0: # If no data, process is probably dead, add to bad_pipes bad_pipes.append(fi) continue if lastlines_dirpath: # Overwrite the lastlines file for this source path # Probably just want to write the last 1-3 lines. write_lastlines_file(lastlines_dirpath, path, data) for line in data.splitlines(): lines.append('[%s]\t%s\n' % (path, line)) return lines, bad_pipes def snuff(subprocs): """Helper for killing off remaining live subprocesses. Args: subprocs: list; [subprocess.Popen, ...] """ for proc in subprocs: if proc.poll() is None: os.kill(proc.pid, signal.SIGKILL) proc.wait() def follow_files(follow_paths, outstream, lastlines_dirpath=None, waitsecs=5): """Launch tail on a set of files and merge their output into outstream. Args: follow_paths: list; Local paths to launch tail on. outstream: file; Output stream to write aggregated lines to. lastlines_dirpath: Local dirpath to record last lines seen in. waitsecs: int; Timeout for poll_tail_pipes. """ procs, pipes = launch_tails(follow_paths, lastlines_dirpath) while pipes: lines, bad_pipes = poll_tail_pipes(pipes, lastlines_dirpath, waitsecs) for bad in bad_pipes: pipes.pop(bad) try: outstream.writelines(['\n'] + lines) outstream.flush() except (IOError, OSError), e: # Something is wrong. Stop looping. break snuff(procs.values())<|fim▁end|>
Returns: function with a signature of (*params); The format for a warning used here is: %(timestamp)d\t%(msg_type)s\t%(status)s\n
<|file_name|>zsys_openbsd.go<|end_file_name|><|fim▁begin|>// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_openbsd.go package ipv4 <|fim▁hole|>const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x1e sysIP_RECVTTL = 0x1f sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysSizeofIPMreq = 0x8 ) type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ }<|fim▁end|>
<|file_name|>plastiqqcolormap.cpp<|end_file_name|><|fim▁begin|>#include "plastiqmethod.h" #include "plastiqqcolormap.h" #include <QColormap> #include <QColor> QHash<QByteArray, PlastiQMethod> PlastiQQColormap::plastiqConstructors = { { "QColormap(QColormap&)", { "QColormap", "QColormap&", "QColormap*", 0, PlastiQMethod::Public, PlastiQMethod::Constructor } }, }; QHash<QByteArray, PlastiQMethod> PlastiQQColormap::plastiqMethods = { { "colorAt(long)", { "colorAt", "uint", "const QColor", 0, PlastiQMethod::Public, PlastiQMethod::Method } }, { "depth()", { "depth", "", "int", 1, PlastiQMethod::Public, PlastiQMethod::Method } }, { "mode()", { "mode", "", "Mode", 2, PlastiQMethod::Public, PlastiQMethod::Method } }, { "pixel(QColor&)", { "pixel", "QColor&", "uint", 3, PlastiQMethod::Public, PlastiQMethod::Method } }, { "size()", { "size", "", "int", 4, PlastiQMethod::Public, PlastiQMethod::Method } }, { "instance()", { "instance", "", "QColormap", 5, PlastiQMethod::StaticPublic, PlastiQMethod::Method } }, { "instance(int)", { "instance", "int", "QColormap", 6, PlastiQMethod::StaticPublic, PlastiQMethod::Method } }, }; QHash<QByteArray, PlastiQMethod> PlastiQQColormap::plastiqSignals = { }; QHash<QByteArray, PlastiQProperty> PlastiQQColormap::plastiqProperties = { }; QHash<QByteArray, long> PlastiQQColormap::plastiqConstants = { /* QColormap::Mode */ { "Direct", QColormap::Direct }, { "Indexed", QColormap::Indexed }, { "Gray", QColormap::Gray }, }; QVector<PlastiQMetaObject*> PlastiQQColormap::plastiqInherits = { }; const PlastiQ::ObjectType PlastiQQColormap::plastiq_static_objectType = PlastiQ::IsQtObject; PlastiQMetaObject PlastiQQColormap::plastiq_static_metaObject = { { Q_NULLPTR, &plastiqInherits, "QColormap", &plastiq_static_objectType, &plastiqConstructors, &plastiqMethods, &plastiqSignals, &plastiqProperties, &plastiqConstants, plastiq_static_metacall } }; const PlastiQMetaObject *PlastiQQColormap::plastiq_metaObject() const { return &plastiq_static_metaObject; } void PlastiQQColormap::plastiq_static_metacall(PlastiQObject *object, PlastiQMetaObject::Call call, int id, const PMOGStack &stack) { if(call == PlastiQMetaObject::CreateInstance) { QColormap *o = Q_NULLPTR; switch(id) { case 0: o = new QColormap((*reinterpret_cast< QColormap(*) >(stack[1].s_voidp))); break; default: ; } /*%UPDATEWRAPPER%*/ PlastiQQColormap *p = new PlastiQQColormap(); p->plastiq_setData(reinterpret_cast<void*>(o), p); PlastiQObject *po = static_cast<PlastiQObject*>(p); *reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = po; } else if(call == PlastiQMetaObject::CreateDataInstance) { PlastiQQColormap *p = new PlastiQQColormap(); p->plastiq_setData(stack[1].s_voidp, p); *reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = p; } else if(call == PlastiQMetaObject::InvokeMethod || call == PlastiQMetaObject::InvokeStaticMember) { if(id >= 7) { id -= 7; return; } bool sc = call == PlastiQMetaObject::InvokeStaticMember; bool isWrapper = sc ? false : object->isWrapper(); QColormap *o = sc ? Q_NULLPTR : reinterpret_cast<QColormap*>(object->plastiq_data()); switch(id) { case 0: { /* COPY OBJECT */ QColor *_r = new QColor(o->colorAt(stack[1].s_long)); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QColor"; stack[0].type = PlastiQ::QtObject; } break; case 1: { int _r = o->depth(); stack[0].s_int = _r; stack[0].type = PlastiQ::Int; } break; case 2: { qint64 _r = o->mode(); // HACK for Mode stack[0].s_int64 = _r; stack[0].type = PlastiQ::Enum; } break; case 3: { long _r = o->pixel((*reinterpret_cast< QColor(*) >(stack[1].s_voidp))); stack[0].s_long = _r; stack[0].type = PlastiQ::Long; } break; case 4: { int _r = o->size(); stack[0].s_int = _r; stack[0].type = PlastiQ::Int; } break; case 5: { /* COPY OBJECT */ QColormap *_r = sc ? new QColormap(QColormap::instance()) : new QColormap(o->instance()); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QColormap"; stack[0].type = PlastiQ::QtObject; } break; case 6: { /* COPY OBJECT */ QColormap *_r = sc ? new QColormap(QColormap::instance(stack[1].s_int)) : new QColormap(o->instance(stack[1].s_int)); reinterpret_cast<void*>(stack[0].s_voidp) = _r; stack[0].name = "QColormap"; stack[0].type = PlastiQ::QtObject; } break; default: ; } } else if(call == PlastiQMetaObject::ToQObject) { } else if(call == PlastiQMetaObject::HaveParent) { stack[0].s_bool = false; } else if(call == PlastiQMetaObject::DownCast) {<|fim▁hole|> stack[0].name = "Q_NULLPTR"; } } PlastiQQColormap::~PlastiQQColormap() { QColormap* o = reinterpret_cast<QColormap*>(plastiq_data()); if(o != Q_NULLPTR) { delete o; } o = Q_NULLPTR; plastiq_setData(Q_NULLPTR, Q_NULLPTR); }<|fim▁end|>
QByteArray className = stack[1].s_bytearray; QColormap *o = reinterpret_cast<QColormap*>(object->plastiq_data()); stack[0].s_voidp = Q_NULLPTR;
<|file_name|>slice_visualization_ui.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'slice_visualization.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_slice_visualization_gui(object): def setupUi(self, slice_visualization_gui): slice_visualization_gui.setObjectName("slice_visualization_gui") slice_visualization_gui.resize(800, 600) self.centralwidget = QtWidgets.QWidget(slice_visualization_gui) self.centralwidget.setObjectName("centralwidget") slice_visualization_gui.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(slice_visualization_gui) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))<|fim▁hole|> self.menubar.setObjectName("menubar") slice_visualization_gui.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(slice_visualization_gui) self.statusbar.setObjectName("statusbar") slice_visualization_gui.setStatusBar(self.statusbar) self.retranslateUi(slice_visualization_gui) QtCore.QMetaObject.connectSlotsByName(slice_visualization_gui) def retranslateUi(self, slice_visualization_gui): _translate = QtCore.QCoreApplication.translate slice_visualization_gui.setWindowTitle(_translate("slice_visualization_gui", "MainWindow"))<|fim▁end|>
<|file_name|>tfchart_datacontroler_simple.ts<|end_file_name|><|fim▁begin|>import { TFChartRange, TFChartRangeMake, TFChartIntersectionRange, TFChartEqualRanges, TFChartRangeMax, TFChartUnionRange, TFChartRangeInvalid } from '../tfchart_utils' import { TFChartDataController, TFChartDataRequestType, TFChartDataAvailability, DataSubscription, TFChartDataOperationType, DataOperation } from '../tfchart_datacontroller' import { TFChartDataSupplier, RequestResults } from '../tfchart_datasupplier' import { TFChartDataBuffer } from './tfchart_databuffer' import { TFChartDataType } from '../series/tfchart_series' import { Subject } from 'rxjs/Subject' export class TFChartSimpleDataController<T extends TFChartDataType> extends TFChartDataController { private period: number = -1; private data: TFChartDataBuffer<T> = new TFChartDataBuffer<T>(); private pending_request_queue = []; private availableDataRange: TFChartRange = TFChartRangeInvalid(); private observers: Subject<DataOperation>; private requestInProgress: boolean = false; private requestBacklog: TFChartRange[] = []; public constructor(private dataSupplier: TFChartDataSupplier<T>) { super(); this.observers = new Subject(); } public setPeriod(period: number) { this.period = period; // we need to clear our current cache and requre a re-request this.data.clear(); this.dataSupplier.getAvailableRange(period) .then((range: TFChartRange) => this.availableDataRange = range) .then(() => console.log("Available range is: " + this.availableDataRange)) .then(() => this.dataSupplier.fetchInitialDataRange(TFChartRangeMake(this.availableDataRange.position, period * 40), period) .then((initialRange: TFChartRange) => { console.log("Requesting initial range of: " + initialRange); return initialRange; }) .then((initialRange: TFChartRange) => this.requestData(initialRange)) ); } public subscribe(subscriber: DataSubscription) { this.observers.subscribe( subscriber, function(err) { console.log("Error: " + err); }, function() { console.log("Completed"); } ) } public availableRange(): TFChartRange { return this.availableDataRange; } public requestData(range: TFChartRange) { if (this.requestInProgress) { // console.log("Request already in progress - queuing"); this.requestBacklog.push(range); } else { // console.log("think we want: " + range + " currently have " + this.data.getRange() + " for period: " + this.period); // we don't want any gaps in our cached data... range = TFChartIntersectionRange(range, this.availableDataRange); if (range.span == 0) { throw new Error("Request out of available range [we have " + this.availableDataRange + " but requested " + range + "]"); } else { console.log("Requesting range of: " + range); } let operation: TFChartDataRequestType; if (this.data.getRange() !== TFChartRangeInvalid()) { if (range.position < this.data.getRange().position) { operation = TFChartDataRequestType.PREPEND; range = TFChartUnionRange(range, this.data.getRange()); range.span -= this.data.getRange().span; } else if (TFChartRangeMax(range) > TFChartRangeMax(this.data.getRange())) { operation = TFChartDataRequestType.APPEND; let currentEnd = TFChartRangeMax(this.data.getRange()); range = TFChartRangeMake(currentEnd, TFChartRangeMax(range) - currentEnd); } else { console.log("We already have the requested data"); throw new Error("invalid data request " + range); } } else { operation = TFChartDataRequestType.APPEND; } if (range.span > 0) { this.requestInProgress = true; this.dataSupplier.fetchPaginationData(range, this.period) .then((results: RequestResults<T>) => { if (results.success == false) { console.log("Failure returned from fetchPaginationData in dataSupplier"); } else { switch (operation) { case TFChartDataRequestType.PREPEND: this.prependData(results.data, results.range); break; case TFChartDataRequestType.APPEND: this.appendData(results.data, results.range); break; } } }) .catch((err) => { console.log(err + " for " + operation); }) .then(() => { this.requestInProgress = false; this.processPendingRequestQueue(); }); } } } public getCachedRange(): TFChartRange { return this.data.getRange(); } public getCachedData<T>(): any[] { return this.data.getData(); } private prependData(data: T[], range: TFChartRange): void { this.data.prependData(data, range); this.observers.next({ method: TFChartDataOperationType.ADD, count: data.length, type: TFChartDataRequestType.PREPEND });<|fim▁hole|> } private appendData(data: T[], range: TFChartRange): void { this.data.appendData(data, range); this.observers.next({ method: TFChartDataOperationType.ADD, count: data.length, type: TFChartDataRequestType.APPEND }); } // private removeCurrentDataFromRange(range: TFChartRange) { // if (range !== null) { // // we need to make sure we don't request the same data // var intersection = TFChartIntersectionRange(this.dataRange, range); // if (intersection.span > 0) { // something intersects // if (TFChartEqualRanges(intersection, range)) { // // we already have this pending data // return null; // } else { // // we need to update 'range' // if (range.position == intersection.position) { // // the beginning over laps // range.position += intersection.span + this.period; // range.span -= intersection.span; // } else if (TFChartRangeMax(range) == TFChartRangeMax(intersection)) { // // the end over laps // range.span = intersection.position - range.position - this.period; // } // } // } // } // return range; // } private processPendingRequestQueue() { if (this.requestBacklog.length == 0) { return; } else { let resultingRange: TFChartRange; if (this.requestBacklog.length >= 2) { resultingRange = this.requestBacklog[0]; for (let r of this.requestBacklog) { resultingRange = TFChartUnionRange(resultingRange, r); } } else { resultingRange = this.requestBacklog[0]; } // console.log("Processing backlog of " + this.requestBacklog.length + " requests: " + resultingRange); this.requestBacklog = []; let results: TFChartRange[] = []; let overlap = TFChartIntersectionRange(resultingRange, this.data.getRange()); if (overlap.span != 0) { if (resultingRange.position < overlap.position) { results.push(TFChartRangeMake(resultingRange.position, resultingRange.position - overlap.position)); } if (TFChartRangeMax(resultingRange) > TFChartRangeMax(overlap)) { results.push(TFChartRangeMake(TFChartRangeMax(overlap), TFChartRangeMax(resultingRange) - TFChartRangeMax(overlap))); } } else { results.push(resultingRange); } for (let r of results) { this.requestData(r); } } } }<|fim▁end|>