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 |
|---|---|---|---|---|
femutils.py | return
the conventional ``TypeId`` value.
:para obj: a document object
"""
if hasattr(obj, "Proxy") and hasattr(obj.Proxy, "Type"):
return obj.Proxy.Type
return obj.TypeId
def is_of_type(obj, ty):
""" Compare type of *obj* with *ty* honoring Fems typesystem.
See :py:func:`type_o... | aFace = sel.SubObjects[0]
if aFace.ShapeType != "Face":
FreeCAD.Console.PrintMessage("Not a Face selected.\n")
else:
FreeCAD.Console.PrintMessage(":-)\n")
return aFace | conditional_block | |
femutils.py | various places in the Fem module.
"""
__title__ = "FEM Utilities"
__author__ = "Markus Hovorka, Bernd Hahnebach"
__url__ = "https://www.freecadweb.org"
import os
import sys
import FreeCAD
if FreeCAD.GuiUp:
import FreeCADGui
from PySide import QtGui
# *****************************************************... |
:note:
Not working correctly for most cases because this circumvents directory
caching of the solver framework. For solver use getMachine from run.py
instead.
"""
from femsolver import settings
dir_setting = settings.get_dir_setting()
if dir_setting == settings.DirSetting.TEMPORARY:
... | If user setting is set to BESIDE and the document isn't saved. | random_line_split |
femutils.py | various places in the Fem module.
"""
__title__ = "FEM Utilities"
__author__ = "Markus Hovorka, Bernd Hahnebach"
__url__ = "https://www.freecadweb.org"
import os
import sys
import FreeCAD
if FreeCAD.GuiUp:
import FreeCADGui
from PySide import QtGui
# *****************************************************... | (solver_obj):
""" Return working directory for solver honoring user settings.
:throws femtools.errors.MustSaveError:
If user setting is set to BESIDE and the document isn't saved.
:note:
Not working correctly for most cases because this circumvents directory
caching of the solver framework.... | get_pref_working_dir | identifier_name |
__init__.py | "DiskCache: disk and file backed cache." |
__all__ = [
'Cache',
'Disk',
'UnknownFileWarning',
'EmptyDirWarning',
'Timeout',
'DEFAULT_SETTINGS',
'EVICTION_POLICY',
'FanoutCache',
'Deque',
'Index',
]
try:
from .djangocache import DjangoCache # pylint: disable=wrong-import-position
__all__.append('DjangoCache')
ex... |
from .core import Cache, Disk, UnknownFileWarning, EmptyDirWarning, Timeout
from .core import DEFAULT_SETTINGS, EVICTION_POLICY
from .fanout import FanoutCache
from .persistent import Deque, Index | random_line_split |
fixup_oslogin_v1_keywords.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | )
args, ctrl_args = args[:len(kword_params)], args[len(kword_params):]
ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl))
for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS))
request_arg = cst.Arg(
value=cst.Dict([
... | lambda a: a.keyword.value not in self.CTRL_PARAMS,
kwargs | random_line_split |
fixup_oslogin_v1_keywords.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl))
for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS))
request_arg = cst.Arg(
value=cst.Dict([
cst.DictElement(
cst.SimpleString("'{}'".format(name)),
cst.Element... | try:
key = original.func.attr.value
kword_params = self.METHOD_TO_PARAMS[key]
except (AttributeError, KeyError):
# Either not a method from the API or too convoluted to be sure.
return updated
# If the existing code is valid, keyword args come after posit... | identifier_body |
fixup_oslogin_v1_keywords.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
if not output_dir.is_dir():
print(
f"output directory '{output_dir}' does not exist or is not a directory",
file=sys.stderr,
)
sys.exit(-1)
if os.listdir(output_dir):
print(
f"output directory '{output_dir}' is not empty",
file=s... | print(
f"input directory '{input_dir}' does not exist or is not a directory",
file=sys.stderr,
)
sys.exit(-1) | conditional_block |
fixup_oslogin_v1_keywords.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | (self, original: cst.Call, updated: cst.Call) -> cst.CSTNode:
try:
key = original.func.attr.value
kword_params = self.METHOD_TO_PARAMS[key]
except (AttributeError, KeyError):
# Either not a method from the API or too convoluted to be sure.
return updated
... | leave_Call | identifier_name |
InputWidgetBase.tsx | import React, { ChangeEvent, useCallback } from "react";
import { formatUserLabel } from "../userLabel";
import { getInputClass, WidgetProps } from "./types";
export default function InputWidgetBase({
type,
value,
onChange,
postprocessValue,
inputAddon,
inputType,
validate,
disabled,
placeholder,
}: ... |
onChange(value);
},
[onChange, postprocessValue]
);
const failure = validate ? validate(value) : null;
const setValidity = (el: HTMLInputElement | null) => {
el?.setCustomValidity(failure ?? "");
};
const configuredAddon = type.addon_label_i18n;
const addon = configuredAddon ? formatUse... | {
value = postprocessValue(value);
} | conditional_block |
InputWidgetBase.tsx | import React, { ChangeEvent, useCallback } from "react";
import { formatUserLabel } from "../userLabel";
import { getInputClass, WidgetProps } from "./types";
export default function InputWidgetBase({
type,
value,
onChange,
postprocessValue,
inputAddon,
inputType, | postprocessValue?: (val: string) => string;
inputAddon: JSX.Element | string;
inputType: string;
validate?: (val: string) => string | null;
}): JSX.Element {
const onChangeHandler = useCallback(
(event: ChangeEvent<HTMLInputElement>) => {
let value = event.target.value;
if (postprocessValue) {... | validate,
disabled,
placeholder,
}: WidgetProps & { | random_line_split |
TriggerConfig.tsx | import React from "react";
import {Input} from "reactstrap";
interface TriggerConfigProps {
allModuleTypes: string[];
setConfig: (value: any) => void;
configValue: string;
}
const TriggerConfig: React.FC<TriggerConfigProps> = ({
configValue = "",
setConfig,
allModuleTypes,
}) => {
const [triggerType, set... | >
<option>Manual</option>
<option>Immediate</option>
<option>Timer</option>
<option>Remote Access Code</option>
{allModuleTypes.includes("Scan Trigger") && (
<option>Scan Trigger</option>
)}
{allModuleTypes.includes("Proximity Trigger") && (
... | }} | random_line_split |
pool-test.js | var equal = require('assert').equal,
notEqual = require('assert').notEqual,
Pool = require('../lib').Pool;
describe('Pool', function () {
it('should run multiple scripts', function (finished) {
var pool = new Pool({numberOfInstances: 5});
var scriptsExited = 0;
for (var i = 0; i < 20; ++i) {
... | script.on('exit', function (err, result) {
scriptsExited++;
if (scriptsExited == 10) {
pool.kill();
equal(10, result);
finished();
}
});
script.run({testGlobal: 10});
}
});
it('should run scripts on non blocking instances', function (finis... | "
); | random_line_split |
pool-test.js | var equal = require('assert').equal,
notEqual = require('assert').notEqual,
Pool = require('../lib').Pool;
describe('Pool', function () {
it('should run multiple scripts', function (finished) {
var pool = new Pool({numberOfInstances: 5});
var scriptsExited = 0;
for (var i = 0; i < 20; ++i) {
... |
setTimeout(function () {
if (!exited) {
equal(false, true);
}
}, 3000);
});
it('should not be created if there are zero or negative amount of specified instances', function (finished) {
var pool = null;
try {
pool = new Pool({numberOfInstances: 0});
equal(false, tru... | {
var script2 = pool.createScript("\
exports.main = function() {\n\
exit(10);\n\
}\n\
"
);
script2.on('exit', function (err, result) {
scriptsExited++;
if (scriptsExited == 10) {
pool.kill();
equal(10, result);
exite... | conditional_block |
lib.rs | //! A database access library for leveldb
//!
//! Usage:
//!
//! ```rust,ignore
//! extern crate tempdir;
//! extern crate leveldb;
//!
//! use tempdir::TempDir;
//! use leveldb::database::Database;
//! use leveldb::kv::KV;
//! use leveldb::options::{Options,WriteOptions,ReadOptions};
//!
//! let tempdir = TempDir::new... |
/// The minor version
fn minor() -> isize {
unsafe { leveldb_minor_version() as isize }
}
}
| {
unsafe { leveldb_major_version() as isize }
} | identifier_body |
lib.rs | //! A database access library for leveldb
//!
//! Usage:
//!
//! ```rust,ignore
//! extern crate tempdir;
//! extern crate leveldb;
//!
//! use tempdir::TempDir;
//! use leveldb::database::Database;
//! use leveldb::kv::KV;
//! use leveldb::options::{Options,WriteOptions,ReadOptions};
//!
//! let tempdir = TempDir::new... | pub use database::batch;
pub use database::management;
pub use database::compaction;
#[allow(missing_docs)]
pub mod database;
/// Library version information
///
/// Need a recent version of leveldb to be used.
pub trait Version {
/// The major version.
fn major() -> isize {
unsafe { leveldb_major_ve... | pub use database::snapshots;
pub use database::comparator;
pub use database::kv; | random_line_split |
lib.rs | //! A database access library for leveldb
//!
//! Usage:
//!
//! ```rust,ignore
//! extern crate tempdir;
//! extern crate leveldb;
//!
//! use tempdir::TempDir;
//! use leveldb::database::Database;
//! use leveldb::kv::KV;
//! use leveldb::options::{Options,WriteOptions,ReadOptions};
//!
//! let tempdir = TempDir::new... | () -> isize {
unsafe { leveldb_minor_version() as isize }
}
}
| minor | identifier_name |
create_router_state.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, ... |
function createNode(curr: TreeNode<ActivatedRouteSnapshot>, prevState?: TreeNode<ActivatedRoute>):
TreeNode<ActivatedRoute> {
if (prevState && equalRouteSnapshots(prevState.value.snapshot, curr.value)) {
const value = prevState.value;
value._futureSnapshot = curr.value;
const children = createOrReu... | {
const root = createNode(curr._root, prevState ? prevState._root : undefined);
const queryParams = prevState ? prevState.queryParams : new BehaviorSubject(curr.queryParams);
const fragment = prevState ? prevState.fragment : new BehaviorSubject(curr.fragment);
return new RouterState(root, queryParams, fragment,... | identifier_body |
create_router_state.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license | import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot} from './router_state';
import {TreeNode} from './utils/tree';
export function createRouterState(curr: RouterStateSnapshot, prevState: RouterState): RouterState {
const root = createNode(curr._root, prevState ? prevState._root : undefin... | */
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
| random_line_split |
create_router_state.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, ... |
}
return createNode(child);
});
}
function createActivatedRoute(c: ActivatedRouteSnapshot) {
return new ActivatedRoute(
new BehaviorSubject(c.url), new BehaviorSubject(c.params), new BehaviorSubject(c.data),
c.outlet, c.component, c);
}
function equalRouteSnapshots(a: ActivatedRouteSnapshot, ... | {
return createNode(child, p);
} | conditional_block |
create_router_state.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, ... | (
curr: TreeNode<ActivatedRouteSnapshot>, prevState: TreeNode<ActivatedRoute>) {
return curr.children.map(child => {
for (const p of prevState.children) {
if (equalRouteSnapshots(p.value.snapshot, child.value)) {
return createNode(child, p);
}
}
return createNode(child);
});
}
f... | createOrReuseChildren | identifier_name |
views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, Http404
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from models import Story
from places.models import Place
from places.views import InOtherPl... | (request, place_slug, story_slug=None):
page_type = "story"
place = get_object_or_404(Place, slug=place_slug)
place_stories = place.datastories.all()
# Maybe return an alternate rendering if place_stories.count == 0?
try:
if story_slug is None:
story = place_stories[0]
... | story | identifier_name |
views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, Http404
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from models import Story
from places.models import Place
from places.views import InOtherPl... |
except (Story.DoesNotExist, IndexError):
story = None
if story:
pages = story.pages.order_by('storypage__page_number')
else:
pages = []
paginator = Paginator(pages, 1)
page_count = paginator.num_pages
page_num = request.GET.get('page_num')
try:
pgpg = pag... | story = place_stories.get(slug=story_slug) | conditional_block |
views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, Http404
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from models import Story
from places.models import Place
from places.views import InOtherPl... | paginator = Paginator(pages, 1)
page_count = paginator.num_pages
page_num = request.GET.get('page_num')
try:
pgpg = paginator.page(page_num)
except PageNotAnInteger:
pgpg = paginator.page(1)
except EmptyPage:
pgpg = paginator.page(page_count)
if not pgpg.object_lis... | page_type = "story"
place = get_object_or_404(Place, slug=place_slug)
place_stories = place.datastories.all()
# Maybe return an alternate rendering if place_stories.count == 0?
try:
if story_slug is None:
story = place_stories[0]
else:
story = place_stories.get... | identifier_body |
views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, Http404
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from models import Story
from places.models import Place
from places.views import InOtherPl... | try:
if story_slug is None:
story = place_stories[0]
else:
story = place_stories.get(slug=story_slug)
except (Story.DoesNotExist, IndexError):
story = None
if story:
pages = story.pages.order_by('storypage__page_number')
else:
pages = []
... |
# Maybe return an alternate rendering if place_stories.count == 0?
| random_line_split |
minters.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo 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 2 of the
# License, or (at your option) any later v... | })
return depid
def zenodo_reserved_record_minter(record_uuid=None, data=None):
"""Reserve a recid."""
id_ = RecordIdentifier.next()
recid = PersistentIdentifier.create(
'recid', id_, status=PIDStatus.RESERVED
)
data['recid'] = recid.pid_value
return recid
| """Mint the DEPID, and reserve the Concept RECID and RECID PIDs."""
if 'conceptrecid' not in data:
zenodo_concept_recid_minter(data=data)
recid = zenodo_reserved_record_minter(data=data)
# Create depid with same pid_value of the recid
depid = PersistentIdentifier.create(
'depid',
... | identifier_body |
minters.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo 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 2 of the
# License, or (at your option) any later v... | },
})
return depid
def zenodo_reserved_record_minter(record_uuid=None, data=None):
"""Reserve a recid."""
id_ = RecordIdentifier.next()
recid = PersistentIdentifier.create(
'recid', id_, status=PIDStatus.RESERVED
)
data['recid'] = recid.pid_value
return recid |
data.update({
'_deposit': {
'id': depid.pid_value,
'status': 'draft', | random_line_split |
minters.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo 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 2 of the
# License, or (at your option) any later v... | (record_uuid, data):
"""Mint the DEPID, and reserve the Concept RECID and RECID PIDs."""
if 'conceptrecid' not in data:
zenodo_concept_recid_minter(data=data)
recid = zenodo_reserved_record_minter(data=data)
# Create depid with same pid_value of the recid
depid = PersistentIdentifier.creat... | zenodo_deposit_minter | identifier_name |
minters.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2016 CERN.
#
# Zenodo 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 2 of the
# License, or (at your option) any later v... |
recid = zenodo_reserved_record_minter(data=data)
# Create depid with same pid_value of the recid
depid = PersistentIdentifier.create(
'depid',
str(recid.pid_value),
object_type='rec',
object_uuid=record_uuid,
status=PIDStatus.REGISTERED,
)
data.update({
... | zenodo_concept_recid_minter(data=data) | conditional_block |
05-kitchen-sink.js | var Promise = require("bluebird");
var path = require("path");
var fs = Promise.promisifyAll(require("fs"));
var should = require('should');
var testFile = path.resolve("..", "testFile.txt");
var gratuitousFileFunction = function () {
return ensureFileDoesntExist()
.then(writeData)
.then(verifyDat... | (timeEvenness) {
return fs.readFileAsync(testFile, 'utf8').then(function (data) {
data.should.equal("Hello World! " + timeEvenness +
" 0 1 2 3 4 5 6 7 8 9 10");
});
}
gratuitousFileFunction().then(function () {
console.log("Done!");
}).catch (function (err) {
console.l... | verifyData | identifier_name |
05-kitchen-sink.js | var Promise = require("bluebird");
var path = require("path");
var fs = Promise.promisifyAll(require("fs"));
var should = require('should');
var testFile = path.resolve("..", "testFile.txt");
var gratuitousFileFunction = function () {
return ensureFileDoesntExist()
.then(writeData)
.then(verifyDat... | else {
evenness = 'Time was odd, need to wait a ms...';
rightMoment = Promise.delay(1);
}
return rightMoment.then(function() {
return fs.appendFileAsync(testFile, "!");
}).then(function() {
return fs.appendFileAsync(testFile, " " + evenness);
}).thenReturn(evenness);
}... | {
evenness = 'Time was even, doing nothing!'
rightMoment = Promise.fulfilled();
} | conditional_block |
05-kitchen-sink.js | var Promise = require("bluebird");
var path = require("path");
var fs = Promise.promisifyAll(require("fs"));
var should = require('should');
var testFile = path.resolve("..", "testFile.txt");
var gratuitousFileFunction = function () {
return ensureFileDoesntExist()
.then(writeData)
.then(verifyDat... | evenness = 'Time was even, doing nothing!'
rightMoment = Promise.fulfilled();
} else {
evenness = 'Time was odd, need to wait a ms...';
rightMoment = Promise.delay(1);
}
return rightMoment.then(function() {
return fs.appendFileAsync(testFile, "!");
}).then(funct... |
function writeTime() {
var rightMoment, evenness;
if (Date.now() % 2 === 0) { | random_line_split |
05-kitchen-sink.js | var Promise = require("bluebird");
var path = require("path");
var fs = Promise.promisifyAll(require("fs"));
var should = require('should');
var testFile = path.resolve("..", "testFile.txt");
var gratuitousFileFunction = function () {
return ensureFileDoesntExist()
.then(writeData)
.then(verifyDat... |
function writeTime() {
var rightMoment, evenness;
if (Date.now() % 2 === 0) {
evenness = 'Time was even, doing nothing!'
rightMoment = Promise.fulfilled();
} else {
evenness = 'Time was odd, need to wait a ms...';
rightMoment = Promise.delay(1);
}
return rightMome... | {
return fs.writeFileAsync(testFile, "Hello World")
.then(function() {
return Promise.delay(500);
});
} | identifier_body |
write-presumbit-scheduler.js | #!/usr/bin/env node
const path = require('path');
const fs = require('fs');
const GitHubApi = require('github');
const github = new GitHubApi();
/** CONFIGURATION: change these things if you want to tweak how the runs are made. */
/** Path to the local material2. By default based on the location of this script. */
... | (prs) {
let script =
`#!/bin/bash \n\n` +
`mkdir -p ${logDir} \n\n` +
`# Be sure you have no locally modified files in your git client before running this. \n\n`;
// Generate a command for each file to be piped into the `at` command, scheduling it to run at
// a later time.
for (const pr of prs) {
... | writeScheduleScript | identifier_name |
write-presumbit-scheduler.js | #!/usr/bin/env node
const path = require('path');
const fs = require('fs');
const GitHubApi = require('github');
const github = new GitHubApi();
/** CONFIGURATION: change these things if you want to tweak how the runs are made. */
/** Path to the local material2. By default based on the location of this script. */
... |
function writeScheduleScript(prs) {
let script =
`#!/bin/bash \n\n` +
`mkdir -p ${logDir} \n\n` +
`# Be sure you have no locally modified files in your git client before running this. \n\n`;
// Generate a command for each file to be piped into the `at` command, scheduling it to run at
// a later tim... | console.error(error);
}
});
}
| random_line_split |
write-presumbit-scheduler.js | #!/usr/bin/env node
const path = require('path');
const fs = require('fs');
const GitHubApi = require('github');
const github = new GitHubApi();
/** CONFIGURATION: change these things if you want to tweak how the runs are made. */
/** Path to the local material2. By default based on the location of this script. */
... | fs.writeFileSync(path.join(localRepo, 'dist', 'schedule-presubmit.sh'), script, 'utf-8');
console.log('schedule-presubmit.sh written to dist');
console.log('Be sure to prodaccess overnight and that you have no locally modified files');
}
| {
let script =
`#!/bin/bash \n\n` +
`mkdir -p ${logDir} \n\n` +
`# Be sure you have no locally modified files in your git client before running this. \n\n`;
// Generate a command for each file to be piped into the `at` command, scheduling it to run at
// a later time.
for (const pr of prs) {
sc... | identifier_body |
write-presumbit-scheduler.js | #!/usr/bin/env node
const path = require('path');
const fs = require('fs');
const GitHubApi = require('github');
const github = new GitHubApi();
/** CONFIGURATION: change these things if you want to tweak how the runs are made. */
/** Path to the local material2. By default based on the location of this script. */
... |
});
}
function writeScheduleScript(prs) {
let script =
`#!/bin/bash \n\n` +
`mkdir -p ${logDir} \n\n` +
`# Be sure you have no locally modified files in your git client before running this. \n\n`;
// Generate a command for each file to be piped into the `at` command, scheduling it to run at
// a... | {
console.error('Fetching merge-ready PRs failed.');
console.error(error);
} | conditional_block |
extern-fail.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | do task::spawn {
let result = count(5u);
debug!("result = %?", result);
fail!();
};
}
} | fn main() {
for old_iter::repeat(10u) { | random_line_split |
extern-fail.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
for old_iter::repeat(10u) {
do task::spawn {
let result = count(5u);
debug!("result = %?", result);
fail!();
};
}
}
| {
unsafe {
task::yield();
rustrt::rust_dbg_call(cb, n)
}
} | identifier_body |
extern-fail.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
count(data - 1u) + count(data - 1u)
}
}
fn count(n: uint) -> uint {
unsafe {
task::yield();
rustrt::rust_dbg_call(cb, n)
}
}
fn main() {
for old_iter::repeat(10u) {
do task::spawn {
let result = count(5u);
debug!("result = %?", result);
... | {
data
} | conditional_block |
extern-fail.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
count(data - 1u) + count(data - 1u)
}
}
fn count(n: uint) -> uint {
unsafe {
task::yield();
rustrt::rust_dbg_call(cb, n)
}
}
fn main() {
for old_iter::repeat(10u) {
do task::spawn... | cb | identifier_name |
autosize.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
Directive,
ElementRef,
Input,
AfterViewInit,
DoCheck,
OnDestroy,
NgZone,
} from '@angular/core... | (value: number) {
this._maxRows = value;
this._setMaxHeight();
}
/** Cached height of a textarea with a single row. */
private _cachedLineHeight: number;
constructor(
private _elementRef: ElementRef,
private _platform: Platform,
private _ngZone?: NgZone) {}
// TODO(crisbeto): make the `... | maxRows | identifier_name |
autosize.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
Directive,
ElementRef,
Input,
AfterViewInit,
DoCheck,
OnDestroy,
NgZone,
} from '@angular/core... |
get minRows(): number { return this._minRows; }
/** Maximum amount of rows in the textarea. */
@Input('matAutosizeMaxRows')
get maxRows(): number { return this._maxRows; }
set maxRows(value: number) {
this._maxRows = value;
this._setMaxHeight();
}
/** Cached height of a textarea with a single r... | {
this._minRows = value;
this._setMinHeight();
} | identifier_body |
autosize.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
Directive,
ElementRef,
Input,
AfterViewInit,
DoCheck,
OnDestroy,
NgZone,
} from '@angular/core... | * Directive to automatically resize a textarea to fit its content.
*/
@Directive({
selector: `textarea[mat-autosize], textarea[matTextareaAutosize]`,
exportAs: 'matTextareaAutosize',
host: {
'class': 'mat-autosize',
// Textarea elements that have the directive applied should have a single row by default... |
/** | random_line_split |
autosize.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
Directive,
ElementRef,
Input,
AfterViewInit,
DoCheck,
OnDestroy,
NgZone,
} from '@angular/core... |
}
/** Sets the maximum height of the textarea as determined by maxRows. */
_setMaxHeight(): void {
const maxHeight = this.maxRows && this._cachedLineHeight ?
`${this.maxRows * this._cachedLineHeight}px` : null;
if (maxHeight) {
this._setTextareaStyle('maxHeight', maxHeight);
}
}
... | {
this._setTextareaStyle('minHeight', minHeight);
} | conditional_block |
karma.conf.js | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '', | require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageI... | frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'), | random_line_split |
generic-derived-type.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn f<T:Clone>(t: T) -> Pair<T> {
let x: Pair<T> = Pair {a: t.clone(), b: t};
return g::<Pair<T>>(x);
}
pub fn main() {
let b = f::<isize>(10);
println!("{}" ,b.a);
println!("{}", b.b);
assert_eq!(b.a, 10);
assert_eq!(b.b, 10);
} | a: T,
b: T
} | random_line_split |
generic-derived-type.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[derive(Clone)]
struct Pair<T> {
a: T,
b: T
}
fn f<T:Clone>(t: T) -> Pair<T> {
let x: Pair<T> = Pair {a: t.clone(), b: t};
return g::<Pair<T>>(x);
}
pub fn main() {
let b = f::<isize>(10);
println!("{}" ,b.a);
println!("{}", b.b);
assert_eq!(b.a, 10);
assert_eq!(b.b, 10);
}
| { return x; } | identifier_body |
generic-derived-type.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <X>(x: X) -> X { return x; }
#[derive(Clone)]
struct Pair<T> {
a: T,
b: T
}
fn f<T:Clone>(t: T) -> Pair<T> {
let x: Pair<T> = Pair {a: t.clone(), b: t};
return g::<Pair<T>>(x);
}
pub fn main() {
let b = f::<isize>(10);
println!("{}" ,b.a);
println!("{}", b.b);
assert_eq!(b.a, 10);
... | g | identifier_name |
3.js | var arrayOfInts = [1, 10, -5, 1, -100];
function maxProduct(arr) | } else {
if( arr[i] < almostSmallest) {
almostSmallest = arr[i]
}
}
}
}
if(smallest * almostSmallest > second * third) {
return largest * almostSmallest * smallest
}
return largest * second * third
}
maxProduct(arrayOfInts) | {
var smallest = 0;
var almostSmallest = 0;
var largest = 0;
var second = 0;
var third = 0;
for(var i = 0; i < arr.length; i++ ) {
if(arr[i] > largest){
third = second
second = largest
largest = arr[i]
} else if(arr[i] > second) {
third = second
... | identifier_body |
3.js | var arrayOfInts = [1, 10, -5, 1, -100];
function maxProduct(arr) {
var smallest = 0;
var almostSmallest = 0;
var largest = 0;
var second = 0;
var third = 0;
for(var i = 0; i < arr.length; i++ ) {
if(arr[i] > largest){
third = second
second = largest
largest = ... | if( arr[i] < almostSmallest) {
almostSmallest = arr[i]
}
}
}
}
if(smallest * almostSmallest > second * third) {
return largest * almostSmallest * smallest
}
return largest * second * third
}
maxProduct(arrayOfInts) | almostSmallest = smallest
smallest = arr[i];
} else { | random_line_split |
3.js | var arrayOfInts = [1, 10, -5, 1, -100];
function | (arr) {
var smallest = 0;
var almostSmallest = 0;
var largest = 0;
var second = 0;
var third = 0;
for(var i = 0; i < arr.length; i++ ) {
if(arr[i] > largest){
third = second
second = largest
largest = arr[i]
} else if(arr[i] > second) {
third = second... | maxProduct | identifier_name |
increase_in_window.rs | use crate::client::types::ClientTypes;
use crate::common::increase_in_window_common::IncreaseInWindowCommon;
use crate::server::types::ServerTypes;
enum Impl {
Client(IncreaseInWindowCommon<ClientTypes>),
Server(IncreaseInWindowCommon<ServerTypes>),
}
/// Utility to tell the peer that it can send more data.
p... |
}
| {
match &mut self.0 {
Impl::Client(c) => c.increase_window_auto_above(above),
Impl::Server(c) => c.increase_window_auto_above(above),
}
} | identifier_body |
increase_in_window.rs | use crate::client::types::ClientTypes;
use crate::common::increase_in_window_common::IncreaseInWindowCommon;
use crate::server::types::ServerTypes;
enum Impl {
Client(IncreaseInWindowCommon<ClientTypes>),
Server(IncreaseInWindowCommon<ServerTypes>),
}
/// Utility to tell the peer that it can send more data.
p... | (c: IncreaseInWindowCommon<ClientTypes>) -> Self {
IncreaseInWindow(Impl::Client(c))
}
}
impl From<IncreaseInWindowCommon<ServerTypes>> for IncreaseInWindow {
fn from(c: IncreaseInWindowCommon<ServerTypes>) -> Self {
IncreaseInWindow(Impl::Server(c))
}
}
impl IncreaseInWindow {
/// Cur... | from | identifier_name |
increase_in_window.rs | use crate::client::types::ClientTypes;
use crate::common::increase_in_window_common::IncreaseInWindowCommon;
use crate::server::types::ServerTypes;
enum Impl {
Client(IncreaseInWindowCommon<ClientTypes>),
Server(IncreaseInWindowCommon<ServerTypes>),
}
/// Utility to tell the peer that it can send more data.
p... | // TODO: drop this operation.
pub fn increase_window_auto(&mut self) -> crate::Result<()> {
match &mut self.0 {
Impl::Client(c) => c.increase_window_auto(),
Impl::Server(c) => c.increase_window_auto(),
}
}
/// Auto-increase in window above specified limit.
//... | /// Auto-increase in window. | random_line_split |
models.py | return r['F'], r['M']
def __unicode__(self):
if self.type == 'plenum':
return "%s" % ugettext('Plenum')
else:
return "%s" % self.name
@models.permalink
def get_absolute_url(self):
if self.type == 'plenum':
return 'plenum', []
else... | qs = qs.filter(time__lte=kwargs['to_date'] + timedelta(days=1))
if kwargs.get('from_date'):
qs = qs.filter(time__gte=kwargs['from_date'])
return qs.select_related('committee')
class CommitteesMeetingsOnlyManager(CommitteeMeetingManager):
def get_queryset(self):
return super(... | qs = qs.exclude(tagged_items__isnull=False)
elif kwargs['tagged'] != ['all']:
qs = qs.filter(tagged_items__tag__name__in=kwargs['tagged'])
if kwargs.get('to_date'):
| conditional_block |
models.py | return r['F'], r['M']
def __unicode__(self):
if self.type == 'plenum':
return "%s" % ugettext('Plenum')
else:
return "%s" % self.name
@models.permalink
def get_absolute_url(self):
|
@property
def annotations(self):
protocol_part_tn = ProtocolPart._meta.db_table
meeting_tn = CommitteeMeeting._meta.db_table
committee_tn = Committee._meta.db_table
annotation_tn = Annotation._meta.db_table
protocol_part_ct = ContentType.objects.get_for_model(ProtocolPa... | if self.type == 'plenum':
return 'plenum', []
else:
return 'committee-detail', [str(self.id)] | identifier_body |
models.py | knesset_id = models.IntegerField(null=True, blank=True)
knesset_type_id = models.IntegerField(null=True, blank=True)
knesset_parent_id = models.IntegerField(null=True, blank=True)
# Deprecated? In use? does not look
last_scrape_time = models.DateTimeField(null=True, blank=True)
name_eng = models... | # Deprecated? In use? does not look in use
protocol_not_published = models.BooleanField(default=False) | random_line_split | |
models.py | return r['F'], r['M']
def __unicode__(self):
if self.type == 'plenum':
return "%s" % ugettext('Plenum')
else:
return "%s" % self.name
@models.permalink
def get_absolute_url(self):
if self.type == 'plenum':
return 'plenum', []
else... | (self):
protocol_part_tn = ProtocolPart._meta.db_table
meeting_tn = CommitteeMeeting._meta.db_table
committee_tn = Committee._meta.db_table
annotation_tn = Annotation._meta.db_table
protocol_part_ct = ContentType.objects.get_for_model(ProtocolPart)
ret = Annotation.object... | annotations | identifier_name |
app.component.ts | import { Component, ViewEncapsulation, Inject, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute, PRIMARY_OUTLET } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { Subscription } from 'rxjs/Subscription';
import { isBrowser } from 'angular2-unive... | () {
this.sub = this.router.events
.filter(event => event instanceof NavigationEnd)
.map(() => this.activatedRoute)
.map(route => {
while (route.firstChild) route = route.firstChild;
return route;
})
.filter(route => ro... | changeTitleOnNavigation | identifier_name |
app.component.ts | import { Component, ViewEncapsulation, Inject, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute, PRIMARY_OUTLET } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { Subscription } from 'rxjs/Subscription';
import { isBrowser } from 'angular2-unive... |
ngOnDestroy() {
// Subscription clean-up
this.sub.unsubscribe();
this.routerSubscription.unsubscribe();
}
private changeTitleOnNavigation () {
this.sub = this.router.events
.filter(event => event instanceof NavigationEnd)
.map(() => this.activat... | {
this.changeTitleOnNavigation();
this.routerSubscription = this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
if (isBrowser) {
document.body.scrollTop = 0;
}
});
if (this.tokenService.hasValid... | identifier_body |
app.component.ts | import { Component, ViewEncapsulation, Inject, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute, PRIMARY_OUTLET } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { Subscription } from 'rxjs/Subscription';
import { isBrowser } from 'angular2-unive... | @Component({
selector: 'app-root',
template: require('./app.component.html'),
styles: [require('./app.component.css')],
encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit, OnDestroy {
private defaultPageTitle: string = 'Hidden Sound';
private sub: Subscription;... | import { PageScrollConfig } from 'ng2-page-scroll';
| random_line_split |
index.d.ts | /*
* @license Apache-2.0
* | * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES ... | * Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); | random_line_split |
web.worker.d.ts | /* eslint-disable @typescript-eslint/no-explicit-any */
export interface Glue42NotificationClickHandler {
handler: (event: Event, isPlatformOpened: boolean) => Promise<void>;
action: string;
}
export interface WebWorkerConfig {
platform?: {
url: string;
openIfMissing?: boolean;
};
n... |
declare const WebWorkerFactory: Glue42WebWorkerFactoryFunction;
export const openCorePlatform: OpenCorePlatform;
export const raiseGlueNotification: RaiseGlueNotification;
export default WebWorkerFactory; | random_line_split | |
vuex-mockstorage-prevdata.spec.ts | /**
* Created by championswimmer on 20/07/17.
*/
import { assert, expect, should } from 'chai'
import Vue from 'vue'
import { Store } from 'vuex'
import Vuex from 'vuex'
import VuexPersistence, { MockStorage } from '..'
Vue.use(Vuex)
// @ts-ignore
const mockStorage = new MockStorage()
mockStorage.setItem('vuex', JSO... | (state) {
state.cat.mews++
}
},
plugins: [vuexPersist.plugin]
})
const getSavedStore = () => JSON.parse(mockStorage.getItem('vuex') || '')
describe('Storage: MockStorage, Test: reducer, filter, Existing Data: TRUE', () => {
it('should persist reduced state', () => {
store.commit('dogBark')
expe... | catMew | identifier_name |
vuex-mockstorage-prevdata.spec.ts | import Vue from 'vue'
import { Store } from 'vuex'
import Vuex from 'vuex'
import VuexPersistence, { MockStorage } from '..'
Vue.use(Vuex)
// @ts-ignore
const mockStorage = new MockStorage()
mockStorage.setItem('vuex', JSON.stringify({
dog: {
barks: 2
}
}))
const vuexPersist = new VuexPersistence<any>({
stor... | /**
* Created by championswimmer on 20/07/17.
*/
import { assert, expect, should } from 'chai' | random_line_split | |
vuex-mockstorage-prevdata.spec.ts | /**
* Created by championswimmer on 20/07/17.
*/
import { assert, expect, should } from 'chai'
import Vue from 'vue'
import { Store } from 'vuex'
import Vuex from 'vuex'
import VuexPersistence, { MockStorage } from '..'
Vue.use(Vuex)
// @ts-ignore
const mockStorage = new MockStorage()
mockStorage.setItem('vuex', JSO... |
},
plugins: [vuexPersist.plugin]
})
const getSavedStore = () => JSON.parse(mockStorage.getItem('vuex') || '')
describe('Storage: MockStorage, Test: reducer, filter, Existing Data: TRUE', () => {
it('should persist reduced state', () => {
store.commit('dogBark')
expect(getSavedStore().dog.barks).to.equal... | {
state.cat.mews++
} | identifier_body |
rename.py | #! /usr/bin/env python
import os
import glob
def addSubFold(file_path):
file_name = os.path.basename(file_path)
file_dir = os.path.dirname(file_path)
sub_fold = file_dir + "/" + file_name[0:5]
if not os.path.exists(sub_fold):
os.makedirs(sub_fold)
return sub_fold + "/" + file_name
def cha... | def reName(dir_name,ext = "*.obj"):
files = glob.glob(dir_name+ext)
for old_name in files:
new_name = addSubFold(changeName(old_name))
print new_name
if new_name != old_name:
os.system("mv " + old_name + " " + new_name)
# reName("./data/dino/tempt_cubes_test/obj/")
# reName(... | elif old_name[-7] == '_':
new_name = old_name[0:-6] + "0" + old_name[-6:len(old_name)]
return new_name
| random_line_split |
rename.py | #! /usr/bin/env python
import os
import glob
def addSubFold(file_path):
file_name = os.path.basename(file_path)
file_dir = os.path.dirname(file_path)
sub_fold = file_dir + "/" + file_name[0:5]
if not os.path.exists(sub_fold):
os.makedirs(sub_fold)
return sub_fold + "/" + file_name
def cha... | (dir_name,ext = "*.obj"):
files = glob.glob(dir_name+ext)
for old_name in files:
new_name = addSubFold(changeName(old_name))
print new_name
if new_name != old_name:
os.system("mv " + old_name + " " + new_name)
# reName("./data/dino/tempt_cubes_test/obj/")
# reName("./data/dr... | reName | identifier_name |
rename.py | #! /usr/bin/env python
import os
import glob
def addSubFold(file_path):
file_name = os.path.basename(file_path)
file_dir = os.path.dirname(file_path)
sub_fold = file_dir + "/" + file_name[0:5]
if not os.path.exists(sub_fold):
os.makedirs(sub_fold)
return sub_fold + "/" + file_name
def cha... |
def reName(dir_name,ext = "*.obj"):
files = glob.glob(dir_name+ext)
for old_name in files:
new_name = addSubFold(changeName(old_name))
print new_name
if new_name != old_name:
os.system("mv " + old_name + " " + new_name)
# reName("./data/dino/tempt_cubes_test/obj/")
# reNam... | new_name = old_name
if old_name[-6] == '_':
new_name = old_name[0:-5] + "00" + old_name[-5:len(old_name)]
elif old_name[-7] == '_':
new_name = old_name[0:-6] + "0" + old_name[-6:len(old_name)]
return new_name | identifier_body |
rename.py | #! /usr/bin/env python
import os
import glob
def addSubFold(file_path):
file_name = os.path.basename(file_path)
file_dir = os.path.dirname(file_path)
sub_fold = file_dir + "/" + file_name[0:5]
if not os.path.exists(sub_fold):
os.makedirs(sub_fold)
return sub_fold + "/" + file_name
def cha... |
return new_name
def reName(dir_name,ext = "*.obj"):
files = glob.glob(dir_name+ext)
for old_name in files:
new_name = addSubFold(changeName(old_name))
print new_name
if new_name != old_name:
os.system("mv " + old_name + " " + new_name)
# reName("./data/dino/tempt_cubes... | new_name = old_name[0:-6] + "0" + old_name[-6:len(old_name)] | conditional_block |
search.reducer.ts | import { createFeatureSelector, createSelector } from '@ngrx/store';
import { Direction, Item, Page, SearchItemPageRequest } from '../shared/entity';
import { SearchAction, SearchActions } from './search.actions';
export interface SearchState {
request: SearchItemPageRequest;
results: Page<Item>;
}
const initialSta... | (state = initialState, action: SearchActions): SearchState {
switch (action.type) {
case SearchAction.SEARCH: {
return { ...state, request: action.pageRequest };
}
case SearchAction.SEARCH_SUCCESS: {
return { ...state, results: action.results };
}
default: {
return state;
}
}
}
const moduleSel... | search | identifier_name |
search.reducer.ts | import { createFeatureSelector, createSelector } from '@ngrx/store';
import { Direction, Item, Page, SearchItemPageRequest } from '../shared/entity';
import { SearchAction, SearchActions } from './search.actions';
export interface SearchState {
request: SearchItemPageRequest;
results: Page<Item>;
}
const initialSta... |
const moduleSelector = createFeatureSelector<SearchState>('search');
export const searchResults = createSelector(moduleSelector, (s: SearchState) => s.results);
export const searchRequest = createSelector(moduleSelector, (s: SearchState) => s.request);
| {
switch (action.type) {
case SearchAction.SEARCH: {
return { ...state, request: action.pageRequest };
}
case SearchAction.SEARCH_SUCCESS: {
return { ...state, results: action.results };
}
default: {
return state;
}
}
} | identifier_body |
search.reducer.ts | import { createFeatureSelector, createSelector } from '@ngrx/store';
import { Direction, Item, Page, SearchItemPageRequest } from '../shared/entity';
import { SearchAction, SearchActions } from './search.actions';
export interface SearchState {
request: SearchItemPageRequest;
results: Page<Item>;
}
const initialSta... | const moduleSelector = createFeatureSelector<SearchState>('search');
export const searchResults = createSelector(moduleSelector, (s: SearchState) => s.results);
export const searchRequest = createSelector(moduleSelector, (s: SearchState) => s.request); | random_line_split | |
iv.rs | use Error;
use header::tlv::Tlv;
use std::io::Read;
const IV_LENGTH: usize = 16;
pub fn read_tlv(reader: &mut Read, length: u16) -> Result<Tlv, Error> |
#[cfg(test)]
mod test {
use super::*;
use Error;
use header::tlv::Tlv;
#[test]
fn should_read_tlv() {
let bytes = [1; 16];
let result = read_tlv(&mut &bytes[..], 16);
match result {
Ok(Tlv::EncryptionIv(iv)) => assert_eq!(iv, bytes),
_ => panic!("... | {
try!(super::check_tlv_length(length, IV_LENGTH as u16));
let iv = try!(read_array!(reader, IV_LENGTH));
Ok(Tlv::EncryptionIv(iv))
} | identifier_body |
iv.rs | use Error;
use header::tlv::Tlv;
use std::io::Read;
const IV_LENGTH: usize = 16;
pub fn read_tlv(reader: &mut Read, length: u16) -> Result<Tlv, Error> {
try!(super::check_tlv_length(length, IV_LENGTH as u16));
let iv = try!(read_array!(reader, IV_LENGTH));
Ok(Tlv::EncryptionIv(iv))
}
#[cfg(test)]
mod ... | _ => panic!("Invalid result: {:#?}", result),
}
}
#[test]
fn should_return_error_if_wrong_length() {
let bytes = vec![];
let result = read_tlv(&mut &bytes[..], 15);
match result {
Err(Error::InvalidTlvSize) => (),
_ => panic!("Invalid res... |
match result {
Ok(Tlv::EncryptionIv(iv)) => assert_eq!(iv, bytes), | random_line_split |
iv.rs | use Error;
use header::tlv::Tlv;
use std::io::Read;
const IV_LENGTH: usize = 16;
pub fn read_tlv(reader: &mut Read, length: u16) -> Result<Tlv, Error> {
try!(super::check_tlv_length(length, IV_LENGTH as u16));
let iv = try!(read_array!(reader, IV_LENGTH));
Ok(Tlv::EncryptionIv(iv))
}
#[cfg(test)]
mod ... | () {
let bytes = [1; 16];
let result = read_tlv(&mut &bytes[..], 16);
match result {
Ok(Tlv::EncryptionIv(iv)) => assert_eq!(iv, bytes),
_ => panic!("Invalid result: {:#?}", result),
}
}
#[test]
fn should_return_error_if_wrong_length() {
let ... | should_read_tlv | identifier_name |
fiatToUnit.ts | import { Pipe, PipeTransform } from '@angular/core';
import { ConfigProvider } from '../providers/config/config';
import { RateProvider } from '../providers/rate/rate';
import { TxFormatProvider } from '../providers/tx-format/tx-format';
@Pipe({
name: 'fiatToUnit',
pure: false
})
export class FiatToUnitPipe implem... |
}
| {
alternative = alternative
? alternative
: this.walletSettings.alternativeIsoCode;
let amount_ = this.rateProvider.fromFiat(amount, alternative, coin);
return this.txFormatProvider.formatAmountStr(coin, amount_, true);
} | identifier_body |
fiatToUnit.ts | import { Pipe, PipeTransform } from '@angular/core';
import { ConfigProvider } from '../providers/config/config';
import { RateProvider } from '../providers/rate/rate';
import { TxFormatProvider } from '../providers/tx-format/tx-format';
@Pipe({
name: 'fiatToUnit',
pure: false
})
export class FiatToUnitPipe implem... | (amount: number, coin: string, alternative?: string) {
alternative = alternative
? alternative
: this.walletSettings.alternativeIsoCode;
let amount_ = this.rateProvider.fromFiat(amount, alternative, coin);
return this.txFormatProvider.formatAmountStr(coin, amount_, true);
}
}
| transform | identifier_name |
fiatToUnit.ts | import { Pipe, PipeTransform } from '@angular/core';
import { ConfigProvider } from '../providers/config/config';
import { RateProvider } from '../providers/rate/rate';
import { TxFormatProvider } from '../providers/tx-format/tx-format';
@Pipe({
name: 'fiatToUnit',
pure: false
})
export class FiatToUnitPipe implem... | let amount_ = this.rateProvider.fromFiat(amount, alternative, coin);
return this.txFormatProvider.formatAmountStr(coin, amount_, true);
}
} | }
transform(amount: number, coin: string, alternative?: string) {
alternative = alternative
? alternative
: this.walletSettings.alternativeIsoCode; | random_line_split |
t_BarPlot_std.py | #! /usr/bin/env python
from openturns import *
from math import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
try:
# Instanciate one distribution object
dim = 1
meanPoint = NumericalPoint(dim, 1.0)
meanPoint[0] = 0.5
sigma = NumericalPoint(dim, 1.0)
sigma[0] = 2.0
R = CorrelationMatrix(dim)... |
# Create an empty graph
myGraph = Graph("Some barplots", "y", "frequency", True, "topleft")
# Create the first barplot
myBarPlot1 = BarPlot(data1, min1, "blue", "shaded", "dashed", "histogram1")
# Then, draw it
myGraph.add(myBarPlot1)
myGraph.draw("Graph_BarPlot_a_OT", 640, 480)
# C... | index = long(floor((sample1[i, 0] - min1) / (max1 - min1) * nBars))
data1[index, 1] += 1
index = long(floor((sample2[i, 0] - min2) / (max2 - min2) * nBars))
data2[index, 1] += 1 | conditional_block |
t_BarPlot_std.py | #! /usr/bin/env python
from openturns import *
from math import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
try:
# Instanciate one distribution object
dim = 1
meanPoint = NumericalPoint(dim, 1.0)
meanPoint[0] = 0.5
sigma = NumericalPoint(dim, 1.0)
sigma[0] = 2.0
R = CorrelationMatrix(dim)... | # Then, draw it
myGraph.add(myBarPlot1)
myGraph.draw("Graph_BarPlot_a_OT", 640, 480)
# Check that the correct files have been generated by computing their
# checksum
# Create the second barplot
myBarPlot2 = BarPlot(data2, min2, "red", "solid", "solid", "histogram2")
# Add it to the gr... | myGraph = Graph("Some barplots", "y", "frequency", True, "topleft")
# Create the first barplot
myBarPlot1 = BarPlot(data1, min1, "blue", "shaded", "dashed", "histogram1")
| random_line_split |
FilterComponent.js | .query.getOption('page') !== 0) {
this.query.previousPage(successCallback);
}
break;
case 'next':
this.query.nextPage(successCallback);
break;
default:
this.query.setOption('page', page);
this.que... | random_line_split | ||
FilterComponent.js | written to the parameter.
* @return {this}
*/
processChange: function (value) {
this._value = value;
this.dashboard.processChange(this.name);
return this;
}
};
/*
* Interface mixin for the configuration
*/
var IConfiguration = /** @lends cdf.components.filter.FilterComp... | var successCallback = _.bind(function (data) {
this.inputDataHandler.updateModel(data);
this.model.setBusy(false);
deferred.resolve(data);
return data;
}, this);
var errorCallback = _.bind(function () {
this.model.setBusy(false);
deferr... |
deferred.resolve({});
return deferred;
}
| conditional_block |
string.js |
/** related to: String#gsub
* String#scan(pattern, iterator) -> String
*
* Allows iterating over every occurrence of the given pattern (which can be a
* string or a regular expression).
* Returns the original string.
*
* Internally just calls [[String#gsub]] passing it `pattern` and `ite... | {
replacement = prepareReplacement(replacement);
count = Object.isUndefined(count) ? 1 : count;
return this.gsub(pattern, function(match) {
if (--count < 0) return match[0];
return replacement(match);
});
} | identifier_body | |
string.js | Array
*
* Splits the string character-by-character and returns an array with
* the result.
*
* ##### Examples
*
* 'a'.toArray();
* // -> ['a']
*
* 'hello world!'.toArray();
* // -> ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']
**/
funct... | * externals sources to prevent XSS attacks.
*
* As [[String#evalJSON]] internally calls [[String#unfilterJSON]], optional | random_line_split | |
string.js | A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/-/g, '_')
.toLowerCase();
}
/**
* String#dasherize() -> String
*
* Replaces every instance of the underscore character `"_"` by a dash `"-"`.
*
* ##### Example
*
* ... | blank | identifier_name | |
string.js | normal form.
*
* ##### Examples
*
* 'x > 10'.unescapeHTML()
* // -> 'x > 10'
*
* '<h1>Pride & Prejudice</h1>;'.unescapeHTML()
* // -> '<h1>Pride & Prejudice</h1>'
**/
function unescapeHTML() {
// Warning: In 1.7 String#unescapeHTML will no longer ca... | {
return String.specialChar[character];
} | conditional_block | |
util.py | # Copyright 2010-2021 Kurt McKee <contactme@kurtmckee.org>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistrib... |
def __hash__(self):
# This is incorrect behavior -- dictionaries shouldn't be hashable.
# Note to self: remove this behavior in the future.
return id(self)
| try:
return self.__getitem__(key)
except KeyError:
raise AttributeError("object has no attribute '%s'" % key) | identifier_body |
util.py | # Copyright 2010-2021 Kurt McKee <contactme@kurtmckee.org>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistrib... | def __setitem__(self, key, value):
key = self.keymap.get(key, key)
if isinstance(key, list):
key = key[0]
return dict.__setitem__(self, key, value)
def setdefault(self, k, default):
if k not in self:
self[k] = default
return default
re... | try:
return self.__getitem__(key)
except KeyError:
return default
| random_line_split |
util.py | # Copyright 2010-2021 Kurt McKee <contactme@kurtmckee.org>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistrib... | (self, k, default):
if k not in self:
self[k] = default
return default
return self[k]
def __getattr__(self, key):
# __getattribute__() is called first; this will be called
# only if an attribute was not already found
try:
return self.__get... | setdefault | identifier_name |
util.py | # Copyright 2010-2021 Kurt McKee <contactme@kurtmckee.org>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistrib... |
elif key == 'updated':
# Temporarily help developers out by keeping the old
# broken behavior that was reported in issue 310.
# This fix was proposed in issue 328.
if (
not dict.__contains__(self, 'updated')
and dict.__cont... | if link['rel'] == 'license' and 'href' in link:
return link['href'] | conditional_block |
hooks.py | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... |
def get(name):
return hooks.get(name, [])
def registered(name):
""" Returns True if at least one function is registered for the given hook """
return hooks.get(name, []) != []
def call(name, *args):
n = 0
for hk in hooks.get(name, []):
n += 1
try:
hk(*args)
exc... | global hooks
hooks = {}
def register(name, func):
hooks.setdefault(name, []).append(func) | random_line_split |
hooks.py | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... |
raise
| import traceback, StringIO
txt = StringIO.StringIO()
t, v, tb = sys.exc_info()
traceback.print_exception(t, v, tb, None, txt)
html.show_error("<h1>" + _("Error executing hook") + " %s #%d: %s</h1>"
"<pre>%s</pre>" % (name, n... | conditional_block |
hooks.py | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... |
def get(name):
return hooks.get(name, [])
def registered(name):
""" Returns True if at least one function is registered for the given hook """
return hooks.get(name, []) != []
def call(name, *args):
n = 0
for hk in hooks.get(name, []):
n += 1
try:
hk(*args)
ex... | hooks.setdefault(name, []).append(func) | identifier_body |
hooks.py | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... | (name):
""" Returns True if at least one function is registered for the given hook """
return hooks.get(name, []) != []
def call(name, *args):
n = 0
for hk in hooks.get(name, []):
n += 1
try:
hk(*args)
except Exception, e:
if config.debug:
... | registered | identifier_name |
report.py | total_bp2
self.total_bp += total_bp2
def collect(self, adapters_pair, time, modifiers, modifiers2, writers):
self.time = max(time, 0.01)
self.too_short = None
self.too_long = None
self.written = 0
self.written_bp = [0, 0]
self.too_many_n = None
# Collect statistics from writers/filters
for w in wr... | def redirect_standard_output(file):
if file is None:
yield
return
old_stdout = sys.stdout
sys.stdout = file
yield
sys.stdout = old_stdout
def print_report(stats, adapters_pair):
"""Print report to standard output."""
if stats.n == 0:
print("No reads processed! Either your input file is empty or you used ... |
@contextmanager | random_line_split |
report.py | total_bp2
self.total_bp += total_bp2
def collect(self, adapters_pair, time, modifiers, modifiers2, writers):
self.time = max(time, 0.01)
self.too_short = None
self.too_long = None
self.written = 0
self.written_bp = [0, 0]
self.too_many_n = None
# Collect statistics from writers/filters
for w in wr... |
def print_adjacent_bases(bases, sequence):
"""
Print a summary of the bases preceding removed adapter sequences.
Print a warning if one of the bases is overrepresented and there are
at least 20 preceding bases available.
Return whether a warning was printed.
"""
total = sum(bases.values())
if total == 0:
... | """
Print a histogram. Also, print the no. of reads expected to be
trimmed by chance (assuming a uniform distribution of nucleotides in the reads).
d -- a dictionary mapping lengths of trimmed sequences to their respective frequency
adapter_length -- adapter length
n -- total no. of reads.
"""
h = []
for length... | identifier_body |
report.py | ritten_bp[0] + w.written_bp[0], self.written_bp[1] + w.written_bp[1]
elif isinstance(w.filter, TooShortReadFilter):
self.too_short = w.filtered
elif isinstance(w.filter, TooLongReadFilter):
self.too_long = w.filtered
elif isinstance(w.filter, NContentFilter):
self.too_many_n = w.filtered
assert s... | extra = '' | conditional_block | |
report.py | :
def __init__(self, n, total_bp1, total_bp2):
"""
n -- total number of reads
total_bp1 -- number of bases in first reads
total_bp2 -- number of bases in second reads (set to None for single-end data)
"""
self.n = n
self.total_bp = total_bp1
self.total_bp1 = total_bp1
if total_bp2 is None:
self.pa... | Statistics | identifier_name | |
sync.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals, print_function
"""
Sync's doctype and docfields from txt files to database
perms will get synced only if none exist
"""
import frappe
import os
from frappe.modules.import_file ... | #print module_name + ' | ' + doctype + ' | ' + name
frappe.db.commit()
# show progress bar
update_progress_bar("Updating DocTypes for {0}".format(app_name), i, l)
print()
def get_doc_files(files, start_path, force=0, sync_everything = False, verbose=False):
"""walk and sync all doctypes and pages""... | files = []
if app_name == "frappe":
# these need to go first at time of install
for d in (("core", "docfield"), ("core", "docperm"), ("core", "has_role"), ("core", "doctype"),
("core", "user"), ("core", "role"), ("custom", "custom_field"),
("custom", "property_setter"), ("website", "web_form"),
("website... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.