file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
UserRouter.js
const _ = require("lodash"); const Qs = require("qs"); const Op = require("sequelize").Op; function
(app) { const { models } = app.data.sequelize; const api = { pathname: "/users", middlewares: [ app.server.auth.isAuthenticated, app.server.auth.isAuthorized ], ops: { getAll: { pathname: "/", method: "get", handler: async context => { const filte...
UserRouter
identifier_name
UserRouter.js
const _ = require("lodash"); const Qs = require("qs"); const Op = require("sequelize").Op; function UserRouter(app) { const { models } = app.data.sequelize; const api = { pathname: "/users", middlewares: [ app.server.auth.isAuthenticated, app.server.auth.isAuthorized ], ops: { ge...
} } } }; app.server.createRouter(api); return {}; } module.exports = UserRouter;
{ context.body = user.get(); context.status = 200; }
conditional_block
UserRouter.js
const _ = require("lodash"); const Qs = require("qs"); const Op = require("sequelize").Op; function UserRouter(app)
const result = await models.User.findAndCountAll({ limit: filter.limit, order: [["createdAt", filter.order]], offset: filter.offset, where: filter.search && { [Op.or]: [ { username: { [Op.like]: `%${filter.search}%` } }, ...
{ const { models } = app.data.sequelize; const api = { pathname: "/users", middlewares: [ app.server.auth.isAuthenticated, app.server.auth.isAuthorized ], ops: { getAll: { pathname: "/", method: "get", handler: async context => { const filter = Qs...
identifier_body
recruiters.js
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. var onReady = function() { $('table.table a#ping').on('click', function(event) { var recruiterId = $(this).closest('tr.recruiter-id').attr('id').split('-')[1]; c...
}); // this is the event that is fired when a user clicks on a suggestion $(searchSelector).bind('typeahead:selected', function(event, datum, name) { //console.debug('Suggestion clicked:', event, datum, name); window.location.href = '/recruiters/' + datum.id; }); // Modal for blacklist button $('d...
// initialize typeahead widget and hook it up to bloodhound engine // #typeahead is just a text input $(searchSelector).typeahead(null, { displayKey: 'email', source: bloodhound.ttAdapter()
random_line_split
test_views.py
# -*- coding:utf-8 -*- import vcr from django.conf import settings from django.test import TestCase from django.urls import reverse_lazy from estacaometeorologica.core.models import EstacaoMeteorologica from estacaometeorologica.core.api_morangos import get_data class IndexViewTestCase(TestCase): @vcr.use_cas...
@vcr.use_cassette(settings.BASE_DIR + '/estacaometeorologica/core/tests/cassettes/morangos.yaml') def test_get(self): response = self.client.get(reverse_lazy('estacao-meteorologica'), HTTP_X_REQUESTED_WITH='XMLHttpRequest') content = response.json() self.assertTrue(content['temperature']) ...
identifier_body
test_views.py
# -*- coding:utf-8 -*- import vcr from django.conf import settings from django.test import TestCase from django.urls import reverse_lazy from estacaometeorologica.core.models import EstacaoMeteorologica from estacaometeorologica.core.api_morangos import get_data class IndexViewTestCase(TestCase): @vcr.use_cas...
self.assertTrue(response.context_data.get('humidity')) self.assertTrue(response.context_data.get('date')) class EstacaoMeteorologicaViewTestCase(TestCase): @vcr.use_cassette(settings.BASE_DIR + '/estacaometeorologica/core/tests/cassettes/morangos.yaml') def test_get(self): response = ...
self.assertTrue(response.context_data.get('temperature'))
random_line_split
test_views.py
# -*- coding:utf-8 -*- import vcr from django.conf import settings from django.test import TestCase from django.urls import reverse_lazy from estacaometeorologica.core.models import EstacaoMeteorologica from estacaometeorologica.core.api_morangos import get_data class IndexViewTestCase(TestCase): @vcr.use_cas...
(self): response = self.client.get(reverse_lazy('estacao-meteorologica'), HTTP_X_REQUESTED_WITH='XMLHttpRequest') content = response.json() self.assertTrue(content['temperature']) self.assertTrue(content['humidity']) self.assertTrue(content['date'])
test_get
identifier_name
payments.rs
use std::error::Error; use std::fmt; use std::fmt::{Display, Formatter}; use api::ErrorCode; use errors::ToErrorCode; use errors::prelude::*; #[derive(Debug)] pub enum PaymentsError { PluggedMethodError(ErrorCode), UnknownType(String), CommonError(CommonError), IncompatiblePaymentError(String), } imp...
(&self) -> ErrorCode { match *self { PaymentsError::PluggedMethodError(e) => e, PaymentsError::CommonError(ref err) => err.to_error_code(), PaymentsError::UnknownType(ref _str) => ErrorCode::PaymentUnknownMethodError, PaymentsError::IncompatiblePaymentError(ref _s...
to_error_code
identifier_name
payments.rs
use std::error::Error; use std::fmt; use std::fmt::{Display, Formatter}; use api::ErrorCode; use errors::ToErrorCode; use errors::prelude::*; #[derive(Debug)] pub enum PaymentsError { PluggedMethodError(ErrorCode), UnknownType(String), CommonError(CommonError), IncompatiblePaymentError(String), } imp...
} impl Display for PaymentsError { fn fmt(&self, _f: &mut Formatter) -> fmt::Result { match *self { PaymentsError::CommonError(ref err) => err.fmt(_f), PaymentsError::PluggedMethodError(_err_code) => write!(_f, "Plugged method error. Consider the error code."), Payments...
{ match *self { PaymentsError::CommonError(ref err) => err.description(), PaymentsError::UnknownType(ref msg) => msg.as_str(), PaymentsError::PluggedMethodError(_error_code) => "Plugged method error. Consider the error code.", PaymentsError::IncompatiblePaymentErr...
identifier_body
payments.rs
use std::error::Error; use std::fmt; use std::fmt::{Display, Formatter}; use api::ErrorCode; use errors::ToErrorCode; use errors::prelude::*; #[derive(Debug)] pub enum PaymentsError { PluggedMethodError(ErrorCode), UnknownType(String), CommonError(CommonError), IncompatiblePaymentError(String), } imp...
} } impl Display for PaymentsError { fn fmt(&self, _f: &mut Formatter) -> fmt::Result { match *self { PaymentsError::CommonError(ref err) => err.fmt(_f), PaymentsError::PluggedMethodError(_err_code) => write!(_f, "Plugged method error. Consider the error code."), Pay...
PaymentsError::PluggedMethodError(_error_code) => "Plugged method error. Consider the error code.", PaymentsError::IncompatiblePaymentError(ref msg) => msg.as_str(), }
random_line_split
image_reorientation.py
# -*- coding: utf-8 -*- """ Created on Thu Aug 1 16:10:56 2013 @author: vterzopoulos, abrys """ # To ignore numpy errors: # pylint: disable=E1101 import nibabel import numpy from dicom2nifti.image_volume import load, SliceType, ImageVolume def reorient_image(input_image, output_image): """ Change the o...
return new_image
""" Reorganize the data for a 3d nifti """ # Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size # of the array in each direction is the same with the corresponding direction of the input image. new_image = numpy.zeros([image.dimensions[image....
identifier_body
image_reorientation.py
# -*- coding: utf-8 -*- """ Created on Thu Aug 1 16:10:56 2013 @author: vterzopoulos, abrys """ # To ignore numpy errors: # pylint: disable=E1101 import nibabel import numpy from dicom2nifti.image_volume import load, SliceType, ImageVolume def reorient_image(input_image, output_image): """ Change the o...
if image.axial_orientation.y_inverted: new_affine[:, 1] = - new_affine[:, 1] point[image.coronal_orientation.normal_component] = image.dimensions[ image.coronal_orientation.normal_component] - 1 # new_affine[1, 3] = - new_affin...
new_affine[:, 0] = - new_affine[:, 0] point[image.sagittal_orientation.normal_component] = image.dimensions[ image.sagittal_orientation.normal_component] - 1 # new_affine[0, 3] = - new_affine[0, 3]
conditional_block
image_reorientation.py
# -*- coding: utf-8 -*- """ Created on Thu Aug 1 16:10:56 2013 @author: vterzopoulos, abrys """ # To ignore numpy errors: # pylint: disable=E1101 import nibabel import numpy from dicom2nifti.image_volume import load, SliceType, ImageVolume def reorient_image(input_image, output_image): """ Change the o...
new_affine = numpy.eye(4) new_affine[:, 0] = affine[:, image.sagittal_orientation.normal_component] new_affine[:, 1] = affine[:, image.coronal_orientation.normal_component] new_affine[:, 2] = affine[:, image.axial_orientation.normal_component] point = [0, 0, 0, 1] # If the orientation of coord...
# Create new affine header by changing the order of the columns of the input image header # the last column with the origin depends on the origin of the original image, the size and the direction of x,y,z
random_line_split
image_reorientation.py
# -*- coding: utf-8 -*- """ Created on Thu Aug 1 16:10:56 2013 @author: vterzopoulos, abrys """ # To ignore numpy errors: # pylint: disable=E1101 import nibabel import numpy from dicom2nifti.image_volume import load, SliceType, ImageVolume def
(input_image, output_image): """ Change the orientation of the Image data in order to be in LAS space x will represent the coronal plane, y the sagittal and z the axial plane. x increases from Right (R) to Left (L), y from Posterior (P) to Anterior (A) and z from Inferior (I) to Superior (S) :retur...
reorient_image
identifier_name
ua_i_priority_mapping_entry.ts
// ----- this file has been automatically generated - do not edit import { DataType } from "node-opcua-variant" import { UInt32, Byte, UAString } from "node-opcua-basic-types" import { UABaseInterface, UABaseInterface_Base } from "./ua_base_interface" import { UABaseDataVariable } from "./ua_base_data_variable" /** * ...
export interface UAIPriorityMappingEntry extends UABaseInterface, UAIPriorityMappingEntry_Base { }
random_line_split
test_authorization.py
from __future__ import unicode_literals, absolute_import from mock import MagicMock from ....unittest import TestCase from oauthlib.oauth1 import RequestValidator from oauthlib.oauth1.rfc5849 import errors from oauthlib.oauth1.rfc5849.endpoints import AuthorizationEndpoint class ResourceEndpointTest(TestCase): ...
self.uri, realms=['bar']) def test_create_authorization_response(self): self.validator.get_redirect_uri.return_value = 'https://c.b/cb' h, b, s = self.endpoint.create_authorization_response(self.uri) self.assertEqual(s, 302) self.assertIn('Location', ...
def test_verify_realms(self): self.validator.verify_realms.return_value = False self.assertRaises(errors.InvalidRequestError, self.endpoint.create_authorization_response,
random_line_split
test_authorization.py
from __future__ import unicode_literals, absolute_import from mock import MagicMock from ....unittest import TestCase from oauthlib.oauth1 import RequestValidator from oauthlib.oauth1.rfc5849 import errors from oauthlib.oauth1.rfc5849.endpoints import AuthorizationEndpoint class ResourceEndpointTest(TestCase): ...
(self): self.validator = MagicMock(wraps=RequestValidator()) self.validator.verify_request_token.return_value = True self.validator.verify_realms.return_value = True self.validator.get_realms.return_value = ['test'] self.validator.save_verifier = MagicMock() self.endpoint...
setUp
identifier_name
test_authorization.py
from __future__ import unicode_literals, absolute_import from mock import MagicMock from ....unittest import TestCase from oauthlib.oauth1 import RequestValidator from oauthlib.oauth1.rfc5849 import errors from oauthlib.oauth1.rfc5849.endpoints import AuthorizationEndpoint class ResourceEndpointTest(TestCase): ...
def test_verify_realms(self): self.validator.verify_realms.return_value = False self.assertRaises(errors.InvalidRequestError, self.endpoint.create_authorization_response, self.uri, realms=['bar']) def test_create_authorization_response(self): ...
self.validator.verify_request_token.return_value = False self.assertRaises(errors.InvalidClientError, self.endpoint.get_realms_and_credentials, self.uri) self.assertRaises(errors.InvalidClientError, self.endpoint.create_authorization_response, self.uri)
identifier_body
gamepadbuttonlist.rs
/* 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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding; use crate::dom::bindings::codegen::Binding...
}
{ self.Item(index) }
identifier_body
gamepadbuttonlist.rs
/* 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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding; use crate::dom::bindings::codegen::Binding...
self.list.len() as u32 } // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn Item(&self, index: u32) -> Option<DomRoot<GamepadButton>> { self.list .get(index as usize) .map(|button| DomRoot::from_ref(&**button)) } // https://w3c.github.io/gamepad/#dom-g...
impl GamepadButtonListMethods for GamepadButtonList { // https://w3c.github.io/gamepad/#dom-gamepad-buttons fn Length(&self) -> u32 {
random_line_split
gamepadbuttonlist.rs
/* 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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding; use crate::dom::bindings::codegen::Binding...
(&self, index: u32) -> Option<DomRoot<GamepadButton>> { self.Item(index) } }
IndexedGetter
identifier_name
uri.ts
import { Reader } from '../reader'; export class
extends Reader { public uri: string; constructor(uri: string) { super(); this.uri = uri; } public async open() { return fetch(this.uri, { method: 'HEAD' }).then((response) => { if (!response.ok) { throw new Error('Could not open URI'); } const length = response...
UriReader
identifier_name
uri.ts
import { Reader } from '../reader'; export class UriReader extends Reader { public uri: string; constructor(uri: string) { super(); this.uri = uri; } public async open() { return fetch(this.uri, { method: 'HEAD' }).then((response) => { if (!response.ok) { throw new Error('...
} public close() { return Promise.resolve(); } public reset() { return; } public async read(length: number, position: number) { return fetch(this.uri, { method: 'GET', headers: { Range: `bytes=${position}-${position + length - 1}` } }).then((response) => { ...
random_line_split
uri.ts
import { Reader } from '../reader'; export class UriReader extends Reader { public uri: string; constructor(uri: string) { super(); this.uri = uri; } public async open() { return fetch(this.uri, { method: 'HEAD' }).then((response) => { if (!response.ok) { throw new Error('...
}); } public close() { return Promise.resolve(); } public reset() { return; } public async read(length: number, position: number) { return fetch(this.uri, { method: 'GET', headers: { Range: `bytes=${position}-${position + length - 1}` } }).then((response) =>...
{ this.size = parseInt(length, 10); }
conditional_block
uri.ts
import { Reader } from '../reader'; export class UriReader extends Reader { public uri: string; constructor(uri: string) { super(); this.uri = uri; } public async open()
public close() { return Promise.resolve(); } public reset() { return; } public async read(length: number, position: number) { return fetch(this.uri, { method: 'GET', headers: { Range: `bytes=${position}-${position + length - 1}` } }).then((response) => { if ...
{ return fetch(this.uri, { method: 'HEAD' }).then((response) => { if (!response.ok) { throw new Error('Could not open URI'); } const length = response.headers.get('Content-Length'); if (length !== null) { this.size = parseInt(length, 10); } }); }
identifier_body
challenge19_20.rs
use crate::errors::*; use crate::set1::break_multibyte_xor_for_keysize; use aes::random_block; use std::path::PathBuf; use aes::{Aes128, MODE}; use serialize::from_base64_lines; pub enum Exercise { _19, _20, } struct
{ key: Vec<u8>, exercise: Exercise, } impl Encrypter { pub fn new(exercise: Exercise) -> Self { Encrypter { key: random_block(), exercise, } } pub fn get_ciphertexts(&self) -> Result<Vec<Vec<u8>>> { let mut input_file_path = PathBuf::from("data"); ...
Encrypter
identifier_name
challenge19_20.rs
use crate::errors::*; use crate::set1::break_multibyte_xor_for_keysize; use aes::random_block; use std::path::PathBuf; use aes::{Aes128, MODE}; use serialize::from_base64_lines;
pub enum Exercise { _19, _20, } struct Encrypter { key: Vec<u8>, exercise: Exercise, } impl Encrypter { pub fn new(exercise: Exercise) -> Self { Encrypter { key: random_block(), exercise, } } pub fn get_ciphertexts(&self) -> Result<Vec<Vec<u8>>> { ...
random_line_split
challenge19_20.rs
use crate::errors::*; use crate::set1::break_multibyte_xor_for_keysize; use aes::random_block; use std::path::PathBuf; use aes::{Aes128, MODE}; use serialize::from_base64_lines; pub enum Exercise { _19, _20, } struct Encrypter { key: Vec<u8>, exercise: Exercise, } impl Encrypter { pub fn new(exe...
{ let encrypter = Encrypter::new(exercise); let ciphertexts = encrypter.get_ciphertexts()?; let size = ciphertexts.iter().map(|c| c.len()).min().unwrap(); // unwrap is ok let ciphertext: Vec<u8> = ciphertexts .iter() .flat_map(|ciphertext| &ciphertext[..size]) .cloned() ....
identifier_body
playback.py
import logging, logging.handlers import sys logging.handlers.HTTPHandler('','',method='GET') logger = logging.getLogger('simple_example') # http_handler = logging.handlers.HTTPHandler('127.0.0.1:9022', '/event', method='GET') http_handler = logging.handlers.HTTPHandler('127.0.0.1:9999', '/httpevent', method='GET') ...
## For reference, the exert of the relevant Python logger # import errno, logging, socket, os, pickle, struct, time, re # from codecs import BOM_UTF8 # from stat import ST_DEV, ST_INO, ST_MTIME # import queue # try: # import threading # except ImportError: #pragma: no cover # threading = None # import htt...
line = f.readline() print line logger.critical(line)
conditional_block
playback.py
import logging, logging.handlers import sys logging.handlers.HTTPHandler('','',method='GET') logger = logging.getLogger('simple_example') # http_handler = logging.handlers.HTTPHandler('127.0.0.1:9022', '/event', method='GET') http_handler = logging.handlers.HTTPHandler('127.0.0.1:9999', '/httpevent', method='GET') ...
## For reference, the exert of the relevant Python logger # import errno, logging, socket, os, pickle, struct, time, re # from codecs import BOM_UTF8 # from stat import ST_DEV, ST_INO, ST_MTIME # import queue # try: # import threading # except ImportError: #pragma: no cover # threading = None # import http.c...
print line logger.critical(line)
random_line_split
index.d.ts
// Type definitions for gulp-filter v3.0.1 // Project: https://github.com/sindresorhus/gulp-filter
/// <reference types="node" /> import File = require('vinyl'); import * as Minimatch from 'minimatch'; declare namespace filter { interface FileFunction { (file: File): boolean; } interface Options extends Minimatch.IOptions { restore?: boolean; passthrough?: boolean; } /...
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2
random_line_split
ve.dm.DocumentNode.js
/*! * VisualEditor DataModel DocumentNode class. * * @copyright 2011-2014 VisualEditor Team and others; see http://ve.mit-license.org */ /** * DataModel document node. * * @class * @extends ve.dm.BranchNode * * @constructor * @param {ve.dm.BranchNode[]} [children] Child nodes to attach */ ve.dm.DocumentNod...
ve.dm.modelRegistry.register( ve.dm.DocumentNode );
random_line_split
kendo.culture.hr-BA.js
/** * Copyright <%= year %> Telerik AD * * 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 agr...
groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ".", ".": ",", groupSize: [3], symbol: "%" }, currency: { pattern: ["-n $","n $"], ...
decimals: 2, ",": ".", ".": ",",
random_line_split
helpers.rs
// Example of a module shared among test code. /*BEGIN*/pub fn helper() { // ^^^^^^^^^^^^^^^WARN(>=1.22.0) function is never used // ^^^^^^^^^^^^^^^NOTE(>=1.22.0) #[warn(dead_code)] }/*END*/ // ~WARN(<1.22.0) function is never used // ~NOTE(<1.22.0,>=1.17.0) #[warn(dead_code)] /*BEGIN*/pub fn unused() { /...
// ~NOTE(<1.22.0,>=1.17.0) #[warn(dead_code)]
// ^^^^^^^^^^^^^^^NOTE(>=1.22.0,<1.24.0-beta) #[warn(dead_code)] }/*END*/ // ~WARN(<1.22.0) function is never used
random_line_split
helpers.rs
// Example of a module shared among test code. /*BEGIN*/pub fn helper()
/*END*/ // ~WARN(<1.22.0) function is never used // ~NOTE(<1.22.0,>=1.17.0) #[warn(dead_code)] /*BEGIN*/pub fn unused() { // ^^^^^^^^^^^^^^^WARN(>=1.22.0) function is never used // ^^^^^^^^^^^^^^^NOTE(>=1.22.0,<1.24.0-beta) #[warn(dead_code)] }/*END*/ // ~WARN(<1.22.0) function is never used // ~NOTE(<1.22...
{ // ^^^^^^^^^^^^^^^WARN(>=1.22.0) function is never used // ^^^^^^^^^^^^^^^NOTE(>=1.22.0) #[warn(dead_code)] }
identifier_body
helpers.rs
// Example of a module shared among test code. /*BEGIN*/pub fn helper() { // ^^^^^^^^^^^^^^^WARN(>=1.22.0) function is never used // ^^^^^^^^^^^^^^^NOTE(>=1.22.0) #[warn(dead_code)] }/*END*/ // ~WARN(<1.22.0) function is never used // ~NOTE(<1.22.0,>=1.17.0) #[warn(dead_code)] /*BEGIN*/pub fn
() { // ^^^^^^^^^^^^^^^WARN(>=1.22.0) function is never used // ^^^^^^^^^^^^^^^NOTE(>=1.22.0,<1.24.0-beta) #[warn(dead_code)] }/*END*/ // ~WARN(<1.22.0) function is never used // ~NOTE(<1.22.0,>=1.17.0) #[warn(dead_code)]
unused
identifier_name
LinkMenuItem.tsx
/* eslint-disable react/prop-types */ import * as React from 'react'; import Icon from '../../Icon/Icon'; import { MenuItemDefinition, MenuItemProps } from './MenuItem'; export const LinkMenuItem: React.FunctionComponent<MenuItemProps<LinkMenuItemDefinition>> = ( { item, path, state, dispatch, navigate }) => { c...
const className = ( 'sidebar-menu-item' + (isActive ? ' sidebar-menu-item--active' : '') + (isInSubMenu ? ' sidebar-menu-item--in-sub-menu' : '') ); return ( <li className={className}> <a href={item.url} aria-current={isCurrent ? 'page' : undefined} onClick={onClick...
}); };
random_line_split
LinkMenuItem.tsx
/* eslint-disable react/prop-types */ import * as React from 'react'; import Icon from '../../Icon/Icon'; import { MenuItemDefinition, MenuItemProps } from './MenuItem'; export const LinkMenuItem: React.FunctionComponent<MenuItemProps<LinkMenuItemDefinition>> = ( { item, path, state, dispatch, navigate }) => { c...
({ path, state, dispatch, navigate }) { return ( <LinkMenuItem key={this.name} item={this} path={path} state={state} dispatch={dispatch} navigate={navigate} /> ); } }
render
identifier_name
LinkMenuItem.tsx
/* eslint-disable react/prop-types */ import * as React from 'react'; import Icon from '../../Icon/Icon'; import { MenuItemDefinition, MenuItemProps } from './MenuItem'; export const LinkMenuItem: React.FunctionComponent<MenuItemProps<LinkMenuItemDefinition>> = ( { item, path, state, dispatch, navigate }) => { c...
e.preventDefault(); navigate(item.url).then(() => { // Set active menu item dispatch({ type: 'set-active-path', path, }); // Reset navigation path to close any open submenus dispatch({ type: 'set-navigation-path', path: '', }); }); };...
{ return; }
conditional_block
index.js
/* eslint-disable id-match, id-length, no-undef, camelcase */ import PianoConfig from '../src/example-config.js'; import ReactI13nPiano from '../src/index'; import chai from 'chai'; import spies from 'chai-spies'; chai.use(spies).should(); mocha.setup({ globals: [ 'tp', 'init', 'jQuery*', 'setAdblockerCookie', 'script'...
describe('piano plugin', () => { it('window.tp.experience.execute() is called with specific properties', () => { const TrackedApp = new ReactI13nPiano(PianoConfig); TrackedApp.updateTinypass = chai.spy(() => Promise.resolve()); return TrackedApp.pageview().then(() => { TrackedApp.upd...
const plugin = new ReactI13nPiano({ ...PianoConfig, loadExternalScript }); plugin.ensureScriptHasLoaded(); loadExternalScript.should.have.been.called.exactly(1); }); });
random_line_split
dwellClick.js
/* exported DwellClickIndicator */ const { Clutter, Gio, GLib, GObject, St } = imports.gi; const PanelMenu = imports.ui.panelMenu; const MOUSE_A11Y_SCHEMA = 'org.gnome.desktop.a11y.mouse'; const KEY_DWELL_CLICK_ENABLED = 'dwell-click-enabled'; const KEY_DWELL_MODE = 'dwell-mode'; const DWELL_MODE_WINDO...
(manager, clickType) { for (let mode in DWELL_CLICK_MODES) { if (DWELL_CLICK_MODES[mode].type == clickType) this._icon.icon_name = DWELL_CLICK_MODES[mode].icon; } } _setClickType(mode) { this._seat.set_pointer_a11y_dwell_click_type(mode.type); this._i...
_updateClickType
identifier_name
dwellClick.js
/* exported DwellClickIndicator */ const { Clutter, Gio, GLib, GObject, St } = imports.gi; const PanelMenu = imports.ui.panelMenu; const MOUSE_A11Y_SCHEMA = 'org.gnome.desktop.a11y.mouse'; const KEY_DWELL_CLICK_ENABLED = 'dwell-click-enabled'; const KEY_DWELL_MODE = 'dwell-mode'; const DWELL_MODE_WINDO...
_addDwellAction(mode) { this.menu.addAction(mode.name, this._setClickType.bind(this, mode), mode.icon); } _updateClickType(manager, clickType) { for (let mode in DWELL_CLICK_MODES) { if (DWELL_CLICK_MODES[mode].type == clickType) this._icon.icon_name = DWELL_CL...
{ this.visible = this._a11ySettings.get_boolean(KEY_DWELL_CLICK_ENABLED) && this._a11ySettings.get_string(KEY_DWELL_MODE) == DWELL_MODE_WINDOW; return GLib.SOURCE_REMOVE; }
identifier_body
dwellClick.js
/* exported DwellClickIndicator */ const { Clutter, Gio, GLib, GObject, St } = imports.gi; const PanelMenu = imports.ui.panelMenu; const MOUSE_A11Y_SCHEMA = 'org.gnome.desktop.a11y.mouse'; const KEY_DWELL_CLICK_ENABLED = 'dwell-click-enabled'; const KEY_DWELL_MODE = 'dwell-mode'; const DWELL_MODE_WINDO...
this._addDwellAction(DWELL_CLICK_MODES.primary); this._addDwellAction(DWELL_CLICK_MODES.double); this._addDwellAction(DWELL_CLICK_MODES.drag); this._addDwellAction(DWELL_CLICK_MODES.secondary); this._setClickType(DWELL_CLICK_MODES.primary); this._syncMenuVisibility(); ...
random_line_split
console.target.ts
import { Injectable, Provider } from '@angular/core'; import { LogTargetBase, LogEvent, LogLevel, LogTargetOptions, LogTarget } from './log.target'; import { ConsoleService } from '../console.service'; @Injectable() export class ConsoleTarget extends LogTargetBase { constructor(private console: ConsoleService, optio...
(event: LogEvent) { switch (event.level) { case LogLevel.Debug: this.console.log(event.message); break; case LogLevel.Info: this.console.info(event.message); break; case LogLevel.Warning: this.console.warn(event.message); break; case LogLevel.E...
writeToLog
identifier_name
console.target.ts
import { Injectable, Provider } from '@angular/core'; import { LogTargetBase, LogEvent, LogLevel, LogTargetOptions, LogTarget } from './log.target'; import { ConsoleService } from '../console.service'; @Injectable() export class ConsoleTarget extends LogTargetBase { constructor(private console: ConsoleService, optio...
writeToLog(event: LogEvent) { switch (event.level) { case LogLevel.Debug: this.console.log(event.message); break; case LogLevel.Info: this.console.info(event.message); break; case LogLevel.Warning: this.console.warn(event.message); break; c...
{ super(options); }
identifier_body
console.target.ts
import { Injectable, Provider } from '@angular/core'; import { LogTargetBase, LogEvent, LogLevel, LogTargetOptions, LogTarget } from './log.target'; import { ConsoleService } from '../console.service'; @Injectable() export class ConsoleTarget extends LogTargetBase { constructor(private console: ConsoleService, optio...
return new ConsoleTarget(consoleService, { minLogLevel: level }); } export function provideConsoleTarget(logLevel: LogLevel): Provider { return { provide: LogTarget, deps: [ConsoleService], multi: true, useFactory: (c: ConsoleService) => new ConsoleTarget(c, { minLogLevel: logLevel }) }; }
export function createConsoleTarget(level: LogLevel, consoleService: ConsoleService) {
random_line_split
g++.py
"""SCons.Tool.g++ Tool-specific initialization for g++. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation # # Permission is...
(env): """Add Builders and construction variables for g++ to an Environment.""" static_obj, shared_obj = SCons.Tool.createObjBuilders(env) cplusplus.generate(env) env['CXX'] = env.Detect(compilers) # platform specific settings if env['PLATFORM'] == 'aix': env['SHCXXFLAGS'] = SC...
generate
identifier_name
g++.py
"""SCons.Tool.g++ Tool-specific initialization for g++. There normally shouldn't be any need to import this module directly.
""" # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation # # 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 limitati...
It will usually be imported through the generic SCons.Tool.Tool() selection method.
random_line_split
g++.py
"""SCons.Tool.g++ Tool-specific initialization for g++. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation # # Permission is...
def exists(env): return env.Detect(compilers)
pipe = SCons.Action._subproc(env, [env['CXX'], '--version'], stdin = 'devnull', stderr = 'devnull', stdout = subprocess.PIPE) if pipe.wait() != 0: return # -dumpversion was added in GCC 3.0. A...
conditional_block
g++.py
"""SCons.Tool.g++ Tool-specific initialization for g++. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation # # Permission is...
return env.Detect(compilers)
identifier_body
config.default.js
'use strict'; var path = require('path'); module.exports = function (config, storages) { config.port = process.env.MEDIA_SERVICE_PORT || 80; config.autoRestart = true; config.progressive = true; config.metadata = false; config.quality = 90; config.webp = true; // access control config.enableAccessCo...
'avatar': 'small-avatar', 'big-avatar': 'avatar' } }; // storages var localStorage = new storages.LocalStorage('local', { baseUrl: 'http://localhost', dir: path.join(__dirname, 'medias') }); config.storages = [ localStorage ]; };
phone: {
random_line_split
static_content.py
# /usr/bin/env python """ This module has utility functions for gathering up the static content that is defined by XModules and XModuleDescriptors (javascript and css) """ import logging import hashlib import os import errno import sys from collections import defaultdict from docopt import docopt from path import path...
type=filetype) contents[filename] = fragment _write_files(output_root, contents, {'.coffee': '.js'}) return [output_root / filename for filename in contents.keys()] def _write_files(output_root, contents, generated_suffix_map=None): """ Write file contents to output root. An...
random_line_split
static_content.py
# /usr/bin/env python """ This module has utility functions for gathering up the static content that is defined by XModules and XModuleDescriptors (javascript and css) """ import logging import hashlib import os import errno import sys from collections import defaultdict from docopt import docopt from path import path...
to_delete.discard(output_file.replace(suffix, generated_suffix)) for extra_file in to_delete: (output_root / extra_file).remove_p() for filename, file_content in contents.iteritems(): output_file = output_root / filename not_file = not output_file.isfile() ...
""" Write file contents to output root. Any files not listed in contents that exists in output_root will be deleted, unless it matches one of the patterns in `generated_suffix_map`. output_root (path): The root directory to write the file contents in contents (dict): A map from filenames to file c...
identifier_body
static_content.py
# /usr/bin/env python """ This module has utility functions for gathering up the static content that is defined by XModules and XModuleDescriptors (javascript and css) """ import logging import hashlib import os import errno import sys from collections import defaultdict from docopt import docopt from path import path...
(output_root): """Write all registered XModule js and coffee files to output root.""" return _write_js(output_root, _list_modules()) def write_descriptor_styles(output_root): """Write all registered XModuleDescriptor css, sass, and scss files to output root.""" return _write_styles('.xmodule_edit', ou...
write_module_js
identifier_name
static_content.py
# /usr/bin/env python """ This module has utility functions for gathering up the static content that is defined by XModules and XModuleDescriptors (javascript and css) """ import logging import hashlib import os import errno import sys from collections import defaultdict from docopt import docopt from path import path...
else: LOG.debug("%s unchanged, skipping", output_file) def main(): """ Generate Usage: static_content.py <output_root> """ args = docopt(main.__doc__) root = path(args['<output_root>']) write_descriptor_js(root / 'descriptors/js') write_descriptor_styles(root / 'd...
LOG.debug("Writing %s", output_file) output_file.write_bytes(file_content)
conditional_block
index.tsx
import * as React from 'react'; import * as moment from 'moment'; import RcCalendar from 'rc-calendar'; import MonthCalendar from 'rc-calendar/lib/MonthCalendar'; import createPicker from './createPicker'; import wrapPicker from './wrapPicker'; import RangePicker from './RangePicker'; import WeekPicker from './WeekPick...
value?: [moment.Moment, moment.Moment]; defaultValue?: [moment.Moment, moment.Moment]; defaultPickerValue?: [moment.Moment, moment.Moment]; onChange?: (dates: [moment.Moment, moment.Moment], dateStrings: [string, string]) => void; onCalendarChange?: (dates: [moment.Moment, moment.Moment], dateStrings: [string...
random_line_split
trafficDownloader.py
#!/usr/bin/env python __author__ = "Devin Kelly" import pymongo import time import json import re import os import daemon from datetime import datetime from tornado import httpclient, ioloop def parseHTML(htmlData): expr = re.compile("In current traffic: [0-9]{0,2} mins") matches = re.finditer(expr, htmlData...
F1 = getWeekdayCommuteTimeFunction(coll, home, work, startHour, endHour) callbacks.append(ioloop.PeriodicCallback(F1, interval, io_loop)) # afternoon commute startHour = 15 endHour = 23 coll = db["afternoon"] F2 = getWeekdayCommuteTimeFunction(coll, work, home, startHour, endHour) callbacks.app...
dbName = "traffic" cli = pymongo.MongoClient() db = cli[dbName] # Read Config File with open("trafficConfig.json") as fd: config = json.loads(fd.read()) home = config["home"] work = config["work"] interval = config["interval_ms"] # Setup IO Loop callbacks = [] io_loop = ioloop.IOL...
identifier_body
trafficDownloader.py
#!/usr/bin/env python __author__ = "Devin Kelly" import pymongo import time import json import re import os import daemon from datetime import datetime from tornado import httpclient, ioloop def parseHTML(htmlData): expr = re.compile("In current traffic: [0-9]{0,2} mins") matches = re.finditer(expr, htmlData...
travelTime = re.sub("^.*:\s*", "", travelTime) tmpData["time"] = travelTime trafficData.append(tmpData) return trafficData def insertData(coll, data): timestamp = time.time() for trip in data: coll.insert({"commuteTime": trip['time'], "timestamp": timestamp, "route": trip['route']}...
tmpData["route"] = route
random_line_split
trafficDownloader.py
#!/usr/bin/env python __author__ = "Devin Kelly" import pymongo import time import json import re import os import daemon from datetime import datetime from tornado import httpclient, ioloop def parseHTML(htmlData): expr = re.compile("In current traffic: [0-9]{0,2} mins") matches = re.finditer(expr, htmlData...
return trafficData def insertData(coll, data): timestamp = time.time() for trip in data: coll.insert({"commuteTime": trip['time'], "timestamp": timestamp, "route": trip['route']}) def getWeekdayCommuteTimeFunction(coll, toAddr, fromAddr, startHour, endHour): toAddr = toAddr.replace(" ", "+") ...
tmpData = {} s = re.sub('<[^<]+?>', '', htmlData[ii.start(0): ii.start(0) + 180]) s = re.sub("<.*$", '', s) (travelTime, route) = s.split('mins') route = re.sub("^\s*", "", route) route = re.sub("\s*$", "", route) tmpData["route"] = route travelTime = re.sub("^.*:\s*", "", tr...
conditional_block
trafficDownloader.py
#!/usr/bin/env python __author__ = "Devin Kelly" import pymongo import time import json import re import os import daemon from datetime import datetime from tornado import httpclient, ioloop def parseHTML(htmlData): expr = re.compile("In current traffic: [0-9]{0,2} mins") matches = re.finditer(expr, htmlData...
(): now = time.time() dt = datetime.fromtimestamp(now) if dt.weekday() > 4: return if dt.hour < startHour or dt.hour > endHour: return http_client = httpclient.HTTPClient() print 'fetching' try: response = http_client.fetch(url) trafficData...
weekdayCommuteTime
identifier_name
match-arm-statics.rs
// 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 ...
_ => { "Unknown" } } } assert_eq!(action_to_str(glfw::RELEASE), "Released"); assert_eq!(action_to_str(glfw::PRESS), "Pressed"); assert_eq!(action_to_str(glfw::REPEAT), "Repeated"); } fn issue_13626() { const VAL: [u8, ..1] = [0]; match [1] { VAL => unreachab...
{ "Repeated" }
conditional_block
match-arm-statics.rs
// 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 ...
assert_eq!(match C::D { F => 1i, _ => 2, }, 1); } fn issue_13731() { enum A { AA(()) } const B: A = A::AA(()); match A::AA(()) { B => () } } fn issue_15393() { #![allow(dead_code)] struct Flags { bits: uint } const FOO: Flags = Flags { bits: 0x01 }; const BAR...
enum C { D = 3, E = 4 } const F : C = C::D;
random_line_split
match-arm-statics.rs
// 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 ...
{ Variant1(bool), Variant2 { dir: Direction } } const TRUE_TRUE: (bool, bool) = (true, true); const NONE: Option<Direction> = None; const EAST: Direction = Direction::East; const NEW_FALSE: NewBool = NewBool(false); const STATIC_FOO: Foo = Foo { bar: Some(Direction::South), baz: NEW_FALSE }; const...
EnumWithStructVariants
identifier_name
event_binder.ts
/** * @license * Copyright Google Inc. 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 {EventHandlerVars, convertActionBinding} from '../compiler_util/expression_converter'; import {createInlineAr...
function collectEvents( boundEvents: BoundEventAst[], directives: DirectiveAst[]): Map<string, EventSummary> { const usedEvents = new Map<string, EventSummary>(); boundEvents.forEach((event) => { usedEvents.set(event.fullName, event); }); directives.forEach((dirAst) => { dirAst.hostEvents.forEach((event...
{ const usedEvents = collectEvents(boundEvents, directives); if (!usedEvents.size) { return false; } if (bindToRenderer) { subscribeToRenderEvents(usedEvents, compileElement); } subscribeToDirectiveEvents(usedEvents, directives, compileElement); generateHandleEventMethod(boundEvents, directives, c...
identifier_body
event_binder.ts
/** * @license * Copyright Google Inc. 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 {EventHandlerVars, convertActionBinding} from '../compiler_util/expression_converter'; import {createInlineAr...
subscribeToDirectiveEvents(usedEvents, directives, compileElement); generateHandleEventMethod(boundEvents, directives, compileElement); return true; } function collectEvents( boundEvents: BoundEventAst[], directives: DirectiveAst[]): Map<string, EventSummary> { const usedEvents = new Map<string, EventSumm...
{ subscribeToRenderEvents(usedEvents, compileElement); }
conditional_block
event_binder.ts
/** * @license * Copyright Google Inc. 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 {EventHandlerVars, convertActionBinding} from '../compiler_util/expression_converter'; import {createInlineAr...
( boundEvents: BoundEventAst[], directives: DirectiveAst[]): Map<string, EventSummary> { const usedEvents = new Map<string, EventSummary>(); boundEvents.forEach((event) => { usedEvents.set(event.fullName, event); }); directives.forEach((dirAst) => { dirAst.hostEvents.forEach((event) => { usedEvents.set(ev...
collectEvents
identifier_name
event_binder.ts
/** * @license * Copyright Google Inc. 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 {EventHandlerVars, convertActionBinding} from '../compiler_util/expression_converter'; import {createInlineAr...
import {CompileElement} from './compile_element'; import {CompileMethod} from './compile_method'; import {ViewProperties} from './constants'; import {getHandleEventMethodName} from './util'; export function bindOutputs( boundEvents: BoundEventAst[], directives: DirectiveAst[], compileElement: CompileElement, ...
import {Identifiers, resolveIdentifier} from '../identifiers'; import * as o from '../output/output_ast'; import {BoundEventAst, DirectiveAst} from '../template_parser/template_ast';
random_line_split
animation.rs
/* 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/. */ //! CSS transitions and animations. use clock_ticks; use flow::{self, Flow}; use gfx::display_list::OpaqueNode; u...
{ layout_task.tick_animations(rw_data); layout_task.script_chan .send(ConstellationControlMsg::TickAllAnimations(layout_task.id)) .unwrap(); }
identifier_body
animation.rs
/* 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/. */ //! CSS transitions and animations. use clock_ticks; use flow::{self, Flow}; use gfx::display_list::OpaqueNode; u...
(layout_task: &LayoutTask, rw_data: &mut LayoutTaskData) { layout_task.tick_animations(rw_data); layout_task.script_chan .send(ConstellationControlMsg::TickAllAnimations(layout_task.id)) .unwrap(); }
tick_all_animations
identifier_name
animation.rs
/* 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/. */ //! CSS transitions and animations.
use incremental::{self, RestyleDamage}; use layout_task::{LayoutTask, LayoutTaskData}; use msg::constellation_msg::{AnimationState, Msg, PipelineId}; use script::layout_interface::Animation; use script_traits::ConstellationControlMsg; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::sync::...
use clock_ticks; use flow::{self, Flow}; use gfx::display_list::OpaqueNode;
random_line_split
build.js
var fs = require('fs'), exec = require('child_process').exec; var modules = process.argv.slice(2)[0]; modules = modules ? modules.split('=')[1].split(',') : [ ]; var minifier = process.argv.slice(3)[0]; var mininfierCmd; minifier = minifier ? minifier.split('=')[1] : 'yui'; if (minifier === 'yui') { mininfierC...
(fileNames, callback) { (function readNextFile() { if (fileNames.length <= 0) { return callback(); } var fileName = fileNames.shift(); if (!fileName) { return readNextFile(); } fs.readFile(__dirname + '/' + fileName, function (err, data) { if (err) thro...
appendFileContents
identifier_name
build.js
var fs = require('fs'), exec = require('child_process').exec; var modules = process.argv.slice(2)[0];
var mininfierCmd; minifier = minifier ? minifier.split('=')[1] : 'yui'; if (minifier === 'yui') { mininfierCmd = 'java -jar lib/yuicompressor-2.4.2.jar dist/all.js -o dist/all.min.js'; } else if (minifier === 'closure') { mininfierCmd = 'java -jar lib/google_closure_compiler.jar --js dist/all.js --js_output_file d...
modules = modules ? modules.split('=')[1].split(',') : [ ]; var minifier = process.argv.slice(3)[0];
random_line_split
build.js
var fs = require('fs'), exec = require('child_process').exec; var modules = process.argv.slice(2)[0]; modules = modules ? modules.split('=')[1].split(',') : [ ]; var minifier = process.argv.slice(3)[0]; var mininfierCmd; minifier = minifier ? minifier.split('=')[1] : 'yui'; if (minifier === 'yui') { mininfierC...
var filesToInclude = [ 'HEADER.js', ifSpecifiedInclude('serialization', 'lib/json2.js'), ifSpecifiedInclude('text', 'lib/cufon.js'), 'src/log.js', 'src/observable.js', 'src/util/misc.js', 'src/util/lang_array.js', 'src/util/lang_object.js', 'src/util/lang_string.js', 'src/util/lang_funct...
{ return (modules.indexOf(moduleName) > -1 || includeAllModules) ? fileName : ''; }
identifier_body
serializers.py
from rest_framework import serializers from models import SurveyDraft from taggit.models import Tag class WritableJSONField(serializers.Field): """ Serializer for JSONField -- required to make field writable""" """ ALSO REQUIRED because the default JSONField serialization includes the `u` prefix on string...
def get_tag_names(self, obj): return obj.tags.names() class TagSerializer(serializers.HyperlinkedModelSerializer): count = serializers.SerializerMethodField() label = serializers.CharField(source='name') class Meta: model = Tag fields = ('id', 'label', 'count') def get_co...
random_line_split
serializers.py
from rest_framework import serializers from models import SurveyDraft from taggit.models import Tag class WritableJSONField(serializers.Field): """ Serializer for JSONField -- required to make field writable""" """ ALSO REQUIRED because the default JSONField serialization includes the `u` prefix on string...
def to_representation(self, value): return value class ListSurveyDraftSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = SurveyDraft fields = ('id', 'name', 'asset_type', 'summary', 'date_modified', 'description') summary = WritableJSONField(required=False) ...
try: return json.loads(data) except Exception as e: raise serializers.ValidationError( u'Unable to parse JSON: {}'.format(e))
conditional_block
serializers.py
from rest_framework import serializers from models import SurveyDraft from taggit.models import Tag class WritableJSONField(serializers.Field): """ Serializer for JSONField -- required to make field writable""" """ ALSO REQUIRED because the default JSONField serialization includes the `u` prefix on string...
class TagSerializer(serializers.HyperlinkedModelSerializer): count = serializers.SerializerMethodField() label = serializers.CharField(source='name') class Meta: model = Tag fields = ('id', 'label', 'count') def get_count(self, obj): return SurveyDraft.objects.filter(tags__na...
return obj.tags.names()
identifier_body
serializers.py
from rest_framework import serializers from models import SurveyDraft from taggit.models import Tag class WritableJSONField(serializers.Field): """ Serializer for JSONField -- required to make field writable""" """ ALSO REQUIRED because the default JSONField serialization includes the `u` prefix on string...
(self, obj): return obj.tags.names() class TagSerializer(serializers.HyperlinkedModelSerializer): count = serializers.SerializerMethodField() label = serializers.CharField(source='name') class Meta: model = Tag fields = ('id', 'label', 'count') def get_count(self, obj): ...
get_tag_names
identifier_name
arrays.js
/**
* Arrays * Most of your answers should be stored in variables called q1, q2 etc.. * and the variables printed to the console. * (i.e) console.log("Question 1" + q1) */ /** * Question 1 * Create an array of image source filenames. * Use "image1.png", "image2.png", and "image3.png" as the array values. */ // Y...
random_line_split
petition-page-loader.ts
/// <reference path="../node.d.ts" /> import loading = require('./loading'); import https = require('https'); import petitionUtil = require('../private/petition-util'); var getJsonOverHttps = petitionUtil.getJsonOverHttps; export module UkPetitions { /** * Loads a page of petition summaries. It is statele...
(agent?: https.Agent) { this.agent = agent; } /** * Load a page of petitions by number. Returns an emitter. Emits either 'loaded' or 'error' events. * The 'loaded' event is passed the data of the petition. * The 'error' event is passed the Error. * @retur...
constructor
identifier_name
petition-page-loader.ts
/// <reference path="../node.d.ts" /> import loading = require('./loading'); import https = require('https'); import petitionUtil = require('../private/petition-util'); var getJsonOverHttps = petitionUtil.getJsonOverHttps; export module UkPetitions { /** * Loads a page of petition summaries. It is stateles...
/** * Load a page of petitions by number. Returns an emitter. Emits either 'loaded' or 'error' events. * The 'loaded' event is passed the data of the petition. * The 'error' event is passed the Error. * @return The emitter */ load(page: any): loading.UkPetiti...
this.agent = agent; }
random_line_split
petition-page-loader.ts
/// <reference path="../node.d.ts" /> import loading = require('./loading'); import https = require('https'); import petitionUtil = require('../private/petition-util'); var getJsonOverHttps = petitionUtil.getJsonOverHttps; export module UkPetitions { /** * Loads a page of petition summaries. It is statele...
} getJsonOverHttps({ hostname: 'petition.parliament.uk', port: 443, path: pathToLoad, agent: this.agent }) .on('error', emitter.error.bind(emitter)) .on('data', emitter.loaded.bind(emitter)); ...
{ var emitter: loading.UkPetitions.Loading = new loading.UkPetitions.Loading(); var pathToLoad: string; if (typeof page === 'number') { pathToLoad = '/petitions.json?page=' + page; } else if (typeof page === 'string') { pathToLoad = page; ...
identifier_body
petition-page-loader.ts
/// <reference path="../node.d.ts" /> import loading = require('./loading'); import https = require('https'); import petitionUtil = require('../private/petition-util'); var getJsonOverHttps = petitionUtil.getJsonOverHttps; export module UkPetitions { /** * Loads a page of petition summaries. It is statele...
else if (typeof page === 'object') { if (page instanceof String) { pathToLoad = page; } else if (page instanceof Number) { pathToLoad = '/petitions.json?page=' + page; } else { emitter.error('Problem parameter')...
{ pathToLoad = page; }
conditional_block
scrapbook-list.js
var GridLayout = require("ui/layouts/grid-layout").GridLayout; var ListView = require("ui/list-view").ListView; var StackLayout = require("ui/layouts/stack-layout").StackLayout; var Image = require("ui/image").Image; var Label = require("ui/label").Label; var ScrapbookList = (function (_super) { global.__e...
var image = new Image(); image.className = "thumb img-circle"; image.bind({ targetProperty: "src", sourceProperty: "image" }); stackLa...
{ _super.call(this); this._items; this.rows = "*"; this.columns = "*"; var listView = new ListView(); listView.className = "list-group"; listView.itemTemplate = function() { var stackLayout = new StackLayout(); stackLa...
identifier_body
scrapbook-list.js
var GridLayout = require("ui/layouts/grid-layout").GridLayout; var ListView = require("ui/list-view").ListView; var StackLayout = require("ui/layouts/stack-layout").StackLayout; var Image = require("ui/image").Image; var Label = require("ui/label").Label; var ScrapbookList = (function (_super) { global.__e...
() { _super.call(this); this._items; this.rows = "*"; this.columns = "*"; var listView = new ListView(); listView.className = "list-group"; listView.itemTemplate = function() { var stackLayout = new StackLayout(); stac...
ScrapbookList
identifier_name
scrapbook-list.js
var GridLayout = require("ui/layouts/grid-layout").GridLayout; var ListView = require("ui/list-view").ListView; var StackLayout = require("ui/layouts/stack-layout").StackLayout; var Image = require("ui/image").Image; var Label = require("ui/label").Label; var ScrapbookList = (function (_super) { global.__e...
}; listView.on(ListView.itemTapEvent, function(args) { onItemTap(this, args.index); }.bind(listView)); this.addChild(listView); this.bindData = function () { listView.bind({ sourceProperty: "$value"...
return stackLayout;
random_line_split
data.ts
import mem from 'mem'; import { elections } from '../../../data/elections'; import { ElectionDataRow, ElectionYear } from '../../../data/types'; import { ElectionResult, getResult } from '../../../lib/election'; type DataRow = [string, number, number]; /** * * @param year * @param reallocate */ export const getD...
(row: ElectionDataRow): DataRow => [row[0], row[1], row[2] || 0] ) }; if (reallocate) { const act = data.r.findIndex( (row: DataRow): row is DataRow => row[0] === 'act' ); const nat = data.r.findIndex( (row: DataRow): row is DataRow => row[0] === 'nat' ); ...
const data = { ...elections[year], r: elections[year].r.map(
random_line_split
data.ts
import mem from 'mem'; import { elections } from '../../../data/elections'; import { ElectionDataRow, ElectionYear } from '../../../data/types'; import { ElectionResult, getResult } from '../../../lib/election'; type DataRow = [string, number, number]; /** * * @param year * @param reallocate */ export const getD...
return getResult(data.r, { seats: 120, threshold: 5, overhang: true, tagAlong: true, tagAlongSeats: 1 }); }, { cacheKey: (args) => [args[0], Number(args[1])].join('-') } );
{ const act = data.r.findIndex( (row: DataRow): row is DataRow => row[0] === 'act' ); const nat = data.r.findIndex( (row: DataRow): row is DataRow => row[0] === 'nat' ); data.r[nat][2] = data.r[act][2]; data.r[act][2] = 0; }
conditional_block
clean.py
from gitcd.interface.cli.abstract import BaseCommand from gitcd.git.branch import Branch from gitcd.app.clean import Clean as CleanHelper class
(BaseCommand): updateRemote = True def run(self, branch: Branch): helper = CleanHelper() branchesToDelete = helper.getBranchesToDelete() self.interface.writeOut('Branches to delete') if len(branchesToDelete) == 0: self.interface.ok(' - no branches to delete') ...
Clean
identifier_name
clean.py
from gitcd.interface.cli.abstract import BaseCommand from gitcd.git.branch import Branch from gitcd.app.clean import Clean as CleanHelper class Clean(BaseCommand): updateRemote = True def run(self, branch: Branch): helper = CleanHelper() branchesToDelete = helper.getBranchesToDelete() ...
self.interface.red(" - %s" % branchToDelete.getName()) self.interface.writeOut('') if len(branchesToDelete) == 0: self.interface.ok('Nice, your local repository is clean already.') return True delete = self.interface.askFor( 'Do you want me to d...
self.interface.ok(' - no branches to delete') for branchToDelete in branchesToDelete:
random_line_split
clean.py
from gitcd.interface.cli.abstract import BaseCommand from gitcd.git.branch import Branch from gitcd.app.clean import Clean as CleanHelper class Clean(BaseCommand):
delete = self.interface.askFor( 'Do you want me to delete those branches locally?', ['yes', 'no'], 'yes' ) if delete == 'yes': helper.deleteBranches(branchesToDelete) return True
updateRemote = True def run(self, branch: Branch): helper = CleanHelper() branchesToDelete = helper.getBranchesToDelete() self.interface.writeOut('Branches to delete') if len(branchesToDelete) == 0: self.interface.ok(' - no branches to delete') for branchToD...
identifier_body
clean.py
from gitcd.interface.cli.abstract import BaseCommand from gitcd.git.branch import Branch from gitcd.app.clean import Clean as CleanHelper class Clean(BaseCommand): updateRemote = True def run(self, branch: Branch): helper = CleanHelper() branchesToDelete = helper.getBranchesToDelete() ...
self.interface.writeOut('') if len(branchesToDelete) == 0: self.interface.ok('Nice, your local repository is clean already.') return True delete = self.interface.askFor( 'Do you want me to delete those branches locally?', ['yes', 'no'], ...
self.interface.red(" - %s" % branchToDelete.getName())
conditional_block
cache_padded.rs
use std::marker; use std::cell::UnsafeCell; use std::mem; use std::ptr; use std::ops::{Deref, DerefMut}; // For now, treat this as an arch-independent constant. const CACHE_LINE: usize = 32; #[repr(simd)] struct Padding(u64, u64, u64, u64); /// Pad `T` to the length of a cacheline. /// /// Sometimes concurrent progr...
(&self) -> &T { assert_valid::<T>(); unsafe { mem::transmute(&self.data) } } } impl<T> DerefMut for CachePadded<T> { fn deref_mut(&mut self) -> &mut T { assert_valid::<T>(); unsafe { mem::transmute(&mut self.data) } } } // FIXME: support Drop by pulling out a version usable...
deref
identifier_name
cache_padded.rs
use std::marker; use std::cell::UnsafeCell; use std::mem; use std::ptr; use std::ops::{Deref, DerefMut}; // For now, treat this as an arch-independent constant. const CACHE_LINE: usize = 32; #[repr(simd)] struct Padding(u64, u64, u64, u64); /// Pad `T` to the length of a cacheline. /// /// Sometimes concurrent progr...
/// architectures. /// /// **Warning**: the wrapped data is never dropped; move out using `ptr::read` /// if you need to run dtors. pub struct CachePadded<T> { data: UnsafeCell<[usize; CACHE_LINE]>, _marker: ([Padding; 0], marker::PhantomData<T>), } unsafe impl<T: Send> Send for CachePadded<T> {} unsafe impl<T...
/// /// At the moment, cache lines are assumed to be 32 * sizeof(usize) on all
random_line_split
predictText.py
#Minimal example for running location prediction from keras.models import load_model import pickle from keras.preprocessing.sequence import pad_sequences import numpy as np import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"] = "" binaryPath= 'data/binaries/' ...
print("%s with score=%.3f" % (colnames[index], float(predict[0][index])) )
conditional_block
predictText.py
#Minimal example for running location prediction from keras.models import load_model import pickle from keras.preprocessing.sequence import pad_sequences import numpy as np import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"] = "" binaryPath= 'data/binaries/' ...
descriptionTokenizer, domainEncoder, tldEncoder, locationTokenizer, sourceEncoder, textTokenizer, nameTokenizer, timeZoneTokenizer, utcEncoder, langEncoder, placeMedian, colnames, classEncoder = pickle.load(file) #Predict text (e.g., 'Montmartre is truly beautiful') testTexts=[]; testTexts.append("Montmartre is truly...
#Load Model textBranch = load_model(modelPath +'/textBranchNorm.h5') #Load preprocessed data... file = open(binaryPath +"processors.obj",'rb')
random_line_split
http.py
# -*- coding: UTF-8 -*- import logging from model_utils import Choices from simptools.wrappers.http import HttpClient, HttpRequest from requests.exceptions import ConnectionError from payway.merchants.models import Merchant __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' RESPONSE_STATUS = Choices(...
(HttpClient): @classmethod def notify(cls, merchant, order): result = '' try: request = MerchantHttpRequest(merchant, order) response = cls.execute(request) result = response.text except ConnectionError: logging.warn('Problems when connect...
MerchantHttpClient
identifier_name
http.py
# -*- coding: UTF-8 -*- import logging from model_utils import Choices from simptools.wrappers.http import HttpClient, HttpRequest from requests.exceptions import ConnectionError from payway.merchants.models import Merchant __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' RESPONSE_STATUS = Choices(...
def __set_POST(self, *args, **kwargs): self.POST = self.__request() def __set_GET(self, *args, **kwargs): self.GET = self.__request() def __request(self): return { 'url': self.merchant.result_url, 'data': { 'uid': self.order.uid, ...
self.__set_POST()
conditional_block
http.py
# -*- coding: UTF-8 -*- import logging from model_utils import Choices from simptools.wrappers.http import HttpClient, HttpRequest from requests.exceptions import ConnectionError from payway.merchants.models import Merchant __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' RESPONSE_STATUS = Choices(...
self.order = order if self.merchant.result_url_method == Merchant.URL_METHODS.GET: self.__set_GET() else: self.__set_POST() def __set_POST(self, *args, **kwargs): self.POST = self.__request() def __set_GET(self, *args, **kwargs): self.GET = self...
class MerchantHttpRequest(HttpRequest): def __init__(self, merchant, order): self.merchant = merchant
random_line_split
http.py
# -*- coding: UTF-8 -*- import logging from model_utils import Choices from simptools.wrappers.http import HttpClient, HttpRequest from requests.exceptions import ConnectionError from payway.merchants.models import Merchant __author__ = 'Razzhivin Alexander' __email__ = 'admin@httpbots.com' RESPONSE_STATUS = Choices(...
def __request(self): return { 'url': self.merchant.result_url, 'data': { 'uid': self.order.uid, 'is_paid': self.order.is_paid, 'sum': self.order.sum.amount, 'sum_currency': self.order.sum_currency, 'des...
self.GET = self.__request()
identifier_body
useMediaPicker.js
/* * Copyright 2020 Google LLC * * 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 ...
} ); return { openMediaPicker: result.current, onPermissionError, }; } describe('useMediaPicker', () => { it('user unable to upload', () => { const { openMediaPicker, onPermissionError } = setup({ args: { capabilities: { hasUploadMediaAction: false, }, }, ...
{ const configValue = { capabilities: { hasUploadMediaAction: true, }, ...args, }; const wrapper = ({ children }) => ( <ConfigContext.Provider value={configValue}> <SnackbarContext.Provider>{children}</SnackbarContext.Provider> </ConfigContext.Provider> ); const onSelect = jes...
identifier_body