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 |
|---|---|---|---|---|
mod.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... | save_data: &mut SaveData,
) -> Mode {
let view = {
let visible_rect = window.visible_rect();
View::new(
&mut window.resources(),
visible_rect,
&save_data.game_mut().column_as_icy_em,
)
};
run_puzzle(window, save_data, view)
}
// ==============... | // ========================================================================= //
pub fn run_column_as_icy_em(
window: &mut Window, | random_line_split |
__init__.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | @@LinearRegressor
@@LogisticRegressor
@@Experiment
@@ExportStrategy
@@TaskType
@@NanLossDuringTrainingError
@@RunConfig
@@evaluate
@@infer
@@run_feeds
@@run_n
@@train
@@extract_dask_data
@@extract_dask_labels
@@extract_pandas_data
@@extract_pandas_labels
@@extract_pandas_matrix
@@infer_real_valued_columns_from_input... | @@DNNLinearCombinedClassifier
@@LinearClassifier | random_line_split |
slow.rs | num);
// We have 2 major algorithms we use for this:
// 1. An algorithm with a finite number of digits and a positive exponent.
// 2. An algorithm with a finite number of digits and a negative exponent.
let (bigmant, digits) = parse_mantissa(integer, fraction, F::MAX_DIGITS);
let exponent = sci_e... | <F: Float>(mut bigmant: Bigint, exponent: i32) -> ExtendedFloat {
// Simple, we just need to multiply by the power of the radix.
// Now, we can calculate the mantissa and the exponent from this.
// The binary exponent is the binary exponent for the mantissa
// shifted to the hidden bit.
bigmant.pow(... | positive_digit_comp | identifier_name |
slow.rs | num);
// We have 2 major algorithms we use for this:
// 1. An algorithm with a finite number of digits and a positive exponent.
// 2. An algorithm with a finite number of digits and a negative exponent.
let (bigmant, digits) = parse_mantissa(integer, fraction, F::MAX_DIGITS);
let exponent = sci_e... | exp,
};
// Shift the digits into position and determine if we need to round-up.
round::<F, _>(&mut fp, |f, s| {
round_nearest_tie_even(f, s, |is_odd, is_halfway, is_above| {
is_above || (is_halfway && is_truncated) || (is_odd && is_halfway)
});
});
fp
}
/// Gene... | let mut fp = ExtendedFloat {
mant, | random_line_split |
slow.rs | num);
// We have 2 major algorithms we use for this:
// 1. An algorithm with a finite number of digits and a positive exponent.
// 2. An algorithm with a finite number of digits and a negative exponent.
let (bigmant, digits) = parse_mantissa(integer, fraction, F::MAX_DIGITS);
let exponent = sci_e... | is_above || (is_halfway && is_truncated) || (is_odd && is_halfway)
});
});
fp
}
/// Generate the significant digits with a negative exponent relative to mantissa.
///
/// This algorithm is quite simple: we have the significant digits `m1 * b^N1`,
/// where `m1` is the bigint mantissa, `b` ... | {
// Simple, we just need to multiply by the power of the radix.
// Now, we can calculate the mantissa and the exponent from this.
// The binary exponent is the binary exponent for the mantissa
// shifted to the hidden bit.
bigmant.pow(10, exponent as u32).unwrap();
// Get the exact representat... | identifier_body |
specialization_graph.rs | insert(&mut self,
tcx: TyCtxt<'a, 'gcx, 'tcx>,
impl_def_id: DefId,
simplified_self: Option<SimplifiedType>)
-> Result<Inserted, OverlapError>
{
let mut last_lint = None;
let mut replace_children = Vec::new();
debug!(
"inse... | Node | identifier_name | |
specialization_graph.rs | ()
}
}
// A custom iterator used by Children::insert
enum PotentialSiblings<I, J>
where I: Iterator<Item = DefId>,
J: Iterator<Item = DefId>
{
Unfiltered(I),
Filtered(J)
}
impl<I, J> Iterator for PotentialSiblings<I, J>
where I: Iterator<Item = DefId>,
J: Iterator<Item = DefId>... | }
}
| random_line_split | |
grade_dialogue.js | // This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle is dis... |
/**
* Opens the picker.
*
* @param {Number} competencyId The competency ID of the competency to work on.
* @method display
* @return {Promise}
*/
Grade.prototype.display = function() {
return this._render().then(function(html) {
return Str.get_string('rate', 't... | this._popup.close();
this._popup = null;
}; | random_line_split |
grade_dialogue.js | // This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle is dis... | lse {
btnRate.prop('disabled', false);
}
}).change();
btnRate.click(function(e) {
e.preventDefault();
var val = lstRating.val();
if (!val) {
return;
}
this._trigger('rated', {
'rating... | btnRate.prop('disabled', true);
} e | conditional_block |
mastermodel.py | import os
import json
from PySide2 import QtCore
from opencmiss.zinc.context import Context
from opencmiss.zinc.material import Material
from mapclientplugins.meshgeneratorstep.model.meshgeneratormodel import MeshGeneratorModel
from mapclientplugins.meshgeneratorstep.model.meshannotationmodel import MeshAnnotationMo... |
def getMeshAnnotationModel(self):
return self._annotation_model
def getSegmentationDataModel(self):
return self._segmentation_data_model
def getScene(self):
return self._region.getScene()
def getContext(self):
return self._context
def registerSceneChangeCallback... | return self._generator_model | identifier_body |
mastermodel.py | import os
import json
from PySide2 import QtCore
from opencmiss.zinc.context import Context
from opencmiss.zinc.material import Material
from mapclientplugins.meshgeneratorstep.model.meshgeneratormodel import MeshGeneratorModel
from mapclientplugins.meshgeneratorstep.model.meshannotationmodel import MeshAnnotationMo... | (self):
return self._context
def registerSceneChangeCallback(self, sceneChangeCallback):
self._generator_model.registerSceneChangeCallback(sceneChangeCallback)
def done(self):
self._saveSettings()
self._generator_model.done()
self._generator_model.writeModel(self.getOut... | getContext | identifier_name |
mastermodel.py | import os
import json
from PySide2 import QtCore
from opencmiss.zinc.context import Context
from opencmiss.zinc.material import Material
from mapclientplugins.meshgeneratorstep.model.meshgeneratormodel import MeshGeneratorModel
from mapclientplugins.meshgeneratorstep.model.meshannotationmodel import MeshAnnotationMo... |
def _initialise(self):
self._filenameStem = os.path.join(self._location, self._identifier)
tess = self._context.getTessellationmodule().getDefaultTessellation()
tess.setRefinementFactors(12)
# set up standard materials and glyphs so we can use them elsewhere
self._materialm... | print(logger.getMessageTextAtIndex(index)) | conditional_block |
mastermodel.py | import os |
from opencmiss.zinc.context import Context
from opencmiss.zinc.material import Material
from mapclientplugins.meshgeneratorstep.model.meshgeneratormodel import MeshGeneratorModel
from mapclientplugins.meshgeneratorstep.model.meshannotationmodel import MeshAnnotationModel
from mapclientplugins.meshgeneratorstep.model.... | import json
from PySide2 import QtCore | random_line_split |
main.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | (
project, location="us-central1", workflow="myFirstWorkflow"
):
"""Execute a workflow and print the execution results."""
# [START workflows_api_quickstart]
import time
from google.cloud import workflows_v1beta
from google.cloud.workflows import executions_v1beta
from google.cloud.workflow... | execute_workflow | identifier_name |
main.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | project = os.environ.get('GOOGLE_CLOUD_PROJECT')
execute_workflow(project=project) | conditional_block | |
main.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Construct the fully qualified location path.
parent = workflows_client.workflow_path(project, location, workflow)
# Execute the workflow.
response = execution_client.create_execution(request={"parent": parent})
print(f"Created execution: {response.name}")
# Wait for execution to finish, then... | """Execute a workflow and print the execution results."""
# [START workflows_api_quickstart]
import time
from google.cloud import workflows_v1beta
from google.cloud.workflows import executions_v1beta
from google.cloud.workflows.executions_v1beta.types import executions
# TODO(developer): Uncom... | identifier_body |
main.py | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # project = 'my-project-id'
# location = 'us-central1'
# workflow = 'myFirstWorkflow'
if not project:
raise Exception('GOOGLE_CLOUD_PROJECT env var is required.')
# Set up API clients.
execution_client = executions_v1beta.ExecutionsClient()
workflows_client = workflows_v1beta.Workf... | from google.cloud import workflows_v1beta
from google.cloud.workflows import executions_v1beta
from google.cloud.workflows.executions_v1beta.types import executions
# TODO(developer): Uncomment these lines and replace with your values. | random_line_split |
result.service.ts | import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {SearchResults} from "./search_results.model";
import {LazyLoadEvent} from "primeng/components/common/api";
import {Observable} from "rxjs/Observable";
@Injectable()
export class | {
private resultUrl = 'http://localhost:8100/search_results/limit/'; // URL to web api
constructor(private http: Http) {}
getResults(event: LazyLoadEvent): Observable<SearchResults> {
let url = this.resultUrl+`?page=${event.first/event.rows}&limit=${event.rows}`;
return this.http.get(url)
.map(... | SearchResultService | identifier_name |
result.service.ts | import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {SearchResults} from "./search_results.model";
import {LazyLoadEvent} from "primeng/components/common/api";
import {Observable} from "rxjs/Observable";
@Injectable()
export class SearchResultService {
private resultUrl =... | } else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
} | let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`; | random_line_split |
result.service.ts | import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {SearchResults} from "./search_results.model";
import {LazyLoadEvent} from "primeng/components/common/api";
import {Observable} from "rxjs/Observable";
@Injectable()
export class SearchResultService {
private resultUrl =... |
console.error(errMsg);
return Observable.throw(errMsg);
}
}
| {
errMsg = error.message ? error.message : error.toString();
} | conditional_block |
result.service.ts | import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {SearchResults} from "./search_results.model";
import {LazyLoadEvent} from "primeng/components/common/api";
import {Observable} from "rxjs/Observable";
@Injectable()
export class SearchResultService {
private resultUrl =... |
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.s... | {
let body = res.json();
return body || { };
} | identifier_body |
deprecated_fields.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree. | use common::{Diagnostic, DiagnosticTag, DiagnosticsResult, NamedItem, WithLocation};
use graphql_ir::{
ExecutableDefinition, LinkedField, Program, ScalarField, ValidationMessage, Validator, Value,
};
use intern::string_key::{Intern, StringKey};
use lazy_static::lazy_static;
use schema::{FieldID, SDLSchema, Schema};... | */
use std::sync::Arc;
| random_line_split |
deprecated_fields.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::sync::Arc;
use common::{Diagnostic, DiagnosticTag, DiagnosticsResult, NamedItem, WithLocation};
use graphql_ir::{
E... | (&mut self, field: &ScalarField) -> DiagnosticsResult<()> {
self.validate_field(&field.definition);
self.default_validate_scalar_field(field)
}
fn validate_value(&mut self, value: &Value) -> DiagnosticsResult<()> {
// TODO: `@deprecated` is allowed on Enum values, so technically we
... | validate_scalar_field | identifier_name |
deprecated_fields.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::sync::Arc;
use common::{Diagnostic, DiagnosticTag, DiagnosticsResult, NamedItem, WithLocation};
use graphql_ir::{
E... |
pub fn deprecated_fields_for_executable_definition(
schema: &Arc<SDLSchema>,
definition: &ExecutableDefinition,
) -> DiagnosticsResult<Vec<Diagnostic>> {
let mut validator = DeprecatedFields::new(schema);
match definition {
ExecutableDefinition::Fragment(fragment) => validator.validate_fragme... | {
let mut validator = DeprecatedFields::new(schema);
validator.validate_program(program)?;
Ok(validator.warnings)
} | identifier_body |
_app_statistic.js | (function($, Backbone, _) {
"use strict";
var name_prefix = '{{ name }}'
, catalogKey = '{{ catalog_key }}'
|
name: "StatisticApplication"
, preinitialize: function(options){
var uses = [
catalogKey
, 'StatisticView'
]
this.uses = _.union(this.uses, uses)
}
, initialize: function(options){
// catalog app
... | // The Module
// --------------
var Module = BBNS.Module.extend({ | random_line_split |
tinymce_setup.js | //For submit articles
tinymce.init({
selector: '#content',
directionality:'ltr',
language:'zh_CN', | 'save table contextmenu directionality emoticons template paste textcolor',
'codesample',
],
toolbar: 'insertfile undo redo | \
styleselect | \
bold italic | \
alignleft aligncenter alignright alignjustify | \
bullist numlist outdent indent | \
link image | \
... | height:400,
plugins: [
'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking', | random_line_split |
queries.js | var Db = require('../lib/mongodb').Db,
Connection = require('../lib/mongodb').Connection,
Server = require('../lib/mongodb').Server;
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.e... |
collection.find({'a':/[1|2]/}, {'hint':'a'}, function(err, cursor) {
cursor.explain(function(err, doc) {
console.log("-------------------------- Explanation");
console.dir(doc);
db.close();
})
});
});
... | random_line_split | |
cluster_msa_processing.py | import re
import os
import sys
from Bio import Seq
from Bio import SeqIO
import pandas as pd
import itertools
import numpy as np
path = "/home/venevs/fludb_pH1N1"
# seg5-GenomicFastaResults.fasta
# seg7.afa
centroids = SeqIO.parse(os.path.join(path,"nr.fasta"),"fasta")
clust_msa = SeqIO.parse(os.path.join(path,"seg1.... | # # countATGC = {}
# # length = {}
# data = {}
# for seg in segments:
# get_ATGC = lambda seq: seq.count('A')+seq.count('T')+seq.count('G')+seq.count('C')
# get_strain = lambda seqrec: seqrec.description.strip().split('|')[1]
# countATGC = []
# length = []
# strain = []
# for seqrec in segments[... | random_line_split | |
cluster_msa_processing.py | import re
import os
import sys
from Bio import Seq
from Bio import SeqIO
import pandas as pd
import itertools
import numpy as np
path = "/home/venevs/fludb_pH1N1"
# seg5-GenomicFastaResults.fasta
# seg7.afa
centroids = SeqIO.parse(os.path.join(path,"nr.fasta"),"fasta")
clust_msa = SeqIO.parse(os.path.join(path,"seg1.... |
# now extract aligned centroid sequences ...
centroids_aligned = [clust_msa[sid] for sid in centroids]
# output the alignment now ...
SeqIO.write(centroids_aligned,"centrs.afa","fasta")
# # now let's gather the statistics about each of the segments ...
# # segments with lots of non-ATGC letters ...
# # countATGC... | raise ValueError("All ids from centroids must match ids in clust_msa ...") | conditional_block |
ChatCtrl.ts | profiles: IProfile[],
server: {
ts: number,
pts: number,
server: string,
key: string,
},
}
interface executeGetHistoryResponse_History {
count: number,
items: IMessage[],
unread?: number
}
export class ChatCtrl {
currentMessMap: IMessageMap | undefined;
message: string;
isMore: boole... | module SectionsApp {
interface executeGetHistoryResponse {
history: executeGetHistoryResponse_History | random_line_split | |
ChatCtrl.ts | module SectionsApp {
interface executeGetHistoryResponse {
history: executeGetHistoryResponse_History
profiles: IProfile[],
server: {
ts: number,
pts: number,
server: string,
key: string,
},
}
interface executeGetHistoryResponse_History {
count: number,
items: IMessage[],
unread?: number... | (peer_id: number, offset = 0, count = 20) {
return this.$vk.api('execute.getHistory', {
access_token: this.$vk.stg.access_token,
peer_id,
count,
offset,
});
}
loadMore(peer_id: number) {
const targetMessMap = this.messMap.getMessMap(peer_id);
const offset = targetMessMap && targetMess... | loadHistory | identifier_name |
ChatCtrl.ts | module SectionsApp {
interface executeGetHistoryResponse {
history: executeGetHistoryResponse_History
profiles: IProfile[],
server: {
ts: number,
pts: number,
server: string,
key: string,
},
}
interface executeGetHistoryResponse_History {
count: number,
items: IMessage[],
unread?: number... |
onLongPollDone(API: any) {
this.LongPollParams.pts = API.new_pts;
if (angular.isArray(API.profiles)) {
this.storage.setProfiles(API.profiles);
}
if (!this.currentMessMap) return true;
angular.forEach(API.history, (event) => {
// console.log(event);
switch (event[0]) {
case 4 : {
... | {
const targetMessMap = this.messMap.getMessMap(peer_id);
const offset = targetMessMap && targetMessMap.items ? targetMessMap.items.length : 0;
return this.loadHistory(peer_id, offset).then((API: executeGetHistoryResponse) => {
this.storage.setProfiles(API.profiles);
this.messMap.insertMessages(peer_... | identifier_body |
ChatCtrl.ts | module SectionsApp {
interface executeGetHistoryResponse {
history: executeGetHistoryResponse_History
profiles: IProfile[],
server: {
ts: number,
pts: number,
server: string,
key: string,
},
}
interface executeGetHistoryResponse_History {
count: number,
items: IMessage[],
unread?: number... |
if (!this.currentMessMap) return true;
angular.forEach(API.history, (event) => {
// console.log(event);
switch (event[0]) {
case 4 : {
const [event_code, message_id, flags, peer_id] = event;
const message = API.messages.items.find((m: IMessage) => m.id === message_id);
this.mess... | {
this.storage.setProfiles(API.profiles);
} | conditional_block |
mod.rs | //! Serialization and encodings.
//!
//! This module provides encoding support enabled via Cargo features. Each
//! enabled encoding has a corresponding sub-module. For example, when [PLY]
//! support is enabled, the `ply` module is exposed. The following table
//! summarizes the encodings supported by Plexus:
//!
//! ... | // features to be supported, such as edge geometry for `MeshGraph`s.
pub trait FromEncoding<E>: Sized
where
E: FaceDecoder + VertexDecoder,
{
type Error: Debug;
fn from_encoding(
vertices: <E as VertexDecoder>::Output,
faces: <E as FaceDecoder>::Output,
) -> Result<Self, Self::Err... |
// TODO: This trait is a bit limiting. Consider implementing more specific
// traits like `FromPly` directly. This could allow more specific | random_line_split |
perftest.rs | use std::fs::File;
use std::path::Path;
use std::time::Instant;
use perftest_data::PerftestData;
use protobuf::Message;
use protobuf::MessageFull;
use rand::Rng;
use rand::SeedableRng;
use rand::StdRng;
mod perftest_data;
fn measure_ns<R, F: FnMut() -> R>(mut f: F) -> (u64, R) {
let start = Instant::now();
l... | random_data.len() as u64,
|| {
for m in &random_data {
m.write_length_delimited_to_vec(&mut buf).unwrap();
}
},
);
let read_data =
measure_and_print(&format!("{}: read", name), random_data.len() as u64, ... | measure_and_print(
&format!("{}: write", name), | random_line_split |
perftest.rs | use std::fs::File;
use std::path::Path;
use std::time::Instant;
use perftest_data::PerftestData;
use protobuf::Message;
use protobuf::MessageFull;
use rand::Rng;
use rand::SeedableRng;
use rand::StdRng;
mod perftest_data;
fn measure_ns<R, F: FnMut() -> R>(mut f: F) -> (u64, R) {
let start = Instant::now();
l... |
struct TestRunner {
data_size: u32,
selected: Option<String>,
any_matched: bool,
}
impl TestRunner {
fn run_test<M: MessageFull + Clone + PartialEq>(&self, name: &str, data: &[M]) {
assert!(data.len() > 0, "empty string for test: {}", name);
let mut rng: StdRng = SeedableRng::from_se... | {
let (ns, r) = measure_ns(f);
let ns_per_iter = ns / iter;
println!("{}: {} ns per iter", title, ns_per_iter);
r
} | identifier_body |
perftest.rs | use std::fs::File;
use std::path::Path;
use std::time::Instant;
use perftest_data::PerftestData;
use protobuf::Message;
use protobuf::MessageFull;
use rand::Rng;
use rand::SeedableRng;
use rand::StdRng;
mod perftest_data;
fn measure_ns<R, F: FnMut() -> R>(mut f: F) -> (u64, R) {
let start = Instant::now();
l... | {
data_size: u32,
selected: Option<String>,
any_matched: bool,
}
impl TestRunner {
fn run_test<M: MessageFull + Clone + PartialEq>(&self, name: &str, data: &[M]) {
assert!(data.len() > 0, "empty string for test: {}", name);
let mut rng: StdRng = SeedableRng::from_seed([
10... | TestRunner | identifier_name |
perftest.rs | use std::fs::File;
use std::path::Path;
use std::time::Instant;
use perftest_data::PerftestData;
use protobuf::Message;
use protobuf::MessageFull;
use rand::Rng;
use rand::SeedableRng;
use rand::StdRng;
mod perftest_data;
fn measure_ns<R, F: FnMut() -> R>(mut f: F) -> (u64, R) {
let start = Instant::now();
l... |
}
}
fn main() {
let args = std::env::args().collect::<Vec<_>>();
if args.len() > 3 {
panic!("usage: {} [data_size] [test]", args[0])
}
let data_size = args
.iter()
.nth(1)
.map(|x| x.parse().unwrap())
.unwrap_or(1000000);
let selected = args.iter().nth(2... | {
let name = self.selected.as_ref().map(|s| &s[..]).unwrap_or("bug");
panic!("no tests found with name {}", name);
} | conditional_block |
line_item.ts | import { TaxLine } from "./tax_line";
import { ShopifyObject } from "./base";
import { LineItemProperty } from "./line_item_property";
export interface LineItem extends ShopifyObject {
/// <summary>
/// The amount available to fulfill. This is the quantity - max(refunded_quantity, fulfilled_quantity) - pending... | /// </summary>
properties?: LineItemProperty[];
} | random_line_split | |
main.rs | use amiquip::{Connection, ConsumerMessage, ConsumerOptions, QueueDeclareOptions, Result};
fn main() -> Result<()> | other => {
println!("Consumer ended: {:?}", other);
break;
}
}
}
connection.close()
} | {
// Open connection.
let mut connection = Connection::insecure_open("amqp://guest:guest@mkstack_rabbitmq:5672")?;
// Open a channel - None says let the library choose the channel ID.
let channel = connection.open_channel(None)?;
// Declare the "hello" queue.
let queue = channel.queue_declare(... | identifier_body |
main.rs | use amiquip::{Connection, ConsumerMessage, ConsumerOptions, QueueDeclareOptions, Result};
fn main() -> Result<()> {
// Open connection.
let mut connection = Connection::insecure_open("amqp://guest:guest@mkstack_rabbitmq:5672")?;
// Open a channel - None says let the library choose the channel ID.
let ... | match message {
ConsumerMessage::Delivery(delivery) => {
let body = String::from_utf8_lossy(&delivery.body);
println!("({:>3}) Received [{}]", i, body);
consumer.ack(delivery)?;
}
other => {
println!("Consumer en... | random_line_split | |
main.rs | use amiquip::{Connection, ConsumerMessage, ConsumerOptions, QueueDeclareOptions, Result};
fn | () -> Result<()> {
// Open connection.
let mut connection = Connection::insecure_open("amqp://guest:guest@mkstack_rabbitmq:5672")?;
// Open a channel - None says let the library choose the channel ID.
let channel = connection.open_channel(None)?;
// Declare the "hello" queue.
let queue = chann... | main | identifier_name |
main.rs | //
// Copyright (C) 2017 Kubos Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
fn main() {
let graphql_endpoint =
GraphQLHandler::new(context_factory, schema::QueryRoot, schema::MutationRoot);
let graphiql_endpoint = GraphiQLHandler::new("/grapihql");
let mut mount = mount::Mount::new();
mount.mount("/", graphql_endpoint);
mount.mount("/graphiql", graphiql_endpoint... | {
schema::Context { subsystem: model::Subsystem::new() }
} | identifier_body |
main.rs | //
// Copyright (C) 2017 Kubos Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | () {
let graphql_endpoint =
GraphQLHandler::new(context_factory, schema::QueryRoot, schema::MutationRoot);
let graphiql_endpoint = GraphiQLHandler::new("/grapihql");
let mut mount = mount::Mount::new();
mount.mount("/", graphql_endpoint);
mount.mount("/graphiql", graphiql_endpoint);
l... | main | identifier_name |
main.rs | //
// Copyright (C) 2017 Kubos Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | let graphql_endpoint =
GraphQLHandler::new(context_factory, schema::QueryRoot, schema::MutationRoot);
let graphiql_endpoint = GraphiQLHandler::new("/grapihql");
let mut mount = mount::Mount::new();
mount.mount("/", graphql_endpoint);
mount.mount("/graphiql", graphiql_endpoint);
let (l... |
fn main() { | random_line_split |
bootstrap.ts | declare var System: any;
(function(global) {
writeScriptTag('/all/playground/vendor/es6-shim.js');
writeScriptTag('/all/playground/vendor/zone.js');
writeScriptTag('/all/playground/vendor/long-stack-trace-zone.js');
writeScriptTag('/all/playground/vendor/system.src.js');
writeScriptTag('/all/playground/ven... | // defaultExtension: 'js'
// },
'@angular/core': {main: 'index.js', defaultExtension: 'js'},
'@angular/compiler': {main: 'index.js', defaultExtension: 'js'},
'@angular/common': {main: 'index.js', defaultExtension: 'js'},
'@angular/platform-browser': {main: '... | // 'app': {
// main: 'index.js', | random_line_split |
bootstrap.ts | declare var System: any;
(function(global) {
writeScriptTag('/all/playground/vendor/es6-shim.js');
writeScriptTag('/all/playground/vendor/zone.js');
writeScriptTag('/all/playground/vendor/long-stack-trace-zone.js');
writeScriptTag('/all/playground/vendor/system.src.js');
writeScriptTag('/all/playground/ven... |
}(window));
| {
document.write(`<script src="${scriptUrl}" onload="${onload}"></script>`);
} | identifier_body |
bootstrap.ts | declare var System: any;
(function(global) {
writeScriptTag('/all/playground/vendor/es6-shim.js');
writeScriptTag('/all/playground/vendor/zone.js');
writeScriptTag('/all/playground/vendor/long-stack-trace-zone.js');
writeScriptTag('/all/playground/vendor/system.src.js');
writeScriptTag('/all/playground/ven... | (scriptUrl, onload?) {
document.write(`<script src="${scriptUrl}" onload="${onload}"></script>`);
}
}(window));
| writeScriptTag | identifier_name |
bootstrap.ts | declare var System: any;
(function(global) {
writeScriptTag('/all/playground/vendor/es6-shim.js');
writeScriptTag('/all/playground/vendor/zone.js');
writeScriptTag('/all/playground/vendor/long-stack-trace-zone.js');
writeScriptTag('/all/playground/vendor/system.src.js');
writeScriptTag('/all/playground/ven... | }
else {
console.warn(
"Not using the Angular bundles. Don't use this configuration for e2e/performance tests!");
System.config({
map: {'index': 'index.js', '@angular': '/all/@angular'},
packages: {
// 'app': {
// main: 'index.js',
// default... | {
System.config({
map: {
'index': 'index.js',
'@angular/core': '/packages-dist/core/bundles/core.umd.js',
'@angular/common': '/packages-dist/common/bundles/common.umd.js',
'@angular/compiler': '/packages-dist/compiler/bundles/compiler.umd.js',
'@angular/pl... | conditional_block |
common.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: common.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
import random
import time
import threading
import multiprocessing
import numpy as np
from tqdm import tqdm
from six.moves import queue
from tensorpack import *
from tensorpack.utils.concurrency import *
from tensor... | threads = [Worker(f, q) for f in predictors]
for k in threads:
k.start()
time.sleep(0.1) # avoid simulator bugs
stat = StatCounter()
try:
for _ in tqdm(range(nr_eval), **get_tqdm_kwargs()):
r = q.get()
stat.feed(r)
logger.info("Waiting for all th... | except RuntimeError:
return
self.queue_put_stoppable(self.q, score)
q = queue.Queue() | random_line_split |
common.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: common.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
import random
import time
import threading
import multiprocessing
import numpy as np
from tqdm import tqdm
from six.moves import queue
from tensorpack import *
from tensorpack.utils.concurrency import *
from tensor... |
def eval_with_funcs(predictors, nr_eval, get_player_fn):
class Worker(StoppableThread, ShareSessionThread):
def __init__(self, func, queue):
super(Worker, self).__init__()
self._func = func
self.q = queue
def func(self, *args, **kwargs):
if self.st... | score = play_one_episode(player, predfunc)
print("Total:", score) | conditional_block |
common.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: common.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
import random
import time
import threading
import multiprocessing
import numpy as np
from tqdm import tqdm
from six.moves import queue
from tensorpack import *
from tensorpack.utils.concurrency import *
from tensor... | (self, *args, **kwargs):
if self.stopped():
raise RuntimeError("stopped!")
return self._func(*args, **kwargs)
def run(self):
with self.default_sess():
player = get_player_fn(train=False)
while not self.stopped():
... | func | identifier_name |
common.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: common.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
import random
import time
import threading
import multiprocessing
import numpy as np
from tqdm import tqdm
from six.moves import queue
from tensorpack import *
from tensorpack.utils.concurrency import *
from tensor... | logger.info("Start evaluation: ")
for k in range(nr):
if k != 0:
player.restart_episode()
score = play_one_episode(player, predfunc)
print("{}/{}, score={}".format(k, nr, score)) | identifier_body | |
create.ts | import { RequestHandler } from 'express'
import validate from './validate'
import clone from '../git/clone'
import * as db from '../../data'
type Body = {
name: string
label: string
repository: string
key: string
dockerfile: string
}
const handler: RequestHandler = async (req, res) => {
const { repository... | const result: number[] = await db.applications()
.insert(body)
const id = result[0]
const app = { ...body, id }
res.json(app)
clone(app)
} catch (ex) {
res.status(500)
res.json({ message: ex.message || ex })
}
}
export default handler |
try { | random_line_split |
create.ts | import { RequestHandler } from 'express'
import validate from './validate'
import clone from '../git/clone'
import * as db from '../../data'
type Body = {
name: string
label: string
repository: string
key: string
dockerfile: string
}
const handler: RequestHandler = async (req, res) => {
const { repository... |
try {
const result: number[] = await db.applications()
.insert(body)
const id = result[0]
const app = { ...body, id }
res.json(app)
clone(app)
} catch (ex) {
res.status(500)
res.json({ message: ex.message || ex })
}
}
export default handler | {
const message = errors.join(', ')
res.status(400).json({ message })
return
} | conditional_block |
3_2_HelloWorld.py | #%%
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))
| batch_xs, batch_ys = mnist.train.next_batch(100)
train_step.run({x: batch_xs, y_: batch_ys}) | conditional_block |
3_2_HelloWorld.py | #%%
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | # ==============================================================================
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
pr... | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License. | random_line_split |
configuration.js | 'use strict';
const utils = require('../common/utils');
module.exports = {
instance : function (service, settings, initial) {
let _self = this;
let _service = service;
let _settings = settings || {};
let _default = initial;
let _overwrite = _settings.overwrite || false;
let _file = _settings.file || (se... |
}
};
_self.refresh = function () {
if (_default && _overwrite === true) {
_self.reset(_default);
_service.log.debug.config_overwrite_warning.args(_service.key).print();
} else {
if (_file) {
try {
let data = utils.internal.file.read(_file);
_self.reset(JSON.parse(data));
... | {
_self[i] = utils.general.data.copy(values[i]);
} | conditional_block |
configuration.js | 'use strict';
const utils = require('../common/utils');
module.exports = {
instance : function (service, settings, initial) {
let _self = this;
let _service = service;
let _settings = settings || {};
let _default = initial;
let _overwrite = _settings.overwrite || false;
let _file = _settings.file || (se... |
utils.internal.file.write(_file, {
text : JSON.stringify(data, null, 2),
replace : true
});
}
};
_self.reset = function (values) {
for (let i in _self) {
if (typeof _self[i] !== 'function') {
delete _self[i];
}
}
if (values) {
pushValues(values);
}
_self.sav... | } | random_line_split |
stats.py | class Stats:
"""
Contains the stats that a character or monster may have.
The stats tied to an agent are:
* Health: The amount of damage the agent can withstand. The agent dies when their health falls to zero. This is
the only stat that will persist after a battle ends.
* Stamina: An... | :
"""
Contains the stats that come from equipment. Only characters have equipment.
* Attack: Heavily influences physical attacks.
* Magic attack: Heavily influences magic attacks.
* Armour: Heavily influences physical defence.
* Magic armour: Heavily influences magic defence.
"""
... | EquipmentStats | identifier_name |
stats.py | class Stats:
"""
Contains the stats that a character or monster may have.
The stats tied to an agent are:
* Health: The amount of damage the agent can withstand. The agent dies when their health falls to zero. This is
the only stat that will persist after a battle ends.
* Stamina: An... | def __str__(self):
return str(self.__dict__) | self.armour = armour
self.magic_armour = magic_armour
| random_line_split |
stats.py | class Stats:
| self.stamina = stamina
self.strength = strength
self.magic = magic
self.endurance = endurance
self.agility = agility
def __str__(self):
return str(self.__dict__)
class EquipmentStats:
"""
Contains the stats that come from equipment. Only characte... | """
Contains the stats that a character or monster may have.
The stats tied to an agent are:
* Health: The amount of damage the agent can withstand. The agent dies when their health falls to zero. This is
the only stat that will persist after a battle ends.
* Stamina: An arbitrary measure... | identifier_body |
editor.py | """gui systems to manage actions
"""
import os
from sftoolbox.content import ActionContent, PanelContent
from sftoolboxqt import qtgui, qtcore
from sftoolboxqt.tree import PanelsModel, PanelsTreeWidget
class ActionsTreeWidget(qtgui.QTreeWidget):
"""tree widget holding actions
"""
def startDrag(self, dro... | (self):
"""return tree widget that will contain the actions
"""
tree = ActionsTreeWidget()
tree.setHeaderLabels(['Action', 'IDName', 'Tags'])
tree.setSortingEnabled(True)
tree.setDragEnabled(True)
return tree
def __init__(self, project=None, parent=None):
... | _create_actions_tree_widget | identifier_name |
editor.py | """gui systems to manage actions
"""
import os
from sftoolbox.content import ActionContent, PanelContent
from sftoolboxqt import qtgui, qtcore
from sftoolboxqt.tree import PanelsModel, PanelsTreeWidget
class ActionsTreeWidget(qtgui.QTreeWidget):
"""tree widget holding actions
"""
def startDrag(self, dro... |
def _create_panels_tree_widget(self, model):
"""return tree widget that will contain the actions
"""
tree = PanelsTreeWidget()
tree.setModel(model)
tree.setSortingEnabled(True)
tree.setDragEnabled(True)
tree.setAcceptDrops(True)
return tree
@pro... | """construct the browser
"""
super(PanelsWidget, self).__init__(parent=parent)
self.setWindowTitle('Panels Browser')
self._project = project
self._tree_model = PanelsModel(project)
self._tree = self._create_panels_tree_widget(self._tree_model)
layout = qtgui.QVBo... | identifier_body |
editor.py | """gui systems to manage actions
"""
import os
from sftoolbox.content import ActionContent, PanelContent
from sftoolboxqt import qtgui, qtcore
from sftoolboxqt.tree import PanelsModel, PanelsTreeWidget
class ActionsTreeWidget(qtgui.QTreeWidget):
"""tree widget holding actions
"""
def startDrag(self, dro... |
layout = qtgui.QVBoxLayout()
layout.addWidget(self._tree)
self.setLayout(layout)
def _create_panels_tree_widget(self, model):
"""return tree widget that will contain the actions
"""
tree = PanelsTreeWidget()
tree.setModel(model)
tree.setSortingEnabl... | random_line_split | |
editor.py | """gui systems to manage actions
"""
import os
from sftoolbox.content import ActionContent, PanelContent
from sftoolboxqt import qtgui, qtcore
from sftoolboxqt.tree import PanelsModel, PanelsTreeWidget
class ActionsTreeWidget(qtgui.QTreeWidget):
"""tree widget holding actions
"""
def startDrag(self, dro... |
item.setText(0, action.human_label)
item.setText(1, action.idname)
item.setText(2, ', '.join(map(str, action.tags)))
item.action = action
self._tree_widget.addTopLevelItem(item)
class EditorWidget(qtgui.QWidget):
""""""
def __init__(self, project=... | item.setIcon(0, qtgui.QIcon(icon_filepath)) | conditional_block |
cfg.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 ... | <'cx>(cx: &mut ExtCtxt,
sp: Span,
tts: &[ast::TokenTree])
-> Box<base::MacResult+'static> {
let mut p = cx.new_parser_from_tts(tts);
let cfg = p.parse_meta_item();
if !p.eat(&token::Eof) {
cx.span_err(sp, "expected 1 cfg-pattern")... | expand_cfg | identifier_name |
cfg.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 ... | {
let mut p = cx.new_parser_from_tts(tts);
let cfg = p.parse_meta_item();
if !p.eat(&token::Eof) {
cx.span_err(sp, "expected 1 cfg-pattern");
return DummyResult::expr(sp);
}
let matches_cfg = attr::cfg_matches(&cx.parse_sess.span_diagnostic, &cx.cfg, &*cfg);
MacExpr::new(cx.exp... | identifier_body | |
cfg.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 ... | use attr;
use attr::*;
use parse::attr::ParserAttr;
use parse::token;
pub fn expand_cfg<'cx>(cx: &mut ExtCtxt,
sp: Span,
tts: &[ast::TokenTree])
-> Box<base::MacResult+'static> {
let mut p = cx.new_parser_from_tts(tts);
let cfg = p.parse_meta... | random_line_split | |
cfg.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 ... |
let matches_cfg = attr::cfg_matches(&cx.parse_sess.span_diagnostic, &cx.cfg, &*cfg);
MacExpr::new(cx.expr_bool(sp, matches_cfg))
}
| {
cx.span_err(sp, "expected 1 cfg-pattern");
return DummyResult::expr(sp);
} | conditional_block |
allStageMemoryConsumer.js | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... |
}); | {
refreshTimeSeriesData();
} | conditional_block |
allStageMemoryConsumer.js | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | return 0;
}
};
}
});
var stages = $scope.pipelineConfig.stages;
angular.forEach(stages, function(stage) {
$scope.chartData.push({
instanceName: stage.instanceName,
key: stage.uiInfo.label,
value: 0
});
});
$scope.$on('summar... | if(d[1] > 0) {
return (d[1]).toFixed(2);
} else { | random_line_split |
mimetypearray.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::MimeTypeArrayBinding;
use dom::bindings::codegen::Bindings::MimeTypeArrayBin... | (global: &GlobalScope) -> DomRoot<MimeTypeArray> {
reflect_dom_object(
Box::new(MimeTypeArray::new_inherited()),
global,
MimeTypeArrayBinding::Wrap,
)
}
}
impl MimeTypeArrayMethods for MimeTypeArray {
// https://html.spec.whatwg.org/multipage/#dom-mimetypearr... | new | identifier_name |
mimetypearray.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::MimeTypeArrayBinding;
use dom::bindings::codegen::Bindings::MimeTypeArrayBin... |
// https://html.spec.whatwg.org/multipage/#dom-mimetypearray-item
fn IndexedGetter(&self, _index: u32) -> Option<DomRoot<MimeType>> {
None
}
// check-tidy: no specs after this line
fn NamedGetter(&self, _name: DOMString) -> Option<DomRoot<MimeType>> {
None
}
// https://he... | {
None
} | identifier_body |
mimetypearray.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::MimeTypeArrayBinding;
use dom::bindings::codegen::Bindings::MimeTypeArrayBin... |
impl MimeTypeArray {
pub fn new_inherited() -> MimeTypeArray {
MimeTypeArray {
reflector_: Reflector::new(),
}
}
pub fn new(global: &GlobalScope) -> DomRoot<MimeTypeArray> {
reflect_dom_object(
Box::new(MimeTypeArray::new_inherited()),
global,
... | } | random_line_split |
loader.rs | /// CPU the binary file is intended for.
#[derive(Clone,Copy,Debug)]
pub enum Machine {
/// 8-bit AVR
Avr,
/// AMD64
Amd64,
/// Intel x86
Ia32,
}
/// Parses a non-fat Mach-o binary from `bytes` at `offset` and creates a `Project` from it. Returns the `Project` instance and
/// the CPU its inten... | use uuid::Uuid;
| random_line_split | |
loader.rs | -o binary from `bytes` at `offset` and creates a `Project` from it. Returns the `Project` instance and
/// the CPU its intended for.
pub fn | (bytes: &[u8], offset: usize, name: String) -> Result<(Project, Machine)> {
let binary = mach::MachO::parse(&bytes, offset)?;
debug!("mach: {:#?}", &binary);
let mut base = 0x0;
let cputype = binary.header.cputype;
let (machine, mut reg) = match cputype {
mach::cputype::CPU_TYPE_X86 => {
... | load_mach | identifier_name |
loader.rs | -o binary from `bytes` at `offset` and creates a `Project` from it. Returns the `Project` instance and
/// the CPU its intended for.
pub fn load_mach(bytes: &[u8], offset: usize, name: String) -> Result<(Project, Machine)> {
let binary = mach::MachO::parse(&bytes, offset)?;
debug!("mach: {:#?}", &binary);
l... |
elf::header::EM_AVR => {
let reg = Region::undefined("Flash".to_string(), 0x2_0000);
(Machine::Avr, reg)
}
machine => return Err(format!("Unsupported machine: {}", machine).into()),
};
for ph in &binary.program_headers {
if ph.p_type == program_header::P... | {
let reg = Region::undefined("RAM".to_string(), 0x1_0000_0000);
(Machine::Ia32, reg)
} | conditional_block |
loader.rs | ) -> Result<(Project, Machine)> {
let binary = mach::MachO::parse(&bytes, offset)?;
debug!("mach: {:#?}", &binary);
let mut base = 0x0;
let cputype = binary.header.cputype;
let (machine, mut reg) = match cputype {
mach::cputype::CPU_TYPE_X86 => {
let reg = Region::undefined("RAM"... | {
let pe = pe::PE::parse(&bytes)?;
debug!("pe: {:#?}", &pe);
let image_base = pe.image_base as u64;
let mut ram = Region::undefined("RAM".to_string(), 0x100000000);
for section in &pe.sections {
let name = String::from_utf8_lossy(§ion.name);
debug!("section: {}", name);
l... | identifier_body | |
c_str.rs | bytes yielded contain an
/// internal 0 byte. The error returned will contain the bytes as well as
/// the position of the nul byte.
pub fn new<T: IntoBytes>(t: T) -> Result<CString, NulError> {
let bytes = t.into_bytes();
match bytes.iter().position(|x| *x == 0) {
Some(i) => Er... | }
}
/// Deprecated in favor of `CStr`
#[unstable(feature = "std_misc")] | random_line_split | |
c_str.rs | /// extern { fn puts(s: *const libc::c_char); }
///
/// fn main() {
/// let to_print = CString::new("Hello!").unwrap();
/// unsafe {
/// puts(to_print.as_ptr());
/// }
/// }
/// ```
///
/// # Errors
///
/// This function will return an error if the by... | partial_cmp | identifier_name | |
c_str.rs | /// version of an instance of `CString`. This type can be constructed from a raw
/// C string as well and represents a C string borrowed from another location.
///
/// Note that this structure is **not** `repr(C)` and is not recommended to be
/// placed in the signatures of FFI functions. Instead safe wrappers of FFI
/... |
}
impl Error for NulError {
fn description(&self) -> &str { "nul byte found in data" }
}
impl fmt::Display for NulError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "nul byte found in provided data at position: {}", self.0)
}
}
impl FromError<NulError> for io::Error {
f... | { self.1 } | identifier_body |
test_utils.py | """
Test runner for Evennia test suite. Run with "game/manage.py test".
"""
from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner
class | (DjangoTestSuiteRunner):
"""
This test runner only runs tests on the apps specified in src/ and game/ to
avoid running the large number of tests defined by Django
"""
def build_suite(self, test_labels, extra_tests=None, **kwargs):
"""
Build a test suite for Evennia. test_labels is a... | EvenniaTestSuiteRunner | identifier_name |
test_utils.py | """
Test runner for Evennia test suite. Run with "game/manage.py test".
"""
from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner
class EvenniaTestSuiteRunner(DjangoTestSuiteRunner):
"""
This test runner only runs tests on the apps specified in src/ and game/ to
avoid r... | If not given, a subset of settings.INSTALLED_APPS will be used.
"""
if not test_labels:
test_labels = [applabel.rsplit('.', 1)[1] for applabel in settings.INSTALLED_APPS
if (applabel.startswith('src.') or applabel.startswith('game.'))]
return super... | random_line_split | |
test_utils.py | """
Test runner for Evennia test suite. Run with "game/manage.py test".
"""
from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner
class EvenniaTestSuiteRunner(DjangoTestSuiteRunner):
| """
This test runner only runs tests on the apps specified in src/ and game/ to
avoid running the large number of tests defined by Django
"""
def build_suite(self, test_labels, extra_tests=None, **kwargs):
"""
Build a test suite for Evennia. test_labels is a list of apps to test.
... | identifier_body | |
test_utils.py | """
Test runner for Evennia test suite. Run with "game/manage.py test".
"""
from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner
class EvenniaTestSuiteRunner(DjangoTestSuiteRunner):
"""
This test runner only runs tests on the apps specified in src/ and game/ to
avoid r... |
return super(EvenniaTestSuiteRunner, self).build_suite(test_labels, extra_tests=extra_tests, **kwargs)
| test_labels = [applabel.rsplit('.', 1)[1] for applabel in settings.INSTALLED_APPS
if (applabel.startswith('src.') or applabel.startswith('game.'))] | conditional_block |
cli.ts | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
describe('Mapping pr yargs to create PR options', () => {
const sandbox = sinon.createSandbox();
afterEach(() => {
sandbox.restore();
});
it('Creates', () => {
const options = {
upstreamRepo: 'foo',
upstreamOwner: 'bar',
message: 'message',
description: 'description',
ti... | sandbox.stub(yargs, 'argv').value({...yargs.argv, _: ['unrecognized']});
await assert.rejects(main());
});
}); | random_line_split |
test.rs | be used for tests"));
}
_ => {
debug!("this is a test function");
let test = Test {
span: i.span,
path: self.cx.path.clone(),
bench: is_bench_fn(&self.cx, &*i),
... | is_ignored | identifier_name | |
test.rs | let diag = self.cx.span_diagnostic;
panic!(diag.span_fatal(i.span, "unsafe functions cannot be used for tests"));
}
_ => {
debug!("this is a test function");
let test = Test {
span: i.... |
(it, sym)
}
fn generate_test_harness(sess: &ParseSess,
reexport_test_harness_main: Option<InternedString>,
krate: ast::Crate,
cfg: &ast::CrateConfig,
sd: &diagnostic::SpanHandler) -> ast::Crate {
let mut featur... | id: ast::DUMMY_NODE_ID,
node: ast::ItemMod(reexport_mod),
vis: ast::Public,
span: DUMMY_SP,
}); | random_line_split |
test.rs | else {
strip_test_functions(krate)
}
}
struct TestHarnessGenerator<'a> {
cx: TestCtxt<'a>,
tests: Vec<ast::Ident>,
// submodule name, gensym'd identifier for re-exports
tested_submods: Vec<(ast::Ident, ast::Ident)>,
}
impl<'a> fold::Folder for TestHarnessGenerator<'a> {
fn fold_crate... | {
generate_test_harness(sess, reexport_test_harness_main, krate, cfg, span_diagnostic)
} | conditional_block | |
test.rs |
struct TestHarnessGenerator<'a> {
cx: TestCtxt<'a>,
tests: Vec<ast::Ident>,
// submodule name, gensym'd identifier for re-exports
tested_submods: Vec<(ast::Ident, ast::Ident)>,
}
impl<'a> fold::Folder for TestHarnessGenerator<'a> {
fn fold_crate(&mut self, c: ast::Crate) -> ast::Crate {
... | {
// We generate the test harness when building in the 'test'
// configuration, either with the '--test' or '--cfg test'
// command line options.
let should_test = attr::contains_name(&krate.config, "test");
// Check for #[reexport_test_harness_main = "some_name"] which
// creates a `use some_n... | identifier_body | |
fuzzylogic.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Quality Control based on fuzzy logic.
"""
import logging
import numpy as np
from .core import QCCheckVar
from .gradient import gradient
from .spike import spike
from .woa_normbias import woa_normbias
from cotede.fuzzy im... |
return uncertainty
class FuzzyLogic(QCCheckVar):
def set_features(self):
self.features = {}
for v in [f for f in self.cfg["features"] if f not in self.features]:
if v == "woa_bias":
woa_comparison = woa_normbias(self.data, self.varname, self.attrs)
... | """
FIXME: Think about, should I return 0, or have an assert, and at qc.py
all qc tests are applied with a try, and in case it fails it flag
0s.
"""
require = cfg.get("require", require)
if (require == "all") and not np.all([f in features for f in cfg["features"]]):
mo... | identifier_body |
fuzzylogic.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Quality Control based on fuzzy logic.
"""
import logging
import numpy as np
from .core import QCCheckVar
from .gradient import gradient
from .spike import spike
from .woa_normbias import woa_normbias
from cotede.fuzzy im... | # I needed to use np.nonzeros because now uncertainty is a masked array,
# to accept when a feature is masked.
flag[np.nonzero(uncertainty <= 0.29)] = 1
flag[np.nonzero((uncertainty > 0.29) & (uncertainty <= 0.34))] = 2
flag[np.nonzero((uncertainty > 0.34) & (uncertainty <= 0.7... | # where some values in a profile would not be estimated, hence flag=0 | random_line_split |
fuzzylogic.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Quality Control based on fuzzy logic.
"""
import logging
import numpy as np
from .core import QCCheckVar
from .gradient import gradient
from .spike import spike
from .woa_normbias import woa_normbias
from cotede.fuzzy im... |
self.features["fuzzylogic"] = fuzzylogic(self.features, self.cfg)
def test(self):
self.flags = {}
cfg = self.cfg
flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1")
uncertainty = self.features["fuzzylogic"]
# FIXME: As it is now, it will have no zero f... | if v == "woa_bias":
woa_comparison = woa_normbias(self.data, self.varname, self.attrs)
self.features[v] = woa_comparison["woa_bias"]
elif v == "woa_normbias":
woa_comparison = woa_normbias(self.data, self.varname, self.attrs)
self.features[v] =... | conditional_block |
fuzzylogic.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Quality Control based on fuzzy logic.
"""
import logging
import numpy as np
from .core import QCCheckVar
from .gradient import gradient
from .spike import spike
from .woa_normbias import woa_normbias
from cotede.fuzzy im... | (features, cfg, require="all"):
"""
FIXME: Think about, should I return 0, or have an assert, and at qc.py
all qc tests are applied with a try, and in case it fails it flag
0s.
"""
require = cfg.get("require", require)
if (require == "all") and not np.all([f in features fo... | fuzzylogic | identifier_name |
Suspencified.tsx | /*
* Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope tha... |
export function WithEmptyState<ResourceType = unknown[]>(props: SuspenseWithEmptyStateProps<ResourceType>) {
const { children, isEmpty = (value: ResourceType) => (value as any).length === 0, resource, emptyStateProps } = props;
const value = resource.read();
const finalEmptyStateProps: EmptyStateProps = {
ti... | suspenseProps?: SuspenseProps;
loadingStateProps?: LoadingStateProps;
errorBoundaryProps?: ErrorBoundaryProps;
}>; | random_line_split |
Suspencified.tsx | /*
* Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope tha... |
export function SuspenseWithEmptyState<ResourceType = unknown>(
props: SuspencifiedProps & {
resource: Resource<ResourceType>;
withEmptyStateProps?: Partial<SuspenseWithEmptyStateProps<ResourceType>>;
}
) {
const { children, withEmptyStateProps, resource } = props;
return (
<Suspencified {...props... | {
const { children, loadingStateProps, errorBoundaryProps, suspenseProps } = props;
return (
<ErrorBoundary {...errorBoundaryProps}>
<Suspense fallback={<LoadingState {...loadingStateProps} />} {...suspenseProps} children={children} />
</ErrorBoundary>
);
} | identifier_body |
Suspencified.tsx | /*
* Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope tha... | <ResourceType = unknown[]>(props: SuspenseWithEmptyStateProps<ResourceType>) {
const { children, isEmpty = (value: ResourceType) => (value as any).length === 0, resource, emptyStateProps } = props;
const value = resource.read();
const finalEmptyStateProps: EmptyStateProps = {
title: <FormattedMessage id="with... | WithEmptyState | identifier_name |
option.d.ts | import { ElementRef, EventEmitter, Renderer } from '@angular/core';
export declare class MdOption {
private _element;
private _renderer;
private _selected;
/** Whether the option is disabled. */
private _disabled;
private _id;
/** The unique ID of the option. */
readonly id: string;
... | _handleKeydown(event: KeyboardEvent): void;
/**
* Selects the option while indicating the selection came from the user. Used to
* determine if the select's view -> model callback should be invoked.
*/
_selectViaInteraction(): void;
/** Returns the correct tabindex for the option depending... | random_line_split | |
option.d.ts | import { ElementRef, EventEmitter, Renderer } from '@angular/core';
export declare class | {
private _element;
private _renderer;
private _selected;
/** Whether the option is disabled. */
private _disabled;
private _id;
/** The unique ID of the option. */
readonly id: string;
/** The form value of the option. */
value: any;
disabled: any;
/** Event emitted wh... | MdOption | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.