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 |
|---|---|---|---|---|
main.rs | // Copyright 2016 Gomez Guillaume
//
// 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 ... |
}
Err(e) => {
println!("\x1b[31;1mProblem with directory '{}': {}\x1b[0m", entry_name, e);
}
}
}
} else {
match entry.file_name() {
Some(s) => {
match ... | {
println!("\x1b[34;1m<- Leaving {}\x1b[0m", entry_name);
} | conditional_block |
main.rs | // Copyright 2016 Gomez Guillaume
//
// 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 files.len() == 0 {
files.push(Path::new("."));
}
if options.verbose {
println!("\x1b[33;1m=== VERBOSE MODE ===\x1b[0m");
}
for tmp in files.iter() {
start_clean(&options, tmp, 0);
}
if options.verbose {
println!("\x1b[33;1mEnd of execution\x1b[0m");
}
} | }
} | random_line_split |
main.rs | // Copyright 2016 Gomez Guillaume
//
// 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 ... |
fn print_help() {
println!("./clean [options] [files | dirs]");
println!(" -r : recursive mode");
println!(" -v : verbose mode");
println!(" -i : prompt before every removal");
println!(" -l=[number] : Add a level for recursive mode");
println!("--help : ... | {
let m = match ::std::fs::metadata(&entry) {
Ok(e) => e,
Err(e) => {
println!("An error occured on '{:?}': {}", entry, e);
return
}
};
let entry_name = match entry.to_str() {
Some(n) => n,
None => {
println!("Invalid entry '{:?}'",... | identifier_body |
main.rs | // Copyright 2016 Gomez Guillaume
//
// 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 ... | () {
let mut args = Vec::new();
for argument in std::env::args() {
args.push(argument);
}
let mut options = CleanOptions{recursive: false, verbose: false, confirmation: false, level: 0};
let mut files = Vec::new();
args.remove(0);
for tmp in args.iter() {
if tmp.clone().int... | main | identifier_name |
index.js | /**
* @module express-universal-query-validator/util
* @description Utility functions needed for this module
*/
import url from 'url';
import { attempt, some, reject, isError } from 'lodash';
/**
* Checks if a key=value param can not be
* parsed by global `decodeURIComponent`
* @param {string} query
* @return... |
/**
* Are all queries parseable?
* @param {Array} queries
* @returns {boolean}
*/
export function validateQueryParams(queries = []) {
return !some(queries, isUnparseableQuery);
}
/**
* Returns input minus unparseable queries
* @param {Array} queries
* @returns {Array}
*/
export function dropInvalidQuer... | {
return isError(attempt(decodeURIComponent, query));
} | identifier_body |
index.js | /**
* @module express-universal-query-validator/util
* @description Utility functions needed for this module
*/
import url from 'url';
import { attempt, some, reject, isError } from 'lodash';
/**
* Checks if a key=value param can not be
* parsed by global `decodeURIComponent`
* @param {string} query
* @return... | (query = 'key=value') {
return isError(attempt(decodeURIComponent, query));
}
/**
* Are all queries parseable?
* @param {Array} queries
* @returns {boolean}
*/
export function validateQueryParams(queries = []) {
return !some(queries, isUnparseableQuery);
}
/**
* Returns input minus unparseable queries
* @... | isUnparseableQuery | identifier_name |
index.js | /**
* @module express-universal-query-validator/util
* @description Utility functions needed for this module
*/
import url from 'url';
import { attempt, some, reject, isError } from 'lodash';
/**
* Checks if a key=value param can not be
* parsed by global `decodeURIComponent`
* @param {string} query
* @return... | */
export function dropInvalidQueryParams(queries = []) {
return reject(queries, isUnparseableQuery);
} | * @param {Array} queries
* @returns {Array} | random_line_split |
promote.py | import re
import subprocess
import sys
def get_promotion_chain(git_directory, git_branch, upstream_name='origin'):
"""
For a given git repository & branch, determine the promotion chain
Following the promotion path defined for pulp figure out what the full promotion
path to master is from wherever we... |
# parse the git_branch: x.y-(dev|testing|release)
branch_regex = "(\d+.\d+)-(dev|testing|release)"
match = re.search(branch_regex, git_branch)
source_branch_version = match.group(1)
source_branch_stream = match.group(2)
# get the branch list
raw_branch_list = subprocess.check_output(['git... | return ['master'] | conditional_block |
promote.py | import re
import subprocess
import sys
def get_promotion_chain(git_directory, git_branch, upstream_name='origin'):
"""
For a given git repository & branch, determine the promotion chain
Following the promotion path defined for pulp figure out what the full promotion
path to master is from wherever we... |
def merge_forward(git_directory, push=False):
"""
From whatever the current checkout is, merge it forward
:param git_directory: directory containing the git project
:type git_directory: str
:param push: Whether or not we should push the results to github
:type push: bool
"""
startin... | """
Ensure that branch_name is checkout from the given upstream
:param git_directory: directory containing the git project
:type git_directory: str
:param branch_name: The local branch name. if the remote is specified in the branch name
eg upstream/2.6-dev then the remote specified in the bran... | identifier_body |
promote.py | import re
import subprocess
import sys
def get_promotion_chain(git_directory, git_branch, upstream_name='origin'):
"""
For a given git repository & branch, determine the promotion chain
Following the promotion path defined for pulp figure out what the full promotion
path to master is from wherever we... | (git_directory, push=False):
"""
From whatever the current checkout is, merge it forward
:param git_directory: directory containing the git project
:type git_directory: str
:param push: Whether or not we should push the results to github
:type push: bool
"""
starting_branch = get_curre... | merge_forward | identifier_name |
promote.py | import re
import subprocess
import sys
def get_promotion_chain(git_directory, git_branch, upstream_name='origin'):
"""
For a given git repository & branch, determine the promotion chain
Following the promotion path defined for pulp figure out what the full promotion
path to master is from wherever we... | """
For a given git directory, get the current remote branch
:param git_directory: The directory containing the git repo
:type git_directory: str
:return: remote branch
:rtype: str
"""
command = 'git rev-parse --abbrev-ref --symbolic-full-name @{u}'
command = command.split(' ')
... |
def get_current_git_upstream_branch(git_directory): | random_line_split |
team-item.controller.ts | /*
* Copyright (c) [2015] - [2017] Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* ... | (tab: string) {
this.$location.path('/team/' + this.team.qualifiedName).search(!tab ? {} : {tab: tab});
}
/**
* Removes team after confirmation.
*/
removeTeam(): void {
this.confirmRemoval().then(() => {
this.codenvyTeam.deleteTeam(this.team.id).then(() => {
this.onUpdate();
}, ... | redirectToTeamDetails | identifier_name |
team-item.controller.ts | /*
* Copyright (c) [2015] - [2017] Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* ... | * Removes team after confirmation.
*/
removeTeam(): void {
this.confirmRemoval().then(() => {
this.codenvyTeam.deleteTeam(this.team.id).then(() => {
this.onUpdate();
}, (error: any) => {
this.cheNotification.showError(error && error.data && error.data.message ? error.data.message... | this.$location.path('/team/' + this.team.qualifiedName).search(!tab ? {} : {tab: tab});
}
/** | random_line_split |
livestream.py | import logging
import re
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream
from streamlink.utils.parse import parse_json
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
r"https?://(?:www\.)?livestream\.com/"
))
cla... | (self):
res = self.session.http.get(self.url)
m = self._config_re.search(res.text)
if not m:
log.debug("Unable to find _config_re")
return
stream_info = parse_json(m.group(1), "config JSON",
schema=self._stream_config_schema)
... | _get_streams | identifier_name |
livestream.py | import logging
import re
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream
from streamlink.utils.parse import parse_json
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
r"https?://(?:www\.)?livestream\.com/"
))
cla... |
m3u8_url = stream_info.get("secure_m3u8_url")
if m3u8_url:
yield from HLSStream.parse_variant_playlist(self.session, m3u8_url).items()
__plugin__ = Livestream
| log.debug("Stream might be Off Air")
return | conditional_block |
livestream.py | import logging
import re
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream
from streamlink.utils.parse import parse_json
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
r"https?://(?:www\.)?livestream\.com/"
))
cla... |
__plugin__ = Livestream
| res = self.session.http.get(self.url)
m = self._config_re.search(res.text)
if not m:
log.debug("Unable to find _config_re")
return
stream_info = parse_json(m.group(1), "config JSON",
schema=self._stream_config_schema)
log.trace("... | identifier_body |
livestream.py | import logging
import re
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream
from streamlink.utils.parse import parse_json
log = logging.getLogger(__name__)
@pluginmatcher(re.compile(
r"https?://(?:www\.)?livestream\.com/"
))
cla... | if not (stream_info and stream_info["is_live"]):
log.debug("Stream might be Off Air")
return
m3u8_url = stream_info.get("secure_m3u8_url")
if m3u8_url:
yield from HLSStream.parse_variant_playlist(self.session, m3u8_url).items()
__plugin__ = Livestream |
stream_info = parse_json(m.group(1), "config JSON",
schema=self._stream_config_schema)
log.trace("stream_info: {0!r}".format(stream_info)) | random_line_split |
productiontiles.component.ts | import {Component, ElementRef} from '@angular/core';
import { ProductionTileService } from '../../shared/services/productiontile.service';
import { Router } from '@angular/router';
import {Observable} from 'rxjs/Rx';
//import 'style-loader!./tiles.scss';
@Component({
selector: 'production-tiles',
styleUrls: ['./tile... | this.router.navigate(['pages/productiontiles/details', id]);
}
summary_details(id): void {
this.summary = 1;
document.getElementsByClassName('widgets')['0'].style.display = 'none';
document.getElementById("summary").style.display = 'block';
}
back_state():void{
this.summary = 0;
document.getElementsBy... | this.sub_prod=this.productions;
}
button_details(id): void { | random_line_split |
productiontiles.component.ts | import {Component, ElementRef} from '@angular/core';
import { ProductionTileService } from '../../shared/services/productiontile.service';
import { Router } from '@angular/router';
import {Observable} from 'rxjs/Rx';
//import 'style-loader!./tiles.scss';
@Component({
selector: 'production-tiles',
styleUrls: ['./tile... |
summary_details(id): void {
this.summary = 1;
document.getElementsByClassName('widgets')['0'].style.display = 'none';
document.getElementById("summary").style.display = 'block';
}
back_state():void{
this.summary = 0;
document.getElementsByClassName('widgets')['0'].style.display = 'block';
document.getEl... | {
this.router.navigate(['pages/productiontiles/details', id]);
} | identifier_body |
productiontiles.component.ts | import {Component, ElementRef} from '@angular/core';
import { ProductionTileService } from '../../shared/services/productiontile.service';
import { Router } from '@angular/router';
import {Observable} from 'rxjs/Rx';
//import 'style-loader!./tiles.scss';
@Component({
selector: 'production-tiles',
styleUrls: ['./tile... | (id): void {
this.summary = 1;
document.getElementsByClassName('widgets')['0'].style.display = 'none';
document.getElementById("summary").style.display = 'block';
}
back_state():void{
this.summary = 0;
document.getElementsByClassName('widgets')['0'].style.display = 'block';
document.getElementById("summar... | summary_details | identifier_name |
sidebar.js | /** ***** BEGIN LICENSE BLOCK *****
*
* Copyright (C) 2019 Marc Ruiz Altisent. All rights reserved.
*
* This file is part of FoxReplace.
*
* FoxReplace 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, ... | () {
document.removeEventListener("DOMContentLoaded", onLoad);
document.getElementById("form").addEventListener("submit", onSubmit);
}
function onUnload() {
document.removeEventListener("unload", onUnload);
document.getElementById("form").removeEventListener("submit", onSubmit);
}
function onSubmit(event) {
... | onLoad | identifier_name |
sidebar.js | /** ***** BEGIN LICENSE BLOCK *****
*
* Copyright (C) 2019 Marc Ruiz Altisent. All rights reserved.
*
* This file is part of FoxReplace.
*
* FoxReplace 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, ... | document.addEventListener("unload", onUnload); | random_line_split | |
sidebar.js | /** ***** BEGIN LICENSE BLOCK *****
*
* Copyright (C) 2019 Marc Ruiz Altisent. All rights reserved.
*
* This file is part of FoxReplace.
*
* FoxReplace 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, ... |
function onSubmit(event) {
event.preventDefault(); // we just want to get the values, we don't want to submit anything
let serialized = $('#form').serializeArray();
let formValues = {};
for (let item of serialized) {
formValues[item.name] = item.value;
}
// Checkbox values are returned as 'on' when ... | {
document.removeEventListener("unload", onUnload);
document.getElementById("form").removeEventListener("submit", onSubmit);
} | identifier_body |
sampler.py | # coding: utf-8
import random
import json
def | (tar_f=None, res_f=None, res_size=50, start_pos=0, end_pos=100):
buff = []
if tar_f:
with open(tar_f, 'r') as reader:
cnt = 0
for line in reader:
buff.append(json.dumps({'text': line, 'id': cnt}))
if cnt > end_pos:
break
... | full_sample | identifier_name |
sampler.py | # coding: utf-8
import random | import json
def full_sample(tar_f=None, res_f=None, res_size=50, start_pos=0, end_pos=100):
buff = []
if tar_f:
with open(tar_f, 'r') as reader:
cnt = 0
for line in reader:
buff.append(json.dumps({'text': line, 'id': cnt}))
if cnt > end_pos:
... | random_line_split | |
sampler.py | # coding: utf-8
import random
import json
def full_sample(tar_f=None, res_f=None, res_size=50, start_pos=0, end_pos=100):
|
if __name__ == '__main__':
test_f = './template/title_template'
full_sample(test_f, res_size=50, start_pos=0, end_pos=2000)
| buff = []
if tar_f:
with open(tar_f, 'r') as reader:
cnt = 0
for line in reader:
buff.append(json.dumps({'text': line, 'id': cnt}))
if cnt > end_pos:
break
cnt += 1
target_field = buff[start_pos: end_pos]
... | identifier_body |
sampler.py | # coding: utf-8
import random
import json
def full_sample(tar_f=None, res_f=None, res_size=50, start_pos=0, end_pos=100):
buff = []
if tar_f:
with open(tar_f, 'r') as reader:
cnt = 0
for line in reader:
buff.append(json.dumps({'text': line, 'id': cnt}))
... | test_f = './template/title_template'
full_sample(test_f, res_size=50, start_pos=0, end_pos=2000) | conditional_block | |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2013 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free ... | (object):
__str__ = lambda x: x.__unicode__()
import binascii
def to_hex(x):
return binascii.hexlify(x).decode('utf-8')
else: # pragma: no cover
PY2, PY3 = True, False
__all__ = [str(s) for s in __all__] # fix imports for python2
unicode_text_type = unicode
native_text_type ... | UnicodeMixin | identifier_name |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2013 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free ... |
elif infotype == 'hash_mpc':
from guessit.hash_mpc import hash_file
try:
result.append(Guess({infotype: hash_file(filename)},
confidence=1.0))
except Exception as e:
log.warning('Could not compute MPC-style... | result.append(_guess_filename(filename, options, **kwargs)) | conditional_block |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2013 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free ... |
class UnicodeMixin(object):
__str__ = lambda x: unicode(x).encode('utf-8')
def to_hex(x):
return x.encode('hex')
range = xrange
from guessit.guess import Guess, merge_all
from guessit.language import Language
from guessit.matcher import IterativeMatcher
from guessit.textutils import cl... | if isinstance(x, unicode):
return x.encode('utf-8')
if isinstance(x, list):
return [s(y) for y in x]
if isinstance(x, tuple):
return tuple(s(y) for y in x)
if isinstance(x, dict):
return dict((s(key), s(value)) for key, value in x.items())
... | identifier_body |
__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2013 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free ... | from guessit.hash_mpc import hash_file
try:
result.append(Guess({infotype: hash_file(filename)},
confidence=1.0))
except Exception as e:
log.warning('Could not compute MPC-style hash because: %s' % e)
elif i... | result.append(_guess_filename(filename, options, **kwargs))
elif infotype == 'hash_mpc': | random_line_split |
sha3.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | // when
let hash = sha3(&mut file).unwrap();
// then
assert_eq!(format!("{:?}", hash), "68371d7e884c168ae2022c82bd837d51837718a7f7dfb7aa3f753074a35e1d87");
}
} | random_line_split | |
sha3.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | () {
// given
use devtools::RandomTempPath;
let path = RandomTempPath::new();
// Prepare file
{
let mut file = fs::File::create(&path).unwrap();
file.write_all(b"something").unwrap();
}
let mut file = BufReader::new(fs::File::open(&path).unwrap());
// when
let hash = sha3(&mut file).unwrap();
... | should_sha3_a_file | identifier_name |
sha3.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
sha3.update(&input[0..some]);
}
sha3.finalize(&mut output);
Ok(output.into())
}
#[cfg(test)]
mod tests {
use std::fs;
use std::io::{Write, BufReader};
use super::*;
#[test]
fn sha3_empty() {
assert_eq!([0u8; 0].sha3(), SHA3_EMPTY);
}
#[test]
fn sha3_as() {
assert_eq!([0x41u8; 32].sha3(), From::from... | {
break;
} | conditional_block |
sha3.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
fn sha3_into(&self, dest: &mut [u8]) {
let input: &[u8] = self.as_ref();
unsafe {
sha3_256(dest.as_mut_ptr(), dest.len(), input.as_ptr(), input.len());
}
}
}
/// Calculate SHA3 of given stream.
pub fn sha3(r: &mut io::BufRead) -> Result<H256, io::Error> {
let mut output = [0u8; 32];
let mut input = [0u8... | {
let mut ret: H256 = H256::zero();
self.sha3_into(&mut *ret);
ret
} | identifier_body |
mod.rs | #[cfg(test)]
use game;
use ai;
use ai::run_match;
use constants::LINES;
use std::sync::Arc; | fn match_mc() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player = ai::mc::MonteCarloAI::new(1000);
let mut black_player = ai::mc::MonteCarloAI::new(1000);
run_match(structure, &mut white_player, &mut black_player);
}
#[test]
fn match_mc_tree() {
let structure = Arc::new... |
#[test] | random_line_split |
mod.rs | #[cfg(test)]
use game;
use ai;
use ai::run_match;
use constants::LINES;
use std::sync::Arc;
#[test]
fn match_mc() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player = ai::mc::MonteCarloAI::new(1000);
let mut black_player = ai::mc::MonteCarloAI::new(1000);
run_match(structure... |
#[test]
fn subset_coherence() {
// This is a property based test, see QuickCheck for more information.
use rand::{thread_rng, Rng};
let mut rng = thread_rng();
for _ in 0..10000 {
// Ensure that all positions returned by the Subset iterator are
// contained in the Subset.
let... | {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
let mut black_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
run_match(structure,... | identifier_body |
mod.rs | #[cfg(test)]
use game;
use ai;
use ai::run_match;
use constants::LINES;
use std::sync::Arc;
#[test]
fn match_mc() {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player = ai::mc::MonteCarloAI::new(1000);
let mut black_player = ai::mc::MonteCarloAI::new(1000);
run_match(structure... | () {
let structure = Arc::new(game::Structure::new(&LINES));
let mut white_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
let mut black_player =
ai::tree::TreeJudgementAI::new(structure.clone(), 2, ai::value::Simple::Subsets);
run_match(structu... | match_tree | identifier_name |
session.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | () -> SMBTransactionSessionSetup {
return SMBTransactionSessionSetup {
request_host: None,
response_host: None,
ntlmssp: None,
krb_ticket: None,
}
}
}
impl SMBState {
pub fn new_sessionsetup_tx(&mut self, hdr: SMBCommonHdr)
-> &mut SMBTran... | new | identifier_name |
session.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | return SMBTransactionSessionSetup {
request_host: None,
response_host: None,
ntlmssp: None,
krb_ticket: None,
}
}
}
impl SMBState {
pub fn new_sessionsetup_tx(&mut self, hdr: SMBCommonHdr)
-> &mut SMBTransaction
{
let mut tx = ... | }
impl SMBTransactionSessionSetup {
pub fn new() -> SMBTransactionSessionSetup { | random_line_split |
session.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
}
| {
for tx in &mut self.transactions {
let hit = tx.hdr.compare(&hdr) && match tx.type_data {
Some(SMBTransactionTypeData::SESSIONSETUP(_)) => { true },
_ => { false },
};
if hit {
return Some(tx);
}
}
... | identifier_body |
Config.js | /**
* afterglow - An easy to integrate HTML5 video player with lightbox support.
* @link http://afterglowplayer.com
* @license MIT
*/
'use strict';
import Util from '../lib/Util';
class Config {
constructor(videoelement, skin = 'afterglow'){
return this.init(videoelement, skin);
}
init(videoelement, skin =... |
}
/**
* Sets options needed for vimeo to work and replaces the sources with the correct vimeo source
*/
setVimeoOptions(){
this.options.techOrder = ["vimeo"];
this.options.sources = [{
"type": "video/vimeo",
"src": "https://vimeo.com/"+this.getPlayerAttributeFromVideoElement('vimeo-id')
}];
}
/*... | {
this.options.youtube = {
'iv_load_policy' : 3,
modestbranding: 1
};
} | conditional_block |
Config.js | /**
* afterglow - An easy to integrate HTML5 video player with lightbox support.
* @link http://afterglowplayer.com
* @license MIT
*/
'use strict';
import Util from '../lib/Util';
class Config {
constructor(videoelement, skin = 'afterglow'){
return this.init(videoelement, skin);
}
init(videoelement, skin =... | // Default tech order
this.options.techOrder = ["Html5"];
// Some default player parameters
this.options.preload = this.getPlayerAttributeFromVideoElement('preload','auto');
this.options.autoplay = this.getPlayerAttributeFromVideoElement('autoplay');
this.options.poster = this.getPlayerAttributeFromVideoE... | setDefaultOptions(){
// Controls needed for the player
this.options.controls = true;
| random_line_split |
Config.js | /**
* afterglow - An easy to integrate HTML5 video player with lightbox support.
* @link http://afterglowplayer.com
* @license MIT
*/
'use strict';
import Util from '../lib/Util';
class Config {
constructor(videoelement, skin = 'afterglow'){
return this.init(videoelement, skin);
}
init(videoelement, skin =... |
/**
* Sets some basic options based on the videoelement's attributes
* @return {void}
*/
setDefaultOptions(){
// Controls needed for the player
this.options.controls = true;
// Default tech order
this.options.techOrder = ["Html5"];
// Some default player parameters
this.options.preload = this... | {
// Check for the video element
if(videoelement == undefined){
console.error('Please provide a proper video element to afterglow');
}
else{
// Set videoelement
this.videoelement = videoelement;
// Prepare the options container
this.options = {};
// Set the skin
this.skin = skin;
// ... | identifier_body |
Config.js | /**
* afterglow - An easy to integrate HTML5 video player with lightbox support.
* @link http://afterglowplayer.com
* @license MIT
*/
'use strict';
import Util from '../lib/Util';
class Config {
| (videoelement, skin = 'afterglow'){
return this.init(videoelement, skin);
}
init(videoelement, skin = 'afterglow'){
// Check for the video element
if(videoelement == undefined){
console.error('Please provide a proper video element to afterglow');
}
else{
// Set videoelement
this.videoelement = vi... | constructor | identifier_name |
AlertTab.tsx | import React, { useEffect, useState } from 'react';
import Styled, { css, Keyframes, keyframes } from 'styled-components';
import { IAlertMessage } from '../../store/modules/common';
import Transition, { ENTERED, ENTERING, EXITED, EXITING, TransitionStatus } from 'react-transition-group/Transition';
const ScrollDownKe... | case ENTERING:
case ENTERED:
return animation(ScrollDownKeyFrames);
case EXITING:
case EXITED:
return animation(ScrollUpKeyFrames);
default:
return 'height: 0';
}
}}
`;
interface IProps extends IAlertMessage {
}
const AlertTab: React.FC<I... | line-height: 35px;
${({ state }) => {
switch (state) { | random_line_split |
0068_iaticheck.py | # -*- coding: utf-8 -*-
import django.db.models.deletion
from django.db import models, migrations
import akvo.rsr.fields
class | (migrations.Migration):
dependencies = [
('rsr', '0067_auto_20160412_1858'),
]
operations = [
migrations.CreateModel(
name='IatiCheck',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
... | Migration | identifier_name |
0068_iaticheck.py | # -*- coding: utf-8 -*-
import django.db.models.deletion
from django.db import models, migrations
import akvo.rsr.fields
class Migration(migrations.Migration):
dependencies = [
('rsr', '0067_auto_20160412_1858'),
]
operations = [
migrations.CreateModel(
name='IatiCheck',
... | 'verbose_name': 'IATI check',
'verbose_name_plural': 'IATI checks',
},
bases=(models.Model,),
),
] | ],
options={ | random_line_split |
0068_iaticheck.py | # -*- coding: utf-8 -*-
import django.db.models.deletion
from django.db import models, migrations
import akvo.rsr.fields
class Migration(migrations.Migration):
| dependencies = [
('rsr', '0067_auto_20160412_1858'),
]
operations = [
migrations.CreateModel(
name='IatiCheck',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('status', models.P... | identifier_body | |
bench_serialization.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request};
use raft::eraftpb::Entry;
use protobuf::{self, Message};
use rand::{thread_rng, RngCore};
use test::Bencher;
use collections::HashMap;
#[inline]
fn gen_rand_str(len: usize) -> Vec<u8> {
... | b.iter(|| {
encode(&map);
});
}
#[bench]
fn bench_decode_two(b: &mut Bencher) {
let key_for_lock = gen_rand_str(30);
let value_for_lock = gen_rand_str(10);
let key_for_data = gen_rand_str(30);
let value_for_data = gen_rand_str(256);
let mut map: HashMap<&[u8], &[u8]> = HashMap::defa... | map.insert(&key_for_data, &value_for_data); | random_line_split |
bench_serialization.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request};
use raft::eraftpb::Entry;
use protobuf::{self, Message};
use rand::{thread_rng, RngCore};
use test::Bencher;
use collections::HashMap;
#[inline]
fn gen_rand_str(len: usize) -> Vec<u8> {
... |
#[bench]
fn bench_decode_one(b: &mut Bencher) {
let key = gen_rand_str(30);
let value = gen_rand_str(256);
let mut map: HashMap<&[u8], &[u8]> = HashMap::default();
map.insert(&key, &value);
let data = encode(&map);
b.iter(|| {
decode(&data);
});
}
#[bench]
fn bench_encode_two(b: &... | {
let key = gen_rand_str(30);
let value = gen_rand_str(256);
let mut map: HashMap<&[u8], &[u8]> = HashMap::default();
map.insert(&key, &value);
b.iter(|| {
encode(&map);
});
} | identifier_body |
bench_serialization.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::raft_cmdpb::{CmdType, RaftCmdRequest, Request};
use raft::eraftpb::Entry;
use protobuf::{self, Message};
use rand::{thread_rng, RngCore};
use test::Bencher;
use collections::HashMap;
#[inline]
fn gen_rand_str(len: usize) -> Vec<u8> {
... | (b: &mut Bencher) {
let key_for_lock = gen_rand_str(30);
let value_for_lock = gen_rand_str(10);
let key_for_data = gen_rand_str(30);
let value_for_data = gen_rand_str(256);
let mut map: HashMap<&[u8], &[u8]> = HashMap::default();
map.insert(&key_for_lock, &value_for_lock);
map.insert(&key_fo... | bench_decode_two | identifier_name |
extensions.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | (self, **kwds):
# LOG.debug("extensions constructor: %s" % kwds)
super(Extensions, self).__init__(**kwds)
| __init__ | identifier_name |
extensions.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | """extensions resource"""
extension_links = [common_types.Link]
"""This attribute contains Links to extension resources that contain
information about the extensions supported by this Platform."""
def __init__(self, **kwds):
# LOG.debug("extensions constructor: %s" % kwds)
super(Extens... | identifier_body | |
extensions.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | def __init__(self, **kwds):
# LOG.debug("extensions constructor: %s" % kwds)
super(Extensions, self).__init__(**kwds) | """This attribute contains Links to extension resources that contain
information about the extensions supported by this Platform."""
| random_line_split |
vi.js | /**
* @Project NUKEVIET 4.x
* @Author Mr.Thang (kid.apt@gmail.com) | toolbar : 'Dán HTMl để tải ảnh về máy chủ',
tooltip : 'Dán bài viết để tải hình ảnh về máy chủ',
content_html: 'Nội dung cần tải hình ảnh',
url_path_save: 'Đường dẫn lưu trữ hình ảnh',
pasteMsg: 'Hãy dán nội dung vào trong khung bên dưới, sử dụng tổ hợp phím (<STRONG>Ctrl/Cmd+V</STRONG>) và nhấn v... | * @License GNU/GPL version 2 or any later version
* @Createdate 16-03-2015 12:55
*/
CKEDITOR.plugins.setLang('tbvdownload', 'vi', { | random_line_split |
profiling.py | from __future__ import absolute_import, division, unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from debug_toolbar.panels import Panel
from debug_toolbar import settings as dt_settings
import cProfile
from pstats import Stats
from colorsys impor... | (self):
cc, nc, tt, ct = self.stats
return self.stats[3]
def tottime_per_call(self):
cc, nc, tt, ct = self.stats
if nc == 0:
return 0
return tt / nc
def cumtime_per_call(self):
cc, nc, tt, ct = self.stats
if cc == 0:
return 0
... | cumtime | identifier_name |
profiling.py | from __future__ import absolute_import, division, unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from debug_toolbar.panels import Panel
from debug_toolbar import settings as dt_settings
import cProfile
from pstats import Stats
from colorsys impor... | if not hasattr(self, 'profiler'):
return None
# Could be delayed until the panel content is requested (perf. optim.)
self.profiler.create_stats()
self.stats = DjangoDebugToolbarStats(self.profiler)
self.stats.calc_callees()
root = FunctionCall(self.stats, self.stats.... | identifier_body | |
profiling.py | from __future__ import absolute_import, division, unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from debug_toolbar.panels import Panel
from debug_toolbar import settings as dt_settings
import cProfile
from pstats import Stats
from colorsys impor... | self.stats = DjangoDebugToolbarStats(self.profiler)
self.stats.calc_callees()
root = FunctionCall(self.stats, self.stats.get_root_func(), depth=0)
func_list = []
self.add_node(func_list,
root,
dt_settings.CONFIG['PROFILER_MAX_DEPTH'],... | # Could be delayed until the panel content is requested (perf. optim.)
self.profiler.create_stats() | random_line_split |
profiling.py | from __future__ import absolute_import, division, unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from debug_toolbar.panels import Panel
from debug_toolbar import settings as dt_settings
import cProfile
from pstats import Stats
from colorsys impor... |
def subfuncs(self):
i = 0
h, s, v = self.hsv
count = len(self.statobj.all_callees[self.func])
for func, stats in self.statobj.all_callees[self.func].items():
i += 1
h1 = h + (i / count) / (self.depth + 1)
if stats[3] == 0:
s1 = 0
... | file_name, line_num, method = self.func
idx = file_name.find('/site-packages/')
if idx > -1:
file_name = file_name[(idx + 14):]
file_path, file_name = file_name.rsplit(os.sep, 1)
return mark_safe(
'<span class="path">{0}/</span>'
... | conditional_block |
WhoObserver.py | from FaustBot.Communication import Connection
from FaustBot.Model.RemoteUser import RemoteUser
from FaustBot.Modules.MagicNumberObserverPrototype import MagicNumberObserverPrototype
from FaustBot.Modules.ModuleType import ModuleType
from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype
from FaustBot.... |
self.pending_whos = []
def update_on_ping(self, data, connection: Connection):
if self.pings_seen % 90 == 0: # 90 * 2 min = 3 Stunden
connection.raw_send('WHO ' + connection.details.get_channel())
self.pings_seen += 1
| self.user_list.add_user(remuser) | conditional_block |
WhoObserver.py | from FaustBot.Communication import Connection
from FaustBot.Model.RemoteUser import RemoteUser
from FaustBot.Modules.MagicNumberObserverPrototype import MagicNumberObserverPrototype
from FaustBot.Modules.ModuleType import ModuleType
from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype
from FaustBot.... |
def update_on_magic_number(self, data, connection):
if data['number'] == '352': # RPL_WHOREPLY
self.input_who(data, connection)
elif data['number'] == '315': # RPL_ENDOFWHO
self.end_who()
def input_who(self, data, connection: Connection):
# target #channel us... | return [ModuleType.ON_MAGIC_NUMBER, ModuleType.ON_PING] | identifier_body |
WhoObserver.py | from FaustBot.Communication import Connection
from FaustBot.Model.RemoteUser import RemoteUser
from FaustBot.Modules.MagicNumberObserverPrototype import MagicNumberObserverPrototype
from FaustBot.Modules.ModuleType import ModuleType
from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype
from FaustBot.... | ():
return None
def __init__(self, user_list: UserList):
super().__init__()
self.user_list = user_list
self.pings_seen = 1
self.pending_whos = []
@staticmethod
def get_module_types():
return [ModuleType.ON_MAGIC_NUMBER, ModuleType.ON_PING]
def update_on... | help | identifier_name |
WhoObserver.py | from FaustBot.Communication import Connection
from FaustBot.Model.RemoteUser import RemoteUser
from FaustBot.Modules.MagicNumberObserverPrototype import MagicNumberObserverPrototype | from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype
from FaustBot.Modules.UserList import UserList
class WhoObserver(MagicNumberObserverPrototype, PingObserverPrototype):
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
def __init__(... | from FaustBot.Modules.ModuleType import ModuleType | random_line_split |
data_Error_Num__JOIN_5.js | var nodes = new vis.DataSet([
/* {id: a, label: b, ...}, */
|
var edges = new vis.DataSet([
/* {from: id_a, to: id_b}, */
{from: '5002', to: '5003'},
{from: '5001', to: '5003'},
{from: '5003', to: '5000'}
]); | {id: '5000', label: 'A1\n#NUM!', color: '#31b0d5', title: 'Name: A1<br>Alias: null<br>Value: #NUM!<br>Type: CELL_WITH_FORMULA<br>Id: 5000<br>Formula Expression: Formula String: COMBIN(VALUE, VALUE); Formula Values: COMBIN(8.0, 6.0); Formula Ptg: ; Ptgs: Index in Ptgs: 0 <br>Source Object Id: com.dataart.spreadsheetana... | random_line_split |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn | () {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect... | main | identifier_name |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() | {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("F... | identifier_body | |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess... | conditional_block | ||
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess... | break;
}
}
}
} | Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!"); | random_line_split |
_font.py | import _plotly_utils.basevalidators
class FontValidator(_plotly_utils.basevalidators.CompoundValidator):
def | (self, plotly_name="font", parent_name="box.hoverlabel", **kwargs):
super(FontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Font"),
data_docs=kwargs.pop(
"data_docs",
... | __init__ | identifier_name |
_font.py | import _plotly_utils.basevalidators
class FontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="font", parent_name="box.hoverlabel", **kwargs):
super(FontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | for color .
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple ... | Sets the source reference on Chart Studio Cloud | random_line_split |
_font.py | import _plotly_utils.basevalidators
class FontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="font", parent_name="box.hoverlabel", **kwargs):
| super(FontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Font"),
data_docs=kwargs.pop(
"data_docs",
"""
color
colorsrc
Sets ... | identifier_body | |
sensor-threat-triage.module.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... |
@NgModule ({
imports: [ SharedModule, SensorRuleEditorModule ],
declarations: [ SensorThreatTriageComponent ],
exports: [ SensorThreatTriageComponent ]
})
export class SensorThreatTriageModule {} | import {SensorRuleEditorModule} from './rule-editor/sensor-rule-editor.module';
| random_line_split |
sensor-threat-triage.module.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | {}
| SensorThreatTriageModule | identifier_name |
connectToStore.tsx | import * as React from 'react'
import {Component, ComponentClass, createElement} from 'react'
import * as PropTypes from 'prop-types'
import {connect} from 'react-redux' |
function connectToStore<P>(component:ComponentClass<P>):ComponentClass<P> {
type PS = P & {store:Store}
const mapStateToProps = (state:ComputedState, ownProps:PS):P => ({
...Object(ownProps),
...state
})
const WrappedComponent = (props:P) => createElement(component, props)
const ConnectedComponent ... | import {Store} from '../store'
import ComputedState from '../model/ComputedState' | random_line_split |
connectToStore.tsx | import * as React from 'react'
import {Component, ComponentClass, createElement} from 'react'
import * as PropTypes from 'prop-types'
import {connect} from 'react-redux'
import {Store} from '../store'
import ComputedState from '../model/ComputedState'
function connectToStore<P>(component:ComponentClass<P>):ComponentCl... |
export default connectToStore | {
type PS = P & {store:Store}
const mapStateToProps = (state:ComputedState, ownProps:PS):P => ({
...Object(ownProps),
...state
})
const WrappedComponent = (props:P) => createElement(component, props)
const ConnectedComponent = connect(mapStateToProps)(WrappedComponent)
return class ConnectToStore... | identifier_body |
connectToStore.tsx | import * as React from 'react'
import {Component, ComponentClass, createElement} from 'react'
import * as PropTypes from 'prop-types'
import {connect} from 'react-redux'
import {Store} from '../store'
import ComputedState from '../model/ComputedState'
function connectToStore<P>(component:ComponentClass<P>):ComponentCl... | () {
const {rrnhStore} = this.context
return <ConnectedComponent store={rrnhStore} {...this.props} />
}
}
}
export default connectToStore | render | identifier_name |
PRESUBMIT.py | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for changes affecting tools/perf/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about th... |
def _CheckWprShaFiles(input_api, output_api):
"""Check whether the wpr sha files have matching URLs."""
from catapult_base import cloud_storage
results = []
for affected_file in input_api.AffectedFiles(include_deletes=False):
filename = affected_file.AbsoluteLocalPath()
if not filename.endswith('wpr.... | """Performs common checks, which includes running pylint."""
results = []
old_sys_path = sys.path
try:
# Modules in tools/perf depend on telemetry.
sys.path = [os.path.join(os.pardir, 'telemetry')] + sys.path
results.extend(input_api.canned_checks.RunPylint(
input_api, output_api, black_list=[... | identifier_body |
PRESUBMIT.py | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for changes affecting tools/perf/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about th... |
expected_hash = cloud_storage.ReadHash(filename)
is_wpr_file_uploaded = any(
cloud_storage.Exists(bucket, expected_hash)
for bucket in cloud_storage.BUCKET_ALIASES.itervalues())
if not is_wpr_file_uploaded:
wpr_filename = filename[:-5]
results.append(output_api.PresubmitError(
... | continue | conditional_block |
PRESUBMIT.py | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for changes affecting tools/perf/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about th... | benchmarks_modified = _IsBenchmarksModified(change)
rietveld_obj = cl.RpcServer()
issue = cl.issue
original_description = rietveld_obj.get_description(issue)
if not benchmarks_modified or re.search(
r'^CQ_EXTRA_TRYBOTS=.*', original_description, re.M | re.I):
return []
results = []
bots = [
... | This hook adds extra try bots list to the CL description in order to run
Telemetry benchmarks on Perf trybots in addtion to CQ trybots if the CL
contains any changes to Telemetry benchmarks.
""" | random_line_split |
PRESUBMIT.py | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for changes affecting tools/perf/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about th... | (input_api, output_api):
report = []
report.extend(_CommonChecks(input_api, output_api))
return report
def _IsBenchmarksModified(change):
"""Checks whether CL contains any modification to Telemetry benchmarks."""
for affected_file in change.AffectedFiles():
affected_file_path = affected_file.LocalPath()... | CheckChangeOnCommit | identifier_name |
simpleDataTable.ts | /**
* @module DataTable
*/
module DataTable {
export class SimpleDataTable {
public restrict = 'A';
public scope = {
config: '=hawtioSimpleTable',
target: '@',
showFiles: '@'
};
public link:(scope, element, attrs) => any;
constructor(public $compile) {
// necessary to... | ($scope, $element, $attrs) {
var defaultPrimaryKeyFn = (entity, idx) => {
// default function to use id/_id/name as primary key, and fallback to use index
return entity["id"] || entity["_id"] || entity["name"] || idx;
};
var config = $scope.config;
var dataName = config.data |... | doLink | identifier_name |
simpleDataTable.ts | /**
* @module DataTable
*/
module DataTable {
export class SimpleDataTable {
public restrict = 'A';
public scope = {
config: '=hawtioSimpleTable',
target: '@',
showFiles: '@'
};
public link:(scope, element, attrs) => any;
constructor(public $compile) {
// necessary to... | var spk = primaryKeyFn(s, s.index);
return angular.equals(rpk, spk);
});
if (selected) {
// need to enrich entity with index, as we push row.entity to the re-selected items
row.entity.index = row.index;
reSelectedItems.push(row.entity);
... | var selected = config.selectedItems.some(s => { | random_line_split |
simpleDataTable.ts | /**
* @module DataTable
*/
module DataTable {
export class SimpleDataTable {
public restrict = 'A';
public scope = {
config: '=hawtioSimpleTable',
target: '@',
showFiles: '@'
};
public link:(scope, element, attrs) => any;
constructor(public $compile) {
// necessary to... |
$scope.$emit("hawtio.datatable." + dataName);
};
$scope.getClass = (field) => {
if ('sortInfo' in $scope.config) {
if ($scope.config.sortInfo.sortBy === field) {
if ($scope.config.sortInfo.ascending) {
return 'asc';
} else {
ret... | {
$scope.config.sortInfo.sortBy = field;
$scope.config.sortInfo.ascending = true;
} | conditional_block |
redux.js | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Redux"] = factory();
else
root["Redux"]... | *
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ },
/*... | * @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example | random_line_split |
redux.js | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Redux"] = factory();
else
root["Redux"]... | return action;
}
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for R... | listeners[i]();
}
| conditional_block |
redux.js | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Redux"] = factory();
else
root["Redux"]... | () {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice();
}
}
/**
* Reads the state tree managed by the store.
*
* @returns {any} The current state tree of your application.
*/
function getState() {
return currentState;
}
/**
* Ad... | ensureCanMutateNextListeners | identifier_name |
redux.js | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Redux"] = factory();
else
root["Redux"]... | **
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @param {Object} reducers An object whose valu... | Object.keys(reducers).forEach(function (key) {
var reducer = reducers[key];
var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT });
if (typeof initialState === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the stat... | identifier_body |
event.rs | use devices::{HatSwitch, JoystickState};
/// State of a Key or Button
#[derive(Eq, PartialEq, Clone, Debug)]
pub enum State {
Pressed,
Released,
}
/// Key Identifier (UK Keyboard Layout)
#[derive(Eq, PartialEq, Hash, Clone, Debug)]
pub enum KeyId {
Escape,
Return,
Backspace,
Lef... | if let Some(value_self) = self.hatswitch.clone() {
if value_self != value_other {
output.push(RawEvent::JoystickHatSwitchEvent(id, value_other));
}
}
}
output
}
} | if let Some(value_other) = other_state.hatswitch {
| random_line_split |
event.rs | use devices::{HatSwitch, JoystickState};
/// State of a Key or Button
#[derive(Eq, PartialEq, Clone, Debug)]
pub enum State {
Pressed,
Released,
}
/// Key Identifier (UK Keyboard Layout)
#[derive(Eq, PartialEq, Hash, Clone, Debug)]
pub enum KeyId {
Escape,
Return,
Backspace,
Lef... |
}
if let Some(value_other) = other_state.hatswitch {
if let Some(value_self) = self.hatswitch.clone() {
if value_self != value_other {
output.push(RawEvent::JoystickHatSwitchEvent(id, value_other));
}
}
}
... | {
output.push(RawEvent::JoystickAxisEvent(id, Axis::SLIDER, value));
} | conditional_block |
event.rs | use devices::{HatSwitch, JoystickState};
/// State of a Key or Button
#[derive(Eq, PartialEq, Clone, Debug)]
pub enum | {
Pressed,
Released,
}
/// Key Identifier (UK Keyboard Layout)
#[derive(Eq, PartialEq, Hash, Clone, Debug)]
pub enum KeyId {
Escape,
Return,
Backspace,
Left,
Right,
Up,
Down,
Space,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
... | State | identifier_name |
clv_medicament_template_history.py | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... |
@api.multi
def write(self, values):
if (not 'state' in values) and (not 'date' in values):
notes = values.keys()
self.insert_clv_medicament_template_history(self.id, self.state, notes)
return super(clv_medicament_template, self).write(values)
@api.one
def butto... | values = {
'medicament_template_id': medicament_template_id,
'state': state,
'notes': notes,
}
self.pool.get('clv_medicament.template.history').create(self._cr, self._uid, values) | conditional_block |
clv_medicament_template_history.py | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... |
@api.one
def set_to_draft(self, *args):
self.state = 'draft'
self.create_workflow()
return True
| self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.state = 'canceled'
self.insert_clv_medicament_template_history(self.id, 'canceled', '') | identifier_body |
clv_medicament_template_history.py | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | # You should have received a copy of the GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
from openerp import models, fields, api
from datetime import *
class clv_me... | # This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. ... | random_line_split |
clv_medicament_template_history.py | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | (self):
self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.state = 'revised'
self.insert_clv_medicament_template_history(self.id, 'revised', '')
@api.one
def button_waiting(self):
self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.state = 'waiting'
... | button_revised | identifier_name |
test.ts | const TestCommand = require('ember-cli/lib/commands/test');
import TestTask from '../tasks/test';
import {CliConfig} from '../models/config';
const NgCliTestCommand = TestCommand.extend({
availableOptions: [
{ name: 'watch', type: Boolean, default: true, aliases: ['w'] },
{ name: 'browsers', type: String },
... | if (!commandOptions.watch) {
// if not watching ensure karma is doing a single run
commandOptions.singleRun = true;
}
return testTask.run(commandOptions);
}
});
NgCliTestCommand.overrideCore = true;
export default NgCliTestCommand; | random_line_split | |
test.ts | const TestCommand = require('ember-cli/lib/commands/test');
import TestTask from '../tasks/test';
import {CliConfig} from '../models/config';
const NgCliTestCommand = TestCommand.extend({
availableOptions: [
{ name: 'watch', type: Boolean, default: true, aliases: ['w'] },
{ name: 'browsers', type: String },
... |
return testTask.run(commandOptions);
}
});
NgCliTestCommand.overrideCore = true;
export default NgCliTestCommand;
| {
// if not watching ensure karma is doing a single run
commandOptions.singleRun = true;
} | conditional_block |
client.rs | extern crate nanomsg;
use std::thread;
use std::time::Duration;
use std::sync::mpsc::*;
use super::media_player;
use super::protocol;
use self::nanomsg::{Socket, Protocol, Error};
pub fn run(rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>) | {
let mut subscriber = match Socket::new(Protocol::Sub) {
Ok(socket) => socket,
Err(err) => panic!("{}", err)
};
subscriber.subscribe(&String::from("").into_bytes()[..]);
subscriber.set_receive_timeout(500).unwrap();
match subscriber.connect("tcp://*:5555") {
Ok(_) => println!("Connected to se... | identifier_body | |
client.rs | extern crate nanomsg;
use std::thread;
use std::time::Duration;
use std::sync::mpsc::*;
use super::media_player;
use super::protocol;
use self::nanomsg::{Socket, Protocol, Error};
pub fn | (rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>) {
let mut subscriber = match Socket::new(Protocol::Sub) {
Ok(socket) => socket,
Err(err) => panic!("{}", err)
};
subscriber.subscribe(&String::from("").into_bytes()[..]);
subscriber.set_receive_timeout(500).unwrap();
match subscriber... | run | identifier_name |
client.rs | extern crate nanomsg;
use std::thread;
use std::time::Duration;
use std::sync::mpsc::*;
use super::media_player;
use super::protocol; |
pub fn run(rx_quit: Receiver<bool>, tx_state: Sender<media_player::State>) {
let mut subscriber = match Socket::new(Protocol::Sub) {
Ok(socket) => socket,
Err(err) => panic!("{}", err)
};
subscriber.subscribe(&String::from("").into_bytes()[..]);
subscriber.set_receive_timeout(500).unwrap();
matc... | use self::nanomsg::{Socket, Protocol, Error}; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.