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
forecastqueryservice.d.ts
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class ForecastQu...
export type DateTime = string; export type Double = number; export type Filters = {[key: string]: AttributeValue}; export interface Forecast { /** * The forecast. The string of the string-to-array map is one of the following values: p10 p50 p90 */ Predictions?: Predictions; } expor...
/** * The forecast value. */ Value?: Double; }
random_line_split
lunet2.py
import DeepFried2 as df from .. import dfext def mknet(mkbn=lambda chan: df.BatchNormalization(chan, 0.95)): kw = dict(mkbn=mkbn) net = df.Sequential( # -> 128x48 df.SpatialConvolutionCUDNN(3, 64, (7,7), border='same', bias=None), dfext.resblock(64, **kw), df.PoolingCUDNN((2,2...
# Eq. to flatten + linear df.SpatialConvolutionCUDNN(128, 256, (4,1), bias=None), mkbn(256), df.ReLU(), df.StoreOut(df.SpatialConvolutionCUDNN(256, 128, (1,1))) ) net.emb_mod = net[-1] net.in_shape = (128, 48) net.scale_factor = (2*2*2*2*2, 2*2*2*2*3) print("Net h...
random_line_split
lunet2.py
import DeepFried2 as df from .. import dfext def mknet(mkbn=lambda chan: df.BatchNormalization(chan, 0.95)): kw = dict(mkbn=mkbn) net = df.Sequential( # -> 128x48 df.SpatialConvolutionCUDNN(3, 64, (7,7), border='same', bias=None), dfext.resblock(64, **kw), df.PoolingCUDNN((2,2...
(lunet2): newnet = lunet2[:-1] newnet.emb_mod = lunet2[-1] newnet.iou_mod = df.StoreOut(df.Sequential(df.SpatialConvolutionCUDNN(256, 1, (1,1)), df.Sigmoid())) newnet.add(df.RepeatInput(newnet.emb_mod, newnet.iou_mod)) newnet.embs_from_out = lambda out: out[0] newnet.ious_from_out = lambda out:...
add_piou
identifier_name
lunet2.py
import DeepFried2 as df from .. import dfext def mknet(mkbn=lambda chan: df.BatchNormalization(chan, 0.95)): kw = dict(mkbn=mkbn) net = df.Sequential( # -> 128x48 df.SpatialConvolutionCUDNN(3, 64, (7,7), border='same', bias=None), dfext.resblock(64, **kw), df.PoolingCUDNN((2,2...
newnet = lunet2[:-1] newnet.emb_mod = lunet2[-1] newnet.iou_mod = df.StoreOut(df.Sequential(df.SpatialConvolutionCUDNN(256, 1, (1,1)), df.Sigmoid())) newnet.add(df.RepeatInput(newnet.emb_mod, newnet.iou_mod)) newnet.embs_from_out = lambda out: out[0] newnet.ious_from_out = lambda out: out[1][:,0] ...
identifier_body
oauth-token-service.d.ts
import JwtTokenService, { JwtClaims } from './jwt-token-service'; export interface OAuthTokenConfig { name: string; urlTokenParameters?: { idToken: string; tokenType?: string; }; expireOffsetSeconds?: number; } export interface OAuthTokenData { token: string; tokenType: string; ...
jwtClaims?: JwtClaims; } export declare class OAuthTokenService { private jwtTokenService; config: OAuthTokenConfig; private tokenData; constructor(jwtTokenService: JwtTokenService); configure: (config: OAuthTokenConfig) => OAuthTokenConfig; createToken: (urlTokenData: any) => OAuthTokenData...
random_line_split
oauth-token-service.d.ts
import JwtTokenService, { JwtClaims } from './jwt-token-service'; export interface OAuthTokenConfig { name: string; urlTokenParameters?: { idToken: string; tokenType?: string; }; expireOffsetSeconds?: number; } export interface OAuthTokenData { token: string; tokenType: string; ...
{ private jwtTokenService; config: OAuthTokenConfig; private tokenData; constructor(jwtTokenService: JwtTokenService); configure: (config: OAuthTokenConfig) => OAuthTokenConfig; createToken: (urlTokenData: any) => OAuthTokenData; setToken: (data: OAuthTokenData) => OAuthTokenData; getTo...
OAuthTokenService
identifier_name
Gruntfile.js
module.exports = function (grunt) { grunt.loadNpmTasks("grunt-contrib-uglify"); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.initConfig({ uglify: { dev: { files: { 'app/js/app.min.js': ['app/js/app.js', 'app/...
grunt.registerTask("default", ['uglify', 'cssmin', 'karma']) };
configFile: 'karma.conf.js' } } });
random_line_split
skip_null_arguments_transform.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value}; /// Removes arguments with a `null` value. Th...
struct SkipNullArgumentsTransform; impl Transformer for SkipNullArgumentsTransform { const NAME: &'static str = "SkipNullArgumentsTransform"; const VISIT_ARGUMENTS: bool = true; const VISIT_DIRECTIVES: bool = true; fn transform_argument(&mut self, argument: &Argument) -> Transformed<Argument> { ...
{ SkipNullArgumentsTransform .transform_program(program) .replace_or_else(|| program.clone()) }
identifier_body
skip_null_arguments_transform.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value}; /// Removes arguments with a `null` value. Th...
}
}
random_line_split
skip_null_arguments_transform.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value}; /// Removes arguments with a `null` value. Th...
(program: &Program) -> Program { SkipNullArgumentsTransform .transform_program(program) .replace_or_else(|| program.clone()) } struct SkipNullArgumentsTransform; impl Transformer for SkipNullArgumentsTransform { const NAME: &'static str = "SkipNullArgumentsTransform"; const VISIT_ARGUMENTS...
skip_null_arguments_transform
identifier_name
skip_null_arguments_transform.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use graphql_ir::{Argument, ConstantValue, Program, Transformed, Transformer, Value}; /// Removes arguments with a `null` value. Th...
else { Transformed::Keep } } }
{ Transformed::Delete }
conditional_block
command.rs
use std::error; use clap; use crate::config; use super::executer::Executer; use super::{Arguments, Program}; pub struct Command<'c> { config: &'c config::command::Config, program: Program<'c>, args: Arguments<'c>, } impl<'c> Command<'c> { pub fn from_args( config: &'c config::command::Confi...
}
{ trace!("command::params::exec::Command::run"); if let Some(params_config) = self.config.params.as_ref() { let exec = Executer::from_config(params_config); exec.run(&self.program, &self.args).await?; } Ok(()) }
identifier_body
command.rs
use std::error; use clap; use crate::config; use super::executer::Executer; use super::{Arguments, Program}; pub struct Command<'c> { config: &'c config::command::Config, program: Program<'c>, args: Arguments<'c>, } impl<'c> Command<'c> { pub fn from_args( config: &'c config::command::Confi...
(&self) -> Result<(), Box<dyn error::Error>> { trace!("command::params::exec::Command::run"); if let Some(params_config) = self.config.params.as_ref() { let exec = Executer::from_config(params_config); exec.run(&self.program, &self.args).await?; } Ok(()) } }
run
identifier_name
command.rs
use std::error; use clap; use crate::config; use super::executer::Executer; use super::{Arguments, Program}; pub struct Command<'c> { config: &'c config::command::Config, program: Program<'c>, args: Arguments<'c>, } impl<'c> Command<'c> { pub fn from_args( config: &'c config::command::Confi...
} Ok(()) } }
pub async fn run(&self) -> Result<(), Box<dyn error::Error>> { trace!("command::params::exec::Command::run"); if let Some(params_config) = self.config.params.as_ref() { let exec = Executer::from_config(params_config); exec.run(&self.program, &self.args).await?;
random_line_split
rsa.py
# Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>. # All rights reserved. # # This program and the accompanying materials are made available under # the terms of the Eclipse Public License v1.0 which accompanies this # distribution and is available at: # # http://www.eclipse.org/legal/epl-v10.html # #...
: def __init__(self, n, e, d, p, q): self.n = n self.e = e self.d = d self.p = p self.q = q dmp1 = rsa_crt_dmp1(d, p) dmq1 = rsa_crt_dmq1(d, q) iqmp = rsa_crt_iqmp(p, q) pub = RSAPublicNumbers(e, n) priv = RSAPrivateNumbers(p, q, d, d...
RSAPrivateKey
identifier_name
rsa.py
# Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>. # All rights reserved. # # This program and the accompanying materials are made available under # the terms of the Eclipse Public License v1.0 which accompanies this # distribution and is available at: # # http://www.eclipse.org/legal/epl-v10.html # #...
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateNumbers from cryptography.hazmat.primitives.asymmetric.rsa import rsa_crt_dmp1 from cryptography.hazmat.primitives.asymmetric.rsa import rsa_crt_dmq1 from cryptography.hazmat.primitives.asymmetric.rsa import rsa_crt_iqmp class RSAPrivateKey: def ...
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers
random_line_split
rsa.py
# Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>. # All rights reserved. # # This program and the accompanying materials are made available under # the terms of the Eclipse Public License v1.0 which accompanies this # distribution and is available at: # # http://www.eclipse.org/legal/epl-v10.html # #...
def verify(self, data, sig): verifier = self._key.verifier(sig, PKCS1v15(), SHA1()) verifier.update(data) try: verifier.verify() return True except InvalidSignature: return False
self.n = n self.e = e self._key = RSAPublicNumbers(e, n).public_key(default_backend())
identifier_body
0003_auto__del_field_campaign_photo__add_field_campaign_image.py
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Campaign.photo'
def backwards(self, orm): # Adding field 'Campaign.photo' db.add_column(u'campaign_campaign', 'photo', self.gf('cloudinary.models.CloudinaryField')(default=0, max_length=100), keep_default=False) # Deleting field 'Campaign.image' db.del...
db.delete_column(u'campaign_campaign', 'photo') # Adding field 'Campaign.image' db.add_column(u'campaign_campaign', 'image', self.gf('cloudinary.models.CloudinaryField')(default=0, max_length=100), keep_default=False)
identifier_body
0003_auto__del_field_campaign_photo__add_field_campaign_image.py
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Campaign.photo' db.delete_column(u'campaign_campaign', 'photo') # Addi...
random_line_split
0003_auto__del_field_campaign_photo__add_field_campaign_image.py
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def
(self, orm): # Deleting field 'Campaign.photo' db.delete_column(u'campaign_campaign', 'photo') # Adding field 'Campaign.image' db.add_column(u'campaign_campaign', 'image', self.gf('cloudinary.models.CloudinaryField')(default=0, max_length=100), ...
forwards
identifier_name
time.rs
use core::cmp::Ordering; use core::ops::{Add, Sub}; pub const NANOS_PER_MICRO: i32 = 1000; pub const NANOS_PER_MILLI: i32 = 1000000; pub const NANOS_PER_SEC: i32 = 1000000000; /// A duration #[derive(Copy, Clone)] pub struct Duration { /// The seconds pub secs: i64, /// The nano seconds pub nanos: i32...
(self, other: Self) -> Self { Duration::new(self.secs + other.secs, self.nanos + other.nanos) } } impl Sub for Duration { type Output = Duration; fn sub(self, other: Self) -> Self { Duration::new(self.secs - other.secs, self.nanos - other.nanos) } } impl PartialEq for Duration { f...
add
identifier_name
time.rs
use core::cmp::Ordering; use core::ops::{Add, Sub}; pub const NANOS_PER_MICRO: i32 = 1000; pub const NANOS_PER_MILLI: i32 = 1000000; pub const NANOS_PER_SEC: i32 = 1000000000; /// A duration #[derive(Copy, Clone)] pub struct Duration { /// The seconds pub secs: i64, /// The nano seconds pub nanos: i32...
} while nanos < 0 && secs > 0 { secs -= 1; nanos += NANOS_PER_SEC; } Duration { secs: secs, nanos: nanos, } } /// Get the current duration pub fn monotonic() -> Self { ::env().clock_monotonic.lock().clone() ...
/// Create a new duration pub fn new(mut secs: i64, mut nanos: i32) -> Self { while nanos >= NANOS_PER_SEC || (nanos > 0 && secs < 0) { secs += 1; nanos -= NANOS_PER_SEC;
random_line_split
time.rs
use core::cmp::Ordering; use core::ops::{Add, Sub}; pub const NANOS_PER_MICRO: i32 = 1000; pub const NANOS_PER_MILLI: i32 = 1000000; pub const NANOS_PER_SEC: i32 = 1000000000; /// A duration #[derive(Copy, Clone)] pub struct Duration { /// The seconds pub secs: i64, /// The nano seconds pub nanos: i32...
/// Get the current duration pub fn monotonic() -> Self { ::env().clock_monotonic.lock().clone() } /// Get the realtime pub fn realtime() -> Self { ::env().clock_realtime.lock().clone() } } impl Add for Duration { type Output = Duration; fn add(self, other: Self) -> ...
{ while nanos >= NANOS_PER_SEC || (nanos > 0 && secs < 0) { secs += 1; nanos -= NANOS_PER_SEC; } while nanos < 0 && secs > 0 { secs -= 1; nanos += NANOS_PER_SEC; } Duration { secs: secs, nanos: nanos, ...
identifier_body
time.rs
use core::cmp::Ordering; use core::ops::{Add, Sub}; pub const NANOS_PER_MICRO: i32 = 1000; pub const NANOS_PER_MILLI: i32 = 1000000; pub const NANOS_PER_SEC: i32 = 1000000000; /// A duration #[derive(Copy, Clone)] pub struct Duration { /// The seconds pub secs: i64, /// The nano seconds pub nanos: i32...
} }
{ Some(Ordering::Equal) }
conditional_block
crisis-center.routing.ts
// #docplaster // #docregion import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { CrisisCenterHomeComponent } from './crisis-center-home.component'; import { CrisisListComponent } from './crisis-list.component'; import { CrisisCenterComponent } ...
component: CrisisDetailComponent, canDeactivate: [CanDeactivateGuard], resolve: { crisis: CrisisDetailResolve } }, { path: '', component: CrisisCenterHomeComponent } ] } ] } ]; export...
component: CrisisListComponent, children: [ { path: ':id',
random_line_split
index.js
/* global Flash */ export default class
{ constructor() { this.switcher = document.querySelector('.js-blob-viewer-switcher'); this.switcherBtns = document.querySelectorAll('.js-blob-viewer-switch-btn'); this.copySourceBtn = document.querySelector('.js-copy-blob-source-btn'); this.simpleViewer = document.querySelector('.blob-viewer[data-typ...
BlobViewer
identifier_name
index.js
/* global Flash */ export default class BlobViewer { constructor() { this.switcher = document.querySelector('.js-blob-viewer-switcher'); this.switcherBtns = document.querySelectorAll('.js-blob-viewer-switch-btn'); this.copySourceBtn = document.querySelector('.js-copy-blob-source-btn'); this.simpleView...
} else if (this.activeViewer === this.simpleViewer) { this.copySourceBtn.setAttribute('title', 'Wait for the source to load to copy it to the clipboard'); this.copySourceBtn.classList.add('disabled'); } else { this.copySourceBtn.setAttribute('title', 'Switch to the source to copy it to the cli...
if (!this.copySourceBtn) return; if (this.simpleViewer.getAttribute('data-loaded')) { this.copySourceBtn.setAttribute('title', 'Copy source to clipboard'); this.copySourceBtn.classList.remove('disabled');
random_line_split
index.js
/* global Flash */ export default class BlobViewer { constructor() { this.switcher = document.querySelector('.js-blob-viewer-switcher'); this.switcherBtns = document.querySelectorAll('.js-blob-viewer-switch-btn'); this.copySourceBtn = document.querySelector('.js-copy-blob-source-btn'); this.simpleView...
viewer.setAttribute('data-loading', 'true'); $.ajax({ url, dataType: 'JSON', }) .fail(() => new Flash('Error loading source view')) .done((data) => { viewer.innerHTML = data.html; $(viewer).syntaxHighlight(); viewer.setAttribute('data-loaded', 'true'); this.$...
{ return; }
conditional_block
index.js
/* global Flash */ export default class BlobViewer { constructor() { this.switcher = document.querySelector('.js-blob-viewer-switcher'); this.switcherBtns = document.querySelectorAll('.js-blob-viewer-switch-btn'); this.copySourceBtn = document.querySelector('.js-copy-blob-source-btn'); this.simpleView...
loadViewer(viewerParam) { const viewer = viewerParam; const url = viewer.getAttribute('data-url'); if (!url || viewer.getAttribute('data-loaded') || viewer.getAttribute('data-loading')) { return; } viewer.setAttribute('data-loading', 'true'); $.ajax({ url, dataType: 'JSO...
{ if (!this.copySourceBtn) return; if (this.simpleViewer.getAttribute('data-loaded')) { this.copySourceBtn.setAttribute('title', 'Copy source to clipboard'); this.copySourceBtn.classList.remove('disabled'); } else if (this.activeViewer === this.simpleViewer) { this.copySourceBtn.setAttrib...
identifier_body
_calculate_exchange_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
begin_post.metadata = {'url': '/providers/Microsoft.Capacity/calculateExchange'} # type: ignore
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
conditional_block
_calculate_exchange_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
:ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.reservations.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deseria...
random_line_split
_calculate_exchange_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(body, 'CalculateExchangeRequest') body_content_kwargs['content'] = body_content request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = a...
cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.CalculateExchangeOperationResultResponse"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-...
identifier_body
_calculate_exchange_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
( self, body: "_models.CalculateExchangeRequest", **kwargs: Any ) -> AsyncLROPoller["_models.CalculateExchangeOperationResultResponse"]: """Calculates the refund amounts and price of the new purchases. Calculates price for exchanging ``Reservations`` if there are no policy e...
begin_post
identifier_name
array.ts
import { Subscription, StreamOps } from './index' declare module '.' { interface S_<A> { 'ArrayStream': Array<A> } } declare module '../fantasy/typeclasses' { interface _<A> { 'ArrayStream': Array<A> } } StreamOps.prototype.empty = function() { return [] } StreamOps.prototype.just = function(a) { ...
return [p.valueOf()] } StreamOps.prototype.from = function(fa) { return [fa.valueOf()] }
{ throw Error("You're not using real Promise aren't you, expecting Id Monad") }
conditional_block
array.ts
import { Subscription, StreamOps } from './index' declare module '.' { interface S_<A> { 'ArrayStream': Array<A> } } declare module '../fantasy/typeclasses' { interface _<A> { 'ArrayStream': Array<A> } } StreamOps.prototype.empty = function() { return [] } StreamOps.prototype.just = function(a) { ...
() { } Subject.prototype = Array.prototype Subject.prototype.next = function(a: any) { this.push(a) } Subject.prototype.complete = function() { } StreamOps.prototype.subject = function <A>() { return new (<any>Subject)() } StreamOps.prototype.subscribe = function <A>(fa: Array<A>, next: (v: A) => void, complete...
Subject
identifier_name
array.ts
import { Subscription, StreamOps } from './index' declare module '.' { interface S_<A> { 'ArrayStream': Array<A> } } declare module '../fantasy/typeclasses' { interface _<A> { 'ArrayStream': Array<A> } } StreamOps.prototype.empty = function() { return [] } StreamOps.prototype.just = function(a) { ...
Subject.prototype = Array.prototype Subject.prototype.next = function(a: any) { this.push(a) } Subject.prototype.complete = function() { } StreamOps.prototype.subject = function <A>() { return new (<any>Subject)() } StreamOps.prototype.subscribe = function <A>(fa: Array<A>, next: (v: A) => void, complete?: () =...
}
random_line_split
array.ts
import { Subscription, StreamOps } from './index' declare module '.' { interface S_<A> { 'ArrayStream': Array<A> } } declare module '../fantasy/typeclasses' { interface _<A> { 'ArrayStream': Array<A> } } StreamOps.prototype.empty = function() { return [] } StreamOps.prototype.just = function(a) { ...
Subject.prototype = Array.prototype Subject.prototype.next = function(a: any) { this.push(a) } Subject.prototype.complete = function() { } StreamOps.prototype.subject = function <A>() { return new (<any>Subject)() } StreamOps.prototype.subscribe = function <A>(fa: Array<A>, next: (v: A) => void, complete?: () ...
{ }
identifier_body
ai_qoff_player.rs
.01; //minimum NN LR const MOM:f64 = 0.05; //neural net momentum const EPOCHS_PER_STEP:u32 = 10; //epochs to learn from each turn/game const RND_PICK_START:f64 = 1.0f64; //exploration factor start const RND_PICK_DEC:f64 = 20000f64; //random exploration decrease (half every DEC games) const LEARNING_SET:i32 = 100; //num...
for (i, val) in field.get_field().iter().enumerate() { //2 nodes for every square: -1 enemy, 0 free, 1 own; 0 square will not be reached with one move, 1 square can be directly filled if *val == p { input.push(1f64); input.push(0f64); } else if *val == op { input.push(-1f64); input.push(0f64); } else { ...
random_line_split
ai_qoff_player.rs
.01; //minimum NN LR const MOM:f64 = 0.05; //neural net momentum const EPOCHS_PER_STEP:u32 = 10; //epochs to learn from each turn/game const RND_PICK_START:f64 = 1.0f64; //exploration factor start const RND_PICK_DEC:f64 = 20000f64; //random exploration decrease (half every DEC games) const LEARNING_SET:i32 = 100; //num...
//perform action res = field.play(self.pid, x); //save play data if not fixed, but learn if move did not was rule-conform if !self.fixed || !res { //calculate q update or collect data for later learn if !res { qval[x as usize] = 0f64; } //invalid play instant learn else { qval[x as u...
{ x = rng.gen::<u32>() % field.get_w(); }
conditional_block
ai_qoff_player.rs
01; //minimum NN LR const MOM:f64 = 0.05; //neural net momentum const EPOCHS_PER_STEP:u32 = 10; //epochs to learn from each turn/game const RND_PICK_START:f64 = 1.0f64; //exploration factor start const RND_PICK_DEC:f64 = 20000f64; //random exploration decrease (half every DEC games) const LEARNING_SET:i32 = 100; //numb...
(&self) -> f64 { LR_MIN.max(LR * (2f64).powf(-(self.games_played as f64)/LR_DECAY)) } fn argmax(slice:&[f64]) -> u32 { let mut x:u32 = 0; let mut max = slice[0]; for i in 1..slice.len() { if max<slice[i] { x = i as u32; max = slice[i]; } } x } fn field_to_input(field:&mut Field,...
get_lr
identifier_name
ai_qoff_player.rs
.01; //minimum NN LR const MOM:f64 = 0.05; //neural net momentum const EPOCHS_PER_STEP:u32 = 10; //epochs to learn from each turn/game const RND_PICK_START:f64 = 1.0f64; //exploration factor start const RND_PICK_DEC:f64 = 20000f64; //random exploration decrease (half every DEC games) const LEARNING_SET:i32 = 100; //num...
fn get_exploration(&self) -> f64 { RND_PICK_START * (2f64).powf(-(self.games_played as f64)/RND_PICK_DEC) } fn get_lr(&self) -> f64 { LR_MIN.max(LR * (2f64).powf(-(self.games_played as f64)/LR_DECAY)) } fn argmax(slice:&[f64]) -> u32 { let mut x:u32 = 0; let mut max = slice[0]; for i in 1..slic...
{ Box::new(PlayerAIQOff { initialized: false, fixed: fix, filename: String::new(), pid: 0, nn: None, games_played: 0, lr: LR, exploration: RND_PICK_START, play_buffer: Vec::new(), num_buffered: 0 }) }
identifier_body
collection-versions.js
const jwt = require("jwt-simple"); const co = require('co'); const config = require('../config'); const dbX = require('../db'); const coForEach = require('co-foreach'); module.exports = (io) => { const collectionVersionsNS = io.of('/collectionVersions'); collectionVersionsNS.use((socket, next) => { let token...
} else { socket.send({message: 'all collections up-to-date'}); } }).catch(error => { console.log(error.stack); socket.emit('error', { error: error.stack }) }) }) // after connection, client sends collectionVersions, then server co...
}); socket.emit('collectionUpdate', clientCollectionUpdates);
random_line_split
spanner_v1_generated_database_admin_create_database_async.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...
(): # Create a client client = spanner_admin_database_v1.DatabaseAdminAsyncClient() # Initialize request argument(s) request = spanner_admin_database_v1.CreateDatabaseRequest( parent="parent_value", create_statement="create_statement_value", ) # Make the request operation =...
sample_create_database
identifier_name
spanner_v1_generated_database_admin_create_database_async.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...
# NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-spanner-admin-database # [START spanner_v1_generated_D...
# limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for CreateDatabase
random_line_split
spanner_v1_generated_database_admin_create_database_async.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...
# [END spanner_v1_generated_DatabaseAdmin_CreateDatabase_async]
client = spanner_admin_database_v1.DatabaseAdminAsyncClient() # Initialize request argument(s) request = spanner_admin_database_v1.CreateDatabaseRequest( parent="parent_value", create_statement="create_statement_value", ) # Make the request operation = client.create_database(reques...
identifier_body
magiclink.py
# @domain part start (?:(?:[-a-z\d_]|(?<!\.)\.(?!\.))*)[a-z]\b # @domain.end (allow multiple dot names) (?![-@]) # Don't allow last char to be followed by these ) ''' RE_LINK = r'''(?xi) ( (?:(?<=\b)|(?<=_))(?: ...
"""Initialize.""" self.config = { 'hide_protocol': [ False, "If 'True', links are displayed without the initial ftp://, http:// or https://" "- Default: False" ], 'repo_url_shortener': [ False, "...
identifier_body
magiclink.py
, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import unicode_literals from markdown import Extension from markdown.inlinepatterns import LinkPattern, Pattern from markdown.treeprocessors import Treeprocessor from markdown import util as md_ut...
random_line_split
magiclink.py
AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT O...
(self, code): """Return entity definition by code, or the code if not defined.""" return "%s#%d;" % (md_util.AMP_SUBSTITUTE, code) def handleMatch(self, m): """Handle email link patterns.""" el = md_util.etree.Element("a") email = self.unescape(m.group(2)) href = "m...
email_encode
identifier_name
magiclink.py
AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT O...
else: # user/repo#(issue|pull) link.text = ('#' + value) if my_repo else (user_repo + '#' + value) def get_provider(self, match): """Get the provider and hash size.""" # Set provider specific variables if match.group('github'): provider = 'githu...
link.append(child) p.remove(child)
conditional_block
mail.py
# * Added try/except to support lack of getpid() in Jython (#5496). def make_msgid(idstring=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of th...
def send(self, fail_silently=False): """Sends the email message.""" return self.get_connection(fail_silently).send_messages([self]) def attach(self, filename=None, content=None, mimetype=None): """ Attaches a file with the given filename and content. The filename can be ...
random_line_split
mail.py
# * Added try/except to support lack of getpid() in Jython (#5496). def make_msgid(idstring=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of th...
def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False try: self.connection.sendmail(email_message.from_email, email_message.recipients(), email_mess...
""" Sends one or more EmailMessage objects and returns the number of email messages sent. """ if not email_messages: return new_conn_created = self.open() if not self.connection: # We failed silently on open(). Trying to send would be pointless. ...
identifier_body
mail.py
# * Added try/except to support lack of getpid() in Jython (#5496). def make_msgid(idstring=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of th...
if 'message-id' not in header_names: msg['Message-ID'] = make_msgid() for name, value in self.extra_headers.items(): msg[name] = value return msg def recipients(self): """ Returns a list of all recipients of the email (includes direct address...
msg['Date'] = formatdate()
conditional_block
mail.py
.getpid() except AttributeError: # No getpid() in Jython, for example. pid = 1 randint = random.randrange(100000) if idstring is None: idstring = '' else: idstring = '.' + idstring idhost = DNS_NAME msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idh...
attach_alternative
identifier_name
tensorflow_layer_ray_transform.py
"""Example of how to convert a RayTransform operator to a tensorflow layer. This example is similar to ``tensorflow_layer_matrix``, but demonstrates how more advanced operators, such as a ray transform, can be handled. """ from __future__ import print_function import tensorflow as tf import numpy as np import odl imp...
print(tf.gradients(y, [x_reshaped], z_reshaped)[0].eval() * scale) # Compare result with pure ODL print(ray_transform.derivative(x.eval()).adjoint(z.eval()))
# in tensorflow uses unweighted spaces. scale = ray_transform.range.cell_volume / ray_transform.domain.cell_volume
random_line_split
builtin-superkinds-capabilities-xc.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...
<T: RequiresRequiresShareAndSend + 'static>(val: T, chan: Sender<T>) { chan.send(val).unwrap(); } pub fn main() { let (tx, rx): (Sender<X<isize>>, Receiver<X<isize>>) = channel(); foo(X(31337), tx); assert_eq!(rx.recv().unwrap(), X(31337)); }
foo
identifier_name
builtin-superkinds-capabilities-xc.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...
fn foo<T: RequiresRequiresShareAndSend + 'static>(val: T, chan: Sender<T>) { chan.send(val).unwrap(); } pub fn main() { let (tx, rx): (Sender<X<isize>>, Receiver<X<isize>>) = channel(); foo(X(31337), tx); assert_eq!(rx.recv().unwrap(), X(31337)); }
impl <T: Sync+Send> RequiresRequiresShareAndSend for X<T> { }
random_line_split
keyVault.ts
// // Copyright (c) Microsoft. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // import adalNode, { TokenResponse } from 'adal-node'; // NOTE: this is deprecated-ish import { KeyVaultClient, KeyVaultCredentials } from 'azure-keyvault'; export default function cr...
return keyVaultClient; } ;
{ if (!kvConfig.clientId) { throw new Error('KeyVault client ID required at this time for the middleware to initialize.'); } if (!kvConfig.clientSecret) { throw new Error('KeyVault client credential/secret required at this time for the middleware to initialize.'); } const authenticator = (challenge, a...
identifier_body
keyVault.ts
// // Copyright (c) Microsoft. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // import adalNode, { TokenResponse } from 'adal-node'; // NOTE: this is deprecated-ish import { KeyVaultClient, KeyVaultCredentials } from 'azure-keyvault'; export default function
(kvConfig) { if (!kvConfig.clientId) { throw new Error('KeyVault client ID required at this time for the middleware to initialize.'); } if (!kvConfig.clientSecret) { throw new Error('KeyVault client credential/secret required at this time for the middleware to initialize.'); } const authenticator = (c...
createClient
identifier_name
keyVault.ts
// // Copyright (c) Microsoft. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // import adalNode, { TokenResponse } from 'adal-node'; // NOTE: this is deprecated-ish import { KeyVaultClient, KeyVaultCredentials } from 'azure-keyvault'; export default function cr...
if (!kvConfig.clientSecret) { throw new Error('KeyVault client credential/secret required at this time for the middleware to initialize.'); } const authenticator = (challenge, authCallback) => { const context = new adalNode.AuthenticationContext(challenge.authorization); return context.acquireTokenWi...
{ throw new Error('KeyVault client ID required at this time for the middleware to initialize.'); }
conditional_block
keyVault.ts
// // Copyright (c) Microsoft. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // import adalNode, { TokenResponse } from 'adal-node'; // NOTE: this is deprecated-ish import { KeyVaultClient, KeyVaultCredentials } from 'azure-keyvault'; export default function cr...
return keyVaultClient; };
const credentials = new KeyVaultCredentials(authenticator, null); const keyVaultClient = new KeyVaultClient(credentials);
random_line_split
webm.ts
import { Operation } from 'express-openapi'; import IStreamApiModel, { StreamResponse } from '../../../../../api/stream/IStreamApiModel'; import container from '../../../../../ModelContainer'; import * as api from '../../../../api'; export const get: Operation = async (req, res) => { const streamApiModel = contain...
res.status(200); result.stream.on('close', () => { res.end(); }); result.stream.on('exit', () => { res.end(); }); result.stream.on('error', () => { res.end(); }); result.stream.pipe(res); }; get.apiDoc = { summary: '録画 WebM ストリーム', tags: ['streams'], ...
return; } res.setHeader('Content-Type', 'video/webm');
random_line_split
webm.ts
import { Operation } from 'express-openapi'; import IStreamApiModel, { StreamResponse } from '../../../../../api/stream/IStreamApiModel'; import container from '../../../../../ModelContainer'; import * as api from '../../../../api'; export const get: Operation = async (req, res) => { const streamApiModel = contain...
res.setHeader('Content-Type', 'video/webm'); res.status(200); result.stream.on('close', () => { res.end(); }); result.stream.on('exit', () => { res.end(); }); result.stream.on('error', () => { res.end(); }); result.stream.pipe(res); }; get.apiDoc = { ...
{ await stop(); return; }
conditional_block
connection.js
export class Connection { constructor (url) { this._url = url this.connecting = false this.connect(this._url) this.listener = null } get url () { return this._url } set url (v) { if (v !== this._url) { this._url = v this.connect() } } connect () { ...
} send (data) { this.ws.send(JSON.stringify(data)) } } export class Subscriptor extends Connection { constructor (url) { super(url) this.items = [] this.map = {} this.nextId = 1 this.onPublish = () => null this.onPackage = () => null } onOpen () { if (this.it...
{ this.listener.onOpen() }
conditional_block
connection.js
export class
{ constructor (url) { this._url = url this.connecting = false this.connect(this._url) this.listener = null } get url () { return this._url } set url (v) { if (v !== this._url) { this._url = v this.connect() } } connect () { this.connecting = tr...
Connection
identifier_name
connection.js
export class Connection { constructor (url) { this._url = url this.connecting = false this.connect(this._url) this.listener = null } get url () { return this._url } set url (v) { if (v !== this._url) { this._url = v this.connect() } } connect () { ...
unsubscribe (id) { const item = this.items.find(i => i.id === id) if (!item) { return false } try { this.send({ type: 'Unsubscribe', id }) this.items.splice(this.items.indexOf(item), 1) delete this.map[id] return true } catch (e) {...
{ if (data.type === 'Data') { const item = this.map[data.id] if (item) { if (item.callback) { item.callback(data.value, item.name, item.args) } else { this.onPublish(data.value, item.name, item.args) } } } else { this.onPackage(data)...
identifier_body
connection.js
export class Connection { constructor (url) { this._url = url this.connecting = false this.connect(this._url) this.listener = null } get url () { return this._url } set url (v) { if (v !== this._url) { this._url = v this.connect() } } connect () { ...
}
}
random_line_split
OFShell.py
import threading import time import re from openflow.optin_manager.sfa.openflow_utils.CreateOFSliver import CreateOFSliver from openflow.optin_manager.sfa.openflow_utils.sliver_status import get_sliver_status from openflow.optin_manager.sfa.openflow_utils.delete_slice import delete_slice from openflow.optin_manager.sfa...
else: raise "" def RebootSlice(self, slice_urn): return self.StartSlice(slice_urn) def DeleteSlice(self, slice_urn): try: delete_slice(slice_urn) return 1 except Exception as e: ...
return True
conditional_block
OFShell.py
import threading import time import re from openflow.optin_manager.sfa.openflow_utils.CreateOFSliver import CreateOFSliver from openflow.optin_manager.sfa.openflow_utils.sliver_status import get_sliver_status from openflow.optin_manager.sfa.openflow_utils.delete_slice import delete_slice from openflow.optin_manager.sfa...
return links
random_line_split
OFShell.py
import threading import time import re from openflow.optin_manager.sfa.openflow_utils.CreateOFSliver import CreateOFSliver from openflow.optin_manager.sfa.openflow_utils.sliver_status import get_sliver_status from openflow.optin_manager.sfa.openflow_utils.delete_slice import delete_slice from openflow.optin_manager.sfa...
: def __init__(self): pass @staticmethod def get_switches(used_switches=[]): complete_list = [] switches = OFShell().get_raw_switches() for switch in switches: if len(used_switches)>0: if not switch[0] in used_swi...
OFShell
identifier_name
OFShell.py
import threading import time import re from openflow.optin_manager.sfa.openflow_utils.CreateOFSliver import CreateOFSliver from openflow.optin_manager.sfa.openflow_utils.sliver_status import get_sliver_status from openflow.optin_manager.sfa.openflow_utils.delete_slice import delete_slice from openflow.optin_manager.sfa...
def CreateSliver(self, requested_attributes, slice_urn, authority,expiration): project_description = 'SFA Project from %s' %authority slice_id = slice_urn for rspec_attrs in requested_attributes: switch_slivers = get_fs_from_group(rspec_attrs['match...
try: delete_slice(slice_urn) return 1 except Exception as e: print e raise ""
identifier_body
forms.py
from django import forms from django.forms import Form, ModelForm from django.utils import timezone from webapp.models import Task, TaskGroup, TaskGroupSet from webapp.validators import validate_package from webapp.widgets import CustomSplitDateTimeWidget class TaskGroupForm(ModelForm): class Meta: model...
(Form): comment = forms.CharField( label='Your comment', widget=forms.Textarea(attrs={'placeholder': 'Type in the reason here'}), required=True ) class CopyTaskGroup(Form): name = forms.CharField( label='New name', widget=forms.TextInput(attrs={'placeholder': 'New n...
InvalidateSubmissionForm
identifier_name
forms.py
from django import forms from django.forms import Form, ModelForm from django.utils import timezone from webapp.models import Task, TaskGroup, TaskGroupSet from webapp.validators import validate_package from webapp.widgets import CustomSplitDateTimeWidget class TaskGroupForm(ModelForm): class Meta: model...
class InvalidateSubmissionForm(Form): comment = forms.CharField( label='Your comment', widget=forms.Textarea(attrs={'placeholder': 'Type in the reason here'}), required=True ) class CopyTaskGroup(Form): name = forms.CharField( label='New name', widget=forms.TextI...
self.fields['deadline'].initial = timezone.now() + timezone.timedelta(days=14) del self.fields['tg_set']
conditional_block
forms.py
from django import forms from django.forms import Form, ModelForm from django.utils import timezone from webapp.models import Task, TaskGroup, TaskGroupSet from webapp.validators import validate_package from webapp.widgets import CustomSplitDateTimeWidget class TaskGroupForm(ModelForm): class Meta: model...
del self.fields['tg_set'] class InvalidateSubmissionForm(Form): comment = forms.CharField( label='Your comment', widget=forms.Textarea(attrs={'placeholder': 'Type in the reason here'}), required=True ) class CopyTaskGroup(Form): name = forms.CharField( label='...
self.fields['deadline'].initial = timezone.now() + timezone.timedelta(days=14)
random_line_split
forms.py
from django import forms from django.forms import Form, ModelForm from django.utils import timezone from webapp.models import Task, TaskGroup, TaskGroupSet from webapp.validators import validate_package from webapp.widgets import CustomSplitDateTimeWidget class TaskGroupForm(ModelForm): class Meta: model...
password = forms.CharField(min_length=8, label='Password', widget=forms.PasswordInput) repeat_password = forms.CharField(label='Repeat password', widget=forms.PasswordInput)
identifier_body
ai.rs
use level::*; pub fn ai_step(level : &mut Level, player_pos: (i32,i32)) { let mut x = 0; let mut y = 0; let mut enemies = Vec::with_capacity(16); for line in &level.tiles { for tile in line { match tile.entity { Some(Entity::Dragon{..}) => { enem...
if distance<6f32 { let dir = if dx<0f32 { Direction::Left } else if dx>0f32 { Direction::Right } else if dy<0f32 { Direction::Up } else { Direction::Down }; level.interact((x,y...
let distance = (dx*dx + dy*dy).sqrt();
random_line_split
ai.rs
use level::*; pub fn
(level : &mut Level, player_pos: (i32,i32)) { let mut x = 0; let mut y = 0; let mut enemies = Vec::with_capacity(16); for line in &level.tiles { for tile in line { match tile.entity { Some(Entity::Dragon{..}) => { enemies.push((x,y)); ...
ai_step
identifier_name
ai.rs
use level::*; pub fn ai_step(level : &mut Level, player_pos: (i32,i32)) { let mut x = 0; let mut y = 0; let mut enemies = Vec::with_capacity(16); for line in &level.tiles { for tile in line { match tile.entity { Some(Entity::Dragon{..}) => { enem...
} }
{ let dir = if dx<0f32 { Direction::Left } else if dx>0f32 { Direction::Right } else if dy<0f32 { Direction::Up } else { Direction::Down }; level.interact((x,y), dir); }
conditional_block
ai.rs
use level::*; pub fn ai_step(level : &mut Level, player_pos: (i32,i32))
for e in enemies { let (x,y) = e; let dx = (px-x) as f32; let dy = (py-y) as f32; let distance = (dx*dx + dy*dy).sqrt(); if distance<6f32 { let dir = if dx<0f32 { Direction::Left } else if dx>0f32 { Direction::Right ...
{ let mut x = 0; let mut y = 0; let mut enemies = Vec::with_capacity(16); for line in &level.tiles { for tile in line { match tile.entity { Some(Entity::Dragon{..}) => { enemies.push((x,y)); }, _ => {} }...
identifier_body
colormap.py
#!/usr/bin/env python # Copyright (C) 2001 Colin Phipps <cphipps@doomworld.com> # Copyright (C) 2008, 2013 Simon Howard # Parts copyright (C) 1999 by id Software (http://www.idsoftware.com/) # # SPDX-License-Identifier: GPL-2.0+ # # Takes PLAYPAL as input (filename is the only parameter) # Produces a light graduated CO...
def set_parameter(name, value): """Set configuration value, from command line parameters.""" global dark_color, tint_color, tint_frac, tint_bright if name == 'dark_color': dark_color = parse_color_code(value) elif name == 'tint_color': tint_color = parse_color_code(value) elif name == 'tint_pct': tint_fra...
"""Parse a color code in HTML color code format, into an RGB 3-tuple value.""" if not s.startswith('#') or len(s) != 7: raise Exception('Not in HTML color code form: %s' % s) return (int(s[1:3], 16), int(s[3:5], 16), int(s[5:7], 16))
identifier_body
colormap.py
#!/usr/bin/env python # Copyright (C) 2001 Colin Phipps <cphipps@doomworld.com> # Copyright (C) 2008, 2013 Simon Howard # Parts copyright (C) 1999 by id Software (http://www.idsoftware.com/) # # SPDX-License-Identifier: GPL-2.0+ # # Takes PLAYPAL as input (filename is the only parameter) # Produces a light graduated CO...
return result def tint_colors(colors, tint, bright=0.5): """Given a list of colors, tint them a particular color.""" result = [] for c in colors: # I've experimented with different methods of calculating # intensity, but this seems to work the best. This is basically # doing an average of the full channels...
random_line_split
colormap.py
#!/usr/bin/env python # Copyright (C) 2001 Colin Phipps <cphipps@doomworld.com> # Copyright (C) 2008, 2013 Simon Howard # Parts copyright (C) 1999 by id Software (http://www.idsoftware.com/) # # SPDX-License-Identifier: GPL-2.0+ # # Takes PLAYPAL as input (filename is the only parameter) # Produces a light graduated CO...
(color): """Generate a 256-entry palette where all entries are the same color.""" return [color] * 256 def output_colormap(colormap): """Output the given palette to stdout.""" for c in colormap: x = struct.pack("B", c) os.write(sys.stdout.fileno(), x) def print_palette(colors): for y in range(16): for ...
solid_color_list
identifier_name
colormap.py
#!/usr/bin/env python # Copyright (C) 2001 Colin Phipps <cphipps@doomworld.com> # Copyright (C) 2008, 2013 Simon Howard # Parts copyright (C) 1999 by id Software (http://www.idsoftware.com/) # # SPDX-License-Identifier: GPL-2.0+ # # Takes PLAYPAL as input (filename is the only parameter) # Produces a light graduated CO...
return best_index def generate_colormap(colors, palette): """Given a list of colors, translate these into indexes into the given palette, finding the nearest color where an exact match cannot be found.""" result = [] for color in colors: index = search_palette(palette, color) result.append(index) ...
best_diff = diff best_index = i
conditional_block
mivExchangeTimeZone.js
absoluteDateTransitions = xml2json.XPath(aValue, "/t:Transitions/t:AbsoluteDateTransition"); var lastDate = "1900-01-01T00:00:00"; var transitionIndex = 0; for each(var absoluteDateTransition in absoluteDateTransitions) { var newDate = xml2json.getTagValue(absoluteDateTransition, "t:DateTime", lastDate); i...
name
identifier_name
mivExchangeTimeZone.js
//dump("exchangezone:"+aValue+"\n"); // Se if we have <t:Transitions><t:AbsoluteDateTransition> var absoluteDateTransitions = xml2json.XPath(aValue, "/t:Transitions/t:AbsoluteDateTransition"); var lastDate = "1900-01-01T00:00:00"; var transitionIndex = 0; for each(var absoluteDateTransition in absoluteDateT...
{ return this._standardRRule; }
identifier_body
mivExchangeTimeZone.js
result += "0"; result += aDate.day+"T"; if (aDate.hour < 10) result += "0"; result += aDate.hour; if (aDate.minute < 10) result += "0"; result += aDate.minute; if (aDate.second < 10) result += "0"; result += aDate.second; return result; }, // External methods setExchangeTimezone: function _setExc...
}
random_line_split
should-tests.ts
/// <reference path="should.d.ts" /> import should = require('should'); should.fail('actual', 'expected', 'msg', 'operator'); should.assert('value', 'msg'); should.ok('value'); should.equal('actual', 'expected'); should.notEqual('actual', 'expected'); should.deepEqual('actual', 'expected'); should.notDeepEqual('actua...
{ name: string; pets: string[]; age: number; } var user = { name: 'tj', pets: ['tobi', 'loki', 'jane', 'bandit'], age: 17 }; user.should.have.property('name', 'tj'); user.should.have.property('pets').with.lengthOf(4); should.exist('hello'); should.exist([]); should.exist(null); should.not.exist(false);...
User
identifier_name
should-tests.ts
/// <reference path="should.d.ts" /> import should = require('should'); should.fail('actual', 'expected', 'msg', 'operator'); should.assert('value', 'msg'); should.ok('value'); should.equal('actual', 'expected'); should.notEqual('actual', 'expected'); should.deepEqual('actual', 'expected'); should.notDeepEqual('actua...
[1, 2, 3].should.include(3); [1, 2, 3].should.include(2); [1, 2, 3].should.not.include(4); 'foo bar baz'.should.include('foo'); 'foo bar baz'.should.include('bar'); 'foo bar baz'.should.include('baz'); 'foo bar baz'.should.not.include('FOO'); var tobi = { name: 'Tobi', age: 1 }; var jane = { name: 'Jane', age: 5 }; v...
res.should.be.json; res.should.be.html;
random_line_split
moment.js
'use strict'; var babelHelpers = require('../util/babelHelpers.js'); exports.__esModule = true; var _configure = require('../configure'); var _configure2 = babelHelpers.interopRequireDefault(_configure); function endOfDecade(date) { date = new Date(date); date.setFullYear(date.getFullYear() + 10); date.setMi...
month: 'MMM', year: 'YYYY', decade: function decade(date, culture, localizer) { return localizer.format(date, 'YYYY', culture) + ' - ' + localizer.format(endOfDecade(date), 'YYYY', culture); }, century: function century(date, culture, localizer) { return localizer.format(...
random_line_split
moment.js
'use strict'; var babelHelpers = require('../util/babelHelpers.js'); exports.__esModule = true; var _configure = require('../configure'); var _configure2 = babelHelpers.interopRequireDefault(_configure); function endOfDecade(date) { date = new Date(date); date.setFullYear(date.getFullYear() + 10); date.setMi...
(culture, value, format) { return culture ? moment(value, format)[localField](culture) : moment(value, format); } var localizer = { formats: { date: 'L', time: 'LT', 'default': 'lll', header: 'MMMM YYYY', footer: 'LL', weekday: 'dd', dayOfMonth: 'DD', month: ...
getMoment
identifier_name
moment.js
'use strict'; var babelHelpers = require('../util/babelHelpers.js'); exports.__esModule = true; var _configure = require('../configure'); var _configure2 = babelHelpers.interopRequireDefault(_configure); function endOfDecade(date) { date = new Date(date); date.setFullYear(date.getFullYear() + 10); date.setMi...
exports['default'] = function (moment) { if (typeof moment !== 'function') throw new TypeError('You must provide a valid moment object'); var localField = typeof moment().locale === 'function' ? 'locale' : 'lang', hasLocaleData = !!moment.localeData; if (!hasLocaleData) throw new TypeError('The Moment l...
{ date = new Date(date); date.setFullYear(date.getFullYear() + 100); date.setMilliseconds(date.getMilliseconds() - 1); return date; }
identifier_body
htmlareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; use dom::bindings::codegen::InheritTypes::HTMLAreaEl...
(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLAreaElement { HTMLAreaElement { htmlelement: HTMLElement::new_inherited(HTMLAreaElementTypeId, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefi...
new_inherited
identifier_name
htmlareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; use dom::bindings::codegen::InheritTypes::HTMLAreaEl...
use servo_util::str::DOMString; #[jstraceable] #[must_root] #[privatize] pub struct HTMLAreaElement { htmlelement: HTMLElement } impl HTMLAreaElementDerived for EventTarget { fn is_htmlareaelement(&self) -> bool { *self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLAreaElementTypeId)) } } i...
use dom::htmlelement::HTMLElement; use dom::node::{Node, NodeHelpers, ElementNodeTypeId};
random_line_split
htmlareaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; use dom::bindings::codegen::InheritTypes::HTMLAreaEl...
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLAreaElement> { let element = HTMLAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap)...
{ HTMLAreaElement { htmlelement: HTMLElement::new_inherited(HTMLAreaElementTypeId, localName, prefix, document) } }
identifier_body
custom_config_functions.js
module.exports = function(grunt) { grunt.config('file_dependencies.custom_config_functions', { files: { src: [ 'test/fixtures/custom_config_functions/ClassB.js', 'test/fixtures/custom_config_functions/ClassA.js'
options: { extractDefines: function(fileContent) { var regex = /framework\.defineClass\s*\(\s*['"]([^'"]+)['"]/g, matches = [], match; while(match = regex.exec(fileContent)) matches.push(match[1]); return matches; }, extractRequires: function(fil...
] },
random_line_split
error-code.service.ts
import { Inject, Injectable } from '@angular/core'; import { ACCESS_DENIED, FAILED_EXTRACT_TOKEN, IMMEDIATE_FAILED, POPUP_CLOSED_BY_USER } from './error-codes'; import { ACCESS_DENIED_TOKEN } from './tokens/access-denied.token'; import { FAILED_EXTRACT_TOKEN_TOKEN } from './tokens/falied-extract-token.token'; import { ...
providedIn: 'root' }) export class ErrorCodeService { constructor( @Inject(ACCESS_DENIED_TOKEN) private accessDenied: string, @Inject(FAILED_EXTRACT_TOKEN_TOKEN) private faliedExtractToken: string, @Inject(IMMEDIATE_FAILED_TOKEN) private immediateFailed: string, @Inject(POPUP_CL...
@Injectable({
random_line_split
error-code.service.ts
import { Inject, Injectable } from '@angular/core'; import { ACCESS_DENIED, FAILED_EXTRACT_TOKEN, IMMEDIATE_FAILED, POPUP_CLOSED_BY_USER } from './error-codes'; import { ACCESS_DENIED_TOKEN } from './tokens/access-denied.token'; import { FAILED_EXTRACT_TOKEN_TOKEN } from './tokens/falied-extract-token.token'; import { ...
{ constructor( @Inject(ACCESS_DENIED_TOKEN) private accessDenied: string, @Inject(FAILED_EXTRACT_TOKEN_TOKEN) private faliedExtractToken: string, @Inject(IMMEDIATE_FAILED_TOKEN) private immediateFailed: string, @Inject(POPUP_CLOSED_BY_USER_TOKEN) private popupClosedByUser: string, ...
ErrorCodeService
identifier_name
archive_org_plugin.py
# -*- coding: utf-8 -*- from __future__ import (unicode_literals, division, absolute_import, print_function) store_version = 1 # Needed for dynamic plugin loading __license__ = 'GPL 3' __copyright__ = '2011, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.gui2.store.basic_con...
def get_details(self, search_result, timeout): ''' The opensearch feed only returns a subset of formats that are available. We want to get a list of all formats that the user can get. ''' from calibre import browser from contextlib import closing from lxml i...
s.detail_item = 'http://www.archive.org/details/' + s.detail_item.split(':')[-1] s.price = '$0.00' s.drm = SearchResult.DRM_UNLOCKED yield s
conditional_block
archive_org_plugin.py
# -*- coding: utf-8 -*- from __future__ import (unicode_literals, division, absolute_import, print_function) store_version = 1 # Needed for dynamic plugin loading __license__ = 'GPL 3' __copyright__ = '2011, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.gui2.store.basic_con...
def get_details(self, search_result, timeout): ''' The opensearch feed only returns a subset of formats that are available. We want to get a list of all formats that the user can get. ''' from calibre import browser from contextlib import closing from lxml i...
for s in OpenSearchOPDSStore.search(self, query, max_results, timeout): s.detail_item = 'http://www.archive.org/details/' + s.detail_item.split(':')[-1] s.price = '$0.00' s.drm = SearchResult.DRM_UNLOCKED yield s
identifier_body
archive_org_plugin.py
# -*- coding: utf-8 -*- from __future__ import (unicode_literals, division, absolute_import, print_function) store_version = 1 # Needed for dynamic plugin loading __license__ = 'GPL 3' __copyright__ = '2011, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.gui2.store.basic_con...
from calibre import browser from contextlib import closing from lxml import html br = browser() with closing(br.open(search_result.detail_item, timeout=timeout)) as nf: idata = html.fromstring(nf.read()) formats = ', '.join(idata.xpath('//p[@id="dl" and @...
We want to get a list of all formats that the user can get. '''
random_line_split
archive_org_plugin.py
# -*- coding: utf-8 -*- from __future__ import (unicode_literals, division, absolute_import, print_function) store_version = 1 # Needed for dynamic plugin loading __license__ = 'GPL 3' __copyright__ = '2011, John Schember <john@nachtimwald.com>' __docformat__ = 'restructuredtext en' from calibre.gui2.store.basic_con...
(self, query, max_results=10, timeout=60): for s in OpenSearchOPDSStore.search(self, query, max_results, timeout): s.detail_item = 'http://www.archive.org/details/' + s.detail_item.split(':')[-1] s.price = '$0.00' s.drm = SearchResult.DRM_UNLOCKED yield s def...
search
identifier_name