file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
issue-62307-match-ref-ref-forbidden-without-eq.rs
// RFC 1445 introduced `#[structural_match]`; this attribute must // appear on the `struct`/`enum` definition for any `const` used in a // pattern. // // This is our (forever-unstable) way to mark a datatype as having a
// Issue 62307 pointed out a case where the structural-match checking // was too shallow. #![warn(indirect_structural_match, nontrivial_structural_match)] // run-pass #[derive(Debug)] struct B(i32); // Overriding `PartialEq` to use this strange notion of "equality" exposes // whether `match` is using structural-equa...
// `PartialEq` implementation that is equivalent to recursion over its // substructure. This avoids (at least in the short term) any need to // resolve the question of what semantics is used for such matching. // (See RFC 1445 for more details and discussion.)
random_line_split
datatype-date-math.js
YUI.add('datatype-date-math', function (Y, NAME) { /** * Date Math submodule. * * @module datatype-date * @submodule datatype-date-math * @for Date */ var LANG = Y.Lang; Y.mix(Y.namespace("Date"), { /** * Checks whether a native JavaScript Date contains a valid value. * @for Date * @method isValidDate ...
/** * Adds a specified number of years to the given date. * @for Date * @method addYears * @param oDate {Date} The date to add years to. * @param numYears {Number} The number of years to add (can be negative) * @return {Date} A new Date with the specified number of years * added to the original date. ...
return newDate; },
random_line_split
github.com.js
if (Zepto.ajax.restore)
sinon.stub(Zepto, "ajax") .yieldsTo("success", { responseStatus : 200, responseDetails : null, responseData : { feed: { link : "http://github.com", title : "GitHub Public Timeline", entries : [ { title : "Croaky signed up", link ...
{ Zepto.ajax.restore(); }
conditional_block
github.com.js
if (Zepto.ajax.restore) { Zepto.ajax.restore(); } sinon.stub(Zepto, "ajax") .yieldsTo("success", { responseStatus : 200, responseDetails : null, responseData : { feed: { link : "http://github.com", title : "GitHub Public Timeline", entries : [ { title ...
] } } });
random_line_split
camera.py
"""Support for Axis camera streaming.""" from homeassistant.components.camera import SUPPORT_STREAM from homeassistant.components.mjpeg.camera import ( CONF_MJPEG_URL, CONF_STILL_IMAGE_URL, MjpegCamera, filter_urllib3_logging, ) from homeassistant.const import ( CONF_AUTHENTICATION, CONF_DEVICE...
return SUPPORT_STREAM async def stream_source(self): """Return the stream source.""" return AXIS_STREAM.format( self.device.config_entry.data[CONF_DEVICE][CONF_USERNAME], self.device.config_entry.data[CONF_DEVICE][CONF_PASSWORD], self.device.host, ...
random_line_split
camera.py
"""Support for Axis camera streaming.""" from homeassistant.components.camera import SUPPORT_STREAM from homeassistant.components.mjpeg.camera import ( CONF_MJPEG_URL, CONF_STILL_IMAGE_URL, MjpegCamera, filter_urllib3_logging, ) from homeassistant.const import ( CONF_AUTHENTICATION, CONF_DEVICE...
async def stream_source(self): """Return the stream source.""" return AXIS_STREAM.format( self.device.config_entry.data[CONF_DEVICE][CONF_USERNAME], self.device.config_entry.data[CONF_DEVICE][CONF_PASSWORD], self.device.host, ) def _new_address(self...
"""Return supported features.""" return SUPPORT_STREAM
identifier_body
camera.py
"""Support for Axis camera streaming.""" from homeassistant.components.camera import SUPPORT_STREAM from homeassistant.components.mjpeg.camera import ( CONF_MJPEG_URL, CONF_STILL_IMAGE_URL, MjpegCamera, filter_urllib3_logging, ) from homeassistant.const import ( CONF_AUTHENTICATION, CONF_DEVICE...
(hass, config_entry, async_add_entities): """Set up the Axis camera video stream.""" filter_urllib3_logging() serial_number = config_entry.data[CONF_MAC] device = hass.data[AXIS_DOMAIN][serial_number] config = { CONF_NAME: config_entry.data[CONF_NAME], CONF_USERNAME: config_entry.d...
async_setup_entry
identifier_name
arc-rw-write-mode-shouldnt-escape.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 ...
{ let x = ~arc::RWARC(1); let mut y = None; do x.write_downgrade |write_mode| { y = Some(write_mode); } y.get(); // Adding this line causes a method unification failure instead // do (&option::unwrap(y)).write |state| { assert!(*state == 1); } }
identifier_body
arc-rw-write-mode-shouldnt-escape.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 ...
() { let x = ~arc::RWARC(1); let mut y = None; do x.write_downgrade |write_mode| { y = Some(write_mode); } y.get(); // Adding this line causes a method unification failure instead // do (&option::unwrap(y)).write |state| { assert!(*state == 1); } }
main
identifier_name
arc-rw-write-mode-shouldnt-escape.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 ...
// do (&option::unwrap(y)).write |state| { assert!(*state == 1); } }
random_line_split
tasks.py
from __future__ import unicode_literals from alliance_auth.celeryapp import app from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from .models import MumbleUser from .manager import MumbleManager import logging logger = logging.getLogg...
return False @staticmethod def disable_mumble(): logger.info("Deleting all MumbleUser models") MumbleUser.objects.all().delete() @staticmethod @app.task(bind=True, name="mumble.update_groups") def update_groups(self, pk): user = User.objects.get(pk=pk) l...
@staticmethod def has_account(user): try: return user.mumble.username != '' except ObjectDoesNotExist:
random_line_split
tasks.py
from __future__ import unicode_literals from alliance_auth.celeryapp import app from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from .models import MumbleUser from .manager import MumbleManager import logging logger = logging.getLogg...
@staticmethod @app.task(name="mumble.update_all_groups") def update_all_groups(): logger.debug("Updating ALL mumble groups") for mumble_user in MumbleUser.objects.exclude(username__exact=''): MumbleTasks.update_groups.delay(mumble_user.user.pk)
user = User.objects.get(pk=pk) logger.debug("Updating mumble groups for user %s" % user) if MumbleTasks.has_account(user): groups = [] for group in user.groups.all(): groups.append(str(group.name)) if len(groups) == 0: groups.append('em...
identifier_body
tasks.py
from __future__ import unicode_literals from alliance_auth.celeryapp import app from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from .models import MumbleUser from .manager import MumbleManager import logging logger = logging.getLogg...
except: logger.exception("Mumble group sync failed for %s, retrying in 10 mins" % user) raise self.retry(countdown=60 * 10) logger.debug("Updated user %s mumble groups." % user) else: logger.debug("User %s does not have a mumble account, skipp...
raise Exception("Group sync failed")
conditional_block
tasks.py
from __future__ import unicode_literals from alliance_auth.celeryapp import app from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from .models import MumbleUser from .manager import MumbleManager import logging logger = logging.getLogg...
(self, pk): user = User.objects.get(pk=pk) logger.debug("Updating mumble groups for user %s" % user) if MumbleTasks.has_account(user): groups = [] for group in user.groups.all(): groups.append(str(group.name)) if len(groups) == 0: ...
update_groups
identifier_name
flat.ts
import { IterableX } from '../iterablex'; import { isIterable } from '../../util/isiterable'; import { MonoTypeOperatorFunction } from '../../interfaces'; export class FlattenIterable<TSource> extends IterableX<TSource> { private _source: Iterable<TSource>; private _depth: number; constructor(source: Iterable<T...
for (const item of source) { if (isIterable(item)) { for (const innerItem of this._flatten(item, depth - 1)) { yield innerItem; } } else { yield item; } } } [Symbol.iterator]() { return this._flatten(this._source, this._depth)[Symbol.iterator](); }...
{ for (const item of source) { yield item; } return undefined; }
conditional_block
flat.ts
import { IterableX } from '../iterablex'; import { isIterable } from '../../util/isiterable'; import { MonoTypeOperatorFunction } from '../../interfaces'; export class FlattenIterable<TSource> extends IterableX<TSource> { private _source: Iterable<TSource>; private _depth: number; constructor(source: Iterable<T...
}
random_line_split
flat.ts
import { IterableX } from '../iterablex'; import { isIterable } from '../../util/isiterable'; import { MonoTypeOperatorFunction } from '../../interfaces'; export class FlattenIterable<TSource> extends IterableX<TSource> { private _source: Iterable<TSource>; private _depth: number; constructor(source: Iterable<T...
<T>(depth = Infinity): MonoTypeOperatorFunction<T> { return function flattenOperatorFunction(source: Iterable<T>): IterableX<T> { return new FlattenIterable<T>(source, depth); }; }
flat
identifier_name
flat.ts
import { IterableX } from '../iterablex'; import { isIterable } from '../../util/isiterable'; import { MonoTypeOperatorFunction } from '../../interfaces'; export class FlattenIterable<TSource> extends IterableX<TSource> { private _source: Iterable<TSource>; private _depth: number; constructor(source: Iterable<T...
{ return function flattenOperatorFunction(source: Iterable<T>): IterableX<T> { return new FlattenIterable<T>(source, depth); }; }
identifier_body
dataset_matcher.py
import galaxy.model from logging import getLogger log = getLogger( __name__ ) ROLES_UNSET = object() INVALID_STATES = [ galaxy.model.Dataset.states.ERROR, galaxy.model.Dataset.states.DISCARDED ] class DatasetMatcher( object ): """ Utility class to aid DataToolParameter and similar classes in reasoning about...
formats = self.param.formats if hda.datatype.matches_any( formats ): return HdaDirectMatch( hda ) if not check_implicit_conversions: return False target_ext, converted_dataset = hda.find_conversion_destination( formats ) if target_ext: if conv...
return False
conditional_block
dataset_matcher.py
import galaxy.model from logging import getLogger log = getLogger( __name__ ) ROLES_UNSET = object() INVALID_STATES = [ galaxy.model.Dataset.states.ERROR, galaxy.model.Dataset.states.DISCARDED ] class DatasetMatcher( object ): """ Utility class to aid DataToolParameter and similar classes in reasoning about...
class HdaImplicitMatch( object ): """ Supplied HDA was a valid option directly (did not need to find implicit conversion). """ def __init__( self, hda, target_ext ): self.hda = hda self.target_ext = target_ext @property def implicit_conversion( self ): return True ...
""" Supplied HDA was a valid option directly (did not need to find implicit conversion). """ def __init__( self, hda ): self.hda = hda @property def implicit_conversion( self ): return False
identifier_body
dataset_matcher.py
import galaxy.model from logging import getLogger log = getLogger( __name__ ) ROLES_UNSET = object() INVALID_STATES = [ galaxy.model.Dataset.states.ERROR, galaxy.model.Dataset.states.DISCARDED ] class DatasetMatcher( object ): """ Utility class to aid DataToolParameter and similar classes in reasoning about...
# Lazily cache current_user_roles. if self.current_user_roles is ROLES_UNSET: self.current_user_roles = self.trans.get_current_user_roles() return self.trans.app.security_agent.can_access_dataset( self.current_user_roles, dataset ) class HdaDirectMatch( object ): """ Supplied H...
def __can_access_dataset( self, dataset ):
random_line_split
dataset_matcher.py
import galaxy.model from logging import getLogger log = getLogger( __name__ ) ROLES_UNSET = object() INVALID_STATES = [ galaxy.model.Dataset.states.ERROR, galaxy.model.Dataset.states.DISCARDED ] class DatasetMatcher( object ): """ Utility class to aid DataToolParameter and similar classes in reasoning about...
( self, hda, check_implicit_conversions=True, check_security=False ): """ Return False of this parameter can not be matched to a the supplied HDA, otherwise return a description of the match (either a HdaDirectMatch describing a direct match or a HdaImplicitMatch describing an implicit c...
valid_hda_match
identifier_name
motion.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/. */ //! Computed types for CSS values that are related to motion path. use crate::values::computed::Angle; use crate...
(auto: &bool, angle: &Angle) -> bool { *auto && angle.is_zero() } /// A computed offset-rotate. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToAnimatedZero, ToCss, ToResolvedValue, )] #[repr(C)] pub struct OffsetRotate { /// If ...
is_auto_zero_angle
identifier_name
motion.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/. */ //! Computed types for CSS values that are related to motion path. use crate::values::computed::Angle; use crate...
ToResolvedValue, )] #[repr(C)] pub struct OffsetRotate { /// If auto is false, this is a fixed angle which indicates a /// constant clockwise rotation transformation applied to it by this /// specified rotation angle. Otherwise, the angle will be added to /// the angle of the direction in layout. ...
ToAnimatedZero, ToCss,
random_line_split
motion.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/. */ //! Computed types for CSS values that are related to motion path. use crate::values::computed::Angle; use crate...
}
{ OffsetRotate { auto: true, angle: Zero::zero(), } }
identifier_body
mssdk.py
# # Copyright (c) 2001 - 2016 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 limitation the rights to use, copy, modify, merge...
def exists(env): return mssdk_exists() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
"""Add construction variables for an MS SDK to an Environment.""" mssdk_setup_env(env)
identifier_body
mssdk.py
# # Copyright (c) 2001 - 2016 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 limitation the rights to use, copy, modify, merge...
(env): """Add construction variables for an MS SDK to an Environment.""" mssdk_setup_env(env) def exists(env): return mssdk_exists() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
generate
identifier_name
mssdk.py
# # Copyright (c) 2001 - 2016 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 limitation the rights to use, copy, modify, merge...
from MSCommon import mssdk_exists, \ mssdk_setup_env def generate(env): """Add construction variables for an MS SDK to an Environment.""" mssdk_setup_env(env) def exists(env): return mssdk_exists() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab ta...
random_line_split
editor.ts
/* Top-level React component for an X Window
import { Launcher } from "./launcher"; import { set } from "smc-util/misc2"; import { terminal } from "../terminal-editor/editor"; export const x11 = { short: "X11", name: "X11", icon: "window-restore", component: X11, buttons: set([ "decrease_font_size", "increase_font_size", "set_zoom", "re...
*/ import { createEditor } from "../frame-tree/editor"; import { X11 } from "./x11";
random_line_split
lib.rs
//! //! # Conrod //! //! An easy-to-use, immediate-mode, 2D GUI library featuring a range of useful widgets. //! #![deny(missing_copy_implementations)] #![warn(missing_docs)] #[macro_use] extern crate bitflags; extern crate clock_ticks; extern crate elmesque; extern crate graphics; extern crate json_io; extern crate ...
// Handle the final ID. ( $prev_id:expr => ) => (); ///// Handle end cases that don't have a trailing comma. ///// // Handle a single ID without a trailing comma. ( $widget_id:ident ) => ( const $widget_id: $crate::WidgetId = 0; ); // Handle a single ID with some given step with...
() => ();
random_line_split
lib.rs
//! //! # Conrod //! //! An easy-to-use, immediate-mode, 2D GUI library featuring a range of useful widgets. //! #![deny(missing_copy_implementations)] #![warn(missing_docs)] #[macro_use] extern crate bitflags; extern crate clock_ticks; extern crate elmesque; extern crate graphics; extern crate json_io; extern crate ...
() { widget_ids! { A, B with 64, C with 32, D, E with 8, } assert_eq!(A, 0); assert_eq!(B, 1); assert_eq!(C, 66); assert_eq!(D, 99); assert_eq!(E, 100); }
test
identifier_name
lib.rs
//! //! # Conrod //! //! An easy-to-use, immediate-mode, 2D GUI library featuring a range of useful widgets. //! #![deny(missing_copy_implementations)] #![warn(missing_docs)] #[macro_use] extern crate bitflags; extern crate clock_ticks; extern crate elmesque; extern crate graphics; extern crate json_io; extern crate ...
{ widget_ids! { A, B with 64, C with 32, D, E with 8, } assert_eq!(A, 0); assert_eq!(B, 1); assert_eq!(C, 66); assert_eq!(D, 99); assert_eq!(E, 100); }
identifier_body
QuestionsPage.js
// Component: QuestionsPage import React from 'react'; import { Redirect } from 'react-router-dom'; import { Header, SubTitle } from 'styles/Layout'; import { QuestionCard, UnansweredList } from 'Questions/ui/dynamicRoutes'; const QuestionListCard = question => <QuestionCard {...question} />; const QuestionsPage = ...
<QuestionListCard key={question.id} {...question} /> ))} </ul> </> ); }; export default QuestionsPage;
</Header> {!completed && <UnansweredList unanswered={unanswered} />} <SubTitle className="subtitle">{questionnaire.subtitle}</SubTitle> <ul className="questions-list"> {list.map(question => (
random_line_split
QuestionsPage.js
// Component: QuestionsPage import React from 'react'; import { Redirect } from 'react-router-dom'; import { Header, SubTitle } from 'styles/Layout'; import { QuestionCard, UnansweredList } from 'Questions/ui/dynamicRoutes'; const QuestionListCard = question => <QuestionCard {...question} />; const QuestionsPage = ...
return ( <> <Header> <h1> Paitent Health Questionnaire <small>(PHQ-9)</small> </h1> </Header> {!completed && <UnansweredList unanswered={unanswered} />} <SubTitle className="subtitle">{questionnaire.subtitle}</SubTitle> <ul className="questions-list"> ...
{ return <Redirect to="/results" />; }
conditional_block
matrix-sqrt.py
""" https://en.wikipedia.org/wiki/Square_root_of_a_matrix B is the sqrt of a matrix A if B*B = A """ import numpy as np from scipy.linalg import sqrtm from scipy.stats import special_ortho_group def denman_beaver(A, n=50): Y = A Z = np.eye(len(A)) for i in range(n): Yn = 0.5*(Y + np.linalg.inv(...
# iteration methods above tend to fail on random and symmetric matrices test("random", gen_random_matrix, 5, 10) test("symmetric", gen_symmetric_matrix, 5, 10) # for rotation matrices, the iteration methods work test("rotation", gen_rotation_matrix, 5, 10)
print("Testing {} matrix".format(title)) for i in range(1, size): for j in range(iters): try: A = gen_matrix(i) d = np.linalg.det(A) Y, _ = denman_beaver(A) X = babylonian(A) Z = sqrtm(A) print("{}x{}...
identifier_body
matrix-sqrt.py
""" https://en.wikipedia.org/wiki/Square_root_of_a_matrix B is the sqrt of a matrix A if B*B = A """ import numpy as np from scipy.linalg import sqrtm from scipy.stats import special_ortho_group def
(A, n=50): Y = A Z = np.eye(len(A)) for i in range(n): Yn = 0.5*(Y + np.linalg.inv(Z)) Zn = 0.5*(Z + np.linalg.inv(Y)) Y = Yn Z = Zn return (Y, Z) def babylonian(A, n=50): X = np.eye(len(A)) for i in range(n): X = 0.5*(X + np.dot(A, np.linalg.inv(X))) ...
denman_beaver
identifier_name
matrix-sqrt.py
""" https://en.wikipedia.org/wiki/Square_root_of_a_matrix B is the sqrt of a matrix A if B*B = A """ import numpy as np from scipy.linalg import sqrtm from scipy.stats import special_ortho_group def denman_beaver(A, n=50): Y = A Z = np.eye(len(A)) for i in range(n): Yn = 0.5*(Y + np.linalg.inv(...
X = 0.5*(X + np.dot(A, np.linalg.inv(X))) return X def gen_random_matrix(n): return np.random.rand(n, n) def gen_rotation_matrix(n): return special_ortho_group.rvs(n)*np.random.randint(-100, 101) def gen_symmetric_matrix(n): A = np.random.randint(-10, 11, size=(n, n)) A = 0.5*(A + A.T) ...
X = np.eye(len(A)) for i in range(n):
random_line_split
matrix-sqrt.py
""" https://en.wikipedia.org/wiki/Square_root_of_a_matrix B is the sqrt of a matrix A if B*B = A """ import numpy as np from scipy.linalg import sqrtm from scipy.stats import special_ortho_group def denman_beaver(A, n=50): Y = A Z = np.eye(len(A)) for i in range(n): Yn = 0.5*(Y + np.linalg.inv(...
# iteration methods above tend to fail on random and symmetric matrices test("random", gen_random_matrix, 5, 10) test("symmetric", gen_symmetric_matrix, 5, 10) # for rotation matrices, the iteration methods work test("rotation", gen_rotation_matrix, 5, 10)
try: A = gen_matrix(i) d = np.linalg.det(A) Y, _ = denman_beaver(A) X = babylonian(A) Z = sqrtm(A) print("{}x{} matrix (det {})".format(i, i, d)) print(A) print("Denman Beaver") ...
conditional_block
Program.ts
/* Copyright 2016 Yuki KAN Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
this.save(); } } exists(id: number): boolean { return this.get(id) !== null; } findByQuery(query: object): ProgramItem[] { return sift(query, this._items); } findByServiceId(serviceId: number): ProgramItem[] { const items = []; ...
random_line_split
Program.ts
/* Copyright 2016 Yuki KAN Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
if (now > (program.startAt + program.duration)) { dropped = true; return; } this.add(new ProgramItem(program), true); }); if (dropped) { this.save(); } } private _save(): void { l...
{ dropped = true; return; }
conditional_block
Program.ts
/* Copyright 2016 Yuki KAN Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
get items(): ProgramItem[] { return this._items; } add(item: ProgramItem, firstAdd: boolean = false): void { if (this.get(item.id) !== null) { return; } const removedIds = []; if (firstAdd === false) { _.program.findConflic...
{ this._load(); setTimeout(this._gc.bind(this), this._programGCInterval); }
identifier_body
Program.ts
/* Copyright 2016 Yuki KAN Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
{ static get(id: number): ProgramItem { return _.program.get(id); } static exists(id: number): boolean { return _.program.exists(id); } static findByQuery(query: object): ProgramItem[] { return _.program.findByQuery(query); } static findByServiceId(...
Program
identifier_name
CalcLogitChoice.py
#----------------------------------------------------------------------------------------------------------------------------------------------------------------------# # Name: CalcLogitChoice # Purpose: Utilities for various calculations of different types of choice models. # a) CalcMultino...
lnSum = sumExp.copy() #Maybe there is a better way of doing the next 4 steps in 1 shot lnSum[sumExp == 0] = 0.000000001 lnSum = numpy.log(lnSum) lnSum[sumExp == 0] = -999 MatRefs[key[1]] = TreeDefn[key][0]*lnSum #---> Get ln sum of sublevel #Probability going down.....
MatRefs[code] = MatRefs[code]/TreeDefn[key][0] #---> scale the utility sumExp+=numpy.exp(MatRefs[code])
conditional_block
CalcLogitChoice.py
#----------------------------------------------------------------------------------------------------------------------------------------------------------------------# # Name: CalcLogitChoice # Purpose: Utilities for various calculations of different types of choice models. # a) CalcMultino...
(Utils, Po): ''' Utils = Updated delta utility matrices in a dictionary i.e delta of Uk (k = mode) ex. Utils = {'auto':mat1, 'transit':mat2, 'bike':mat3, 'walk':mat4} Po = Base probabilities in a dictionary ex. Po = {'auto':mat1, 'transit':mat2, 'bike':mat3, 'walk':mat4} ...
CalcPivotPoint
identifier_name
CalcLogitChoice.py
#----------------------------------------------------------------------------------------------------------------------------------------------------------------------# # Name: CalcLogitChoice # Purpose: Utilities for various calculations of different types of choice models. # a) CalcMultino...
## for code in sublevelmat_codes: ## ProbMats[code] = ProbMats[key[1]]*numpy.exp(MatRefs[code])/eU_total nSublevels = len(sublevelmat_codes) cumProb = 0 for i in xrange(nSublevels - 1): code = sublevelmat_codes[i] temp = numpy.exp(MatRefs[code])/e...
#print ([code, TreeDefn[key][0]]) eU_total+=numpy.exp(MatRefs[code]) eU_total[eU_total == 0] = 0.0001 #Avoid divide by 0 error
random_line_split
CalcLogitChoice.py
#----------------------------------------------------------------------------------------------------------------------------------------------------------------------# # Name: CalcLogitChoice # Purpose: Utilities for various calculations of different types of choice models. # a) CalcMultino...
#@profile def CalcNestedChoice(TreeDefn, MatRefs, numZn, getLogSumAccess = 0): ''' #TreeDefn = {(0,'ROOT'):[1.0,['AU', 'TR', 'AC']], # (1,'AU'):[0.992,['CD', 'CP']], # (1,'TR'):[0.992,['TB', 'TP']], # (1,'AC'):[0.992,['BK', 'WK']]} # #Key-> (Level...
''' Utils = Updated delta utility matrices in a dictionary i.e delta of Uk (k = mode) ex. Utils = {'auto':mat1, 'transit':mat2, 'bike':mat3, 'walk':mat4} Po = Base probabilities in a dictionary ex. Po = {'auto':mat1, 'transit':mat2, 'bike':mat3, 'walk':mat4} ''' Prob...
identifier_body
package_report.py
import sublime import sublime_plugin from ..core import oa_syntax, decorate_pkg_name from ..core import ReportGenerationThread from ...lib.packages import PackageList ###---------------------------------------------------------------------------- class PackageReportThread(ReportGenerationThread):
###---------------------------------------------------------------------------- class OverrideAuditPackageReportCommand(sublime_plugin.WindowCommand): """ Generate a tabular report of all installed packages and their state. """ def run(self, force_reuse=False): PackageReportThread(self.wind...
""" Generate a tabular report of all installed packages and their state. """ def _process(self): pkg_list = PackageList() pkg_counts = pkg_list.package_counts() title = "{} Total Packages".format(len(pkg_list)) t_sep = "=" * len(title) fmt = '{{:>{}}}'.format(len(st...
identifier_body
package_report.py
import sublime import sublime_plugin from ..core import oa_syntax, decorate_pkg_name from ..core import ReportGenerationThread from ...lib.packages import PackageList ###---------------------------------------------------------------------------- class PackageReportThread(ReportGenerationThread): """ Genera...
fmt = '{{:>{}}}'.format(len(str(max(pkg_counts)))) stats = ("{0} [S]hipped with Sublime\n" "{0} [I]nstalled (user) sublime-package files\n" "{0} [U]npacked in Packages\\ directory\n" "{0} Currently in ignored_packages\n" "{0} Installed ...
title = "{} Total Packages".format(len(pkg_list)) t_sep = "=" * len(title)
random_line_split
package_report.py
import sublime import sublime_plugin from ..core import oa_syntax, decorate_pkg_name from ..core import ReportGenerationThread from ...lib.packages import PackageList ###---------------------------------------------------------------------------- class PackageReportThread(ReportGenerationThread): """ Genera...
(self, force_reuse=False): PackageReportThread(self.window, "Generating Package Report", self.window.active_view(), force_reuse=force_reuse).start() ###---------------------------------------------------------------------------- #
run
identifier_name
package_report.py
import sublime import sublime_plugin from ..core import oa_syntax, decorate_pkg_name from ..core import ReportGenerationThread from ...lib.packages import PackageList ###---------------------------------------------------------------------------- class PackageReportThread(ReportGenerationThread): """ Genera...
result.extend([r_sep, ""]) self._set_content("OverrideAudit: Package Report", result, ":packages", oa_syntax("OA-PkgReport"), { "override_audit_report_packages": packages, "context_menu": "OverrideAuditReport.sublime-men...
packages[pkg_name] = pkg_info.status(detailed=False) result.append( "| {:<40} | [{:1}] | [{:1}] | [{:1}] |".format( decorate_pkg_name(pkg_info, name_only=True), "S" if pkg_info.shipped_path is not None else " ", "I" if pkg_info.ins...
conditional_block
learn-math.ts
import * as assert from 'assert'; import * as brain from '../index'; const LSTM = brain.recurrent.LSTM; const net = new LSTM(); // used to build list below // const mathProblemsSet = new Set(); // for (let i = 0; i < 10; i++) { // for (let j = 0; j < 10; j++) { // mathProblemsSet.add(`${i}+${j}=${i + j}`); // ...
'8+7=15', '7+9=16', '9+7=16', '8+8=16', '8+9=17', '9+8=17', '9+9=18' ]; net.train(mathProblems, { log: true, errorThresh: 0.03 }); let errors = 0; for (let i = 0; i < mathProblems.length; i++) { const input = mathProblems[i].split('=')[0] + '='; const output = net.run(input); const predictedMathPr...
'9+6=15', '7+7=14', '7+8=15',
random_line_split
learn-math.ts
import * as assert from 'assert'; import * as brain from '../index'; const LSTM = brain.recurrent.LSTM; const net = new LSTM(); // used to build list below // const mathProblemsSet = new Set(); // for (let i = 0; i < 10; i++) { // for (let j = 0; j < 10; j++) { // mathProblemsSet.add(`${i}+${j}=${i + j}`); // ...
console.log("Errors: " + errors / mathProblems.length);
{ const input = mathProblems[i].split('=')[0] + '='; const output = net.run(input); const predictedMathProblem = input + output; const error = mathProblems.indexOf(predictedMathProblem) <= -1 ? 1 : 0; errors += error; console.log(input + output + (error ? " - error" : "")); }
conditional_block
fake_operation_log.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
(**updates): db_operation_log = { "id": "36ea41b2-c358-48a7-9117-70cb7617410a", "project_id": "586cc6ce-e286-40bd-b2b5-dd32694d9944", "operation_type": "protect", "checkpoint_id": "dcb20606-ad71-40a3-80e4-ef0fafdad0c3", "plan_id": "cf56bd3e-97a7-4078-b6d5-f36246333fd9", ...
fake_db_operation_log
identifier_name
fake_operation_log.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
db_operation_log = { "id": "36ea41b2-c358-48a7-9117-70cb7617410a", "project_id": "586cc6ce-e286-40bd-b2b5-dd32694d9944", "operation_type": "protect", "checkpoint_id": "dcb20606-ad71-40a3-80e4-ef0fafdad0c3", "plan_id": "cf56bd3e-97a7-4078-b6d5-f36246333fd9", "provider_id":...
identifier_body
fake_operation_log.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
continue if field.nullable: db_operation_log[name] = None elif field.default != fields.UnspecifiedDefault: db_operation_log[name] = field.default else: raise Exception('db_operation_log needs help with %s.' % name) if updates: db_opera...
random_line_split
fake_operation_log.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
return db_operation_log
db_operation_log.update(updates)
conditional_block
test_shared_folders.py
from nxdrive.tests.common_unit_test import UnitTestCase from nxdrive.client import RemoteDocumentClient from nxdrive.client import LocalClient class TestSharedFolders(UnitTestCase): def test_move_sync_root_child_to_user_workspace(self):
"""See https://jira.nuxeo.com/browse/NXP-14870""" admin_remote_client = self.root_remote_client user1_workspace_path = ('/default-domain/UserWorkspaces/' 'nuxeoDriveTestUser-user-1') try: # Get remote and local clients remote_user1 = Remo...
identifier_body
test_shared_folders.py
from nxdrive.tests.common_unit_test import UnitTestCase from nxdrive.client import RemoteDocumentClient from nxdrive.client import LocalClient class TestSharedFolders(UnitTestCase): def test_move_sync_root_child_to_user_workspace(self): """See https://jira.nuxeo.com/browse/NXP-14870""" admin_rem...
if admin_remote_client.exists(user1_workspace_path): admin_remote_client.delete(user1_workspace_path, use_trash=False)
# Cleanup user1 personal workspace
random_line_split
test_shared_folders.py
from nxdrive.tests.common_unit_test import UnitTestCase from nxdrive.client import RemoteDocumentClient from nxdrive.client import LocalClient class TestSharedFolders(UnitTestCase): def
(self): """See https://jira.nuxeo.com/browse/NXP-14870""" admin_remote_client = self.root_remote_client user1_workspace_path = ('/default-domain/UserWorkspaces/' 'nuxeoDriveTestUser-user-1') try: # Get remote and local clients rem...
test_move_sync_root_child_to_user_workspace
identifier_name
test_shared_folders.py
from nxdrive.tests.common_unit_test import UnitTestCase from nxdrive.client import RemoteDocumentClient from nxdrive.client import LocalClient class TestSharedFolders(UnitTestCase): def test_move_sync_root_child_to_user_workspace(self): """See https://jira.nuxeo.com/browse/NXP-14870""" admin_rem...
admin_remote_client.delete(user1_workspace_path, use_trash=False)
conditional_block
touch.rs
// Copyright 2014 The sdl2-rs Developers. // // 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 a...
pub fn SDL_GetNumTouchFingers(touchID: SDL_TouchID) -> c_int; pub fn SDL_GetTouchFinger(touchID: SDL_TouchID, index: c_int) -> *SDL_Finger; }
pub fn SDL_GetTouchDevice(index: c_int) -> SDL_TouchID;
random_line_split
touch.rs
// Copyright 2014 The sdl2-rs Developers. // // 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 a...
{ pub id: SDL_FingerID, pub x: c_float, pub y: c_float, pub pressure: c_float, } pub static SDL_TOUCH_MOUSEID: Uint32 = -1; extern "C" { pub fn SDL_GetNumTouchDevices() -> c_int; pub fn SDL_GetTouchDevice(index: c_int) -> SDL_TouchID; pub fn SDL_GetNumTouchFingers(touchID: SDL_TouchID) ->...
SDL_Finger
identifier_name
HammerOfTheRighteous.js
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import Abilities from 'parser/core/modules/Abilities'...
extends Analyzer { static dependencies = { abilities: Abilities, spells: SpellUsable, }; activeSpell = SPELLS.HAMMER_OF_THE_RIGHTEOUS; _badCasts = 0; _casts = 0; constructor(props) { super(props); if (this.selectedCombatant.hasTalent(SPELLS.BLESSED_HAMMER_TALENT.id)) { this.activeSp...
HammerOfTheRighteous
identifier_name
HammerOfTheRighteous.js
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import Abilities from 'parser/core/modules/Abilities'...
suggestions(when) { when(this.badCastThreshold).addSuggestion((suggest, actual, recommended) => suggest( <> You should avoid casting <SpellLink id={this.activeSpell.id} /> while better spells (namely <SpellLink id={SPELLS.JUDGMENT_CAST_PROTECTION.id} /> and{' '} <Spel...
{ return { actual: this.badCastRatio, isGreaterThan: { minor: 0.1, average: 0.15, major: 0.25, }, style: 'percentage', }; }
identifier_body
HammerOfTheRighteous.js
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import Abilities from 'parser/core/modules/Abilities'...
Events.cast.by(SELECTED_PLAYER).spell(this.activeSpell), this._handleFiller, ); } _handleFiller(event) { const hadBetterSpell = !BETTER_SPELLS.every(this.spells.isOnCooldown.bind(this.spells)); if (hadBetterSpell) { this._badCasts += 1; } this._casts += 1; } get badCastR...
if (this.selectedCombatant.hasTalent(SPELLS.BLESSED_HAMMER_TALENT.id)) { this.activeSpell = SPELLS.BLESSED_HAMMER_TALENT; } this.addEventListener(
random_line_split
HammerOfTheRighteous.js
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import Abilities from 'parser/core/modules/Abilities'...
this.addEventListener( Events.cast.by(SELECTED_PLAYER).spell(this.activeSpell), this._handleFiller, ); } _handleFiller(event) { const hadBetterSpell = !BETTER_SPELLS.every(this.spells.isOnCooldown.bind(this.spells)); if (hadBetterSpell) { this._badCasts += 1; } this._ca...
{ this.activeSpell = SPELLS.BLESSED_HAMMER_TALENT; }
conditional_block
LivePanel.tsx
import React, { PureComponent } from 'react'; import { Unsubscribable, PartialObserver } from 'rxjs'; import { Alert, stylesFactory, Button, JSONFormatter, CustomScrollbar, CodeEditor } from '@grafana/ui'; import { GrafanaTheme, PanelProps, LiveChannelStatusEvent, isValidLiveChannelAddress, LiveChannelEvent, ...
(props: Props) { super(props); this.isValid = !!getGrafanaLiveSrv(); this.state = { changed: 0 }; } async componentDidMount() { this.loadChannel(); } componentWillUnmount() { if (this.subscription) { this.subscription.unsubscribe(); } } componentDidUpdate(prevProps: Props):...
constructor
identifier_name
LivePanel.tsx
import React, { PureComponent } from 'react'; import { Unsubscribable, PartialObserver } from 'rxjs'; import { Alert, stylesFactory, Button, JSONFormatter, CustomScrollbar, CodeEditor } from '@grafana/ui'; import { GrafanaTheme, PanelProps, LiveChannelStatusEvent, isValidLiveChannelAddress, LiveChannelEvent, ...
} streamObserver: PartialObserver<LiveChannelEvent> = { next: (event: LiveChannelEvent) => { if (isLiveChannelStatusEvent(event)) { this.setState({ status: event, changed: Date.now() }); } else if (isLiveChannelMessageEvent(event)) { this.setState({ message: event.message, changed:...
{ this.loadChannel(); }
conditional_block
LivePanel.tsx
import React, { PureComponent } from 'react'; import { Unsubscribable, PartialObserver } from 'rxjs'; import { Alert, stylesFactory, Button, JSONFormatter, CustomScrollbar, CodeEditor } from '@grafana/ui'; import { GrafanaTheme, PanelProps, LiveChannelStatusEvent, isValidLiveChannelAddress, LiveChannelEvent, ...
}); return; } if (isEqual(addr, this.state.addr)) { console.log('Same channel', this.state.addr); return; } const live = getGrafanaLiveSrv(); if (!live) { console.log('INVALID', addr); this.unsubscribe(); this.setState({ addr: undefined, }); ...
console.log('INVALID', addr); this.unsubscribe(); this.setState({ addr: undefined,
random_line_split
LivePanel.tsx
import React, { PureComponent } from 'react'; import { Unsubscribable, PartialObserver } from 'rxjs'; import { Alert, stylesFactory, Button, JSONFormatter, CustomScrollbar, CodeEditor } from '@grafana/ui'; import { GrafanaTheme, PanelProps, LiveChannelStatusEvent, isValidLiveChannelAddress, LiveChannelEvent, ...
return <pre>{JSON.stringify(message)}</pre>; } renderPublish(height: number) { const { options } = this.props; return ( <> <CodeEditor height={height - 32} language="json" value={options.json ? JSON.stringify(options.json, null, 2) : '{ }'} onBlur...
{ if (message instanceof StreamingDataFrame) { const data: PanelData = { series: applyFieldOverrides({ data: [message], theme: config.theme2, replaceVariables: (v: string) => v, fieldConfig: { defaults: {}, overrides: []...
identifier_body
deriving-meta-multiple.rs
// Copyright 2013-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-MI...
{ bar: uint, baz: int } fn hash<T: Hash>(_t: &T) {} pub fn main() { let a = Foo {bar: 4, baz: -3}; a == a; // check for PartialEq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness hash(&a); // check for Hash impl w/o testing its correctness }...
Foo
identifier_name
deriving-meta-multiple.rs
// Copyright 2013-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-MI...
pub fn main() { let a = Foo {bar: 4, baz: -3}; a == a; // check for PartialEq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness hash(&a); // check for Hash impl w/o testing its correctness }
{}
identifier_body
deriving-meta-multiple.rs
// Copyright 2013-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
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::hash::{Hash, SipHasher}; // testing multiple separate deriving attributes #[derive(PartialEq)] #[derive(Clone)] #[derive(Hash)] struct Foo { ...
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
preload-main.ts
import { ipcRenderer, webFrame } from 'electron'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { apiCmds, apiName } from '../common/api-interface'; import { i18n } from '../common/i18n-preload'; import './app-bridge'; import DownloadManager from './components/download-manager'; import ...
(words, callback) { const misspelled = words.filter((word) => { return ipcRenderer.sendSync(apiName.symphonyApi, { cmd: apiCmds.isMisspelled, word, }); }); callback(misspelled); }, }); // injects...
spellCheck
identifier_name
preload-main.ts
import { ipcRenderer, webFrame } from 'electron'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { apiCmds, apiName } from '../common/api-interface'; import { i18n } from '../common/i18n-preload'; import './app-bridge'; import DownloadManager from './components/download-manager'; import ...
webFrame.setSpellCheckProvider('en-US', { spellCheck(words, callback) { const misspelled = words.filter((word) => { return ipcRenderer.sendSync(apiName.symphonyApi, { cmd: apiCmds.isMisspelled, word, }); }); ...
{ // injects custom title bar const element = React.createElement(WindowsTitleBar); const div = document.createElement( 'div' ); document.body.appendChild(div); ReactDOM.render(element, div); document.body.classList.add('sda-title-bar'); }
conditional_block
preload-main.ts
import { ipcRenderer, webFrame } from 'electron'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { apiCmds, apiName } from '../common/api-interface'; import { i18n } from '../common/i18n-preload'; import './app-bridge';
import DownloadManager from './components/download-manager'; import MessageBanner from './components/message-banner'; import NetworkError from './components/network-error'; import SnackBar from './components/snack-bar'; import WindowsTitleBar from './components/windows-title-bar'; import { SSFApi } from './ssf-api'; i...
random_line_split
preload-main.ts
import { ipcRenderer, webFrame } from 'electron'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { apiCmds, apiName } from '../common/api-interface'; import { i18n } from '../common/i18n-preload'; import './app-bridge'; import DownloadManager from './components/download-manager'; import ...
, }); // injects snack bar snackBar.initSnackBar(); // injects download manager contents const downloadManager = new DownloadManager(); downloadManager.initDownloadManager(); // initialize red banner banner.initBanner(); banner.showBanner(false, 'error'); }); // When the window f...
{ const misspelled = words.filter((word) => { return ipcRenderer.sendSync(apiName.symphonyApi, { cmd: apiCmds.isMisspelled, word, }); }); callback(misspelled); }
identifier_body
userinfo.py
""" oauthlib.openid.connect.core.endpoints.userinfo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module is an implementation of userinfo endpoint. """ import json import logging from oauthlib.common import Request from oauthlib.oauth2.rfc6749 import errors from oauthlib.oauth2.rfc6749.endpoints.base imp...
"""Authorizes access to userinfo resource. """ def __init__(self, request_validator): self.bearer = BearerToken(request_validator, None, None, None) self.request_validator = request_validator BaseEndpoint.__init__(self) @catch_errors_and_unavailability def create_userinfo_respon...
identifier_body
userinfo.py
""" oauthlib.openid.connect.core.endpoints.userinfo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module is an implementation of userinfo endpoint. """ import json import logging from oauthlib.common import Request from oauthlib.oauth2.rfc6749 import errors from oauthlib.oauth2.rfc6749.endpoints.base imp...
body = json.dumps(claims) elif isinstance(claims, str): resp_headers = { 'Content-Type': 'application/jwt' } body = claims else: log.error('Userinfo return unknown response for %r.', request) raise errors.ServerErro...
log.error('Userinfo MUST have "sub" for %r.', request) raise errors.ServerError(status_code=500)
conditional_block
userinfo.py
""" oauthlib.openid.connect.core.endpoints.userinfo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module is an implementation of userinfo endpoint. """ import json import logging from oauthlib.common import Request from oauthlib.oauth2.rfc6749 import errors from oauthlib.oauth2.rfc6749.endpoints.base imp...
(self, request): """Ensure the request is valid. 5.3.1. UserInfo Request The Client sends the UserInfo Request using either HTTP GET or HTTP POST. The Access Token obtained from an OpenID Connect Authentication Request MUST be sent as a Bearer Token, per Section 2 of OAuth 2.0 ...
validate_userinfo_request
identifier_name
ur.js
/** * @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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { glo...
global.ng.common.locales['ur'] = [ 'ur', [['a', 'p'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'ہفتہ'], u, u ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ...
{ var i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; }
identifier_body
ur.js
/** * @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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { glo...
[ ['آدھی رات', 'صبح', 'دوپہر', 'سہ پہر', 'شام', 'رات'], u, [ 'آدھی رات', 'صبح میں', 'دوپہر میں', 'سہ پہر', 'شام میں', 'رات میں' ] ], [['آدھی رات', 'صبح', 'دوپہر', 'سہ پہر', 'شام', 'رات'], u, u], [ '00:00', ['04:00', '12:00'], ['12:00', '16:00']...
{'JPY': ['JP¥', '¥'], 'PKR': ['Rs'], 'THB': ['฿'], 'TWD': ['NT$']}, 'rtl', plural, [
random_line_split
ur.js
/** * @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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { glo...
(n) { var i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } global.ng.common.locales['ur'] = [ 'ur', [['a', 'p'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['اتوار'...
plural
identifier_name
MySqlDatabase.d.ts
import Context from "../../../../Context"; import Database from '../Database'; declare class MySqlDatabase extends Database { pool: any; constructor(data: any, parent?: any); deinit(): Promise<void>; getPool(): any; getConfig(): any; static Pool_getConnection(pool: any): Promise<any>;
begin(context: Context): Promise<void>; commit(context: Context): Promise<void>; rollback(context: Context, err: any): Promise<void>; static queryFormat(query: any, params?: {}): string; static typeCast(field: any, next: any): any; getTableList(): Promise<string[]>; getTableInfo(table: any):...
queryRows(context: Context, query: string, params?: any): Promise<any[]>; queryResult(context: any, query: any, params?: any): Promise<any>; _getRows(result: any, fields: any): any[];
random_line_split
MySqlDatabase.d.ts
import Context from "../../../../Context"; import Database from '../Database'; declare class
extends Database { pool: any; constructor(data: any, parent?: any); deinit(): Promise<void>; getPool(): any; getConfig(): any; static Pool_getConnection(pool: any): Promise<any>; queryRows(context: Context, query: string, params?: any): Promise<any[]>; queryResult(context: any, query: a...
MySqlDatabase
identifier_name
user.py
# -*- coding: utf-8 -*- from . import app, db from flask import request, g, session, redirect from Lotus.model.user import User from hashlib import md5 from Lotus.lib.msg_code import Msg import json @app.route('/user/login', methods=['POST']) def user_login(): email = request.form.get('email', None) psw = req...
identifier_body
user.py
# -*- coding: utf-8 -*- from . import app, db from flask import request, g, session, redirect from Lotus.model.user import User from hashlib import md5 from Lotus.lib.msg_code import Msg import json @app.route('/user/login', methods=['POST']) def user_login(): email = request.form.get('email', None) psw = req...
nds/page/<int:page>', methods=['GET']) def user_issues_send(userid, page): pass @app.route('/user/<int:userid>/issue/favours/page/<int:page>', methods=['GET']) def user_issues_favour(userid, page): pass @app.route('/user/<int:userid>/issue/favours/page/<int:page>', methods=['GET']) def user_messages(userid,...
r/<int:userid>/issue/se
conditional_block
user.py
# -*- coding: utf-8 -*- from . import app, db from flask import request, g, session, redirect from Lotus.model.user import User from hashlib import md5 from Lotus.lib.msg_code import Msg import json @app.route('/user/login', methods=['POST']) def user_login(): email = request.form.get('email', None) psw = req...
m.update(request.form.get('psw', User.CONST_DEFAULT_PASSWORD)) # 默认密码 u.psw = m.hexdigest() db.session.add(u) db.session.commit() except Exception as e: return '{"code":%d,"msg":$s}'.format(Msg['faild'], 'register faild') return '{"code":%d,"msg":$s}'.format(Msg['success...
m = md5()
random_line_split
user.py
# -*- coding: utf-8 -*- from . import app, db from flask import request, g, session, redirect from Lotus.model.user import User from hashlib import md5 from Lotus.lib.msg_code import Msg import json @app.route('/user/login', methods=['POST']) def user_login(): email = request.form.get('email', None) psw = req...
load avater if request.method == 'POST': pass else: pass @app.route('/user/<int:userid>/profile', methods=['GET']) def user_profile(userid): if session.get('userid'): result = { 'userid': g.user.userid, 'username': g.user.username, 'avatar': g.us...
support up
identifier_name
solution.py
class Solution: # @param prices, a list of integer # @return an integer def
(self, prices): if not prices: return 0 n = len(prices) m1 = [0] * n m2 = [0] * n max_profit1 = 0 min_price1 = prices[0] max_profit2 = 0 max_price2 = prices[-1] for i in range(n): max_profit1 = max(max_profit1, prices[i] - m...
maxProfit
identifier_name
solution.py
class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): if not prices: return 0 n = len(prices) m1 = [0] * n m2 = [0] * n max_profit1 = 0
max_profit2 = 0 max_price2 = prices[-1] for i in range(n): max_profit1 = max(max_profit1, prices[i] - min_price1) m1[i] = max_profit1 min_price1 = min(min_price1, prices[i]) for i in range(n): max_profit2 = max(max_profit2, max_price2 - pri...
min_price1 = prices[0]
random_line_split
solution.py
class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices):
if not prices: return 0 n = len(prices) m1 = [0] * n m2 = [0] * n max_profit1 = 0 min_price1 = prices[0] max_profit2 = 0 max_price2 = prices[-1] for i in range(n): max_profit1 = max(max_profit1, prices[i] - min_price1) m...
identifier_body
solution.py
class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): if not prices: return 0 n = len(prices) m1 = [0] * n m2 = [0] * n max_profit1 = 0 min_price1 = prices[0] max_profit2 = 0 max_price2...
for i in range(n): max_profit2 = max(max_profit2, max_price2 - prices[n - 1 - i]) m2[n - 1 - i] = max_profit2 max_price2 = max(max_price2, prices[n - 1 - i]) max_profit = 0 for i in range(n): max_profit = max(m1[i] + m2[i], max_profit) ret...
max_profit1 = max(max_profit1, prices[i] - min_price1) m1[i] = max_profit1 min_price1 = min(min_price1, prices[i])
conditional_block
Armory.tsx
import ItemGrid from 'app/armory/ItemGrid'; import { addCompareItem } from 'app/compare/actions'; import BungieImage, { bungieNetPath } from 'app/dim-ui/BungieImage'; import { DestinyTooltipText } from 'app/dim-ui/DestinyTooltipText'; import ElementIcon from 'app/dim-ui/ElementIcon'; import RichDestinyText from 'app/di...
<div>{t('MovePopup.Rewards')}</div> {item.pursuit.rewards.map((reward) => ( <Reward key={reward.itemHash} reward={reward} /> ))} </div> )} {item.pursuit?.questLineDescription && ( <p> <RichDestinyText tex...
</div> )} {defs.isDestiny2() && item.pursuit.rewards.length !== 0 && ( <div className={styles.section}>
random_line_split
gbb.py
# SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2018 Google, Inc # Written by Simon Glass <sjg@chromium.org> # # Support for a Chromium OS Google Binary Block, used to record read-only # information mostly used by firmware. from collections import OrderedDict from patman import command from binman.entry import E...
"""An entry which contains a Chromium OS Google Binary Block Properties / Entry arguments: - hardware-id: Hardware ID to use for this build (a string) - keydir: Directory containing the public keys to use - bmpblk: Filename containing images used by recovery Chromium OS uses a GBB to s...
identifier_body
gbb.py
# SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2018 Google, Inc # Written by Simon Glass <sjg@chromium.org> # # Support for a Chromium OS Google Binary Block, used to record read-only # information mostly used by firmware. from collections import OrderedDict from patman import command from binman.entry import E...
(self): gbb = 'gbb.bin' fname = tools.GetOutputFilename(gbb) if not self.size: self.Raise('GBB must have a fixed size') gbb_size = self.size bmpfv_size = gbb_size - 0x2180 if bmpfv_size < 0: self.Raise('GBB is too small (minimum 0x2180 bytes)') ...
ObtainContents
identifier_name
gbb.py
# SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2018 Google, Inc # Written by Simon Glass <sjg@chromium.org> # # Support for a Chromium OS Google Binary Block, used to record read-only # information mostly used by firmware. from collections import OrderedDict from patman import command from binman.entry import E...
def ObtainContents(self): gbb = 'gbb.bin' fname = tools.GetOutputFilename(gbb) if not self.size: self.Raise('GBB must have a fixed size') gbb_size = self.size bmpfv_size = gbb_size - 0x2180 if bmpfv_size < 0: self.Raise('GBB is too small (min...
self.gbb_flags |= value
conditional_block
gbb.py
# SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2018 Google, Inc # Written by Simon Glass <sjg@chromium.org> # # Support for a Chromium OS Google Binary Block, used to record read-only # information mostly used by firmware. from collections import OrderedDict from patman import command from binman.entry import E...
Properties / Entry arguments: - hardware-id: Hardware ID to use for this build (a string) - keydir: Directory containing the public keys to use - bmpblk: Filename containing images used by recovery Chromium OS uses a GBB to store various pieces of information, in particular the root...
random_line_split
test_addonconf.py
import sys import unittest sys.path.insert(0, "../src/build") import addonconf class AddonConfModuleTestCase(unittest.TestCase): def test_load(self): # act config = addonconf.load("configs/config.json") # assert self.assertEqual(config, None, "Wrong return value for not exists con...
if __name__ == '__main__': unittest.main()
correct_config = {'version': '0.1', 'xpi': {'theme': 'firefox-theme-test.xpi', 'package': 'firefox-test-@VERSION@.xpi', 'extension': 'firefox-extension-test.xpi'}, 'max-version': '31.0a1', 'directory-structure': {'shared-dir': 'chrome'}, 'min-version': '29.0'} # act config = addonconf.load("configs/con...
identifier_body
test_addonconf.py
import sys import unittest sys.path.insert(0, "../src/build") import addonconf class
(unittest.TestCase): def test_load(self): # act config = addonconf.load("configs/config.json") # assert self.assertEqual(config, None, "Wrong return value for not exists config") def test_load2(self): # act config = addonconf.load("configs/config.json.1") ...
AddonConfModuleTestCase
identifier_name