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
pagers.py
# -*- coding: utf-8 -*- # Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
method: Callable[..., compute.PublicDelegatedPrefixList], request: compute.ListGlobalPublicDelegatedPrefixesRequest, response: compute.PublicDelegatedPrefixList, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. Args: method...
random_line_split
pagers.py
# -*- coding: utf-8 -*- # Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
( self, method: Callable[..., compute.PublicDelegatedPrefixList], request: compute.ListGlobalPublicDelegatedPrefixesRequest, response: compute.PublicDelegatedPrefixList, *, metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. Args: ...
__init__
identifier_name
beatmap_processor.py
#!/usr/bin/env python import sys from utils.file_system import * from calculations.beatmap_metadata import BeatmapMetadata from database.database_wrapper import DatabaseWrapper def
(msg): print("Hello world! " + msg) def print_help(): print("Usage: ./beatmap_processor.py [songs_folder]") print("This script initializes beatmap database with pp calculations") print("of all standard maps located on [songs_folder]") exit(1) if (len(sys.argv) != 2): print_help() songs_abs_pa...
hello
identifier_name
beatmap_processor.py
#!/usr/bin/env python import sys from utils.file_system import * from calculations.beatmap_metadata import BeatmapMetadata from database.database_wrapper import DatabaseWrapper def hello(msg): print("Hello world! " + msg) def print_help():
if (len(sys.argv) != 2): print_help() songs_abs_path = abs_path(sys.argv[1]) print(songs_abs_path) files = list_files(songs_abs_path) osu_files = [x for x in files if x.endswith(".osu")] #print("=======================================") #print(str(len(osu_files)) + " maps found!") #for u in osu_files: # pri...
print("Usage: ./beatmap_processor.py [songs_folder]") print("This script initializes beatmap database with pp calculations") print("of all standard maps located on [songs_folder]") exit(1)
identifier_body
beatmap_processor.py
#!/usr/bin/env python import sys from utils.file_system import * from calculations.beatmap_metadata import BeatmapMetadata from database.database_wrapper import DatabaseWrapper def hello(msg): print("Hello world! " + msg) def print_help(): print("Usage: ./beatmap_processor.py [songs_folder]") print("This...
print(str(errors) + " beatmaps with errors found!") print(str(other_modes) + " beatmaps from other modes were skipped.")
random_line_split
beatmap_processor.py
#!/usr/bin/env python import sys from utils.file_system import * from calculations.beatmap_metadata import BeatmapMetadata from database.database_wrapper import DatabaseWrapper def hello(msg): print("Hello world! " + msg) def print_help(): print("Usage: ./beatmap_processor.py [songs_folder]") print("This...
db_wrapper = DatabaseWrapper() added = 0 errors = 0 other_modes = 0 print("\n\nSTARTING PP CALCULATIONS.....\n") for u in osu_files: print("Calculating pp for '" + u + "'.....") b = BeatmapMetadata(u) if not b.is_standard_map(): print("Not a osu! standard map. Skipping...") other_modes += ...
mkdir("thumbnails")
conditional_block
useLocalStorage.tsx
import { useState } from 'react' interface LocalStorageState { darkModeEnabled: boolean } interface UseLocalStorageI { <K extends keyof LocalStorageState>( key: K, initialValue: LocalStorageState[K] ): [LocalStorageState[K], (v: LocalStorageState[K]) => void] } /** * Persist state in the browser local...
const useLocalStorage: UseLocalStorageI = (key, initialValue) => { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key) return item ? JSON.parse(item) : initialValue } catch (error) { return initialValue } }) // eslint-disable-ne...
* @param initialValue */
random_line_split
reducer.ts
import { SAVE_LOGIN, LOGOUT, SaveLoginAction, AuthActions } from './actions' import { Reduxer } from '../reduxer' import { GoogleToken } from './token'; import { Option } from '../../utils/option' import { readFromLocalStorage, saveToLocalStorage, deleteFromLocalStorage } from './effects' export interface State { lo...
implements Reduxer<State, AuthActions> { initialState = initialState reducer(state: State = initialState, action: AuthActions) { switch(action.type) { case SAVE_LOGIN: const saveAction = action as SaveLoginAction saveToLocalStorage(saveAction.token) return { loggedIn: true, cred...
AuthReduxer
identifier_name
reducer.ts
import { SAVE_LOGIN, LOGOUT, SaveLoginAction, AuthActions } from './actions' import { Reduxer } from '../reduxer' import { GoogleToken } from './token'; import { Option } from '../../utils/option' import { readFromLocalStorage, saveToLocalStorage, deleteFromLocalStorage } from './effects' export interface State { lo...
case LOGOUT: deleteFromLocalStorage() return { loggedIn: false, credentials: undefined } default: return state } } selectors = { loggedIn: (state: State) => () => state.loggedIn, credentials: (state: State) => () => state.creden...
case SAVE_LOGIN: const saveAction = action as SaveLoginAction saveToLocalStorage(saveAction.token) return { loggedIn: true, credentials: saveAction.token }
random_line_split
Example_Dudko_Fit.py
# force floating point division. Can still use integer with // from __future__ import division # This file is used for importing the common utilities classes. import numpy as np import matplotlib.pyplot as plt
sys.path.append("../../../../../") from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.Util import \ Example_Data def PlotFit(data,BaseName): fig = Example_Data.PlotHistograms(data) fig.savefig(BaseName + "_Histogram.png") fig = Example_Data.PlotLifetimesAndFit(data) fig.savefig(BaseName +...
import sys
random_line_split
Example_Dudko_Fit.py
# force floating point division. Can still use integer with // from __future__ import division # This file is used for importing the common utilities classes. import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../../../../") from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.U...
(data,BaseName): fig = Example_Data.PlotHistograms(data) fig.savefig(BaseName + "_Histogram.png") fig = Example_Data.PlotLifetimesAndFit(data) fig.savefig(BaseName + "_Lifetimes.png") def run(): """ """ # figure 1 from dudko 2008 data = Example_Data.Dudko2008Fig1_Probabilities() ...
PlotFit
identifier_name
Example_Dudko_Fit.py
# force floating point division. Can still use integer with // from __future__ import division # This file is used for importing the common utilities classes. import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../../../../") from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.U...
def run(): """ """ # figure 1 from dudko 2008 data = Example_Data.Dudko2008Fig1_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig1") # figure 2 frm dudko 2008 data = Example_Data.Dudko2008Fig2_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig2") if __name__ == "__main__": ...
fig = Example_Data.PlotHistograms(data) fig.savefig(BaseName + "_Histogram.png") fig = Example_Data.PlotLifetimesAndFit(data) fig.savefig(BaseName + "_Lifetimes.png")
identifier_body
Example_Dudko_Fit.py
# force floating point division. Can still use integer with // from __future__ import division # This file is used for importing the common utilities classes. import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../../../../") from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.U...
run()
conditional_block
Message.ts
'\r': 'r', ' ': 's' }; function escapeTag(str: string) { return str.replace(/[\\;\n\r ]/g, match => `\\${tagEscapeMap[match]}`); } export function prefixToString(prefix: MessagePrefix): string { let result = `${prefix.nick}`; if (prefix.user) { result += `!${prefix.user}`; } if (prefix.host) { result += `@$...
// eslint-disable-next-line @typescript-eslint/no-explicit-any
random_line_split
Message.ts
fer<T>>; SUPPORTS_CAPTURE: boolean; getMinParamCount: (isServer?: boolean) => number; checkParam: (param: string, spec: MessageParamSpecEntry, serverProperties?: ServerProperties) => boolean; new ( command: string, params?: MessageParam[], tags?: Map<string, string>, prefix?: MessagePrefix, serverProper...
tagsToString(): string { return [...this._tags.entries()].map(([key, value]) => (value ? `${key}=${escapeTag(value)}` : key)).join(';'); } toString(includePrefix: boolean = false): string { const cls = this.constructor as MessageConstructor<T>; const specKeys = cls.PARAM_SPEC ? (Object.keys(cls.PARAM_SPEC) ...
{ if (!this._prefix) { return ''; } return prefixToString(this._prefix); }
identifier_body
Message.ts
fer<T>>; SUPPORTS_CAPTURE: boolean; getMinParamCount: (isServer?: boolean) => number; checkParam: (param: string, spec: MessageParamSpecEntry, serverProperties?: ServerProperties) => boolean; new ( command: string, params?: MessageParam[], tags?: Map<string, string>, prefix?: MessagePrefix, serverProper...
return true; } static getMinParamCount(isServer: boolean = false): number { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!this.PARAM_SPEC) { return 0; } return Object.values(this.PARAM_SPEC).filter((spec: MessageParamSpecEntry) => { if (spec.noServer && isServer) { ...
{ if (!spec.match.test(param)) { return false; } }
conditional_block
Message.ts
Infer<T>>; SUPPORTS_CAPTURE: boolean; getMinParamCount: (isServer?: boolean) => number; checkParam: (param: string, spec: MessageParamSpecEntry, serverProperties?: ServerProperties) => boolean; new ( command: string, params?: MessageParam[], tags?: Map<string, string>, prefix?: MessagePrefix, serverProp...
<T extends Message<T> = any> { static readonly COMMAND: string = ''; // eslint-disable-next-line @typescript-eslint/no-explicit-any static readonly PARAM_SPEC: MessageParamSpec<any>; static readonly SUPPORTS_CAPTURE: boolean = false; protected _tags: Map<string, string>; protected _prefix?: MessagePrefix; prote...
Message
identifier_name
config.ts
import chokidar from 'chokidar'; import notify from './notify'; import {_import, getDefaultConfig} from './config/import'; import _openConfig from './config/open'; import {cfgPath, cfgDir} from './config/paths'; import {getColorMap} from './utils/colors'; import {parsedConfig, configOptions} from '../lib/config'; impor...
}, 100); }; _watcher = chokidar.watch(cfgPath); _watcher.on('change', onChange); _watcher.on('error', (error) => { console.error('error watching config', error); }); app.on('before-quit', (e) => { if (Object.keys(_watcher.getWatched()).length > 0) { e.preventDefault(); _watcher ...
checkDeprecatedConfig();
random_line_split
config.ts
import chokidar from 'chokidar'; import notify from './notify'; import {_import, getDefaultConfig} from './config/import'; import _openConfig from './config/open'; import {cfgPath, cfgDir} from './config/paths'; import {getColorMap} from './utils/colors'; import {parsedConfig, configOptions} from '../lib/config'; impor...
}); }; export const subscribe = (fn: Function) => { watchers.push(fn); return () => { watchers.splice(watchers.indexOf(fn), 1); }; }; export const getConfigDir = () => { // expose config directory to load plugin from the right place return cfgDir; }; export const getConfig = () => { return cfg.con...
{ e.preventDefault(); _watcher .close() .catch((err) => { console.warn(err); }) .finally(() => { app.quit(); }); }
conditional_block
restyle_damage.rs
-context-relative position of this node or its descendants has \ changed."] #[doc = "Propagates both up and down the flow tree."] const REPOSITION = 0x02, #[doc = "Recompute the overflow regions (bounding box of object and all descendants)."] #[doc = "Propagates down th...
, (REFLOW, "Reflow") , (RESOLVE_GENERATED_CONTENT, "ResolveGeneratedContent") , (RECONSTRUCT_FLOW, "ReconstructFlow") ]; for &(damage, damage_str) in &to_iter { if self.contains(damage) { if !first_elem { try!(write!(f, " | ")); } ...
, (STORE_OVERFLOW, "StoreOverflow") , (BUBBLE_ISIZES, "BubbleISizes") , (REFLOW_OUT_OF_FLOW, "ReflowOutOfFlow")
random_line_split
restyle_damage.rs
-relative position of this node or its descendants has \ changed."] #[doc = "Propagates both up and down the flow tree."] const REPOSITION = 0x02, #[doc = "Recompute the overflow regions (bounding box of object and all descendants)."] #[doc = "Propagates down the flow t...
} impl Default for ServoRestyleDamage { fn default() -> Self { Self::empty() } } impl fmt::Display for ServoRestyleDamage { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { let mut first_elem = true; let to_iter = [ (REPAINT, "Repaint") , ...
{ Self::empty() }
identifier_body
restyle_damage.rs
-relative position of this node or its descendants has \ changed."] #[doc = "Propagates both up and down the flow tree."] const REPOSITION = 0x02, #[doc = "Recompute the overflow regions (bounding box of object and all descendants)."] #[doc = "Propagates down the flow t...
Ok(()) } } // NB: We need the braces inside the RHS due to Rust #8012. This particular // version of this macro might be safe anyway, but we want to avoid silent // breakage on modifications. macro_rules! add_if_not_equal( ($old:ident, $new:ident, $damage:ident, [ $($effect:ident),* ], [ $($sty...
{ try!(write!(f, "NoDamage")); }
conditional_block
restyle_damage.rs
-relative position of this node or its descendants has \ changed."] #[doc = "Propagates both up and down the flow tree."] const REPOSITION = 0x02, #[doc = "Recompute the overflow regions (bounding box of object and all descendants)."] #[doc = "Propagates down the flow t...
(self, child_is_absolutely_positioned: bool) -> ServoRestyleDamage { if child_is_absolutely_positioned { self & (REPAINT | REPOSITION | STORE_OVERFLOW | REFLOW_OUT_OF_FLOW | RESOLVE_GENERATED_CONTENT) } else { self & (REPAINT | REPOSITION | STORE_OVERFLOW | RE...
damage_for_parent
identifier_name
parse.js
var _ = require('lodash'); var norma = require('norma'); var jsonic = require('jsonic'); // string args override object args module.exports = function parse_pattern(instance,args,normaspec,fixed) { args = norma('{strargs:s? objargs:o? moreobjargs:o? '+(normaspec||'')+'}', args) try { return _.e...
args.objargs ? args.objargs : {}, args.strargs ? jsonic( args.strargs ) : {}, fixed || {} ) }) } catch( e ) { var col = 1==e.line?e.column-1:e.column throw error('add_string_pattern_syntax',{ argstr: args, syntax: e.message, line: e.line, col: col ...
// Precedence of arguments in add,act is left-to-right args.moreobjargs ? args.moreobjargs : {},
random_line_split
karma.d.ts
ServerCallback): Server; /** * Start the server */ start(): void; /** * Get properties from the injector * @param token */ get(token: string): any; /** * Force a refresh of the file...
protocol?: string; /**
random_line_split
http_client.py
import json from urllib2 import urlopen, HTTPError from urllib import urlencode import logging class HTTPClient(object): def __init__(self, host='localhost', port=90): self.host = host self.port = port def get_serv_addr (self): return 'http://%s:%s/' % ( self.host, self.port, ) ...
except: postdata=None for arg in args: url += '%s/' % arg params = urlencode(kwargs) url = '%s?%s'% (url, params) logging.debug("Request url: %s" % url) try: response = urlopen(url, postdata) except HTTPError as err: raise(er...
try: postdata = kwargs.pop('postdata')
random_line_split
http_client.py
import json from urllib2 import urlopen, HTTPError from urllib import urlencode import logging class
(object): def __init__(self, host='localhost', port=90): self.host = host self.port = port def get_serv_addr (self): return 'http://%s:%s/' % ( self.host, self.port, ) def call_handler(self, handler, *args, **kwargs): url = '%s%s/' % (self.get_serv_add...
HTTPClient
identifier_name
http_client.py
import json from urllib2 import urlopen, HTTPError from urllib import urlencode import logging class HTTPClient(object): def __init__(self, host='localhost', port=90): self.host = host self.port = port def get_serv_addr (self): return 'http://%s:%s/' % ( self.host, self.port, ) ...
params = urlencode(kwargs) url = '%s?%s'% (url, params) logging.debug("Request url: %s" % url) try: response = urlopen(url, postdata) except HTTPError as err: raise(err) except: return None ## Reading data: t...
url += '%s/' % arg
conditional_block
http_client.py
import json from urllib2 import urlopen, HTTPError from urllib import urlencode import logging class HTTPClient(object): def __init__(self, host='localhost', port=90):
def get_serv_addr (self): return 'http://%s:%s/' % ( self.host, self.port, ) def call_handler(self, handler, *args, **kwargs): url = '%s%s/' % (self.get_serv_addr(), handler) try: postdata = kwargs.pop('postdata') except: postdata=None for arg in...
self.host = host self.port = port
identifier_body
length.js
// Copyright (C) 2015 André Bargull. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es6id: 20.1.2.3
description: > Number.isInteger.length is 1. info: | Number.isInteger ( number ) 17 ECMAScript Standard Built-in Objects: Every built-in Function object, including constructors, has a length property whose value is an integer. Unless otherwise specified, this value is equal to the largest number of n...
random_line_split
mysql_operator.py
import logging from airflow.hooks import MySqlHook from airflow.models import BaseOperator from airflow.utils import apply_defaults class MySqlOperator(BaseOperator): """ Executes sql code in a specific MySQL database
:type sql: Can receive a str representing a sql statement, a list of str (sql statements), or reference to a template file. Template reference are recognized by str ending in '.sql' """ template_fields = ('sql',) template_ext = ('.sql',) ui_color = '#ededed' @apply_defaults ...
:param mysql_conn_id: reference to a specific mysql database :type mysql_conn_id: string :param sql: the sql code to be executed
random_line_split
mysql_operator.py
import logging from airflow.hooks import MySqlHook from airflow.models import BaseOperator from airflow.utils import apply_defaults class MySqlOperator(BaseOperator): """ Executes sql code in a specific MySQL database :param mysql_conn_id: reference to a specific mysql database :type mysql_conn_id: ...
logging.info('Executing: ' + str(self.sql)) hook = MySqlHook(mysql_conn_id=self.mysql_conn_id) hook.run(self.sql)
identifier_body
mysql_operator.py
import logging from airflow.hooks import MySqlHook from airflow.models import BaseOperator from airflow.utils import apply_defaults class
(BaseOperator): """ Executes sql code in a specific MySQL database :param mysql_conn_id: reference to a specific mysql database :type mysql_conn_id: string :param sql: the sql code to be executed :type sql: Can receive a str representing a sql statement, a list of str (sql statements), ...
MySqlOperator
identifier_name
css_provider.rs
// Copyright 2013-2015, 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 std::fmt::{self, Display, Formatter}; use ffi::{self, GtkCssProvider}; use glib::translat...
(name: &str, variant: &str) -> Self { unsafe { CssProvider { pointer: ffi::gtk_css_provider_get_named(name.to_glib_none().0, variant.to_glib_none().0) } } } pub fn load_from_path(path: &str) -> Result<CssProvider, gl...
get_named
identifier_name
css_provider.rs
// Copyright 2013-2015, 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 std::fmt::{self, Display, Formatter}; use ffi::{self, GtkCssProvider}; use glib::translat...
} impl_GObjectFunctions!(CssProvider, GtkCssProvider); impl_TraitObject!(CssProvider, GtkCssProvider);
{ let tmp: String = unsafe { from_glib_full(ffi::gtk_css_provider_to_string(self.pointer)) }; write!(f, "{}", tmp) }
identifier_body
css_provider.rs
// Copyright 2013-2015, 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 std::fmt::{self, Display, Formatter}; use ffi::{self, GtkCssProvider}; use glib::translat...
pub fn get_named(name: &str, variant: &str) -> Self { unsafe { CssProvider { pointer: ffi::gtk_css_provider_get_named(name.to_glib_none().0, variant.to_glib_none().0) } } } pub fn load_from_path(path: &str) -> Re...
pub fn get_default() -> Self { unsafe { CssProvider { pointer: ffi::gtk_css_provider_get_default() } } }
random_line_split
css_provider.rs
// Copyright 2013-2015, 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 std::fmt::{self, Display, Formatter}; use ffi::{self, GtkCssProvider}; use glib::translat...
else { Err(glib::Error::wrap(error)) } } } } impl Display for CssProvider { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let tmp: String = unsafe { from_glib_full(ffi::gtk_css_provider_to_string(self.pointer)) }; write!(f, "{}", tmp) } } impl_GObj...
{ Ok(CssProvider { pointer: pointer }) }
conditional_block
manage_topics.js
/* Copyright (C) 2014 PencilBlue, LLC 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...
//none to manage if(topics.length === 0) { self.redirect('/admin/content/topics/new', cb); return; } //currently, mongo cannot do case-insensitive sorts. We do it manually //until a solution for https://jira.mongodb.org/browse/SERVER-90 is merged. to...
{ //TODO handle this }
conditional_block
manage_topics.js
/* Copyright (C) 2014 PencilBlue, LLC 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...
//inheritance util.inherits(ManageTopics, pb.BaseController); var SUB_NAV_KEY = 'manage_topics'; ManageTopics.prototype.render = function(cb) { var self = this; var dao = new pb.DAO(); dao.query('topic', pb.DAO.ANYWHERE, pb.DAO.PROJECT_ALL).then(function(topics) { if (util.isError(topics)) { //TODO handle ...
{}
identifier_body
manage_topics.js
/* Copyright (C) 2014 PencilBlue, LLC 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...
() {} //inheritance util.inherits(ManageTopics, pb.BaseController); var SUB_NAV_KEY = 'manage_topics'; ManageTopics.prototype.render = function(cb) { var self = this; var dao = new pb.DAO(); dao.query('topic', pb.DAO.ANYWHERE, pb.DAO.PROJECT_ALL).then(function(topics) { if (util.isError(topics)) { //TODO ha...
ManageTopics
identifier_name
manage_topics.js
/* Copyright (C) 2014 PencilBlue, LLC 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...
self.setPageName(self.ls.get('MANAGE_TOPICS')); self.ts.registerLocal('angular_objects', new pb.TemplateValue(angularObjects, false)); self.ts.load('admin/content/topics/manage_topics', function(err, data) { var result = '' + data; cb({content: result}); }); }); };...
{ navigation: pb.AdminNavigation.get(self.session, ['content', 'topics'], self.ls), pills: pb.AdminSubnavService.get(SUB_NAV_KEY, self.ls, SUB_NAV_KEY), topics: topics });
random_line_split
generic-tup.rs
// Copyright 2012 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 ...
info!("{:?}", get_third((1, 2, 3))); assert_eq!(get_third((1, 2, 3)), 3); assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8); }
fn get_third<T>(t: (T, T, T)) -> T { let (_, _, x) = t; return x; } pub fn main() {
random_line_split
generic-tup.rs
// Copyright 2012 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 ...
{ info!("{:?}", get_third((1, 2, 3))); assert_eq!(get_third((1, 2, 3)), 3); assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8); }
identifier_body
generic-tup.rs
// Copyright 2012 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 ...
() { info!("{:?}", get_third((1, 2, 3))); assert_eq!(get_third((1, 2, 3)), 3); assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8); }
main
identifier_name
admin.py
from django.contrib import admin try: from django.contrib.auth import get_permission_codename except ImportError: # pragma: no cover # Django < 1.6 def get_permission_codename(action, opts): return '%s_%s' % (action, opts.object_name.lower()) class ObjectPermissionsModelAdminMixin(object): d...
def has_delete_permission(self, request, obj=None): # pragma: no cover if self.opts.auto_created: return self.has_change_permission(request, obj) return super(ObjectPermissionsInlineModelAdminMixin, self).has_delete_permission(request, obj) class ObjectPermissionsModelAdmin(ObjectPe...
opts = self.opts if opts.auto_created: for field in opts.fields: if field.rel and field.rel.to != self.parent_model: opts = field.rel.to._meta break codename = get_permission_codename('change', opts) return request.user.has_perm...
identifier_body
admin.py
from django.contrib import admin try: from django.contrib.auth import get_permission_codename except ImportError: # pragma: no cover # Django < 1.6 def get_permission_codename(action, opts): return '%s_%s' % (action, opts.object_name.lower()) class ObjectPermissionsModelAdminMixin(object): d...
codename = get_permission_codename('change', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) def has_delete_permission(self, request, obj=None): # pragma: no cover if self.opts.auto_created: return self.has_change_permission(request, obj) ...
if field.rel and field.rel.to != self.parent_model: opts = field.rel.to._meta break
conditional_block
admin.py
from django.contrib import admin try: from django.contrib.auth import get_permission_codename except ImportError: # pragma: no cover # Django < 1.6 def
(action, opts): return '%s_%s' % (action, opts.object_name.lower()) class ObjectPermissionsModelAdminMixin(object): def has_change_permission(self, request, obj=None): opts = self.opts codename = get_permission_codename('change', opts) return request.user.has_perm('%s.%s' % (opts.a...
get_permission_codename
identifier_name
admin.py
from django.contrib import admin try: from django.contrib.auth import get_permission_codename except ImportError: # pragma: no cover # Django < 1.6 def get_permission_codename(action, opts): return '%s_%s' % (action, opts.object_name.lower()) class ObjectPermissionsModelAdminMixin(object): d...
pass
class ObjectPermissionsTabularInline(ObjectPermissionsInlineModelAdminMixin, admin.TabularInline):
random_line_split
setup.py
#!/usr/bin/env python """ responses ========= A utility library for mocking out the `requests` Python library. :copyright: (c) 2013 Dropbox, Inc. """ from setuptools import setup from setuptools.command.test import test as TestCommand import sys setup_requires = [] if 'test' in sys.argv: setup_requires.append(...
(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = ['test_responses.py'] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) ...
PyTest
identifier_name
setup.py
#!/usr/bin/env python """ responses ========= A utility library for mocking out the `requests` Python library. :copyright: (c) 2013 Dropbox, Inc. """ from setuptools import setup from setuptools.command.test import test as TestCommand import sys setup_requires = [] if 'test' in sys.argv: setup_requires.append(...
setup( name='responses', version='0.2.2', author='David Cramer', description=( 'A utility library for mocking out the `requests` Python library.' ), long_description=open('README.rst').read(), py_modules=['responses'], zip_safe=False, install_requires=install_requires, ...
import pytest errno = pytest.main(self.test_args) sys.exit(errno)
identifier_body
setup.py
#!/usr/bin/env python """ responses ========= A utility library for mocking out the `requests` Python library. :copyright: (c) 2013 Dropbox, Inc. """ from setuptools import setup from setuptools.command.test import test as TestCommand import sys setup_requires = [] if 'test' in sys.argv: setup_requires.append(...
'pytest-cov', 'flake8', ] class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = ['test_responses.py'] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pyt...
random_line_split
setup.py
#!/usr/bin/env python """ responses ========= A utility library for mocking out the `requests` Python library. :copyright: (c) 2013 Dropbox, Inc. """ from setuptools import setup from setuptools.command.test import test as TestCommand import sys setup_requires = [] if 'test' in sys.argv:
install_requires = [ 'requests', 'mock', 'six', ] tests_require = [ 'pytest', 'pytest-cov', 'flake8', ] class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = ['test_responses.py'] self.test_suite = True de...
setup_requires.append('pytest')
conditional_block
urls.py
from django.conf.urls import * from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # django-flags for internationalization (r'^lang/', include('sampleproject.flags.urls')),
(r'^$', 'sampleproject.sampleapp.views.home'), # home redirection (r'^.*home/$', 'django.views.generic.simple.redirect_to', {'url':'/'}), # login/logout (r'^logout/$', 'django.contrib.auth.views.logout'), (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name':'goflow/login.ht...
# FOR DEBUG AND TEST ONLY (r'^.*switch/(?P<username>.*)/(?P<password>.*)/$', 'goflow.workflow.views.debug_switch_user'), # home page
random_line_split
main_check_remaining.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Apr 27 12:16:26 2017 @author: Anand A Joshi, Divya Varadarajan """ import glob from os.path import isfile, split import configparser config_file = u'/big_disk/ajoshi/ABIDE2/study.cfg' Config = configparser.ConfigParser() Config.read(config_file) Conf...
# print img if not isfile(outsurfname): incom += 1 print outsurfname continue com += 1 print str(incom) + ' remaining ' + str(com) + ' done'
outsurfname = subpath + '/t1.heat_sol_comp.mat'
random_line_split
main_check_remaining.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Apr 27 12:16:26 2017 @author: Anand A Joshi, Divya Varadarajan """ import glob from os.path import isfile, split import configparser config_file = u'/big_disk/ajoshi/ABIDE2/study.cfg' Config = configparser.ConfigParser() Config.read(config_file) Conf...
print str(incom) + ' remaining ' + str(com) + ' done'
img = sub + '/anat/t1.roiwise.stats.txt' subpath, filename = split(img) outsurfname = subpath + '/t1.heat_sol_comp.mat' # print img if not isfile(outsurfname): incom += 1 print outsurfname continue com += 1
conditional_block
update_instances_utils.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
elif policy_type_str == 'proactive': return (messages.InstanceGroupManagerUpdatePolicy .TypeValueValuesEnum.PROACTIVE) raise exceptions.InvalidArgumentException(flag_name, 'unknown update policy.') def ValidateUpdateInstancesArgs(args): """Validates update arguments provided by the user. Arg...
return (messages.InstanceGroupManagerUpdatePolicy .TypeValueValuesEnum.OPPORTUNISTIC)
conditional_block
update_instances_utils.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
(flag_name, version_map, resources, messages): """Retrieves version from input map. Args: flag_name: name of the flag associated with the parsed string. version_map: map containing version data provided by the user. resources: provides reference for instance template resource. messages: module cont...
ParseVersion
identifier_name
update_instances_utils.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
raise exceptions.InvalidArgumentException(flag_name, 'unknown update policy.') def ValidateUpdateInstancesArgs(args): """Validates update arguments provided by the user. Args: args: arguments provided by the user. """ if args.action == 'restart': if args.version_original: raise exceptions.Inv...
elif policy_type_str == 'proactive': return (messages.InstanceGroupManagerUpdatePolicy .TypeValueValuesEnum.PROACTIVE)
random_line_split
update_instances_utils.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
"""Retrieves canary version from input map. Args: flag_name: name of the flag associated with the parsed string. version_map: map containing version data provided by the user. """ if version_map and TARGET_SIZE_NAME not in version_map: raise exceptions.RequiredArgumentException( '{} {}={}'.fo...
identifier_body
redux-api-middleware.d.ts
declare module "redux-api-middleware" { import {Middleware} from "redux"; /** * Symbol key that carries API call info interpreted by this Redux middleware. * * @constant {string} * @access public * @default */ export const RSAA: string; //// ERRORS /** *...
statusText: string; response?: any; } //// VALIDATION /** * Is the given action a plain JavaScript object with a [RSAA] property? */ export function isRSAA(action: object): action is RSAAction<any, any, any>; export interface TypeDescriptor<TSymbol> { type: stri...
name: string; message: string; status: number;
random_line_split
redux-api-middleware.d.ts
declare module "redux-api-middleware" { import {Middleware} from "redux"; /** * Symbol key that carries API call info interpreted by this Redux middleware. * * @constant {string} * @access public * @default */ export const RSAA: string; //// ERRORS /** *...
{ constructor(validationErrors: Array<string>); name: string; message: string; validationErrors: Array<string>; } /** * Error class for a custom `payload` or `meta` function throwing * * @class InternalError * @access public * @param {string} message -...
InvalidRSAA
identifier_name
setting.py
# -*- coding: utf-8 -*- import sae.const DEBUG = False SITE_TITLE = u"博客标题" SITE_SUB_TITLE = u"博客副标题" SITE_KEYWORDS = u"博客关键字" SITE_DECRIPTION = u"博客描述" AUTHOR_NAME = u"博客作者" #显示在RSS订阅里面 #CONACT_MAIL = "xxx@gmail.com" #暂未用到 THEMES = ['octopress','admin'] LINK_BROLL = [ {'text': u"爱简单吧", 'url': "http://www....
LANGUAGE = 'zh-CN' EACH_PAGE_POST_NUM = 10 #每页显示文章数 RECENT_POST_NUM = 10 #边栏显示最近文章数 RELATED_NUM = 10 #显示相关文章数 SIDER_TAG_NUM = 100 #边栏显示标签数 SIDER_CAT_NUM = 100 #边栏显示分类数 SHORTEN_CONTENT_WORDS = 150 #文章列表截取的字符数 DESCRIPTION_CUT_WORDS = 100 #meta description 显示的字符数 FEED_NUM = 10 #订阅输出文章数 #######下面是保存附件的空间,可选SAE Storage ...
JQUERY = "http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js" COOKIE_SECRET = "11orTzKXQAsaYdkL5gEtGeJJFuYh7EQnp2XdTP1o/Vo="
random_line_split
form.js
import React, { PropTypes } from 'react'; import Actions from '../../actions/lists'; import PageClick from 'react-page-click'; export default class ListForm extends React.Component { componentDidMount() { this.refs.name.focus(); } _handleSubmit(e) { e.preventDefault(); const { dispatch, channel, li...
(field) { const { errors } = this.props; if (!errors) return false; return errors.map((error, i) => { if (error[field]) { return ( <div key={i} className="error"> {error[field]} </div> ); } }); } _handleCancelClick(e) { e.preventDefa...
_renderErrors
identifier_name
form.js
import React, { PropTypes } from 'react'; import Actions from '../../actions/lists'; import PageClick from 'react-page-click'; export default class ListForm extends React.Component { componentDidMount() { this.refs.name.focus(); } _handleSubmit(e) { e.preventDefault(); const { dispatch, channel, li...
_handleCancelClick(e) { e.preventDefault(); this.props.onCancelClick(); } render() { const defaultValue = this.props.list ? this.props.list.name : ''; const buttonText = this.props.list ? 'Update list' : 'Save list'; return ( <PageClick onClick={::this._handleCancelClick}> ...
{ const { errors } = this.props; if (!errors) return false; return errors.map((error, i) => { if (error[field]) { return ( <div key={i} className="error"> {error[field]} </div> ); } }); }
identifier_body
form.js
import React, { PropTypes } from 'react'; import Actions from '../../actions/lists'; import PageClick from 'react-page-click'; export default class ListForm extends React.Component { componentDidMount() { this.refs.name.focus(); }
e.preventDefault(); const { dispatch, channel, list } = this.props; const { name } = this.refs; const data = { id: list ? list.id : null, name: name.value, }; dispatch(Actions.save(channel, data)); } _renderErrors(field) { const { errors } = this.props; if (!errors) ...
_handleSubmit(e) {
random_line_split
views.py
import logging from flask import abort from flask import Blueprint from flask import current_app from flask import flash from flask import redirect from flask import session from flask import url_for from testrail_reporting.auth.models import AuthUser from testrail_reporting.auth.oauth import get_google log = loggin...
google_token = resp['access_token'] session['google_token'] = (google_token, '') user_info = get_google().get('userinfo').data domain = user_info.get('hd', None) if domain != current_app.config['GOOGLE_APP_DOMAIN']: flash('Domain is not allowed') return redirect(url_for('pages.index...
random_line_split
views.py
import logging from flask import abort from flask import Blueprint from flask import current_app from flask import flash from flask import redirect from flask import session from flask import url_for from testrail_reporting.auth.models import AuthUser from testrail_reporting.auth.oauth import get_google log = loggin...
user_info.update({'google_token': google_token}) AuthUser.objects(email=user_info["email"]).update_one(upsert=True, **user_info) return redirect(url_for('pages.index')) @auth.route('/logout') def logout(): session.pop('google_token', None) ...
flash('Domain is not allowed') return redirect(url_for('pages.index'))
conditional_block
views.py
import logging from flask import abort from flask import Blueprint from flask import current_app from flask import flash from flask import redirect from flask import session from flask import url_for from testrail_reporting.auth.models import AuthUser from testrail_reporting.auth.oauth import get_google log = loggin...
(): resp = get_google().authorized_response() if resp is None: abort(401) google_token = resp['access_token'] session['google_token'] = (google_token, '') user_info = get_google().get('userinfo').data domain = user_info.get('hd', None) if domain != current_app.config['GOOGLE_APP_DO...
authorized
identifier_name
views.py
import logging from flask import abort from flask import Blueprint from flask import current_app from flask import flash from flask import redirect from flask import session from flask import url_for from testrail_reporting.auth.models import AuthUser from testrail_reporting.auth.oauth import get_google log = loggin...
session.pop('google_token', None) return redirect(url_for('pages.login'))
identifier_body
reconst_mapmri.py
""" ================================================================ Continuous and analytical diffusion signal modelling with MAPMRI ================================================================ We show how to model the diffusion signal as a linear combination of continuous functions from the MAPMRI basis [Ozarsla...
data contains the voxel data and gtab contains a GradientTable object (gradient information e.g. b-values). For example, to show the b-values it is possible to write print(gtab.bvals). Instantiate the MAPMRI Model. radial_order is the radial order of the MAPMRI basis. For details regarding the parameters see [Ozarsl...
"""
random_line_split
ivy-localize-merging.ts
/** * @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 { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { setupI18nCon...
}
}
random_line_split
ivy-localize-merging.ts
/** * @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 { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { setupI18nCon...
}
{ throw new Error('duplicate translations warning not shown'); }
conditional_block
twisted_test.py
(ReactorTestCase): def test_callLater(self): self._later1Called = False self._later2Called = False self._now = self._reactor.seconds() self._timeout1 = 0.0005 dc1 = self._reactor.callLater(self._timeout1, self.callLaterCallback1) self._timeout2 = 0.001 dc2 = s...
ReactorTwoCallLaterTest
identifier_name
twisted_test.py
writeOnce(fd): if self.shouldWrite: self.shouldWrite = False fd.write(b'x') self._reader = Reader(self._p1, checkReadInput) self._writer = Writer(self._p2, writeOnce) self._reactor.addWriter(self._writer) # Test that adding the reader twice ...
twisted_tests = { 'twisted.internet.test.test_core.ObjectModelIntegrationTest': [], 'twisted.internet.test.test_core.SystemEventTestsBuilder': [ 'test_iterate', # deliberately not supported # Fails on TwistedIOLoop and AsyncIOLoop. 'test_runAfterCrash', ], ...
conditional_block
twisted_test.py
() def writeOnce(fd): if self.shouldWrite: self.shouldWrite = False fd.write(b'x') self._reader = Reader(self._p1, checkReadInput) self._writer = Writer(self._p2, writeOnce) self._reactor.addWriter(self._writer) # Test that adding th...
'test_childConnectionLost',
random_line_split
twisted_test.py
Read(self): self._callback(self._fd) if have_twisted: Reader = implementer(IReadDescriptor)(Reader) class Writer(object): def __init__(self, fd, callback): self._fd = fd self._callback = callback def logPrefix(self): return "Writer" def close(self): self._fd.c...
if False: # inlineCallbacks doesn't work with regular functions; # must have a yield even if it's unreachable. yield returnValue(42)
identifier_body
incremental.rs
self.contains(REFLOW_OUT_OF_FLOW) { self | REFLOW } else { self } } _ => { // TODO(pcwalton): Take floatedness into account. self & (REPAINT | REFLOW) } } } } impl fm...
{ let self_base = flow::mut_base(self); self_base.restyle_damage.insert(RestyleDamage::rebuild_and_reflow()); self_base.restyle_damage.remove(RECONSTRUCT_FLOW); for kid in self_base.children.iter_mut() { kid.reflow_entire_document(); } }
identifier_body
incremental.rs
) } } /// Supposing the *parent* of a flow with the given `position` property has this damage, /// returns the damage that we should add to this flow. pub fn damage_for_child(self, parent_is_absolutely_positioned: bool, child_is_absolutely...
}
random_line_split
incremental.rs
_is_absolutely_positioned, child_is_absolutely_positioned) { (false, true) => { // Absolute children are out-of-flow and therefore insulated from changes. // // FIXME(pcwalton): Au contraire, if the containing block dimensions change! self & RE...
{ self_base.flags.insert(HAS_COUNTER_AFFECTING_CHILDREN) }
conditional_block
incremental.rs
ServoComputedValues; fn compute(old: Option<&Arc<ServoComputedValues>>, new: &ServoComputedValues) -> RestyleDamage { compute_damage(old, new) } /// Returns a bitmask that represents a flow that needs to be rebuilt and reflowed. /// /// Use this instead of `RestyleDamage::all()` because `Resty...
compute_layout_damage
identifier_name
__init__.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2010 Anso Labs, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); you may # ...
.. moduleauthor:: Andy Smith <andy@anarkystic.com> """ from exception import *
.. moduleauthor:: Devin Carlen <devin.carlen@gmail.com> .. moduleauthor:: Vishvananda Ishaya <vishvananda@yahoo.com> .. moduleauthor:: Joshua McKenty <joshua@cognition.ca> .. moduleauthor:: Manish Singh <yosh@gimp.org>
random_line_split
tensor_signature.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
(self): if self.is_sparse: return array_ops.sparse_placeholder(dtype=self.dtype) return array_ops.placeholder(dtype=self.dtype, shape=self.shape) def tensors_compatible(tensors, signatures): """Check that tensors are compatible with signatures. Args: tensors: Dict of `Tensor` objects or single ...
get_placeholder
identifier_name
tensor_signature.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
"""Creates TensorSignature objects for given tensors. Args: tensors: Dict of `Tensor` objects or single `Tensor`. Returns: Dict of `TensorSignature` objects or single `TensorSignature`. """ if isinstance(tensors, dict): return { key: TensorSignature(tensors[key]) for key in tensors} re...
def create_signatures(tensors):
random_line_split
tensor_signature.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
# Single tensor as input. if isinstance(signatures, dict): return False return TensorSignature(tensors).is_compatible_with(signatures) def create_signatures(tensors): """Creates TensorSignature objects for given tensors. Args: tensors: Dict of `Tensor` objects or single `Tensor`. Returns: ...
"""Check that tensors are compatible with signatures. Args: tensors: Dict of `Tensor` objects or single `Tensor` object. signatures: Dict of `TensorSignature` objects or single `TensorSignature` object. Returns: True if all tensors are compatible, False otherwise. """ # Dict of Ten...
identifier_body
tensor_signature.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
return True # Single tensor as input. if isinstance(signatures, dict): return False return TensorSignature(tensors).is_compatible_with(signatures) def create_signatures(tensors): """Creates TensorSignature objects for given tensors. Args: tensors: Dict of `Tensor` objects or single `Tensor`. ...
if key not in tensors: return False if not TensorSignature(tensors[key]).is_compatible_with(signatures[key]): return False
conditional_block
kik-browser-tests.ts
{ typeof user.username; // "string" typeof user.fullName; // "string" typeof user.firstName; // "string" typeof user.lastName; // "string" typeof user.pic; // "string" typeof user.thumbnail; // "string" } }); if (kik.hasPermission()) { // your webpage h...
() { // called when back button is pressed return false; // optionally cancel default behavior } kik.browser.back(handleBackButton); // handle back button kik.browser.unbindBack(handleBackButton); // unbind from handling back button kik.open("http://www.google.com/"); kik.open("https://pop.kik.com/"); ...
handleBackButton
identifier_name
kik-browser-tests.ts
typeof user.username; // "string" typeof user.fullName; // "string" typeof user.firstName; // "string" typeof user.lastName; // "string" typeof user.pic; // "string" typeof user.thumbnail; // "string" } }); if (kik.hasPermission()) { // your webpage has ...
// bind to event kik.on("message", eventHandler); // unbind from event kik.off("message", eventHandler); // bind to an event once (ignoring subsequent occurrences) kik.once("message", eventHandler); kik.trigger("message", { title : "Fake
{ // do something when event occurs }
identifier_body
kik-browser-tests.ts
{ typeof user.username; // "string" typeof user.fullName; // "string" typeof user.firstName; // "string" typeof user.lastName; // "string" typeof user.pic; // "string" typeof user.thumbnail; // "string" } }); if (kik.hasPermission()) { // your webpage h...
} }); kik.photo.get({ quality : 0.7 , // number between 0-1 minResults : 2 , // number between 1-25 maxResults : 25 , // number between 1-25 maxHeight : 1280 , // number in pixels between 0-1280 maxWidth : 1280 , // number in pixels between 0-1280 }, function (photos) { // do so...
random_line_split
kik-browser-tests.ts
typeof user.username; // "string" typeof user.fullName; // "string" typeof user.firstName; // "string" typeof user.lastName; // "string" typeof user.pic; // "string" typeof user.thumbnail; // "string" } }); if (kik.hasPermission()) { // your webpage has ...
}); kik.picker( "http://othersite.com/", { arbitrary : "request data" }, function (response) { // do something with the picked data! } ); if (kik.picker.reply) { // webpage was launched in "picker mode" // kik.picker.url === the url of the calling webpage // kik.picker.data === {...
{ // save failed }
conditional_block
make_current_guard.rs
use std::marker::PhantomData; use std::os::raw::c_void; use std::io; use winapi::shared::windef::{HDC, HGLRC}; use CreationError; use super::gl; /// A guard for when you want to make the context current. Destroying the guard restores the /// previously-current context. pub struct CurrentContextGuard<'a, 'b> { pre...
} impl<'a, 'b> Drop for CurrentContextGuard<'a, 'b> { fn drop(&mut self) { unsafe { gl::wgl::MakeCurrent(self.previous_hdc as *const c_void, self.previous_hglrc as *const c_void); } } }
{ let previous_hdc = gl::wgl::GetCurrentDC() as HDC; let previous_hglrc = gl::wgl::GetCurrentContext() as HGLRC; let result = gl::wgl::MakeCurrent(hdc as *const _, context as *const _); if result == 0 { return Err(CreationError::OsError(format!("wglMakeCurrent function faile...
identifier_body
make_current_guard.rs
use std::marker::PhantomData; use std::os::raw::c_void; use std::io; use winapi::shared::windef::{HDC, HGLRC}; use CreationError;
previous_hglrc: HGLRC, marker1: PhantomData<&'a ()>, marker2: PhantomData<&'b ()>, } impl<'a, 'b> CurrentContextGuard<'a, 'b> { pub unsafe fn make_current(hdc: HDC, context: HGLRC) -> Result<CurrentContextGuard<'a, 'b>, CreationError> { let previous_hdc = gl::...
use super::gl; /// A guard for when you want to make the context current. Destroying the guard restores the /// previously-current context. pub struct CurrentContextGuard<'a, 'b> { previous_hdc: HDC,
random_line_split
make_current_guard.rs
use std::marker::PhantomData; use std::os::raw::c_void; use std::io; use winapi::shared::windef::{HDC, HGLRC}; use CreationError; use super::gl; /// A guard for when you want to make the context current. Destroying the guard restores the /// previously-current context. pub struct CurrentContextGuard<'a, 'b> { pre...
Ok(CurrentContextGuard { previous_hdc: previous_hdc, previous_hglrc: previous_hglrc, marker1: PhantomData, marker2: PhantomData, }) } } impl<'a, 'b> Drop for CurrentContextGuard<'a, 'b> { fn drop(&mut self) { unsafe { gl::wgl...
{ return Err(CreationError::OsError(format!("wglMakeCurrent function failed: {}", format!("{}", io::Error::last_os_error())))); }
conditional_block
make_current_guard.rs
use std::marker::PhantomData; use std::os::raw::c_void; use std::io; use winapi::shared::windef::{HDC, HGLRC}; use CreationError; use super::gl; /// A guard for when you want to make the context current. Destroying the guard restores the /// previously-current context. pub struct
<'a, 'b> { previous_hdc: HDC, previous_hglrc: HGLRC, marker1: PhantomData<&'a ()>, marker2: PhantomData<&'b ()>, } impl<'a, 'b> CurrentContextGuard<'a, 'b> { pub unsafe fn make_current(hdc: HDC, context: HGLRC) -> Result<CurrentContextGuard<'a, 'b>, CreationError> ...
CurrentContextGuard
identifier_name
TransitionAnimation.tsx
/* * 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/. */ import React from 'react'; import { isEqual } from 'lodash'; export interface Props { animationClass: strin...
} public shouldComponentUpdate(nextProps: Props, nextState: State) { if (nextProps.changeVariable !== this.props.changeVariable) { return true; } if ((typeof nextProps.changeVariable === 'object' || typeof this.props.changeVariable === 'object' || (Array.isArray(nextProps.changeVariable)...
<div className={`${animationClass} ${containerClass}`}> {this.props.children} </div> );
random_line_split
TransitionAnimation.tsx
/* * 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/. */ import React from 'react'; import { isEqual } from 'lodash'; export interface Props { animationClass: strin...
if ((typeof nextProps.changeVariable === 'object' || typeof this.props.changeVariable === 'object' || (Array.isArray(nextProps.changeVariable) || Array.isArray(this.props.changeVariable))) && !isEqual(nextProps.changeVariable, this.props.changeVariable)) { return true; } if (nextSta...
{ return true; }
conditional_block
TransitionAnimation.tsx
/* * 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/. */ import React from 'react'; import { isEqual } from 'lodash'; export interface Props { animationClass: strin...
() { const animationClass = this.state.shouldPlayAnimation ? this.props.animationClass : ''; const containerClass = this.props.containerStyles ? this.props.containerStyles : ''; return ( <div className={`${animationClass} ${containerClass}`}> {this.props.children} </div> ); } pu...
render
identifier_name
utils.tsx
import {DateTimeObject, getDiffInMinutes, TWO_WEEKS} from 'app/components/charts/utils'; import {t} from 'app/locale'; import {GlobalSelection, NewQuery, Organization} from 'app/types'; import {escapeDoubleQuotes} from 'app/utils'; import {getUtcDateString} from 'app/utils/dates'; import EventView from 'app/utils/disco...
( selection: GlobalSelection, version: string, yAxis?: YAxis, eventType?: EventType, organization?: Organization, /** * Indicates that we're only interested in the current release. * This is useful for the event meta end point where we don't want * to include the other releases. */ currentOnly...
getReleaseEventView
identifier_name
utils.tsx
import {DateTimeObject, getDiffInMinutes, TWO_WEEKS} from 'app/components/charts/utils'; import {t} from 'app/locale'; import {GlobalSelection, NewQuery, Organization} from 'app/types'; import {escapeDoubleQuotes} from 'app/utils'; import {getUtcDateString} from 'app/utils/dates'; import EventView from 'app/utils/disco...
else { // TODO(tonyx): Delete this else once the feature flags are removed return EventView.fromSavedQuery({ ...baseQuery, fields: ['title', 'count()', 'event.type', 'issue', 'last_seen()'], query: stringifyQueryObject( new QueryResults([`release:${version}`, '...
{ const eventTypeFilter = eventType === 'all' ? '' : `event.type:${eventType}`; return EventView.fromSavedQuery({ ...baseQuery, query: stringifyQueryObject( new QueryResults([releaseFilter, eventTypeFilter].filter(Boolean)) ), }); }
conditional_block
utils.tsx
import {DateTimeObject, getDiffInMinutes, TWO_WEEKS} from 'app/components/charts/utils'; import {t} from 'app/locale'; import {GlobalSelection, NewQuery, Organization} from 'app/types'; import {escapeDoubleQuotes} from 'app/utils'; import {getUtcDateString} from 'app/utils/dates'; import EventView from 'app/utils/disco...
const baseQuery: Omit<NewQuery, 'query'> = { id: undefined, version: 2, name: `${t('Release')} ${formatVersion(version)}`, fields: [`count()`, toOther], orderby: toOtherAlias, range: period, environment: environments, projects, start: start ? getUtcDateString(start) : undefined, ...
random_line_split
utils.tsx
import {DateTimeObject, getDiffInMinutes, TWO_WEEKS} from 'app/components/charts/utils'; import {t} from 'app/locale'; import {GlobalSelection, NewQuery, Organization} from 'app/types'; import {escapeDoubleQuotes} from 'app/utils'; import {getUtcDateString} from 'app/utils/dates'; import EventView from 'app/utils/disco...
switch (yAxis) { case YAxis.FAILED_TRANSACTIONS: const statusFilters = ['ok', 'cancelled', 'unknown'].map( s => `!transaction.status:${s}` ); return EventView.fromSavedQuery({ ...baseQuery, query: stringifyQueryObject( new QueryResults( ['event.type...
{ const {projects, environments, datetime} = selection; const {start, end, period} = datetime; const releaseFilter = currentOnly ? `release:${version}` : ''; const toOther = `to_other(release,"${escapeDoubleQuotes(version)}",others,current)`; // this orderby ensures that the order is [others, current] const...
identifier_body