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 |
|---|---|---|---|---|
util.py | """
This module contains several handy functions primarily meant for internal use.
"""
from datetime import date, datetime, timedelta
from time import mktime
import re
import sys
from types import MethodType
__all__ = ('asint', 'asbool', 'convert_to_datetime', 'timedelta_seconds',
'time_difference', 'datet... | f_self = getattr(func, '__self__', None) or getattr(func, 'im_self', None)
if f_self and hasattr(func, '__name__'):
if isinstance(f_self, type):
# class method
return '%s.%s' % (f_self.__name__, func.__name__)
# bound method
return '%s.%s' % (f_self.__class__.__n... | """
Returns the best available display name for the given function/callable.
""" | random_line_split |
util.py | """
This module contains several handy functions primarily meant for internal use.
"""
from datetime import date, datetime, timedelta
from time import mktime
import re
import sys
from types import MethodType
__all__ = ('asint', 'asbool', 'convert_to_datetime', 'timedelta_seconds',
'time_difference', 'datet... | (obj):
"""
Returns the path to the given object.
"""
ref = '%s:%s' % (obj.__module__, get_callable_name(obj))
try:
obj2 = ref_to_obj(ref)
if obj != obj2:
raise ValueError
except Exception:
raise ValueError('Cannot determine the reference to %s' % repr(obj))
... | obj_to_ref | identifier_name |
util.py | """
This module contains several handy functions primarily meant for internal use.
"""
from datetime import date, datetime, timedelta
from time import mktime
import re
import sys
from types import MethodType
__all__ = ('asint', 'asbool', 'convert_to_datetime', 'timedelta_seconds',
'time_difference', 'datet... |
def ref_to_obj(ref):
"""
Returns the object pointed to by ``ref``.
"""
if not isinstance(ref, basestring):
raise TypeError('References must be strings')
if not ':' in ref:
raise ValueError('Invalid reference')
modulename, rest = ref.split(':', 1)
try:
obj = __impo... | """
Returns the path to the given object.
"""
ref = '%s:%s' % (obj.__module__, get_callable_name(obj))
try:
obj2 = ref_to_obj(ref)
if obj != obj2:
raise ValueError
except Exception:
raise ValueError('Cannot determine the reference to %s' % repr(obj))
retu... | identifier_body |
conf.py | # CoderDojo Twin Cities Python for Minecraft documentation build configuration file, created by
# sphinx-quickstart on Fri Oct 24 00:52:04 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated fi... | # If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per... | #latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
| random_line_split |
ntcc.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// 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... | par_body
= oror expression
tell
= store_kw left_arrow constraint
next
= next_kw expression
async
= async_kw expression
rep
= rep_kw expression
unless
= unless_kw entailed_by next
when
= when_kw entails right_arrow expression
entails
= store_kw entail constraint
... | par
= par_kw oror? expression par_body* end_kw?
| random_line_split |
game-board.component.ts | import { Component, Input, OnInit, OnDestroy, ViewChildren, QueryList } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GameHubService } from '../services/game-services.imports';
import { Game, Field, FieldChecked } from '../game.models';
import { GameFieldComponent } from './board-com... | }
}
| this.rows[index] = tempArray.splice(0, this.game.boardWidth);
index++;
}
| conditional_block |
game-board.component.ts | import { Component, Input, OnInit, OnDestroy, ViewChildren, QueryList } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GameHubService } from '../services/game-services.imports';
import { Game, Field, FieldChecked } from '../game.models';
import { GameFieldComponent } from './board-com... | rivate route: ActivatedRoute,
private gameHub: GameHubService) {
}
initialize(game: Game) {
this.game = game;
this.createRows();
this.calculateFlex();
this.gameHub.fieldChecked(this.onFieldChecked);
}
onFieldChecked = (args: FieldChecked) => {
var comp... | nstructor(p | identifier_name |
game-board.component.ts | import { Component, Input, OnInit, OnDestroy, ViewChildren, QueryList } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GameHubService } from '../services/game-services.imports';
import { Game, Field, FieldChecked } from '../game.models';
import { GameFieldComponent } from './board-com... | initialize(game: Game) {
this.game = game;
this.createRows();
this.calculateFlex();
this.gameHub.fieldChecked(this.onFieldChecked);
}
onFieldChecked = (args: FieldChecked) => {
var component = this.gameFields.filter(f => f.field.id == args.fieldId)[0];
var ... | }
| identifier_body |
game-board.component.ts | import { Component, Input, OnInit, OnDestroy, ViewChildren, QueryList } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GameHubService } from '../services/game-services.imports';
import { Game, Field, FieldChecked } from '../game.models';
import { GameFieldComponent } from './board-com... | var team = this.game.teams.filter(t => t.id == args.teamId)[0];
if (team)
component.onFieldChecked(args, team.color);
else
component.onFieldChecked(args);
}
private calculateFlex() {
const baseFlexValue: number = 95;
this.colFlex = baseFlexValue ... | var component = this.gameFields.filter(f => f.field.id == args.fieldId)[0]; | random_line_split |
mod.rs | //! Abstracts out the APIs necessary to `Runtime` for integrating the blocking
//! pool. When the `blocking` feature flag is **not** enabled, these APIs are
//! shells. This isolates the complexity of dealing with conditional
//! compilation.
mod pool;
pub(crate) use pool::{spawn_blocking, BlockingPool, Mandatory, Spa... |
/*
cfg_not_blocking_impl! {
use crate::runtime::Builder;
use std::time::Duration;
#[derive(Debug, Clone)]
pub(crate) struct BlockingPool {}
pub(crate) use BlockingPool as Spawner;
pub(crate) fn create_blocking_pool(_builder: &Builder, _thread_cap: usize) -> BlockingPool {
BlockingPo... | {
BlockingPool::new(builder, thread_cap)
} | identifier_body |
mod.rs | //! Abstracts out the APIs necessary to `Runtime` for integrating the blocking
//! pool. When the `blocking` feature flag is **not** enabled, these APIs are
//! shells. This isolates the complexity of dealing with conditional
//! compilation.
mod pool;
pub(crate) use pool::{spawn_blocking, BlockingPool, Mandatory, Spa... | (builder: &Builder, thread_cap: usize) -> BlockingPool {
BlockingPool::new(builder, thread_cap)
}
/*
cfg_not_blocking_impl! {
use crate::runtime::Builder;
use std::time::Duration;
#[derive(Debug, Clone)]
pub(crate) struct BlockingPool {}
pub(crate) use BlockingPool as Spawner;
pub(crate)... | create_blocking_pool | identifier_name |
mod.rs | //! Abstracts out the APIs necessary to `Runtime` for integrating the blocking
//! pool. When the `blocking` feature flag is **not** enabled, these APIs are
//! shells. This isolates the complexity of dealing with conditional
//! compilation.
mod pool;
pub(crate) use pool::{spawn_blocking, BlockingPool, Mandatory, Spa... | pub(crate) use task::BlockingTask;
use crate::runtime::Builder;
pub(crate) fn create_blocking_pool(builder: &Builder, thread_cap: usize) -> BlockingPool {
BlockingPool::new(builder, thread_cap)
}
/*
cfg_not_blocking_impl! {
use crate::runtime::Builder;
use std::time::Duration;
#[derive(Debug, Clone)... | mod task;
pub(crate) use schedule::NoopSchedule; | random_line_split |
Messages.tsx | import React from "react"
import { Dimensions, FlatList, RefreshControl, ViewStyle } from "react-native"
import { createPaginationContainer, graphql, RelayPaginationProp } from "react-relay"
import styled from "styled-components/native"
import { PAGE_SIZE } from "lib/data/constants"
import ARSwitchBoard from "../../.... |
this.setState({ reloadingData: false })
})
}
render() {
const edges = (this.props.conversation.messages && this.props.conversation.messages.edges) || []
const messageCount = edges.length
const messages = edges
.filter(edge => {
return (edge.node.body && edge.node.body.length) ... | {
// FIXME: Handle error
console.error("Messages.tsx", error.message)
} | conditional_block |
Messages.tsx | import React from "react"
import { Dimensions, FlatList, RefreshControl, ViewStyle } from "react-native"
import { createPaginationContainer, graphql, RelayPaginationProp } from "react-relay"
import styled from "styled-components/native"
import { PAGE_SIZE } from "lib/data/constants"
import ARSwitchBoard from "../../.... | <ArtworkPreview
artwork={subjectItem}
onSelected={() => ARSwitchBoard.presentNavigationViewController(this, subjectItem.href)}
/>
)
}
showPreview={
item.first_message &&
subjectItem.__typename === "Show" && (
<... | random_line_split | |
Messages.tsx | import React from "react"
import { Dimensions, FlatList, RefreshControl, ViewStyle } from "react-native"
import { createPaginationContainer, graphql, RelayPaginationProp } from "react-relay"
import styled from "styled-components/native"
import { PAGE_SIZE } from "lib/data/constants"
import ARSwitchBoard from "../../.... | ,
getVariables(props, paginationInfo, _fragmentVariables) {
return {
conversationID: props.conversation.internalID,
count: paginationInfo.count,
after: paginationInfo.cursor,
}
},
query: graphql`
query MessagesQuery($conversationID: String!, $count: Int!, $after: St... | {
return {
...prevVars,
count: totalCount,
}
} | identifier_body |
Messages.tsx | import React from "react"
import { Dimensions, FlatList, RefreshControl, ViewStyle } from "react-native"
import { createPaginationContainer, graphql, RelayPaginationProp } from "react-relay"
import styled from "styled-components/native"
import { PAGE_SIZE } from "lib/data/constants"
import ARSwitchBoard from "../../.... | (props) {
return props.conversation && props.conversation.messages
},
getFragmentVariables(prevVars, totalCount) {
return {
...prevVars,
count: totalCount,
}
},
getVariables(props, paginationInfo, _fragmentVariables) {
return {
conversationID: props.conver... | getConnectionFromProps | identifier_name |
mod.rs | // ColdFire Target
//
// This file is part of AEx.
// Copyright (C) 2017 Jeffrey Sharp
//
// AEx is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any la... | {
/// No associated size.
Zero,
/// Byte
Byte,
/// Word (2 bytes)
Word,
/// Longword (4 bytes)
Long,
/// Single-precision floating-point (4 bytes)
Single,
/// Double-precision floating-point (8 bytes)
Double,
}
| Size | identifier_name |
mod.rs | // ColdFire Target
//
// This file is part of AEx.
// Copyright (C) 2017 Jeffrey Sharp
//
// AEx is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any la... | #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Size {
/// No associated size.
Zero,
/// Byte
Byte,
/// Word (2 bytes)
Word,
/// Longword (4 bytes)
Long,
/// Single-precision floating-point (4 bytes)
Single,
/// Double-precision floating-point (8 b... | pub use self::mnemonics::*;
pub use self::opcodes::*;
pub use self::operand::*;
/// Operation sizes. | random_line_split |
crud.service.ts | // Angular dependencies.
import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { AuthHttp } from 'angular2-jwt';
import 'rxjs/Rx';
// Services.
import { BaseService } from './base.service';
import { ConfigService } from '... |
}
// Delete.
public Delete(relativeApiUrl: string, urlParams: Object = {})
{
// Get the API URL.
let apiUrl = this.buildUrl(relativeApiUrl, urlParams);
// Log it.
console.warn(this.constructor.name, 'DELETING:', apiUrl);
// Send the HTTP request.
return this.authHttp
.delete(apiUrl)
.map(thi... | {
// Create a new item.
return this.authHttp
.post(apiUrl, body, {headers: jsonHeaders})
.map(this.extractData)
.catch(this.handleError);
} | conditional_block |
crud.service.ts | // Angular dependencies.
import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { AuthHttp } from 'angular2-jwt';
import 'rxjs/Rx';
// Services.
import { BaseService } from './base.service';
import { ConfigService } from '... | (protected authHttp: AuthHttp, protected http: Http, protected config: ConfigService)
{
super(config);
}
// Query API for a list of items.
public GetItems(relativeApiUrl: string, urlParams: Object = {}, filters: Object = {}): Observable<any[]>
{
// Get the API URL.
let apiUrl = this.buildUrl(relativeApiUrl... | constructor | identifier_name |
crud.service.ts | // Angular dependencies.
import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { AuthHttp } from 'angular2-jwt';
import 'rxjs/Rx';
// Services.
import { BaseService } from './base.service';
import { ConfigService } from '... | return this.authHttp
.get(apiUrl, {search: urlSearchParams})
.map(this.extractData)
.publishReplay(1)
.refCount()
.catch(this.handleError);
}
// Query API for a specific item.
public GetItem(relativeApiUrl: string, urlParams: Object = {}, filters: Object = {})
{
// Get the API URL.
let apiUrl... | random_line_split | |
crud.service.ts | // Angular dependencies.
import { Injectable } from '@angular/core';
import { Http, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { AuthHttp } from 'angular2-jwt';
import 'rxjs/Rx';
// Services.
import { BaseService } from './base.service';
import { ConfigService } from '... |
// Query API for a list of items.
public GetItems(relativeApiUrl: string, urlParams: Object = {}, filters: Object = {}): Observable<any[]>
{
// Get the API URL.
let apiUrl = this.buildUrl(relativeApiUrl, urlParams);
// Build search filters.
let urlSearchParams: URLSearchParams = new URLSearchParams();
f... | {
super(config);
} | identifier_body |
specification.tsx | /*
* Copyright 2018 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless r... |
return docString.replace(/@param .*[\n\r]*/gim, '');
}
private renderDocString(item: HasDocString) {
if (!item.docString) {
return;
}
const docString = item.docString as string;
const lines = docString.split(/(?:\r\n|\n|\r)/gim);
// eslint-disable-next-line no-param-reassign
item... | {
return '';
} | conditional_block |
specification.tsx | /*
* Copyright 2018 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless r... | (data: SpecificationData) {
this.data = JSON.parse(JSON.stringify(data));
this.enumsByName = createMapByName(this.data.enums);
this.servicesByName = createMapByName(this.data.services);
this.structsByName = createMapByName([
...this.data.structs,
...this.data.exceptions,
]);
this.u... | constructor | identifier_name |
specification.tsx | /*
* Copyright 2018 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless r... | const pattern = /@param\s+(\w+)[\s.]+(({@|[^@])*)(?=(@[\w]+|$|\s))/gm;
let match = pattern.exec(docString);
while (match != null) {
parameters.set(match[1], match[2]);
match = pattern.exec(docString);
}
return parameters;
}
private removeParamDocStrings(docString: string | undefined... | private parseParamDocStrings(docString: string | undefined) {
const parameters = new Map<string, string>();
if (!docString) {
return parameters;
} | random_line_split |
specification.tsx | /*
* Copyright 2018 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless r... |
private getTypeLink(name: string, type: 'enum' | 'struct') {
return (
<Link key={`/${type}s/${name}`} to={`/${type}s/${name}`}>
{simpleName(name)}
</Link>
);
}
private updateDocStrings() {
for (const service of this.data.services) {
for (const method of service.methods) {
... | {
let type: Enum | Struct | undefined = this.enumsByName.get(part);
if (type) {
return this.getTypeLink(type.name, 'enum');
}
type = this.structsByName.get(part);
if (type) {
return this.getTypeLink(type.name, 'struct');
}
return simpleName(part);
} | identifier_body |
__init__.py | # -*- encoding: utf-8 -*-
############################################################################## | #
# OpenERP, Open Source Management Solution
#
# Copyright (c) 2013-2015 Noviat nv/sa (www.noviat.com).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 o... | random_line_split | |
markers.py | ''' Display a variety of simple scatter marker shapes whose attributes
can be associated with data columns from ``ColumnDataSources``.
The full list of markers built into Bokeh is given below:
* :class:`~bokeh.models.markers.Asterisk`
* :class:`~bokeh.models.markers.Circle`
* :class:`~bokeh.models.markers.CircleCross... | a radius in addition to a size. Only one of ``radius`` or ``size``
should be given.
.. warning::
Note that ``Circle`` glyphs are always drawn as circles on the screen,
even in cases where the data space aspect ratio is not 1-1. In all
cases where radius values are specified,... | random_line_split | |
markers.py | ''' Display a variety of simple scatter marker shapes whose attributes
can be associated with data columns from ``ColumnDataSources``.
The full list of markers built into Bokeh is given below:
* :class:`~bokeh.models.markers.Asterisk`
* :class:`~bokeh.models.markers.Circle`
* :class:`~bokeh.models.markers.CircleCross... | (Marker):
''' Render circle markers with a '+' cross through the center. '''
__example__ = "examples/reference/models/CircleCross.py"
class CircleX(Marker):
''' Render circle markers with an 'X' cross through the center. '''
__example__ = "examples/reference/models/CircleX.py"
class Cross(Marker):
... | CircleCross | identifier_name |
markers.py | ''' Display a variety of simple scatter marker shapes whose attributes
can be associated with data columns from ``ColumnDataSources``.
The full list of markers built into Bokeh is given below:
* :class:`~bokeh.models.markers.Asterisk`
* :class:`~bokeh.models.markers.Circle`
* :class:`~bokeh.models.markers.CircleCross... |
class DiamondCross(Marker):
''' Render diamond markers with a '+' cross through the center. '''
__example__ = "examples/reference/models/DiamondCross.py"
class Hex(Marker):
''' Render hexagon markers. '''
__example__ = "examples/reference/models/Hex.py"
class InvertedTriangle(Marker):
''' Rend... | ''' Render diamond markers. '''
__example__ = "examples/reference/models/Diamond.py" | identifier_body |
after.js | var toInteger = require('./toInteger');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @category Fu... | if (--n < 1) {
return func.apply(this, arguments);
}
};
}
module.exports = after; | throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() { | random_line_split |
after.js | var toInteger = require('./toInteger');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @category Fu... | (n, func) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
module.exports = after;
| after | identifier_name |
after.js | var toInteger = require('./toInteger');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @category Fu... |
n = toInteger(n);
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
module.exports = after;
| {
throw new TypeError(FUNC_ERROR_TEXT);
} | conditional_block |
after.js | var toInteger = require('./toInteger');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @category Fu... |
module.exports = after;
| {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
} | identifier_body |
mnist-visualizations.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: mnist-visualizations.py
"""
The same MNIST ConvNet example, but with weights/activations visualization.
"""
import tensorflow as tf
from tensorpack import *
from tensorpack.dataflow import dataset
IMAGE_SIZE = 28
def visualize_conv_weights(filters, name):
"... | filters: tensor containing the weights [H,W,Cin,Cout]
name: label for tensorboard
Returns:
image of all weight
"""
with tf.name_scope('visualize_w_' + name):
filters = tf.transpose(filters, (3, 2, 0, 1)) # [h, w, cin, cout] -> [cout, cin, h, w]
filters = tf.unstack... |
Args: | random_line_split |
mnist-visualizations.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: mnist-visualizations.py
"""
The same MNIST ConvNet example, but with weights/activations visualization.
"""
import tensorflow as tf
from tensorpack import *
from tensorpack.dataflow import dataset
IMAGE_SIZE = 28
def visualize_conv_weights(filters, name):
"... | ():
train = BatchData(dataset.Mnist('train'), 128)
test = BatchData(dataset.Mnist('test'), 256, remainder=True)
return train, test
if __name__ == '__main__':
logger.auto_set_dir()
dataset_train, dataset_test = get_data()
config = TrainConfig(
model=Model(),
dataflow=dataset_tr... | get_data | identifier_name |
mnist-visualizations.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: mnist-visualizations.py
"""
The same MNIST ConvNet example, but with weights/activations visualization.
"""
import tensorflow as tf
from tensorpack import *
from tensorpack.dataflow import dataset
IMAGE_SIZE = 28
def visualize_conv_weights(filters, name):
"... | visualize_conv_weights(c3.variables.W, 'conv3')
visualize_conv_activations(c3, 'conv3')
tf.summary.image('input', (image + 1.0) * 128., 3)
cost = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label)
cost = tf.reduce_mean(cost, name='cross_entr... | image = tf.expand_dims(image * 2 - 1, 3)
with argscope(Conv2D, kernel_shape=3, nl=tf.nn.relu, out_channel=32):
c0 = Conv2D('conv0', image)
p0 = MaxPooling('pool0', c0, 2)
c1 = Conv2D('conv1', p0)
c2 = Conv2D('conv2', c1)
p1 = MaxPooling('pool1', c2, 2... | identifier_body |
mnist-visualizations.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: mnist-visualizations.py
"""
The same MNIST ConvNet example, but with weights/activations visualization.
"""
import tensorflow as tf
from tensorpack import *
from tensorpack.dataflow import dataset
IMAGE_SIZE = 28
def visualize_conv_weights(filters, name):
"... | logger.auto_set_dir()
dataset_train, dataset_test = get_data()
config = TrainConfig(
model=Model(),
dataflow=dataset_train,
callbacks=[
ModelSaver(),
InferenceRunner(
dataset_test, ScalarStats(['cross_entropy_loss', 'accuracy'])),
],
... | conditional_block | |
propagate-multiple-requirements.rs | // Test that we propagate *all* requirements to the caller, not just the first
// one.
#![feature(nll)]
fn once<S, T, U, F: FnOnce(S, T) -> U>(f: F, s: S, t: T) -> U |
pub fn dangle() -> &'static [i32] {
let other_local_arr = [0, 2, 4];
let local_arr = other_local_arr;
let mut out: &mut &'static [i32] = &mut (&[1] as _);
once(|mut z: &[i32], mut out_val: &mut &[i32]| {
// We unfortunately point to the first use in the closure in the error
// message
... | {
f(s, t)
} | identifier_body |
propagate-multiple-requirements.rs | // Test that we propagate *all* requirements to the caller, not just the first
// one.
#![feature(nll)] | pub fn dangle() -> &'static [i32] {
let other_local_arr = [0, 2, 4];
let local_arr = other_local_arr;
let mut out: &mut &'static [i32] = &mut (&[1] as _);
once(|mut z: &[i32], mut out_val: &mut &[i32]| {
// We unfortunately point to the first use in the closure in the error
// message
... |
fn once<S, T, U, F: FnOnce(S, T) -> U>(f: F, s: S, t: T) -> U {
f(s, t)
}
| random_line_split |
propagate-multiple-requirements.rs | // Test that we propagate *all* requirements to the caller, not just the first
// one.
#![feature(nll)]
fn | <S, T, U, F: FnOnce(S, T) -> U>(f: F, s: S, t: T) -> U {
f(s, t)
}
pub fn dangle() -> &'static [i32] {
let other_local_arr = [0, 2, 4];
let local_arr = other_local_arr;
let mut out: &mut &'static [i32] = &mut (&[1] as _);
once(|mut z: &[i32], mut out_val: &mut &[i32]| {
// We unfortunately ... | once | identifier_name |
find-cli-tree.ts | import { ICliTree, TCliRoot } from './cli-tree';
import { CLI_COMMAND } from './cli-command';
import { CLI_COMMAND_GROUP } from './cli-command-group';
/**
* The result of calling [[`findCliTree`]]
*/
export interface IFindCliTreeResult extends ICliTree {
/** Passed args past those used during navigation */
args: s... |
return recursiveFindCliTree({
parents: [...result.parents, result.current],
current: next,
args: result.args.slice(1),
});
}
throw new Error('Unexpected kind');
}
| {
// E.g. Should be "cli login". Is "cli log".
return { ...result, message: `Bad command "${result.args[0]}"` };
} | conditional_block |
find-cli-tree.ts | import { ICliTree, TCliRoot } from './cli-tree';
import { CLI_COMMAND } from './cli-command';
import { CLI_COMMAND_GROUP } from './cli-command-group';
/**
* The result of calling [[`findCliTree`]]
*/
export interface IFindCliTreeResult extends ICliTree {
/** Passed args past those used during navigation */
args: s... | });
}
throw new Error('Unexpected kind');
} | current: next,
args: result.args.slice(1), | random_line_split |
find-cli-tree.ts | import { ICliTree, TCliRoot } from './cli-tree';
import { CLI_COMMAND } from './cli-command';
import { CLI_COMMAND_GROUP } from './cli-command-group';
/**
* The result of calling [[`findCliTree`]]
*/
export interface IFindCliTreeResult extends ICliTree {
/** Passed args past those used during navigation */
args: s... | (result: IFindCliTreeResult): IFindCliTreeResult {
// Terminate recursion if current is a command
if (result.current.kind === CLI_COMMAND) {
return result;
}
if (result.current.kind === CLI_COMMAND_GROUP) {
if (result.args.length === 0) {
// Example: Full command is "cli user login". They've done "cli user"... | recursiveFindCliTree | identifier_name |
find-cli-tree.ts | import { ICliTree, TCliRoot } from './cli-tree';
import { CLI_COMMAND } from './cli-command';
import { CLI_COMMAND_GROUP } from './cli-command-group';
/**
* The result of calling [[`findCliTree`]]
*/
export interface IFindCliTreeResult extends ICliTree {
/** Passed args past those used during navigation */
args: s... | );
if (!next) {
// E.g. Should be "cli login". Is "cli log".
return { ...result, message: `Bad command "${result.args[0]}"` };
}
return recursiveFindCliTree({
parents: [...result.parents, result.current],
current: next,
args: result.args.slice(1),
});
}
throw new Error('Unexpected kind');
... | {
// Terminate recursion if current is a command
if (result.current.kind === CLI_COMMAND) {
return result;
}
if (result.current.kind === CLI_COMMAND_GROUP) {
if (result.args.length === 0) {
// Example: Full command is "cli user login". They've done "cli user". In
// this case we want to print the usage s... | identifier_body |
URLSearchParams.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Sdk = require('./Sdk');
var _Sdk2 = _interopRequireDefault(_Sdk);
var _global = require('./global');
var _global2 = _interopRequireDefault(_global);
function _interopRequireDefault(obj) |
exports.default = {
load: function load() {
var _this = this;
if (typeof _global2.default.URLSearchParams === 'function') {
this.URLSearchParams = _global2.default.URLSearchParams;
return _Sdk2.default.Promise.resolve();
}
return new _Sdk2.default.Promise(function (resolve) {
if ... | { return obj && obj.__esModule ? obj : { default: obj }; } | identifier_body |
URLSearchParams.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Sdk = require('./Sdk');
var _Sdk2 = _interopRequireDefault(_Sdk);
var _global = require('./global');
var _global2 = _interopRequireDefault(_global);
function | (obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
load: function load() {
var _this = this;
if (typeof _global2.default.URLSearchParams === 'function') {
this.URLSearchParams = _global2.default.URLSearchParams;
return _Sdk2.default.Promise.resolve();
}
... | _interopRequireDefault | identifier_name |
URLSearchParams.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Sdk = require('./Sdk'); | var _Sdk2 = _interopRequireDefault(_Sdk);
var _global = require('./global');
var _global2 = _interopRequireDefault(_global);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
load: function load() {
var _this = this;
if (typeof _global2.de... | random_line_split | |
URLSearchParams.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Sdk = require('./Sdk');
var _Sdk2 = _interopRequireDefault(_Sdk);
var _global = require('./global');
var _global2 = _interopRequireDefault(_global);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { def... |
return new _Sdk2.default.Promise(function (resolve) {
if (typeof require.ensure !== 'function') {
require.ensure = function (dependencies, callback) {
callback(require);
};
}
require.ensure(['url-search-params'], function (require) {
_this.URLSearchParams = req... | {
this.URLSearchParams = _global2.default.URLSearchParams;
return _Sdk2.default.Promise.resolve();
} | conditional_block |
ShowProfile.js | // @flow
import React, { Component } from 'react'
import { withStyles } from 'material-ui/styles'
import Profile from 'models/Profile'
import IconButton from 'material-ui/IconButton'
import Typography from 'material-ui/Typography'
import FontAwesome from 'react-fontawesome'
import Avatar from 'components/common/Avatar'... | textAlign: 'center',
flexGrow: 1,
},
lateral: {
width: '20px !important',
},
})
export default withStyles(style)(ShowProfile) | identity: {
margin: '0 10px 0 !important',
fontSize: '2em !important', | random_line_split |
ShowProfile.js | // @flow
import React, { Component } from 'react'
import { withStyles } from 'material-ui/styles'
import Profile from 'models/Profile'
import IconButton from 'material-ui/IconButton'
import Typography from 'material-ui/Typography'
import FontAwesome from 'react-fontawesome'
import Avatar from 'components/common/Avatar'... | extends Component {
props: {
profile: Profile,
onEditClick: () => any
}
render() {
const { classes, profile } = this.props
return (
<div>
<div className={classes.header}>
<div className={classes.lateral} />
<Typography className={classes.identity}>{profile.ide... | ShowProfile | identifier_name |
stopTick.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... | conditional_block | ||
stopTick.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... | ect);
}
} | ,thisObj | identifier_name |
stopTick.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... | // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLI... | random_line_split | |
stopTick.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... | identifier_body | ||
__init__.py | """Emission python module
This module is for everyone who wants to build tools / systems for calculating vehicle
emissions for various types of vehicles (Trucks, Buses, Cars, Vans, scooters, ..).
The calculation and factors is provided by the EU EEA guidebook: http://www.eea.europa.eu/publications/emep-eea-guidebook-... | log = logging.getLogger("emission")
from .Extrapolate import Extrapolate
from .Interpolate import Interpolate
from .Pollutants import Pollutants
from .EmissionJSONReader import EmissionsJsonParser
from .planner import Planner
from .planner import PollutantTypes
from .__version__ import __version__
__author__ = "NPR... | For the transportation industry this will be of great importance.
"""
import logging | random_line_split |
renamer.js | "use strict";
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule =... |
},
"AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) {
var ids = path.getOuterBindingIdentifiers();
for (var _name in ids) {
if (_name === state.oldName) ids[_name].name = state.newName;
}
}
};
var Renamer = (function () {
function Renamer(binding, o... | {
path.skip();
} | conditional_block |
renamer.js | "use strict";
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule =... |
Renamer.prototype.maybeConvertFromClassFunctionExpression = function maybeConvertFromClassFunctionExpression(path) {
return; // TODO
// retain the `name` of a class/function expression
if (!path.isFunctionExpression() && !path.isClassExpression()) return;
if (this.binding.kind !== "local") return;
... | path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(t.identifier(this.newName), t.toExpression(path.node))]));
}; | random_line_split |
renamer.js | "use strict";
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule =... |
Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) {
var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath;
if (!exportDeclar) return;
// build specifiers that point back to this export declaration
var... | {
_classCallCheck(this, Renamer);
this.newName = newName;
this.oldName = oldName;
this.binding = binding;
} | identifier_body |
renamer.js | "use strict";
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule =... | (binding, oldName, newName) {
_classCallCheck(this, Renamer);
this.newName = newName;
this.oldName = oldName;
this.binding = binding;
}
Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) {
var exportDeclar = parentDeclar.parentPath.is... | Renamer | identifier_name |
res_partner_btree.py | # -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2013 Vauxoo - http://www.vauxoo.com/
# All Rights Reserved.
# info Vauxoo (info@vauxoo.com)
####################################... | _inherit = 'res.partner'
_order = "parent_left"
_parent_order = "ref"
_parent_store = True
_columns = {
'parent_right': fields.integer('Parent Right', select=1),
'parent_left': fields.integer('Parent Left', select=1),
} | identifier_body | |
res_partner_btree.py | # -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2013 Vauxoo - http://www.vauxoo.com/
# All Rights Reserved.
# info Vauxoo (info@vauxoo.com)
####################################... | (osv.Model):
_inherit = 'res.partner'
_order = "parent_left"
_parent_order = "ref"
_parent_store = True
_columns = {
'parent_right': fields.integer('Parent Right', select=1),
'parent_left': fields.integer('Parent Left', select=1),
}
| res_partner | identifier_name |
res_partner_btree.py | # -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution | ############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your o... | #
# Copyright (c) 2013 Vauxoo - http://www.vauxoo.com/
# All Rights Reserved.
# info Vauxoo (info@vauxoo.com) | random_line_split |
Node.js | BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
var React = require('react');
var assign = require('object-assign');
var decorate = require('./decora... | (nextProps: PropsType) {
return nextProps !== this.props;
}
componentDidMount() {
if (this.props.selected) {
this.ensureInView();
}
}
componentDidUpdate(prevProps) {
if (this.props.selected && !prevProps.selected) {
this.ensureInView();
}
}
ensureInView() {
var node = ... | shouldComponentUpdate | identifier_name |
Node.js | -style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
var React = require('react');
var assign = require('object-assign');
var decorate = require('./decorate')... | else if (nodeType === 'Empty') {
tag =
<span style={styles.tagText}>
<span style={styles.falseyLiteral}>null</span>
</span>;
}
return (
<div style={styles.container}>
<div style={headStyles} ref={h => this._head = h} {...tagEvents}>
{tag... | {
var content = node.get('text');
tag =
<span style={styles.tagText}>
<span style={styles.openTag}>
"
</span>
<span style={styles.textContent}>{content}</span>
<span style={styles.closeTag}>
"
</span>
... | conditional_block |
Node.js | BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
var React = require('react');
var assign = require('object-assign');
var decorate = require('./decora... | wrappedChildren: ?Array<any>,
onHover: (isHovered: boolean) => void,
onContextMenu: () => void,
onToggleCollapse: () => void,
onSelectBottom: () => void,
onSelect: () => void,
};
class Node {
_head: Object;
_tail: Object;
context: Object;
props: PropsType;
static contextTypes: Object;
shouldC... | hovered: boolean,
selected: boolean,
node: Map,
depth: number,
isBottomTagSelected: boolean, | random_line_split |
Node.js | -style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
var React = require('react');
var assign = require('object-assign');
var decorate = require('./decorate')... |
ensureInView() {
var node = this.props.isBottomTagSelected ? this._tail : this._head;
if (!node) {
return;
}
var domnode = React.findDOMNode(node);
this.context.scrollTo(domnode.offsetTop, domnode.offsetHeight);
}
render(): ReactElement {
var node = this.props.node;
if (!node)... | {
if (this.props.selected && !prevProps.selected) {
this.ensureInView();
}
} | identifier_body |
vmfs_datastore_create_spec.py |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VmfsDatastoreCreateSpec(vim, *args, **kwargs):
'''This data object type is used when ... |
return obj
| raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) | conditional_block |
vmfs_datastore_create_spec.py |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def | (vim, *args, **kwargs):
'''This data object type is used when creating a new VMFS datastore, to create a
specification for the VMFS datastore.'''
obj = vim.client.factory.create('ns0:VmfsDatastoreCreateSpec')
# do some validation checking...
if (len(args) + len(kwargs)) < 3:
raise Inde... | VmfsDatastoreCreateSpec | identifier_name |
vmfs_datastore_create_spec.py | import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VmfsDatastoreCreateSpec(vim, *args, **kwargs):
'''This data object type is used when c... | if name in required + optional:
setattr(obj, name, value)
else:
raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional)))
return obj |
for name, arg in zip(required+optional, args):
setattr(obj, name, arg)
for name, value in kwargs.items(): | random_line_split |
vmfs_datastore_create_spec.py |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VmfsDatastoreCreateSpec(vim, *args, **kwargs):
|
return obj
| '''This data object type is used when creating a new VMFS datastore, to create a
specification for the VMFS datastore.'''
obj = vim.client.factory.create('ns0:VmfsDatastoreCreateSpec')
# do some validation checking...
if (len(args) + len(kwargs)) < 3:
raise IndexError('Expected at least 4 ... | identifier_body |
vj_serial.py | import logging
import struct
import threading
import serial
import serial.tools.list_ports
COMMAND_TO_CHANNEL = {
'F': 0x00,
'W': 0x01,
'H': 0x02,
'C': 0x03
}
class SerialPort(object):
def __init__(self, port_name):
self.port_name = port_name
self.serial_port = None
self.serial_lock = None
self.log_thr... |
def send_serial_command(self, command, value):
if not self.serial_port:
self.initSerialPort()
if self.serial_port:
try:
self._send_serial_command(command, value)
except IOError:
self.initSerialPort()
self._send_serial_command(command, value)
def get_serial_port_device(self):
ports = ser... | logging.error("Not sending %s, %s - no serial port?", command, value) | conditional_block |
vj_serial.py | import logging
import struct
import threading
import serial
import serial.tools.list_ports
COMMAND_TO_CHANNEL = {
'F': 0x00,
'W': 0x01,
'H': 0x02,
'C': 0x03
}
class SerialPort(object):
def __init__(self, port_name):
self.port_name = port_name
self.serial_port = None
self.serial_lock = None
self.log_thr... | (self, command, value):
if command not in COMMAND_TO_CHANNEL:
logging.error("Unknown command: %s", command)
return
message = self.int2bin(0xF6) + self.int2bin(0x6F) + self.int2bin(0x04) + self.int2bin(COMMAND_TO_CHANNEL[command]) + self.int2bin(value)
if self.serial_port:
try:
self.serial_lock.acqu... | _send_serial_command | identifier_name |
vj_serial.py | import logging
import struct
import threading
import serial
import serial.tools.list_ports
COMMAND_TO_CHANNEL = {
'F': 0x00,
'W': 0x01,
'H': 0x02,
'C': 0x03
}
class SerialPort(object):
def __init__(self, port_name):
self.port_name = port_name
self.serial_port = None
self.serial_lock = None
self.log_thr... |
@staticmethod
def int2bin(value):
return struct.pack('!B', value)
@staticmethod
def bin2int(value):
if isinstance(value, int):
return value
return struct.unpack('!B', value)[0]
def close(self):
# Close serial port
logging.info("Close serial port")
if self.serial_port is not None and self.serial_... | ports = serial.tools.list_ports.grep(self.port_name)
try:
return next(ports).device
except StopIteration:
return None | identifier_body |
vj_serial.py | import logging
import struct
import threading
import serial
import serial.tools.list_ports
COMMAND_TO_CHANNEL = {
'F': 0x00,
'W': 0x01,
'H': 0x02,
'C': 0x03
}
class SerialPort(object):
def __init__(self, port_name):
self.port_name = port_name
self.serial_port = None
self.serial_lock = None
self.log_thr... |
def get_serial_port_device(self):
ports = serial.tools.list_ports.grep(self.port_name)
try:
return next(ports).device
except StopIteration:
return None
@staticmethod
def int2bin(value):
return struct.pack('!B', value)
@staticmethod
def bin2int(value):
if isinstance(value, int):
return value
... | self._send_serial_command(command, value)
except IOError:
self.initSerialPort()
self._send_serial_command(command, value) | random_line_split |
Painting.js | import { attempt } from "./stats.js";
import { between, betweenHigh } from "./math.js";
import { weightMap, weightAverage } from "./weightMap.js";
import Shape from "./Shape.js";
const COST_SCORE_RATIO = 1000;
export const paintingBaseSize = 100;
function setText(element, text) {
element.innerText = element.textCo... | () {
return this.shapes
.map(shape => shape.cost())
.reduce((sum, cost) => sum + cost, 0);
}
}
Painting.width = paintingBaseSize;
Painting.height = paintingBaseSize;
| cost | identifier_name |
Painting.js | import { attempt } from "./stats.js";
import { between, betweenHigh } from "./math.js";
import { weightMap, weightAverage } from "./weightMap.js";
import Shape from "./Shape.js";
const COST_SCORE_RATIO = 1000;
export const paintingBaseSize = 100;
function setText(element, text) {
element.innerText = element.textCo... |
}
diffScore(canvas, targetData) {
const ctx = canvas.getContext("2d");
let score = 0;
const data = ctx.getImageData(0, 0, target.width, target.height).data;
let w = weightMap.length;
let i = data.length;
while (i) {
--i;
const db = data[--i] - targetData[i];
const dg = da... | {
const label = `~${this.scoreError.toPrecision(
5
)} $${this.scoreCost.toFixed(2)}`;
return setText(box.children[1], label);
} | conditional_block |
Painting.js | import { attempt } from "./stats.js";
import { between, betweenHigh } from "./math.js";
import { weightMap, weightAverage } from "./weightMap.js";
import Shape from "./Shape.js";
const COST_SCORE_RATIO = 1000;
export const paintingBaseSize = 100;
function setText(element, text) {
element.innerText = element.textCo... | const ctx = canvas.getContext("2d");
const testData = ctx.getImageData(0, 0, target.width, target.height).data;
const diffData = ctx.createImageData(target.width, target.height);
const ddd = diffData.data;
let i = ddd.length;
while (i) {
ddd[--i] = 255;
ddd[--i] = Math.abs(testData[i... | return (this.score = this.scoreError + this.scoreCost);
}
paintDiffMap(canvas, targetData) {
this.paint(canvas); | random_line_split |
Painting.js | import { attempt } from "./stats.js";
import { between, betweenHigh } from "./math.js";
import { weightMap, weightAverage } from "./weightMap.js";
import Shape from "./Shape.js";
const COST_SCORE_RATIO = 1000;
export const paintingBaseSize = 100;
function setText(element, text) |
export default class Painting {
constructor(shapes) {
this.shapes = shapes != null ? shapes : [new Shape()];
this.score = 1 / 0;
this.maturity = 0;
this.age = 0;
}
paint(canvas, opaque) {
let ctx, i$, ref$, len$, shape;
ctx = canvas.getContext("2d");
if (opaque) {
ctx.fillStyl... | {
element.innerText = element.textContent = text;
} | identifier_body |
generalCtable.ts | Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import {TextTypes} from '../../types/common';
import {FreqResultResponse} from '../../types/ajaxResponses';
import * as Immutable from 'immutable';
import {StatefulModel} from '../base';
import {PageModel} from '../../app/... | getConcSelectedTextTypes | identifier_name | |
generalCtable.ts | can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* dated June, 1991.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTAB... | const begin2 = this.ctFcrit2;
const end2 = this.ctFcrit2;
args.set('q2', `p${begin2} ${end2} 0 [${this.attr2}="${icase2}${v2}"] within <${s1} ${a1}="${v1}" />`);
} else {
const icase1 = ''; // TODO - optionally (?i)
const begin1 = this.ctFcrit1;
... | {
const args = this.pageModel.getConcArgs();
if (this.isStructAttr(this.attr1) && this.isStructAttr(this.attr2)) {
const [s1, a1] = this.attr1.split('.');
const [s2, a2] = this.attr2.split('.');
args.set('q2', `p0 0 1 [] within <${s1} ${a1}="${v1}" /> within <${s2} $... | identifier_body |
generalCtable.ts | you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* dated June, 1991.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHA... | * import to indices within sorted list of these items according
* to the current freq. mode (ipm, abs). This is used when filtering
* values by percentile.
*/
abstract createPercentileSortMapping():Immutable.Map<number, number>;
/**
*
*/
protected createMinFreqFilterFn():(CTFr... | }
/**
* Generate a mapping from original items' order generated during | random_line_split |
index.d.ts | // Type definitions for react-typist 2.0
// Project: https://github.com/jstejada/react-typist#readme
// Definitions by: Shawn Choi <https://github.com/shawnkoon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.1
import * as React from 'react';
export namespace Typist {
... | extends React.Component<TypistProps> {}
export default Typist;
| Typist | identifier_name |
index.d.ts | // Type definitions for react-typist 2.0
// Project: https://github.com/jstejada/react-typist#readme
// Definitions by: Shawn Choi <https://github.com/shawnkoon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.1
import * as React from 'react'; | element?: string | undefined;
hideWhenDone?: boolean | undefined;
hideWhenDoneDelay?: number | undefined;
}
interface CurrentTextProps {
line: string;
lineIdx: number;
character: string;
charIdx: number;
defDelayGenerator: (mn: number, st: number)... |
export namespace Typist {
interface CursorProps {
show?: boolean | undefined;
blink?: boolean | undefined; | random_line_split |
DummyEffectGlyph.ts | import { Color } from '@src/model/Color';
import { ICanvas } from '@src/platform/ICanvas';
import { EffectGlyph } from '@src/rendering/glyphs/EffectGlyph';
export class DummyEffectGlyph extends EffectGlyph {
private _w:number;
private _h:number;
public constructor(x: number, y: number, w: number = 20, h: ... | canvas.color = c;
}
} | let c = canvas.color;
canvas.color = Color.random();
canvas.fillRect(cx + this.x, cy + this.y, this.width, this.height); | random_line_split |
DummyEffectGlyph.ts | import { Color } from '@src/model/Color';
import { ICanvas } from '@src/platform/ICanvas';
import { EffectGlyph } from '@src/rendering/glyphs/EffectGlyph';
export class DummyEffectGlyph extends EffectGlyph {
private _w:number;
private _h:number;
public constructor(x: number, y: number, w: number = 20, h: ... | (): void {
this.width = this._w * this.scale;
this.height = this._h * this.scale;
}
public override paint(cx: number, cy: number, canvas: ICanvas): void {
let c = canvas.color;
canvas.color = Color.random();
canvas.fillRect(cx + this.x, cy + this.y, this.width, this.hei... | doLayout | identifier_name |
inputhandler.py | '''
File: input.py
Author: Tristan van Vaalen
Handles user input
'''
import signal
import sys
import verbose
v = verbose.Verbose()
class InputHandler():
def __init__(self):
v.debug('Initializing input handler').indent()
self.running = True
self.signal_level = 0
v.debug('Regist... | v.write(
'Invalid command \'{}\'. Try \'help\' for a list of commands'
.format(raw)
) | conditional_block | |
inputhandler.py | '''
File: input.py
Author: Tristan van Vaalen
Handles user input
'''
import signal
import sys
import verbose
v = verbose.Verbose()
class InputHandler():
def __init__(self): | self.signal_level = 0
v.debug('Registering signal handler').unindent()
signal.signal(signal.SIGINT, self.signal_handler)
def test(self):
pass
def signal_handler(self, signal, frame):
self.signal_level += 1
if self.signal_level == 1:
self.running = ... | v.debug('Initializing input handler').indent()
self.running = True | random_line_split |
inputhandler.py | '''
File: input.py
Author: Tristan van Vaalen
Handles user input
'''
import signal
import sys
import verbose
v = verbose.Verbose()
class InputHandler():
def __init__(self):
v.debug('Initializing input handler').indent()
self.running = True
self.signal_level = 0
v.debug('Regist... |
def _parse_input(self, raw):
raw = raw.strip()
if raw in ['help', 'h', '?']:
self.output_options()
elif raw in ['quit', 'exit', 'stop', 'abort']:
self.running = False
elif raw in ['test']:
self.test()
else:
v.write(
... | v.debug('Entering input loop')
v.write('AUDIOLYZE v0.01\nPress ctrl+D to exit')
while self.running:
try:
self._parse_input(raw_input('>>> '))
except EOFError:
v.write('EOF received')
self.running = False
v.write('Goodbye') | identifier_body |
inputhandler.py | '''
File: input.py
Author: Tristan van Vaalen
Handles user input
'''
import signal
import sys
import verbose
v = verbose.Verbose()
class | ():
def __init__(self):
v.debug('Initializing input handler').indent()
self.running = True
self.signal_level = 0
v.debug('Registering signal handler').unindent()
signal.signal(signal.SIGINT, self.signal_handler)
def test(self):
pass
def signal_handler(self... | InputHandler | identifier_name |
typed.js | this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnish... | // less than the stop number, keep going
if (curStrPos > self.stopNum){
// subtract characters one by one
curStrPos--;
// loop the function
self.backspace(... | // replace text with current text + typed characters
self.el.text(self.text + curString.substr(0, curStrPos));
// if the number (id of character in current string) is
| random_line_split |
typed.js | this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnish... |
// contain typing function in a timeout humanize'd delay
self.timeout = setTimeout(function() {
// check for an escape character before a pause value
// format: \^\d+ eg: ^1000 should be able to print the ^ too using ^^
... | {
self.stopNum = 0;
self.backDelay = self.options.backDelay;
} | conditional_block |
CacheItemInterface.d.ts | declare namespace Jymfony.Component.Cache {
import DateTime = Jymfony.Component.DateTime.DateTime;
import TimeSpan = Jymfony.Component.DateTime.TimeSpan;
/**
* CacheItemInterface defines an interface for interacting with objects inside a cache.
*
* Each Item object MUST be associated with a ... | * Calling Libraries MUST NOT instantiate Item objects themselves. They may only
* be requested from a Pool object via the getItem() method. Calling Libraries
* SHOULD NOT assume that an Item created by one Implementing Library is
* compatible with a Pool from another Implementing Library.
*/
... | random_line_split | |
CacheItemInterface.d.ts | declare namespace Jymfony.Component.Cache {
import DateTime = Jymfony.Component.DateTime.DateTime;
import TimeSpan = Jymfony.Component.DateTime.TimeSpan;
/**
* CacheItemInterface defines an interface for interacting with objects inside a cache.
*
* Each Item object MUST be associated with a ... | <T> implements MixinInterface {
public static readonly definition: Newable<CacheItemInterface<any>>;
/**
* Returns the key for the current cache item.
*
* The key is loaded by the Implementing Library, but should be available to
* the higher level callers when needed... | CacheItemInterface | identifier_name |
app.component.spec.ts | /* tslint:disable:no-unused-variable */
import {TestBed} from '@angular/core/testing';
import {AppComponent} from './app.component';
import {AuthService} from './shared/auth/auth.service';
import {RouterTestingModule} from '@angular/router/testing';
import {COMMON_TESTING_MODULES, COMMON_TESING_PROVIDERS} from './test... | pathMatch: 'prefix',
component: AppComponent
}]),
],
declarations: [
AppComponent
],
});
});
it('should create the app', () => {
let fixture = TestBed.createComponent(AppComponent);
let app = fixture.debugElement.componentInstance;
expect(app).t... | RouterTestingModule.withRoutes([{
path: '', | random_line_split |
lang_items.rs | table.
// So you probably just want to nip down to the end.
macro_rules! lets_do_this {
(
$( $variant:ident, $name:expr, $method:ident; )*
) => {
enum_from_u32! {
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub enum LangItem {
$($variant,)*
}
}
pub struct LanguageItems {
pub ... | BitAndTraitLangItem, "bitand", bitand_trait;
BitOrTraitLangItem, "bitor", bitor_trait;
ShlTraitLangItem, "shl", shl_trait;
ShrTraitLangItem, "shr", shr_trait;
IndexTraitL... | random_line_split | |
Typescript.tsx | /** @jsxRuntime classic */
/** @jsx jsx */
import { jsx } from '@emotion/react';
import { Gradients, IconProps } from './util';
export function Typescript({ grad, ...props }: IconProps) | }
| {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
aria-label="Typescript"
role="img"
fill="none"
stroke={grad ? `url(#Typescript-${grad})` : 'currentColor'}
{...props}
>
<Gradients name="Typescript" />
<path
strokeLinecap="roun... | identifier_body |
Typescript.tsx | /** @jsxRuntime classic */
/** @jsx jsx */
import { jsx } from '@emotion/react';
import { Gradients, IconProps } from './util';
export function Typescript({ grad, ...props }: IconProps) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
aria-label="Typescript"
role="i... | >
<Gradients name="Typescript" />
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M11.0278 6H7.02777H3.02777 M7.02777 6V18 M20.9723 8.30769C20.9723 7.84615 20.0973 6 17.4723 6C14.8473 6 13.9723 7.84615 13.9723 8.76923C13.9723 10.6154 14.8473 11.5385 ... | fill="none"
stroke={grad ? `url(#Typescript-${grad})` : 'currentColor'}
{...props} | random_line_split |
Typescript.tsx | /** @jsxRuntime classic */
/** @jsx jsx */
import { jsx } from '@emotion/react';
import { Gradients, IconProps } from './util';
export function | ({ grad, ...props }: IconProps) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
aria-label="Typescript"
role="img"
fill="none"
stroke={grad ? `url(#Typescript-${grad})` : 'currentColor'}
{...props}
>
<Gradients name="Typescript" />
<... | Typescript | identifier_name |
1.run_find_repos.py | from glob import glob
import numpy
import pickle
import os
# Run iterations of "count" to count the number of terms in each folder of zipped up pubmed articles
home = os.environ["HOME"]
scripts = "%s/SCRIPT/repofish/analysis/methods" %(home)
base = "%s/data/pubmed" %os.environ["LAB"]
outfolder = "%s/repos" %(base)
ar... | # Prepare and submit a job for each
for i in range(iters):
start = i*int(batch_size)
if i != iters:
end = start + int(batch_size)
else:
end = len(folders)
subset = folders[start:end]
script_file = "%s/findgithub_%s.job" %(scripts,i)
filey = open(script_file,'w')
filey.writel... | batch_size = 1000.0
iters = int(numpy.ceil(len(folders)/batch_size))
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.