file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
zmq_server.py | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 00:01:09 2021
@author: roman
"""
import zmq
import time
import sys
#import random
import os;
sys.path.append(os.path.join('..', '..', '..')) # analysis:ignore
#sys.path.append(r'C:\Github\xrt') # analysis:ignore
import numpy as np
#import matplotlib
#matplotlib.use... | send_zipped_pickle(socket, reply, protocol=2) | print("calculations complete. sending back results") | random_line_split |
fake_muscle_model.py | # -*- coding: utf-8 -*-
# Copyright (c) 2010 Jérémie DECOCK (http://www.jdhp.org)
import numpy as np
from pyarm import fig
class MuscleModel:
"Muscle model."
# CONSTANTS ###############################################################
name = 'Fake'
##################################################... | def compute_torque(self, angles, velocities, command):
"Compute the torque"
torque = np.zeros(2)
if len(command) > 2:
torque[0] = (command[0] - command[1])
torque[1] = (command[2] - command[3])
fig.append('command', command[0:4])
else:
... | g.subfig('command',
title='Command',
xlabel='time (s)',
ylabel='Command',
ylim=[-0.1, 1.1])
#legend=('shoulder +', 'shoulder -',
# 'elbow +', 'elbow -'))
| identifier_body |
fake_muscle_model.py | # -*- coding: utf-8 -*-
# Copyright (c) 2010 Jérémie DECOCK (http://www.jdhp.org)
import numpy as np
from pyarm import fig
class Mu | "Muscle model."
# CONSTANTS ###############################################################
name = 'Fake'
###########################################################################
def __init__(self):
# Init datas to plot
fig.subfig('command',
title='Command',... | scleModel:
| identifier_name |
fake_muscle_model.py | # -*- coding: utf-8 -*-
# Copyright (c) 2010 Jérémie DECOCK (http://www.jdhp.org)
import numpy as np
from pyarm import fig
class MuscleModel:
"Muscle model."
# CONSTANTS ###############################################################
name = 'Fake'
##################################################... | else:
torque = np.array(command)
fig.append('command', command[0:2])
return torque
| rque[0] = (command[0] - command[1])
torque[1] = (command[2] - command[3])
fig.append('command', command[0:4])
| conditional_block |
fake_muscle_model.py | # -*- coding: utf-8 -*-
# Copyright (c) 2010 Jérémie DECOCK (http://www.jdhp.org)
import numpy as np
from pyarm import fig
class MuscleModel:
"Muscle model."
# CONSTANTS ###############################################################
name = 'Fake' | # Init datas to plot
fig.subfig('command',
title='Command',
xlabel='time (s)',
ylabel='Command',
ylim=[-0.1, 1.1])
#legend=('shoulder +', 'shoulder -',
# 'elbow +', 'elbow -'))
d... |
###########################################################################
def __init__(self): | random_line_split |
ru.js | окенов доступа. Проверьте корректность ключа и секрета приложения.",
"Please provide a valid app key and secret." : "Пожалуйста укажите корректные ключ и секрет приложения.",
"Step 1 failed. Exception: %s" : "Шаг 1 неудачен. Исключение: %s",
"Step 2 failed. Exception: %s" : "Шаг 2 неудачен. Исключение: %s",... | "Credentials saving failed" : "Ошибка сохранения учетных данных",
"Credentials required" : "Требуются учетные данные",
"Save" : "Сохранить",
"Storage with id \"%i\" not found" : "Хранилище с идентификатором \"%i\" не найдено",
"Invalid backend or authentication mechanism class" : "Некорректный механ... | "Please enter the credentials for the {mount} mount" : "Пожалуйста укажите учетные данные для {mount}",
"Username" : "Имя пользователя",
"Password" : "Пароль",
"Credentials saved" : "Учетные данные сохранены", | random_line_split |
stack_depth_checker.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... |
}?;
}
Ok(())
}
pub struct StackDepthChecker;
impl BuildASTPass for StackDepthChecker {
fn run_pass(contract_ast: &mut ContractAST) -> ParseResult<()> {
check(&contract_ast.pre_expressions, 0)
}
}
| {
// Other symbolic expressions don't have depth
// impacts.
Ok(())
} | conditional_block |
stack_depth_checker.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... | ;
impl BuildASTPass for StackDepthChecker {
fn run_pass(contract_ast: &mut ContractAST) -> ParseResult<()> {
check(&contract_ast.pre_expressions, 0)
}
}
| StackDepthChecker | identifier_name |
stack_depth_checker.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program 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... |
pub struct StackDepthChecker;
impl BuildASTPass for StackDepthChecker {
fn run_pass(contract_ast: &mut ContractAST) -> ParseResult<()> {
check(&contract_ast.pre_expressions, 0)
}
}
| {
if depth >= (AST_CALL_STACK_DEPTH_BUFFER + MAX_CALL_STACK_DEPTH as u64) {
return Err(ParseErrors::ExpressionStackDepthTooDeep.into());
}
for expression in args.iter() {
match expression.pre_expr {
List(ref exprs) => check(exprs, depth + 1),
_ => {
//... | identifier_body |
stack_depth_checker.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify | // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Gene... | // it under the terms of the GNU General Public License as published by | random_line_split |
upload.py | import requests
import os
print('\n***数据与算法 GitHub自动上传脚本***\n')
username = input('输入你在GitHub上的用户名,如 Robert Ying:')
email = input('输入你注册GitHub用的Email:')
print('\n开始配置Git...')
os.system('git config --global user.name "' + username + '"')
os.system('git config --global user.email ' + email)
print('\n你输入的信息如下:')
os.syst... |
run_results = results[0]['run_results']
for i in range(len(run_results)):
md.write(
'|' + str(i + 1) + '|' + str(run_results[i][1]) + ' ms|' + str(run_results[i][2]) + ' KB|\n')
with open('./data-and-algorithms... | md.write('# ' + result['problem_title'] + '\n\n')
md.write(
'| # | 时间 | 内存 |\n')
md.write(
'|:----------:|:------------------------------:|:-----------... | random_line_split |
upload.py | import requests
import os
print('\n***数据与算法 GitHub自动上传脚本***\n')
username = input('输入你在GitHub上的用户名,如 Robert Ying:')
email = input('输入你注册GitHub用的Email:')
print('\n开始配置Git...')
os.system('git config --global user.name "' + username + '"')
os.system('git config --global user.email ' + email)
print('\n你输入的信息如下:')
os.syst... | d data-and-algorithms & git commit -m "Initial commit to ' +
result['problem_title'] + ' by ' + name)
already_walked_results.append(result['problem_title'])
continue
os.system('cd data-and-algorithms & git push origin master')
input('\n上传完成!如果发现没有效果,那么请重新再试一遍。回... | source.write(result['code'] + '\n')
os.system('cd data-and-algorithms & git add .')
os.system('c | conditional_block |
table_rowgroup.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... |
}
if let Some(collapsed_block_direction_border_width_for_table) =
collapsed_block_direction_border_widths_for_table.peek() {
self.collapsed_block_direction_border_widths_for_table
.push(**collapsed_block_direction_border_width_for_table)
}
}
}
im... | {
self.collapsed_block_direction_border_widths_for_table
.push(*collapsed_block_direction_border_width_for_table)
} | conditional_block |
table_rowgroup.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... |
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_th... | {
self.block_flow.generated_containing_block_size(flow)
} | identifier_body |
table_rowgroup.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... | (&self, print_tree: &mut PrintTree) {
self.block_flow.print_extra_flow_children(print_tree);
}
}
impl fmt::Debug for TableRowGroupFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableRowGroupFlow: {:?}", self.block_flow)
}
}
| print_extra_flow_children | identifier_name |
table_rowgroup.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMargi... | let inline_size_computer = InternalTable;
inline_size_computer.compute_used_inline_size(&mut self.block_flow,
shared_context,
containing_block_inline_size);
let collapsed_inline_direction... | random_line_split | |
repl2.js | /*eslint no-console: 0*/
import { sexpToString, lex } from '../src/lex'
import { parse } from '../src/parser'
import { desugar, analyze } from '../src/analyzer'
import { compile } from '../src/compiler'
export var repl_input
export var repl_input_li
export var output_list
export var __history_front
export var __histor... | (makeTeachpack) {
var programName = makeTeachpack ? prompt("What is the name of the teachpack?") : undefined
var aSource = repl_input.value
// run the local compiler
var debug = true
var sexp = lex(aSource, programName, debug)
var AST = parse(sexp, debug)
var ASTandPinfo = desugar(AST, undefined, debug)... | compileREPL | identifier_name |
repl2.js | /*eslint no-console: 0*/
import { sexpToString, lex } from '../src/lex'
import { parse } from '../src/parser'
import { desugar, analyze } from '../src/analyzer'
import { compile } from '../src/compiler'
export var repl_input
export var repl_input_li
export var output_list
export var __history_front
export var __histor... | console.log(response)
}
repl_input.value = ""; // clear the input
var temp = document.createElement("li"); // make an li element
temp.textContent = aSource; // stick the program's text in there
} | {
var programName = makeTeachpack ? prompt("What is the name of the teachpack?") : undefined
var aSource = repl_input.value
// run the local compiler
var debug = true
var sexp = lex(aSource, programName, debug)
var AST = parse(sexp, debug)
var ASTandPinfo = desugar(AST, undefined, debug)
var program =... | identifier_body |
repl2.js | /*eslint no-console: 0*/
import { sexpToString, lex } from '../src/lex'
import { parse } from '../src/parser'
import { desugar, analyze } from '../src/analyzer'
import { compile } from '../src/compiler'
export var repl_input
export var repl_input_li
export var output_list
export var __history_front
export var __histor... |
repl_input.value = ""; // clear the input
var temp = document.createElement("li"); // make an li element
temp.textContent = aSource; // stick the program's text in there
} | {
response.bytecode = (0, eval)('(' + response.bytecode + ')')
console.log(response)
} | conditional_block |
repl2.js | /*eslint no-console: 0*/
import { sexpToString, lex } from '../src/lex'
import { parse } from '../src/parser'
import { desugar, analyze } from '../src/analyzer'
import { compile } from '../src/compiler'
export var repl_input
export var repl_input_li
export var output_list
export var __history_front
export var __histor... | return __history_back.pop()
}
return current
}
export function getError(e) {
try {
var err = JSON.parse(e),
structuredErr = JSON.parse(err['structured-error'])
return structuredErr.message
} catch (JSONerror) {
console.log('!!!!!!!!!!!! FATAL ERROR !!!!!!!!!!!!!!!')
throw (e)
}
}
... | __history_back.push(current)
return __history_front.pop()
} else if (dir === -1 && __history_back.length > 0) {
__history_front.push(current) | random_line_split |
x86_64_unknown_hermit.rs | // Copyright 2016 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 ... | () -> TargetResult {
let mut base = super::hermit_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.linker = Some("x86_64-hermit-gcc".to_string());
base.max_atomic_width = Some(64);
Ok(Target {
llvm_targ... | target | identifier_name |
x86_64_unknown_hermit.rs | // Copyright 2016 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 ... | }
| {
let mut base = super::hermit_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.get_mut(&LinkerFlavor::Gcc).unwrap().push("-m64".to_string());
base.linker = Some("x86_64-hermit-gcc".to_string());
base.max_atomic_width = Some(64);
Ok(Target {
llvm_target: "x86_64-unknown... | identifier_body |
x86_64_unknown_hermit.rs | // Copyright 2016 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 ... | target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
options: base,
})
} | target_env: String::new(), | random_line_split |
index.js | import React from 'react';
import { connect } from 'react-redux';
import { searchActions } from '../../../core/search';
import ContentHeader from '../../components/content-header';
import Tracklist from '../../components/tracklist';
import PropTypes from 'prop-types';
export class SearchPage extends React.Component ... |
render() {
return (
<section>
<ContentHeader
section="Search Results"
title={this.props.query}
/>
<Tracklist />
</section>
);
}
}
//=====================================
// CONNECT
//-------------------------------------
const mapStateToProps = ... | {
if (nextProps.query !== this.props.query) {
this.props.loadSearchResults(nextProps.query);
}
} | identifier_body |
index.js | import React from 'react';
import { connect } from 'react-redux';
import { searchActions } from '../../../core/search';
import ContentHeader from '../../components/content-header';
import Tracklist from '../../components/tracklist';
import PropTypes from 'prop-types';
export class SearchPage extends React.Component ... |
render() {
return (
<section>
<ContentHeader
section="Search Results"
title={this.props.query}
/>
<Tracklist />
</section>
);
}
}
//=====================================
// CONNECT
//-------------------------------------
const mapStateToProps = (... | this.props.loadSearchResults(nextProps.query);
}
} | random_line_split |
index.js | import React from 'react';
import { connect } from 'react-redux';
import { searchActions } from '../../../core/search';
import ContentHeader from '../../components/content-header';
import Tracklist from '../../components/tracklist';
import PropTypes from 'prop-types';
export class | extends React.Component {
static propTypes = {
loadSearchResults: PropTypes.func.isRequired,
query: PropTypes.string.isRequired
};
componentWillMount() {
this.props.loadSearchResults(this.props.query);
}
componentWillUpdate(nextProps) {
if (nextProps.query !== this.props.query) {
this... | SearchPage | identifier_name |
index.js | import React from 'react';
import { connect } from 'react-redux';
import { searchActions } from '../../../core/search';
import ContentHeader from '../../components/content-header';
import Tracklist from '../../components/tracklist';
import PropTypes from 'prop-types';
export class SearchPage extends React.Component ... |
}
render() {
return (
<section>
<ContentHeader
section="Search Results"
title={this.props.query}
/>
<Tracklist />
</section>
);
}
}
//=====================================
// CONNECT
//-------------------------------------
const mapStateToProp... | {
this.props.loadSearchResults(nextProps.query);
} | conditional_block |
flat.js | 'use strict';
const chalk = require('chalk');
const EventEmitter = require('events').EventEmitter;
const FlatReporter = require('lib/reporters/flat-factory/flat');
const logger = require('lib/utils').logger;
const Events = require('lib/constants/events');
describe('Reporter#Flat', () => {
const sandbox = sinon.s... |
let test;
let emitter;
const emit = (event, data) => {
emitter.emit(Events.BEGIN);
if (event) {
emitter.emit(event, data);
}
emitter.emit(Events.END, {});
};
beforeEach(() => {
test = {
suite: {path: []},
state: {name: ... | random_line_split | |
flat.js | 'use strict';
const chalk = require('chalk');
const EventEmitter = require('events').EventEmitter;
const FlatReporter = require('lib/reporters/flat-factory/flat');
const logger = require('lib/utils').logger;
const Events = require('lib/constants/events');
describe('Reporter#Flat', () => {
const sandbox = sinon.s... |
emitter.emit(Events.END, {});
};
beforeEach(() => {
test = {
suite: {path: []},
state: {name: 'test'},
browserId: 0,
retriesLeft: 1
};
const reporter = new FlatReporter();
emitter = new EventEmitter();
reporter.... | {
emitter.emit(event, data);
} | conditional_block |
utils.rs | use nom::IResult;
use std::str;
use super::{BestTimes, ElmaError, Time, TimeEntry};
/// Parse top10 lists and return a vector of `TimeEntry`s
pub fn parse_top10(top10: &[u8]) -> Result<Vec<TimeEntry>, ElmaError> {
let mut list: Vec<TimeEntry> = vec![];
let times = LE::read_i32(&top10[0..4]);
for n in 0..t... |
let mut bytes = name.to_vec();
bytes.resize(pad, 0);
Ok(bytes)
}
#[cfg_attr(rustfmt, rustfmt_skip)]
named!(_boolean<bool>,
map!(le_i32, to_bool)
);
#[cfg_attr(rustfmt, rustfmt_skip)]
named_args!(_null_padded_string(n: usize)<&str>,
do_parse!(
s: map_res!(take_while!(is_nonzero), str::from_utf8) ... | {
return Err(ElmaError::PaddingTooShort(
(pad as isize - name.len() as isize) as isize,
));
} | conditional_block |
utils.rs | use nom::IResult;
use std::str;
use super::{BestTimes, ElmaError, Time, TimeEntry};
/// Parse top10 lists and return a vector of `TimeEntry`s
pub fn parse_top10(top10: &[u8]) -> Result<Vec<TimeEntry>, ElmaError> {
let mut list: Vec<TimeEntry> = vec![];
let times = LE::read_i32(&top10[0..4]);
for n in 0..t... |
pub(crate) fn is_nonzero(u: u8) -> bool {
to_bool(i32::from(u))
}
#[cfg(test)]
mod tests {
use super::null_padded_string;
use nom::verbose_errors::Context::Code;
use nom::Err::Error;
use nom::Err::Incomplete;
use nom::ErrorKind::CondReduce;
use nom::Needed::Size;
#[test]
fn null_p... | {
i != 0
} | identifier_body |
utils.rs | use nom::IResult;
use std::str;
use super::{BestTimes, ElmaError, Time, TimeEntry};
/// Parse top10 lists and return a vector of `TimeEntry`s
pub fn parse_top10(top10: &[u8]) -> Result<Vec<TimeEntry>, ElmaError> {
let mut list: Vec<TimeEntry> = vec![];
let times = LE::read_i32(&top10[0..4]);
for n in 0..t... | (u: u8) -> bool {
to_bool(i32::from(u))
}
#[cfg(test)]
mod tests {
use super::null_padded_string;
use nom::verbose_errors::Context::Code;
use nom::Err::Error;
use nom::Err::Incomplete;
use nom::ErrorKind::CondReduce;
use nom::Needed::Size;
#[test]
fn null_pad_string() {
asse... | is_nonzero | identifier_name |
utils.rs | use nom::IResult;
use std::str;
use super::{BestTimes, ElmaError, Time, TimeEntry};
/// Parse top10 lists and return a vector of `TimeEntry`s
pub fn parse_top10(top10: &[u8]) -> Result<Vec<TimeEntry>, ElmaError> {
let mut list: Vec<TimeEntry> = vec![];
let times = LE::read_i32(&top10[0..4]);
for n in 0..t... | let mut names_1 = vec![];
let mut names_2 = vec![];
for (n, entry) in best_times.single.iter().enumerate() {
if n < 10 {
times[n] = entry.time.into();
names_1.extend_from_slice(&string_null_pad(&entry.names.0, 15)?);
names_2.extend_from_slice(&string_null_pad(&ent... |
// Single-player times.
let single_times = best_times.single.len();
top10_bytes.write_i32::<LE>(if 10 < single_times { 10 } else { single_times } as i32)?;
let mut times = [0_i32; 10]; | random_line_split |
ubivalid.py | import struct
import binascii
import binwalk.core.plugin
class UBIValidPlugin(binwalk.core.plugin.Plugin):
'''
Helps validate UBI erase count signature results.
Checks header CRC and calculates jump value
'''
MODULES = ['Signature']
current_file=None
last_ec_hdr_offset = None
peb_size... | if result.file and result.description.lower().startswith('ubi erase count header'):
# Seek to and read the suspected UBI erase count header
fd = self.module.config.open_file(result.file.name, offset=result.offset)
ec_header = fd.read(1024)
fd.close()
result.... | identifier_body | |
ubivalid.py | import struct
import binascii
import binwalk.core.plugin
class UBIValidPlugin(binwalk.core.plugin.Plugin):
'''
Helps validate UBI erase count signature results.
Checks header CRC and calculates jump value
'''
MODULES = ['Signature']
current_file=None
last_ec_hdr_offset = None
peb_size... | (self, ec_header):
# Get the header's reported CRC value
header_crc = struct.unpack(">I", ec_header[60:64])[0]
# Calculate the actual CRC
calculated_header_crc = ~binascii.crc32(ec_header[0:60]) & 0xffffffff
# Make sure they match
return header_crc == calculated_header_... | _check_crc | identifier_name |
ubivalid.py | import struct
import binascii
import binwalk.core.plugin
class UBIValidPlugin(binwalk.core.plugin.Plugin):
'''
Helps validate UBI erase count signature results.
Checks header CRC and calculates jump value
'''
MODULES = ['Signature']
current_file=None
last_ec_hdr_offset = None
peb_size... |
if self.peb_size:
# If PEB size has been determined jump PEB size
result.jump = self.peb_size
else:
result.jump = 0
def scan(self, result):
if result.file and result.description.lower().startswith('ubi erase count header'):
# Seek to and read... | random_line_split | |
ubivalid.py | import struct
import binascii
import binwalk.core.plugin
class UBIValidPlugin(binwalk.core.plugin.Plugin):
'''
Helps validate UBI erase count signature results.
Checks header CRC and calculates jump value
'''
MODULES = ['Signature']
current_file=None
last_ec_hdr_offset = None
peb_size... |
else:
result.jump = 0
def scan(self, result):
if result.file and result.description.lower().startswith('ubi erase count header'):
# Seek to and read the suspected UBI erase count header
fd = self.module.config.open_file(result.file.name, offset=result.offset)
... | result.jump = self.peb_size | conditional_block |
assessments.py | for the specific language governing permissions and
# limitations under the License.
"""Classes and methods to manage all aspects of student assessments."""
__author__ = 'pgbovine@google.com (Philip Guo)'
import datetime
import logging
from models import courses
from models import models
from models import review
... | i += 1
# compute overall score after mandatory modules are done
if complete:
part_score = 0
tq = 0
for i in range(MAX_MODULES):
if ms[i] <> None:
part_score += mn[i] * ms[i]
tq += mn[i]
# todo - somar 0.5 antes do int?
overall_score = int((part_score/tq)+0.5)
... | mn = MODULE_QUESTIONS
# mm = MANDATORY_MODULES
#
overall_score = -1
ms = []
for i in range(1,MAX_MODULES+1):
course = 'a'+str(i)+'course'
ms.append(utils.get_score(student, course))
# get profile for this user - mandatary modules
valid = ValidStudent.get_valid(student.key().nam... | identifier_body |
assessments.py | for the specific language governing permissions and
# limitations under the License.
"""Classes and methods to manage all aspects of student assessments."""
__author__ = 'pgbovine@google.com (Philip Guo)'
import datetime
import logging
from models import courses
from models import models
from models import review
... | (
self, email, assessment_name,assessment_type,new_answers, score):
"""Stores answer and updates user scores.
Args:
email: the student's email address.
assessment_type: the type of the assessment (as stated in unit.csv).
new_answers: the latest set of answers... | update_assessment_transaction | identifier_name |
assessments.py |
# limitations under the License.
"""Classes and methods to manage all aspects of student assessments."""
__author__ = 'pgbovine@google.com (Philip Guo)'
import datetime
import logging
from models import courses
from models import models
from models import review
from models import student_work
from models import t... | self.template_value['error_code'] = (
'assignment_deadline_exceeded')
self.render('error.html')
return | random_line_split | |
assessments.py | for the specific language governing permissions and
# limitations under the License.
"""Classes and methods to manage all aspects of student assessments."""
__author__ = 'pgbovine@google.com (Philip Guo)'
import datetime
import logging
from models import courses
from models import models
from models import review
... |
return overall_score
def store_score(course, student, assessment_name, assessment_type,score):
"""Stores a student's score on a particular assessment.
Args:
course: the course containing the assessment.
student: the student whose data is stored.
assessment_type: the type of the ... | part_score = 0
tq = 0
for i in range(MAX_MODULES):
if ms[i] <> None:
part_score += mn[i] * ms[i]
tq += mn[i]
# todo - somar 0.5 antes do int?
overall_score = int((part_score/tq)+0.5) | conditional_block |
clientscriptAPI.js | // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
get_server_fields = function(method, arg, table_field, doc, dt, dn, allow_edit, call_back) {
frappe.dom.freeze();
if($.isPlainObject(arg)) arg = JSON.stringify(arg);
return $c('runserverobj',
args={'method': m... | cur_frm.field_map(fnames, function(field) { field.reqd = mandatory ? true : false; });
}
_f.Frm.prototype.toggle_display = function(fnames, show) {
cur_frm.field_map(fnames, function(field) { field.hidden = show ? 0 : 1; });
}
_f.Frm.prototype.call_server = function(method, args, callback) {
return $c_obj(cur_frm.... | random_line_split | |
clientscriptAPI.js | // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
get_server_fields = function(method, arg, table_field, doc, dt, dn, allow_edit, call_back) {
frappe.dom.freeze();
if($.isPlainObject(arg)) arg = JSON.stringify(arg);
return $c('runserverobj',
args={'method': m... |
}
_f.Frm.prototype.call = function(opts) {
var me = this;
if(!opts.doc) {
if(opts.method.indexOf(".")===-1)
opts.method = frappe.model.get_server_module_name(me.doctype) + "." + opts.method;
opts.original_callback = opts.callback;
opts.callback = function(r) {
if($.isPlainObject(r.message)) {
if(opt... | {
$.each(field, function(f, v) {
_set(f, v);
})
} | conditional_block |
interactiveToolConfig.js | (function() {
"use strict";
define(
function() {
var interactiveToolConfig = new function() {
var self = this;
//This is the default value for the textbox that holds the value of the number of units to buffer in the buffering tool
self.def... | text: "Kilometer",
value: esri.tasks.GeometryService.UNIT_KILOMETER
}, {
text: "Feet",
value: esri.tasks.GeometryService.UNIT_FOOT
}, {
text: "Meter",
value: esri.tasks... | random_line_split | |
ObjectInspector.js | /**
* @widgetClass Structure class
* @package wof.bizWidget
* @copyright author
* @Time: 13-9-21 下午08:46
*/
wof.bizWidget.ObjectInspector = function (root) {
this.getDomInstance().mousedown(function (event) {
event.stopPropagation();
});
};
wof.bizWidget.ObjectInspector.prototype =... | e {
jsonArray += '{"name" : "' + className + '","oid" : "' + id + '"}';
}
}
}
if (index == 0) {
return null;
}
return jsonArray += ']';
},
... | jsonArray += '{"name" : "' + className + '","oid" : "' + id + '"';
var childrenJson = convertInstanceToJson(children);
if (childrenJson) {
jsonArray += ',"children" : ' + childrenJson;
... | conditional_block |
ObjectInspector.js | /**
* @widgetClass Structure class
* @package wof.bizWidget
* @copyright author
* @Time: 13-9-21 下午08:46
*/
wof.bizWidget.ObjectInspector = function (root) {
this.getDomInstance().mousedown(function (event) {
event.stopPropagation();
});
};
wof.bizWidget.ObjectInspector.prototype =... | */
//----------必须实现----------
getData: function () {
return {
};
},
//----------必须实现----------
setData: function (data) {
}
}; | * getData/setData 方法定义
| random_line_split |
spacesfolder.py | ###############################################################################
#cyn.in is an open source Collaborative Knowledge Management Appliance that
#enables teams to seamlessly work together on files, documents and content in
#a secure central environment.
#
#cyn.in v2 an open source appliance is distrib... | (BaseClass):
__doc__ = BaseClass.__doc__ + "(customizable version)"
# portal_type = BaseClass.portal_type
# archetype_name = BaseClass.archetype_name
schema = schema
_at_rename_after_creation = True
# enable FTP/WebDAV and friends
PUT = BaseClass.PUT
registerATCT(SpacesFolder, ... | SpacesFolder | identifier_name |
spacesfolder.py | ###############################################################################
#cyn.in is an open source Collaborative Knowledge Management Appliance that
#enables teams to seamlessly work together on files, documents and content in
#a secure central environment.
#
#cyn.in v2 an open source appliance is distrib... | from Products.ATContentTypes.content.folder \
import ATFolder as BaseClass
from Products.ATContentTypes.content.folder \
import ATFolderSchema as DefaultSchema
from Products.ATContentTypes.content.base import registerATCT
from ubify.coretypes.config import PROJECTNAME
schema = DefaultSchema.copy()
... | ###############################################################################
from Products.Archetypes.atapi import *
| random_line_split |
spacesfolder.py | ###############################################################################
#cyn.in is an open source Collaborative Knowledge Management Appliance that
#enables teams to seamlessly work together on files, documents and content in
#a secure central environment.
#
#cyn.in v2 an open source appliance is distrib... |
registerATCT(SpacesFolder, PROJECTNAME)
| __doc__ = BaseClass.__doc__ + "(customizable version)"
# portal_type = BaseClass.portal_type
# archetype_name = BaseClass.archetype_name
schema = schema
_at_rename_after_creation = True
# enable FTP/WebDAV and friends
PUT = BaseClass.PUT | identifier_body |
conf.py | #
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import mock
MO... | random_line_split | ||
conf.py | configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import mock
MOCK_MODULES = ['numpy','six','six.moves','matplotlib','_csphi']
for mod in MOCK_MODULES:
|
import sphinx_bootstrap_theme
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../../'))
#pr... | sys.modules[mod] = mock.Mock() | conditional_block |
message-contract-generator.ts | import { Block } from "../codeGeneration/code-entity";
import { CodePrinter } from "../codeGeneration/code-printer";
export class | implements IServiceContractGenerator {
constructor(private $fs: IFileSystem,
private $messagesService: IMessagesService) {
}
public async generate(): Promise<IServiceContractClientCode> {
const interfacesFile = new Block();
const implementationsFile = new Block();
implementationsFile.writeLine("//");
im... | MessageContractGenerator | identifier_name |
message-contract-generator.ts | import { Block } from "../codeGeneration/code-entity";
import { CodePrinter } from "../codeGeneration/code-printer";
export class MessageContractGenerator implements IServiceContractGenerator {
constructor(private $fs: IFileSystem,
private $messagesService: IMessagesService) {
}
public async generate(): Promise<... |
const newBlock = new Block(`${key} ${separator} `);
newBlock.endingCharacter = endingSymbol;
this.generateFileRecursive(val, newPropertyValue + ".", newBlock, depth + 1, options);
block.addBlock(newBlock);
});
}
}
$injector.register("messageContractGenerator", MessageContractGenerator);
| {
const actualValue = options.shouldGenerateInterface ? "string" : `"${newPropertyValue}"`;
block.writeLine(`${key}${separator} ${actualValue}${endingSymbol}`);
newPropertyValue = propertyValue;
return;
} | conditional_block |
message-contract-generator.ts | import { Block } from "../codeGeneration/code-entity";
import { CodePrinter } from "../codeGeneration/code-printer";
export class MessageContractGenerator implements IServiceContractGenerator {
constructor(private $fs: IFileSystem,
private $messagesService: IMessagesService) {
}
public async generate(): Promise<... | });
}
}
$injector.register("messageContractGenerator", MessageContractGenerator); | random_line_split | |
message-contract-generator.ts | import { Block } from "../codeGeneration/code-entity";
import { CodePrinter } from "../codeGeneration/code-printer";
export class MessageContractGenerator implements IServiceContractGenerator {
constructor(private $fs: IFileSystem,
private $messagesService: IMessagesService) {
}
public async generate(): Promise<... | implementationBlock: CodeGeneration.IBlock = new Block(),
interfaceBlock: CodeGeneration.IBlock = new Block();
this.generateFileRecursive(jsonContents, "", implementationBlock, 0, { shouldGenerateInterface: false });
this.generateFileRecursive(jsonContents, "", interfaceBlock, 0, { shouldGenerateInterfac... | {
const interfacesFile = new Block();
const implementationsFile = new Block();
implementationsFile.writeLine("//");
implementationsFile.writeLine("// automatically generated code; do not edit manually!");
implementationsFile.writeLine("//");
implementationsFile.writeLine("/* tslint:disable:all */");
impl... | identifier_body |
mock_env.js | /**
* @license
* Copyright 2014 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 requir... | global.registerService(lf.service.CACHE, this.cache);
global.registerService(lf.service.INDEX_STORE, this.indexStore);
global.registerService(lf.service.OBSERVER_REGISTRY, this.observerRegistry);
return this.indexStore.init(this.schema);
}, this));
};
/** @return {!IThenable} */
lf.testing.MockEnv.p... | global.registerService(lf.service.RUNNER, this.runner); | random_line_split |
mock_env.js | /**
* @license
* Copyright 2014 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 requir... |
var tx = this.store.createTx(
lf.TransactionType.READ_WRITE,
new lf.cache.Journal(lf.Global.get(), [table]));
var store = tx.getTable(table.getName(), table.deserializeRow);
store.put(rows);
// Updating journals, which will automatically update indices.
tx.getJournal().insert(table, rows);
r... | {
rows[i] = table.createRow({
'id': i.toString(),
'name': 'dummyName' + i.toString()
});
rows[i].assignRowId(i);
} | conditional_block |
responsible.component.ts | import { Component} from '@angular/core';
import { BaseComponent } from '../../catalogs/base.component';
import gql from 'graphql-tag';
const responsibleCatalogs = gql`
query {
positions { id name description }
users { id name }
}
`;
@Component({
selector: 'crm-responsible',
templateUrl: './responsi... | () {
this.catalogName = 'Responsible';
this.baseApi = 'Responsible/';
}
addColumns() {
this.columns.push({ name: 'name', label: 'Name' });
this.columns.push({ name: 'eMail', label: 'E-Mail' });
this.columns.push({ name: 'isActive', label: 'Active' });
this.columns.push({ name: 'cellP... | doConstruct | identifier_name |
responsible.component.ts | import { Component} from '@angular/core';
import { BaseComponent } from '../../catalogs/base.component';
import gql from 'graphql-tag';
const responsibleCatalogs = gql`
query {
positions { id name description }
users { id name }
}
`;
@Component({
selector: 'crm-responsible',
templateUrl: './responsi... | export class ResponsibleComponent extends BaseComponent {
doConstruct() {
this.catalogName = 'Responsible';
this.baseApi = 'Responsible/';
}
addColumns() {
this.columns.push({ name: 'name', label: 'Name' });
this.columns.push({ name: 'eMail', label: 'E-Mail' });
this.columns.push({ ... | styleUrls: ['./responsible.component.scss']
}) | random_line_split |
responsible.component.ts | import { Component} from '@angular/core';
import { BaseComponent } from '../../catalogs/base.component';
import gql from 'graphql-tag';
const responsibleCatalogs = gql`
query {
positions { id name description }
users { id name }
}
`;
@Component({
selector: 'crm-responsible',
templateUrl: './responsi... |
}
| {
this._curService.loadQl(responsibleCatalogs, undefined)
.subscribe(({data}) => {
this.catPosition = data['positions'];
this.catUser = data['users'];
}, (error: Error) => {
this._loadingService.resolve('');
this._actions.showSnackBar(' Could not load ' + this.catalogName, '... | identifier_body |
usernav.component.ts | import { Component, OnInit, Input } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Auth } from '../.././shared-services/authorization/auth.service';
@Component({
selector: 'user-top-nav',
templateUrl: './usernav.component.html',
styleUrls: ['./usernav.component.... |
ngOnInit() {
if (this.auth.authenticated() === true) {
// console.log(localStorage.getItem('id_token'));
// this.route.params.subscribe((response) => {
// console.log('data received ', response);
// });
// this.loggedInUser = this.auth.getProfile(localStorage.getItem('id_token'))... | {
// Do stuff
} | identifier_body |
usernav.component.ts | import { Component, OnInit, Input } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Auth } from '../.././shared-services/authorization/auth.service';
@Component({
selector: 'user-top-nav',
templateUrl: './usernav.component.html',
styleUrls: ['./usernav.component.... | // );
console.log('this.loggedInUser in UserNavComponent', this.loggedInUser);
}
}
} | // console.log('this.loggedInUser in UserNavComponent', this.loggedInUser); },
// function (err) { console.log('error', err); },
// function () { console.log('done'); } | random_line_split |
usernav.component.ts | import { Component, OnInit, Input } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Auth } from '../.././shared-services/authorization/auth.service';
@Component({
selector: 'user-top-nav',
templateUrl: './usernav.component.html',
styleUrls: ['./usernav.component.... |
}
}
| {
// console.log(localStorage.getItem('id_token'));
// this.route.params.subscribe((response) => {
// console.log('data received ', response);
// });
// this.loggedInUser = this.auth.getProfile(localStorage.getItem('id_token'));
// this.auth.getProfileObservable(localStorage.getIte... | conditional_block |
usernav.component.ts | import { Component, OnInit, Input } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Auth } from '../.././shared-services/authorization/auth.service';
@Component({
selector: 'user-top-nav',
templateUrl: './usernav.component.html',
styleUrls: ['./usernav.component.... | (private auth: Auth, private route: ActivatedRoute, private router: Router) {
// Do stuff
}
ngOnInit() {
if (this.auth.authenticated() === true) {
// console.log(localStorage.getItem('id_token'));
// this.route.params.subscribe((response) => {
// console.log('data received ', response);... | constructor | identifier_name |
iframe.py | import pytest
from tests.support.asserts import assert_success
"""
Tests that WebDriver can transcend site origins.
Many modern browsers impose strict cross-origin checks,
and WebDriver should be able to transcend these.
Although an implementation detail, certain browsers
also enforce process isolation based on si... |
@pytest.mark.parametrize("domain", ["", "alt"], ids=["same_origin", "cross_origin"])
def test_origin(session, inline, iframe, domain):
session.url = inline("<title>foo</title>{}".format(
iframe("<title>bar</title><p>frame", domain=domain)))
frame = session.find.css("iframe", all=False)
session.s... | session.url = nested_frames_doc
outer_frame = session.find.css("iframe", all=False)
session.switch_frame(outer_frame)
inner_frame = session.find.css("iframe", all=False)
session.switch_frame(inner_frame)
session.find.css("p", all=False)
response = get_title(session)
assert_success(respons... | identifier_body |
iframe.py | import pytest
from tests.support.asserts import assert_success
"""
Tests that WebDriver can transcend site origins.
Many modern browsers impose strict cross-origin checks,
and WebDriver should be able to transcend these.
Although an implementation detail, certain browsers
also enforce process isolation based on si... | (session, inline, iframe, domain):
session.url = inline("<title>foo</title>{}".format(
iframe("<title>bar</title><p>frame", domain=domain)))
frame = session.find.css("iframe", all=False)
session.switch_frame(frame)
session.find.css("p", all=False)
response = get_title(session)
assert_s... | test_origin | identifier_name |
iframe.py | import pytest
from tests.support.asserts import assert_success
"""
Tests that WebDriver can transcend site origins.
Many modern browsers impose strict cross-origin checks,
and WebDriver should be able to transcend these.
| """
@pytest.fixture
def frame_doc(inline):
return inline("<title>cheese</title><p>frame")
@pytest.fixture
def one_frame_doc(inline, frame_doc):
return inline("<title>bar</title><iframe src='%s'></iframe>" % frame_doc)
@pytest.fixture
def nested_frames_doc(inline, one_frame_doc):
return inline("<title>... | Although an implementation detail, certain browsers
also enforce process isolation based on site origin.
This is known to sometimes cause problems for WebDriver implementations. | random_line_split |
program_struct.py | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... | (self, tab_cnt=0):
st = ' ' * tab_cnt + self.get_name()
print(st)
for _, c in self.children:
c.pprint(tab_cnt=tab_cnt + 1)
def __str__(self):
st = '(' + self.get_name()
for _, c in self.children:
st += c.__str__()
st += ')'
return st
class AbsRFillNode(ProgNode):
"""abstra... | pprint | identifier_name |
program_struct.py | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
self.last_terminal = cur_root
return cur_root.index
| self.add_bidir_edge(self.last_terminal.index, cur_root.index, 'succ') | conditional_block |
program_struct.py | # coding=utf-8
# Copyright 2022 The Google Research Authors.
# | # http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing pe... | # 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
# | random_line_split |
program_struct.py | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
def add_child(self, edge_type, child_node):
self.children.append((edge_type, child_node))
def pprint(self, tab_cnt=0):
st = ' ' * tab_cnt + self.get_name()
print(st)
for _, c in self.children:
c.pprint(tab_cnt=tab_cnt + 1)
def __str__(self):
st = '(' + self.get_name()
for _, c i... | if self.value is None:
return self.syntax
return self.syntax + '-' + str(self.value) | identifier_body |
update_repo_file.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
api_utils::{create_command, get_hosts, wait_for_cmds_success, SendCmd, SendJob},
display_utils::{display_cancelled, display_error, wrap_fut},
... |
}
if xs.is_empty() {
display_error("0 hosts can be updated. Exiting");
return Ok(());
}
let cmd = SendCmd {
jobs: xs
.iter()
.map(|x| SendJob {
class_name: "UpdateYumFileJob".into(),
args: HostId { host_id: x.id },
... | {
display_cancelled(format!("Unknown host: {}", x));
} | conditional_block |
update_repo_file.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
api_utils::{create_command, get_hosts, wait_for_cmds_success, SendCmd, SendJob},
display_utils::{display_cancelled, display_error, wrap_fut},
... |
#[derive(serde::Serialize)]
pub struct HostId {
host_id: i32,
}
pub async fn update_repo_file_cli(config: UpdateRepoFileHosts) -> Result<(), ImlManagerCliError> {
let r = parse_hosts(&config.hosts)?;
tracing::debug!("Parsed hosts {:?}", r);
let api_hosts = wrap_fut("Fetching hosts...", get_hosts())... | {
api_hosts
.iter()
.any(|y| y.fqdn == host || y.nodename == host)
} | identifier_body |
update_repo_file.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
api_utils::{create_command, get_hosts, wait_for_cmds_success, SendCmd, SendJob},
display_utils::{display_cancelled, display_error, wrap_fut},
... | <'a, 'b>(
hostlist: &'b BTreeSet<String>,
api_hosts: &'a [Host],
) -> Vec<&'a Host> {
api_hosts
.iter()
.filter(move |x| hostlist.contains(&x.fqdn) || hostlist.contains(&x.nodename))
.collect()
}
fn has_host(api_hosts: &[&Host], host: &str) -> bool {
api_hosts
.iter()
... | filter_known_hosts | identifier_name |
update_repo_file.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
api_utils::{create_command, get_hosts, wait_for_cmds_success, SendCmd, SendJob},
display_utils::{display_cancelled, display_error, wrap_fut},
... |
for x in r.iter() {
if !has_host(&xs, &x) {
display_cancelled(format!("Unknown host: {}", x));
}
}
if xs.is_empty() {
display_error("0 hosts can be updated. Exiting");
return Ok(());
}
let cmd = SendCmd {
jobs: xs
.iter()
... | let xs = filter_known_hosts(&r, &api_hosts.objects); | random_line_split |
logic.py | asin, sqrt
import cherrypy
import googlemaps
import requests
RAIN_TRESHOLD = 1.0 # mm
WIND_TRESHOLD = 5.0 # m/s
class RouteManager:
exposed=True
def __init__(self):
self.data_hub = DataHub()
def get_route_recomendation(self, from_location, to_location, _time=None):
route_data = sel... |
return location_data
class RouteManagerEndpoint(object):
exposed = True
def __init__(self):
cherrypy.log("Creating RouteManagerEndpoint")
self.manager = RouteManager()
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def get_route_recomend... | location_data["string"] += " It is windy, so put on warm clothes" | conditional_block |
logic.py | asin, sqrt
import cherrypy
import googlemaps
import requests
RAIN_TRESHOLD = 1.0 # mm
WIND_TRESHOLD = 5.0 # m/s
class RouteManager:
exposed=True
def __init__(self):
self.data_hub = DataHub()
def get_route_recomendation(self, from_location, to_location, _time=None):
route_data = sel... |
def get_location_data(self, location, _time=None):
if _time is None:
_time = datetime.datetime.now()
data = {
"weather": {
"weather_string": "light rain",
"rain": (3, 4), # mm (min, max)
"wind": (12, 15), # m/s (min, ma... | if len(args) > 1:
return (self.get_coordinates(arg) for arg in args)
coords = (12.3, 45.6) #Dummy coords
return coords | identifier_body |
logic.py | , asin, sqrt
import cherrypy
import googlemaps
import requests
RAIN_TRESHOLD = 1.0 # mm
WIND_TRESHOLD = 5.0 # m/s
class RouteManager:
exposed=True
def __init__(self):
self.data_hub = DataHub()
def get_route_recomendation(self, from_location, to_location, _time=None):
route_data = se... | },
"bicycling": {
"time": 1543, # seconds
"co2": 0 # kg
},
"walking": {
"time": 2541, # seconds
"co2": 0 # kg
},
"transit": {
... | random_line_split | |
logic.py | asin, sqrt
import cherrypy
import googlemaps
import requests
RAIN_TRESHOLD = 1.0 # mm
WIND_TRESHOLD = 5.0 # m/s
class RouteManager:
exposed=True
def __init__(self):
self.data_hub = DataHub()
def get_route_recomendation(self, from_location, to_location, _time=None):
route_data = sel... | (self, location_category):
source = self.translation[location_category]
my_location = self.gmaps.geocode(self.locations["home"])
latitude = my_location[0]['geometry']['location']['lat']
longitude = my_location[0]['geometry']['location']['lng']
radius="10"
url = 'http://l... | get_nearest_location | identifier_name |
program.rs | //! A `Program` holds multiple `Function`.
use crate::il::*;
use crate::RC;
use std::collections::BTreeMap;
use std::fmt;
/// A representation of a program by `il::Function`
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
pub struct Program {
// Mapping of function indices (not addresses) to `Function`.
... |
}
None
}
/// Get all `Function` for this `Program`.
pub fn functions(&self) -> Vec<&Function> {
let mut v = Vec::new();
for f in &self.functions {
let f: &Function = &f.1;
v.push(f);
}
v
}
/// Get the underlying BTreeMap hold... | {
return Some(function.1);
} | conditional_block |
program.rs | //! A `Program` holds multiple `Function`.
use crate::il::*;
use crate::RC;
use std::collections::BTreeMap;
use std::fmt;
/// A representation of a program by `il::Function`
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
pub struct Program {
// Mapping of function indices (not addresses) to `Function`.
... |
}
impl fmt::Display for Program {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for function in &self.functions {
writeln!(f, "{}@{:08X}", function.1.name(), function.0)?
}
Ok(())
}
}
| {
self.functions
.iter()
.find(|(_, function)| function.name() == name)
.map(|(_, function)| function.as_ref())
} | identifier_body |
program.rs | //! A `Program` holds multiple `Function`.
use crate::il::*;
use crate::RC;
use std::collections::BTreeMap;
use std::fmt;
/// A representation of a program by `il::Function`
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
pub struct Program {
// Mapping of function indices (not addresses) to `Function`.
... | pub fn add_function(&mut self, mut function: Function) {
function.set_index(Some(self.next_index));
self.functions.insert(self.next_index, RC::new(function));
self.next_index += 1;
}
/// Get a `Function` by its name.
pub fn function_by_name(&self, name: &str) -> Option<&Function... | /// Add a `Function` to the `Program`.
///
/// This will also assign an index to the `Function`. | random_line_split |
program.rs | //! A `Program` holds multiple `Function`.
use crate::il::*;
use crate::RC;
use std::collections::BTreeMap;
use std::fmt;
/// A representation of a program by `il::Function`
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
pub struct Program {
// Mapping of function indices (not addresses) to `Function`.
... | (&self) -> BTreeMap<usize, &Function> {
self.functions
.iter()
.map(|(index, function)| (*index, function.as_ref()))
.collect::<BTreeMap<usize, &Function>>()
}
/// Get a `Function` by its index.
///
/// A `Function` index is assigned by `Program` and is not t... | functions_map | identifier_name |
ansispan.js | /* globals ansispan:true */
ansispan = function(str) {
str = str.replace(/>/g, '>');
str = str.replace(/</g, '<');
Object.keys(ansispan.foregroundColors).forEach(function(ansi) {
var span = '<span style="color: ' + ansispan.foregroundColors[ansi] + '">';
//
// `\033[Xm` == `\033[0;Xm` sets foreground ... | '30': 'gray',
'31': 'red',
'32': 'lime',
'33': 'yellow',
'34': '#6B98FF',
'35': '#FF00FF',
'36': 'cyan',
'37': 'white'
}; | random_line_split | |
tools.py | '''
Created on 15.11.2021
@author: michael
'''
from alexandriabase.daos import DocumentDao, DaoModule, DOCUMENT_TABLE,\
DocumentFileInfoDao
from injector import Injector, inject
from alexandriabase import AlexBaseModule
from alexandriabase.services import ServiceModule, DocumentFileManager,\
DocumentFileNotFou... |
def close_file(self):
self.file.write("\\end{document}\n")
self.file.close()
class FemPlakatExporter(PlakatExporter):
def open_file(self):
self.titel = "Plakate zur Neuen Frauenbewegung\\linebreak{}(vor 1990 oder Entstehung nicht bestimmt)"
PlakatExporter.... | f.file = open("/tmp/plakate.tex", "w")
self.file.write("\\documentclass[german, a4paper, 12pt, twocolums]{article}\n")
self.file.write("\\usepackage[utf8]{inputenc}\n")
self.file.write("\\usepackage[T1]{fontenc}\n")
self.file.write("\\usepackage{graphicx}\n")
self.file.write("\\... | identifier_body |
tools.py | '''
Created on 15.11.2021
@author: michael
'''
from alexandriabase.daos import DocumentDao, DaoModule, DOCUMENT_TABLE,\
DocumentFileInfoDao
from injector import Injector, inject
from alexandriabase import AlexBaseModule
from alexandriabase.services import ServiceModule, DocumentFileManager,\
DocumentFileNotFou... | :
@inject
def __init__(self, dao: DocumentDao,
file_info_dao: DocumentFileInfoDao,
file_manager: DocumentFileManager,
file_provider: FileProvider,
reference_service: ReferenceService):
self.dao = dao
self.file_i... | PlakatExporter | identifier_name |
tools.py | '''
Created on 15.11.2021
@author: michael
'''
from alexandriabase.daos import DocumentDao, DaoModule, DOCUMENT_TABLE,\
DocumentFileInfoDao
from injector import Injector, inject
from alexandriabase import AlexBaseModule
from alexandriabase.services import ServiceModule, DocumentFileManager,\
DocumentFileNotFou... |
def open_file(self):
self.file = open("/tmp/plakate.tex", "w")
self.file.write("\\documentclass[german, a4paper, 12pt, twocolums]{article}\n")
self.file.write("\\usepackage[utf8]{inputenc}\n")
self.file.write("\\usepackage[T1]{fontenc}\n")
self.file.write("\\usepac... | except DocumentFileNotFound:
self.file.write("\n\nDokumentdatei nicht gefunden!")
except OSError as e:
print(e)
print("Error on document %d" % id) | random_line_split |
tools.py | '''
Created on 15.11.2021
@author: michael
'''
from alexandriabase.daos import DocumentDao, DaoModule, DOCUMENT_TABLE,\
DocumentFileInfoDao
from injector import Injector, inject
from alexandriabase import AlexBaseModule
from alexandriabase.services import ServiceModule, DocumentFileManager,\
DocumentFileNotFou... | self.file.write("\n\n\\vspace{0.5cm}")
self.file.write("\n\n\\includegraphics[width=7.0cm]{%s}\n" % file_name)
except NoSuchEntityException:
self.file.write("\n\nEintrag nicht gefunden!")
except DocumentFileNotFound:
self.file.write("\n\nDokumentdatei nicht ... | nt("Generating file %s" % file_name)
self.file_provider.get_thumbnail(file_info)
| conditional_block |
tilejsonsource.js | // FIXME add some error checking
// FIXME check order of async callbacks
/**
* @see http://mapbox.com/developers/api/
*/
goog.provide('ol.source.TileJSON');
goog.provide('ol.tilejson');
goog.require('goog.asserts');
goog.require('goog.net.Jsonp');
goog.require('ol.Attribution');
goog.require('ol.TileRange');
goog.... |
if (goog.isDef(tileJSON.scheme)) {
goog.asserts.assert(tileJSON.scheme == 'xyz', 'tileJSON-scheme is "xyz"');
}
var minZoom = tileJSON.minzoom || 0;
var maxZoom = tileJSON.maxzoom || 22;
var tileGrid = ol.tilegrid.createXYZ({
extent: ol.tilegrid.extentFromProjection(sourceProjection),
maxZoom: m... | {
var transform = ol.proj.getTransformFromProjections(
epsg4326Projection, sourceProjection);
extent = ol.extent.applyTransform(tileJSON.bounds, transform);
} | conditional_block |
tilejsonsource.js | // FIXME add some error checking
// FIXME check order of async callbacks
/**
* @see http://mapbox.com/developers/api/
*/
goog.provide('ol.source.TileJSON');
goog.provide('ol.tilejson');
goog.require('goog.asserts');
goog.require('goog.net.Jsonp');
goog.require('ol.Attribution');
goog.require('ol.TileRange');
goog.... | }
var minZoom = tileJSON.minzoom || 0;
var maxZoom = tileJSON.maxzoom || 22;
var tileGrid = ol.tilegrid.createXYZ({
extent: ol.tilegrid.extentFromProjection(sourceProjection),
maxZoom: maxZoom,
minZoom: minZoom
});
this.tileGrid = tileGrid;
this.tileUrlFunction = ol.TileUrlFunction.createFrom... | extent = ol.extent.applyTransform(tileJSON.bounds, transform);
}
if (goog.isDef(tileJSON.scheme)) {
goog.asserts.assert(tileJSON.scheme == 'xyz', 'tileJSON-scheme is "xyz"'); | random_line_split |
enkf_node.py | # Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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... | (self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_i... | asGenData | identifier_name |
enkf_node.py | # Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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... |
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", ... | if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step)) | random_line_split |
enkf_node.py | # Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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... |
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node",... | raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step)) | conditional_block |
enkf_node.py | # Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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... | def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNa... | def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_po... | identifier_body |
checks.ts | export interface InputPermutation {
nodeName: string;
cssSelector: string;
props?: {
[key: string]: string
} | }
export const INPUT_NODES = ['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON'];
export const INPUT_PERMS: Array<InputPermutation> = [
{ nodeName: 'INPUT', cssSelector: 'input[type=number]', props: { type: 'number' } },
{ nodeName: 'INPUT', cssSelector: 'input[type=range]', props: { type: 'range' } },
{ nodeName: ... | random_line_split | |
urls.py | # vim: set tw=0:
from django.conf.urls import url, include
from django.core.urlresolvers import RegexURLPattern
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.authtoken.views import obtain_auth_token
from . import views
def | (urlpatterns):
"If a URL pattern ends in a slash, it should be able to be rendered as different types"
suffixes = ['json', 'jsonld', 'jsonld-browse', 'ttl', 'ttl-browse']
ret = []
for urlpattern in urlpatterns:
if isinstance(urlpattern, RegexURLPattern):
pattern = urlpattern.regex.pa... | format_patterns | identifier_name |
urls.py | # vim: set tw=0:
from django.conf.urls import url, include
from django.core.urlresolvers import RegexURLPattern
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.authtoken.views import obtain_auth_token
from . import views
def format_patterns(urlpatterns):
|
project_specific_patterns = [
### Project (general) ###
url(r'^$', views.ProjectDetail.as_view(), name='projects-detail'),
url(r'^vocab$', views.ProjectAPIDocumentation.as_view(), name='projects-api-documentation'),
url(r'^activity/$', views.ActivityView.as_view(), name='projects-activity'),
###... | "If a URL pattern ends in a slash, it should be able to be rendered as different types"
suffixes = ['json', 'jsonld', 'jsonld-browse', 'ttl', 'ttl-browse']
ret = []
for urlpattern in urlpatterns:
if isinstance(urlpattern, RegexURLPattern):
pattern = urlpattern.regex.pattern
i... | identifier_body |
urls.py | # vim: set tw=0:
from django.conf.urls import url, include
from django.core.urlresolvers import RegexURLPattern
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.authtoken.views import obtain_auth_token
from . import views
| suffixes = ['json', 'jsonld', 'jsonld-browse', 'ttl', 'ttl-browse']
ret = []
for urlpattern in urlpatterns:
if isinstance(urlpattern, RegexURLPattern):
pattern = urlpattern.regex.pattern
is_empty = pattern == '^$'
if is_empty or pattern.endswith('/$'):
... | def format_patterns(urlpatterns):
"If a URL pattern ends in a slash, it should be able to be rendered as different types" | random_line_split |
urls.py | # vim: set tw=0:
from django.conf.urls import url, include
from django.core.urlresolvers import RegexURLPattern
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.authtoken.views import obtain_auth_token
from . import views
def format_patterns(urlpatterns):
"If a URL pattern ends i... |
ret.append(urlpattern)
return ret
project_specific_patterns = [
### Project (general) ###
url(r'^$', views.ProjectDetail.as_view(), name='projects-detail'),
url(r'^vocab$', views.ProjectAPIDocumentation.as_view(), name='projects-api-documentation'),
url(r'^activity/$', views.ActivityView.... | regex = '^' if is_empty else urlpattern.regex.pattern[:-2]
view = urlpattern._callback or urlpattern._callback_str
kwargs = urlpattern.default_args
name = urlpattern.name
stripped_url = url(regex, view, kwargs, name)
ret.append(format_suf... | conditional_block |
events.ts | import { Table, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn } from 'typeorm';
import NotificationRead from './notification';
export enum EventType {
WORK_CREATED,
PROFILE_CREATED,
TITLE_ASSIGNED,
TITLE_REVOKED,
LICENSE_OFFERED,
LICENSE_BOUGHT,
LICENSE_SOLD,
SELF_LICENSE,
WORK_MODIFIED,
WOR... | @Column({ nullable: true })
workDisplayName?: string
@Column({ nullable: true })
actorId?: string
@Column({ nullable: true })
actorDisplayName?: string
@Column({ nullable: true })
payload: string
@OneToOne(type => NotificationRead)
@JoinColumn()
read: NotificationRead
} | @Column({ nullable: true })
workId?: string
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.