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 |
|---|---|---|---|---|
label.rs | use std::fmt::{Write, self};
use std::iter;
use std::str;
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Label {
bits: u8, // amount of bits in tail (last element of vec). always between 0 and 7
buffer: Vec<u8> // backing buffer
}
impl Label {
/**
* Small layout intermezzo
* A lab... |
}
pub fn pop(&mut self) -> Option<bool> {
if self.bits == 0 {
if self.buffer.len() > 1 {
self.buffer.pop();
self.bits = 8;
} else {
return None;
}
}
let len = self.buffer.len();
let tail = &mut... | {
self.buffer.push(0);
self.bits = 0;
} | conditional_block |
frontpage.js | /**
* @fileOverview scripts about the frontpage.
*/
var calendarth = require('calendarth');
var util = require('./util');
var Front = module.exports = function() {
this.$agendaContainer = null;
this.$agendaItem = null;
this.$error = null;
};
/** @const {number} Maximum events to display, use an even number ... |
if (displayed && displayed % 2 === 0) {
// rows
elements += '</div><div class="row">';
}
elements += this._assignValues(this.$agendaItem.clone(), item);
displayed++;
}, this);
elements += '</div>';
this.$agendaContainer.append(elements);
};
/**
* Assign the Calendar item values to... | {
meetups.push(item.summary);
} | conditional_block |
frontpage.js |
var util = require('./util');
var Front = module.exports = function() {
this.$agendaContainer = null;
this.$agendaItem = null;
this.$error = null;
};
/** @const {number} Maximum events to display, use an even number */
Front.MAX_EVENTS_SHOW = 10;
/**
* Initialize the frontpage view.
*
*/
Front.prototype.in... | /**
* @fileOverview scripts about the frontpage.
*/
var calendarth = require('calendarth'); | random_line_split | |
main.rs | extern crate stopwatch;
use stopwatch::{Stopwatch};
fn main() {
let timer = Stopwatch::start_new();
//digits are stored in reverse order (least significant first) as an optimization
match expand(196, 100000) {
Ok(iter) => println!("converged after {} iterations", iter),
Err(max_iters) => pr... |
if is_palindrome(&digits) {
return Ok(iter);
}
}
//return iteration count as error value
Err(max_iters)
}
fn to_digits(n:u64) -> Vec<u8> {
let mut rem = n;
let mut digits:Vec<u8> = Vec::new();
while rem > 0 {
let digit = (rem % 10) as u8;
rem /= 10;
... | {
println!("{} {}", iter, digits.len());
} | conditional_block |
main.rs | extern crate stopwatch;
use stopwatch::{Stopwatch};
fn main() {
let timer = Stopwatch::start_new();
//digits are stored in reverse order (least significant first) as an optimization
match expand(196, 100000) {
Ok(iter) => println!("converged after {} iterations", iter),
Err(max_iters) => pr... | (digits: &mut Vec<u8>) {
//first fold in half and sum, to cut down on additions
let digits_len = digits.len();
for i in 0 .. (digits_len + 1) / 2 {
let j = digits_len - 1 - i;
let sum = digits[i] + digits[j];
digits[i] = sum;
digits[j] = sum;
}
//now propagate overflo... | reverse_add | identifier_name |
main.rs | extern crate stopwatch;
use stopwatch::{Stopwatch};
fn main() {
let timer = Stopwatch::start_new();
//digits are stored in reverse order (least significant first) as an optimization
match expand(196, 100000) {
Ok(iter) => println!("converged after {} iterations", iter),
Err(max_iters) => pr... |
/*
note that digits here are in reverse order (least significant digit first)
e.g. the number 349 should be represented as vec![9,4,3]
this lets us easily grow the array when a new digit is created by overflow, as we can simply
append it. Otherwise we'd have to prepend, which is slower.
*/
fn reverse_add(digits: &mu... | {
let mut rem = n;
let mut digits:Vec<u8> = Vec::new();
while rem > 0 {
let digit = (rem % 10) as u8;
rem /= 10;
digits.push(digit);
}
return digits;
} | identifier_body |
main.rs | extern crate stopwatch;
use stopwatch::{Stopwatch};
fn main() {
let timer = Stopwatch::start_new();
//digits are stored in reverse order (least significant first) as an optimization
match expand(196, 100000) {
Ok(iter) => println!("converged after {} iterations", iter),
Err(max_iters) => pr... | } | }
}
return true; | random_line_split |
run.py | import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import logging.config
from flask import Flask, Blueprint
from werkzeug.contrib.fixers import ProxyFix
from ceep_api import settings
from ceep_api.api import restplus
from ceep_api.api.endpoints.adbmonitors import ns as adbmonitors_n... | def initialize_app(flask_app):
log.debug('Initialize APP...')
configure_app(flask_app)
blueprint = Blueprint('api', __name__, url_prefix='/api/1.0')
api.init_app(blueprint)
api.add_namespace(adbmonitors_namespace)
flask_app.register_blueprint(blueprint)
db.init_app(flask_app)
logging.confi... | random_line_split | |
run.py | import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import logging.config
from flask import Flask, Blueprint
from werkzeug.contrib.fixers import ProxyFix
from ceep_api import settings
from ceep_api.api import restplus
from ceep_api.api.endpoints.adbmonitors import ns as adbmonitors_n... |
logging.config.fileConfig('logging.conf')
log = logging.getLogger(__name__)
app = Flask(__name__)
initialize_app(app)
app.wsgi_app = ProxyFix(app.wsgi_app)
| log.debug('Initialize APP...')
configure_app(flask_app)
blueprint = Blueprint('api', __name__, url_prefix='/api/1.0')
api.init_app(blueprint)
api.add_namespace(adbmonitors_namespace)
flask_app.register_blueprint(blueprint)
db.init_app(flask_app) | identifier_body |
run.py | import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import logging.config
from flask import Flask, Blueprint
from werkzeug.contrib.fixers import ProxyFix
from ceep_api import settings
from ceep_api.api import restplus
from ceep_api.api.endpoints.adbmonitors import ns as adbmonitors_n... | (flask_app):
flask_app.config['SQLALCHEMY_DATABASE_URI'] = settings.SQLALCHEMY_DATABASE_URI
flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = settings.SQLALCHEMY_TRACK_MODIFICATIONS
flask_app.config['SWAGGER_UI_DOC_EXPANSION'] = settings.RESTPLUS_SWAGGER_UI_DOC_EXPANSION
flask_app.config['RESTPLUS_VA... | configure_app | identifier_name |
_textfont.py | import _plotly_utils.basevalidators
class | (_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="textfont", parent_name="scattersmith", **kwargs):
super(TextfontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Text... | TextfontValidator | identifier_name |
_textfont.py | import _plotly_utils.basevalidators
class TextfontValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="textfont", parent_name="scattersmith", **kwargs):
super(TextfontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | ) | ),
**kwargs | random_line_split |
_textfont.py | import _plotly_utils.basevalidators
class TextfontValidator(_plotly_utils.basevalidators.CompoundValidator):
| apply fonts if they aren't available on the
system. The Chart Studio Cloud (at
https://chart-studio.plotly.com or on-premise)
generates images on a server, where only a
select number of fonts are installed and
supported. The... | def __init__(self, plotly_name="textfont", parent_name="scattersmith", **kwargs):
super(TextfontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Textfont"),
data_docs=kwargs.pop(
... | identifier_body |
parse_un.py | from xml.etree import ElementTree
from os.path import dirname, realpath
directory_of_sources = dirname(realpath(__file__)) + "/sources/"
d = {}
d['AR'] = "Arabic"
d['EN'] = "English"
d['ES'] = "Spanish"
d['FR'] = "French"
d['RU'] = "Russian"
d['ZH'] = "Mandarin"
filepath = '/tmp/uncorpora_plain_20090831.tmx'
count... |
if elem.tag == "seg":
text = elem.text
print language, "text is", text
if text and len(text) > 200:
with open(directory_of_sources + d[language] + "/" + uid, "wb") as f:
f.write(text.encode("utf-8"))
count += 1
if count == 50000:
... | language = elem.attrib['{http://www.w3.org/XML/1998/namespace}lang'] | conditional_block |
parse_un.py | from xml.etree import ElementTree
from os.path import dirname, realpath
directory_of_sources = dirname(realpath(__file__)) + "/sources/"
| d['AR'] = "Arabic"
d['EN'] = "English"
d['ES'] = "Spanish"
d['FR'] = "French"
d['RU'] = "Russian"
d['ZH'] = "Mandarin"
filepath = '/tmp/uncorpora_plain_20090831.tmx'
count = 0
for event, elem in ElementTree.iterparse(filepath, events=('start', 'end', 'start-ns', 'end-ns')):
if event == "start":
print event... |
d = {} | random_line_split |
lmdtest.py | from __future__ import print_function
import os
import json
import base64
import psycopg2
pg_host = os.getenv('PGHOST', "172.17.0.1")
pg_user = os.getenv('PGUSER', "postgres")
pg_password = os.getenv('PGPASSWORD', "root")
pg_database = os.getenv('PGDATABASE', "db_server")
pg_port = os.getenv('PGPORT', "5432")
print(... | elif operation == "update":
pairs = []
for key, value in row["payload"].iteritems():
if key == "id":
continue
if type(value) is object:
pairs.append(key + "='" + json.dumps(value) + "'")
elif type(value) is unicode:
... | sql = None
operation = row["operation"]
if operation == "insert":
keys = []
pairs = []
for key, value in row["payload"].iteritems():
keys.append(key)
if type(value) is object:
pairs.append("'" + json.dumps(value) + "'")
elif type(value... | identifier_body |
lmdtest.py | from __future__ import print_function
import os
import json
import base64
import psycopg2
pg_host = os.getenv('PGHOST', "172.17.0.1")
pg_user = os.getenv('PGUSER', "postgres")
pg_password = os.getenv('PGPASSWORD', "root")
pg_database = os.getenv('PGDATABASE', "db_server")
pg_port = os.getenv('PGPORT', "5432")
print(... |
values = ','.join(pairs)
payload_id = row["payload"]["id"]
sql = "UPDATE " + row["table"] + " SET " + values + " WHERE id=" + str(payload_id)
elif operation == "delete":
payload_id = row["payload"]["id"]
sql = "DELETE FROM " + row["table"] + " WHERE id=" + str(payload_id... | pairs.append(key + "=" + str(value)) | conditional_block |
lmdtest.py | from __future__ import print_function
import os
import json
import base64
import psycopg2
pg_host = os.getenv('PGHOST', "172.17.0.1")
pg_user = os.getenv('PGUSER', "postgres")
pg_password = os.getenv('PGPASSWORD', "root")
pg_database = os.getenv('PGDATABASE', "db_server")
pg_port = os.getenv('PGPORT', "5432")
print(... | (row):
sql = None
operation = row["operation"]
if operation == "insert":
keys = []
pairs = []
for key, value in row["payload"].iteritems():
keys.append(key)
if type(value) is object:
pairs.append("'" + json.dumps(value) + "'")
elif... | createOperation | identifier_name |
lmdtest.py | from __future__ import print_function
import os
import json
import base64
import psycopg2
pg_host = os.getenv('PGHOST', "172.17.0.1")
pg_user = os.getenv('PGUSER', "postgres")
pg_password = os.getenv('PGPASSWORD', "root")
pg_database = os.getenv('PGDATABASE', "db_server")
pg_port = os.getenv('PGPORT', "5432")
print(... | else:
pairs.append(key + "=" + str(value))
values = ','.join(pairs)
payload_id = row["payload"]["id"]
sql = "UPDATE " + row["table"] + " SET " + values + " WHERE id=" + str(payload_id)
elif operation == "delete":
payload_id = row["payload"]["id"]
... | pairs.append(key + "='" + json.dumps(value) + "'")
elif type(value) is unicode:
pairs.append(key + "='" + value + "'") | random_line_split |
mk.js | /**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
moduleType: 'locale',
name: 'mk',
dictionary: {},
format: {
days: ['Н... | ],
date: '%d/%m/%Y'
}
}; | 'Јан', 'Фев', 'Мар', 'Апр', 'Мај', 'Јун',
'Јул', 'Авг', 'Сеп', 'Окт', 'Нов', 'Дек' | random_line_split |
FullNavComponentLink.tsx | import React from 'react'
import styled, { useTheme } from 'styled-components'
import { Link } from 'gatsby'
import media from '../../theming/mediaQueries'
import { ChartNavData } from '../../types'
export const FullNavComponentLink = ({ name, id, flavors }: ChartNavData) => {
const theme = useTheme()
return ... | }
`}
`
const Content = styled.div`
margin-left: 6px;
flex: 1;
`
const IconContainer = styled.span`
width: 42px;
height: 42px;
overflow: hidden;
position: relative;
flex-shrink: 0;
`
const Icon = styled.span`
display: block;
position: absolute;
top: 50%;
left: 5... | }
&:nth-child(2n+1) {
margin-right: 0; | random_line_split |
admin.py | from django.contrib import admin
from django.contrib.contenttypes import generic
from .models import (Media, PhoneNumber, Episode, EpisodeExtra, Contact,
Category, EpisodePermanent, EpisodeMaxNum)
site = admin.AdminSite(name="admin")
class MediaInline(generic.GenericTabularInline):
model = Media
class Ep... | max_num = 2
class PhoneNumberInline(generic.GenericTabularInline):
model = PhoneNumber
class MediaPermanentInline(generic.GenericTabularInline):
model = Media
can_delete = False
site.register(Episode, EpisodeAdmin)
site.register(EpisodeExtra, inlines=[MediaExtraInline])
site.register(EpisodeMaxNum... | extra = 5 | random_line_split |
admin.py | from django.contrib import admin
from django.contrib.contenttypes import generic
from .models import (Media, PhoneNumber, Episode, EpisodeExtra, Contact,
Category, EpisodePermanent, EpisodeMaxNum)
site = admin.AdminSite(name="admin")
class MediaInline(generic.GenericTabularInline):
model = Media
class Ep... | (generic.GenericTabularInline):
model = Media
can_delete = False
site.register(Episode, EpisodeAdmin)
site.register(EpisodeExtra, inlines=[MediaExtraInline])
site.register(EpisodeMaxNum, inlines=[MediaMaxNumInline])
site.register(Contact, inlines=[PhoneNumberInline])
site.register(Category)
site.register(Epis... | MediaPermanentInline | identifier_name |
admin.py | from django.contrib import admin
from django.contrib.contenttypes import generic
from .models import (Media, PhoneNumber, Episode, EpisodeExtra, Contact,
Category, EpisodePermanent, EpisodeMaxNum)
site = admin.AdminSite(name="admin")
class MediaInline(generic.GenericTabularInline):
model = Media
class Ep... |
site.register(Episode, EpisodeAdmin)
site.register(EpisodeExtra, inlines=[MediaExtraInline])
site.register(EpisodeMaxNum, inlines=[MediaMaxNumInline])
site.register(Contact, inlines=[PhoneNumberInline])
site.register(Category)
site.register(EpisodePermanent, inlines=[MediaPermanentInline])
| model = Media
can_delete = False | identifier_body |
unbind_3pid.rs | //! [POST /_matrix/client/r0/account/3pid/unbind](https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-account-3pid-unbind)
use ruma_api::ruma_api;
use super::ThirdPartyIdRemovalStatus;
use crate::r0::thirdparty::Medium;
ruma_api! {
metadata {
description: "Unbind a 3PID from a user's ... | error: crate::Error
} | random_line_split | |
operation-handling.ts | import * as SITE from "globals-site";
import * as CONFIG from "globals-config";
import OPERATIONS from "operations";
import { OperationManager, Operation } from "lib/operation-manager";
import { compose, quote, formattedList } from "lib/utilities";
import { log, logError } from "userscripter/logging";
function errorS... |
export function stopOperations(delay: number): void {
setTimeout(operationManager.stop, delay);
}
| {
operationManager.start();
} | identifier_body |
operation-handling.ts | import * as SITE from "globals-site";
import * as CONFIG from "globals-config";
import OPERATIONS from "operations";
import { OperationManager, Operation } from "lib/operation-manager";
import { compose, quote, formattedList } from "lib/utilities";
import { log, logError } from "userscripter/logging";
function errorS... | (delay: number): void {
setTimeout(operationManager.stop, delay);
}
| stopOperations | identifier_name |
operation-handling.ts | import * as SITE from "globals-site";
import * as CONFIG from "globals-config";
import OPERATIONS from "operations";
import { OperationManager, Operation } from "lib/operation-manager"; |
function errorString(operation: Operation): string {
const plural = operation.selectors.length > 1;
return `Could not ${operation.description}.
${plural ? "One or more of these selectors" : "This selector"} didn't match anything:
${formattedList(operation.selectors)}
This problem might be caused by ${SITE.N... | import { compose, quote, formattedList } from "lib/utilities";
import { log, logError } from "userscripter/logging";
| random_line_split |
motion.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 https://mozilla.org/MPL/2.0/. */
//! Specified types for CSS values that are related to motion path.
use crate::parser::{Parse, ParserContext};
u... | (computed: &Self::ComputedValue) -> Self {
OffsetRotate {
direction: if computed.auto {
OffsetRotateDirection::Auto
} else {
OffsetRotateDirection::None
},
angle: ToComputedValue::from_computed_value(&computed.angle),
}
... | from_computed_value | identifier_name |
motion.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 https://mozilla.org/MPL/2.0/. */
//! Specified types for CSS values that are related to motion path.
use crate::parser::{Parse, ParserContext};
u... | #[derive(Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)]
#[repr(u8)]
pub enum OffsetRotateDirection {
/// Unspecified direction keyword.
#[css(skip)]
None,
/// 0deg offset (face forward).
Auto,
/// 180deg offset (face backward).
Reverse,
}
impl Offse... |
/// The direction of offset-rotate. | random_line_split |
motion.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 https://mozilla.org/MPL/2.0/. */
//! Specified types for CSS values that are related to motion path.
use crate::parser::{Parse, ParserContext};
u... |
}
| {
OffsetRotate {
direction: if computed.auto {
OffsetRotateDirection::Auto
} else {
OffsetRotateDirection::None
},
angle: ToComputedValue::from_computed_value(&computed.angle),
}
} | identifier_body |
motion.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 https://mozilla.org/MPL/2.0/. */
//! Specified types for CSS values that are related to motion path.
use crate::parser::{Parse, ParserContext};
u... |
if !contain {
contain = input.try(|i| i.expect_ident_matching("contain")).is_ok();
if contain {
continue;
}
}
break;
}
if angle.is_none() || size.is_none() {
return Err(input.new_custom... | {
size = input.try(RaySize::parse).ok();
if size.is_some() {
continue;
}
} | conditional_block |
models-cart.js | define(['underscore', 'modules/backbone-mozu', 'hyprlive', "modules/api"], function (_, Backbone, Hypr, api) {
var CartItemProduct = Backbone.MozuModel.extend({
helpers: ['mainImage'],
mainImage: function() {
var imgs = this.get("productImages"),
img = imgs && imgs[0],
... | var price = this.get('unitPrice');
return price.baseAmount != price.discountedAmount;
},
saveQuantity: function() {
var self = this;
var oldQuantity = this.previous("quantity");
if (this.hasChanged("quantity")) {
this.apiUpdateQ... | handlesMessages: true,
helpers: ['priceIsModified'],
priceIsModified: function() { | random_line_split |
models-cart.js | define(['underscore', 'modules/backbone-mozu', 'hyprlive', "modules/api"], function (_, Backbone, Hypr, api) {
var CartItemProduct = Backbone.MozuModel.extend({
helpers: ['mainImage'],
mainImage: function() {
var imgs = this.get("productImages"),
img = imgs && imgs[0],
... | var couponIsNotApplied = (!allDiscounts || !_.find(allDiscounts, function(d) {
return d.couponCode.toLowerCase() === lowerCode;
}));
me.set('tentativeCoupon', couponExists && couponIsNotApplied ? code : undefined);
me.isLoading(false);... | me.trigger('error', {
message: Hypr.getLabel('promoCodeError', code)
});
}
| conditional_block |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib 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 ap... | interface Routine {
/**
* Simultaneously sorts two double-precision floating-point strided arrays based on the sort order of the first array using Shellsort.
*
* @param N - number of indexed elements
* @param order - sort order
* @param x - first input array
* @param strideX - `x` stride length
* @param y - sec... | /**
* Interface describing `dsort2sh`.
*/ | random_line_split |
main.rs | // Powerlink Analyzer - Analyze Ethernet POWERLINK Network Traffic
// Copyright (C) 2016, Thomas Keh
//
// 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, version 3 of the License.
//
// This pr... | eval.print_errors::<StdoutPrinter>();
eval.print_state_changes::<StdoutPrinter>();
eval.print_stats::<StdoutPrinter>();
}
}
} | eval.print_stats::<CsvPrinter>();
} else if matches.opt_present("r") {
eval.print_raw(&filter, matches.opt_present("s"));
} else {
eval.print_metadata::<StdoutPrinter>(); | random_line_split |
main.rs | // Powerlink Analyzer - Analyze Ethernet POWERLINK Network Traffic
// Copyright (C) 2016, Thomas Keh
//
// 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, version 3 of the License.
//
// This pr... | () {
let _ = SimpleLogger::init(LogLevelFilter::Info);
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optflag("h", "help", "print this help menu");
opts.optflag("p", "pgftable", "prints master metrics as pgf table");
opts.optflag("c", "csv", "... | main | identifier_name |
main.rs | // Powerlink Analyzer - Analyze Ethernet POWERLINK Network Traffic
// Copyright (C) 2016, Thomas Keh
//
// 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, version 3 of the License.
//
// This pr... |
fn main() {
let _ = SimpleLogger::init(LogLevelFilter::Info);
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.optflag("h", "help", "print this help menu");
opts.optflag("p", "pgftable", "prints master metrics as pgf table");
opts.optflag("c",... | {
let brief = format!("Usage: {} [options] PCAPNG_FILE", program);
print!("{}", opts.usage(&brief));
} | identifier_body |
main.rs | // Powerlink Analyzer - Analyze Ethernet POWERLINK Network Traffic
// Copyright (C) 2016, Thomas Keh
//
// 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, version 3 of the License.
//
// This pr... | else {
"type=='pres'".to_string()
};
for file_path in &matches.free {
//info!("Loading PCAP file {}.",file_path);
let file_path = Path::new(&file_path);
let mut cap = Capture::from_file_with_precision(file_path,Precision::Nano).expect("Loading PCAP file failed");
let mut db = Database::new();
{
... | {
matches.opt_str("f").unwrap()
} | conditional_block |
test_bytes2human.py | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013, 2019-2020 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018-2019 Philipp Wolfer
#
# This program is free software; you can ... | ():
values = [0, 1]
for n in [1000, 1024]:
p = 1
for e in range(0, 6):
p *= n
for x in [0.1, 0.5, 0.99, 0.9999, 1, 1.5]:
values.append(int(p * x))
list = []
for x in sorted(values):
list.append(";".jo... | _create_testlist | identifier_name |
test_bytes2human.py | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013, 2019-2020 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018-2019 Philipp Wolfer
#
# This program is free software; you can ... |
@staticmethod
def _read_expected_from(path):
with open(path, 'r') as f:
lines = [line.rstrip("\n") for line in f.readlines()]
f.close()
return lines
def test_calc_unit(self):
self.assertEqual(bytes2human.calc_unit(12456, 1024), (12.1640625, 'KiB'))
... | with open(path, 'wb') as f:
f.writelines([line + "\n" for line in a_list])
f.close() | identifier_body |
test_bytes2human.py | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013, 2019-2020 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018-2019 Philipp Wolfer
#
# This program is free software; you can ... | def _create_testlist():
values = [0, 1]
for n in [1000, 1024]:
p = 1
for e in range(0, 6):
p *= n
for x in [0.1, 0.5, 0.99, 0.9999, 1, 1.5]:
values.append(int(p * x))
list = []
for x in sorted(values):
... |
@staticmethod | random_line_split |
test_bytes2human.py | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2013, 2019-2020 Laurent Monin
# Copyright (C) 2014, 2017 Sophist-UK
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018 Wieland Hoffmann
# Copyright (C) 2018-2019 Philipp Wolfer
#
# This program is free software; you can ... |
@staticmethod
def _create_testlist():
values = [0, 1]
for n in [1000, 1024]:
p = 1
for e in range(0, 6):
p *= n
for x in [0.1, 0.5, 0.99, 0.9999, 1, 1.5]:
values.append(int(p * x))
list = []
for x in so... | self.fail('!!! UNSET create_test_data mode !!! (%s)' % filename) | conditional_block |
AnalogClockLCD.py | # original code is from openmips gb Team: [OMaClockLcd] Renderer #
# Thx to arn354 #
import math
from Components.Renderer.Renderer import Renderer
from skin import parseColor
from enigma import eCanvas, eSize, gRGB, eRect
class AnalogClockLCD(Renderer):
def __init__(self):
Renderer.__init__(self)
self.fColor = ... | ystep = -1
deltax = (x1 - x0)
deltay = abs((y1 - y0))
error = (-deltax / 2)
y = int(y0)
for x in range(int(x0), (int(x1) + 1)):
if steep:
self.instance.fillRect(eRect(y, x, self.linewidth, self.linewidth), self.fColor)
else:
self.instance.fillRect(eRect(x, y, self.linewidth, self.linewidth), ... | else: | random_line_split |
AnalogClockLCD.py | # original code is from openmips gb Team: [OMaClockLcd] Renderer #
# Thx to arn354 #
import math
from Components.Renderer.Renderer import Renderer
from skin import parseColor
from enigma import eCanvas, eSize, gRGB, eRect
class AnalogClockLCD(Renderer):
def __init__(self):
Renderer.__init__(self)
self.fColor = ... |
def parseSize(self, str):
(x, y,) = str.split(',')
return eSize(int(x), int(y))
def postWidgetCreate(self, instance):
for (attrib, value,) in self.skinAttributes:
if ((attrib == 'size') and self.instance.setSize(self.parseSize(value))):
pass
self.instance.clear(self.bColor)
| self.instance.show()
if (self.forend != sopt):
self.forend = sopt
self.instance.clear(self.bColor)
self.hand(opt[1]) | conditional_block |
AnalogClockLCD.py | # original code is from openmips gb Team: [OMaClockLcd] Renderer #
# Thx to arn354 #
import math
from Components.Renderer.Renderer import Renderer
from skin import parseColor
from enigma import eCanvas, eSize, gRGB, eRect
class AnalogClockLCD(Renderer):
def __init__(self):
Renderer.__init__(self)
self.fColor = ... | error = (error + deltay)
if (error > 0):
y = (y + ystep)
error = (error - deltax)
def changed(self, what):
opt = (self.source.text).split(',')
try:
sopt = int(opt[0])
if len(opt) < 2:
opt.append('')
except Exception as e:
return
if (what[0] == self.CHANGED_CLEAR):
pass
elif s... | steep = (abs((y1 - y0)) > abs((x1 - x0)))
if steep:
x0, y0 = y0, x0
x1, y1 = y1, x1
if (x0 > x1):
x0, x1 = x1, x0
y0, y1 = y1, y0
if (y0 < y1):
ystep = 1
else:
ystep = -1
deltax = (x1 - x0)
deltay = abs((y1 - y0))
error = (-deltax / 2)
y = int(y0)
for x in range(int(x0), (int(x1) + 1... | identifier_body |
AnalogClockLCD.py | # original code is from openmips gb Team: [OMaClockLcd] Renderer #
# Thx to arn354 #
import math
from Components.Renderer.Renderer import Renderer
from skin import parseColor
from enigma import eCanvas, eSize, gRGB, eRect
class AnalogClockLCD(Renderer):
def __init__(self):
Renderer.__init__(self)
self.fColor = ... | (self, desktop, parent):
attribs = []
for (attrib, what,) in self.skinAttributes:
if (attrib == 'hColor'):
self.fColorh = parseColor(what)
elif (attrib == 'mColor'):
self.fColorm = parseColor(what)
elif (attrib == 'sColor'):
self.fColors = parseColor(what)
elif (attrib == 'linewidth'):
s... | applySkin | identifier_name |
get_dotcom.js | 'use strict';
var qs = require('querystring');
var request = require('request');
var parseString = require('xml2js').parseString;
module.exports = function(auth) {
return function(o, cb) {
var fmt = 'MM/DD/YYYY';
var url = 'https://xmlreporter.dotcom-monitor.com/reporting/xml/responses.aspx?' +
... | (siteData) {
if(!siteData) {
console.error('parseDotcomAverages - Failed to get siteData');
return [];
}
return siteData.map(function(v) {
var attrs = v.$;
var summary = v.Summary;
return {
name: attrs.Name,
latency: summary.map(function(s) ... | parseDotcomAverages | identifier_name |
get_dotcom.js | 'use strict';
var qs = require('querystring');
var request = require('request');
var parseString = require('xml2js').parseString;
module.exports = function(auth) {
return function(o, cb) {
var fmt = 'MM/DD/YYYY';
var url = 'https://xmlreporter.dotcom-monitor.com/reporting/xml/responses.aspx?' +
... | });
});
};
};
function parseDotcomAverages(siteData) {
if(!siteData) {
console.error('parseDotcomAverages - Failed to get siteData');
return [];
}
return siteData.map(function(v) {
var attrs = v.$;
var summary = v.Summary;
return {
... | random_line_split | |
get_dotcom.js | 'use strict';
var qs = require('querystring');
var request = require('request');
var parseString = require('xml2js').parseString;
module.exports = function(auth) {
return function(o, cb) {
var fmt = 'MM/DD/YYYY';
var url = 'https://xmlreporter.dotcom-monitor.com/reporting/xml/responses.aspx?' +
... |
var report = result.DotcomMonitorOnlineReport;
if(!report) {
return cb(new Error('Missing report!'));
}
var siteData = report.Site;
cb(null, {
providers: parseDotcomAverages(siteData)
... | {
return cb(err);
} | conditional_block |
get_dotcom.js | 'use strict';
var qs = require('querystring');
var request = require('request');
var parseString = require('xml2js').parseString;
module.exports = function(auth) {
return function(o, cb) {
var fmt = 'MM/DD/YYYY';
var url = 'https://xmlreporter.dotcom-monitor.com/reporting/xml/responses.aspx?' +
... | }
return avgResponse;
})
};
});
}
| {
if(!siteData) {
console.error('parseDotcomAverages - Failed to get siteData');
return [];
}
return siteData.map(function(v) {
var attrs = v.$;
var summary = v.Summary;
return {
name: attrs.Name,
latency: summary.map(function(s) {
... | identifier_body |
global-timeline.ts | import $ from 'cafy';
import { ID } from '../../../../misc/cafy-id';
import define from '../../define';
import { fetchMeta } from '../../../../misc/fetch-meta';
import { ApiError } from '../../error';
import { makePaginationQuery } from '../../common/make-pagination-query';
import { Notes } from '../../../../models';
i... | ateQueryBuilder('note'),
ps.sinceId, ps.untilId, ps.sinceDate, ps.untilDate)
.andWhere('note.visibility = \'public\'')
.andWhere('note.channelId IS NULL')
.leftJoinAndSelect('note.user', 'user');
generateRepliesQuery(query, user);
if (user) generateMutedUserQuery(query, user);
if (user) generateMutedNoteQu... | ct query
const query = makePaginationQuery(Notes.cre | conditional_block |
global-timeline.ts | import $ from 'cafy';
import { ID } from '../../../../misc/cafy-id';
import define from '../../define';
import { fetchMeta } from '../../../../misc/fetch-meta';
import { ApiError } from '../../error';
import { makePaginationQuery } from '../../common/make-pagination-query';
import { Notes } from '../../../../models';
i... | },
sinceId: {
validator: $.optional.type(ID),
},
untilId: {
validator: $.optional.type(ID),
},
sinceDate: {
validator: $.optional.num
},
untilDate: {
validator: $.optional.num
},
},
res: {
type: 'array' as const,
optional: false as const, nullable: false as const,
items: {
... | },
limit: {
validator: $.optional.num.range(1, 100),
default: 10 | random_line_split |
recursive-struct.rs | // Copyright 2013-2014 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-MI... | };
// It's important that LongCycleWithAnonymousTypes is encountered only at the end of the
// `box` chain.
let long_cycle_w_anonymous_types = box box box box box LongCycleWithAnonymousTypes {
next: Val {
val: box box box box box LongCycleWithAnonymousTypes {
next: E... | next: None,
value: 29.5, | random_line_split |
recursive-struct.rs | // Copyright 2013-2014 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-MI... | <T> {
next: Box<LongCycle3<T>>,
value: T,
}
struct LongCycle3<T> {
next: Box<LongCycle4<T>>,
value: T,
}
struct LongCycle4<T> {
next: Option<Box<LongCycle1<T>>>,
value: T,
}
struct LongCycleWithAnonymousTypes {
next: Opt<Box<Box<Box<Box<Box<LongCycleWithAnonymousTypes>>>>>>,
value: ui... | LongCycle2 | identifier_name |
nist-spce.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 G. Fraux — BSD license
//! Testing energy computation for SPC/E water using data from
//! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff
//! https://www.nist.gov/mml/csd/che... | {
let system = get_system("spce-1.xyz", 10.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -4.88604e5;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist2() {
let system = get_system("spce-2.xyz", 10.0);
let e... | t1() | identifier_name |
nist-spce.rs |
//! Testing energy computation for SPC/E water using data from
//! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff
//! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-10å-cutoff
extern crate lumol;
ext... | // Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 G. Fraux — BSD license | random_line_split | |
nist-spce.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 G. Fraux — BSD license
//! Testing energy computation for SPC/E water using data from
//! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff
//! https://www.nist.gov/mml/csd/che... | #[test]
fn nist3() {
let system = get_system("spce-3.xyz", 9.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -1.71488e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist4() {
let system = get_system("spce-4.xy... | let system = get_system("spce-2.xyz", 9.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -1.06602e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
| identifier_body |
youtube_a.js | var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'YouTube',
prepareImgLinks:function (callback) {
var res = [],
repl = 'http://i1.ytimg.com/vi/$1/0.jpg';
function decodeQueryString(queryString) {
var keyValPairs = queryString.split("&"), param... | ources, type, quality) {
var lowest = null, exact = null;
for (var key in sources) {
var source = sources[key];
if (source.type.match(type)) {
if (source.quality.match(quality)) {
exact = source;
} el... | tSource(s | identifier_name |
youtube_a.js | var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'YouTube',
prepareImgLinks:function (callback) {
var res = [],
repl = 'http://i1.ytimg.com/vi/$1/0.jpg';
function decodeQueryString(queryString) {
var keyValPairs = queryString.split("&"), param... | });
}
$('a[href*="youtu.be/"]').one('mouseenter', function () {
var link = $(this), match = this.href.match(/^.*youtu.be\/([\w-]+).*$/);
if (!match || match.length < 2) return;
prepareVideoPreview(link, match[1]);
});
$('a[href*="youtube.c... | link.data().hoverZoomSrc = [start ? src.url + '#t=' + start : src.url];
link.addClass('hoverZoomLink');
hoverZoom.displayPicFromElement(link);
}
| conditional_block |
youtube_a.js | var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'YouTube',
prepareImgLinks:function (callback) {
var res = [],
repl = 'http://i1.ytimg.com/vi/$1/0.jpg';
function decodeQueryString(queryString) {
var keyValPairs = queryString.split("&"), param... | function getSource(sources, type, quality) {
var lowest = null, exact = null;
for (var key in sources) {
var source = sources[key];
if (source.type.match(type)) {
if (source.quality.match(quality)) {
exact = sour... | var streams = url_encoded_fmt_stream_map.split(","), sources = {};
for (var i = 0; i < streams.length; i++) {
var stream = decodeQueryString(streams[i]);
var type = stream.type.split(";")[0];
var quality = stream.quality.split(",")[0];
... | identifier_body |
youtube_a.js | var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'YouTube',
prepareImgLinks:function (callback) {
var res = [],
repl = 'http://i1.ytimg.com/vi/$1/0.jpg';
function decodeQueryString(queryString) {
var keyValPairs = queryString.split("&"), param... | var parts = start.split('m');
if (parts.length == 2) {
var parts2 = start.split('h');
if (parts2.length == 2)
parts[0] = parseInt(parts2[0]) * 60 + parseInt(parts2[1]);
start = parseInt(parts[0]) * 60 + p... | random_line_split | |
vec-to_str.rs | // Copyright 2013 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 ... | () {
assert_eq!((~[0, 1]).to_str(), ~"[0, 1]");
assert_eq!((&[1, 2]).to_str(), ~"[1, 2]");
assert_eq!((@[2, 3]).to_str(), ~"[2, 3]");
let foo = ~[3, 4];
let bar = &[4, 5];
let baz = @[5, 6];
assert_eq!(foo.to_str(), ~"[3, 4]");
assert_eq!(bar.to_str(), ~"[4, 5]");
assert_eq!(baz.to... | main | identifier_name |
vec-to_str.rs | // Copyright 2013 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 ... |
assert_eq!(foo.to_str(), ~"[3, 4]");
assert_eq!(bar.to_str(), ~"[4, 5]");
assert_eq!(baz.to_str(), ~"[5, 6]");
} | assert_eq!((@[2, 3]).to_str(), ~"[2, 3]");
let foo = ~[3, 4];
let bar = &[4, 5];
let baz = @[5, 6]; | random_line_split |
vec-to_str.rs | // Copyright 2013 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 ... | {
assert_eq!((~[0, 1]).to_str(), ~"[0, 1]");
assert_eq!((&[1, 2]).to_str(), ~"[1, 2]");
assert_eq!((@[2, 3]).to_str(), ~"[2, 3]");
let foo = ~[3, 4];
let bar = &[4, 5];
let baz = @[5, 6];
assert_eq!(foo.to_str(), ~"[3, 4]");
assert_eq!(bar.to_str(), ~"[4, 5]");
assert_eq!(baz.to_st... | identifier_body | |
PerformanceOverlay.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @provides... | if (perfLogs[key].totalTime) {
var unit = (key === 'BundleSize') ? 'b' : 'ms';
items.push(
<View style={styles.row} key={key}>
<Text style={[styles.text, styles.label]}>{key}</Text>
<Text style={[styles.text, styles.totalTime]}>
{perfLogs[key].totalT... |
for (var key in perfLogs) { | random_line_split |
PerformanceOverlay.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @provides... |
}
return (
<View style={styles.container}>
{items}
</View>
);
}
});
var styles = StyleSheet.create({
container: {
height: 100,
paddingTop: 10,
},
label: {
flex: 1,
},
row: {
flexDirection: 'row',
paddingHorizontal: 10,
},
text: {
color: 'white',... | {
var unit = (key === 'BundleSize') ? 'b' : 'ms';
items.push(
<View style={styles.row} key={key}>
<Text style={[styles.text, styles.label]}>{key}</Text>
<Text style={[styles.text, styles.totalTime]}>
{perfLogs[key].totalTime + unit}
</Text>
... | conditional_block |
DashboardController.js | app.controller('DashboardController',function($scope,$http,Article){
//Pagination configuration
$scope.maxSize = 5;
$scope.numPerPage = 5;
$scope.currentPage = '1';
$scope.isEdit = false;
$scope.isError= false;
$scope.newarticle = {}; // Edit/New panel model
$scope.curArticle = {}; /... |
};
//Cancel panel button
$scope.cancelArticle = function(article){
$scope.isEdit=false;
$scope.isError=false;
//Remove old values
$scope.newarticle= new Article();
};
}); | {
article.$delete(function(data){
alert(data.msg);
//Get selected article index then remove from articles json
var curIndex = $scope.articles.indexOf(article);
$scope.articles.splice(curIndex,1);
},function(error){
... | conditional_block |
DashboardController.js | app.controller('DashboardController',function($scope,$http,Article){
//Pagination configuration
$scope.maxSize = 5;
$scope.numPerPage = 5;
$scope.currentPage = '1';
$scope.isEdit = false;
$scope.isError= false;
$scope.newarticle = {}; // Edit/New panel model
$scope.curArticle = {}; /... |
//Open New panel
$scope.newArticle = function(article){
$scope.isEdit=true;
$scope.isError=false;
//Initialize with Article resource
$scope.newarticle = new Article();
};
//Open Edit panel with data on edit button click
$scope.editArticle = function(article){
... | {
$scope.isError=true; //Show validator error
angular.forEach(error.data,function(key,value){
$scope.errors.push(value + ': ' + key);
});
} | identifier_body |
DashboardController.js | app.controller('DashboardController',function($scope,$http,Article){
//Pagination configuration
$scope.maxSize = 5;
$scope.numPerPage = 5;
$scope.currentPage = '1';
$scope.isEdit = false;
$scope.isError= false;
$scope.newarticle = {}; // Edit/New panel model
$scope.curArticle = {}; /... | // Update values to selected article
angular.extend($scope.curArticle,$scope.curArticle,data);
//Hide edit/new panel
$scope.isEdit = false;
},errorHandler);
}else{
//Send post resource request
article.$save(func... | //Check if update or new
if($scope.curArticle.id){
//Send put resource request
article.$update(function(data){ | random_line_split |
DashboardController.js | app.controller('DashboardController',function($scope,$http,Article){
//Pagination configuration
$scope.maxSize = 5;
$scope.numPerPage = 5;
$scope.currentPage = '1';
$scope.isEdit = false;
$scope.isError= false;
$scope.newarticle = {}; // Edit/New panel model
$scope.curArticle = {}; /... | (error){
$scope.isError=true; //Show validator error
angular.forEach(error.data,function(key,value){
$scope.errors.push(value + ': ' + key);
});
}
//Open New panel
$scope.newArticle = function(article){
$scope.isEdit=true;
$scope.isError=false;
... | errorHandler | identifier_name |
fake.ts | import NoModel from 'jscommons/dist/errors/NoModel';
import Signature, { Opts, Result } from './Signature';
import {
TEST_CLIENT,
TEST_CLIENT_OUTSIDE_ORG,
TEST_CLIENT_OUTSIDE_STORE,
TEST_INVALID_SCOPE_CLIENT,
TEST_INVALID_SCOPE_TOKEN,
TEST_MISSING_TOKEN,
TEST_OUTSIDE_ORG_TOKEN,
TEST_OUTSIDE_STORE_TOKEN,... | }; | random_line_split | |
266658781c00_instances_nullable_in_equipments_provider.py | """
column 'instances' will be deleted later. Has to be nullable for transition
Revision ID: 266658781c00
Revises: 204aae05372a
Create Date: 2019-04-15 16:27:22.362244
"""
# revision identifiers, used by Alembic.
revision = '266658781c00'
down_revision = '204aae05372a'
from alembic import op
import sqlalchemy as sa... |
def downgrade():
op.alter_column(
'equipments_provider', 'instances', existing_type=postgresql.ARRAY(sa.TEXT()), nullable=False
)
| op.alter_column('equipments_provider', 'instances', existing_type=postgresql.ARRAY(sa.TEXT()), nullable=True) | identifier_body |
266658781c00_instances_nullable_in_equipments_provider.py | """
column 'instances' will be deleted later. Has to be nullable for transition
Revision ID: 266658781c00
Revises: 204aae05372a
Create Date: 2019-04-15 16:27:22.362244
"""
# revision identifiers, used by Alembic.
revision = '266658781c00'
down_revision = '204aae05372a'
from alembic import op
import sqlalchemy as sa... | ():
op.alter_column('equipments_provider', 'instances', existing_type=postgresql.ARRAY(sa.TEXT()), nullable=True)
def downgrade():
op.alter_column(
'equipments_provider', 'instances', existing_type=postgresql.ARRAY(sa.TEXT()), nullable=False
)
| upgrade | identifier_name |
266658781c00_instances_nullable_in_equipments_provider.py | """
column 'instances' will be deleted later. Has to be nullable for transition
Revision ID: 266658781c00
Revises: 204aae05372a
Create Date: 2019-04-15 16:27:22.362244
"""
# revision identifiers, used by Alembic.
revision = '266658781c00'
down_revision = '204aae05372a'
from alembic import op
import sqlalchemy as sa... | 'equipments_provider', 'instances', existing_type=postgresql.ARRAY(sa.TEXT()), nullable=False
) | op.alter_column('equipments_provider', 'instances', existing_type=postgresql.ARRAY(sa.TEXT()), nullable=True)
def downgrade():
op.alter_column( | random_line_split |
treePlotter.py | import matplotlib
import matplotlib.pyplot as plt
decisionNoe = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")
def plotNoe(nodeTxt, centerPt, parentPt, nodeType):
createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction',
... | plotTree.yoff = 1.0
plotTree(inTree, (0.5, 1.0), '')
plt.show() | random_line_split | |
treePlotter.py | import matplotlib
import matplotlib.pyplot as plt
decisionNoe = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")
def plotNoe(nodeTxt, centerPt, parentPt, nodeType):
createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction',
... | (cntrPt, parentPt, txtString):
xMid = (parentPt[0] - cntrPt[0]) / 2.0 + cntrPt[0]
yMid = (parentPt[1] - cntrPt[1]) / 2.0 + cntrPt[1]
createPlot.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30)
def plotTree(myTree, parentPt, nodeTxt):
numLeafs = getNumLeafs(myTree)
depth = get... | plotMidText | identifier_name |
treePlotter.py | import matplotlib
import matplotlib.pyplot as plt
decisionNoe = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")
def plotNoe(nodeTxt, centerPt, parentPt, nodeType):
createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction',
... |
def plotMidText(cntrPt, parentPt, txtString):
xMid = (parentPt[0] - cntrPt[0]) / 2.0 + cntrPt[0]
yMid = (parentPt[1] - cntrPt[1]) / 2.0 + cntrPt[1]
createPlot.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30)
def plotTree(myTree, parentPt, nodeTxt):
numLeafs = getNumLeafs(myTre... | listOfTrees = [{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}},
{'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}}]
return listOfTrees[i] | identifier_body |
treePlotter.py | import matplotlib
import matplotlib.pyplot as plt
decisionNoe = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")
def plotNoe(nodeTxt, centerPt, parentPt, nodeType):
createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction',
... |
else:
plotTree.xoff = plotTree.xoff + 1.0 / plotTree.totalW
plotNoe(secondDict[key], (plotTree.xoff, plotTree.yoff), cntrPt, leafNode)
plotMidText((plotTree.xoff, plotTree.yoff), cntrPt, str(key))
plotTree.yoff = plotTree.yoff + 1.0 / plotTree.totalD
def createPlot(inT... | plotTree(secondDict[key], cntrPt, str(key)) | conditional_block |
paper-dialog-inner.js | /**
* @module ember-paper
*/
import Component from '@ember/component';
import { run } from '@ember/runloop';
import Translate3dMixin from '../mixins/translate3d-mixin';
/**
* @class PaperDialogInner
* @extends Ember.Component
* @uses Translate3dMixin
*/
export default Component.extend(Translate3dMixin, {
tagN... | ,
onTranslateToEnd($origin) {
if ($origin) {
$origin.focus();
}
},
didInsertElement() {
this._super(...arguments);
this.checkContentOverflow();
// content overflow might change depending on load of images inside dialog.
let images = this.$().find('img');
images.on(`load.${this.... | {
if (this.get('focusOnOpen')) {
let toFocus = this.$('[autofocus]').last();
if (toFocus.length === 0) {
toFocus = this.$('md-dialog-actions button').last();
}
toFocus.focus();
}
} | identifier_body |
paper-dialog-inner.js | /**
* @module ember-paper
*/
import Component from '@ember/component';
import { run } from '@ember/runloop';
import Translate3dMixin from '../mixins/translate3d-mixin';
/**
* @class PaperDialogInner
* @extends Ember.Component
* @uses Translate3dMixin
*/
export default Component.extend(Translate3dMixin, {
tagN... | () {
if (this.get('focusOnOpen')) {
let toFocus = this.$('[autofocus]').last();
if (toFocus.length === 0) {
toFocus = this.$('md-dialog-actions button').last();
}
toFocus.focus();
}
},
onTranslateToEnd($origin) {
if ($origin) {
$origin.focus();
}
},
didIns... | onTranslateFromEnd | identifier_name |
paper-dialog-inner.js | /**
* @module ember-paper
*/
import Component from '@ember/component';
import { run } from '@ember/runloop';
import Translate3dMixin from '../mixins/translate3d-mixin';
/**
* @class PaperDialogInner
* @extends Ember.Component
* @uses Translate3dMixin
*/
export default Component.extend(Translate3dMixin, {
tagN... | let images = this.$().find('img');
images.off(`load.${this.elementId}`);
},
checkContentOverflow() {
let content = this.element.querySelector('md-dialog-content');
if (content) {
this.set('contentOverflow', content.scrollHeight > content.clientHeight);
}
}
}); | images.on(`load.${this.elementId}`, run.bind(this, this.checkContentOverflow));
},
willDestroyElement() {
this._super(...arguments); | random_line_split |
paper-dialog-inner.js | /**
* @module ember-paper
*/
import Component from '@ember/component';
import { run } from '@ember/runloop';
import Translate3dMixin from '../mixins/translate3d-mixin';
/**
* @class PaperDialogInner
* @extends Ember.Component
* @uses Translate3dMixin
*/
export default Component.extend(Translate3dMixin, {
tagN... |
}
});
| {
this.set('contentOverflow', content.scrollHeight > content.clientHeight);
} | conditional_block |
calibration.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 14:09:59 2017
@author: SaintlyVi
"""
import pandas as pd
import numpy as np
| def uncertaintyStats(submodel):
"""
Creates a dict with statistics for observed hourly profiles for a given year.
Use evaluation.evalhelpers.observedHourlyProfiles() to generate the input dataframe.
"""
allstats = list()
for c in submodel['class'].unique():
stats = submodel[submode... | from support import writeLog
| random_line_split |
calibration.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 14:09:59 2017
@author: SaintlyVi
"""
import pandas as pd
import numpy as np
from support import writeLog
def uncertaintyStats(submodel):
"""
Creates a dict with statistics for observed hourly profiles for a given year.
Use evaluati... |
else:
models = [submodels]
validmodels = pd.DataFrame(columns = ['submodel_name','valid_data','uncertainty_index',
'valid_unit_count', 'unit'])
for m in models:
name = m.name
valid_data = m[(m.AnswerID_count>=min_answerid) & (m.valid_... | models = submodels | conditional_block |
calibration.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 14:09:59 2017
@author: SaintlyVi
"""
import pandas as pd
import numpy as np
from support import writeLog
def uncertaintyStats(submodel):
"""
Creates a dict with statistics for observed hourly profiles for a given year.
Use evaluati... | (submodels, min_answerid, min_obsratio):
"""
This function returns the slice of submodels that meet the specified minimum uncertainty requirements. Submodels must form part of the same experiment (eg demand summary and hourly profiles).
"""
if isinstance(submodels, list):
models = submodels
... | dataIntegrity | identifier_name |
calibration.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 14:09:59 2017
@author: SaintlyVi
"""
import pandas as pd
import numpy as np
from support import writeLog
def uncertaintyStats(submodel):
"""
Creates a dict with statistics for observed hourly profiles for a given year.
Use evaluati... | bm_hp = bm_model[1]
bm_dsts = bm_model[2]
bm_hpts = bm_model[3]
#Calculate model similarity
euclid_ds, count_ds, slice_ex_ds = modelSimilarity(bm_ds, bm_dsts, valid_new_ds, new_dsts, 'ds')
euclid_hp, count_hp, sliced_ex_hp = modelSimilarity(bm_hp, bm_hpts, valid_new_hp, new_hpts, 'hp')
... | """
This function logs the evaluation results of the run.
ex_model = [demand_summary, hourly_profiles, ds_val_col_name, hp_val_col_name]
"""
#Generate data model
ods = pd.read_csv('data/experimental_model/'+exp_model+'/demand_summary_'+year+'.csv')
ohp = pd.read_csv('data/experimental_model... | identifier_body |
test_examples.py | #!/usr/bin/python
#=============================================================================================
# MODULE DOCSTRING
#=============================================================================================
"""
Test examples.
"""
#=================================================================... |
return
def get_immediate_subdirectories(path):
return [name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name)) and os.path.exists(os.path.join(path, name, 'run.sh'))]
@attr('slow') # Skip on Travis-CI
def test_examples():
# Get example path.
from pkg_resources import resource_fi... | raise Exception('Example %s returned exit code %d' % (example, returncode)) | conditional_block |
test_examples.py | #!/usr/bin/python
#=============================================================================================
# MODULE DOCSTRING
#=============================================================================================
"""
Test examples.
"""
#=================================================================... | from pkg_resources import resource_filename
path = resource_filename('yank', '../examples')
# Get list of examples.
directories = get_immediate_subdirectories(path)
# Test examples
for directory in directories:
run_example(path, directory) | identifier_body | |
test_examples.py | #!/usr/bin/python
#=============================================================================================
# MODULE DOCSTRING
#=============================================================================================
"""
Test examples.
"""
#=================================================================... | (path):
return [name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name)) and os.path.exists(os.path.join(path, name, 'run.sh'))]
@attr('slow') # Skip on Travis-CI
def test_examples():
# Get example path.
from pkg_resources import resource_filename
path = resource_filename('yank', '.... | get_immediate_subdirectories | identifier_name |
test_examples.py | #!/usr/bin/python
#=============================================================================================
# MODULE DOCSTRING
#=============================================================================================
"""
Test examples.
"""
#=================================================================... | run_example(path, directory) | # Get list of examples.
directories = get_immediate_subdirectories(path)
# Test examples
for directory in directories: | random_line_split |
setup.py | #!/usr/bin/python3
import os | PLATFORM = sys.platform
if PLATFORM == 'linux' or PLATFORM == 'linux2':
user = os.getenv("SUDO_USER")
if user is None:
print("This program need \'Superuser Privileges\'")
exit()
NAME = 'MissionText'
FILE_NAME = NAME + '.desktop'
BIN = '/usr/bin/' + NAME
WORKING_DIR... | import sys
from shutil import copy2
| random_line_split |
setup.py | #!/usr/bin/python3
import os
import sys
from shutil import copy2
PLATFORM = sys.platform
if PLATFORM == 'linux' or PLATFORM == 'linux2':
user = os.getenv("SUDO_USER")
if user is None:
print("This program need \'Superuser Privileges\'")
exit()
NAME = 'MissionText'
FILE_NA... | .remove(SH) | conditional_block | |
events.rs | ` and it's [`kind`](EventKind).
//!
//! ```rust
//! use ruma_common::events::macros::EventContent;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
//! #[ruma_event(type = "org.example.event", kind = State)]
//! pub struct ExampleContent {
//! field: Str... | / Marker trait for the content of an ephemeral room event.
pub trait EphemeralRoomEventContent: EventContent {}
/// Marker trait for the content of a global account data event.
pub trait GlobalAccountDataEventContent: EventContent {}
/// Marker trait for the content of a room account data event.
pub trait RoomAccount... | T::from_parts(event_type, self.json())
}
}
// | identifier_body |
events.rs | reaction.
//! key: String,
//! },
//!
//! /// Since this event is not fully specified in the Matrix spec
//! /// it may change or types may be added, we are ready!
//! #[serde(rename = "m.whatever")]
//! Whatever,
//! }
//!
//! /// The payload for our reaction event.
//! #[derive(Clone, Deb... | d {
/ | identifier_name | |
events.rs | ` and it's [`kind`](EventKind).
//!
//! ```rust
//! use ruma_common::events::macros::EventContent;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
//! #[ruma_event(type = "org.example.event", kind = State)]
//! pub struct ExampleContent {
//! field: Str... | //! Ok(SyncMessageLikeEvent {
//! content: ReactionEventContent {
//! relates_to: RelatesTo::Annotation { key, .. },
//! },
//! ..
//! }) if key == "👍"
//! );
//! ```
//!
//! # Serialization and deserialization
//!
//! All concrete event types in this module can be serialize... | //! // but could be deserialized from a `Raw<_>` that has failed to deserialize.
//! matches::assert_matches!(
//! serde_json::from_value::<SyncMessageLikeEvent<ReactionEventContent>>(json), | random_line_split |
into.rs | use std::iter;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse::Result, DeriveInput};
use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State};
/// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into`
pub fn expand(input: &DeriveInput, trait... | };
let additional_types = variant_info.additional_types(ref_type);
for explicit_type in iter::once(None).chain(additional_types.iter().map(Some)) {
let into_types: Vec<_> = field_types
.iter()
.map(|field_type| {
// No, `.unwrap_or... | let (impl_generics, _, _) = if ref_type.is_ref() {
generics_impl = add_extra_generic_param(&input.generics, lifetime);
generics_impl.split_for_impl()
} else {
input.generics.split_for_impl() | random_line_split |
into.rs | use std::iter;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse::Result, DeriveInput};
use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State};
/// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into`
pub fn | (input: &DeriveInput, trait_name: &'static str) -> Result<TokenStream> {
let state = State::with_attr_params(
input,
trait_name,
quote!(::core::convert),
trait_name.to_lowercase(),
AttrParams {
enum_: vec!["ignore", "owned", "ref", "ref_mut"],
variant:... | expand | identifier_name |
into.rs | use std::iter;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse::Result, DeriveInput};
use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State};
/// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into`
pub fn expand(input: &DeriveInput, trait... |
let mut tokens = TokenStream::new();
for ref_type in variant_info.ref_types() {
let reference = ref_type.reference();
let lifetime = ref_type.lifetime();
let reference_with_lifetime = ref_type.reference_with_lifetime();
let generics_impl;
let (_, ty_generics, where_cla... | {
let state = State::with_attr_params(
input,
trait_name,
quote!(::core::convert),
trait_name.to_lowercase(),
AttrParams {
enum_: vec!["ignore", "owned", "ref", "ref_mut"],
variant: vec!["ignore", "owned", "ref", "ref_mut"],
struct_: vec!["... | identifier_body |
into.rs | use std::iter;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse::Result, DeriveInput};
use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State};
/// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into`
pub fn expand(input: &DeriveInput, trait... |
});
(quote! {
#[automatically_derived]
impl#impl_generics ::core::convert::From<#reference_with_lifetime #input_type#ty_generics> for
(#(#into_types),*) #where_clause {
#[inline]
fn from(original: #ref... | {
quote! { #reference original.#field_ident }
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.