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 |
|---|---|---|---|---|
programs.ts | import type {
EpisodeCounts,
IDBStoreUpgrade,
ProgramEpisodeCounts,
ProgramsStore,
ProgramsStoreObject,
TVManagerDB
} from "stores";
import type {
ModelType,
PersistedProgram
} from "models";
import type { IDBPDatabase } from "idb";
const upgradeTo: IDBStoreUpgrade<TVManagerDB>[] = [
// Version 1
(db: IDBPDa... | counts.expectedCount += seriesCounts.expectedCount;
return counts;
}, {
seriesCount: 0,
episodeCount: 0,
watchedCount: 0,
recordedCount: 0,
expectedCount: 0
});
return {
ProgramID: id,
Name: name,
... | random_line_split | |
fingerprint.rs | resh = try!(is_fresh(&loc, &mut fingerprint));
let root = cx.out_dir(pkg, kind, target);
let mut missing_outputs = false;
if !profile.doc {
for filename in try!(cx.target_filenames(pkg, target, profile,
kind)).iter() {
missing_outputs |= ... |
/// Prepare work for when a package starts to build
pub fn prepare_init(cx: &mut Context, pkg: &Package, kind: Kind)
-> (Work, Work) {
let new1 = dir(cx, pkg, kind);
let new2 = new1.clone();
let work1 = Work::new(move |_| {
if fs::metadata(&new1).is_err() {
try!(fs... | {
let _p = profile::start(format!("fingerprint build cmd: {}",
pkg.package_id()));
let new = dir(cx, pkg, kind);
let loc = new.join("build");
info!("fingerprint at: {}", loc.display());
let new_fingerprint = try!(calculate_build_cmd_fingerprint(cx, pkg));
le... | identifier_body |
fingerprint.rs | resh = try!(is_fresh(&loc, &mut fingerprint));
let root = cx.out_dir(pkg, kind, target);
let mut missing_outputs = false;
if !profile.doc {
for filename in try!(cx.target_filenames(pkg, target, profile,
kind)).iter() {
missing_outputs |= ... | <'a, 'cfg>(cx: &mut Context<'a, 'cfg>,
pkg: &'a Package,
target: &'a Target,
profile: &'a Profile,
kind: Kind)
-> CargoResult<Fingerprint> {
let key = (pkg.package_id(), target, profile, kind);
mat... | calculate | identifier_name |
fingerprint.rs | not always be
// available and the dirtiness propagation for modification is tracked
// elsewhere. Also skip fingerprints of binaries because they don't actually
// induce a recompile, they're just dependencies in the sense that they need
// to be built.
let deps = try!(cx.dep_targets(pkg, target, ... | source.fingerprint(pkg)
}
fn filename(target: &Target, profile: &Profile) -> String {
let kind = if target.is_lib() {"lib"} else {"bin"}; | random_line_split | |
answer.py | #!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Solution
# Find critical points, store in a max heap using min heap properties (-height)
#-------------------------------------------------------------------------------
import heapq
class Solution:
def getSk... | :
def getSkyline(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
if not buildings:
return []
if len(buildings) == 1:
l, r, h = buildings.pop()
return [[l, h],[r, 0]]
# Find the right most p... | Solution | identifier_name |
answer.py | #!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Solution
# Find critical points, store in a max heap using min heap properties (-height)
#-------------------------------------------------------------------------------
import heapq
class Solution:
def getSk... |
sky = [[-1,0]]
# possible corner positions
position = set([b[0] for b in buildings] + [b[1] for b in buildings])
# live buildings
live = []
i = 0
for t in sorted(position):
# add the new buildings whose left side is lefter than position t
... | if sky[-1][1] != hei:
sky.append([pos, hei]) | identifier_body |
answer.py | #!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Solution
# Find critical points, store in a max heap using min heap properties (-height)
#-------------------------------------------------------------------------------
import heapq
class Solution:
def getSk... |
# pick the highest existing building at this moment
h = -live[0][0] if live else 0
addsky(t, h)
return sky[1:]
#-------------------------------------------------------------------------------
# This does not pass test cases (Memory inefficient)
#--------------------------... | heapq.heappop(live) | conditional_block |
VirtualMachineMonitorAgent.py | Cloud/%s" % self.runningPod
for csOption, csDefault, varName in ( ( "MinWorkingLoad", 0.01, "vmMinWorkingLoad" ),
( "LoadAverageTimespan", 60, "vmLoadAvgTimespan" ),
( "HaltPeriod", 600, "haltPeriod" ),
... | ( self, hb | __processHeartBeatMessage | identifier_name |
VirtualMachineMonitorAgent.py | Cloud/%s" % self.runningPod
for csOption, csDefault, varName in ( ( "MinWorkingLoad", 0.01, "vmMinWorkingLoad" ),
( "LoadAverageTimespan", 60, "vmLoadAvgTimespan" ),
( "HaltPeriod", 600, "haltPeriod" ),
... | self.log.info( "Halt Before Margin : %d" % self.haltBeforeMargin )
self.log.info( "HeartBeat Period : %d" % self.heartBeatPeriod )
if self.vmID:
self.log.info( "DIRAC ID : %s" % self.vmID )
if self.uniqueID:
self.log.info( "Unique ID : %s" % self.uniqueID )
... | self.log.info( "Min Working Load : %f" % self.vmMinWorkingLoad )
self.log.info( "Load Avg Timespan : %d" % self.vmLoadAvgTimespan )
self.log.info( "Job wrappers location : %s" % self.vmJobWrappersLocation )
self.log.info( "Halt Period : %d" % self.haltPeriod ) | random_line_split |
VirtualMachineMonitorAgent.py |
path = "%s/%s" % ( imgPath, csOption )
value = gConfig.getValue( path, csDefault )
if not value :
return S_ERROR( "%s points to an empty string, cannot be!" % path )
setattr( self, varName, value )
self.haltBeforeMargin = max( self.haltBeforeMargin, int( self.am_getPollingTime() ) ... | if not self.runningPod:
return S_ERROR( "/LocalSite/RunningPod is not defined" )
#Variables coming from the vm
imgPath = "/Cloud/%s" % self.runningPod
for csOption, csDefault, varName in ( ( "MinWorkingLoad", 0.01, "vmMinWorkingLoad" ),
( "LoadAverageTimespan... | identifier_body | |
VirtualMachineMonitorAgent.py | Cloud/%s" % self.runningPod
for csOption, csDefault, varName in ( ( "MinWorkingLoad", 0.01, "vmMinWorkingLoad" ),
( "LoadAverageTimespan", 60, "vmLoadAvgTimespan" ),
( "HaltPeriod", 600, "haltPeriod" ),
... |
result = self.__declareInstanceRunning()
if not result[ 'OK' ]:
self.log.error( "Could not declare instance running", result[ 'Message' ] )
self.__haltInstance()
return S_ERROR( "Halting!" )
self.__instanceInfo = result[ 'Value' ]
#Get the cs config
result = self.__getCSConfig()... | self.uniqueID = result['Value'] | conditional_block |
build.rs | Root;
use std::collections::HashSet;
fn main() {
let build_root = BuildRoot::find().unwrap();
let thirdpartyprotobuf = build_root.join("3rdparty/protobuf");
mark_dir_as_rerun_trigger(&thirdpartyprotobuf);
let grpcio_output_dir = PathBuf::from("src/gen");
replace_if_changed(&grpcio_output_dir, |path| {
g... |
}
dirs_needing_mod_rs.remove(&dst);
dst = dst.join("mod.rs");
std::fs::copy(f.path(), dst).unwrap();
}
disable_clippy_in_generated_code(out_dir).expect("Failed to strip clippy from generated code");
for dir in &dirs_needing_mod_rs {
generate_mod_rs(dir).expect("Failed to write mod.rs");
... | {
std::fs::create_dir_all(&dst).unwrap();
} | conditional_block |
build.rs | Root;
use std::collections::HashSet;
fn main() {
let build_root = BuildRoot::find().unwrap();
let thirdpartyprotobuf = build_root.join("3rdparty/protobuf");
mark_dir_as_rerun_trigger(&thirdpartyprotobuf);
let grpcio_output_dir = PathBuf::from("src/gen");
replace_if_changed(&grpcio_output_dir, |path| {
g... | .into_iter()
.filter_map(|f| f.ok())
.filter(|f| f.path().extension() == Some("rs".as_ref()))
{
let mut parts: Vec<_> = f
.path()
.file_name()
.unwrap()
.to_str()
.unwrap()
.split('.')
.collect();
// pop .rs
parts.pop();
let mut dst = out_dir.to_o... | {
tower_grpc_build::Config::new()
.enable_server(true)
.enable_client(true)
.build(
&[PathBuf::from(
"build/bazel/remote/execution/v2/remote_execution.proto",
)],
&std::fs::read_dir(&thirdpartyprotobuf)
.unwrap()
.into_iter()
.map(|d| d.unwrap().path())
... | identifier_body |
build.rs | Root;
use std::collections::HashSet;
fn main() {
let build_root = BuildRoot::find().unwrap();
let thirdpartyprotobuf = build_root.join("3rdparty/protobuf");
mark_dir_as_rerun_trigger(&thirdpartyprotobuf);
let grpcio_output_dir = PathBuf::from("src/gen");
replace_if_changed(&grpcio_output_dir, |path| {
g... | <F: FnOnce(&Path)>(path: &Path, f: F) {
let tempdir = tempfile::TempDir::new().unwrap();
f(tempdir.path());
if !dir_diff::is_different(path, tempdir.path()).unwrap() {
return;
}
if path.exists() {
std::fs::remove_dir_all(path).unwrap();
}
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
... | replace_if_changed | identifier_name |
build.rs | Root;
use std::collections::HashSet;
fn main() {
let build_root = BuildRoot::find().unwrap();
let thirdpartyprotobuf = build_root.join("3rdparty/protobuf"); | format(path);
});
let tower_output_dir = PathBuf::from("src/gen_for_tower");
replace_if_changed(&tower_output_dir, |path| {
generate_for_tower(&thirdpartyprotobuf, path);
format(path);
});
// Re-gen if, say, someone does a git clean on the gen dir but not the target dir. This ensures
// genera... | mark_dir_as_rerun_trigger(&thirdpartyprotobuf);
let grpcio_output_dir = PathBuf::from("src/gen");
replace_if_changed(&grpcio_output_dir, |path| {
generate_for_grpcio(&thirdpartyprotobuf, path); | random_line_split |
AvailabilityNodes.py | from Child import Child
from Node import Node # noqa: I201 | # availability-spec-list -> availability-entry availability-spec-list?
Node('AvailabilitySpecList', kind='SyntaxCollection',
element='AvailabilityArgument'),
# Wrapper for all the different entries that may occur inside @available
# availability-entry -> '*' ','?
# | id... |
AVAILABILITY_NODES = [ | random_line_split |
Stats.tsx | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { translatable } from 'react-instantsearch-core';
import { createClassNames } from '../core/utils';
const cx = createClassNames('Stats');
export type StatsProps = {
className?: string;
areHitsSorted: boolean... | className = '',
areHitsSorted,
nbHits,
nbSortedHits,
processingTimeMS,
translate,
}) => {
return (
<div className={classNames(cx(''), className)}>
<span className={cx('text')}>
{translate(
'stats',
nbHits,
processingTimeMS,
nbSortedHits,
... | areHitsSorted?: boolean
): string;
};
const Stats: React.FC<StatsProps> = ({ | random_line_split |
encodeParam.test.ts | import encodeParam from './encodeParam'
import type { UrlParam } from '../hooks/useParam'
describe('encodeParam', () => {
it('encodes a parameter', () => {
expect(
encodeParam(
{
name: 'test',
defaultValue: {},
encode: (value) => JSON.stringify(value),
decode... | })
}) | expect(encodeParam(param, undefined)).toEqual(null) | random_line_split |
methods.app-test.js | import { Meteor } from "meteor/meteor";
import { Roles } from "meteor/alanning:roles";
import { expect } from "meteor/practicalmeteor:chai";
import { sinon } from "meteor/practicalmeteor:sinon";
import { Discounts } from "/imports/plugins/core/discounts/lib/collections";
const code = {
discount: 12,
label: "Discou... |
beforeEach(function () {
sandbox = sinon.sandbox.create();
});
afterEach(function () {
sandbox.restore();
});
describe("discounts/addCode", function () {
it("should throw 403 error with discounts permission", function (done) {
sandbox.stub(Roles, "userIsInRole", () => false);
// thi... | Meteor._sleepForMs(7000);
});
describe("discount code methods", function () {
let sandbox; | random_line_split |
test_vm_vga.py | '''
New Integration Test for VM vga mode.
@author: quarkonics
'''
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.config_operations as conf_ops
import zstackwoodpecker.test_util as test_util
test_stub = test_lib.lib_get_test_stub()
_config_ = {
'timeout' : 360,
... |
vm.destroy()
vm.check()
conf_ops.change_global_config('vm', 'videoType', default_mode)
test_util.test_pass('Create VM Test Success')
#Will be called only if exception happens in test().
def error_cleanup():
conf_ops.change_global_config('vm', 'videoType', default_mode)
global vm
... | test_util.test_fail('VM is expected to work in vga mode instead of %s' % (vm_mode)) | conditional_block |
test_vm_vga.py | '''
New Integration Test for VM vga mode.
@author: quarkonics
'''
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.config_operations as conf_ops
import zstackwoodpecker.test_util as test_util
test_stub = test_lib.lib_get_test_stub()
_config_ = {
'timeout' : 360,
... | ():
conf_ops.change_global_config('vm', 'videoType', default_mode)
global vm
if vm:
vm.destroy()
| error_cleanup | identifier_name |
test_vm_vga.py | '''
New Integration Test for VM vga mode.
@author: quarkonics
'''
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.config_operations as conf_ops
import zstackwoodpecker.test_util as test_util
test_stub = test_lib.lib_get_test_stub()
_config_ = {
'timeout' : 360,
... | conf_ops.change_global_config('vm', 'videoType', default_mode)
global vm
if vm:
vm.destroy() | identifier_body | |
test_vm_vga.py | '''
New Integration Test for VM vga mode.
| import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.config_operations as conf_ops
import zstackwoodpecker.test_util as test_util
test_stub = test_lib.lib_get_test_stub()
_config_ = {
'timeout' : 360,
'noparallel' : False
}
vm = None
default_mode = None
... | @author: quarkonics
'''
| random_line_split |
outputcomp.ts | import {Component, ElementRef} from 'angular2/core';
import {DigiService} from '../../services/digiservice';
import {Digi, OutText} from '../../lib/digi';
@Component({
selector: 'jdigi-output',
template: '<textarea readonly class=\'console-area col-md-12\'>{{text}}</textarea>',
styles: [
`
.co... | _digi: Digi;
_text: string;
_elem: HTMLTextAreaElement;
constructor(digiService: DigiService, elementRef: ElementRef) {
super();
this._digi = digiService.digi;
this._text = '';
this._digi.outText = this;
this._elem = elementRef.nativeElement;
}
get text(): string {
return this._tex... | export class OutputComponent extends OutText {
| random_line_split |
outputcomp.ts | import {Component, ElementRef} from 'angular2/core';
import {DigiService} from '../../services/digiservice';
import {Digi, OutText} from '../../lib/digi';
@Component({
selector: 'jdigi-output',
template: '<textarea readonly class=\'console-area col-md-12\'>{{text}}</textarea>',
styles: [
`
.co... |
get text(): string {
return this._text;
}
/**
* @Override OutputText
*/
clear():void {
this._text = '';
}
/**
* @Override OutputText
*/
putText(str: string) {
let area = this._elem;
this._text += str;
area.scrollTop = area.scrollHeight;
}
}
| {
super();
this._digi = digiService.digi;
this._text = '';
this._digi.outText = this;
this._elem = elementRef.nativeElement;
} | identifier_body |
outputcomp.ts | import {Component, ElementRef} from 'angular2/core';
import {DigiService} from '../../services/digiservice';
import {Digi, OutText} from '../../lib/digi';
@Component({
selector: 'jdigi-output',
template: '<textarea readonly class=\'console-area col-md-12\'>{{text}}</textarea>',
styles: [
`
.co... | extends OutText {
_digi: Digi;
_text: string;
_elem: HTMLTextAreaElement;
constructor(digiService: DigiService, elementRef: ElementRef) {
super();
this._digi = digiService.digi;
this._text = '';
this._digi.outText = this;
this._elem = elementRef.nativeElement;
}
get text(): string {
... | OutputComponent | identifier_name |
unittest_job_manager.py | #-------------------------------------------------------------------------
# The Azure Batch Apps Python Client
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docu... | mock_job.assert_called_with(mgr._client, '1', '2', '3')
resp.result = {'id':'1', 'name':'2', 'type':'3', 'other':'4'}
job = mgr.get_job(jobid="test_id")
mgr._client.get_job.assert_called_with(job_id="test_id")
mock_job.assert_called_with(mgr._client, '1', '2', '3', other='4')
... | """Test get_job"""
mgr = JobManager(mock_creds, cfg=mock_cfg)
with self.assertRaises(ValueError):
mgr.get_job()
resp = mock.create_autospec(Response)
resp.success = False
resp.result = RestCallException(None, "test", None)
mgr._client.get_job.return_value =... | identifier_body |
unittest_job_manager.py | #-------------------------------------------------------------------------
# The Azure Batch Apps Python Client
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docu... | unittest.main() | conditional_block | |
unittest_job_manager.py | #-------------------------------------------------------------------------
# The Azure Batch Apps Python Client
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docu... | (unittest.TestCase):
"""Unit tests for JobManager"""
@mock.patch('batchapps.credentials.Configuration')
@mock.patch('batchapps.credentials.Credentials')
@mock.patch('batchapps.job_manager.BatchAppsApi')
@mock.patch('batchapps.job_manager.SubmittedJob')
def test_jobmgr_get_job(self, mock_job, mo... | TestJobManager | identifier_name |
unittest_job_manager.py | #-------------------------------------------------------------------------
# The Azure Batch Apps Python Client
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docu... | from unittest import mock
except ImportError:
import mock
from batchapps.job_manager import JobManager
from batchapps.api import Response
from batchapps.exceptions import RestCallException
from batchapps.files import FileCollection
from batchapps.job import (
JobSubmission,
SubmittedJob)
# pylint: dis... | import unittest2 as unittest
except ImportError:
import unittest
try: | random_line_split |
simple.rs | use stb_truetype::FontInfo;
use std::borrow::Cow;
fn main() | {
let file = include_bytes!("../fonts/Gudea-Regular.ttf") as &[u8];
let font = FontInfo::new(Cow::Borrowed(file), 0).unwrap();
let vmetrics = font.get_v_metrics();
println!("{:?}", vmetrics);
let c = '\\';
let cp = c as u32;
let g = font.find_glyph_index(cp);
println!("{:?} -> {:?}", cp,... | identifier_body | |
simple.rs | use stb_truetype::FontInfo;
use std::borrow::Cow;
fn | () {
let file = include_bytes!("../fonts/Gudea-Regular.ttf") as &[u8];
let font = FontInfo::new(Cow::Borrowed(file), 0).unwrap();
let vmetrics = font.get_v_metrics();
println!("{:?}", vmetrics);
let c = '\\';
let cp = c as u32;
let g = font.find_glyph_index(cp);
println!("{:?} -> {:?}", ... | main | identifier_name |
simple.rs | use stb_truetype::FontInfo;
use std::borrow::Cow;
fn main() {
let file = include_bytes!("../fonts/Gudea-Regular.ttf") as &[u8];
let font = FontInfo::new(Cow::Borrowed(file), 0).unwrap();
let vmetrics = font.get_v_metrics();
println!("{:?}", vmetrics);
let c = '\\';
let cp = c as u32;
let g ... | println!("{:?}", advance);
let scale = font.scale_for_pixel_height(20.0);
println!("{:?}", scale);
} | println!("{:?}", hmetrics);
let advance = font.get_codepoint_kern_advance('f' as u32, 'f' as u32); | random_line_split |
runpack.py |
""" WARNING! this module is incomplete and may have rough edges. Use only
if necessary
"""
import py
from struct import unpack
from rpython.rlib.rstruct.formatiterator import FormatIterator
from rpython.rlib.rstruct.error import StructError
class MasterReader(object):
def __init__(self, s):
self.input = ... |
ReaderForPos.__name__ = 'ReaderForPos%d' % pos
return ReaderForPos
class FrozenUnpackIterator(FormatIterator):
def __init__(self, fmt):
self.formats = []
self.fmt = fmt
def operate(self, fmtdesc, repetitions):
if fmtdesc.needcount:
self.formats.append((fmtdesc, rep... | self.value = value | identifier_body |
runpack.py |
""" WARNING! this module is incomplete and may have rough edges. Use only
if necessary
"""
import py
from struct import unpack
from rpython.rlib.rstruct.formatiterator import FormatIterator
from rpython.rlib.rstruct.error import StructError
class MasterReader(object):
def __init__(self, s):
self.input = ... |
return res
def _freeze_(self):
assert self.formats
self._create_unpacking_func()
return True
def create_unpacker(unpack_str):
fmtiter = FrozenUnpackIterator(unpack_str)
fmtiter.interpret(unpack_str)
return fmtiter
create_unpacker._annspecialcase_ = 'specialize:memo'
d... | return res[0] | conditional_block |
runpack.py |
""" WARNING! this module is incomplete and may have rough edges. Use only
if necessary
"""
import py
from struct import unpack
from rpython.rlib.rstruct.formatiterator import FormatIterator
from rpython.rlib.rstruct.error import StructError
class MasterReader(object):
def __init__(self, s):
self.input = ... | (self, count):
return self.mr.read(count)
def appendobj(self, value):
self.value = value
ReaderForPos.__name__ = 'ReaderForPos%d' % pos
return ReaderForPos
class FrozenUnpackIterator(FormatIterator):
def __init__(self, fmt):
self.formats = []
self.fmt = fmt
... | read | identifier_name |
runpack.py | """ WARNING! this module is incomplete and may have rough edges. Use only
if necessary
"""
import py
from struct import unpack
from rpython.rlib.rstruct.formatiterator import FormatIterator
from rpython.rlib.rstruct.error import StructError
class MasterReader(object):
def __init__(self, s):
self.input = s... | def __init__(self, fmt):
self.formats = []
self.fmt = fmt
def operate(self, fmtdesc, repetitions):
if fmtdesc.needcount:
self.formats.append((fmtdesc, repetitions, None))
else:
for i in range(repetitions):
self.formats.append((fmtdesc, 1, ... | ReaderForPos.__name__ = 'ReaderForPos%d' % pos
return ReaderForPos
class FrozenUnpackIterator(FormatIterator): | random_line_split |
__init__.py | #
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# ... | #!/usr/bin/env python
#
# Copyright (c) 2014 Hamilton Kibbe <ham@hamiltonkib.be> | random_line_split | |
fa.ts | export default {
badge: 'نشان',
close: 'بستن',
dataIterator: {
noResultsText: 'نتیجهای یافت نشد',
loadingText: 'در حال بارگذاری...',
},
dataTable: {
itemsPerPageText: 'ردیف در صفحه:',
ariaLabel: {
sortDescending: 'مرتبسازی نزولی',
sortAscending: 'مرتبسازی صعودی',
sortNone:... | pageText: '{0} تا {1} از {2}',
},
datePicker: {
itemsSelected: '{0} انتخاب شده',
nextMonthAriaLabel: 'ماه بعد',
nextYearAriaLabel: 'سال بعد',
prevMonthAriaLabel: 'ماه قبل',
prevYearAriaLabel: 'سال قبل',
},
noDataText: 'دادهای موجود نیست',
carousel: {
prev: 'اسلاید قبلی',
next:... | nextPage: 'صفحهی بعد',
prevPage: 'صفحهی قبل',
firstPage: 'صفحهی یکم',
lastPage: 'صفحهی آخر', | random_line_split |
povray.js | // Generated by CoffeeScript 1.6.3
(function() {
var Stl, stl_parser;
stl_parser = require('../parser/stl_parser');
Stl = (function() {
function | () {}
return Stl;
})();
Stl.PovRay = (function() {
function PovRay() {}
PovRay.prototype._povHeaders = function(name) {
return "#declare " + name + " = mesh {\n";
};
PovRay.prototype._povFooters = function() {
return "}";
};
PovRay.prototype.convertFile = function(fileP... | Stl | identifier_name |
povray.js | // Generated by CoffeeScript 1.6.3
(function() {
var Stl, stl_parser;
stl_parser = require('../parser/stl_parser');
Stl = (function() {
function Stl() {}
return Stl;
})();
Stl.PovRay = (function() {
function PovRay() {}
PovRay.prototype._povHeaders = function(name) {
return "#decla... |
output += " }\n";
return output;
};
return PovRay;
})();
module.exports = new Stl.PovRay();
}).call(this);
| {
vertex = _ref[idx];
output += " <" + vertex[0] + ", " + (-vertex[1]) + ", " + vertex[2] + ">";
if (idx !== (polygon.verticies.length - 1)) {
output += ",\n";
}
} | conditional_block |
povray.js | // Generated by CoffeeScript 1.6.3
(function() {
var Stl, stl_parser;
stl_parser = require('../parser/stl_parser');
Stl = (function() {
function Stl() {}
return Stl;
})();
Stl.PovRay = (function() {
function PovRay() {}
PovRay.prototype._povHeaders = function(name) {
return "#decla... | };
return PovRay;
})();
module.exports = new Stl.PovRay();
}).call(this); | random_line_split | |
povray.js | // Generated by CoffeeScript 1.6.3
(function() {
var Stl, stl_parser;
stl_parser = require('../parser/stl_parser');
Stl = (function() {
function Stl() {}
return Stl;
})();
Stl.PovRay = (function() {
function PovRay() |
PovRay.prototype._povHeaders = function(name) {
return "#declare " + name + " = mesh {\n";
};
PovRay.prototype._povFooters = function() {
return "}";
};
PovRay.prototype.convertFile = function(filePath, callback, progressCb) {
var output,
_this = this;
output = ""... | {} | identifier_body |
Message.js | */
class Message {
constructor(channel, data, client) {
/**
* The client that instantiated the Message
* @name Message#client
* @type {Client}
* @readonly
*/
Object.defineProperty(this, 'client', { value: client });
/**
* The channel that the message was sent in
* @typ... | * Represents a message on Discord. | random_line_split | |
Message.js | AGE_MESSAGES)
);
}
/**
* Whether the message is pinnable by the client user
* @type {boolean}
* @readonly
*/
get pinnable() {
return !this.guild ||
this.channel.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_MESSAGES);
}
/**
* Options that can be passed into editM... | const reaction = this.reactions.get(emojiID);
if (reaction.users.has(user.id)) {
reaction.users.delete(user.id);
reaction.count--;
if (user.id === this.client.user.id) reaction.me = false;
if (reaction.count <= 0) this.reactions.delete(emojiID);
return reaction;
... | conditional_block | |
Message.js | `@${member.user.username}`;
} else {
const user = this.client.users.get(id);
if (user) return `@${user.username}`;
return input;
}
})
.replace(/<#[0-9]+>/g, input => {
const channel = this.client.channels.get(input.replace(/<|#|>/g, ''));
if (ch... | nowledge() | identifier_name | |
Message.js | .get(input.replace(/<|#|>/g, ''));
if (channel) return `#${channel.name}`;
return input;
})
.replace(/<@&[0-9]+>/g, input => {
if (this.channel.type === 'dm' || this.channel.type === 'group') return input;
const role = this.guild.roles.get(input.replace(/<|@|>|&/g, ''));
... | return this.client.api.channels(this.channel.id).messages(this.id).ack
.post({ data: { token: this.client.rest._ackToken } })
.then(res => {
if (res.token) this.client.rest._ackToken = res.token;
return this;
});
}
| identifier_body | |
auto-grade.py | 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 option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHO... |
if not is_client_up(hostname):
print "Unable to reach client on host '%s'" % hostname
sys.exit(1)
try:
ss = dom.snapshotCreateXML(xml % domain, 0)
except:
print "Failed to create snapshot of domain (%s)" % domain
sys.exit(1)
conn.close()
return Environment(do... | print 'Domain (%s) in unsupported state (%s)' % (domain, state)
sys.exit(1) | conditional_block |
auto-grade.py | 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 option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHO... | ssh = ssh_connect(hostname=hostname, port=port)
scp = paramiko.SFTPClient.from_transport(ssh.get_transport())
scp.put(spath, dpath)
scp.put(chk_path, chk_path)
(stdin, stdout, stderr) = ssh.exec_command("sha1sum -c %s" % chk_path)
chan = stdout.channel
if 0 != chan.recv_exit_status():
... | random_line_split | |
auto-grade.py | 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 option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the impli... | grade = 0
args = parse_prog_input()
sys.stdout.write("Standing up test environment...")
sys.stdout.flush()
env = setup_test_env(args.hostname, args.domain)
print "complete"
try:
try:
sys.stdout.write("Checking syntax...")
sys.stdout.flush()
py_compile.... | identifier_body | |
auto-grade.py | 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 option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHO... | ():
grade = 0
args = parse_prog_input()
sys.stdout.write("Standing up test environment...")
sys.stdout.flush()
env = setup_test_env(args.hostname, args.domain)
print "complete"
try:
try:
sys.stdout.write("Checking syntax...")
sys.stdout.flush()
py_... | main | identifier_name |
range.rs | use std::fmt::Display;
#[cfg(feature = "inclusive_range")]
use std::ops::RangeInclusive;
#[cfg(not(feature = "inclusive_range"))]
pub fn range<T: 'static + PartialOrd + Display + Clone>(a: T,
b: T)
-> Box<F... |
})
}
#[cfg(test)]
#[cfg(not(feature = "inclusive_range"))]
mod tests {
use super::*;
// range
#[test]
pub fn range_valid() {
assert!(range(1, 100)(&1).is_ok());
assert!(range(1, 100)(&50).is_ok());
assert!(range(1, 100)(&100).is_ok());
}
#[test]
pub fn range_... | {
Err(::Invalid {
msg: "Must be in the range %1..%2.".to_string(),
args: vec![start.to_string(), end.to_string()],
human_readable: format!("Must be between {} and {}", start, end)
})
} | conditional_block |
range.rs | use std::fmt::Display;
#[cfg(feature = "inclusive_range")]
use std::ops::RangeInclusive;
#[cfg(not(feature = "inclusive_range"))]
pub fn range<T: 'static + PartialOrd + Display + Clone>(a: T,
b: T)
-> Box<F... | () {
assert!(range(1, 100)(&1).is_ok());
assert!(range(1, 100)(&50).is_ok());
assert!(range(1, 100)(&100).is_ok());
}
#[test]
pub fn range_invalid() {
assert!(range(1, 100)(&0).is_err());
assert!(range(1, 100)(&101).is_err());
}
}
#[cfg(test)]
#[cfg(feature = "i... | range_valid | identifier_name |
range.rs | use std::fmt::Display;
#[cfg(feature = "inclusive_range")]
use std::ops::RangeInclusive;
#[cfg(not(feature = "inclusive_range"))]
pub fn range<T: 'static + PartialOrd + Display + Clone>(a: T,
b: T)
-> Box<F... | }
#[cfg(test)]
#[cfg(not(feature = "inclusive_range"))]
mod tests {
use super::*;
// range
#[test]
pub fn range_valid() {
assert!(range(1, 100)(&1).is_ok());
assert!(range(1, 100)(&50).is_ok());
assert!(range(1, 100)(&100).is_ok());
}
#[test]
pub fn range_invalid... | {
// do bounds checking here so we can panic early if needed
if range.end() <= range.start() {
panic!("Invalid range!"); // TODO: Bad way to do this.
}
Box::new(move |s: &T| {
let start = range.start();
let end = range.end();
if *s >= *start && *s <= *end {
... | identifier_body |
range.rs | use std::fmt::Display;
#[cfg(feature = "inclusive_range")]
use std::ops::RangeInclusive;
#[cfg(not(feature = "inclusive_range"))]
pub fn range<T: 'static + PartialOrd + Display + Clone>(a: T,
b: T)
-> Box<F... | pub fn range_invalid() {
assert!(range(1..=100)(&0).is_err());
assert!(range(1..=100)(&101).is_err());
}
} | random_line_split | |
freedb-submit.py | #!/usr/bin/env python
import os, re, sys
if len(sys.argv) < 2:
|
# Read record
filename = sys.argv[1]
fd = file(filename)
record = fd.read()
fd.close()
# Update revision
newrecord = []
lbreak = "\r\n"
for line in record.splitlines():
if line.startswith('# Revision:'):
rev = int(line.split(':')[1]) + 1
line = '# Revision: %u' % rev
newrecord.append(line)
ne... | print "usage: %s <recordfile>" % sys.argv[0]
sys.exit(1) | conditional_block |
freedb-submit.py | #!/usr/bin/env python
import os, re, sys
if len(sys.argv) < 2:
print "usage: %s <recordfile>" % sys.argv[0]
sys.exit(1)
# Read record
filename = sys.argv[1]
fd = file(filename)
record = fd.read() |
# Update revision
newrecord = []
lbreak = "\r\n"
for line in record.splitlines():
if line.startswith('# Revision:'):
rev = int(line.split(':')[1]) + 1
line = '# Revision: %u' % rev
newrecord.append(line)
newrecord = lbreak.join(newrecord)
# Setup mail values
address = 'freedb-submit@freedb.org... | fd.close() | random_line_split |
suite.js | var path = require('path');
var test = require('ava');
var postcss = require('postcss');
var colorblindPlugin = require('..');
var colorNames = require('css-color-names');
var colorblind = require('color-blind');
var onecolor = require('onecolor');
var getProcessor = require('./_getProcessor');
var testPostCSS = requir... |
return testPostCSS(
t,
getFixture(color),
getFixture(colorblind[method.toLowerCase().trim()](color)),
{method: method}
);
}
['#123', '#000', '#fff', '#f06d06'].forEach(function(hex, index) {
test(
'should transform hex (' + (index + 1) + ')',
testColorMutation,
hex
);
});
[{
fro... | {
method = 'deuteranopia';
} | conditional_block |
suite.js | var path = require('path');
var test = require('ava');
var postcss = require('postcss');
var colorblindPlugin = require('..');
var colorNames = require('css-color-names');
var colorblind = require('color-blind');
var onecolor = require('onecolor');
var getProcessor = require('./_getProcessor');
var testPostCSS = requir... |
test(
'should do a multi tritanopia transform',
testPostCSS,
`.some-color { border: 3px #D929E2 solid; color: lime }`,
`.some-color { border: 3px ${colorblind.tritanopia('#D929E2')} solid; color: ${colorblind.tritanopia('lime')} }`,
{method: 'tritanopia'}
);
test(
'should work inside gradients',
testPos... | random_line_split | |
suite.js | var path = require('path');
var test = require('ava');
var postcss = require('postcss');
var colorblindPlugin = require('..');
var colorNames = require('css-color-names');
var colorblind = require('color-blind');
var onecolor = require('onecolor');
var getProcessor = require('./_getProcessor');
var testPostCSS = requir... |
['#123', '#000', '#fff', '#f06d06'].forEach(function(hex, index) {
test(
'should transform hex (' + (index + 1) + ')',
testColorMutation,
hex
);
});
[{
from: '#1234',
hex: '#123',
alpha: '0.27',
}, {
from: '#9344ABCD',
hex: '#9344AB',
alpha: '0.8',
}, {
from: '#FFFFFFFF',
hex: '#FFFFF... | {
if (!method) {
method = 'deuteranopia';
}
return testPostCSS(
t,
getFixture(color),
getFixture(colorblind[method.toLowerCase().trim()](color)),
{method: method}
);
} | identifier_body |
suite.js | var path = require('path');
var test = require('ava');
var postcss = require('postcss');
var colorblindPlugin = require('..');
var colorNames = require('css-color-names');
var colorblind = require('color-blind');
var onecolor = require('onecolor');
var getProcessor = require('./_getProcessor');
var testPostCSS = requir... | (t, color, method) {
if (!method) {
method = 'deuteranopia';
}
return testPostCSS(
t,
getFixture(color),
getFixture(colorblind[method.toLowerCase().trim()](color)),
{method: method}
);
}
['#123', '#000', '#fff', '#f06d06'].forEach(function(hex, index) {
test(
'should transform hex ('... | testColorMutation | identifier_name |
main.rs | #![crate_name = "rduperemove"]
#![feature(plugin)]
#![feature(io, os, collections, path)]
extern crate "rustc-serialize" as rustc_serialize;
extern crate docopt;
extern crate btrfs;
extern crate crypto;
extern crate deque;
#[macro_use]
extern crate log;
#[plugin] #[no_link]
extern crate docopt_macros;
use std::old... | {
base_dirs: Vec<Path>,
worker_count: usize,
min_file_size: usize,
}
docopt!(CommandLineOptions, "
rduperemove - Whole-file deduplication for BTRFS filesystems on (Linux 3.13+).
Usage: rduperemove [options] <path>...
rduperemove (-h|--help)
Options:
<path>... On... | Configuration | identifier_name |
main.rs | #![crate_name = "rduperemove"]
#![feature(plugin)]
#![feature(io, os, collections, path)]
extern crate "rustc-serialize" as rustc_serialize;
extern crate docopt;
extern crate btrfs;
extern crate crypto;
extern crate deque;
#[macro_use]
extern crate log;
#[plugin] #[no_link]
extern crate docopt_macros;
use std::old... | docopt!(CommandLineOptions, "
rduperemove - Whole-file deduplication for BTRFS filesystems on (Linux 3.13+).
Usage: rduperemove [options] <path>...
rduperemove (-h|--help)
Options:
<path>... One or more directories (on the same btrfs filesystem) \
... | }
| random_line_split |
Feature.py | import json
from feature_ramp import redis
class Feature(object):
"""
A class to control ramping features to a percentage of users
without needing to deploy to change the ramp.
Usage:
Feature("on_off_toggled").activate()
Feature("on_off_toggled").is_active
Feature("on_off_toggled").deac... | (self):
""" Returns the dictionary representation of this object for storage in Redis. """
return {
'whitelist': self.whitelist,
'blacklist': self.blacklist,
'percentage': self.percentage
}
def _deserialize(self, redis_obj):
""" Deserializes the ... | _get_redis_data | identifier_name |
Feature.py | import json
from feature_ramp import redis
class Feature(object):
"""
A class to control ramping features to a percentage of users
without needing to deploy to change the ramp.
Usage:
Feature("on_off_toggled").activate()
Feature("on_off_toggled").is_active
Feature("on_off_toggled").deac... |
def reset_settings(self):
""" Clears all settings for the feature. The feature is deactivated and
the whitelist and blacklist are emptied.
"""
self.percentage = 0
self.whitelist = []
self.blacklist = []
self._save()
def delete(self):
""" Delete... | """ Ramp feature to 0%. This is a convenience method useful for single-toggle features. """
self.set_percentage(0) | identifier_body |
Feature.py | import json
from feature_ramp import redis
class Feature(object):
"""
A class to control ramping features to a percentage of users
without needing to deploy to change the ramp.
Usage:
Feature("on_off_toggled").activate()
Feature("on_off_toggled").is_active
Feature("on_off_toggled").deac... |
return features_with_data
def _save(self):
""" Saves the feature settings to Redis in a dictionary. """
key = self._get_redis_key()
value = json.dumps(self._get_redis_data())
redis.set(key, value)
# store feature key in a set so we know what's turned on without
... | features_with_data[feature]['blacklist'] = data.blacklist | conditional_block |
Feature.py | import json
from feature_ramp import redis
class Feature(object):
"""
A class to control ramping features to a percentage of users
without needing to deploy to change the ramp.
Usage:
Feature("on_off_toggled").activate()
Feature("on_off_toggled").is_active
Feature("on_off_toggled").deac... |
def _deserialize(self, redis_obj):
""" Deserializes the serialized JSON representation of this object's dictionary
from Redis. If no object is provided, it returns an empty dictionary.
"""
if redis_obj is None:
return {}
return json.loads(redis_obj)
def __... | return {
'whitelist': self.whitelist,
'blacklist': self.blacklist,
'percentage': self.percentage
} | random_line_split |
cli.js | #!/usr/bin/env node
var listCommand = [];
require('./listCommand')(listCommand)
var logDetail = (str) => {
console.log(' > '+str);
}
var printHelp = () => {
var txtHelp = "";
var h = ' ';
var t = ' ';
txtHelp += "\n"+h+"Usage : rider [command] \n";
txtHelp += "\n"+h+"Command List : \n";
var maxText = 0;
... |
runCommand(params, () => {
process.exit(0);
});
});
}
// -- call main function --
main();
| {
printHelp();
return;
} | conditional_block |
cli.js | #!/usr/bin/env node
var listCommand = [];
require('./listCommand')(listCommand)
var logDetail = (str) => {
console.log(' > '+str);
}
var printHelp = () => {
var txtHelp = "";
var h = ' ';
var t = ' ';
txtHelp += "\n"+h+"Usage : rider [command] \n";
txtHelp += "\n"+h+"Command List : \n";
var maxText = 0;
... | return !foundCmd;
}
var runCommand = (params, cb) => {
var opt = params[2];
var objRun = listCommand[opt];
if(objRun != undefined && objRun != null){
objRun.runCommand(params, cb);
}
}
var main = () => {
console.log(">> Rider ... ");
var params = process.argv;
parseParams(params, (err) => {
if(err){
p... | return;
}
}); | random_line_split |
main.rs | #[macro_use]
extern crate serde_derive;
extern crate itertools;
extern crate clap;
use clap::{App, Arg};
mod config;
mod subscription;
mod util;
fn main() {
let matches = App::new("podstats")
.version("0.2.0")
.author("Andrew Michaud <dev@mail.andrewmichaud.com")
.about("Reads puckfetche... | for (i, item) in conf.get_latest_entry_names().iter().enumerate() {
println!("{} latest entry name: {}", i, item);
}
}
_ => println!("Given invalid option!"),
}
}
... | 6 => { | random_line_split |
main.rs | #[macro_use]
extern crate serde_derive;
extern crate itertools;
extern crate clap;
use clap::{App, Arg};
mod config;
mod subscription;
mod util;
fn main() |
println!("Loaded podstats!");
let conf_file = match matches.value_of("config") {
Some(c) => Some(c.to_string()),
None => None,
};
let mut conf = config::Config::new(conf_file);
conf.load_cache();
let prompt = util::Prompt {};
let mut menu_options = Vec::new();
menu_o... | {
let matches = App::new("podstats")
.version("0.2.0")
.author("Andrew Michaud <dev@mail.andrewmichaud.com")
.about("Reads puckfetcher's msgpack cache and provides stats.")
.arg(
Arg::with_name("config")
.short("c")
.long("config")
... | identifier_body |
main.rs | #[macro_use]
extern crate serde_derive;
extern crate itertools;
extern crate clap;
use clap::{App, Arg};
mod config;
mod subscription;
mod util;
fn main() {
let matches = App::new("podstats")
.version("0.2.0")
.author("Andrew Michaud <dev@mail.andrewmichaud.com")
.about("Reads puckfetche... |
5 => {
for (i, item) in conf.get_earliest_entry_names().iter().enumerate() {
println!("{} earliest entry name: {}", i, item);
}
}
6 => {
for (i, item) in conf.... | {
let item = conf.get_highest_entry_count_sub_name();
println!("Name of sub with highest entry count: {}", item);
} | conditional_block |
main.rs | #[macro_use]
extern crate serde_derive;
extern crate itertools;
extern crate clap;
use clap::{App, Arg};
mod config;
mod subscription;
mod util;
fn | () {
let matches = App::new("podstats")
.version("0.2.0")
.author("Andrew Michaud <dev@mail.andrewmichaud.com")
.about("Reads puckfetcher's msgpack cache and provides stats.")
.arg(
Arg::with_name("config")
.short("c")
.long("config")
... | main | identifier_name |
logged-in.guard.ts |
import { Injectable } from '@angular/core';
import { Router,Route, CanActivate,ActivatedRouteSnapshot,RouterStateSnapshot,CanLoad } from '@angular/router';
import { UserService } from './index';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class LoggedInGuard implements CanActivate,CanLoad {
| (private userService: UserService,private router:Router) {
}
// canActivate() {
// return this.user.isLoggedIn();
// }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
if (state.url !== '/login' && !this.userService.isLoggedIn()) {
... | constructor | identifier_name |
logged-in.guard.ts | import { Injectable } from '@angular/core';
import { Router,Route, CanActivate,ActivatedRouteSnapshot,RouterStateSnapshot,CanLoad } from '@angular/router';
import { UserService } from './index';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class LoggedInGuard implements CanActivate,CanLoad {
co... | } | random_line_split | |
logged-in.guard.ts |
import { Injectable } from '@angular/core';
import { Router,Route, CanActivate,ActivatedRouteSnapshot,RouterStateSnapshot,CanLoad } from '@angular/router';
import { UserService } from './index';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class LoggedInGuard implements CanActivate,CanLoad {
c... |
// canActivate() {
// return this.user.isLoggedIn();
// }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
if (state.url !== '/login' && !this.userService.isLoggedIn()) {
this.router.navigate(['/login']);
return false;
... | {
} | identifier_body |
logged-in.guard.ts |
import { Injectable } from '@angular/core';
import { Router,Route, CanActivate,ActivatedRouteSnapshot,RouterStateSnapshot,CanLoad } from '@angular/router';
import { UserService } from './index';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class LoggedInGuard implements CanActivate,CanLoad {
c... |
return true;
}
canLoad(route: Route): boolean {
let url = route.path;
this.userService.redirectURL=url;
if ( !this.userService.isLoggedIn() ) {
this.router.navigate(['/login']);
return false;
}
return true;
}
} | {
this.router.navigate(['/login']);
return false;
} | conditional_block |
zyx.py | """
/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
di... |
def write():
result = ""
# Just copy the first two lines: numAtoms and comment/title
result += sys.stdin.readline()
result += sys.stdin.readline()
for line in sys.stdin:
words = line.split()
result += '%-3s %9.5f %9.5f %9.5f' %\
(words[0], float(words[3]), float(word... | metaData = {}
metaData['inputFormat'] = 'xyz'
metaData['outputFormat'] = 'xyz'
metaData['operations'] = ['read', 'write']
metaData['identifier'] = 'ZYX Example Format'
metaData['name'] = 'ZYX'
metaData['description'] = "Mostly useless file format that reads xyz-style " +\
... | identifier_body |
zyx.py | """
/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
di... | result += sys.stdin.readline()
result += sys.stdin.readline()
for line in sys.stdin:
words = line.split()
result += '%-3s %9.5f %9.5f %9.5f' %\
(words[0], float(words[3]), float(words[2]), float(words[1]))
if len(words) > 4:
result += words[4:].join(' ')
... | result = ""
# Just copy the first two lines: numAtoms and comment/title | random_line_split |
zyx.py | """
/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
di... | ():
result = ""
# Just copy the first two lines: numAtoms and comment/title
result += sys.stdin.readline()
result += sys.stdin.readline()
for line in sys.stdin:
words = line.split()
result += '%-3s %9.5f %9.5f %9.5f' %\
(words[0], float(words[3]), float(words[2]), float... | write | identifier_name |
zyx.py | """
/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
di... |
elif args['display_name']:
print(getMetaData()['name'])
elif args['read']:
print(read())
elif args['write']:
print(write())
| print(json.dumps(getMetaData())) | conditional_block |
types.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::OESTextureHalfFloatBinding::OESTextureHalfFloatConstants;
use dom::bindings:... | (&self) -> u32 {
use self::TexFormat::*;
match *self {
DepthComponent => 1,
Alpha => 1,
Luminance => 1,
LuminanceAlpha => 2,
RGB => 3,
RGBA => 4,
}
}
}
| components | identifier_name |
types.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::OESTextureHalfFloatBinding::OESTextureHalfFloatConstants;
use dom::bindings:... | }
}
}
type_safe_wrapper! { TexFormat,
DepthComponent => constants::DEPTH_COMPONENT,
Alpha => constants::ALPHA,
RGB => constants::RGB,
RGBA => constants::RGBA,
Luminance => constants::LUMINANCE,
LuminanceAlpha => constants::LUMINANCE_ALPHA,
}
impl TexFormat {
/// Returns how man... | Float => 1,
HalfFloat => 1, | random_line_split |
types.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::OESTextureHalfFloatBinding::OESTextureHalfFloatConstants;
use dom::bindings:... |
/// Returns how many components a single element may hold. For example, a
/// UnsignedShort4444 holds four components, each with 4 bits of data.
pub fn components_per_element(&self) -> u32 {
use self::TexDataType::*;
match *self {
UnsignedByte => 1,
UnsignedShort565... | {
use self::TexDataType::*;
match *self {
UnsignedByte => 1,
UnsignedShort4444 | UnsignedShort5551 | UnsignedShort565 => 2,
Float => 4,
HalfFloat => 2,
}
} | identifier_body |
controllers.js | 'use strict';
angular
.module('app', ['angularFileUpload'])
.controller('AppController', ['$scope', 'FileUploader', function($scope, FileUploader) {
var uploader = $scope.uploader = new FileUploader({
url: 'upload.php'
});
// FILTERS
uploader.filters.push({
... | console.info('onProgressAll', progress);
};
uploader.onSuccessItem = function(fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
};
uploader.onErrorItem = function(fileItem, response, status, headers) {
... | uploader.onProgressItem = function(fileItem, progress) {
console.info('onProgressItem', fileItem, progress);
};
uploader.onProgressAll = function(progress) { | random_line_split |
dbw_test.py | #!/usr/bin/env python
import os
import csv
import rospy
from std_msgs.msg import Bool
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport
'''
You can use this file to test your DBW code against a bag recorded with a reference implementation.
The bag can be found at https://s3-us-west-1.a... | def __init__(self):
rospy.init_node('dbw_test_node')
rospy.Subscriber('/vehicle/steering_cmd', SteeringCmd, self.steer_cb)
rospy.Subscriber('/vehicle/throttle_cmd', ThrottleCmd, self.throttle_cb)
rospy.Subscriber('/vehicle/brake_cmd', BrakeCmd, self.brake_cb)
rospy.Subscrib... | class DBWTestNode(object): | random_line_split |
dbw_test.py | #!/usr/bin/env python
import os
import csv
import rospy
from std_msgs.msg import Bool
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport
'''
You can use this file to test your DBW code against a bag recorded with a reference implementation.
The bag can be found at https://s3-us-west-1.a... | (self):
rospy.init_node('dbw_test_node')
rospy.Subscriber('/vehicle/steering_cmd', SteeringCmd, self.steer_cb)
rospy.Subscriber('/vehicle/throttle_cmd', ThrottleCmd, self.throttle_cb)
rospy.Subscriber('/vehicle/brake_cmd', BrakeCmd, self.brake_cb)
rospy.Subscriber('/actual/stee... | __init__ | identifier_name |
dbw_test.py | #!/usr/bin/env python
import os
import csv
import rospy
from std_msgs.msg import Bool
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport
'''
You can use this file to test your DBW code against a bag recorded with a reference implementation.
The bag can be found at https://s3-us-west-1.a... |
base_path = os.path.dirname(os.path.abspath(__file__))
self.steerfile = os.path.join(base_path, 'steers.csv')
self.throttlefile = os.path.join(base_path, 'throttles.csv')
self.brakefile = os.path.join(base_path, 'brakes.csv')
self.loop()
def loop(self):
rate = rosp... | def __init__(self):
rospy.init_node('dbw_test_node')
rospy.Subscriber('/vehicle/steering_cmd', SteeringCmd, self.steer_cb)
rospy.Subscriber('/vehicle/throttle_cmd', ThrottleCmd, self.throttle_cb)
rospy.Subscriber('/vehicle/brake_cmd', BrakeCmd, self.brake_cb)
rospy.Subscriber('... | identifier_body |
dbw_test.py | #!/usr/bin/env python
import os
import csv
import rospy
from std_msgs.msg import Bool
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport
'''
You can use this file to test your DBW code against a bag recorded with a reference implementation.
The bag can be found at https://s3-us-west-1.a... |
def actual_throttle_cb(self, msg):
if self.dbw_enabled and self.throttle is not None:
self.throttle_data.append({'actual': msg.pedal_cmd,
'proposed': self.throttle})
self.throttle = None
def actual_brake_cb(self, msg):
if self.dbw... | self.steer_data.append({'actual': msg.steering_wheel_angle_cmd,
'proposed': self.steer})
self.steer = None | conditional_block |
fr_FR.js | Ext.namespace('Ext.ux.radioman.i18n');
/**
*
*/
Ext.ux.radioman.i18n.fr = {
Common: {
Yes: 'Oui',
No: 'Non',
Error: 'Erreur'
},
Navigation: {
Title: 'Navigation',
Items: {
Dashboard: 'Tableau de bord',
MediaLibrary: 'Collection'
},
HelpPanel: {
Title: 'Aide',
Items: {
Dashboard: '<h... | ArtistCol: 'Artiste',
AlbumCol: 'Album',
PlaytimeCol: 'Durée',
PathCol: 'Chemin',
DeleteMsgTitle: 'Vraiment effacer?',
DeleteMsgBody: 'Voulez-vous vraiment effacer la sélection suivante?',
NoSelectionError: 'Vous n\'avez pas sélectionné de playlist. Selectionnez-en une et clickez sur \'Modifier cet... | random_line_split | |
python.py | """
A Python "serializer". Doesn't do much serializing per se -- just converts to
and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for
other serializers.
"""
from __future__ import unicode_literals
from collections import OrderedDict
from django.apps import apps
from django.conf impor... | try:
data[Model._meta.pk.attname] = Model._meta.pk.to_python(d.get('pk'))
except Exception as e:
raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), None)
m2m_data = {}
field_names = {f.name for f in Model._meta.get_fields()}
... | """
Deserialize simple Python objects back into Django ORM instances.
It's expected that you pass the Python objects themselves (instead of a
stream or a string) to the constructor
"""
db = options.pop('using', DEFAULT_DB_ALIAS)
ignore = options.pop('ignorenonexistent', False)
for d in obj... | identifier_body |
python.py | """
A Python "serializer". Doesn't do much serializing per se -- just converts to
and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for
other serializers.
"""
from __future__ import unicode_literals
from collections import OrderedDict
from django.apps import apps
from django.conf impor... |
else:
m2m_convert = lambda v: force_text(field.remote_field.model._meta.pk.to_python(v), strings_only=True)
try:
m2m_data[field.name] = []
for pk in field_value:
m2m_data[field.name].append(m2m_convert(... | return force_text(field.remote_field.model._meta.pk.to_python(value), strings_only=True) | conditional_block |
python.py | """
A Python "serializer". Doesn't do much serializing per se -- just converts to
and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for
other serializers.
"""
from __future__ import unicode_literals
from collections import OrderedDict
from django.apps import apps
from django.conf impor... | data = OrderedDict([('model', force_text(model._meta))])
if not self.use_natural_primary_keys or not hasattr(obj, 'natural_key'):
data["pk"] = force_text(obj._get_pk_val(), strings_only=True)
data['fields'] = self._current
return data
def handle_field(self, obj, field):
... | random_line_split | |
python.py | """
A Python "serializer". Doesn't do much serializing per se -- just converts to
and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for
other serializers.
"""
from __future__ import unicode_literals
from collections import OrderedDict
from django.apps import apps
from django.conf impor... | (value):
if hasattr(value, '__iter__') and not isinstance(value, six.text_type):
return field.remote_field.model._default_manager.db_manager(db).get_by_natural_key(*value).pk
else:
return force_text(field.remote_fiel... | m2m_convert | identifier_name |
util.rs | extern crate libc;
extern crate fst_levenshtein;
extern crate fst_regex;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::intrinsics;
use std::io;
use std::ptr;
use fst_regex::Regex;
use fst_levenshtein::Levenshtein;
/// Exposes information about errors over the ABI
#[repr(C)]
pub s... |
make_free_fn!(fst_regex_free, *mut Regex);
| {
let pat = cstr_to_str(c_pat);
let re = with_context!(ctx, ptr::null_mut(), Regex::new(pat));
to_raw_ptr(re)
} | identifier_body |
util.rs | extern crate libc;
extern crate fst_levenshtein;
extern crate fst_regex;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::intrinsics;
use std::io;
use std::ptr;
use fst_regex::Regex;
use fst_levenshtein::Levenshtein;
/// Exposes information about errors over the ABI
#[repr(C)]
pub s... |
if !self.error_display.is_null() {
fst_string_free(self.error_display);
}
if !self.error_description.is_null() {
fst_string_free(self.error_description);
}
}
}
pub fn cstr_to_str<'a>(s: *mut libc::c_char) -> &'a str {
let cstr = unsafe { CStr::from_ptr(... | {
fst_string_free(self.error_debug);
} | conditional_block |
util.rs | extern crate libc;
extern crate fst_levenshtein;
extern crate fst_regex;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::intrinsics;
use std::io;
use std::ptr;
use fst_regex::Regex;
use fst_levenshtein::Levenshtein;
/// Exposes information about errors over the ABI
#[repr(C)]
pub s... | (&mut self) {
self.has_error = false;
if !self.error_type.is_null() {
fst_string_free(self.error_type);
}
if !self.error_debug.is_null() {
fst_string_free(self.error_debug);
}
if !self.error_display.is_null() {
fst_string_free(self.erro... | clear | identifier_name |
util.rs | extern crate libc;
extern crate fst_levenshtein;
extern crate fst_regex;
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::intrinsics;
use std::io;
use std::ptr;
use fst_regex::Regex;
use fst_levenshtein::Levenshtein;
/// Exposes information about errors over the ABI
#[repr(C)]
pub s... | CString::new(string).unwrap().into_raw()
}
pub fn to_raw_ptr<T>(v: T) -> *mut T {
Box::into_raw(Box::new(v))
}
// FIXME: This requires the nightly channel, isn't there a better way to
// get this information?
pub fn get_typename<T>(_: &T) -> &'static str {
unsafe { intrinsics::type_name::<T>() }
}
... | pub fn str_to_cstr(string: &str) -> *mut libc::c_char { | random_line_split |
momentum_sgd_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import hypothesis
from hypothesis import given
import hypothesis.strategies as st
import n... |
else:
paramup = param - adjgrad
return [adjgrad, adjgrad, paramup]
op = core.CreateOperator(
"MomentumSGDUpdate",
["grad", "param_momentum", "lr", "param"],
["grad", "param_momentum", "param"],
momentum=momentum,
... | return [adjgrad, adjgrad] | conditional_block |
momentum_sgd_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import hypothesis
from hypothesis import given
import hypothesis.strategies as st
import n... | param[i] -= grad_new
return (grad_new, m, param)
self.assertReferenceChecks(gc, op, [grad, m, lr, w, indices], sparse)
if __name__ == "__main__":
unittest.main() | return ((1 + momentum) * m_new - momentum * m, m_new)
def sparse(grad, m, lr, param, i):
grad_new, m_new = momentum_sgd(grad, m[i], lr)
m[i] = m_new | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.