file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
__main__.py | #!/usr/bin/env python
import sys
import argparse
from .audio import create_tracks
from .downloader import YouTube
from .parser import parse_tracks_file
from .prompt import wizard
from .exceptions import WizardError
def get_from_youtube(source):
yt = YouTube(source)
highest_bitrate = yt.audio_available.get('... |
elif mode == 'wizard':
try:
generate_album(**wizard())
except WizardError:
sys.exit()
else:
print('Invalid {} mode'.format(mode))
sys.exit(main())
| del kwargs['mode']
generate_album(**kwargs) | conditional_block |
__main__.py | #!/usr/bin/env python
import sys
import argparse
from .audio import create_tracks
from .downloader import YouTube
from .parser import parse_tracks_file
from .prompt import wizard
from .exceptions import WizardError
def get_from_youtube(source):
yt = YouTube(source)
highest_bitrate = yt.audio_available.get('... |
def main():
parser = argparse.ArgumentParser(
prog='lobster',
description='Cut audio files with a single command'
)
parser.add_argument('--artist', '-ar', type=str, required=False,
help='Name of the artist of the track this will be used '\
... | random_line_split | |
__main__.py | #!/usr/bin/env python
import sys
import argparse
from .audio import create_tracks
from .downloader import YouTube
from .parser import parse_tracks_file
from .prompt import wizard
from .exceptions import WizardError
def | (source):
yt = YouTube(source)
highest_bitrate = yt.audio_available.get('high')
return yt.download_audio(highest_bitrate)
def get_from_local(source):
return source
def generate_album(artist, album, tracks, source, input, output,
format='mp3', from_wizard=None):
"""
Generates... | get_from_youtube | identifier_name |
orphan-widgets-attribute.rs | /*
* Copyright (c) 2020 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... | gtk::Button {
clicked => Increment,
label: "+",
},
gtk::Label {
text: &self.model.counter.to_string(),
},
#[name="radio1"]
gtk::RadioButton {
la... | gtk::Window {
gtk::Box {
orientation: Vertical,
#[name="inc_button"] | random_line_split |
orphan-widgets-attribute.rs | /*
* Copyright (c) 2020 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... |
fn update(&mut self, event: Msg) {
match event {
Click(x, y) => println!("Clicked on {}, {}", x, y),
Decrement => self.model.counter -= 1,
End => println!("End"),
Increment => self.model.counter += 1,
Move(x, y) => println!("Moved to {}, {}", x, ... | {
Model {
counter: 0,
}
} | identifier_body |
orphan-widgets-attribute.rs | /*
* Copyright (c) 2020 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... | () {
Win::run(()).expect("Win::run failed");
}
| main | identifier_name |
directiveHostEventsPlugin.ts | import {DirectiveDefinitionEvent, DirectiveDefinitionType} from '@slicky/core/metadata';
import {forEach, exists} from '@slicky/utils';
import {OnProcessElementArgument} from '@slicky/templates-compiler';
import {BuilderFunction} from '@slicky/templates-compiler/builder';
import * as _ from '@slicky/html-parser';
impor... |
public onAfterElementDirective(directive: ProcessingDirective): void
{
if (directive.directive.metadata.type !== DirectiveDefinitionType.Directive) {
return;
}
forEach(directive.directive.metadata.events, (hostEvent: DirectiveDefinitionEvent) => {
if (!exists(hostEvent.selector)) {
return;
}
... | {
if (directive.directive.metadata.type !== DirectiveDefinitionType.Directive) {
return;
}
forEach(directive.directive.metadata.events, (hostEvent: DirectiveDefinitionEvent) => {
if (directive.processedHostEvents.indexOf(hostEvent) >= 0) {
return;
}
if (!exists(hostEvent.selector)) {
return;... | identifier_body |
directiveHostEventsPlugin.ts | import {DirectiveDefinitionEvent, DirectiveDefinitionType} from '@slicky/core/metadata';
import {forEach, exists} from '@slicky/utils';
import {OnProcessElementArgument} from '@slicky/templates-compiler';
import {BuilderFunction} from '@slicky/templates-compiler/builder'; | import * as _ from '@slicky/html-parser';
import {AbstractDirectivePlugin, ProcessingDirective} from '../abstractDirectivePlugin';
import {ElementProcessingDirective} from '../../slickyEnginePlugin';
export class DirectiveHostEventsPlugin extends AbstractDirectivePlugin
{
public onBeforeProcessDirective(element: _... | random_line_split | |
directiveHostEventsPlugin.ts | import {DirectiveDefinitionEvent, DirectiveDefinitionType} from '@slicky/core/metadata';
import {forEach, exists} from '@slicky/utils';
import {OnProcessElementArgument} from '@slicky/templates-compiler';
import {BuilderFunction} from '@slicky/templates-compiler/builder';
import * as _ from '@slicky/html-parser';
impor... |
this.writeHostEvent(arg.render, hostEvent, directive.id);
directive.processedHostEvents.push(hostEvent);
});
}
public onAfterElementDirective(directive: ProcessingDirective): void
{
if (directive.directive.metadata.type !== DirectiveDefinitionType.Directive) {
return;
}
forEach(directive.direc... | {
return;
} | conditional_block |
directiveHostEventsPlugin.ts | import {DirectiveDefinitionEvent, DirectiveDefinitionType} from '@slicky/core/metadata';
import {forEach, exists} from '@slicky/utils';
import {OnProcessElementArgument} from '@slicky/templates-compiler';
import {BuilderFunction} from '@slicky/templates-compiler/builder';
import * as _ from '@slicky/html-parser';
impor... | extends AbstractDirectivePlugin
{
public onBeforeProcessDirective(element: _.ASTHTMLNodeElement, directive: ElementProcessingDirective, arg: OnProcessElementArgument): void
{
if (directive.directive.metadata.type !== DirectiveDefinitionType.Directive) {
return
}
forEach(directive.directive.metadata.event... | DirectiveHostEventsPlugin | identifier_name |
index.js | // @flow
import React, { Component } from 'react'
import styled from 'styled-components'
import { injectIntl, type IntlShape } from 'react-intl'
import LoginButton from './LoginButton'
import Loading from './Loading'
import ErrorNotify from './ErrorNotify'
import Input from './Input'
import Feild from './Feild'
import ... | (event.target instanceof HTMLInputElement) {
this.setState({ password: event.target.value })
}
}
handleClick = () => {
this.props.onClick(this.state.username, this.state.password)
}
render() {
const { isLoginFailure, isLoading, intl } = this.props
if (isLoading) {
return <Loading... | if | identifier_name |
index.js | // @flow
import React, { Component } from 'react'
import styled from 'styled-components'
import { injectIntl, type IntlShape } from 'react-intl'
import LoginButton from './LoginButton'
import Loading from './Loading'
import ErrorNotify from './ErrorNotify'
import Input from './Input'
import Feild from './Feild'
import ... | }
render() {
const { isLoginFailure, isLoading, intl } = this.props
if (isLoading) {
return <Loading />
}
const { username, password } = this.state
return (
<Wrap>
{isLoginFailure && <ErrorNotify />}
<Feild>
<Input
placeholder={intl.formatMes... |
handleClick = () => {
this.props.onClick(this.state.username, this.state.password) | random_line_split |
cpu-utilization.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ApiResponse } from '../models/api-response';
import { CpuStatus } from '../models/cpu-status';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class CpuUtiliza... | (private http: Http) { }
getApiStatus(): Observable<ApiResponse<string>> {
let response = this.http.get('/api/cpu/status').map((res: Response) => res.json() as ApiResponse<string>);
return response;
};
getCpuUtilization(offset: number, limit: number): Observable<ApiResponse<Array<Cp... | constructor | identifier_name |
cpu-utilization.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ApiResponse } from '../models/api-response';
import { CpuStatus } from '../models/cpu-status';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class CpuUtiliza... |
getApiStatus(): Observable<ApiResponse<string>> {
let response = this.http.get('/api/cpu/status').map((res: Response) => res.json() as ApiResponse<string>);
return response;
};
getCpuUtilization(offset: number, limit: number): Observable<ApiResponse<Array<CpuStatus>>> {
le... | { } | identifier_body |
cpu-utilization.service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ApiResponse } from '../models/api-response';
import { CpuStatus } from '../models/cpu-status';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class CpuUtiliza... | return response;
};
getCpuUtilization(offset: number, limit: number): Observable<ApiResponse<Array<CpuStatus>>> {
let response = this.http.get("/api/cpu/utilization"
+ "?offset=" + (offset || 0)
+ "&limit=" + (limit || 50)
).map((res: Response) => res.json... |
getApiStatus(): Observable<ApiResponse<string>> {
let response = this.http.get('/api/cpu/status').map((res: Response) => res.json() as ApiResponse<string>);
| random_line_split |
make_confidence_report_bundle_examples.py | #!/usr/bin/env python3
"""
make_confidence_report_bundle_examples.py
Usage:
make_confidence_report_bundle_examples.py model.joblib a.npy
make_confidence_report_bundle_examples.py model.joblib a.npy b.npy c.npy
where model.joblib is a file created by cleverhans.serial.save containing
a picklable cleverhans.mode... |
report_path = FLAGS.report_path
if report_path is None:
suffix = "_bundled_examples_report.joblib"
assert model_filepath.endswith('.joblib')
report_path = model_filepath[:-len('.joblib')] + suffix
goal = MaxConfidence()
bundle_examples_with_goal(sess, model, adv_x_list, y, goal,
... | assert adv_x.shape == x.shape, (adv_x.shape, x.shape)
# Make sure these were made for the right dataset with right scaling
# arguments, etc.
assert adv_x.min() >= 0. - dataset.kwargs['center'] * dataset.max_val
assert adv_x.max() <= dataset.max_val
data_range = dataset.max_val * (1. + dataset.kwargs... | conditional_block |
make_confidence_report_bundle_examples.py | #!/usr/bin/env python3
"""
make_confidence_report_bundle_examples.py
Usage:
make_confidence_report_bundle_examples.py model.joblib a.npy
make_confidence_report_bundle_examples.py model.joblib a.npy b.npy c.npy
where model.joblib is a file created by cleverhans.serial.save containing
a picklable cleverhans.mode... | (argv=None):
"""
Make a confidence report and save it to disk.
"""
assert len(argv) >= 3
_name_of_script = argv[0]
model_filepath = argv[1]
adv_x_filepaths = argv[2:]
sess = tf.Session()
with sess.as_default():
model = serial.load(model_filepath)
factory = model.dataset_factory
factory.kwarg... | main | identifier_name |
make_confidence_report_bundle_examples.py | #!/usr/bin/env python3
"""
make_confidence_report_bundle_examples.py
Usage:
make_confidence_report_bundle_examples.py model.joblib a.npy
make_confidence_report_bundle_examples.py model.joblib a.npy b.npy c.npy
where model.joblib is a file created by cleverhans.serial.save containing
a picklable cleverhans.mode... |
if __name__ == '__main__':
flags.DEFINE_string('report_path', None, 'Report path')
flags.DEFINE_integer('train_start', TRAIN_START, 'Starting point (inclusive)'
'of range of train examples to use')
flags.DEFINE_integer('train_end', TRAIN_END, 'Ending point (non-inclusive) '
... | """
Make a confidence report and save it to disk.
"""
assert len(argv) >= 3
_name_of_script = argv[0]
model_filepath = argv[1]
adv_x_filepaths = argv[2:]
sess = tf.Session()
with sess.as_default():
model = serial.load(model_filepath)
factory = model.dataset_factory
factory.kwargs['train_start'... | identifier_body |
make_confidence_report_bundle_examples.py | #!/usr/bin/env python3
"""
make_confidence_report_bundle_examples.py
Usage:
make_confidence_report_bundle_examples.py model.joblib a.npy
make_confidence_report_bundle_examples.py model.joblib a.npy b.npy c.npy
where model.joblib is a file created by cleverhans.serial.save containing
a picklable cleverhans.mode... | Usually example_i.npy is the output of make_confidence_report.py or
make_confidence_report_bundled.py.
This script uses max-confidence attack bundling
( https://openreview.net/forum?id=H1g0piA9tQ )
to combine adversarial example datasets that were created earlier.
It will save a ConfidenceReport to to model_bundle... | random_line_split | |
transformText.js | 'use strict';
import indent from './indent.js';
import transformCategories from './transformCategories.js';
/**
* Transforms data to text.
*
* @param {object} data - Normalized data from `GitHubInspectOrgs` to transform.
* @param {object} options - Optional parameters:
* ```
* (boolean) descr... | if (depth > 0 && lastEntry && maxDepth) { tail += '\n'; }
resultString += `Core: limit: ${entry.core.limit}, remaining: ${entry.core.remaining}, reset: ${
new Date(entry.core.reset)}\n${indent(depth)}Search: limit: ${entry.search.limit}, remaining: ${
entry.search.remaining}, res... | random_line_split | |
transformText.js | 'use strict';
import indent from './indent.js';
import transformCategories from './transformCategories.js';
/**
* Transforms data to text.
*
* @param {object} data - Normalized data from `GitHubInspectOrgs` to transform.
* @param {object} options - Optional parameters:
* ```
* (boolean) descr... |
resultString += `${JSON.stringify(entry)}${tail}`;
break;
}
return resultString;
}; | { tail += '\n'; } | conditional_block |
parser.py | from datetime import datetime
from argparse import ArgumentParser
import pprint
import time
import warnings
import os, sys, io
import signal
import beretta
import importlib
__author__ = 'holly'
class Parser(object):
def __init__(self):
self.parser = ArgumentParser(description=beretta.__doc__)
... | self.subparsers = self.parser.add_subparsers(help='sub-command --help', dest='subparser_name')
def run(self, loader=None):
if loader is None:
loader = importlib.import_module("beretta.loader").Loader()
plugins = {}
for (name, import_plugin) in loader.plugins():
... | random_line_split | |
parser.py | from datetime import datetime
from argparse import ArgumentParser
import pprint
import time
import warnings
import os, sys, io
import signal
import beretta
import importlib
__author__ = 'holly'
class Parser(object):
def | (self):
self.parser = ArgumentParser(description=beretta.__doc__)
self.parser.add_argument('--version', action='version', version='%(prog)s ' + beretta.__version__)
self.subparsers = self.parser.add_subparsers(help='sub-command --help', dest='subparser_name')
def run(self, loader=None):
... | __init__ | identifier_name |
parser.py | from datetime import datetime
from argparse import ArgumentParser
import pprint
import time
import warnings
import os, sys, io
import signal
import beretta
import importlib
__author__ = 'holly'
class Parser(object):
| def __init__(self):
self.parser = ArgumentParser(description=beretta.__doc__)
self.parser.add_argument('--version', action='version', version='%(prog)s ' + beretta.__version__)
self.subparsers = self.parser.add_subparsers(help='sub-command --help', dest='subparser_name')
def run(self, load... | identifier_body | |
parser.py | from datetime import datetime
from argparse import ArgumentParser
import pprint
import time
import warnings
import os, sys, io
import signal
import beretta
import importlib
__author__ = 'holly'
class Parser(object):
def __init__(self):
self.parser = ArgumentParser(description=beretta.__doc__)
... |
plugins[name] = plugin
args = self.parser.parse_args()
if args.subparser_name in plugins:
plugins[args.subparser_name].run_plugin(args)
else:
self.parser.print_help()
| plugin_parser.add_argument(*args, **kwargs) | conditional_block |
issue-9951.rs | // Copyright 2015 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 ... | // pretty-expanded FIXME #23616
#![allow(unused_variables)]
trait Bar {
fn noop(&self);
}
impl Bar for u8 {
fn noop(&self) {}
}
fn main() {
let (a, b) = (&5u8 as &Bar, &9u8 as &Bar);
let (c, d): (&Bar, &Bar) = (a, b);
let (a, b) = (Box::new(5u8) as Box<Bar>, Box::new(9u8) as Box<Bar>);
let (c, d... | random_line_split | |
issue-9951.rs | // Copyright 2015 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 (a, b) = (&5u8 as &Bar, &9u8 as &Bar);
let (c, d): (&Bar, &Bar) = (a, b);
let (a, b) = (Box::new(5u8) as Box<Bar>, Box::new(9u8) as Box<Bar>);
let (c, d): (&Bar, &Bar) = (&*a, &*b);
let (c, d): (&Bar, &Bar) = (&5, &9);
}
| main | identifier_name |
issue-9951.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn main() {
let (a, b) = (&5u8 as &Bar, &9u8 as &Bar);
let (c, d): (&Bar, &Bar) = (a, b);
let (a, b) = (Box::new(5u8) as Box<Bar>, Box::new(9u8) as Box<Bar>);
let (c, d): (&Bar, &Bar) = (&*a, &*b);
let (c, d): (&Bar, &Bar) = (&5, &9);
}
| {} | identifier_body |
backup.rs | use std;
use std::io::{self, Write, Read};
use std::fs;
// pub use decompress::decompress;
pub use compress::compress;
extern crate byteorder; //needed for lz4
extern crate rustc_serialize; //needed for lz4
extern crate docopt;
extern crate seahash; //to hash the blocks
extern crate rusqlite; //to save to backup arch... | (block_size: usize) -> Block {
Block {
serial: String::from(""),
hash: String::from(""),
data_blob: Vec::with_capacity(block_size),
duplicate: String::from("FALSE"),
}
}
}
pub fn backup(block_size: usize,
compression_type: &String,
... | new | identifier_name |
backup.rs | use std;
use std::io::{self, Write, Read};
use std::fs;
// pub use decompress::decompress;
pub use compress::compress;
extern crate byteorder; //needed for lz4
extern crate rustc_serialize; //needed for lz4
extern crate docopt;
extern crate seahash; //to hash the blocks
extern crate rusqlite; //to save to backup arch... | commit_block_to_sqlite(&sqlite_connection, ¤t_block);
if !silent_option {
print!("Blocks: {}, Duplicates: {}. Read: {} MiB, Dedup saving: {:.2} MiB",
block_counter,
duplicate_blocks_foun... | random_line_split | |
backup.rs | use std;
use std::io::{self, Write, Read};
use std::fs;
// pub use decompress::decompress;
pub use compress::compress;
extern crate byteorder; //needed for lz4
extern crate rustc_serialize; //needed for lz4
extern crate docopt;
extern crate seahash; //to hash the blocks
extern crate rusqlite; //to save to backup arch... |
fn print_backup_status_update(block_counter: u64, duplicate_blocks_found: u32, block_size: usize) {
print!("Blocks processed: {}, Duplicates found: {}, Maximum theoretical dedup saving: {:.2} \
MiB",
block_counter,
duplicate_blocks_found,
(duplicate_blocks_found * bloc... | {
connection.execute("INSERT INTO blocks_table (serial, hash, data, duplicate) VALUES (?1,?2,?3,?4)",
&[&block.serial, &block.hash, &block.data_blob, &block.duplicate])
.expect("Error encountered during backup, aborting. Error Code:409");
} | identifier_body |
backup.rs | use std;
use std::io::{self, Write, Read};
use std::fs;
// pub use decompress::decompress;
pub use compress::compress;
extern crate byteorder; //needed for lz4
extern crate rustc_serialize; //needed for lz4
extern crate docopt;
extern crate seahash; //to hash the blocks
extern crate rusqlite; //to save to backup arch... | else {
current_block.data_blob = block_vector.clone();//data into here
}
}
commit_block_to_sqlite(&sqlite_connection, ¤t_block);
if !silent_option {
print!("Blocks: {}, Dupli... | {
current_block.data_blob = compress(&block_vector);//compress data into here
} | conditional_block |
defaults.py | #
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# Copyright (c) 2017-2018, NVIDIA CORPORATION. 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... | _C.MODEL = CN()
_C.MODEL.RPN_ONLY = False
_C.MODEL.MASK_ON = False
_C.MODEL.DEVICE = "cuda"
_C.MODEL.META_ARCHITECTURE = "GeneralizedRCNN"
# If the WEIGHT starts with a catalog://, like :R-50, the code will look for
# the path in paths_catalog. Else, it will use it as the specified absolute
# path
_C.MODEL.WEIGHT = ""... | random_line_split | |
indexer_exceptions.py | # coding=utf-8
# URL: https://pymedusa.com
#
# This file is part of Medusa.
#
# Medusa is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.... | indexer_showincomplete = tvdb_showincomplete | indexer_attributenotfound = tvdb_attributenotfound
indexer_episodenotfound = tvdb_episodenotfound
indexer_seasonnotfound = tvdb_seasonnotfound
indexer_shownotfound = tvdb_shownotfound | random_line_split |
24.rs | use std::fs::File;
use std::io::Read;
fn | () -> std::io::Result<String> {
let mut file = File::open("24.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn list_subsets(numbers: &Vec<usize>, sum: usize, start_index: usize) -> Vec<Vec<usize>> {
if sum == 0 {
return vec![vec![]];
} el... | get_input | identifier_name |
24.rs | use std::fs::File;
use std::io::Read;
fn get_input() -> std::io::Result<String> {
let mut file = File::open("24.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn list_subsets(numbers: &Vec<usize>, sum: usize, start_index: usize) -> Vec<Vec<usize>> |
fn main() {
let input = get_input().unwrap();
let numbers = input.lines().filter_map(|line| match line.parse::<usize>() {
Ok(x) => Some(x),
Err(_) => None
}).collect::<Vec<_>>();
let bucket_size = numbers.iter().sum::<usize>() / 3;
let buckets = list_subsets(&numbers, bucket_size,... | {
if sum == 0 {
return vec![vec![]];
} else if start_index >= numbers.len() {
return vec![];
}
numbers
.iter()
.enumerate()
.skip(start_index)
.filter(|&(_, &x)| x <= sum)
.flat_map(|(i, &x)| {
list_subsets(numbers, sum - x, i + 1)
.into_iter()
... | identifier_body |
24.rs | use std::fs::File;
use std::io::Read;
fn get_input() -> std::io::Result<String> {
let mut file = File::open("24.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn list_subsets(numbers: &Vec<usize>, sum: usize, start_index: usize) -> Vec<Vec<usize>> {
... | })
.collect()
}
fn main() {
let input = get_input().unwrap();
let numbers = input.lines().filter_map(|line| match line.parse::<usize>() {
Ok(x) => Some(x),
Err(_) => None
}).collect::<Vec<_>>();
let bucket_size = numbers.iter().sum::<usize>() / 3;
let buckets = list_subsets... | .map(move |mut subset| {
subset.push(x);
subset
}) | random_line_split |
problem17.rs | ///
/// Computes how many letters there would be if we write out all the numbers
/// from 1 to 1000 in British Egnlish.
///
fn main() {
let zero_to_ten = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3];
let eleven_to_nineteen = [0, 6, 6, 8, 8, 7, 7, 9, 8, 8];
let twenty_to_ninety = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6];
let... | let mut x: uint;
let mut remainder: uint;
let mut wholes: uint;
let mut sum: uint = zero_to_ten[1] + thousand;
for i in range(1, 1000) {
x = i;
if x > 99 {
wholes = x / 100u;
if x % 100 != 0 {
sum += zero_to_ten[wholes] + hundred ... | let and = 3;
| random_line_split |
problem17.rs | ///
/// Computes how many letters there would be if we write out all the numbers
/// from 1 to 1000 in British Egnlish.
///
fn main() | {
let zero_to_ten = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3];
let eleven_to_nineteen = [0, 6, 6, 8, 8, 7, 7, 9, 8, 8];
let twenty_to_ninety = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6];
let hundred = 7;
let thousand = 8;
let and = 3;
let mut x: uint;
let mut remainder: uint;
let mut wholes: uint;
... | identifier_body | |
problem17.rs | ///
/// Computes how many letters there would be if we write out all the numbers
/// from 1 to 1000 in British Egnlish.
///
fn | () {
let zero_to_ten = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3];
let eleven_to_nineteen = [0, 6, 6, 8, 8, 7, 7, 9, 8, 8];
let twenty_to_ninety = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6];
let hundred = 7;
let thousand = 8;
let and = 3;
let mut x: uint;
let mut remainder: uint;
let mut wholes: uint;
... | main | identifier_name |
Tasks.js | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Pro... | () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-tasks`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--respo... | render | identifier_name |
Tasks.js | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Pro... |
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
}; |
Icon.displayName = 'Tasks'; | random_line_split |
stdio.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 ... | <F>(f: F) where F: FnOnce(&mut Writer) -> IoResult<()> {
let mut my_stdout = LOCAL_STDOUT.with(|slot| {
slot.borrow_mut().take()
}).unwrap_or_else(|| {
box stdout() as Box<Writer + Send>
});
let result = f(&mut *my_stdout);
let mut var = Some(my_stdout);
LOCAL_STDOUT.with(|slot| ... | with_task_stdout | identifier_name |
stdio.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 ... |
/// Creates an unbuffered handle to the stderr of the current process
///
/// See notes in `stdout()` for more information.
pub fn stderr_raw() -> StdWriter {
src(libc::STDERR_FILENO, false, |src| StdWriter { inner: src })
}
/// Resets the task-local stdout handle to the specified writer
///
/// This will replac... | {
LineBufferedWriter::new(stderr_raw())
} | identifier_body |
stdio.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 ... | pub fn read_line(&mut self) -> IoResult<String> {
self.inner.lock().unwrap().0.read_line()
}
/// Like `Buffer::read_until`.
///
/// The read is performed atomically - concurrent read calls in other
/// threads will not interleave with this one.
pub fn read_until(&mut self, byte: u8)... | /// The read is performed atomically - concurrent read calls in other
/// threads will not interleave with this one. | random_line_split |
gpm-test.js | #!/usr/bin/env node
/*
The Cedric's Swiss Knife (CSK) - CSK terminal toolbox test suite
Copyright (c) 2009 - 2014 Cédric Ronvel
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in... | console.log( 'Mouse event received:' , name , data ) ;
} ) ;
setTimeout( function() { process.exit() ; } , 15000 ) ; |
handler.on( 'mouse' , function( name , data ) { | random_line_split |
backendMock.ts | import {AnyCoinCode, BlockchainCode, IApi, IBackendApi, IStoredTransaction} from "@emeraldwallet/core";
import {
AddEntry,
BlockchainType,
EntryId,
IdSeedReference,
isReference,
SeedDefinition,
SeedDescription,
SeedReference,
UnsignedTx,
Uuid,
AddressBookItem,
Wallet,
IEmeraldVault,
AddressR... |
}
export class BlockchainMock {
// address -> coin -> balance
balances: Record<string, Record<string, string>> = {};
setBalance(address: string, coin: AnyCoinCode, balance: string) {
if (typeof this.balances[address] == 'undefined') {
this.balances[address] = {};
}
this.balances[address][coin... | {
if (this.seeds.indexOf(seedId) < 0) {
this.seeds.push(seedId);
this.seedAddresses[seedId] = {};
}
this.seedAddresses[seedId][hdpath] = address;
} | identifier_body |
backendMock.ts | import {AnyCoinCode, BlockchainCode, IApi, IBackendApi, IStoredTransaction} from "@emeraldwallet/core";
import {
AddEntry,
BlockchainType,
EntryId,
IdSeedReference,
isReference,
SeedDefinition,
SeedDescription,
SeedReference,
UnsignedTx,
Uuid,
AddressBookItem,
Wallet,
IEmeraldVault,
AddressR... |
const result: { [key: string]: string } = {};
tokens.forEach((token) => {
if (state.balances[address]) {
const balance = state.balances[address][token];
if (balance) {
result[token] = balance;
} else {
result[token] = "0";
}
} else {
resul... | {
return Promise.resolve({});
} | conditional_block |
backendMock.ts | import {AnyCoinCode, BlockchainCode, IApi, IBackendApi, IStoredTransaction} from "@emeraldwallet/core";
import {
AddEntry,
BlockchainType,
EntryId,
IdSeedReference,
isReference,
SeedDefinition,
SeedDescription,
SeedReference,
UnsignedTx,
Uuid,
AddressBookItem,
Wallet,
IEmeraldVault,
AddressR... | (blockchain: BlockchainCode, address: string, tokens: AnyCoinCode[]): Promise<Record<string, string>> {
const state = this.blockchains[blockchain.toLowerCase()];
if (typeof state == 'undefined') {
return Promise.resolve({});
}
const result: { [key: string]: string } = {};
tokens.forEach((token... | getBalance | identifier_name |
backendMock.ts | import {AnyCoinCode, BlockchainCode, IApi, IBackendApi, IStoredTransaction} from "@emeraldwallet/core";
import {
AddEntry,
BlockchainType,
EntryId,
IdSeedReference,
isReference,
SeedDefinition,
SeedDescription,
SeedReference,
UnsignedTx,
Uuid,
AddressBookItem,
Wallet,
IEmeraldVault,
AddressR... | constructor(vault: MemoryVault) {
this.vault = vault;
}
listSeedAddresses(seedId: Uuid | SeedReference | SeedDefinition, blockchain: number, hdpaths: string[]): Promise<{ [key: string]: string }> {
console.log("list addresses", seedId);
if (typeof seedId == "object") {
if (seedId.type == "id") ... | export class VaultMock implements IEmeraldVault {
readonly vault: MemoryVault;
| random_line_split |
single_value.ts | /*
MIT License
Copyright (c) 2022 Looker Data Sciences, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modi... | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import type { VisWrapperProps } from '../VisWrapper'
import type {
SupportedChartTypes,
SDKRecord,
Fields,
ChartLayoutProps,
} from '../types'
import type { CSeriesBasic } from '@looker/visualizations'
export type ... | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | random_line_split |
startJobProcessor.js | "use strict";
var debug = require('debug')('ansijet-job-processor'),
co = require('co'),
path = require('path'),
thunkify = require('thunkify'),
waigo = require('waigo');
var timers = waigo.load('support/timers');
var buildTimerHandler = function(app, maxParallelJobs) {
return co(function*() {
var... | }; | onError: function(err) {
app.logger.error('Job processing error: ' + err.message);
}
}
).start(); | random_line_split |
startJobProcessor.js | "use strict";
var debug = require('debug')('ansijet-job-processor'),
co = require('co'),
path = require('path'),
thunkify = require('thunkify'),
waigo = require('waigo');
var timers = waigo.load('support/timers');
var buildTimerHandler = function(app, maxParallelJobs) {
return co(function*() {
var... |
}
// run all the new jobs in parallel
yield jobsToExecute.map(function(j) {
return j.execute();
});
});
};
/**
* Start the job processor.
*
* This should be the last startup step which gets run to ensure that the
* rest of app is ready and loaded.
*
* The job processor picks up newl... | {
// add this job to execution queue
jobsToExecute.push(nextPendingJob);
// update other lists
processingJobs.push(nextPendingJob);
playbookProcessingJobs[nextPendingJob.trigger.playbook] = true;
} | conditional_block |
main.js | var dropzoneOverlay = document.querySelector('.dropzone-overlay');
function getDataTransferFiles(event) {
var dataTransferItemsList = [];
if (event.dataTransfer) {
var dt = event.dataTransfer;
if (dt.files && dt.files.length) {
dataTransferItemsList = dt.files;
} else if (dt... | }
} else if (event.target && event.target.files) {
dataTransferItemsList = event.target.files;
}
if (dataTransferItemsList.length > 0) {
dataTransferItemsList = [dataTransferItemsList[0]];
}
// Convert from DataTransferItemsList to the native Array
return Array.prototyp... | // During the drag even the dataTransfer.files is null
// but Chrome implements some drag store, which is accesible via dataTransfer.items
dataTransferItemsList = dt.items; | random_line_split |
main.js | var dropzoneOverlay = document.querySelector('.dropzone-overlay');
function getDataTransferFiles(event) {
var dataTransferItemsList = [];
if (event.dataTransfer) {
var dt = event.dataTransfer;
if (dt.files && dt.files.length) {
dataTransferItemsList = dt.files;
} else if (dt... | () {
dropzoneOverlay.className = 'dropzone-overlay';
}
function onFileDragEnter(ev) {
ev.preventDefault();
showDragFocus();
}
function onFileDragOver(ev) {
ev.preventDefault();
}
function onFileDrop(ev) {
ev.preventDefault();
hideDragFocus();
var fileList = getDataTransferFiles(ev);
... | hideDragFocus | identifier_name |
main.js | var dropzoneOverlay = document.querySelector('.dropzone-overlay');
function getDataTransferFiles(event) {
var dataTransferItemsList = [];
if (event.dataTransfer) {
var dt = event.dataTransfer;
if (dt.files && dt.files.length) {
dataTransferItemsList = dt.files;
} else if (dt... |
// Convert from DataTransferItemsList to the native Array
return Array.prototype.slice.call(dataTransferItemsList);
}
function showDragFocus() {
dropzoneOverlay.className = 'dropzone-overlay active';
}
function hideDragFocus() {
dropzoneOverlay.className = 'dropzone-overlay';
}
function onFileDrag... | {
dataTransferItemsList = [dataTransferItemsList[0]];
} | conditional_block |
main.js | var dropzoneOverlay = document.querySelector('.dropzone-overlay');
function getDataTransferFiles(event) {
var dataTransferItemsList = [];
if (event.dataTransfer) {
var dt = event.dataTransfer;
if (dt.files && dt.files.length) {
dataTransferItemsList = dt.files;
} else if (dt... |
function drawImage(canvas, imageBitmap) {
var ctx = canvas.getContext('2d');
ctx.drawImage(file, 0, 0);
}
function updateStickerImage(file) {
var reader = new FileReader();
reader.onload = function(ev) {
var dataURL = ev.target.result;
document.querySelectorAll('.sticker-img').forEach... | {
ev.preventDefault();
console.log(ev.target)
if (ev.target !== document.body) {
return;
}
hideDragFocus();
} | identifier_body |
FileParser.py | # This is a separate module for parser functions to be added.
# This is being created as static, so only one parser exists for the whole game.
from nota import Nota
from timingpoint import TimingPoint
from tools import *
import random
import math
def get_Name (osufile):
Splitlines = osufile.split('\n')
for Line in ... | if ntype == 1 or ntype == 5:
nota = Nota(posx, posy, time, sprites[random.randint(0,3)], screen_width, screen_height, 1)
NoteList.append(nota)
elif ntype == 2 or ntype == 6:
## THE GOD LINE
## this.sliderTime = game.getBeatLength() * (hitObject.getPixelLength() / sliderMultiplier) / 100f;
curv... | time = int(params[2])
ntype = int(params[3])
IgnoreFirstLine = True | random_line_split |
FileParser.py | # This is a separate module for parser functions to be added.
# This is being created as static, so only one parser exists for the whole game.
from nota import Nota
from timingpoint import TimingPoint
from tools import *
import random
import math
def get_Name (osufile):
Splitlines = osufile.split('\n')
for Line in ... |
def get_BreakPeriods(osufile):
Lines = osufile.split('\n')
BreakPString = []
BreakPoints = []
save = False;
for line in Lines:
if line.find("//") == -1:
if save:
BreakPString.append(line)
else:
save = False
if line.find("//Break Periods") != -1:
save = True
for splitted in BreakP... | NoteList = []
SplitLines = []
#This function returns a list of notes with all their properties to the user
#Make sure you have a list to receive it
SplitLines = osufile.split('[HitObjects]\r\n', 1)
SplitObjects = SplitLines[1].split('\n')
for Line in SplitObjects:
if len(Line) > 0:
params = Line.split(',')
... | identifier_body |
FileParser.py | # This is a separate module for parser functions to be added.
# This is being created as static, so only one parser exists for the whole game.
from nota import Nota
from timingpoint import TimingPoint
from tools import *
import random
import math
def get_Name (osufile):
Splitlines = osufile.split('\n')
for Line in ... |
else:
save = False
if line.find("//Break Periods") != -1:
save = True
for splitted in BreakPString:
params = splitted.split(",")
StartBreakTime = int(params[1])
EndBreakTime = int(params[2])
BreakPoints.append((StartBreakTime, EndBreakTime))
#print(BreakPoints)
return BreakPoints
| BreakPString.append(line) | conditional_block |
FileParser.py | # This is a separate module for parser functions to be added.
# This is being created as static, so only one parser exists for the whole game.
from nota import Nota
from timingpoint import TimingPoint
from tools import *
import random
import math
def | (osufile):
Splitlines = osufile.split('\n')
for Line in Splitlines:
if len(Line) > 0:
if Line.find('Title:', 0, len(Line)) != -1:
title = Line.split(':', 1)
return title[1].replace("\r", "")
def get_PreviewTime (osufile):
Splitlines = osufile.split('\n')
for Line in Splitlines:
if len(Line) > 0:
i... | get_Name | identifier_name |
host_daily_profile.py | # -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2017 Michal Stefanik <stefanik dot m@mail.muni.cz>, Tomas Jirsik <jirsik@ics.muni.cz>
# Institute of Computer Science, Masaryk University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated document... |
return merge
# post-processing methods for resulting temporal arrays:
def send_to_kafka(data, producer, topic):
"""
Send given data to the specified kafka topic.
:param data: data to send
:param producer: producer that sends the data
:param topic: name of the receiving kafka topic
"""
... | merge.append(a1[i] if a1[i] != ZERO_ITEM else a2[i]) | conditional_block |
host_daily_profile.py | # -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2017 Michal Stefanik <stefanik dot m@mail.muni.cz>, Tomas Jirsik <jirsik@ics.muni.cz>
# Institute of Computer Science, Masaryk University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated document... |
def modulate_position(timestamp):
"""
counts the position in time-sorted log of IP activity as based on the timestamp attached to
the particular log in rdd
timestamp: attached timestamp
"""
result = (INCREMENT - timestamp) % time_dimension
return result
def update_array(array, position,... | """
increments the global counter that should keep consistent with the duration of the app run in hours
"""
global INCREMENT
INCREMENT += 1 | identifier_body |
host_daily_profile.py | # -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2017 Michal Stefanik <stefanik dot m@mail.muni.cz>, Tomas Jirsik <jirsik@ics.muni.cz>
# Institute of Computer Science, Masaryk University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated document... | "bytes": ip_stats[stat_idx].bytes,
"flows": ip_stats[stat_idx].flows}
stats_dict[stat_idx] = temporal_stats
# construct the output object in predefined format
result_dict = {"@type": "host_stats_temporal_profile",
... | stats_dict = dict()
for stat_idx in range(len(ip_stats)):
temporal_stats = {"packets": ip_stats[stat_idx].packets, | random_line_split |
host_daily_profile.py | # -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2017 Michal Stefanik <stefanik dot m@mail.muni.cz>, Tomas Jirsik <jirsik@ics.muni.cz>
# Institute of Computer Science, Masaryk University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated document... | (stats_json):
"""
Performs a hourly aggregation on input data, which result is to be collected as items of daily aggregation
:param stats_json: RDDs of stats in json format matching the output format of host_stats.py application
:type stats_json: Initialized spark streaming context, with data in json fo... | collect_hourly_stats | identifier_name |
racao-lote.pipe.ts | import { RacaoLote } from './../../../shared/entity/produto/racao-lote';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filtroPorRacaoLote'
})
export class FiltroPorRacaoLote implements PipeTransform {
transform(racaoLotes: RacaoLote[], digitado: string) {
if (!racaoLotes || !dig... | else if (key === 'dataLote' || key === 'dataValidade') {
let dataLocal = new Date(item[key]);
let ano = dataLocal.toLocaleDateString().substring(6, 10);
let mes = dataLocal.toLocaleDateString().substring(3, 5);
let dia = dataLocal.toLocale... | {
var tempString = item[key] + '';
if (tempString.indexOf(digitado) !== -1) {
return true;
}
} | conditional_block |
racao-lote.pipe.ts | import { RacaoLote } from './../../../shared/entity/produto/racao-lote';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filtroPorRacaoLote'
})
export class FiltroPorRacaoLote implements PipeTransform {
| (racaoLotes: RacaoLote[], digitado: string) {
if (!racaoLotes || !digitado) {
return racaoLotes;
}
// return racaoLotes.filter((lote) => {
// return pessoa.nome.toLowerCase().includes(digitado) ||
// pessoa.tipoPessoa.toLowerCase().includes(digitado);
... | transform | identifier_name |
racao-lote.pipe.ts | import { RacaoLote } from './../../../shared/entity/produto/racao-lote';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filtroPorRacaoLote'
})
export class FiltroPorRacaoLote implements PipeTransform {
transform(racaoLotes: RacaoLote[], digitado: string) {
if (!racaoLotes || !dig... | return racaoLotes.filter((item: any) => {
for (let key in item) {
if ((typeof item[key] === 'string' || item[key] instanceof String) &&
(item[key].toUpperCase().indexOf(digitado.toUpperCase()) !== -1)) {
return true;
} else if (... | // return racaoLotes.filter((lote) => {
// return pessoa.nome.toLowerCase().includes(digitado) ||
// pessoa.tipoPessoa.toLowerCase().includes(digitado);
// });
| random_line_split |
common.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 21 10:34:18 2014
@author: eegroopm
"""
import os, sys
import pandas as pd
import numpy as np
class | :
def __init__(self):
self.path = os.path.expanduser('~')
#\u0305 is unicode overline character
#self._overline_strings = [u'1\u0305', u'2\u0305' ,u'3\u0305', u'4\u0305', u'5\u0305', u'6\u0305', u'7\u0305',u'8\u0305',u'9\u0305']
#use matplotlib's mathtex rendering for overline string... | common | identifier_name |
common.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 21 10:34:18 2014
@author: eegroopm
"""
import os, sys
import pandas as pd
import numpy as np
class common:
def __init__(self):
|
def Wavelength(self,E):
hbar = 6.626E-34 #m^2 kg/s
me = 9.109E-31 #kg
c = 3E8 #m/s
e = 1.602E-19 #Coulombs
E = E*1000 #turn to eV
wavelength = hbar/np.sqrt(2*me*e*E)/np.sqrt(1 + (e*E)/(2*me*c**2))*(10**10) #angstroms. relativistic formula
return(... | self.path = os.path.expanduser('~')
#\u0305 is unicode overline character
#self._overline_strings = [u'1\u0305', u'2\u0305' ,u'3\u0305', u'4\u0305', u'5\u0305', u'6\u0305', u'7\u0305',u'8\u0305',u'9\u0305']
#use matplotlib's mathtex rendering for overline strings
self._overline_strings =... | identifier_body |
common.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 21 10:34:18 2014
@author: eegroopm
"""
import os, sys
import pandas as pd
import numpy as np
class common:
def __init__(self):
self.path = os.path.expanduser('~')
#\u0305 is unicode overline character
#self._overline_strings = [u'1\u0305', u'2... |
self.manualConds = [] #empty list of strings for manual conditions
def Wavelength(self,E):
hbar = 6.626E-34 #m^2 kg/s
me = 9.109E-31 #kg
c = 3E8 #m/s
e = 1.602E-19 #Coulombs
E = E*1000 #turn to eV
wavelength = hbar/np.sqrt(2*me*e*E)/np.s... | self.sg = pd.read_hdf('resources/SpaceGroups_py2.h5','table')
self.sghex = pd.read_hdf('resources/SpaceGroupsHex_py2.h5','table')
self.mineraldb = pd.read_hdf('resources/MineralDatabase_py2.h5','table') | conditional_block |
common.py | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 21 10:34:18 2014 | """
import os, sys
import pandas as pd
import numpy as np
class common:
def __init__(self):
self.path = os.path.expanduser('~')
#\u0305 is unicode overline character
#self._overline_strings = [u'1\u0305', u'2\u0305' ,u'3\u0305', u'4\u0305', u'5\u0305', u'6\u0305', u'7\u0305',u'8\u0305',u'9\... |
@author: eegroopm | random_line_split |
i_PA_DeprjDist.py |
import numpy as np
from astropy.coordinates import Angle, Distance
from astropy import units as u
from .angles2Plane import gal_theta
def vdm_2001_dep_dist_kpc(rho, phi, glx_theta, glx_incl, D_0):
"""
Deprojected angular distance from vdM & Cioni (2001).
D is the distance associated to a point defined ... |
def main(rho, phi, inc_lst, pa_lst, gal_dist):
"""
Calculate deprojected distances for all clusters in this galaxy,
for all inclination and position angles defined.
These values depend on the coordinates of the clusters (rho, phi), the
rotation angles that define each inclined plane (inc_lst, pa... | """
Computes deprojected galactocentric distance between cluster and the
center of the MC in kpc.
Based on: https://gist.github.com/jonathansick/9399842
Parameters
----------
glx_PA : :class:`astropy.coordinates.Angle`
Position angle of the galaxy disk.
glx_incl : :class:`astropy.c... | identifier_body |
i_PA_DeprjDist.py |
import numpy as np
from astropy.coordinates import Angle, Distance
from astropy import units as u
from .angles2Plane import gal_theta
def vdm_2001_dep_dist_kpc(rho, phi, glx_theta, glx_incl, D_0):
"""
Deprojected angular distance from vdM & Cioni (2001).
D is the distance associated to a point defined ... |
return dep_dist_i_PA_vals
| for j, pa in enumerate(pa_lst):
# Assign 'degrees' units before passing.
inc, pa = Angle(inc, unit=u.degree), Angle(pa, unit=u.degree)
# Obtain deprojected distances for all the clusters, in kpc,
# using the values of inclination and position angles passed.
d... | conditional_block |
i_PA_DeprjDist.py | import numpy as np
from astropy.coordinates import Angle, Distance
from astropy import units as u
from .angles2Plane import gal_theta
def vdm_2001_dep_dist_kpc(rho, phi, glx_theta, glx_incl, D_0):
"""
Deprojected angular distance from vdM & Cioni (2001).
D is the distance associated to a point defined by... |
The plane itself is defined by its center coordinates (ra_0, dec_0),
included in the (rho, phi) values passed, the distance to those
coordinates (D_0), and the inclination (rotation) angles: glx_theta,
glx_incl.
d_kpc is the distance from point (ra, dec, D) to the center of said plane,
i.e.: (... | random_line_split | |
i_PA_DeprjDist.py |
import numpy as np
from astropy.coordinates import Angle, Distance
from astropy import units as u
from .angles2Plane import gal_theta
def vdm_2001_dep_dist_kpc(rho, phi, glx_theta, glx_incl, D_0):
"""
Deprojected angular distance from vdM & Cioni (2001).
D is the distance associated to a point defined ... | (glx_PA, glx_incl, glx_dist, rho, phi):
"""
Computes deprojected galactocentric distance between cluster and the
center of the MC in kpc.
Based on: https://gist.github.com/jonathansick/9399842
Parameters
----------
glx_PA : :class:`astropy.coordinates.Angle`
Position angle of the g... | get_deproj_dist | identifier_name |
userassist.py | # -*- coding: utf-8 -*-
"""Windows UserAssist information collector."""
import codecs
import logging
from winregrc import data_format
from winregrc import errors
from winregrc import interface
class UserAssistEntry(object):
"""UserAssist entry.
Attributes:
guid (str): GUID.
name (str): name.
value_... | value_string = '{0:.2f}'.format(user_assist_entry.unknown10)
self._DebugPrintValue('Unknown10', value_string)
value_string = '{0:.2f}'.format(user_assist_entry.unknown11)
self._DebugPrintValue('Unknown11', value_string)
value_string = '0x{0:08x}'.format(user_assist_entry.unknown12)
... | random_line_split | |
userassist.py | # -*- coding: utf-8 -*-
"""Windows UserAssist information collector."""
import codecs
import logging
from winregrc import data_format
from winregrc import errors
from winregrc import interface
class UserAssistEntry(object):
"""UserAssist entry.
Attributes:
guid (str): GUID.
name (str): name.
value_... |
def Collect(self, registry): # pylint: disable=arguments-differ
"""Collects the UserAssist information.
Args:
registry (dfwinreg.WinRegistry): Windows Registry.
Returns:
bool: True if the UserAssist key was found, False if not.
"""
user_assist_key = registry.GetKeyByPath(self._USE... | user_assist_entry = self._parser.ParseEntry(format_version, value.data)
user_assist_entry = UserAssistEntry(
guid=guid_subkey.name, name=value_name, value_name=value.name)
self.user_assist_entries.append(user_assist_entry) | conditional_block |
userassist.py | # -*- coding: utf-8 -*-
"""Windows UserAssist information collector."""
import codecs
import logging
from winregrc import data_format
from winregrc import errors
from winregrc import interface
class UserAssistEntry(object):
"""UserAssist entry.
Attributes:
guid (str): GUID.
name (str): name.
value_... | (self, registry): # pylint: disable=arguments-differ
"""Collects the UserAssist information.
Args:
registry (dfwinreg.WinRegistry): Windows Registry.
Returns:
bool: True if the UserAssist key was found, False if not.
"""
user_assist_key = registry.GetKeyByPath(self._USER_ASSIST_KEY)
... | Collect | identifier_name |
userassist.py | # -*- coding: utf-8 -*-
"""Windows UserAssist information collector."""
import codecs
import logging
from winregrc import data_format
from winregrc import errors
from winregrc import interface
class UserAssistEntry(object):
"""UserAssist entry.
Attributes:
guid (str): GUID.
name (str): name.
value_... |
class UserAssistDataParser(data_format.BinaryDataFormat):
"""UserAssist data parser."""
_DEFINITION_FILE = 'userassist.yaml'
# pylint: disable=missing-type-doc
def _DebugPrintEntry(self, format_version, user_assist_entry):
"""Prints UserAssist entry value debug information.
Args:
format_vers... | """Initializes an UserAssist entry.
Args:
guid (Optional[str]): GUID.
name (Optional[str]): name.
value_name (Optional[str]): name of the Windows Registry value.
"""
super(UserAssistEntry, self).__init__()
self.guid = guid
self.name = name
self.value_name = value_name | identifier_body |
test_ghost_check_dao.py | from datetime import datetime, timedelta
from rdr_service.dao.ghost_check_dao import GhostCheckDao
from tests.helpers.unittest_base import BaseTestCase
class GhostCheckDaoTest(BaseTestCase):
def test_loads_only_vibrent(self):
"""We might accidentally start flagging CE participants as ghosts if they're re... | (self):
"""Ensure we get back the ghost data field"""
ghost_participant = self.data_generator.create_database_participant(
participantOrigin='vibrent',
isGhostId=True
)
self.data_generator.create_database_participant(
participantOrigin='vibrent',
... | test_ghost_flag_returned | identifier_name |
test_ghost_check_dao.py | from datetime import datetime, timedelta
from rdr_service.dao.ghost_check_dao import GhostCheckDao
from tests.helpers.unittest_base import BaseTestCase
class GhostCheckDaoTest(BaseTestCase):
def test_loads_only_vibrent(self):
"""We might accidentally start flagging CE participants as ghosts if they're re... | """Ensure we get back the ghost data field"""
ghost_participant = self.data_generator.create_database_participant(
participantOrigin='vibrent',
isGhostId=True
)
self.data_generator.create_database_participant(
participantOrigin='vibrent',
isGhostId... | identifier_body | |
test_ghost_check_dao.py | from datetime import datetime, timedelta
from rdr_service.dao.ghost_check_dao import GhostCheckDao
from tests.helpers.unittest_base import BaseTestCase
class GhostCheckDaoTest(BaseTestCase):
def test_loads_only_vibrent(self):
"""We might accidentally start flagging CE participants as ghosts if they're re... |
else:
self.assertFalse(participant.isGhostId)
| self.assertTrue(participant.isGhostId) | conditional_block |
test_ghost_check_dao.py | from datetime import datetime, timedelta
from rdr_service.dao.ghost_check_dao import GhostCheckDao
from tests.helpers.unittest_base import BaseTestCase
class GhostCheckDaoTest(BaseTestCase):
def test_loads_only_vibrent(self):
"""We might accidentally start flagging CE participants as ghosts if they're re... | )
self.data_generator.create_database_participant(
participantOrigin='vibrent',
isGhostId=None
)
self.data_generator.create_database_participant(
participantOrigin='vibrent',
isGhostId=False
)
results = GhostCheckDao.get_pa... | """Ensure we get back the ghost data field"""
ghost_participant = self.data_generator.create_database_participant(
participantOrigin='vibrent',
isGhostId=True | random_line_split |
main.js | $(document).ready(function(){
/*
// footer hide
$('footer').hide();
// random team-member order
var members = [
['Octavio', 'Biologist', 'https://pingendo.com/assets/photos/user_placeholder.png'],
['Franco', 'Phycisist', 'https://pingendo.com/assets/photos/user_placeholder.png'],
['Cezar', 'C.S. ... | });
}); | random_line_split | |
objectiveUtils.js | (function () {
'use strict';
window.HeVinci = window.HeVinci || {};
window.HeVinci.ObjectiveUtils = Utils;
/**
* Initializes the helper for a given context. Supported contexts are:
*
* - "objectives" Admin management page of objectives
* - "myObjectives" User objectives p... |
/**
* Insert multiple rows as "children" of a given row.
*
* @param {HTMLTableRowElement} parentRow
* @param {Array} data
* @param {String} type
* @param {Number} [indent]
*/
Utils.prototype.insertChildRows = function (parentRow, data,... | {
var rowTemplates = {
objectives: 'ObjectiveRow',
myObjectives: 'MyObjectiveRow',
users: 'UserObjectiveRow',
groups: 'GroupObjectiveRow'
};
if (!(context in rowTemplates)) {
throw new Error('Unknown context "' + context + '"');
... | identifier_body |
objectiveUtils.js | (function () {
'use strict';
window.HeVinci = window.HeVinci || {};
window.HeVinci.ObjectiveUtils = Utils;
/**
* Initializes the helper for a given context. Supported contexts are:
*
* - "objectives" Admin management page of objectives
* - "myObjectives" User objectives p... |
var self = this;
var row = removeLink.parentNode.parentNode;
var route = 'hevinci_remove_' + target + '_objective';
var params = {};
params['objectiveId'] = row.dataset.id;
params[target + 'Id'] = row.dataset.path.match(/^(\d+)\-*/)[1]; // target id is the root in the ... | {
throw new Error('Invalid target');
} | conditional_block |
objectiveUtils.js | (function () {
'use strict';
window.HeVinci = window.HeVinci || {};
window.HeVinci.ObjectiveUtils = Utils;
/**
* Initializes the helper for a given context. Supported contexts are:
*
* - "objectives" Admin management page of objectives
* - "myObjectives" User objectives p... | if (target !== 'user' && target !== 'group') {
throw new Error('Invalid target');
}
var self = this;
var row = removeLink.parentNode.parentNode;
var route = 'hevinci_remove_' + target + '_objective';
var params = {};
params['objectiveId'] = row.datas... | Utils.prototype.removeSubjectObjectiveRow = function (removeLink, target) { | random_line_split |
objectiveUtils.js | (function () {
'use strict';
window.HeVinci = window.HeVinci || {};
window.HeVinci.ObjectiveUtils = Utils;
/**
* Initializes the helper for a given context. Supported contexts are:
*
* - "objectives" Admin management page of objectives
* - "myObjectives" User objectives p... | (context) {
var rowTemplates = {
objectives: 'ObjectiveRow',
myObjectives: 'MyObjectiveRow',
users: 'UserObjectiveRow',
groups: 'GroupObjectiveRow'
};
if (!(context in rowTemplates)) {
throw new Error('Unknown context "' + context + '"... | Utils | identifier_name |
layout-base.d.ts | declare module "ui/layouts/layout-base" {
import view = require("ui/core/view");
import dependencyObservable = require("ui/core/dependency-observable");
/**
* Base class for all views that supports children positioning.
*/
export class | extends view.CustomLayoutView {
public static clipToBoundsProperty: dependencyObservable.Property;
/**
* Returns the number of children in this Layout.
*/
getChildrenCount(): number;
/**
* Returns the view at the specified position.
* @param index ... | LayoutBase | identifier_name |
layout-base.d.ts | declare module "ui/layouts/layout-base" {
import view = require("ui/core/view");
import dependencyObservable = require("ui/core/dependency-observable");
/**
* Base class for all views that supports children positioning.
*/
export class LayoutBase extends view.CustomLayoutView {
publi... | */
addChild(view: view.View): void;
/**
* Inserts the view to children array at the specified index.
* @param view The view to be added to the end of the children array.
* @param atIndex The insertion index.
*/
insertChild(child: view.View, atIndex: ... | random_line_split | |
util.rs | //! Misc. helper functions and utilities used in multiple parts of the application.
use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};
use std::str::FromStr;
use itertools::Itertools;
use serde_json;
use super::{CompositionTree, CompositionTreeNode, CompositionTreeNodeDefinition, MasterConf};
use c... | {
X,
Y,
Z,
}
impl FromStr for Dim {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"X" | "x" => Ok(Dim::X),
"Y" | "y" => Ok(Dim::Y),
"Z" | "z" => Ok(Dim::Z),
_ => Err(format!("Can't convert supplied string to ... | Dim | identifier_name |
util.rs | //! Misc. helper functions and utilities used in multiple parts of the application.
use std::collections::HashMap;
use std::convert::{TryFrom, TryInto};
use std::str::FromStr;
use itertools::Itertools;
use serde_json;
use super::{CompositionTree, CompositionTreeNode, CompositionTreeNodeDefinition, MasterConf};
use c... | pub fn find_setting_by_name(name: &str, settings: &[IrSetting]) -> Result<String, String> {
Ok(settings
.iter()
.find(|&&IrSetting { ref key, .. }| key == name)
.ok_or(String::from(
"No `moduleType` setting provided to node of type `noiseModule`!",
))?.value
.clon... | /// Searches through a slice of `IrSetting`s provided to a node and attempts to find the setting with the supplied name. | random_line_split |
adnoce.js | var db = require('mongoose');
var Log = require('log'), log = new Log('info');
var clienttracking = require('./clienttracking.js');
var mapreduce = require('./mapreduce.js');
var io = null;
exports.server = require('./adnoceserver.js');
exports.setDatabase = function(databaseConfiguration, callback) {
var port = ... |
var pushServerHealth = function(serverOSObject) {
io.emit('health', {uptime: serverOSObject.uptime(), load: serverOSObject.loadavg(), memory: {total: serverOSObject.totalmem(), free: serverOSObject.freemem()}});
}
exports.pushServerHealth = pushServerHealth; | exports.addEvent = function(type, name, sessionId, additionalData) {
clienttracking.addEvent(type, name, sessionId, additionalData);
};
exports.MapReduce = mapreduce.MapReduce; | random_line_split |
adnoce.js | var db = require('mongoose');
var Log = require('log'), log = new Log('info');
var clienttracking = require('./clienttracking.js');
var mapreduce = require('./mapreduce.js');
var io = null;
exports.server = require('./adnoceserver.js');
exports.setDatabase = function(databaseConfiguration, callback) {
var port = ... |
};
exports.addEvent = function(type, name, sessionId, additionalData) {
clienttracking.addEvent(type, name, sessionId, additionalData);
};
exports.MapReduce = mapreduce.MapReduce;
var pushServerHealth = function(serverOSObject) {
io.emit('health', {uptime: serverOSObject.uptime(), load: serverOSObject.loadavg... | {
res.send(200, '1');
var additionalData = req.adnoceData || {};
if (req.param('t')) additionalData.adnocetype = req.param('t');
clienttracking.updateSessionData(req.sessionID, req.param('p'), additionalData);
} | conditional_block |
gk_graphic.py | #!/urs/bin/python
import os
import graphviz
# from gk_node import GKNode
# from gk_link import GKLink
class | (object):
"""Manage graphic"""
def __init__(self, label=None):
self.m_label = label
self.m_nodes_list = []
self.m_link_list = []
def add_link(self, link):
"""add link and related node to the diagram"""
if link is None:
return False
self.m_link_li... | GKGraphic | identifier_name |
gk_graphic.py | #!/urs/bin/python
import os
import graphviz
# from gk_node import GKNode
# from gk_link import GKLink
class GKGraphic(object):
"""Manage graphic"""
def __init__(self, label=None):
|
def add_link(self, link):
"""add link and related node to the diagram"""
if link is None:
return False
self.m_link_list.append(link)
if link.m_node1 not in self.m_nodes_list:
self.m_nodes_list.append(link.m_node1)
if link.m_node2 not in self.m_nodes... | self.m_label = label
self.m_nodes_list = []
self.m_link_list = [] | identifier_body |
gk_graphic.py | #!/urs/bin/python
import os
import graphviz
# from gk_node import GKNode
# from gk_link import GKLink
class GKGraphic(object):
"""Manage graphic"""
def __init__(self, label=None):
self.m_label = label
self.m_nodes_list = []
self.m_link_list = []
| self.m_link_list.append(link)
if link.m_node1 not in self.m_nodes_list:
self.m_nodes_list.append(link.m_node1)
if link.m_node2 not in self.m_nodes_list:
self.m_nodes_list.append(link.m_node2)
return True
def render(self, filename, extension="pdf", size=None):... | def add_link(self, link):
"""add link and related node to the diagram"""
if link is None:
return False
| random_line_split |
gk_graphic.py | #!/urs/bin/python
import os
import graphviz
# from gk_node import GKNode
# from gk_link import GKLink
class GKGraphic(object):
"""Manage graphic"""
def __init__(self, label=None):
self.m_label = label
self.m_nodes_list = []
self.m_link_list = []
def add_link(self, link):
"... |
if link.m_node2 not in self.m_nodes_list:
self.m_nodes_list.append(link.m_node2)
return True
def render(self, filename, extension="pdf", size=None):
"""generate the graphic and save result as an image"""
if filename is None:
return False
if size:
... | self.m_nodes_list.append(link.m_node1) | conditional_block |
test_document.py | from mock import patch, Mock
from nose.tools import istest
from unittest import TestCase
from structominer import Document, Field
class DocumentTests(TestCase):
@istest
def creating_document_object_with_string_should_automatically_parse(self):
html = '<html></html>'
with patch('structom... | doc = Doc(html)
self.assertTrue(doc.one.parse.called)
self.assertFalse(doc.two.parse.called) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.