file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
fileSearch.ts | /*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law... |
if (appSettings.enableFilesystemIndex) {
indexFiles();
}
return requestHandler;
}
| {
appSettings.enableFilesystemIndex = true;
} | conditional_block |
fileSearch.ts | /*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law... | response.writeHead(200, { 'Content-Type': 'application/json' });
if (pattern !== undefined) {
let decodedPattern = decodeURIComponent(pattern);
results = filter(decodedPattern, fileIndex);
}
response.write(JSON.stringify({
files: results.slice(0, clientResultSize),
fullResultSize: results.lengt... | function requestHandler(request: http.ServerRequest, response: http.ServerResponse): void {
const parsedUrl = url.parse(request.url, true);
const pattern = parsedUrl.query['pattern'];
let results: string[] = [];
| random_line_split |
na_elementsw_node.py | #!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or
# https://www.gnu.org/licenses/gpl-3.0.txt)
'''
Element Software Node Operation
'''
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | main() | conditional_block | |
na_elementsw_node.py | #!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or
# https://www.gnu.org/licenses/gpl-3.0.txt)
'''
Element Software Node Operation
'''
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | node_id: 13
- name: Add node from pending to active cluster using node IP
tags:
- elementsw_add_node_ip
na_elementsw_node:
hostname: "{{ elementsw_hostname }}"
username: "{{ elementsw_username }}"
password: "{{ elementsw_password }}"
state: present
node_id: 1... | hostname: "{{ elementsw_hostname }}"
username: "{{ elementsw_username }}"
password: "{{ elementsw_password }}"
state: absent | random_line_split |
na_elementsw_node.py | #!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or
# https://www.gnu.org/licenses/gpl-3.0.txt)
'''
Element Software Node Operation
'''
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
def main():
"""
Main function
"""
na_elementsw_node = ElementSWNode()
na_elementsw_node.apply()
if __name__ == '__main__':
main()
| """
Element SW Storage Node operations
"""
def __init__(self):
self.argument_spec = netapp_utils.ontap_sf_host_argument_spec()
self.argument_spec.update(dict(
state=dict(required=False, choices=['present', 'absent'], default='present'),
node_id=dict(required=True, ty... | identifier_body |
na_elementsw_node.py | #!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or
# https://www.gnu.org/licenses/gpl-3.0.txt)
'''
Element Software Node Operation
'''
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | (self, node_id=None):
"""
Check if node has active drives attached to cluster
:description: Validate if node have active drives in cluster
:return: True or False
:rtype: bool
"""
if node_id is not None:
cluster_drives = self.sfe.list_d... | check_node_has_active_drives | identifier_name |
driversPage.js | $(document).ready(function() {
$.validator.setDefaults({
highlight: function (element) {
$(element)
.closest('.input-group')
.addClass('has-danger')
.removeClass('has-success')
},
unhighlight: function (element) {
$(elem... | required: true,
pattern: "^([А-Я]{2} \\d{6})|(\\d{10})$"
},
"phone-number": {
required: true,
pattern: "^(\\+?\\d{12})|(\\d{10})$"
},
"age": {
required: true,
pattern: "^(1[89]... | random_line_split | |
work_mode.rs | use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, // generate widgets etc.
Sys, // generate -sys with FFI
Doc, // generate documentation file
DisplayNotBound, // Show not bound types
}
impl WorkMode {
pub fn is_normal(s... | "sys" => Ok(WorkMode::Sys),
"doc" => Ok(WorkMode::Doc),
"not_bound" => Ok(WorkMode::DisplayNotBound),
_ => Err(format!("Wrong work mode '{}'", s)),
}
}
} | "normal" => Ok(WorkMode::Normal), | random_line_split |
work_mode.rs | use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, // generate widgets etc.
Sys, // generate -sys with FFI
Doc, // generate documentation file
DisplayNotBound, // Show not bound types
}
impl WorkMode {
pub fn is_normal(s... |
}
| {
match s {
"normal" => Ok(WorkMode::Normal),
"sys" => Ok(WorkMode::Sys),
"doc" => Ok(WorkMode::Doc),
"not_bound" => Ok(WorkMode::DisplayNotBound),
_ => Err(format!("Wrong work mode '{}'", s)),
}
} | identifier_body |
work_mode.rs | use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkMode {
Normal, // generate widgets etc.
Sys, // generate -sys with FFI
Doc, // generate documentation file
DisplayNotBound, // Show not bound types
}
impl WorkMode {
pub fn is_normal(s... | (s: &str) -> Result<Self, Self::Err> {
match s {
"normal" => Ok(WorkMode::Normal),
"sys" => Ok(WorkMode::Sys),
"doc" => Ok(WorkMode::Doc),
"not_bound" => Ok(WorkMode::DisplayNotBound),
_ => Err(format!("Wrong work mode '{}'", s)),
}
}
}
| from_str | identifier_name |
calculus.py | import numpy as np
import json
import scipy as sci
def get_decimal_delta(data, index,decimals):
'''
This function calculates the difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:param decimals: Number of decimal places t... |
def get_average_delta(data, index):
'''
This function calculates the average difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:return: average between all values in the column
'''
deltas = get_decimal_delta(data... | '''
This function calculates the difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:param decimals: Number of decimal places to round to (default: 0).
If decimals is negative, it specifies the number of positions to the lef... | identifier_body |
calculus.py | import numpy as np
import json
import scipy as sci
def get_decimal_delta(data, index,decimals):
'''
This function calculates the difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:param decimals: Number of decimal places t... | def get_average_delta(data, index):
'''
This function calculates the average difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:return: average between all values in the column
'''
deltas = get_decimal_delta(data, i... | realsol = np.array(realsol)
return realsol
| random_line_split |
calculus.py | import numpy as np
import json
import scipy as sci
def get_decimal_delta(data, index,decimals):
'''
This function calculates the difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:param decimals: Number of decimal places t... | (data, index):
'''
This function calculates the average difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:return: average between all values in the column
'''
deltas = get_decimal_delta(data, index, 7)
return s... | get_average_delta | identifier_name |
calculus.py | import numpy as np
import json
import scipy as sci
def get_decimal_delta(data, index,decimals):
'''
This function calculates the difference between the values of one column
:param data: the data array
:param time_index: the index of the column of interest
:param decimals: Number of decimal places t... |
i = 0
realsol = []
while i < len(sol):
intervall = sol[i] - sol[i - 1]
if i == 0:
realsol.append(np.float_(0))
realsol.append(intervall)
i += 1
realsol= np.array(realsol)
return realsol
| res = sci.trapz(data[0:i, index_y], data[0:i, index_x])
res = np.float_(res)
sol.append(res)
i += 1 | conditional_block |
create_attn.py | """ Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import Gl... |
elif attn_type == 'bat':
module_cls = BatNonLocalAttn
# Woops!
else:
assert False, "Invalid attn module (%s)" % attn_type
elif isinstance(attn_type, bool):
if attn_type:
module_cls = SEModule
else:
... | module_cls = NonLocalAttn | conditional_block |
create_attn.py | """ Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import Gl... |
def create_attn(attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
| if isinstance(attn_type, torch.nn.Module):
return attn_type
module_cls = None
if attn_type is not None:
if isinstance(attn_type, str):
attn_type = attn_type.lower()
# Lightweight attention modules (channel and/or coarse spatial).
# Typically added to existing ... | identifier_body |
create_attn.py | """ Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import Gl... | # Self-attention / attention-like modules w/ significant compute and/or params
# Typically replace some of the existing workhorse convs in a network architecture.
# All of these accept a stride argument and can spatially downsample the input.
elif attn_type == 'lambda':
... | module_cls = SplitAttn
| random_line_split |
create_attn.py | """ Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import Gl... | (attn_type, channels, **kwargs):
module_cls = get_attn(attn_type)
if module_cls is not None:
# NOTE: it's expected the first (positional) argument of all attention layers is the # input channels
return module_cls(channels, **kwargs)
return None
| create_attn | identifier_name |
index.d.ts | // Type definitions for angular-formly 7.2.4
// Project: https://github.com/formly-js/angular-formly
// Definitions by: Scott Hatcher <https://github.com/scatcher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="angular" />
declare module 'AngularFor... | * see http://docs.angular-formly.com/docs/field-configuration-object#id-string
*/
id?: string;
initialValue?: any;
/**
* Can be set instead of type or template to use a custom html template form field. Works
* just like a directive templateUrl and uses the $templateCache
*
* see http://docs.... | random_line_split | |
databasehelper.py | # -*- coding: utf-8 -*-
import sqlite3
VERBOSE = 0
CTABLE_DOMAIN = '''
CREATE TABLE IF NOT EXISTS Domains(
did INTEGER PRIMARY KEY AUTOINCREMENT,
domain VARCHAR(64) UNIQUE,
indegree INTEGER,
outdegree INTEGER
)'''
CTABLE_WEBSITE = '''
CREATE TABLE IF NOT EXISTS Websites(
wid INTEGER PRIMARY KEY AUTOINCREMENT,
... | (object):
def __init__(self):
'''创建表'''
self.conn = sqlite3.connect("./items.db")
if VERBOSE:
print 'Database connection OPEN.'
# Domain 表
self.conn.execute(CTABLE_DOMAIN)
# Website 表
self.conn.execute(CTABLE_WEBSITE)
# Rule 表
self.conn.execute(CTABLE_RULESETS)
self.conn.commit()
if VERBOSE:... | DatabaseHelper | identifier_name |
databasehelper.py | # -*- coding: utf-8 -*-
import sqlite3
VERBOSE = 0
CTABLE_DOMAIN = '''
CREATE TABLE IF NOT EXISTS Domains(
did INTEGER PRIMARY KEY AUTOINCREMENT,
domain VARCHAR(64) UNIQUE,
indegree INTEGER,
outdegree INTEGER
)'''
CTABLE_WEBSITE = '''
CREATE TABLE IF NOT EXISTS Websites(
wid INTEGER PRIMARY KEY AUTOINCREMENT,
... | omain 表
self.conn.execute(CTABLE_DOMAIN)
# Website 表
self.conn.execute(CTABLE_WEBSITE)
# Rule 表
self.conn.execute(CTABLE_RULESETS)
self.conn.commit()
if VERBOSE:
cur = self.conn.cursor()
print 'Tables:',cur.execute("SELECT name FROM sqlite_master WHERE type = 'table'").fetchall()
def close(self)... | 'Database connection OPEN.'
# D | conditional_block |
databasehelper.py | # -*- coding: utf-8 -*-
import sqlite3
VERBOSE = 0
CTABLE_DOMAIN = '''
CREATE TABLE IF NOT EXISTS Domains(
did INTEGER PRIMARY KEY AUTOINCREMENT,
domain VARCHAR(64) UNIQUE,
indegree INTEGER,
outdegree INTEGER
)'''
CTABLE_WEBSITE = '''
CREATE TABLE IF NOT EXISTS Websites(
wid INTEGER PRIMARY KEY AUTOINCREMENT,
... | (self):
'''关闭与数据库的连接'''
if VERBOSE:
print 'Database connection CLOSE.'
self.conn.close()
def insertDomain(self, domain, indegree=0, outdegree=0):
'''增加一个域名'''
cur = self.conn.cursor()
cur.execute("INSERT INTO Domains VALUES (NULL,?,?,?)", (domain, indegree, outdegree))
# 写入到文件中
self.conn.commit()
... | '''创建表'''
self.conn = sqlite3.connect("./items.db")
if VERBOSE:
print 'Database connection OPEN.'
# Domain 表
self.conn.execute(CTABLE_DOMAIN)
# Website 表
self.conn.execute(CTABLE_WEBSITE)
# Rule 表
self.conn.execute(CTABLE_RULESETS)
self.conn.commit()
if VERBOSE:
cur = self.conn.cursor()
p... | identifier_body |
databasehelper.py | # -*- coding: utf-8 -*-
import sqlite3
VERBOSE = 0
CTABLE_DOMAIN = '''
CREATE TABLE IF NOT EXISTS Domains(
did INTEGER PRIMARY KEY AUTOINCREMENT,
domain VARCHAR(64) UNIQUE,
indegree INTEGER,
outdegree INTEGER
)'''
CTABLE_WEBSITE = '''
CREATE TABLE IF NOT EXISTS Websites(
wid INTEGER PRIMARY KEY AUTOINCREMENT,
... | # 未有对应domain记录, 先创建domain, 把入度设为1
if VERBOSE:
print 'Spot Domain:',domain
self.insertDomain(domain, indegree=1)
cur.execute("SELECT did FROM Domains WHERE domain=?", (domain,))
did = cur.fetchone()[0]
else:
did = result[0]
# 对应的domain记录已经存在, 对其入度+1
cur.execute("UPDATE Domains SET outdegree... | result = cur.fetchone()
if not result: | random_line_split |
stars.rs | use futures::prelude::*;
use hubcaps::{Credentials, Github};
use std::env;
use std::error::Error;
#[tokio::main]
async fn | () -> Result<(), Box<dyn Error>> {
pretty_env_logger::init();
let token = env::var("GITHUB_TOKEN")?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let stars = github.activity().stars();
let f = futures::f... | main | identifier_name |
stars.rs | use futures::prelude::*;
use hubcaps::{Credentials, Github};
use std::env;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> | {
pretty_env_logger::init();
let token = env::var("GITHUB_TOKEN")?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")),
Credentials::Token(token),
)?;
let stars = github.activity().stars();
let f = futures::future::try_join(
stars.st... | identifier_body | |
stars.rs | use futures::prelude::*;
use hubcaps::{Credentials, Github};
use std::env;
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
pretty_env_logger::init();
let token = env::var("GITHUB_TOKEN")?;
let github = Github::new(
concat!(env!("CARGO_PKG_NAME"), "/", env!("CAR... | .try_for_each(|s| async move {
println!("{:?}", s.html_url);
Ok(())
})
.await?;
Ok(())
} |
stars
.iter("softprops") | random_line_split |
data-onboarding-view.js | var _ = require('underscore');
var $ = require('jquery');
var OnboardingView = require('builder/components/onboardings/generic/generic-onboarding-view');
var template = require('./data-onboarding.tpl');
module.exports = OnboardingView.extend({
initialize: function (opts) {
OnboardingView.prototype.initialize.cal... | this._setMiddlePad('.js-editorPanelContent', {top: 8, right: 24, left: 24, bottom: -$('.js-optionsBar').outerHeight()});
} else if (step === 3) {
this._setMiddlePad('.js-optionsBar', null, {top: -190});
} else if (step === 4) {
var featurePosition = this._getFeatureEditionPosition();
thi... | } else if (step === 1) {
this._setMiddlePad('.js-editorPanelHeader', {top: 16, right: 24, left: 24});
} else if (step === 2) { | random_line_split |
data-onboarding-view.js | var _ = require('underscore');
var $ = require('jquery');
var OnboardingView = require('builder/components/onboardings/generic/generic-onboarding-view');
var template = require('./data-onboarding.tpl');
module.exports = OnboardingView.extend({
initialize: function (opts) {
OnboardingView.prototype.initialize.cal... | else if (step === 3) {
this._setMiddlePad('.js-optionsBar', null, {top: -190});
} else if (step === 4) {
var featurePosition = this._getFeatureEditionPosition();
this._setMiddlePad(featurePosition, {top: 8, right: 8, bottom: 8, left: 8}, {top: -270, left: -330});
}
},
_getFeatureEditionP... | {
this._setMiddlePad('.js-editorPanelContent', {top: 8, right: 24, left: 24, bottom: -$('.js-optionsBar').outerHeight()});
} | conditional_block |
testLinuxMdRaid.ts | process.env.NODE_ENV = 'test';
import {expect} from 'chai';
import * as fs from 'fs';
import {before, describe, it} from 'mocha';
import * as url from 'url';
import {LinuxMdInfo} from '../src';
import {parseMdPartitionData, parseMdStat} from '../src/parseUtils';
let mdstatData: string;
let sshUrlData: url.UrlWithString... | const md = new LinuxMdInfo({host: sshUrlData.host, username, password});
try {
await md.checkMd('md666');
throw new Error('this should not happen');
} catch(err) {
// ignore
}
});
});
}); | if ( ! sshUrlData.auth ) {
throw new Error('no ssh auth data in url');
}
const [username, password] = sshUrlData.auth.split(':', 2) as string[]; | random_line_split |
testLinuxMdRaid.ts | process.env.NODE_ENV = 'test';
import {expect} from 'chai';
import * as fs from 'fs';
import {before, describe, it} from 'mocha';
import * as url from 'url';
import {LinuxMdInfo} from '../src';
import {parseMdPartitionData, parseMdStat} from '../src/parseUtils';
let mdstatData: string;
let sshUrlData: url.UrlWithString... |
const [username, password] = sshUrlData.auth.split(':', 2) as string[];
const md = new LinuxMdInfo({host: sshUrlData.host, username, password});
const data = await md.getMdStatus();
expect(data).to.be.an('array');
});
it('should start raid check', async () => {
if ( ! sshUrlData.auth ) {
throw n... | {
throw new Error('no ssh auth data in url');
} | conditional_block |
condition_evaluator.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 {IMinimatch, Minimatch} from 'minimatch';
/** Map that holds patterns and their corresponding Minimatch glob... | }
const glob = new Minimatch(pattern, {dot: true});
patternCache.set(pattern, glob);
return glob;
} | */
function getOrCreateGlob(pattern: string) {
if (patternCache.has(pattern)) {
return patternCache.get(pattern)!; | random_line_split |
condition_evaluator.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 {IMinimatch, Minimatch} from 'minimatch';
/** Map that holds patterns and their corresponding Minimatch glob... | (expr: string): (files: string[]) => boolean {
// Creates a dynamic function with the specified expression. The first parameter will
// be `files` as that corresponds to the supported `files` variable that can be accessed
// in PullApprove condition expressions. The followed parameters correspond to other
// co... | convertConditionToFunction | identifier_name |
condition_evaluator.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 {IMinimatch, Minimatch} from 'minimatch';
/** Map that holds patterns and their corresponding Minimatch glob... |
/**
* Superset of a native array. The superset provides methods which mimic the
* list data structure used in PullApprove for files in conditions.
*/
class PullApproveArray extends Array<string> {
constructor(...elements: string[]) {
super(...elements);
// Set the prototype explicitly because in ES5, th... | {
return expression.replace(/not\s+/g, '!');
} | identifier_body |
condition_evaluator.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 {IMinimatch, Minimatch} from 'minimatch';
/** Map that holds patterns and their corresponding Minimatch glob... |
return !!result;
};
}
/**
* Transforms a condition expression from PullApprove that is based on python
* so that it can be run inside JavaScript. Current transformations:
* 1. `not <..>` -> `!<..>`
*/
function transformExpressionToJs(expression: string): string {
return expression.replace(/not\s+/g, '!'... | {
return result.length !== 0;
} | conditional_block |
count.spec.js | import * as lamb from "../..";
import { nonFunctions, wannabeEmptyArrays } from "../../__tests__/commons";
describe("count / countBy", function () {
var getCity = lamb.getKey("city");
var persons = [
{ name: "Jane", surname: "Doe", age: 12, city: "New York" },
{ name: "John", surname: "Doe", a... | it("should consider deleted or unassigned indexes in sparse arrays as `undefined` values", function () {
var arr = [1, , 3, void 0, 5]; // eslint-disable-line no-sparse-arrays
var result = { false: 3, true: 2 };
expect(lamb.count(arr, lamb.isUndefined)).toEqual(result);
expect(lamb.... | expect(function () { lamb.countBy()(persons); }).toThrow();
});
| random_line_split |
imdb.py | """
General image database
An image database creates a list of relative image path called image_set_index and
transform index to absolute image path. As to training, it is necessary that ground
truth and proposals are mixed together for training.
roidb
basic format [image_index]
['image', 'height', 'width', 'flipped',
... | (self, roidb, candidate_boxes=None, thresholds=None):
"""
evaluate detection proposal recall metrics
record max overlap value for each gt box; return vector of overlap values
:param roidb: used to evaluate
:param candidate_boxes: if not given, use roidb's non-gt boxes
:pa... | evaluate_recall | identifier_name |
imdb.py | """
General image database
An image database creates a list of relative image path called image_set_index and
transform index to absolute image path. As to training, it is necessary that ground
truth and proposals are mixed together for training.
roidb
basic format [image_index]
['image', 'height', 'width', 'flipped',
... | recalls[i] = (gt_overlaps >= t).sum() / float(num_pos)
ar = recalls.mean()
# print results
print('average recall for {}: {:.3f}'.format(area_name, ar))
for threshold, recall in zip(thresholds, recalls):
print('recall @{:.2f}: {:.3f}'.forma... | thresholds = np.arange(0.5, 0.95 + 1e-5, step)
recalls = np.zeros_like(thresholds)
# compute recall for each IoU threshold
for i, t in enumerate(thresholds): | random_line_split |
imdb.py | """
General image database
An image database creates a list of relative image path called image_set_index and
transform index to absolute image path. As to training, it is necessary that ground
truth and proposals are mixed together for training.
roidb
basic format [image_index]
['image', 'height', 'width', 'flipped',
... |
else:
roidb = self.load_rpn_roidb(gt_roidb)
return roidb
def create_roidb_from_box_list(self, box_list, gt_roidb):
"""
given ground truth, prepare roidb
:param box_list: [image_index] ndarray of [box_index][x1, x2, y1, y2]
:param gt_roidb: [image_index][... | logger.info('%s appending ground truth annotations' % self.name)
rpn_roidb = self.load_rpn_roidb(gt_roidb)
roidb = IMDB.merge_roidbs(gt_roidb, rpn_roidb) | conditional_block |
imdb.py | """
General image database
An image database creates a list of relative image path called image_set_index and
transform index to absolute image path. As to training, it is necessary that ground
truth and proposals are mixed together for training.
roidb
basic format [image_index]
['image', 'height', 'width', 'flipped',
... |
def append_flipped_images(self, roidb):
"""
append flipped images to an roidb
flip boxes coordinates, images will be actually flipped when loading into network
:param roidb: [image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
:return: roidb: [image_index]['boxes'... | """
given ground truth, prepare roidb
:param box_list: [image_index] ndarray of [box_index][x1, x2, y1, y2]
:param gt_roidb: [image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
:return: roidb: [image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
"""
a... | identifier_body |
tooltip-6fa2e4de.js | import { B as Behavior, H as isTouch, f as fixPosition } from './index-16504bb3.js';
class TooltipBehavior extends Behavior {
connected() |
disconnected() {
const removeListeners = this.removeListeners;
if (removeListeners) {
removeListeners();
}
}
}
export default TooltipBehavior;
| {
const { host } = this;
const parent = this.parent = this.host.parentNode;
if (parent && parent.nuElement && !parent.hasAttribute('describedby')) {
parent.setAttribute('describedby', this.nuId);
}
let hover = false;
let focus = false;
host.hidden = true;
this.setMod('tooltip',... | identifier_body |
tooltip-6fa2e4de.js | import { B as Behavior, H as isTouch, f as fixPosition } from './index-16504bb3.js';
class TooltipBehavior extends Behavior {
connected() {
const { host } = this;
const parent = this.parent = this.host.parentNode;
if (parent && parent.nuElement && !parent.hasAttribute('describedby')) {
parent.setA... | () {
const removeListeners = this.removeListeners;
if (removeListeners) {
removeListeners();
}
}
}
export default TooltipBehavior;
| disconnected | identifier_name |
tooltip-6fa2e4de.js | import { B as Behavior, H as isTouch, f as fixPosition } from './index-16504bb3.js';
class TooltipBehavior extends Behavior {
connected() {
const { host } = this;
const parent = this.parent = this.host.parentNode;
if (parent && parent.nuElement && !parent.hasAttribute('describedby')) {
parent.setA... | }
export default TooltipBehavior; | random_line_split | |
GPUComputationRenderer.js | /**
* @author yomboprime https://github.com/yomboprime
*
* GPUComputationRenderer, based on SimulationRenderer by zz85
*
* The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
* for each compute element (texel)
*
* Each variable has a fragment shad... |
function getPassThroughFragmentShader() {
return "uniform sampler2D passThruTexture;\n" +
"\n" +
"void main() {\n" +
"\n" +
" vec2 uv = gl_FragCoord.xy / resolution.xy;\n" +
"\n" +
" gl_FragColor = texture2D( passThruTexture, uv );\n" +
"\n" +
"}\n";
}
};
export { GPUComputationRendere... | {
return "void main() {\n" +
"\n" +
" gl_Position = vec4( position, 1.0 );\n" +
"\n" +
"}\n";
} | identifier_body |
GPUComputationRenderer.js | /**
* @author yomboprime https://github.com/yomboprime
*
* GPUComputationRenderer, based on SimulationRenderer by zz85
*
* The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
* for each compute element (texel)
*
* Each variable has a fragment shad... | *
* // Create initial state float textures
* var pos0 = gpuCompute.createTexture();
* var vel0 = gpuCompute.createTexture();
* // and fill in here the texture data...
*
* // Add texture variables
* var velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, pos0 );
* var posVar = gpuCompute.addV... | * var gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer ); | random_line_split |
GPUComputationRenderer.js | /**
* @author yomboprime https://github.com/yomboprime
*
* GPUComputationRenderer, based on SimulationRenderer by zz85
*
* The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
* for each compute element (texel)
*
* Each variable has a fragment shad... | () {
return "uniform sampler2D passThruTexture;\n" +
"\n" +
"void main() {\n" +
"\n" +
" vec2 uv = gl_FragCoord.xy / resolution.xy;\n" +
"\n" +
" gl_FragColor = texture2D( passThruTexture, uv );\n" +
"\n" +
"}\n";
}
};
export { GPUComputationRenderer };
| getPassThroughFragmentShader | identifier_name |
GPUComputationRenderer.js | /**
* @author yomboprime https://github.com/yomboprime
*
* GPUComputationRenderer, based on SimulationRenderer by zz85
*
* The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
* for each compute element (texel)
*
* Each variable has a fragment shad... |
}
uniforms[ depVar.name ] = { value: null };
material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;
}
}
}
this.currentTextureIndex = 0;
return null;
};
this.compute = function () {
var currentTextureIndex = this.currentTextureIndex;
... | {
return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
} | conditional_block |
deck.repl.js | function content($slide) {
return $slide.children().first().nextAll();
}
function addReplToSlide($, deck, $slide) {
var endpoint = $[deck]('getOptions').repl.endpoint;
content($slide).wrapAll('<div class="repl-slide-column repl-text-column"></div>');
var replHtmlId = "console-" + $slide[0].id;
$('<div/>', { ... |
} | random_line_split | |
deck.repl.js | function content($slide) {
return $slide.children().first().nextAll();
}
function addReplToSlide($, deck, $slide) {
var endpoint = $[deck]('getOptions').repl.endpoint;
content($slide).wrapAll('<div class="repl-slide-column repl-text-column"></div>');
var replHtmlId = "console-" + $slide[0].id;
$('<div/>', { ... |
function getContext(element) {
return element.attr('data-repl-context') || element.parents('[data-repl-context]').attr('data-repl-context');
}
function hasContext(element) {
var ctx = getContext(element);
return ctx !== undefined && ctx !== "";
}
function newConsole(endpoint, element) {
var replContext = ge... | {
return protocol() + endpoint;
} | identifier_body |
deck.repl.js | function content($slide) {
return $slide.children().first().nextAll();
}
function addReplToSlide($, deck, $slide) {
var endpoint = $[deck]('getOptions').repl.endpoint;
content($slide).wrapAll('<div class="repl-slide-column repl-text-column"></div>');
var replHtmlId = "console-" + $slide[0].id;
$('<div/>', { ... | (endpoint, element) {
var replContext = getContext(element);
var jqconsole = element.jqconsole("", "> ");
var startPrompt;
var writeText = function(text) {
jqconsole.Write(text, 'jqconsole-output');
startPrompt();
};
var writeError = function(text) {
jqconsole.Write(text, 'jqconsole-error');
... | newConsole | identifier_name |
users.authentication.js | 'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('../../utils/response/errors'),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User'),
Roles = require('../../config/roles'),
UsersAuthorization = require('./u... | */
exports.signin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
res.status(400).json(info);
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
if (!user.active) {
... | };
/**
* Signin after passport authentication | random_line_split |
users.authentication.js | 'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('../../utils/response/errors'),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User'),
Roles = require('../../config/roles'),
UsersAuthorization = require('./u... |
}
};
/**
* Remove OAuth provider
*/
exports.removeOAuthProvider = function(req, res, next) {
var user = req.user;
var provider = req.param('provider');
if (user && provider) {
// Delete the additional provider
if (user.additionalProvidersData[provider]) {
delete user.additionalProvidersData[p... | {
return done(new Error('User is already connected using this provider'), user);
} | conditional_block |
pubsubhubbub_publish_test.py | #!/usr/bin/env python
#
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
body = self.rfile.read(length)
if self.path == '/single':
if body != urllib.urlencode(
{'hub.url': 'http://example.com/feed', 'hub.mode': 'publish'}):
self.send_error(500)
self.wfile.write('Bad body. Found:')
self.wfile.write(body)
else:
self.send_response... | return self.send_error(500) | conditional_block |
pubsubhubbub_publish_test.py | #!/usr/bin/env python
#
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
class PublishTest(unittest.TestCase):
def setUp(self):
global REQUESTS
REQUESTS = 0
self.server = BaseHTTPServer.HTTPServer(('', 0), RequestHandler)
t = threading.Thread(target=self.server.serve_forever)
t.setDaemon(True)
t.start()
self.hub = 'http://%s:%d' % (
self.server.serv... | def do_POST(self):
global REQUESTS
print 'Accessed', self.path
REQUESTS += 1
length = int(self.headers.get('content-length', 0))
if not length:
return self.send_error(500)
body = self.rfile.read(length)
if self.path == '/single':
if body != urllib.urlencode(
{'hub.url... | identifier_body |
pubsubhubbub_publish_test.py | #!/usr/bin/env python
#
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | (self):
self.assertRaises(
pubsubhubbub_publish.PublishError,
pubsubhubbub_publish.publish,
'http://asdf.does.not.resolve', self.feed)
def testBadArgument(self):
self.assertRaises(
pubsubhubbub_publish.PublishError,
pubsubhubbub_publish.publish,
self.hub + '/fa... | testBadHubHostname | identifier_name |
pubsubhubbub_publish_test.py | #!/usr/bin/env python
#
# Copyright 2009 Google Inc.
#
# 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 | # limitations under the License.
#
"""Tests for the pubsubhubbub_publish module."""
__author__ = 'bslatkin@gmail.com (Brett Slatkin)'
import BaseHTTPServer
import urllib
import unittest
import threading
import pubsubhubbub_publish
REQUESTS = 0
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def d... | #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and | random_line_split |
auto-encode.rs | // xfail-fast
// 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
// <... | (&self, other: &CLike) -> bool {
(*self) as int == *other as int
}
fn ne(&self, other: &CLike) -> bool { !self.eq(other) }
}
#[auto_encode]
#[auto_decode]
#[deriving(Eq)]
struct Spanned<T> {
lo: uint,
hi: uint,
node: T,
}
#[auto_encode]
#[auto_decode]
struct SomeStruct { v: ~[uint] }
#[au... | eq | identifier_name |
auto-encode.rs | // xfail-fast
// 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
// <... | lo: uint,
hi: uint,
node: T,
}
#[auto_encode]
#[auto_decode]
struct SomeStruct { v: ~[uint] }
#[auto_encode]
#[auto_decode]
struct Point {x: uint, y: uint}
#[auto_encode]
#[auto_decode]
enum Quark<T> {
Top(T),
Bottom(T)
}
#[auto_encode]
#[auto_decode]
enum CLike { A, B, C }
pub fn main() {
... | struct Spanned<T> { | random_line_split |
emojiReactionsView_reactable.graphql.js | /**
* @flow
*/
/* eslint-disable */
'use strict';
/*::
import type { ReaderFragment } from 'relay-runtime';
export type ReactionContent = "CONFUSED" | "EYES" | "HEART" | "HOORAY" | "LAUGH" | "ROCKET" | "THUMBS_DOWN" | "THUMBS_UP" | "%future added value";
import type { FragmentReference } from "relay-runtime";
decl... | "name": "reactionGroups",
"storageKey": null,
"args": null,
"concreteType": "ReactionGroup",
"plural": true,
"selections": [
{
"kind": "ScalarField",
"alias": null,
"name": "content",
"args": null,
"storageKey": null
}... | random_line_split | |
createsigningcertificate.py | # Copyright 2009-2015 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions ... |
if not self.args['keyout']:
print result['Certificate']['PrivateKey']
| print result['Certificate']['CertificateBody'] | conditional_block |
createsigningcertificate.py | # Copyright 2009-2015 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions ... | # notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIE... | #
# Redistributions in binary form must reproduce the above copyright | random_line_split |
createsigningcertificate.py | # Copyright 2009-2015 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions ... |
def print_result(self, result):
print result['Certificate']['CertificateId']
if not self.args['out']:
print result['Certificate']['CertificateBody']
if not self.args['keyout']:
print result['Certificate']['PrivateKey']
| if self.args['out']:
with open(self.args['out'], 'w') as certfile:
certfile.write(result['Certificate']['CertificateBody'])
if self.args['keyout']:
old_umask = os.umask(0o077)
with open(self.args['keyout'], 'w') as keyfile:
keyfile.write(result... | identifier_body |
createsigningcertificate.py | # Copyright 2009-2015 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions ... | (self, result):
print result['Certificate']['CertificateId']
if not self.args['out']:
print result['Certificate']['CertificateBody']
if not self.args['keyout']:
print result['Certificate']['PrivateKey']
| print_result | identifier_name |
setup.py | """stockretriever"""
from setuptools import setup
setup(
name='portfolio-manager',
version='1.0',
description='a web app that keeps track of your investment portfolio',
url='https://github.com/gurch101/portfolio-manager',
author='Gurchet Rai',
author_email='gurch101@gmail.com',
license='MI... | ]
) | random_line_split | |
serving.rs | // Copyright (c) 2016-2018 The http-serve developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE.txt or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT.txt or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or dist... | .header(header::ALLOW, HeaderValue::from_static("get, head"))
.body(static_body::<D, E>("This resource only supports GET and HEAD.").into())
.unwrap(),
);
}
let last_modified = ent.last_modified();
let etag = ent.etag();
let (precondition_failed,... | random_line_split | |
serving.rs | // Copyright (c) 2016-2018 The http-serve developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE.txt or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT.txt or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or dist... |
/// An instruction from `serve_inner` to `serve` on how to respond.
enum ServeInner<B> {
Simple(Response<B>),
Multipart {
res: http::response::Builder,
part_headers: Vec<Vec<u8>>,
ranges: SmallVec<[Range<u64>; 1]>,
},
}
/// Runs trait object-based inner logic for `serve`.
fn serve... | {
// serve takes entity itself for ownership, as needed for the multipart case. But to avoid
// monomorphization code bloat when there are many implementations of Entity<Data, Error>,
// delegate as much as possible to functions which take a reference to a trait object.
match serve_inner(&entity, req) {... | identifier_body |
serving.rs | // Copyright (c) 2016-2018 The http-serve developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE.txt or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT.txt or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or dist... | <D, E>(
state: usize,
ent: &dyn Entity<Data = D, Error = E>,
ranges: &[Range<u64>],
part_headers: &mut [Vec<u8>],
) -> impl Future<Output = Option<(InnerBody<D, E>, usize)>>
where
D: 'static + Send + Sync + Buf + From<Vec<u8>> + From<&'static [u8]>,
E: 'static + Send + Sync,
{
let i = state ... | next_multipart_body_chunk | identifier_name |
example.rs | use report::ExampleResult;
use header::ExampleHeader;
/// Test examples are the smallest unit of a testing framework, wrapping one or more assertions.
pub struct Example<T> {
pub(crate) header: ExampleHeader,
pub(crate) function: Box<Fn(&T) -> ExampleResult>,
}
impl<T> Example<T> {
pub(crate) fn new<F>(he... | () -> Self {
Example::new(ExampleHeader::default(), |_| ExampleResult::Failure(None))
}
}
unsafe impl<T> Send for Example<T>
where
T: Send,
{
}
unsafe impl<T> Sync for Example<T>
where
T: Sync,
{
}
| fixture_failed | identifier_name |
example.rs | use report::ExampleResult;
use header::ExampleHeader;
/// Test examples are the smallest unit of a testing framework, wrapping one or more assertions.
pub struct Example<T> {
pub(crate) header: ExampleHeader,
pub(crate) function: Box<Fn(&T) -> ExampleResult>,
} | pub(crate) fn new<F>(header: ExampleHeader, assertion: F) -> Self
where
F: 'static + Fn(&T) -> ExampleResult,
{
Example {
header: header,
function: Box::new(assertion),
}
}
/// Used for testing purpose
#[cfg(test)]
pub fn fixture_success() -> ... |
impl<T> Example<T> { | random_line_split |
main.rs | //! Amethyst CLI binary crate.
//!
use std::process::exit;
use amethyst_cli as cli;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
fn | () {
eprintln!(
"WARNING! amethyst_tools has been deprecated and will stop working in future versions."
);
eprintln!("For more details please see https://community.amethyst.rs/t/end-of-life-for-amethyst-tools-the-cli/1656");
let matches = App::new("Amethyst CLI")
.author("Created by Amet... | main | identifier_name |
main.rs | //! Amethyst CLI binary crate.
//!
use std::process::exit;
use amethyst_cli as cli;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
fn main() {
eprintln!(
"WARNING! amethyst_tools has been deprecated and will stop working in future versions."
);
eprintln!("For more details please see h... | .value_name("AMETHYST_VERSION")
.takes_value(true)
.help("The requested version of Amethyst"),
)
.arg(
Arg::with_name("no_defaults")
.short("n")
.lo... | Arg::with_name("amethyst_version")
.short("a")
.long("amethyst") | random_line_split |
main.rs | //! Amethyst CLI binary crate.
//!
use std::process::exit;
use amethyst_cli as cli;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
fn main() {
eprintln!(
"WARNING! amethyst_tools has been deprecated and will stop working in future versions."
);
eprintln!("For more details please see h... |
fn handle_error(e: &cli::error::Error) {
use ansi_term::Color;
eprintln!("{}: {}", Color::Red.paint("error"), e);
e.iter()
.skip(1)
.for_each(|e| eprintln!("{}: {}", Color::Red.paint("caused by"), e));
// Only shown if `RUST_BACKTRACE=1`.
if let Some(backtrace) = e.backtrace() {
... | {
use ansi_term::Color;
use cli::get_latest_version;
let local_version = semver::Version::parse(env!("CARGO_PKG_VERSION"))?;
let remote_version_str = get_latest_version()?;
let remote_version = semver::Version::parse(&remote_version_str)?;
if local_version < remote_version {
eprintln!(... | identifier_body |
triagelog-page-sk.ts | /**
* @module modules/triagelog-page-sk
* @description <h2><code>triagelog-page-sk</code></h2>
*
* Allows the user to page through the diff triage logs, and optionally undo
* labels applied to triaged diffs.
*/
import { define } from 'elements-sk/define';
import 'elements-sk/checkbox-sk';
import { html } from 'l... |
<tr class="details details-separator"><td colspan="4"></td></tr>
`;
private static detailsEntryTemplate2 = (el: TriagelogPageSk, delta: TriageDelta2) => {
let detailHref = `/detail?test=${delta.grouping.name}&digest=${delta.digest}`;
if (el.changelistID) {
detailHref += `&changelist_id=${el.chan... | <td><strong>Label</strong></td>
</tr>
${entry.details?.map((e) => TriagelogPageSk.detailsEntryTemplate2(el, e))} | random_line_split |
triagelog-page-sk.ts | /**
* @module modules/triagelog-page-sk
* @description <h2><code>triagelog-page-sk</code></h2>
*
* Allows the user to page through the diff triage logs, and optionally undo
* labels applied to triaged diffs.
*/
import { define } from 'elements-sk/define';
import 'elements-sk/checkbox-sk';
import { html } from 'l... | (e: CustomEvent<PaginationSkPageChangedEventDetail>) {
this.pageOffset = Math.max(0, this.pageOffset + e.detail.delta * this.pageSize);
this.stateChanged();
this._render();
this.fetchEntries();
}
private undoEntry(entryId: string) {
sendBeginTask(this);
this.fetchV2(`/json/v2/triagelog/undo... | pageChanged | identifier_name |
triagelog-page-sk.ts | /**
* @module modules/triagelog-page-sk
* @description <h2><code>triagelog-page-sk</code></h2>
*
* Allows the user to page through the diff triage logs, and optionally undo
* labels applied to triaged diffs.
*/
import { define } from 'elements-sk/define';
import 'elements-sk/checkbox-sk';
import { html } from 'l... |
private undoEntry(entryId: string) {
sendBeginTask(this);
this.fetchV2(`/json/v2/triagelog/undo?id=${entryId}`, 'POST')
.then(() => {
this._render();
sendEndTask(this);
})
.catch((e) => sendFetchError(this, e, 'undo'));
}
private fetchEntries(sendBusyDoneEvents = true)... | {
this.pageOffset = Math.max(0, this.pageOffset + e.detail.delta * this.pageSize);
this.stateChanged();
this._render();
this.fetchEntries();
} | identifier_body |
triagelog-page-sk.ts | /**
* @module modules/triagelog-page-sk
* @description <h2><code>triagelog-page-sk</code></h2>
*
* Allows the user to page through the diff triage logs, and optionally undo
* labels applied to triaged diffs.
*/
import { define } from 'elements-sk/define';
import 'elements-sk/checkbox-sk';
import { html } from 'l... |
})
.catch((e) => sendFetchError(this, e, 'triagelog'));
}
private fetchV2(url: string, method: 'GET' | 'POST'): Promise<void> {
// Force only one fetch at a time. Abort any outstanding requests.
if (this.fetchController) {
this.fetchController.abort();
}
this.fetchController = ne... | {
sendEndTask(this);
} | conditional_block |
S15.5.4.5_A8.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The String.prototype.charCodeAt.length property has the attribute DontEnum
es5id: 15.5.4.5_A8
description: >
Checking if enumerating the String.prototype.charCodeAt.length... | }
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// CHECK#2
var count=0;
for (var p in String.prototype.charCodeAt){
if (p==="length") count++;
}
if (count !== 0) {
$ERROR('#2: count=0; for (p in Str... | if (String.prototype.charCodeAt.propertyIsEnumerable('length')) {
$ERROR('#1: String.prototype.charCodeAt.propertyIsEnumerable(\'length\') return false. Actual: '+String.prototype.charCodeAt.propertyIsEnumerable('length')); | random_line_split |
S15.5.4.5_A8.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The String.prototype.charCodeAt.length property has the attribute DontEnum
es5id: 15.5.4.5_A8
description: >
Checking if enumerating the String.prototype.charCodeAt.length... |
//
//////////////////////////////////////////////////////////////////////////////
| {
$ERROR('#2: count=0; for (p in String.prototype.charCodeAt){if (p==="length") count++;} count === 0. Actual: count ==='+count );
} | conditional_block |
multimedia.py | from django.contrib import messages
from django.http import Http404, HttpResponse
from django.shortcuts import render
from corehq.apps.app_manager.dbaccessors import get_app
from corehq.apps.app_manager.decorators import require_deploy_apps, \
require_can_edit_apps
from corehq.apps.app_manager.xform import XForm
fr... |
@require_deploy_apps
def multimedia_ajax(request, domain, app_id, template='app_manager/v1/partials/multimedia_ajax.html'):
app = get_app(domain, app_id)
if app.get_doc_type() == 'Application':
try:
multimedia_state = app.check_media_state()
except ProcessTimedOut:
not... | app = get_app(domain, app_id)
include_audio = request.GET.get("audio", True)
include_images = request.GET.get("images", True)
strip_jr = request.GET.get("strip_jr", True)
filelist = []
for m in app.get_modules():
for f in m.get_forms():
parsed = XForm(f.source)
parsed... | identifier_body |
multimedia.py | from django.contrib import messages
from django.http import Http404, HttpResponse
from django.shortcuts import render
from corehq.apps.app_manager.dbaccessors import get_app
from corehq.apps.app_manager.decorators import require_deploy_apps, \
require_can_edit_apps
from corehq.apps.app_manager.xform import XForm
fr... | (request, domain, app_id):
app = get_app(domain, app_id)
include_audio = request.GET.get("audio", True)
include_images = request.GET.get("images", True)
strip_jr = request.GET.get("strip_jr", True)
filelist = []
for m in app.get_modules():
for f in m.get_forms():
parsed = XFo... | multimedia_list_download | identifier_name |
multimedia.py | from django.contrib import messages
from django.http import Http404, HttpResponse
from django.shortcuts import render
from corehq.apps.app_manager.dbaccessors import get_app
from corehq.apps.app_manager.decorators import require_deploy_apps, \
require_can_edit_apps
from corehq.apps.app_manager.xform import XForm
fr... |
@require_deploy_apps
def multimedia_ajax(request, domain, app_id, template='app_manager/v1/partials/multimedia_ajax.html'):
app = get_app(domain, app_id)
if app.get_doc_type() == 'Application':
try:
multimedia_state = app.check_media_state()
except ProcessTimedOut:
notif... | return response
| random_line_split |
multimedia.py | from django.contrib import messages
from django.http import Http404, HttpResponse
from django.shortcuts import render
from corehq.apps.app_manager.dbaccessors import get_app
from corehq.apps.app_manager.decorators import require_deploy_apps, \
require_can_edit_apps
from corehq.apps.app_manager.xform import XForm
fr... | raise Http404() | conditional_block | |
emerging_hotspot_factor.py | #make sure to have remapped TCD mosaic(0-31 as NoData, 31-101 as 1)
#remap loss 0 values to NoData. Keep all other values
#set indir to AOI (country or other AOI)
#create geodatabase for results
import os
import arcpy
from arcpy.sa import *
import datetime
import utilities
def emerging_hs_points(country_shapefile, d... |
scratch_workspace = os.path.join(datadir, "scratch.gdb")
results_gdb = os.path.join(datadir, "results.gdb")
if not os.path.exists(results_gdb):
arcpy.CreateFileGDB_management(datadir, "results.gdb")
arcpy.env.scratchWorkspace = scratch_workspace
arcpy.env.workspace = datadir
arcpy.env.s... | arcpy.CreateFileGDB_management(datadir, "scratch.gdb") | conditional_block |
emerging_hotspot_factor.py | #make sure to have remapped TCD mosaic(0-31 as NoData, 31-101 as 1)
#remap loss 0 values to NoData. Keep all other values
#set indir to AOI (country or other AOI)
#create geodatabase for results
import os
import arcpy
from arcpy.sa import *
import datetime
import utilities
def emerging_hs_points(country_shapefile, d... | tile_grid = r'U:\egoldman\hs_2015_update\footprint.shp'
#'''Section 3: set path to mosaic files #######################################################################'''
lossyearmosaic = r'U:\egoldman\mosaics_updated.gdb\loss15'
hansenareamosaic = r'U:\egoldman\mosaics_updated.gdb\area'
#create tcd c... | identifier_body | |
emerging_hotspot_factor.py | #make sure to have remapped TCD mosaic(0-31 as NoData, 31-101 as 1)
#remap loss 0 values to NoData. Keep all other values
#set indir to AOI (country or other AOI)
#create geodatabase for results
import os
import arcpy
from arcpy.sa import *
import datetime
import utilities
def | (country_shapefile, datadir, iso):
#''' Section 2: Set directories ###############################################################################'''
tile_grid = r'U:\egoldman\hs_2015_update\footprint.shp'
#'''Section 3: set path to mosaic files #############################################################... | emerging_hs_points | identifier_name |
emerging_hotspot_factor.py | #make sure to have remapped TCD mosaic(0-31 as NoData, 31-101 as 1)
#remap loss 0 values to NoData. Keep all other values
#set indir to AOI (country or other AOI)
#create geodatabase for results
| import datetime
import utilities
def emerging_hs_points(country_shapefile, datadir, iso):
#''' Section 2: Set directories ###############################################################################'''
tile_grid = r'U:\egoldman\hs_2015_update\footprint.shp'
#'''Section 3: set path to mosaic files ####... | import os
import arcpy
from arcpy.sa import * | random_line_split |
headerWrapperComp.d.ts | import { Beans } from "../../rendering/beans";
import { Column } from "../../entities/column";
import { ColDef } from "../../entities/colDef";
import { AbstractHeaderWrapper } from "./abstractHeaderWrapper";
import { ITooltipParams } from "../../rendering/tooltipComponent";
export declare class | extends AbstractHeaderWrapper {
private static TEMPLATE;
private dragAndDropService;
private columnController;
private horizontalResizeService;
private menuFactory;
private gridApi;
private columnApi;
private sortController;
private userComponentFactory;
private columnHoverServi... | HeaderWrapperComp | identifier_name |
headerWrapperComp.d.ts | import { Beans } from "../../rendering/beans";
import { Column } from "../../entities/column";
import { ColDef } from "../../entities/colDef";
import { AbstractHeaderWrapper } from "./abstractHeaderWrapper";
import { ITooltipParams } from "../../rendering/tooltipComponent";
export declare class HeaderWrapperComp extend... | private setupMovingCss;
private addAttributes;
private setupWidth;
private setupMenuClass;
private onMenuVisible;
private onColumnWidthChanged;
private normaliseResizeAmount;
} | onResizeStart(shiftKey: boolean): void;
getTooltipParams(): ITooltipParams;
private setupTooltip; | random_line_split |
nl.js | define(function () {
// Dutch
return {
errorLoading: function () {
return 'De resultaten konden niet worden geladen.';
},
inputTooLong: function (args) {
var overChars = args.input.length - args.maximum;
var message = 'Gelieve ' + overChars + ' karakters te verwijderen';
... | message += ' worden geselecteerd';
return message;
},
noResults: function () {
return 'Geen resultaten gevonden…';
},
searching: function () {
return 'Zoeken…';
}
};
});
|
message += 's';
}
| conditional_block |
nl.js | define(function () {
// Dutch
return {
errorLoading: function () {
return 'De resultaten konden niet worden geladen.';
},
inputTooLong: function (args) {
var overChars = args.input.length - args.maximum;
var message = 'Gelieve ' + overChars + ' karakters te verwijderen';
... | }
};
}); | return 'Zoeken…';
| random_line_split |
movie-edit-template.component.ts | import { Component } from '@angular/core';
import { ControlGroup } from '@angular/common';
import { ROUTER_DIRECTIVES, OnActivate, RouteSegment } from '@angular/router';
import { IMovie } from './movie';
import { MovieService } from './movie.service';
@Component({
templateUrl: 'app/movies/movie-edit-template.comp... |
constructor(private _movieService: MovieService) {
}
routerOnActivate(curr: RouteSegment): void {
let id = +curr.getParam('id');
this.getMovie(id);
}
getMovie(id: number) {
this._movieService.getMovie(id)
.subscribe(
movie => this.onMovieRetrieved(m... | errorMessage: string; | random_line_split |
movie-edit-template.component.ts | import { Component } from '@angular/core';
import { ControlGroup } from '@angular/common';
import { ROUTER_DIRECTIVES, OnActivate, RouteSegment } from '@angular/router';
import { IMovie } from './movie';
import { MovieService } from './movie.service';
@Component({
templateUrl: 'app/movies/movie-edit-template.comp... | (editForm: ControlGroup) {
if (editForm.dirty && editForm.valid) {
this.movie = editForm.value;
alert(`Movie: ${JSON.stringify(this.movie)}`);
}
}
}
| saveMovie | identifier_name |
movie-edit-template.component.ts | import { Component } from '@angular/core';
import { ControlGroup } from '@angular/common';
import { ROUTER_DIRECTIVES, OnActivate, RouteSegment } from '@angular/router';
import { IMovie } from './movie';
import { MovieService } from './movie.service';
@Component({
templateUrl: 'app/movies/movie-edit-template.comp... |
}
}
| {
this.movie = editForm.value;
alert(`Movie: ${JSON.stringify(this.movie)}`);
} | conditional_block |
feature-gate.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 ... |
#[rustc_error]
fn main() { //[with_gate]~ ERROR compilation successful
let y = Foo { x: 1 };
match y {
FOO => { }
_ => { }
}
} | x: u32
}
const FOO: Foo = Foo { x: 0 }; | random_line_split |
feature-gate.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 ... | () { //[with_gate]~ ERROR compilation successful
let y = Foo { x: 1 };
match y {
FOO => { }
_ => { }
}
}
| main | identifier_name |
constants.js | "use strict";
//
// Debugging
//
// Declare DEBUG constant, but be sure we aren't in production
var DEBUG = Browser.inProduction() ? false : true;
// Disable logging if in production
if (!DEBUG) |
//
// Shorthand to localStorage, used everywhere, as essential here as jQuery
//
var ls = localStorage;
//
// All other constants
//
// API server
var API_SERVER = 'https://passoa.online.ntnu.no/api/';
// Loops & intervals
var BACKGROUND_LOOP = 60000; // 60s
var BACKGROUND_LOOP_DEBUG = 5000; // 5s, respond fairly... | {
window.console = {};
window.console.log = function(){};
window.console.info = function(){};
window.console.warn = function(){};
window.console.error = function(){};
} | conditional_block |
constants.js | "use strict";
//
// Debugging
//
// Declare DEBUG constant, but be sure we aren't in production
var DEBUG = Browser.inProduction() ? false : true;
// Disable logging if in production
if (!DEBUG) {
window.console = {};
window.console.log = function(){};
window.console.info = function(){};
window.console.warn = fu... | //
// Shorthand to localStorage, used everywhere, as essential here as jQuery
//
var ls = localStorage;
//
// All other constants
//
// API server
var API_SERVER = 'https://passoa.online.ntnu.no/api/';
// Loops & intervals
var BACKGROUND_LOOP = 60000; // 60s
var BACKGROUND_LOOP_DEBUG = 5000; // 5s, respond fairly q... | }
| random_line_split |
gpu_luts.py | from gpu import *
LAMP_TYPES = [
GPU_DYNAMIC_LAMP_DYNVEC,
GPU_DYNAMIC_LAMP_DYNCO,
GPU_DYNAMIC_LAMP_DYNIMAT,
GPU_DYNAMIC_LAMP_DYNPERSMAT,
GPU_DYNAMIC_LAMP_DYNENERGY,
GPU_DYNAMIC_LAMP_DYNENERGY,
GPU_DYNAMIC_LAMP_DYNCOL,
GPU_DYNAMIC_LAMP_DISTANCE,
GPU_DYNAMIC_LAMP_ATT1,
GPU_DYNAMIC... | GPU_DATA_2F : 35664, # FLOAT_VEC2
GPU_DATA_3F : 35665, # FLOAT_VEC3
GPU_DATA_4F : 35666, # FLOAT_VEC4
} | GPU_DATA_1I : 5124, # INT
GPU_DATA_1F : 5126, # FLOAT | random_line_split |
mallinson.py | """Calculate exact solutions for the zero dimensional LLG as given by
[Mallinson2000]
"""
from __future__ import division
from __future__ import absolute_import
from math import sin, cos, tan, log, atan2, acos, pi, sqrt
import scipy as sp
import matplotlib.pyplot as plt
import functools as ft
import simpleode.core.u... |
def generate_dynamics(magnetic_parameters,
start_angle=pi/18,
end_angle=17*pi/18,
steps=1000):
"""Generate a list of polar angles then return a list of corresponding
m directions (in spherical polar coordinates) and switching times.
"""
... | """Calculate the azimuthal angle corresponding to switching from
p_start to p_now with the magnetic parameters given.
"""
def azi_into_range(azi):
a = azi % (2*pi)
if a < 0:
a += 2*pi
return a
alpha = magnetic_parameters.alpha
no_range_azi = (-1/alpha) * log(tan... | identifier_body |
mallinson.py | """Calculate exact solutions for the zero dimensional LLG as given by
[Mallinson2000]
"""
from __future__ import division
from __future__ import absolute_import
from math import sin, cos, tan, log, atan2, acos, pi, sqrt
import scipy as sp
import matplotlib.pyplot as plt
import functools as ft
import simpleode.core.u... | """
# Should never quite get to pi/2
# if p_now >= pi/2:
# return sp.inf
# Cache some things to simplify the expressions later
H = magnetic_parameters.H(None)
Hk = magnetic_parameters.Hk()
alpha = magnetic_parameters.alpha
gamma = magnetic_parameters.gamma
# Calculate the ... | """Calculate the time taken to switch from polar angle p_start to p_now
with the magnetic parameters given. | random_line_split |
mallinson.py | """Calculate exact solutions for the zero dimensional LLG as given by
[Mallinson2000]
"""
from __future__ import division
from __future__ import absolute_import
from math import sin, cos, tan, log, atan2, acos, pi, sqrt
import scipy as sp
import matplotlib.pyplot as plt
import functools as ft
import simpleode.core.u... | (magnetic_parameters, ts, ms):
# Extract lists of the polar coordinates
m_as_sph_points = map(utils.array2sph, ms)
pols = [m.pol for m in m_as_sph_points]
azis = [m.azi for m in m_as_sph_points]
# Calculate the corresponding exact dynamics
exact_times, exact_azis = \
calculate_equivale... | plot_vs_exact | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.