file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
index.js | import { createFilter, makeLegalIdentifier } from 'rollup-pluginutils';
export default function | (options = {}) {
const filter = createFilter(options.include, options.exclude);
return {
name: 'json',
transform(json, id) {
if (id.slice(-5) !== '.json') return null;
if (!filter(id)) return null;
const data = JSON.parse(json);
let code = '';
const ast = {
type: 'Program',
sourceType: ... | json | identifier_name |
index.js | import { createFilter, makeLegalIdentifier } from 'rollup-pluginutils';
export default function json(options = {}) {
const filter = createFilter(options.include, options.exclude);
return {
name: 'json',
transform(json, id) {
if (id.slice(-5) !== '.json') return null;
if (!filter(id)) return null;
con... | else {
const indent = 'indent' in options ? options.indent : '\t';
const validKeys = [];
const invalidKeys = [];
Object.keys(data).forEach(key => {
if (key === makeLegalIdentifier(key)) {
validKeys.push(key);
} else {
invalidKeys.push(key);
}
});
let char = 0;
... | {
code = `export default ${json};`;
ast.body.push({
type: 'ExportDefaultDeclaration',
start: 0,
end: code.length,
declaration: {
type: 'Literal',
start: 15,
end: code.length - 1,
value: null,
raw: 'null'
}
});
} | conditional_block |
index.js | import { createFilter, makeLegalIdentifier } from 'rollup-pluginutils';
export default function json(options = {}) {
const filter = createFilter(options.include, options.exclude);
return {
name: 'json',
transform(json, id) {
if (id.slice(-5) !== '.json') return null;
if (!filter(id)) return null;
con... | });
char = end + 1;
code += `${declaration}\n`;
});
const defaultExportNode = {
type: 'ExportDefaultDeclaration',
start: char,
end: null,
declaration: {
type: 'ObjectExpression',
start: char + 15,
end: null,
properties: []
}
};
char += 1... | },
specifiers: [],
source: null | random_line_split |
floatf.rs | //! formatter for %f %F common-notation floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common};
pub struct Floatf {
as_num: f64,
}
impl Floatf {
pu... | (&self, prim: &FormatPrimitive, field: FormatField) -> String {
primitive_to_str_common(prim, &field)
}
}
| primitive_to_str | identifier_name |
floatf.rs | //! formatter for %f %F common-notation floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common};
pub struct Floatf {
as_num: f64,
}
impl Floatf {
pu... |
}
| {
primitive_to_str_common(prim, &field)
} | identifier_body |
floatf.rs | //! formatter for %f %F common-notation floating-point subs
use super::super::format_field::FormatField;
use super::super::formatter::{InPrefix, FormatPrimitive, Formatter};
use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common};
pub struct Floatf {
as_num: f64,
}
impl Floatf {
pu... | &str_in[inprefix.offset..],
&analysis,
second_field as usize,
None);
Some(f)
}
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String {
... | inprefix,
None,
Some(second_field as usize),
false);
let f = get_primitive_dec(inprefix, | random_line_split |
count_custom_vhs.py | import os, sys
import json
import copy
import numpy as np
import random
from multiprocessing import Pool
import ipdb
################################################################################################
utils_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'nlp scripts')
source_vh_dir = '/ho... | (self, name):
if name not in self:
return -1
return self[name]
def size(self):
return len(self.names)
################################################################################################
hierarchy = json.loads(open('carreras_ing2.json').read())
# docname : {docname : true name}
nameByFile = js... | get_label_id | identifier_name |
count_custom_vhs.py | import os, sys
import json
import copy
import numpy as np
import random
from multiprocessing import Pool
import ipdb
################################################################################################
utils_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'nlp scripts')
source_vh_dir = '/ho... |
adjmatrix.append(item)
open(adj_name + '.json','w').write(json.dumps(adjmatrix,ensure_ascii=False, indent = 2)) | if graph[k,i]>0:
v = file_dict.get_label_name(i)
imp = dict({'name':nameByFile[v],'weight':int(graph[k,i])})
item["imports"].append(imp) | conditional_block |
count_custom_vhs.py | import os, sys
import json
import copy
import numpy as np
import random
from multiprocessing import Pool
import ipdb
################################################################################################
utils_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'nlp scripts')
source_vh_dir = '/ho... | print(count_id_file)
ipdb.set_trace()
# node
for k in range(count_id_file):
# posible edges
outgoing = set()
for i in range(count_id_file):
if k!=i:
temp = vhsByFile[k] & vhsByFile[i]
graph[k,i] = len(temp)
outgoing |= temp
graph[k,k] = freq_major[k] - len(outgoing)
# GENERATE CARRERA... | random_line_split | |
count_custom_vhs.py | import os, sys
import json
import copy
import numpy as np
import random
from multiprocessing import Pool
import ipdb
################################################################################################
utils_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'nlp scripts')
source_vh_dir = '/ho... |
def size(self):
return len(self.names)
################################################################################################
hierarchy = json.loads(open('carreras_ing2.json').read())
# docname : {docname : true name}
nameByFile = json.loads(open('ident_names2.json').read())
fileByName = {}
temp={}
fo... | if name not in self:
return -1
return self[name] | identifier_body |
containers.py | #!/usr/bin/python
# This file is part of PARPG.
# PARPG is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# PARPG is distr... | def __init__ (self, ID, name = 'Wooden Crate', \
text = 'A battered crate', gfx = 'crate', **kwargs):
ImmovableContainer.__init__(self, ID = ID, name = name, gfx = gfx, \
text = text, **kwargs) | identifier_body | |
containers.py | #!/usr/bin/python
# This file is part of PARPG.
# PARPG is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# PARPG is distr... | barrels, chests, etc."""
__all__ = ["WoodenCrate",]
from composed import ImmovableContainer
class WoodenCrate (ImmovableContainer):
def __init__ (self, ID, name = 'Wooden Crate', \
text = 'A battered crate', gfx = 'crate', **kwargs):
ImmovableContainer.__init__(self, ID = ID, name = name, gfx... | random_line_split | |
containers.py | #!/usr/bin/python
# This file is part of PARPG.
# PARPG is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# PARPG is distr... | (ImmovableContainer):
def __init__ (self, ID, name = 'Wooden Crate', \
text = 'A battered crate', gfx = 'crate', **kwargs):
ImmovableContainer.__init__(self, ID = ID, name = name, gfx = gfx, \
text = text, **kwargs)
| WoodenCrate | identifier_name |
index.d.ts | // Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/56295f5058cac7ae458540423c50ac2dcf9fc711/log4js/log4js.d.ts
// Type definitions for log4js
// Project: https://github.com/nomiddlename/log4js-node
// Definitions by: Kentaro Okuno <http://github.com/armorik83>
// Defini... | /** Loggly customer subdomain (use 'abc' for abc.loggly.com) */
subdomain: string;
/** an array of strings to help segment your data & narrow down search results in Loggly */
tags: string[];
/** Enable JSON logging by setting to 'true' */
json: boolean;
}
export interface ClusteredAppende... | export interface LogglyAppenderConfig extends AppenderConfigBase {
/** Loggly customer token - https://www.loggly.com/docs/api-sending-data/ */
token: string;
| random_line_split |
paste.py | """
Contains a base Site class for pastebin-like sites.
Each child class only needs to specify a base url,
the relative url to the public pastes archive,
and a lambda function to get the paste links out of
the page.
"""
import logging
import re
from urllib.parse import urljoin
from bs4 import BeautifulSoup
import requ... |
return found
class Paste(object):
"""
Base class for pastes. Parses paste ID
from supplied URL
"""
def __init__(self, url):
_id = url.split('/')[-1]
self._id = _id
class PastebinPaste(Paste):
"""
Paste for Pastebin
"""
def __init__(self, url):
sup... | found.append((name, len(matches))) | conditional_block |
paste.py | """
Contains a base Site class for pastebin-like sites.
Each child class only needs to specify a base url,
the relative url to the public pastes archive,
and a lambda function to get the paste links out of
the page.
"""
import logging
import re
from urllib.parse import urljoin
from bs4 import BeautifulSoup
import requ... | (self, url):
super().__init__(url)
self.url = 'http://pastebin.com/raw.php?i={}'.format(self._id)
class PastiePaste(Paste):
"""
Paste for Pastie
"""
def __init__(self, url):
super().__init__(url)
self.url = 'http://pastie.org/pastes/{}/text'.format(self._id)
class Sle... | __init__ | identifier_name |
paste.py | """
Contains a base Site class for pastebin-like sites.
Each child class only needs to specify a base url,
the relative url to the public pastes archive,
and a lambda function to get the paste links out of
the page.
"""
import logging
import re
from urllib.parse import urljoin
from bs4 import BeautifulSoup
import requ... | self.url = 'http://pastie.org/pastes/{}/text'.format(self._id)
class SlexyPaste(Paste):
"""
Paste for Slexy
"""
def __init__(self, url):
super().__init__(url)
self.url = 'http://slexy.org/raw/{}'.format(self._id)
class Pastebin(Site):
"""
Pastebin class
"""
de... | def __init__(self, url):
super().__init__(url) | random_line_split |
paste.py | """
Contains a base Site class for pastebin-like sites.
Each child class only needs to specify a base url,
the relative url to the public pastes archive,
and a lambda function to get the paste links out of
the page.
"""
import logging
import re
from urllib.parse import urljoin
from bs4 import BeautifulSoup
import requ... |
class Pastie(Site):
"""
Pastie class
"""
def __init__(self, target_patterns):
self.url_base = 'http://pastie.org'
self.url_archive = '/pastes'
self.paste_tag = lambda tag: tag.name == 'p' and tag.a and self.url_base in tag.a['href']
super().__init__(self.url_base, self... | """
Pastebin class
"""
def __init__(self, target_patterns):
self.url_base = 'http://pastebin.com/'
self.url_archive = '/archive'
self.paste_tag = lambda tag: tag.name == 'td' and tag.a and \
'/archive/' not in tag.a['href'] and tag.a['href'][1:]
super... | identifier_body |
interactive.js | /**
* class InteractiveBehavior < Behavior
*
* `Physics.behavior('interactive')`.
*
* User interaction helper.
*
* Used to get mouse/touch events and add a mouse grab interaction.
*
* Additional options include:
* - el: The element of the renderer. What you input as the `el` for the renderer.
* - moveThrottl... | ,y = obj.pageY - offset.top
;
return {
x: x
,y: y
};
}
;
return {
// extended
init: function( options ){
var self = this
,prevTreatment
,time
... | random_line_split | |
interactive.js | /**
* class InteractiveBehavior < Behavior
*
* `Physics.behavior('interactive')`.
*
* User interaction helper.
*
* Used to get mouse/touch events and add a mouse grab interaction.
*
* Additional options include:
* - el: The element of the renderer. What you input as the `el` for the renderer.
* - moveThrottl... |
var defaults = {
// the element to monitor
el: null,
// time between move events
moveThrottle: 1000 / 100 | 0,
// minimum velocity clamp
minVel: { x: -5, y: -5 },
// maximum velocity clamp
maxVel: { x: 5, y: 5 }
... | {
// must be in node environment
return {};
} | conditional_block |
table_datablock.py | import attr
import struct
import math
import re
import copy
from datablock import Datablock
from record import Record
from rowid import Rowid
@attr.s
class TableDatablock(Datablock):
header = attr.ib(default=[])
records = attr.ib(default=[])
def get_data(self):
"""
Convert header and reco... |
def write_data(self, record, position=None):
if(position is None):
position = self.free_contiguous_space(record.size()+4)
if(position == -1):
print('Error writing data')
return False
# Insert Header in the right position
place = -1
... | if(len(self.header) == 0):
return 0
last_offset = 0
for i in range(0, len(self.header), 2):
if self.header[last_offset] < self.header[i]:
last_offset = i
#Check for space between records
if(i+2 < len(self.header)):
space_b... | identifier_body |
table_datablock.py | import attr
import struct
import math
import re
import copy
from datablock import Datablock
from record import Record
from rowid import Rowid
@attr.s
class TableDatablock(Datablock):
header = attr.ib(default=[])
records = attr.ib(default=[])
def get_data(self):
"""
Convert header and reco... | (cls, address, data=None, count_record=0):
"""
Creates a new TableDatablock in memory from a string of bytes
"""
if(count_record == 0 and data is None):
return cls(address=address, count_record=count_record, type=1,
header=[], records=[])
heade... | from_bytes | identifier_name |
table_datablock.py | import attr
import struct
import math
import re
import copy
from datablock import Datablock
from record import Record
from rowid import Rowid
@attr.s
class TableDatablock(Datablock):
header = attr.ib(default=[])
records = attr.ib(default=[])
def get_data(self):
"""
Convert header and reco... | return self.records[position]
@classmethod
def from_bytes(cls, address, data=None, count_record=0):
"""
Creates a new TableDatablock in memory from a string of bytes
"""
if(count_record == 0 and data is None):
return cls(address=address, count_record=count_re... | random_line_split | |
table_datablock.py | import attr
import struct
import math
import re
import copy
from datablock import Datablock
from record import Record
from rowid import Rowid
@attr.s
class TableDatablock(Datablock):
header = attr.ib(default=[])
records = attr.ib(default=[])
def get_data(self):
"""
Convert header and reco... |
else:
can_store = ((self.header[pos+1]+(self.header[pos+2]-self.header[pos+1])) >= tmp_record.size())
#Check for space between records
if(can_store):
record.description = desc
self.header[pos+1] = record.size()
self._dirty = True
retur... | can_store =((self.header[pos+1] + (self.records_size() - (self.header[pos]+self.header[pos+1]))) >= tmp_record.size()) | conditional_block |
validating.py | # coding: utf-8
"""参数验证相关工具
"""
import re
import ujson
import types | from girlfriend.exception import InvalidArgumentException
class Rule(object):
"""描述参数验证规则,并执行验证过程
"""
@args2fields()
def __init__(self, name,
type=None,
required=False, min=None, max=None,
regex=None, logic=None, default=None):
"""
:... | import numbers
from girlfriend.util.lang import args2fields | random_line_split |
validating.py | # coding: utf-8
"""参数验证相关工具
"""
import re
import ujson
import types
import numbers
from girlfriend.util.lang import args2fields
from girlfriend.exception import InvalidArgumentException
class Rule(object):
"""描述参数验证规则,并执行验证过程
"""
@args2fields()
def __init__(self, name,
type=None,
... | identifier_name | ||
validating.py | # coding: utf-8
"""参数验证相关工具
"""
import re
import ujson
import types
import numbers
from girlfriend.util.lang import args2fields
from girlfriend.exception import InvalidArgumentException
class Rule(object):
"""描述参数验证规则,并执行验证过程
"""
@args2fields()
def __init__(self, name,
type=None,
... | alue):
if self._logic is None:
return
msg = self._logic(value)
if msg:
raise InvalidArgumentException(msg)
def _is_empty(self, value):
"""判断一个值是否为空
如果值为None,那么返回True
如果值为空字符串,那么返回True
如果值为0, 那么不算空,返回False
"""
i... | earch(self._regex, value):
raise InvalidArgumentException(
u"参数 '{name}' 不符合正则表达式'{regex}'".format(
name=self._name, regex=self._regex)
)
def _validate_logic(self, v | conditional_block |
validating.py | # coding: utf-8
"""参数验证相关工具
"""
import re
import ujson
import types
import numbers
from girlfriend.util.lang import args2fields
from girlfriend.exception import InvalidArgumentException
class Rule(object):
"""描述参数验证规则,并执行验证过程
"""
@args2fields()
def __init__(self, name,
type=None,
... | 度
self._validate_min_max(value)
# 检查正则
self._validate_regex(value)
# 检查逻辑
self._validate_logic(value)
def _validate_type(self, value):
if not self._type:
return
if not isinstance(value, self._type):
raise InvalidArgumentException(
... | ue)
# 检查大小、长 | identifier_body |
main.py | #!/usr/bin/env python
# coding=utf-8
from webapp.web import Application
from handlers.index import IndexHandler
from handlers.register import RegisterHandler
from handlers.user import UserHandler
from handlers.signin import SigninHandler
from handlers.signout import SignoutHandler
from handlers.upload import UploadHan... | app = Application(globals(), URLS)
app.run() | conditional_block | |
main.py | #!/usr/bin/env python
# coding=utf-8
from webapp.web import Application
from handlers.index import IndexHandler
from handlers.register import RegisterHandler
from handlers.user import UserHandler
from handlers.signin import SigninHandler
from handlers.signout import SignoutHandler
from handlers.upload import UploadHan... | ("/error", "ErrorHandler"),
("/pwdchange", "PasswordHandler"),
("/ftypeerror", "FiletypeErrorHandler")
)
if __name__ == '__main__':
app = Application(globals(), URLS)
app.run() | ("/signin", "SigninHandler"),
("/signout", "SignoutHandler"),
("/upload", "UploadHandler"),
("/avatar/(.*)", "AvatarHandler"), | random_line_split |
tooltip.js | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.9.0-rc2-master-041ffe9
*/
goog.provide('ng.material.components.tooltip');
goog.require('ng.material.core');
/**
* @ngdoc module
* @name material.components.tooltip
*/
angular
.module('material.components.tooltip', [ 'mat... |
function getParentWithPointerEvents () {
var parent = element.parent();
while ($window.getComputedStyle(parent[0])['pointer-events'] == 'none') {
parent = parent.parent();
}
return parent;
}
function getNearestContentElement () {
var current = element.parent()[0];
... | {
element.detach();
element.attr('role', 'tooltip');
element.attr('id', attr.id || ('tooltip_' + $mdUtil.nextUid()));
} | identifier_body |
tooltip.js | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.9.0-rc2-master-041ffe9
*/
goog.provide('ng.material.components.tooltip');
goog.require('ng.material.core');
/**
* @ngdoc module
* @name material.components.tooltip
*/
angular
.module('material.components.tooltip', [ 'mat... | (value) {
setVisible.value = !!value;
if (!setVisible.queued) {
if (value) {
setVisible.queued = true;
$timeout(function() {
scope.visible = setVisible.value;
setVisible.queued = false;
}, scope.delay);
} else {
$timeout(functi... | setVisible | identifier_name |
tooltip.js | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.9.0-rc2-master-041ffe9
*/
goog.provide('ng.material.components.tooltip');
goog.require('ng.material.core');
/**
* @ngdoc module
* @name material.components.tooltip
*/
angular
.module('material.components.tooltip', [ 'mat... | height: size + 'px',
left: position.left + '%',
top: position.top + '%'
});
}
function fitInParent (pos) {
var newPosition = { left: pos.left, top: pos.top };
newPosition.left = Math.min( newPosition.left, tooltipParent.prop('scrollWidth') - tipRect.wid... | background.css({
width: size + 'px', | random_line_split |
ihex_writer.rs | //
// Copyright 2016 The c8s Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>.
// All files in the project carrying such notice may not be copied, modified, or
// distributed except according ... |
// Validate the average case yielded the anticipated result.
let ihex_rep = ihex_representation_of_data_ranges(&[range_a, range_b, range_c]);
let expected_ihex_rep = String::new() +
&":0F010000214601360121470136007EFE09D21942\n" +
&":100130003F0156702B5E712B722B732146013421C7\n" +
&":010... | range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21,0x22]);
let mut range_c = DataRange::new(u12![0x200]);
range_c.append(&vec![0x3F]); | random_line_split |
ihex_writer.rs | //
// Copyright 2016 The c8s Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>.
// All files in the project carrying such notice may not be copied, modified, or
// distributed except according ... |
#[test]
#[should_panic]
fn test_ihex_representation_of_data_ranges_panics_when_overlapping() {
// Build an overlapping pair of ranges.
let mut range_a = DataRange::new(u12![0x100]);
range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]);
let mut ra... | {
// Build an uneven set of data ranges.
let mut range_a = DataRange::new(u12![0x100]);
range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19]);
let mut range_b = DataRange::new(u12![0x130]);
range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,... | identifier_body |
ihex_writer.rs | //
// Copyright 2016 The c8s Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>.
// All files in the project carrying such notice may not be copied, modified, or
// distributed except according ... | <'a>(ranges: &'a [DataRange]) -> String {
assert!(data_range::find_overlapping_ranges(ranges).len() == 0);
// All records are collected into a list.
let mut records = Vec::<Record>::new();
for range in ranges.iter() {
// The range will be sub-divded into chunks of up to 16 bytes, so sub-address must be t... | ihex_representation_of_data_ranges | identifier_name |
WeatherForecasts.ts | import { fetch, addTask } from 'domain-task';
import { Action, Reducer, ActionCreator } from 'redux';
import { AppThunkAction } from './';
// -----------------
// STATE - This defines the type of data maintained in the Redux store.
export interface WeatherForecastsState {
isLoading: boolean;
startDateIndex: n... | export const actionCreators = {
requestWeatherForecasts: (startDateIndex: number): AppThunkAction<KnownAction> => (dispatch, getState) => {
// Only load data if it's something we don't already have (and are not already loading)
if (startDateIndex !== getState().weatherForecasts.startDateIndex) {
... | random_line_split | |
WeatherForecasts.ts | import { fetch, addTask } from 'domain-task';
import { Action, Reducer, ActionCreator } from 'redux';
import { AppThunkAction } from './';
// -----------------
// STATE - This defines the type of data maintained in the Redux store.
export interface WeatherForecastsState {
isLoading: boolean;
startDateIndex: n... |
}
};
// ----------------
// REDUCER - For a given state and action, returns the new state. To support time travel, this must not mutate the old state.
const unloadedState: WeatherForecastsState = { startDateIndex: null, forecasts: [], isLoading: false };
export const reducer: Reducer<WeatherForecastsState> = (s... | {
let fetchTask = fetch(`/api/SampleData/WeatherForecasts?startDateIndex=${ startDateIndex }`)
.then(response => response.json() as Promise<WeatherForecast[]>)
.then(data => {
dispatch({ type: 'RECEIVE_WEATHER_FORECASTS', startDateIndex: startDateIndex, fo... | conditional_block |
pmovsxbd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*; | fn pmovsxbd_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 205], OperandSize::Dword)
}
fn pmovsx... | use ::RegScale::*;
| random_line_split |
pmovsxbd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn pmovsxbd_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM1)), operand2: Some(Direc... | () {
run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 246], OperandSize::Qword)
}
fn pmovsxbd_4() {
... | pmovsxbd_3 | identifier_name |
pmovsxbd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn pmovsxbd_1() {
run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM1)), operand2: Some(Direc... | {
run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM5)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Two, 1709813562, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None... | identifier_body | |
13.rs | use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::collections::HashMap;
fn get_input() -> std::io::Result<String> {
let mut file = File::open("13.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
type Point = (isize, isize);
type Tracks = H... | (input: &str) -> (Tracks, Vec<Cart>) {
input.lines()
.enumerate()
.flat_map(|(j, line)| {
let chars: Vec<char> = line.chars().collect();
chars.iter()
.cloned()
.enumerate()
.filter_map(|(i, c)| {
let (x, y) = (i as isize, j as isize);
let hori... | parse | identifier_name |
13.rs | use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::collections::HashMap;
fn get_input() -> std::io::Result<String> {
let mut file = File::open("13.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
type Point = (isize, isize);
type Tracks = H... | '>' => Some((1, 0)),
'^' => Some((0, -1)),
'v' => Some((0, 1)),
_ => None
};
neighbors
.map(|n| ((x, y), n, cart_direction.map(|d| Cart::new((x, y), d))))
})
.collect::<Vec<_>>()
})
.fold((Tracks... | };
let cart_direction = match c {
'<' => Some((-1, 0)), | random_line_split |
metadata_builder.py | # -*- coding: utf-8 -*-
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); | # You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the L... | # you may not use this file except in compliance with the License. | random_line_split |
metadata_builder.py | # -*- coding: utf-8 -*-
# Copyright 2021 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 ... | (self):
"""Returns the current metadata as ExplanationMetadata protobuf"""
| get_metadata_protobuf | identifier_name |
metadata_builder.py | # -*- coding: utf-8 -*-
# Copyright 2021 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 ... |
@abc.abstractmethod
def get_metadata_protobuf(self):
"""Returns the current metadata as ExplanationMetadata protobuf"""
| """Returns the current metadata as a dictionary.""" | identifier_body |
kendo-dojo.js | (function($, window) {
var dojo = {
postSnippet: function (snippet, baseUrl) {
snippet = dojo.fixCDNReferences(snippet);
snippet = dojo.addBaseRedirectTag(snippet, baseUrl);
snippet = dojo.addConsoleScript(snippet);
snippet = dojo.fixLineEndings(snippet);
... |
return code;
},
replaceTheme: function(code, theme) {
if (theme) {
code = code.replace(/default\.min\.css/g, theme + ".min.css");
}
return code;
},
addBaseRedirectTag: function (code, baseUrl) {
return code.re... | {
code = code.replace(/common\.min\.css/, common + ".min.css");
} | conditional_block |
kendo-dojo.js | (function($, window) {
var dojo = {
postSnippet: function (snippet, baseUrl) {
snippet = dojo.fixCDNReferences(snippet);
snippet = dojo.addBaseRedirectTag(snippet, baseUrl);
snippet = dojo.addConsoleScript(snippet);
snippet = dojo.fixLineEndings(snippet);
... | ' <style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>'
);
},
addConsoleScript: function (code) {
if (code.indexOf("kendoConsole") !== -1) {
var styleReference = ' <link rel="stylesheet" href="../content/shared/... | return code.replace(
'<head>',
'<head>\n' +
' <base href="' + baseUrl + '">\n' + | random_line_split |
logIn.js | /*jslint browser: true*/
/*global $, jQuery, alert*/
(function ($) {
"use strict";
$(document).ready(function () {
$("input[name=dob]").datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
showOtherMonths: true
});
});
$(document).ready(functi... | $("input[name=rep_password]").focusin(function () {
$('#passDM').hide(300);
});
});
}(jQuery)); | random_line_split | |
logIn.js | /*jslint browser: true*/
/*global $, jQuery, alert*/
(function ($) {
"use strict";
$(document).ready(function () {
$("input[name=dob]").datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
showOtherMonths: true
});
});
$(document).ready(functi... | else if (p1 === "") {
$('#passDM').show(300);
} else {
$('#passDM').hide(300);
}
});
});
$(document).ready(function () {
$("input[name=password]").focusin(function () {
$('#passDM').hide(300);
});
$("... | {
$('#passDM').show(300);
} | conditional_block |
transpiler.py | import os
import os.path
from collections import OrderedDict
from typing import List, Dict, Any, Tuple, Union
# noinspection PyPackageRequirements
import yaml # from pyyaml
import dectree.propfuncs as propfuncs
from .codegen import gen_code
from .types import TypeDefs
def transpile(src_file, out_file=None, **optio... | (rule_code: str):
raw_lines = rule_code.split('\n')
yml_lines = []
for raw_line in raw_lines:
i = _count_leading_spaces(raw_line)
indent = raw_line[0:i]
content = raw_line[i:]
if content:
if content[0] != '#':
yml_lines.append(indent + '- ' + conte... | _load_raw_rule | identifier_name |
transpiler.py | import os
import os.path
from collections import OrderedDict
from typing import List, Dict, Any, Tuple, Union
# noinspection PyPackageRequirements
import yaml # from pyyaml
import dectree.propfuncs as propfuncs
from .codegen import gen_code
from .types import TypeDefs
def transpile(src_file, out_file=None, **optio... |
return parsed_rule
def _load_raw_rule(rule_code: str):
raw_lines = rule_code.split('\n')
yml_lines = []
for raw_line in raw_lines:
i = _count_leading_spaces(raw_line)
indent = raw_line[0:i]
content = raw_line[i:]
if content:
if content[0] != '#':
... | raise ValueError('illegal rule part: {}'.format(stmt_part)) | conditional_block |
transpiler.py | import os
import os.path
from collections import OrderedDict
from typing import List, Dict, Any, Tuple, Union
# noinspection PyPackageRequirements
import yaml # from pyyaml
import dectree.propfuncs as propfuncs
from .codegen import gen_code
from .types import TypeDefs
def transpile(src_file, out_file=None, **optio... | dir_name = os.path.dirname(src_path)
base_name = os.path.splitext(os.path.basename(src_path))[0]
out_path = os.path.join(dir_name, base_name + ".py")
fd = open(out_path, mode='w')
fd.write(py_code)
if out_path is not None:
fd.close()
return out_path
def _normalize... | except TypeError:
fd = out_file
out_path = None
else:
assert src_path | random_line_split |
transpiler.py | import os
import os.path
from collections import OrderedDict
from typing import List, Dict, Any, Tuple, Union
# noinspection PyPackageRequirements
import yaml # from pyyaml
import dectree.propfuncs as propfuncs
from .codegen import gen_code
from .types import TypeDefs
def transpile(src_file, out_file=None, **optio... |
def _normalize_types(types: Dict[str, Dict[str, str]]) -> TypeDefs:
type_defs = OrderedDict()
for type_name, type_properties in types.items():
type_def = {}
type_defs[type_name] = type_def
for prop_name, prop_value in type_properties.items():
try:
prop_resu... | """
Generate a decision tree function by transpiling *src_file* to *out_file* using the given *options*.
Return the path to the generated file, if any, otherwise return ``None``.
:param src_file: A file descriptor or a path-like object to the decision tree definition source file (YAML format)
:param ou... | identifier_body |
auth.service.ts | import { Injectable } from '@angular/core';
import { HttpRequest } from '@angular/common/http';
import * as jwt_decode_ from 'jwt-decode';
import * as localForage from 'localforage';
const jwt_decode = jwt_decode_;
const TOKEN = 'token';
const CLIENT = 'client';
const UID = 'uid';
const CREATEDAT = 'createdAt';
@Inj... | (): Date {
if (!this.token) {
return undefined;
}
const decoded: any = jwt_decode(this.token);
if (!decoded.hasOwnProperty('exp')) {
return undefined;
}
const date = new Date(0);
date.setUTCSeconds(decoded.exp);
return date;
}
isTokenExpired(): boolean {
if (!this.to... | getTokenExpirationDate | identifier_name |
auth.service.ts | import { Injectable } from '@angular/core';
import { HttpRequest } from '@angular/common/http';
import * as jwt_decode_ from 'jwt-decode';
import * as localForage from 'localforage';
const jwt_decode = jwt_decode_;
const TOKEN = 'token';
const CLIENT = 'client';
const UID = 'uid';
const CREATEDAT = 'createdAt';
@Inj... |
retryFailedRequests(): void {
// retry the requests. this method can
// be called after the token is refreshed
// console.log(this._cachedRequests);
}
}
| {
this._cachedRequests.push(request);
} | identifier_body |
auth.service.ts | import { Injectable } from '@angular/core';
import { HttpRequest } from '@angular/common/http';
import * as jwt_decode_ from 'jwt-decode';
import * as localForage from 'localforage';
const jwt_decode = jwt_decode_;
const TOKEN = 'token';
const CLIENT = 'client';
const UID = 'uid';
const CREATEDAT = 'createdAt';
@Inj... | this.createdAt = undefined;
this._cachedRequests = [];
this.token = '';
this.personId = '';
return localForage.clear();
}
getTokenExpirationDate(): Date {
if (!this.token) {
return undefined;
}
const decoded: any = jwt_decode(this.token);
if (!decoded.hasOwnProperty('exp')... | clearStore(): Promise<void> { | random_line_split |
auth.service.ts | import { Injectable } from '@angular/core';
import { HttpRequest } from '@angular/common/http';
import * as jwt_decode_ from 'jwt-decode';
import * as localForage from 'localforage';
const jwt_decode = jwt_decode_;
const TOKEN = 'token';
const CLIENT = 'client';
const UID = 'uid';
const CREATEDAT = 'createdAt';
@Inj... |
const date = new Date(0);
date.setUTCSeconds(decoded.exp);
return date;
}
isTokenExpired(): boolean {
if (!this.token) return true;
const date = this.getTokenExpirationDate();
if (date === undefined) {
return false;
}
return !(date.valueOf() > new Date().valueOf());
}
co... | {
return undefined;
} | conditional_block |
lib.rs | use std::ops::Range;
use std::cmp::min;
use std::error::Error;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Direction {Forward, Reverse}
use self::Direction::*;
impl Direction {
fn reverse(self) -> Direction {
match self {
Forward => Reverse,
Reverse => Forward
}
}
}
#[derive(Clone, Copy, Debug,... | impl Indexed for CoveredGlyph {}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct GSub<'a> {
pub script_list: ScriptList<'a>,
pub feature_list: FeatureList<'a>,
pub lookup_list: LookupList<'a, GSubLookups>
}
impl<'a> GSub<'a> {
fn new(data: &'a[u8]) -> Result<GSub<'a>, CorruptFont<'a>> {
if data.len() < 10 {ret... | veredGlyph;
| identifier_name |
lib.rs | use std::ops::Range;
use std::cmp::min;
use std::error::Error;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Direction {Forward, Reverse}
use self::Direction::*;
impl Direction {
fn reverse(self) -> Direction {
match self {
Forward => Reverse,
Reverse => Forward
}
}
}
#[derive(Clone, Copy, Debug,... | pub fn features_for(&self, selector: Option<(Tag<Script>, Option<Tag<LangSys>>)>) -> Result<LangSysTable<'a>, CorruptFont<'a>> {
let search = AutoSearch::new(self.num_tables() as usize*6);
if let Some((script, lang_sys_opt)) = selector {
match search.search(0..self.num_tables(), &mut move|&i| Ok(self.tag(Index::... | criptList::new_list(data)}
| identifier_body |
lib.rs | use std::ops::Range;
use std::cmp::min;
use std::error::Error;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Direction {Forward, Reverse}
use self::Direction::*;
impl Direction {
fn reverse(self) -> Direction {
match self {
Forward => Reverse,
Reverse => Forward
}
}
}
#[derive(Clone, Copy, Debug,... | fn new(data: &'a[u8]) -> Result<LookupList<'a, T>, CorruptFont<'a>> {
if data.len() < 2 {return Err(CorruptFont(data, TableTooShort))}
let res = LookupList(data, PhantomData);
if data.len() < res.len() as usize*2+2 {return Err(CorruptFont(data, TableTooShort))}
Ok(res)
}
fn len(&self) -> u16 {read_u16(self.0... | }
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct LookupList<'a, T: LookupContainer<'a>>(&'a[u8], PhantomData<&'static T>);
impl<'a, T: LookupContainer<'a>> LookupList<'a, T> { | random_line_split |
lib.rs | use std::ops::Range;
use std::cmp::min;
use std::error::Error;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Direction {Forward, Reverse}
use self::Direction::*;
impl Direction {
fn reverse(self) -> Direction {
match self {
Forward => Reverse,
Reverse => Forward
}
}
}
#[derive(Clone, Copy, Debug,... | ),
Err(Ok(i)) => {
let range = &data[i as usize*6..][..6];
if step == 2 {return Ok(None)}
let (first, last, offset) = try!(read_range(range));
Ok(if last >= glyph {
Some(Index::new(glyph-first+offset))
} else {
None
})
},
Err(Err((_, CorruptFont(..)))) => unreachable!()
}
}... | })) | conditional_block |
buckets.ts | /**
* Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
*/
import { sort, arraySwap } from './sort';
import { AssignableArrayLike } from '../../mol-util/type-helpers';
type Bucket = {
key: any,
count: number,
off... | <K extends string | number>(
indices: AssignableArrayLike<number>, getKey: (i: number) => K, options?: MakeBucketsOptions<K>): ArrayLike<number> {
const s = (options && options.start) || 0;
const e = (options && options.end) || indices.length;
if (e - s <= 0) throw new Error('Can only bucket non-empty c... | makeBuckets | identifier_name |
buckets.ts | /**
* Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
*/
import { sort, arraySwap } from './sort';
import { AssignableArrayLike } from '../../mol-util/type-helpers';
type Bucket = {
key: any,
count: number,
off... |
}
if (isBucketed && sorted) {
for (let i = 0; i < bucketList.length; i++) bucketOffsets[i] = bucketList[i].offset;
return bucketOffsets;
}
if (sortBuckets && !sorted) {
sort(bucketList, 0, bucketList.length, sortAsc, arraySwap);
}
let offset = 0;
for (let i = 0; i... | {
if (bucketList[i - 1].key > bucketList[i].key) {
sorted = false;
break;
}
} | conditional_block |
buckets.ts | /**
* Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
*/
import { sort, arraySwap } from './sort';
import { AssignableArrayLike } from '../../mol-util/type-helpers';
type Bucket = {
key: any,
count: number,
off... | }
if (isBucketed && sorted) {
for (let i = 0; i < bucketList.length; i++) bucketOffsets[i] = bucketList[i].offset;
return bucketOffsets;
}
if (sortBuckets && !sorted) {
sort(bucketList, 0, bucketList.length, sortAsc, arraySwap);
}
let offset = 0;
for (let i = 0; i ... | } | random_line_split |
buckets.ts | /**
* Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* @author David Sehnal <david.sehnal@gmail.com>
*/
import { sort, arraySwap } from './sort';
import { AssignableArrayLike } from '../../mol-util/type-helpers';
type Bucket = {
key: any,
count: number,
off... | {
const s = (options && options.start) || 0;
const e = (options && options.end) || indices.length;
if (e - s <= 0) throw new Error('Can only bucket non-empty collections.');
return _makeBuckets(indices, getKey, !!(options && options.sort), s, e);
} | identifier_body | |
settings.py | """
Django settings for example_site project.
Generated by 'django-admin startproject' using Django 1.8.dev20150302062936.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settin... | # https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = "/static/"
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" | USE_TZ = True
# Static files (CSS, JavaScript, Images) | random_line_split |
test_metrics.py | # Copyright (c) 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the impl... | (TestCase):
def test_init(self):
t = Timer()
self.assertEqual(t.started, 0)
self.assertEqual(t.stopped, 0)
@patch('time.time')
def test_start(self, _time):
_time.return_value = 10.0
t = Timer()
t.start()
self.assertEqual(t.started, 10.0)
self... | TestTimer | identifier_name |
test_metrics.py | # Copyright (c) 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the impl... |
def test_unicode(self):
t = Timer()
# not started
self.assertEqual(unicode(t), 'not-running')
# started but not stopped
t.started = 1
self.assertEqual(unicode(t), 'started: %d (running)' % t.started)
# milliseconds
t.started = 0.10
t.stopped ... | t = Timer()
t.started = 10.0
t.stopped = 100.0
self.assertEqual(t.duration(), 90.0) | identifier_body |
test_metrics.py | # Copyright (c) 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the impl... |
class TestUtils(TestCase):
@patch('gofer.metrics.datetime')
def test_timestamp(self, dt):
dt.utcnow.return_value = datetime(2014, 12, 25, 9, 30, 0)
ts = timestamp()
self.assertEqual(ts, '2014-12-25T09:30:00Z')
class TestTimer(TestCase):
def test_init(self):
t = Timer()
... | random_line_split | |
core.externs.js | /** @externs */
/**
* @externs
* @suppress {duplicate,checkTypes}
*/
// NOTE: generated by tsickle, do not edit.
// externs from /private/var/folders/7d/r6b3nrdj7bn9t_w_dclm6y9r00kg80/T/angular-release-latest.XXXXXXX.FjdRL2Ds/sandbox/darwin-sandbox/169/execroot/angular/packages/core/src/render3/interfaces/player.ts:... | /** @typedef {?} */
angular$packages$core$src$render3$interfaces$player.DirectiveInstance;
// externs from /private/var/folders/7d/r6b3nrdj7bn9t_w_dclm6y9r00kg80/T/angular-release-latest.XXXXXXX.FjdRL2Ds/sandbox/darwin-sandbox/169/execroot/angular/packages/core/src/render3/util/global_utils.ts:
/** @const */
var angula... | var angular$packages$core$src$render3$interfaces$player = {};
/** @typedef {?} */
angular$packages$core$src$render3$interfaces$player.ComponentInstance;
| random_line_split |
view.js | (function () {
// The default state core singleton for {@link SceneJS.View} nodes
var defaultCore = {
type:"view",
stateId:SceneJS._baseStateId++,
scissorTestEnabled:false
};
var coreStack = [];
var stackLen = 0;
SceneJS_events.addListener(
SceneJS_events.SCENE... |
};
/**
* Enable or disables scissor test.
*
* When enabled, the scissor test will discards fragments that are outside the scissor box.
*
* Scissor test is initially disabled.
*
* @param scissorTestEnabled Specifies whether scissor test is enabled or not
* @return {*}
... | { // This node defines the core
this.setScissorTestEnabled(false);
} | conditional_block |
view.js | (function () {
// The default state core singleton for {@link SceneJS.View} nodes
var defaultCore = {
type:"view",
stateId:SceneJS._baseStateId++,
scissorTestEnabled:false
};
var coreStack = [];
var stackLen = 0;
SceneJS_events.addListener(
SceneJS_events.SCENE... | this.setScissorTestEnabled(false);
}
};
/**
* Enable or disables scissor test.
*
* When enabled, the scissor test will discards fragments that are outside the scissor box.
*
* Scissor test is initially disabled.
*
* @param scissorTestEnabled Specifies whet... | random_line_split | |
plot_missing_values.py | """
====================================================
Imputing missing values before building an estimator
====================================================
Missing values can be replaced by the mean, the median or the most frequent
value using the basic :class:`sklearn.impute.SimpleImputer`.
The median is a mor... | (imputer, X_missing, y_missing):
estimator = make_pipeline(
make_union(imputer, MissingIndicator(missing_values=0)),
REGRESSOR)
impute_scores = cross_val_score(estimator, X_missing, y_missing,
scoring='neg_mean_squared_error',
... | get_scores_for_imputer | identifier_name |
plot_missing_values.py | """
====================================================
Imputing missing values before building an estimator
====================================================
Missing values can be replaced by the mean, the median or the most frequent
value using the basic :class:`sklearn.impute.SimpleImputer`.
The median is a mor... | make_union(imputer, MissingIndicator(missing_values=0)),
REGRESSOR)
impute_scores = cross_val_score(estimator, X_missing, y_missing,
scoring='neg_mean_squared_error',
cv=N_SPLITS)
return impute_scores
def get_results(datas... |
def get_scores_for_imputer(imputer, X_missing, y_missing):
estimator = make_pipeline( | random_line_split |
plot_missing_values.py | """
====================================================
Imputing missing values before building an estimator
====================================================
Missing values can be replaced by the mean, the median or the most frequent
value using the basic :class:`sklearn.impute.SimpleImputer`.
The median is a mor... |
ax2.set_title('Imputation Techniques with Boston Data')
ax2.set_yticks(xval)
ax2.set_xlabel('MSE')
ax2.invert_yaxis()
ax2.set_yticklabels([''] * n_bars)
plt.show()
| ax2.barh(j, mses_boston[j], xerr=stds_boston[j],
color=colors[j], alpha=0.6, align='center') | conditional_block |
plot_missing_values.py | """
====================================================
Imputing missing values before building an estimator
====================================================
Missing values can be replaced by the mean, the median or the most frequent
value using the basic :class:`sklearn.impute.SimpleImputer`.
The median is a mor... |
def get_results(dataset):
X_full, y_full = dataset.data, dataset.target
n_samples = X_full.shape[0]
n_features = X_full.shape[1]
# Estimate the score on the entire dataset, with no missing values
full_scores = cross_val_score(REGRESSOR, X_full, y_full,
scoring='... | estimator = make_pipeline(
make_union(imputer, MissingIndicator(missing_values=0)),
REGRESSOR)
impute_scores = cross_val_score(estimator, X_missing, y_missing,
scoring='neg_mean_squared_error',
cv=N_SPLITS)
return impute_sco... | identifier_body |
fmt.rs | #[macro_use] extern crate custom_derive;
#[macro_use] extern crate newtype_derive;
use std::fmt::{self, Binary, Debug, Display, LowerExp, LowerHex, Octal, Pointer,
UpperExp, UpperHex};
macro_rules! impl_fmt {
(impl $tr:ident for $name:ident: $msg:expr) => {
impl $tr for $name {
fn fmt(&sel... | NewtypePointer,
NewtypeUpperExp,
NewtypeUpperHex
)]
struct Wrapper(Dummy);
}
#[test]
fn test_fmt() {
let a = Wrapper(Dummy);
assert_eq!(&*format!("{:b}", a), "binary");
assert_eq!(&*format!("{:?}", a), "debug");
assert_eq!(&*format!("{}", a), "display");
assert_eq!(... | random_line_split | |
fmt.rs | #[macro_use] extern crate custom_derive;
#[macro_use] extern crate newtype_derive;
use std::fmt::{self, Binary, Debug, Display, LowerExp, LowerHex, Octal, Pointer,
UpperExp, UpperHex};
macro_rules! impl_fmt {
(impl $tr:ident for $name:ident: $msg:expr) => {
impl $tr for $name {
fn fmt(&sel... | ;
impl_fmt!(impl Binary for Dummy: "binary");
impl_fmt!(impl Debug for Dummy: "debug");
impl_fmt!(impl Display for Dummy: "display");
impl_fmt!(impl LowerExp for Dummy: "lowerexp");
impl_fmt!(impl LowerHex for Dummy: "lowerhex");
impl_fmt!(impl Octal for Dummy: "octal");
impl_fmt!(impl Pointer for Dummy: "pointer");
i... | Dummy | identifier_name |
criteo.js | var CONSTANTS = require('../constants.json');
var utils = require('../utils.js');
var bidfactory = require('../bidfactory.js');
var bidmanager = require('../bidmanager.js');
var adloader = require('../adloader');
/**
* Adapter for requesting bids from Criteo.
*
* @returns {{callBids: _callBids}}
* @constructor
*/... |
}
return nids;
}
function _requestBid(bid) {
var varname = 'crtg_varname_' + bid.params.nid;
var scriptUrl = '//rtax.criteo.com/delivery/rta/rta.js?netId=' + encodeURI(bid.params.nid) +
'&cookieName=' + encodeURI(bid.params.cookiename) +
'&rnd=' + Math.floor(Math.random() * 99999999999) +
'&varName... | {
nids.push(map[key]);
} | conditional_block |
criteo.js | var CONSTANTS = require('../constants.json');
var utils = require('../utils.js');
var bidfactory = require('../bidfactory.js');
var bidmanager = require('../bidmanager.js');
var adloader = require('../adloader');
/**
* Adapter for requesting bids from Criteo.
*
* @returns {{callBids: _callBids}}
* @constructor
*/... | function _requestBid(bid) {
var varname = 'crtg_varname_' + bid.params.nid;
var scriptUrl = '//rtax.criteo.com/delivery/rta/rta.js?netId=' + encodeURI(bid.params.nid) +
'&cookieName=' + encodeURI(bid.params.cookiename) +
'&rnd=' + Math.floor(Math.random() * 99999999999) +
'&varName=' + encodeURI(varname);... | }
}
return nids;
}
| random_line_split |
criteo.js | var CONSTANTS = require('../constants.json');
var utils = require('../utils.js');
var bidfactory = require('../bidfactory.js');
var bidmanager = require('../bidmanager.js');
var adloader = require('../adloader');
/**
* Adapter for requesting bids from Criteo.
*
* @returns {{callBids: _callBids}}
* @constructor
*/... |
return {
callBids: _callBids
};
};
module.exports = CriteoAdapter; | {
var varname = 'crtg_varname_' + bid.params.nid;
var scriptUrl = '//rtax.criteo.com/delivery/rta/rta.js?netId=' + encodeURI(bid.params.nid) +
'&cookieName=' + encodeURI(bid.params.cookiename) +
'&rnd=' + Math.floor(Math.random() * 99999999999) +
'&varName=' + encodeURI(varname);
adloader.loadScript(scr... | identifier_body |
criteo.js | var CONSTANTS = require('../constants.json');
var utils = require('../utils.js');
var bidfactory = require('../bidfactory.js');
var bidmanager = require('../bidmanager.js');
var adloader = require('../adloader');
/**
* Adapter for requesting bids from Criteo.
*
* @returns {{callBids: _callBids}}
* @constructor
*/... | (bids) {
var key;
var map = {};
var nids = [];
bids.forEach(function(bid) {
map[bid.params.nid] = bid;
});
for (key in map) {
if (map.hasOwnProperty(key)) {
nids.push(map[key]);
}
}
return nids;
}
function _requestBid(bid) {
var varname = 'crtg_varname_' + bid.params.nid;
var scriptU... | _getUniqueNids | identifier_name |
20210319-tbd-first-round.js | /* eslint no-magic-numbers:0 */
"use strict"
const test = require("tape")
const utils = require("../utils")
const testEvents = (t) => (err, events) => {
t.notOk(err)
t.equal(events[0].region, "nba finals")
t.end()
}
test("works with tbd first round", (t) => { | t.equal(events.length, 16)
t.end()
})
})
test.skip("works with tbd first round", (t) => {
utils.parseUrl(
"https://www.espn.com/mens-college-basketball/scoreboard/_/group/100/date/20210319",
(err, events) => {
t.equal(events.length, 16)
t.end()
}
)
}) | utils.parseFile("20210319-tbd-first-round", (err, events) => { | random_line_split |
ManualEntryPanel.spec.tsx | import React from 'react';
import { act } from 'react-dom/test-utils';
import { mount } from 'enzyme';
import { RcThemeProvider } from '@ringcentral-integration/rcui';
import { ManualEntryPanel, ManualEntryPanelProps } from './ManualEntryPanel';
let wrapper;
const currentLocale = 'en-US';
const defaultTransferCountryO... | describe('<ManualEntryPanel />', async () => {
it('Display Back Button and when user click it, function goBack will be called', () => {
const goBack = jest.fn(() => {});
wrapper = setup({ goBack });
wrapper
.find('[data-sign="backButton"]')
.at(0)
.find('button')
.simulate('click')... | });
| random_line_split |
ManualEntryPanel.spec.tsx | import React from 'react';
import { act } from 'react-dom/test-utils';
import { mount } from 'enzyme';
import { RcThemeProvider } from '@ringcentral-integration/rcui';
import { ManualEntryPanel, ManualEntryPanelProps } from './ManualEntryPanel';
let wrapper;
const currentLocale = 'en-US';
const defaultTransferCountryO... |
afterEach(async () => {
wrapper.unmount();
});
describe('<ManualEntryPanel />', async () => {
it('Display Back Button and when user click it, function goBack will be called', () => {
const goBack = jest.fn(() => {});
wrapper = setup({ goBack });
wrapper
.find('[data-sign="backButton"]')
.... | {
return mount(
<RcThemeProvider>
<ManualEntryPanel
currentLocale={currentLocale}
goBack={goBack}
transferRecipientCountryId={transferRecipientCountryId}
changeRecipientNumber={changeRecipientNumber}
changeRecipientCountryId={changeRecipientCountryId}
transfer... | identifier_body |
ManualEntryPanel.spec.tsx | import React from 'react';
import { act } from 'react-dom/test-utils';
import { mount } from 'enzyme';
import { RcThemeProvider } from '@ringcentral-integration/rcui';
import { ManualEntryPanel, ManualEntryPanelProps } from './ManualEntryPanel';
let wrapper;
const currentLocale = 'en-US';
const defaultTransferCountryO... | ({
goBack = () => {},
transferRecipientCountryId = 'USA',
changeRecipientNumber = () => {},
changeRecipientCountryId = () => {},
transferRecipientNumber = '6508653454',
allowManualInternationalTransfer = false,
}: Partial<ManualEntryPanelProps>) {
return mount(
<RcThemeProvider>
<ManualEntryPane... | setup | identifier_name |
list.tsx | import React, { useRef, useState } from 'react';
import BodyContent from '@/layouts/compents/body_content';
import { Avatar, message } from 'antd';
import { formatTimestamp } from '@/utils/utils';
import { searchAdmins, lockAdmin, setAdminType } from './service';
import { AdminInfo } from './data_d';
import { PlusOutl... | buttons: [
{
btn_text: '取消超管权限',
fetch: (item: AdminInfo) => setAdminType(item, 0),
fetch_desp: '将超级管理员降为普通管理员',
func_code: FuncCodes.Portal_AdminSetType,
// icon: <settt />,
},
],
},
{
condition: (r: AdminInfo) => r.admin_type ... | ],
},
{
condition: (r: AdminInfo) => r.admin_type == 100, | random_line_split |
sjisprober.rs | use std::ops::Deref;
use std::ops::DerefMut;
use super::enums::MachineState;
use super::mbcharsetprober::MultiByteCharsetProber;
use super::charsetprober::CharsetProber;
use super::enums::ProbingState;
use super::codingstatemachine::CodingStateMachine;
use super::mbcssm::SJIS_SM_MODEL;
use super::chardistribution::SJIS... |
MachineState::ERROR => {
self.base.m_state = ProbingState::NotMe;
break;
}
MachineState::ITS_ME => {
self.base.m_state = ProbingState::FoundIt;
break;
... | {
let char_len = sm.get_current_charlen();
if i == 0 {
self.base.m_last_char[1] = byte_str[0];
self.m_context_analyzer.feed(
&self.base.m_last_char[(2 - char_len) as
... | conditional_block |
sjisprober.rs | use std::ops::Deref;
use std::ops::DerefMut;
use super::enums::MachineState;
use super::mbcharsetprober::MultiByteCharsetProber;
use super::charsetprober::CharsetProber;
use super::enums::ProbingState;
use super::codingstatemachine::CodingStateMachine;
use super::mbcssm::SJIS_SM_MODEL;
use super::chardistribution::SJIS... | }
}
impl<'a> SJISProber<'a> {
pub fn new() -> SJISProber<'a> {
let mut x = SJISProber {
base: MultiByteCharsetProber::new(),
m_context_analyzer: SJISContextAnalysis::new(),
};
x.base.m_coding_sm = Some(CodingStateMachine::new(&SJIS_SM_MODEL));
x.base.m_di... | "Japanese".to_string()
}
fn get_state(&self) -> &ProbingState {
self.base.get_state() | random_line_split |
sjisprober.rs | use std::ops::Deref;
use std::ops::DerefMut;
use super::enums::MachineState;
use super::mbcharsetprober::MultiByteCharsetProber;
use super::charsetprober::CharsetProber;
use super::enums::ProbingState;
use super::codingstatemachine::CodingStateMachine;
use super::mbcssm::SJIS_SM_MODEL;
use super::chardistribution::SJIS... |
}
impl<'a> SJISProber<'a> {
pub fn new() -> SJISProber<'a> {
let mut x = SJISProber {
base: MultiByteCharsetProber::new(),
m_context_analyzer: SJISContextAnalysis::new(),
};
x.base.m_coding_sm = Some(CodingStateMachine::new(&SJIS_SM_MODEL));
x.base.m_distrib... | {
self.base.get_state()
} | identifier_body |
sjisprober.rs | use std::ops::Deref;
use std::ops::DerefMut;
use super::enums::MachineState;
use super::mbcharsetprober::MultiByteCharsetProber;
use super::charsetprober::CharsetProber;
use super::enums::ProbingState;
use super::codingstatemachine::CodingStateMachine;
use super::mbcssm::SJIS_SM_MODEL;
use super::chardistribution::SJIS... | <'a>(&'a mut self) -> &'a mut MultiByteCharsetProber<'x> {
&mut self.base
}
}
impl<'a> CharsetProber for SJISProber<'a> {
fn reset(&mut self) {
self.base.reset();
self.m_context_analyzer.reset();
}
fn feed(&mut self, byte_str: &[u8]) -> &ProbingState {
{
let ... | deref_mut | identifier_name |
artsyXapp.ts | import artsyXapp from "@artsy/xapp"
const { API_URL, CLIENT_ID, CLIENT_SECRET } = process.env
export function initializeArtsyXapp(startServerCallback) {
console.log("[Force] Initializing artsyXapp...")
/**
* If we can't get an xapp token, start the server but retry every 30 seconds.
* Until an xapp token i... | artsyXapp.init(
{ id: CLIENT_ID, secret: CLIENT_SECRET, url: API_URL },
error => {
if (error) {
console.error(error)
}
if (!error) {
console.log("[Force] Successfully fetched xapp token.")
startServerCallback()
}
}
)
} |
// Get an xapp token | random_line_split |
artsyXapp.ts | import artsyXapp from "@artsy/xapp"
const { API_URL, CLIENT_ID, CLIENT_SECRET } = process.env
export function | (startServerCallback) {
console.log("[Force] Initializing artsyXapp...")
/**
* If we can't get an xapp token, start the server but retry every 30 seconds.
* Until an xapp token is fetched, the `ARTSY_XAPP_TOKEN` sharify value will
* not be present, and any requests made via the Force server (or a user's
... | initializeArtsyXapp | identifier_name |
artsyXapp.ts | import artsyXapp from "@artsy/xapp"
const { API_URL, CLIENT_ID, CLIENT_SECRET } = process.env
export function initializeArtsyXapp(startServerCallback) {
console.log("[Force] Initializing artsyXapp...")
/**
* If we can't get an xapp token, start the server but retry every 30 seconds.
* Until an xapp token i... |
}
)
}
| {
console.log("[Force] Successfully fetched xapp token.")
startServerCallback()
} | conditional_block |
artsyXapp.ts | import artsyXapp from "@artsy/xapp"
const { API_URL, CLIENT_ID, CLIENT_SECRET } = process.env
export function initializeArtsyXapp(startServerCallback) | {
console.log("[Force] Initializing artsyXapp...")
/**
* If we can't get an xapp token, start the server but retry every 30 seconds.
* Until an xapp token is fetched, the `ARTSY_XAPP_TOKEN` sharify value will
* not be present, and any requests made via the Force server (or a user's
* browser) directly ... | identifier_body | |
github_stats.py | #!/usr/bin/env python
"""Simple tools to query github.com and gather stats about issues.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import print_function
import json
import ... | "this is the full list (generated with the script \n"
":file:`tools/github_stats.py`):" % (n_total, n_pulls, n_issues))
print()
print('Pull Requests (%d):\n' % n_pulls)
report(pulls, show_urls)
print()
print('Issues (%d):\n' % n_issues)
report(issues, show_urls) | random_line_split | |
github_stats.py | #!/usr/bin/env python
"""Simple tools to query github.com and gather stats about issues.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import print_function
import json
import ... | (project="matplotlib/matplotlib", state="closed", pulls=False):
"""Get a list of the issues from the Github API."""
which = 'pulls' if pulls else 'issues'
url = "https://api.github.com/repos/%s/%s?state=%s&per_page=%i" % (project, which, state, PER_PAGE)
return get_paged_request(url)
def _parse_dateti... | get_issues | identifier_name |
github_stats.py | #!/usr/bin/env python
"""Simple tools to query github.com and gather stats about issues.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import print_function
import json
import ... |
# For regular reports, it's nice to show them in reverse chronological order
issues = sorted_by_field(issues, reverse=True)
pulls = sorted_by_field(pulls, reverse=True)
n_issues, n_pulls = map(len, (issues, pulls))
n_total = n_issues + n_pulls
# Print summary report we can directly include i... | issues = issues_closed_since(since, pulls=False)
pulls = issues_closed_since(since, pulls=True) | conditional_block |
github_stats.py | #!/usr/bin/env python
"""Simple tools to query github.com and gather stats about issues.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import print_function
import json
import ... |
def _parse_datetime(s):
"""Parse dates in the format returned by the Github API."""
if s:
return datetime.strptime(s, ISO8601)
else:
return datetime.fromtimestamp(0)
def issues2dict(issues):
"""Convert a list of issues to a dict, keyed by issue number."""
idict = {}
for i in... | """Get a list of the issues from the Github API."""
which = 'pulls' if pulls else 'issues'
url = "https://api.github.com/repos/%s/%s?state=%s&per_page=%i" % (project, which, state, PER_PAGE)
return get_paged_request(url) | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.