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
modifyexperience.js
(function (badges, $, undefined) { "use strict"; var options = {}, geocoder, map, marker; badges.options = function (o) { $.extend(options, o); }; badges.init = function () { initializeTypeahead(); initializeImagePreview(); $(".datepicker").datepicker(...
if (marker) marker.setMap(null); //clear existing marker map.setCenter(results[0].geometry.location); marker = new google.maps.Marker({ map: map, position: results[0].geometry.location })...
var davisLatLng = new google.maps.LatLng(38.5449065, -121.7405167); geocoder = new google.maps.Geocoder(); var mapOptions = { center: davisLatLng, zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(documen...
identifier_body
modifyexperience.js
(function (badges, $, undefined) { "use strict"; var options = {}, geocoder, map, marker; badges.options = function (o) { $.extend(options, o); }; badges.init = function () { initializeTypeahead(); initializeImagePreview(); $(".datepicker").datepicker(...
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); marker = new google.maps.Marker({ map: map, position: davisLatLng }); $("#Experience_Location").blur(function () { var address = this.value; ...
center: davisLatLng, zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP };
random_line_split
modifyexperience.js
(function (badges, $, undefined) { "use strict"; var options = {}, geocoder, map, marker; badges.options = function (o) { $.extend(options, o); }; badges.init = function () { initializeTypeahead(); initializeImagePreview(); $(".datepicker").datepicker(...
}); }); } }(window.Badges = window.Badges || {}, jQuery));
alert('Geocode was not successful for the following reason: ' + status); }
conditional_block
modifyexperience.js
(function (badges, $, undefined) { "use strict"; var options = {}, geocoder, map, marker; badges.options = function (o) { $.extend(options, o); }; badges.init = function () { initializeTypeahead(); initializeImagePreview(); $(".datepicker").datepicker(...
{ $("#cover-image").change(function () { var filesToUpload = this.files; if (filesToUpload.length !== 1) return; var file = filesToUpload[0]; if (!file.type.match(/image.*/)) { alert("only images, please"); } ...
itializeImagePreview()
identifier_name
objectTypesIdentityWithGenericConstructSignaturesOptionalParams3.ts
// Two call or construct signatures are considered identical when they have the same number of type parameters and, considering those // parameters pairwise identical, have identical type parameter constraints, identical number of parameters with identical kind(required, // optional or rest) and types, and identical ...
function foo1c(x: C<string, number>); function foo1c(x: C<string, number>); // error function foo1c(x: any) { } function foo2(x: I<string, number>); function foo2(x: I<string, number>); // error function foo2(x: any) { } function foo3(x: typeof a); function foo3(x: typeof a); // error function foo3(x: any) { } fun...
{ }
identifier_body
objectTypesIdentityWithGenericConstructSignaturesOptionalParams3.ts
// Two call or construct signatures are considered identical when they have the same number of type parameters and, considering those // parameters pairwise identical, have identical type parameter constraints, identical number of parameters with identical kind(required, // optional or rest) and types, and identical ...
function foo3(x: any) { } function foo4(x: typeof b); function foo4(x: typeof b); // error function foo4(x: any) { } function foo8(x: B<string, number>); function foo8(x: I<string, number>); // BUG 832086 function foo8(x: any) { } function foo9(x: B<string, number>); function foo9(x: C<string, number>); // error, di...
random_line_split
objectTypesIdentityWithGenericConstructSignaturesOptionalParams3.ts
// Two call or construct signatures are considered identical when they have the same number of type parameters and, considering those // parameters pairwise identical, have identical type parameter constraints, identical number of parameters with identical kind(required, // optional or rest) and types, and identical ...
(x: T, y?: U) { return null; } } interface I<T, U> { new(x: T, y?: U): B<T, U>; } interface I2 { new<T, U>(x: T, y: U): C<T, U>; } var a: { new <T, U>(x: T, y?: U): B<T, U> }; var b = { new<T, U>(x: T, y: U) { return new C<T, U>(x, y); } }; // not a construct signature, function called new function foo1b(x:...
constructor
identifier_name
extrapolatable.rs
// // This file is part of zero_sum. // // zero_sum 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. // // zero_sum is distributed in...
fn extrapolate(&self) -> Vec<P>; }
/// system does not assume that all plies returned are correct.
random_line_split
mobile.py
#coding:utf-8 from nadmin.sites import site from nadmin.views import BaseAdminPlugin, CommAdminView class MobilePlugin(BaseAdminPlugin): def _test_mobile(self):
def init_request(self, *args, **kwargs): return self._test_mobile() def get_context(self, context): #context['base_template'] = 'nadmin/base_mobile.html' context['is_mob'] = True return context # Media # def get_media(self, media): # return media + self.vendor...
try: return self.request.META['HTTP_USER_AGENT'].find('Android') >= 0 or \ self.request.META['HTTP_USER_AGENT'].find('iPhone') >= 0 except Exception: return False
identifier_body
mobile.py
#coding:utf-8 from nadmin.sites import site from nadmin.views import BaseAdminPlugin, CommAdminView class MobilePlugin(BaseAdminPlugin): def _test_mobile(self): try: return self.request.META['HTTP_USER_AGENT'].find('Android') >= 0 or \
def init_request(self, *args, **kwargs): return self._test_mobile() def get_context(self, context): #context['base_template'] = 'nadmin/base_mobile.html' context['is_mob'] = True return context # Media # def get_media(self, media): # return media + self.vendor('...
self.request.META['HTTP_USER_AGENT'].find('iPhone') >= 0 except Exception: return False
random_line_split
mobile.py
#coding:utf-8 from nadmin.sites import site from nadmin.views import BaseAdminPlugin, CommAdminView class
(BaseAdminPlugin): def _test_mobile(self): try: return self.request.META['HTTP_USER_AGENT'].find('Android') >= 0 or \ self.request.META['HTTP_USER_AGENT'].find('iPhone') >= 0 except Exception: return False def init_request(self, *args, **kwargs): ...
MobilePlugin
identifier_name
redis-to-sqs.rs
#[tokio::main] async fn
() -> Result<(), anyhow::Error> { use redis::Commands as _; use rusoto_sqs::Sqs as _; let config = encoder::load_config()?; let redis_client = redis::Client::open(config.redis.url)?; let mut conn = redis_client.get_connection()?; let sqs_client = rusoto_sqs::SqsClient::new(Default::default()); ...
main
identifier_name
redis-to-sqs.rs
#[tokio::main] async fn main() -> Result<(), anyhow::Error> { use redis::Commands as _; use rusoto_sqs::Sqs as _; let config = encoder::load_config()?; let redis_client = redis::Client::open(config.redis.url)?; let mut conn = redis_client.get_connection()?; let sqs_client = rusoto_sqs::SqsClien...
.send_message(rusoto_sqs::SendMessageRequest { queue_url: config.sqs.queue_url.clone(), message_body: fname, ..Default::default() }) .await?; } Ok(()) }
sqs_client
random_line_split
redis-to-sqs.rs
#[tokio::main] async fn main() -> Result<(), anyhow::Error>
message_body: fname, ..Default::default() }) .await?; } Ok(()) }
{ use redis::Commands as _; use rusoto_sqs::Sqs as _; let config = encoder::load_config()?; let redis_client = redis::Client::open(config.redis.url)?; let mut conn = redis_client.get_connection()?; let sqs_client = rusoto_sqs::SqsClient::new(Default::default()); loop { let job: Vec...
identifier_body
redis-to-sqs.rs
#[tokio::main] async fn main() -> Result<(), anyhow::Error> { use redis::Commands as _; use rusoto_sqs::Sqs as _; let config = encoder::load_config()?; let redis_client = redis::Client::open(config.redis.url)?; let mut conn = redis_client.get_connection()?; let sqs_client = rusoto_sqs::SqsClien...
let fname = job.into_iter().nth(1).unwrap(); println!("Enqueue {}", fname); sqs_client .send_message(rusoto_sqs::SendMessageRequest { queue_url: config.sqs.queue_url.clone(), message_body: fname, ..Default::default() }) ...
{ break; }
conditional_block
lens_flare.py
files. # Copyright (C) 2009 Jonathan Thomas # # This file is part of OpenShot Video Editor (http://launchpad.net/openshot/). # # OpenShot Video Editor 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...
else: material_object.halo.use_star = False material_object.halo.star_tip_count = params["halo_star_tip_count"] # Set the render options. It is important that these are set # to the same values as the current OpenShot project. These # params are automatically set by OpenShot bpy.context.scene.render.filepath = p...
material_object.halo.use_star = True
conditional_block
lens_flare.py
# # This file is part of OpenShot Video Editor (http://launchpad.net/openshot/). # # OpenShot Video Editor 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)...
random_line_split
weight.rs
use super::Scorer; use crate::core::SegmentReader; use crate::query::Explanation; use crate::{DocId, Score, TERMINATED}; /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. pub(crate) fn for_each_scorer<TScorer: Scorer + ?Sized>( scorer: &mut ...
} /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. fn for_each( &self, reader: &SegmentReader, callback: &mut dyn FnMut(DocId, Score), ) -> crate::Result<()> { let mut scorer = self.scorer(re...
{ Ok(scorer.count_including_deleted()) }
conditional_block
weight.rs
use super::Scorer; use crate::core::SegmentReader; use crate::query::Explanation; use crate::{DocId, Score, TERMINATED}; /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. pub(crate) fn for_each_scorer<TScorer: Scorer + ?Sized>( scorer: &mut ...
/// Calls `callback` with all of the `(doc, score)` for which score /// is exceeding a given threshold. /// /// This method is useful for the TopDocs collector. /// For all docsets, the blanket implementation has the benefit /// of prefiltering (doc, score) pairs, avoiding the /// virtual dispatch cost. /// /// More ...
{ let mut doc = scorer.doc(); while doc != TERMINATED { callback(doc, scorer.score()); doc = scorer.advance(); } }
identifier_body
weight.rs
use super::Scorer; use crate::core::SegmentReader; use crate::query::Explanation; use crate::{DocId, Score, TERMINATED}; /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. pub(crate) fn for_each_scorer<TScorer: Scorer + ?Sized>( scorer: &mut ...
( &self, reader: &SegmentReader, callback: &mut dyn FnMut(DocId, Score), ) -> crate::Result<()> { let mut scorer = self.scorer(reader, 1.0)?; for_each_scorer(scorer.as_mut(), callback); Ok(()) } /// Calls `callback` with all of the `(doc, score)` for which sc...
for_each
identifier_name
weight.rs
use super::Scorer; use crate::core::SegmentReader; use crate::query::Explanation; use crate::{DocId, Score, TERMINATED}; /// Iterates through all of the document matched by the DocSet /// `DocSet` and push the scored documents to the collector. pub(crate) fn for_each_scorer<TScorer: Scorer + ?Sized>( scorer: &mut ...
/// important optimization (e.g. BlockWAND for union). fn for_each_pruning( &self, threshold: Score, reader: &SegmentReader, callback: &mut dyn FnMut(DocId, Score) -> Score, ) -> crate::Result<()> { let mut scorer = self.scorer(reader, 1.0)?; for_each_pruning_...
/// For all docsets, the blanket implementation has the benefit /// of prefiltering (doc, score) pairs, avoiding the /// virtual dispatch cost. /// /// More importantly, it makes it possible for scorers to implement
random_line_split
operations.py
'Intersects'), 'relate' : (PostGISRelate, six.string_types), 'coveredby' : PostGISFunction(prefix, 'CoveredBy'), 'covers' : PostGISFunction(prefix, 'Covers'), } # Valid distance types and substitutions dtypes = (Decimal, Distance, float) + six.integer_types ...
get_geom_placeholder
identifier_name
operations.py
Equals'), 'disjoint' : PostGISFunction(prefix, 'Disjoint'), 'touches' : PostGISFunction(prefix, 'Touches'), 'crosses' : PostGISFunction(prefix, 'Crosses'), 'within' : PostGISFunction(prefix, 'Within'), 'overlaps' : PostGISFunction(prefix, 'Overlaps'), ...
dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection)))
conditional_block
operations.py
valid_aggregates = dict([(k, None) for k in ('Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union')]) Adapter = PostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. def __init__(self, connection): super(PostGISOperations, self).__init__(connection) ...
name = 'postgis' postgis = True version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)')
random_line_split
operations.py
.kml = prefix + 'AsKML' self.length = prefix + 'Length' self.length_spheroid = prefix + 'length_spheroid' self.makeline = prefix + 'MakeLine' self.mem_size = prefix + 'mem_size' self.num_geom = prefix + 'NumGeometries' self.num_points = prefix + 'npoints' self.per...
""" Helper routine that returns a boolean indicating whether the number of parameters is correct for the lookup type. """ def exactly_two(np): return np == 2 def two_to_three(np): return np >= 2 and np <=3 if (lookup_type in self.distance_functions and lookup_...
identifier_body
Attribute.ts
/* Copyright 2016 Ling Zhang Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist...
* Attribute. extend from Object is required for type checking of { } attribute */ export interface Attribute extends Object { /** * Before decoration hook. Return false to stop decorate this attribute to a class * * NOTE: we must define something on the interface * * @param {Object | Function} target...
import { Interceptor } from './Interceptor'; /**
random_line_split
init-page.tsx
import * as React from 'react'; import Container from '../components/container'; import { setWine } from '../api/wine'; import { Link } from 'react-router'; export interface ICreatePageProps extends React.Props<any> {} export interface ICreatePageState { isLoading?: boolean; showModal?: boolean; } const styles =...
<a className="github-button" href="https://github.com/ayxos/react-cellar/fork" data-icon="octicon-repo-forked" data-style="mega" data-count-href="/ayxos/react-cellar/network" data-count-api="/repos/ayxos/react-...
random_line_split
init-page.tsx
import * as React from 'react'; import Container from '../components/container'; import { setWine } from '../api/wine'; import { Link } from 'react-router'; export interface ICreatePageProps extends React.Props<any> {} export interface ICreatePageState { isLoading?: boolean; showModal?: boolean; } const styles =...
extends React.Component<ICreatePageProps, ICreatePageState> { componentWillMount() { this.setState({ isLoading: false, showModal: false }); }; onSubmit(values) { setWine(values); } render() { return ( <div> <Container size={0} style={styles.style1} center> ...
InitPage
identifier_name
init-page.tsx
import * as React from 'react'; import Container from '../components/container'; import { setWine } from '../api/wine'; import { Link } from 'react-router'; export interface ICreatePageProps extends React.Props<any> {} export interface ICreatePageState { isLoading?: boolean; showModal?: boolean; } const styles =...
; onSubmit(values) { setWine(values); } render() { return ( <div> <Container size={0} style={styles.style1} center> <div className="home-hero"> <h1>Welcome to React Cellar</h1> <h3> A sample app built with React, Bootstrap, Node.js, and Mongo...
{ this.setState({ isLoading: false, showModal: false }); }
identifier_body
objects-owned-object-borrowed-method-headerless.rs
// // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test invoked ...
// 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.
random_line_split
objects-owned-object-borrowed-method-headerless.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 ...
{ x: uint } impl FooTrait for BarStruct { fn foo(&self) -> uint { self.x } } pub fn main() { let foos: Vec<Box<FooTrait>> = vec!( box BarStruct{ x: 0 } as Box<FooTrait>, box BarStruct{ x: 1 } as Box<FooTrait>, box BarStruct{ x: 2 } as Box<FooTrait> ); for i in...
BarStruct
identifier_name
intrinsic-raw_eq-const.rs
// run-pass #![feature(core_intrinsics)] #![feature(const_intrinsic_raw_eq)] #![deny(const_err)] pub fn
() { use std::intrinsics::raw_eq; const RAW_EQ_I32_TRUE: bool = unsafe { raw_eq(&42_i32, &42) }; assert!(RAW_EQ_I32_TRUE); const RAW_EQ_I32_FALSE: bool = unsafe { raw_eq(&4_i32, &2) }; assert!(!RAW_EQ_I32_FALSE); const RAW_EQ_CHAR_TRUE: bool = unsafe { raw_eq(&'a', &'a') }; assert!(RAW_EQ...
main
identifier_name
intrinsic-raw_eq-const.rs
// run-pass #![feature(core_intrinsics)] #![feature(const_intrinsic_raw_eq)] #![deny(const_err)] pub fn main()
}
{ use std::intrinsics::raw_eq; const RAW_EQ_I32_TRUE: bool = unsafe { raw_eq(&42_i32, &42) }; assert!(RAW_EQ_I32_TRUE); const RAW_EQ_I32_FALSE: bool = unsafe { raw_eq(&4_i32, &2) }; assert!(!RAW_EQ_I32_FALSE); const RAW_EQ_CHAR_TRUE: bool = unsafe { raw_eq(&'a', &'a') }; assert!(RAW_EQ_CH...
identifier_body
intrinsic-raw_eq-const.rs
// run-pass #![feature(core_intrinsics)] #![feature(const_intrinsic_raw_eq)] #![deny(const_err)] pub fn main() { use std::intrinsics::raw_eq; const RAW_EQ_I32_TRUE: bool = unsafe { raw_eq(&42_i32, &42) }; assert!(RAW_EQ_I32_TRUE); const RAW_EQ_I32_FALSE: bool = unsafe { raw_eq(&4_i32, &2) }; ass...
const RAW_EQ_CHAR_FALSE: bool = unsafe { raw_eq(&'a', &'A') }; assert!(!RAW_EQ_CHAR_FALSE); const RAW_EQ_ARRAY_TRUE: bool = unsafe { raw_eq(&[13_u8, 42], &[13, 42]) }; assert!(RAW_EQ_ARRAY_TRUE); const RAW_EQ_ARRAY_FALSE: bool = unsafe { raw_eq(&[13_u8, 42], &[42, 13]) }; assert!(!RAW_EQ_ARRAY...
const RAW_EQ_CHAR_TRUE: bool = unsafe { raw_eq(&'a', &'a') }; assert!(RAW_EQ_CHAR_TRUE);
random_line_split
WikipediaService.ts
import { RemoteAPIService } from './RemoteAPIService'; /** * Wikipedia retrieval service */ export class
extends RemoteAPIService { private static jobName = 'Wikipedia'; /** * Init the queue with the number of workers and a specific job */ public static init() { super.init(); this.workers = +process.env.WIKIPEDIA_WORKERS; // Register the queue's processing behaviour ...
WikipediaService
identifier_name
WikipediaService.ts
import { RemoteAPIService } from './RemoteAPIService'; /** * Wikipedia retrieval service */
private static jobName = 'Wikipedia'; /** * Init the queue with the number of workers and a specific job */ public static init() { super.init(); this.workers = +process.env.WIKIPEDIA_WORKERS; // Register the queue's processing behaviour this.queue.process(this.jo...
export class WikipediaService extends RemoteAPIService {
random_line_split
index.d.ts
// Type definitions for node-srp // Project: https://github.com/mozilla/node-srp // Definitions by: Pat Smuk <https://github.com/Patman64> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="bignum" /> /// <reference types="node" /> import * as BigNum from 'bignum'; export = SRP;...
{ constructor(params: Params, salt: Buffer, identity: Buffer, password: Buffer, secret1: Buffer); computeA(): Buffer; setB(B: Buffer): void; computeM1(): Buffer; checkM2(M2: Buffer): void; computeK(): Buffer; } export class Server { constructor(param...
Client
identifier_name
index.d.ts
// Type definitions for node-srp // Project: https://github.com/mozilla/node-srp // Definitions by: Pat Smuk <https://github.com/Patman64> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="bignum" /> /// <reference types="node" /> import * as BigNum from 'bignum'; export = SRP;...
} export class Server { constructor(params: Params, verifier: Buffer, secret2: Buffer); computeB(): Buffer; setA(A: Buffer): void; checkM1(M1: Buffer): Buffer; computeK(): Buffer; } }
computeM1(): Buffer; checkM2(M2: Buffer): void; computeK(): Buffer;
random_line_split
main.rs
extern crate parolrs; extern crate sodiumoxide; use parolrs::core::{Parols, Parol}; use parolrs::utils::{load_database, save_database}; use sodiumoxide::crypto::secretbox::gen_nonce; // in 9.90user 3.55system 0:14.92elapsed 90%CPU :) fn main() { let mut parols = Parols::new(); for i in 0 .. 100_000 { ...
"Ogromny", "admin", "blabla", ); parols.push(parol); } for i in 0 .. 100 { let nonce = gen_nonce(); save_database(&parols, &nonce, "admin").unwrap(); if i == 99 { println!("load_database(\"admin\").ok().unwrap() = {:#?}", l...
&format!("tox{}", i),
random_line_split
main.rs
extern crate parolrs; extern crate sodiumoxide; use parolrs::core::{Parols, Parol}; use parolrs::utils::{load_database, save_database}; use sodiumoxide::crypto::secretbox::gen_nonce; // in 9.90user 3.55system 0:14.92elapsed 90%CPU :) fn
() { let mut parols = Parols::new(); for i in 0 .. 100_000 { let parol = Parol::new_with_arguments( &format!("tox{}", i), "Ogromny", "admin", "blabla", ); parols.push(parol); } for i in 0 .. 100 { let nonce = gen_nonce(); ...
main
identifier_name
main.rs
extern crate parolrs; extern crate sodiumoxide; use parolrs::core::{Parols, Parol}; use parolrs::utils::{load_database, save_database}; use sodiumoxide::crypto::secretbox::gen_nonce; // in 9.90user 3.55system 0:14.92elapsed 90%CPU :) fn main() { let mut parols = Parols::new(); for i in 0 .. 100_000 { ...
} }
{ load_database("admin").ok().unwrap(); }
conditional_block
main.rs
extern crate parolrs; extern crate sodiumoxide; use parolrs::core::{Parols, Parol}; use parolrs::utils::{load_database, save_database}; use sodiumoxide::crypto::secretbox::gen_nonce; // in 9.90user 3.55system 0:14.92elapsed 90%CPU :) fn main()
} }
{ let mut parols = Parols::new(); for i in 0 .. 100_000 { let parol = Parol::new_with_arguments( &format!("tox{}", i), "Ogromny", "admin", "blabla", ); parols.push(parol); } for i in 0 .. 100 { let nonce = gen_nonce(); ...
identifier_body
codemirror.component.js
/* Misojs Codemirror component */ var m = require('mithril'), basePath = "external/codemirror/", pjson = require("./package.json"); // Here we have a few fixes to make CM work in node - we only setup each, // if they don't already exist, otherwise we would override the browser global.document = global.document || ...
var editor = CodeMirror.fromTextArea(element, { lineNumbers: true }); editor.on("change", function(instance, object) { m.startComputation(); attrs.value(editor.doc.getValue()); if (typeof attrs.onchange == "function"){ attrs.onchange(instance, object); } m.endCo...
random_line_split
codemirror.component.js
/* Misojs Codemirror component */ var m = require('mithril'), basePath = "external/codemirror/", pjson = require("./package.json"); // Here we have a few fixes to make CM work in node - we only setup each, // if they don't already exist, otherwise we would override the browser global.document = global.document || ...
return CodemirrorComponent; };
{ basePath = args.basePath; }
conditional_block
rec-align-u64.rs
// Copyright 2012 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 ...
() -> uint { 12u } } #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } #[cfg(target_os = "win32")] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u ...
size
identifier_name
rec-align-u64.rs
// Copyright 2012 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 size() -> uint { 12u } } #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> uint { 8u } pub fn size() -> uint { 16u } } } #[cfg(target_os = "win32")] mod m { #[cfg(target_arch = "x86")] pub mod m { pub fn align() -> uint { 8u } pub fn s...
{ 4u }
identifier_body
rec-align-u64.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast: check-fast screws up repr paths // Issue #2303 use std::sys; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> uint; pub fn min_align_of<T>() -> uint; } } // ...
// 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 http://opensource.org/licenses/MIT>, at your
random_line_split
nopromise.js
(pending and) follows another thenable T. // resolved + pending = follows only T - ignores later resolve/reject calls. // Thenable = has .then(): promise but not necessarily our implementation. // Note: the API has reject(r)/resolve(v) but not fulfill(v). that is because: // resolve(v) already fulfills with value ...
{ pending++; v.then(fulOne.bind(null, i), allrej); }
conditional_block
nopromise.js
= sealed fate: settled or (pending and) follows another thenable T. // resolved + pending = follows only T - ignores later resolve/reject calls. // Thenable = has .then(): promise but not necessarily our implementation. // Note: the API has reject(r)/resolve(v) but not fulfill(v). that is because: // resolve(v) al...
(promise, x, decidingFate) { if (promise._state || (promise._sealed && !decidingFate)) return; // seal fate. only this instance of resolve can settle it [recursively] promise._sealed = 1; var then, done = 0; try { if (x == promise) { settle(promise, REJECTED, Ty...
resolve
identifier_name
nopromise.js
sealed fate: settled or (pending and) follows another thenable T. // resolved + pending = follows only T - ignores later resolve/reject calls. // Thenable = has .then(): promise but not necessarily our implementation. // Note: the API has reject(r)/resolve(v) but not fulfill(v). that is because: // resolve(v) alre...
iter.forEach(function(v, i) { if (is_thenable(v)) { pending++; v.then(fulOne.bind(null, i),
{ rv[i] = val; --pending || allful(rv); }
identifier_body
nopromise.js
dequeue is already scheduled and will execute globalQ asynchronously, // otherwise, globalQ needs to be created and dequeue needs to be scheduled. // The elements (functions) of the globalQ array need to be invoked in order. function dequeue() { var f, tmp = globalQ.reverse(); globalQ = 0; while (f = tmp.p...
var d = new NoPromise; return d.promise = d;
random_line_split
issue-7013.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 ...
} } struct A { v: ~Foo, } fn main() { let a = A {v: ~B{v: None} as ~Foo}; //~ ERROR cannot pack type `~B`, which does not fulfill `Send` let v = RcMut::new(a); //~ ERROR instantiating a type parameter with an incompatible type let w = v.clone(); v.with_mut_borrow(|p| {p.v.set(w.clone());}) }
impl Foo for B { fn set(&mut self, v: RcMut<A>) { self.v = Some(v);
random_line_split
issue-7013.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 a = A {v: ~B{v: None} as ~Foo}; //~ ERROR cannot pack type `~B`, which does not fulfill `Send` let v = RcMut::new(a); //~ ERROR instantiating a type parameter with an incompatible type let w = v.clone(); v.with_mut_borrow(|p| {p.v.set(w.clone());}) }
main
identifier_name
setup.py
# pyresample, Resampling of remote sensing image data in python # # Copyright (C) 2012, 2014, 2015 Esben S. Nielsen # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of ...
setup(name='pyresample', version=version.__version__, description='Resampling of remote sensing data in Python', author='Thomas Lavergne', author_email='t.lavergne@met.no', package_dir={'pyresample': 'pyresample'}, packages=['pyresample'], install_requires=requirements, ...
requirements.append('multiprocessing')
conditional_block
setup.py
# pyresample, Resampling of remote sensing image data in python # # Copyright (C) 2012, 2014, 2015 Esben S. Nielsen # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of ...
description='Resampling of remote sensing data in Python', author='Thomas Lavergne', author_email='t.lavergne@met.no', package_dir={'pyresample': 'pyresample'}, packages=['pyresample'], install_requires=requirements, extras_require=extras_require, test_suite='pyresample.t...
setup(name='pyresample', version=version.__version__,
random_line_split
PropertyConstants.js
export const FILLPATTERN = { none: '', crossHatched: 'Crosshatched', hatched: 'Hatched', solid: 'Solid' };
dotted: 'Dotted', solid: 'Solid' }; export const ALTITUDEMODE = { NONE: '', ABSOLUTE: 'Absolute', RELATIVE_TO_GROUND: 'Relative to ground', CLAMP_TO_GROUND: 'Clamp to ground' }; export const ICONSIZE = { none: '', verySmall: 'Very Small', small: 'Small', medium: 'Medium', large: 'Large', extra...
export const STROKEPATTERN = { none: '', dashed: 'Dashed',
random_line_split
config.py
# -*- coding: utf-8 -*- """ :copyright: (C) 2010-2013 by Contrail Consortium. """ from conpaas.core.log import create_logger from conpaas.core.node import ServiceNode E_ARGS_UNEXPECTED = 0 E_CONFIG_READ_FAILED = 1 E_CONFIG_NOT_EXIST = 2 E_UNKNOWN = 3 E_ARGS_MISSING = 4 E_ARGS_INVALID = 5 E_STATE_ERROR = 6 E_STR...
(self, nodes): for node in nodes: del self.glb_service_nodes[node.id] def addMySQLServiceNodes(self, nodes): ''' Add new Service Node to the server (configuration). ''' for node in nodes: self.serviceNodes[str(node.id)] = SQLServiceNode(node) d...
remove_glb_nodes
identifier_name
config.py
# -*- coding: utf-8 -*- """ :copyright: (C) 2010-2013 by Contrail Consortium. """ from conpaas.core.log import create_logger from conpaas.core.node import ServiceNode E_ARGS_UNEXPECTED = 0 E_CONFIG_READ_FAILED = 1 E_CONFIG_NOT_EXIST = 2 E_UNKNOWN = 3 E_ARGS_MISSING = 4 E_ARGS_INVALID = 5 E_STATE_ERROR = 6 E_STR...
else : self.glb_service_nodes.pop(node.id,None)
self.serviceNodes.pop(node.id, None)
conditional_block
config.py
# -*- coding: utf-8 -*- """ :copyright: (C) 2010-2013 by Contrail Consortium. """ from conpaas.core.log import create_logger from conpaas.core.node import ServiceNode E_ARGS_UNEXPECTED = 0 E_CONFIG_READ_FAILED = 1 E_CONFIG_NOT_EXIST = 2 E_UNKNOWN = 3 E_ARGS_MISSING = 4 E_ARGS_INVALID = 5 E_STATE_ERROR = 6 E_STR...
def addMySQLServiceNodes(self, nodes): ''' Add new Service Node to the server (configuration). ''' for node in nodes: self.serviceNodes[str(node.id)] = SQLServiceNode(node) def removeMySQLServiceNode(self, id): ''' Remove Service Node to the ser...
for node in nodes: del self.glb_service_nodes[node.id]
identifier_body
config.py
# -*- coding: utf-8 -*- """ :copyright: (C) 2010-2013 by Contrail Consortium. """ from conpaas.core.log import create_logger from conpaas.core.node import ServiceNode E_ARGS_UNEXPECTED = 0 E_CONFIG_READ_FAILED = 1 E_CONFIG_NOT_EXIST = 2 E_UNKNOWN = 3 E_ARGS_MISSING = 4 E_ARGS_INVALID = 5 E_STATE_ERROR = 6 E_STR...
def get_nodes(self): """ Returns the list of MySQL nodes.""" return [serviceNode for serviceNode in self.serviceNodes.values()] def get_glb_nodes(self): ''' Returns the list of GLB nodes''' return [serviceNode for serviceNode in self.glb_service_nodes.values()] def getMySQL...
random_line_split
contextHelpers.js
const path = require('path'); const wmd = require('wmd'); const {getFile} = require('./importHelpers'); const createContextForList = (folderContents) => { let promises = []; return new Promise((resolve, reject) => { for (let file in folderContents) { let promise = getFile(folderContents[file].path); ...
module.exports.createContextFromFile = createContextFromFile;
} module.exports.createContextForList = createContextForList;
random_line_split
CollectableV1Mixin.js
// @link http://schemas.wbeme.com/json-schema/eme/collector/mixin/collectable/1-0-0.json# import Fb from '@gdbots/pbj/FieldBuilder'; import Mixin from '@gdbots/pbj/Mixin'; import SchemaId from '@gdbots/pbj/SchemaId'; import T from '@gdbots/pbj/types'; export default class CollectableV1Mixin extends Mixin { /** * ...
*/ Fb.create('collector', T.MessageType.create()) .anyOfCuries([ 'gdbots:contexts::app', ]) .build(), ]; } }
return [ /* * The application collecting the message. This is set on the * server by the collector app itself.
random_line_split
CollectableV1Mixin.js
// @link http://schemas.wbeme.com/json-schema/eme/collector/mixin/collectable/1-0-0.json# import Fb from '@gdbots/pbj/FieldBuilder'; import Mixin from '@gdbots/pbj/Mixin'; import SchemaId from '@gdbots/pbj/SchemaId'; import T from '@gdbots/pbj/types'; export default class CollectableV1Mixin extends Mixin { /** * ...
() { return [ /* * The application collecting the message. This is set on the * server by the collector app itself. */ Fb.create('collector', T.MessageType.create()) .anyOfCuries([ 'gdbots:contexts::app', ]) .build(), ]; } }
getFields
identifier_name
index.js
'use strict'; var staticMatch = require('css-mediaquery').match; var dynamicMatch = typeof window !== 'undefined' ? window.matchMedia : null; // our fake MediaQueryList function Mql(query, values){ var self = this; if(dynamicMatch){ var mql = dynamicMatch.call(window, query); this.matches = mql.matches; ...
(){ if(mql){ mql.removeListener(update); } } } function matchMedia(query, values){ return new Mql(query, values); } module.exports = matchMedia;
dispose
identifier_name
index.js
'use strict'; var staticMatch = require('css-mediaquery').match; var dynamicMatch = typeof window !== 'undefined' ? window.matchMedia : null; // our fake MediaQueryList function Mql(query, values){ var self = this; if(dynamicMatch){ var mql = dynamicMatch.call(window, query); this.matches = mql.matches; ...
module.exports = matchMedia;
function matchMedia(query, values){ return new Mql(query, values); }
random_line_split
index.js
'use strict'; var staticMatch = require('css-mediaquery').match; var dynamicMatch = typeof window !== 'undefined' ? window.matchMedia : null; // our fake MediaQueryList function Mql(query, values){ var self = this; if(dynamicMatch){ var mql = dynamicMatch.call(window, query); this.matches = mql.matches; ...
} } function matchMedia(query, values){ return new Mql(query, values); } module.exports = matchMedia;
{ mql.removeListener(update); }
conditional_block
index.js
'use strict'; var staticMatch = require('css-mediaquery').match; var dynamicMatch = typeof window !== 'undefined' ? window.matchMedia : null; // our fake MediaQueryList function Mql(query, values)
} } function removeListener(listener){ if(mql){ mql.removeListener(listener); } } // update ourselves! function update(evt){ self.matches = evt.matches; self.media = evt.media; } function dispose(){ if(mql){ mql.removeListener(update); } } } function matchMed...
{ var self = this; if(dynamicMatch){ var mql = dynamicMatch.call(window, query); this.matches = mql.matches; this.media = mql.media; // TODO: is there a time it makes sense to remove this listener? mql.addListener(update); } else { this.matches = staticMatch(query, values); this.media ...
identifier_body
webgl_camera.ts
/// <reference path="../../three.d.ts" /> /// <reference path="../three-tests-setup.ts" /> // https://github.com/mrdoob/three.js/blob/master/examples/webgl_camera.html () => { var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var container, stats; var camera, scene, rende...
var particles = new THREE.Points( geometry, new THREE.PointsMaterial( { color: 0x888888 } ) ); scene.add( particles ); // renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( SCREEN_WIDTH, SCREE...
var vertex = new THREE.Vector3(); vertex.x = THREE.Math.randFloatSpread( 2000 ); vertex.y = THREE.Math.randFloatSpread( 2000 ); vertex.z = THREE.Math.randFloatSpread( 2000 ); geometry.vertices.push( vertex ); }
conditional_block
webgl_camera.ts
/// <reference path="../../three.d.ts" /> /// <reference path="../three-tests-setup.ts" /> // https://github.com/mrdoob/three.js/blob/master/examples/webgl_camera.html () => { var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var container, stats; var camera, scene, rende...
// function animate() { requestAnimationFrame( animate ); render(); stats.update(); } function render() { var r = Date.now() * 0.0005; mesh.position.x = 700 * Math.cos( r ); mesh.position.z = 700 * Math.sin( r ); mesh.position.y = 700 * Mat...
SCREEN_WIDTH = window.innerWidth; SCREEN_HEIGHT = window.innerHeight; renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); camera.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; camera.updateProjectionMatrix(); cameraPerspective.aspect = 0.5 * SCREEN_WIDTH / SCREEN_HEIGHT; ...
identifier_body
webgl_camera.ts
/// <reference path="../../three.d.ts" /> /// <reference path="../three-tests-setup.ts" /> // https://github.com/mrdoob/three.js/blob/master/examples/webgl_camera.html () => { var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var container, stats; var camera, scene, rende...
switch( event.keyCode ) { case 79: /*O*/ activeCamera = cameraOrtho; activeHelper = cameraOrthoHelper; break; case 80: /*P*/ activeCamera = cameraPerspective; activeHelper = cameraPerspectiveHelper; ...
// function onKeyDown ( event ) {
random_line_split
webgl_camera.ts
/// <reference path="../../three.d.ts" /> /// <reference path="../three-tests-setup.ts" /> // https://github.com/mrdoob/three.js/blob/master/examples/webgl_camera.html () => { var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var container, stats; var camera, scene, rende...
{ requestAnimationFrame( animate ); render(); stats.update(); } function render() { var r = Date.now() * 0.0005; mesh.position.x = 700 * Math.cos( r ); mesh.position.z = 700 * Math.sin( r ); mesh.position.y = 700 * Math.sin( r ); mesh.chil...
imate()
identifier_name
utils.py
# It is a bad practice to keep all "miscellaneous" stuffs # into the single "utils" module. # Let's categorize them by purpose and domain, and keep # refactoring to use the proper module names. from .asyncio import ( # for legacy imports # noqa AsyncBarrier, cancel_tasks, current_loop, run_through,...
KT = TypeVar('KT') VT = TypeVar('VT') def env_info() -> str: """ Returns a string that contains the Python version and runtime path. """ v = sys.version_info pyver = f'Python {v.major}.{v.minor}.{v.micro}' if v.releaselevel == 'alpha': pyver += 'a' if v.releaselevel == 'beta': ...
random_line_split
utils.py
# It is a bad practice to keep all "miscellaneous" stuffs # into the single "utils" module. # Let's categorize them by purpose and domain, and keep # refactoring to use the proper module names. from .asyncio import ( # for legacy imports # noqa AsyncBarrier, cancel_tasks, current_loop, run_through,...
: """ Entry class represents a non-comment line on the `fstab` file. """ def __init__(self, device, mountpoint, fstype, options, d=0, p=0) -> None: self.device = device self.mountpoint = mountpoint self.fstype = fstype if not options: options = 'defaults' ...
FstabEntry
identifier_name
utils.py
.files import AsyncFileWriter # for legacy imports # noqa from .networking import ( # for legacy imports # noqa curl, find_free_port, ) from .types import BinarySize KT = TypeVar('KT') VT = TypeVar('VT') def env_info() -> str: """ Returns a string that contains the Python version and runtime pa...
if self._hydrate_entry(line) == entry: found = True break
conditional_block
utils.py
VT = TypeVar('VT') def env_info() -> str: """ Returns a string that contains the Python version and runtime path. """ v = sys.version_info pyver = f'Python {v.major}.{v.minor}.{v.micro}' if v.releaselevel == 'alpha': pyver += 'a' if v.releaselevel == 'beta': pyver += 'b' ...
await self._fp.seek(0) lines = await self._fp.readlines() found = False for index, line in enumerate(lines): try: if not line.strip().startswith("#"): if self._hydrate_entry(line) == entry: found = True ...
identifier_body
mavlog.py
"""Log MAVLink stream.""" import argparse from pymavlink import mavutil import pymavlink.dialects.v10.ceaufmg as mavlink def
(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--verbose", action='store_true', help="print messages to STDOUT") parser.add_argument("--device", required=True, help="serial port") parser.add_argument("--log", type=argparse.FileType('w'), ...
main
identifier_name
mavlog.py
"""Log MAVLink stream.""" import argparse from pymavlink import mavutil import pymavlink.dialects.v10.ceaufmg as mavlink def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--verbose", action='store_true', help="print messages to STDOUT") parse...
if __name__ == '__main__': main()
msg = conn.recv_msg() if args.verbose and msg is not None: print(msg)
conditional_block
mavlog.py
"""Log MAVLink stream.""" import argparse from pymavlink import mavutil import pymavlink.dialects.v10.ceaufmg as mavlink def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--verbose", action='store_true', help="print messages to STDOUT") parse...
main()
random_line_split
mavlog.py
"""Log MAVLink stream.""" import argparse from pymavlink import mavutil import pymavlink.dialects.v10.ceaufmg as mavlink def main():
if __name__ == '__main__': main()
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--verbose", action='store_true', help="print messages to STDOUT") parser.add_argument("--device", required=True, help="serial port") parser.add_argument("--log", type=argparse.FileType('w'), ...
identifier_body
server.py
.app.add_route(self.ping, '/ping') self.app.add_route(self.scan, "/v1/scan", methods=['POST']) self.app.add_route( self.report, '/v1/report/<job_id:int>', methods=['GET']) async def hello(self, _): """ hello endpoint as fallback and catch all @returns: hello world json ...
self.server.close()
conditional_block
server.py
see <http://www.gnu.org/licenses/>. # # # ############################################################################### """ This module implements the Peekaboo server, i.e. the frontend to the client. """ import asyncio import email....
async def ping(self, _): """ ping endpoint for diagnostics @returns: pong json response """ return sanic.response.json({'answer': 'pong'}) async def scan(self, request): """ scan endpoint for job submission @param request: sanic request object @type r...
""" hello endpoint as fallback and catch all @returns: hello world json response """ return sanic.response.json({'hello': 'PeekabooAV'})
identifier_body
server.py
see <http://www.gnu.org/licenses/>. # # # ############################################################################### """ This module implements the Peekaboo server, i.e. the frontend to the client. """ import asyncio import email....
: """ A class wrapping the server components of Peekaboo. """ def __init__(self, host, port, job_queue, sample_factory, request_queue_size, db_con): """ Initialise a new server and start it. All error conditions are returned as exceptions. @param host: The local address...
PeekabooServer
identifier_name
server.py
, see <http://www.gnu.org/licenses/>. # # # ############################################################################### """ This module implements the Peekaboo server, i.e. the frontend to the client. """ import asyncio import email...
@type request_queue_size: int """ logger.debug('Starting up server.') self.app = sanic.Sanic("PeekabooAV", configure_logging=False) self.app.config.FALLBACK_ERROR_FORMAT = "json" # silence sanic to a reasonable amount logging.getLogger('sanic.root').setLevel(logg...
samples. @type sample_factory: SampleFactory @param request_queue_size: Number of requests that may be pending on the socket.
random_line_split
mut_ref.rs
// Compiler: // // Run-time: // stdout: 2 // 7 // 6 // 11 #![allow(unused_attributes)] #![feature(auto_traits, lang_items, no_core, start, intrinsics, track_caller)] #![no_std] #![no_core] /* * Core */ // Because we don't have core yet. #[lang = "sized"] pub trait Sized {} #[lang = "copy"] trait C...
#[lang = "add"] trait Add<RHS = Self> { type Output; fn add(self, rhs: RHS) -> Self::Output; } impl Add for u8 { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs } } impl Add for i8 { type Output = Self; fn add(self, rhs: Self) -> Self { self + rhs ...
{ unsafe { libc::puts("Panicking\0" as *const str as *const u8); libc::fflush(libc::STDOUT); intrinsics::abort(); } }
identifier_body
mut_ref.rs
// Compiler: // // Run-time: // stdout: 2 // 7 // 6 // 11 #![allow(unused_attributes)] #![feature(auto_traits, lang_items, no_core, start, intrinsics, track_caller)] #![no_std] #![no_core] /* * Core */ // Because we don't have core yet. #[lang = "sized"] pub trait Sized {}
#[lang = "copy"] trait Copy { } impl Copy for isize {} impl Copy for *mut i32 {} impl Copy for usize {} impl Copy for u8 {} impl Copy for i8 {} impl Copy for i32 {} #[lang = "receiver"] trait Receiver { } #[lang = "freeze"] pub(crate) unsafe auto trait Freeze {} #[lang = "panic_location"] struct PanicLocation { ...
random_line_split
mut_ref.rs
// Compiler: // // Run-time: // stdout: 2 // 7 // 6 // 11 #![allow(unused_attributes)] #![feature(auto_traits, lang_items, no_core, start, intrinsics, track_caller)] #![no_std] #![no_core] /* * Core */ // Because we don't have core yet. #[lang = "sized"] pub trait Sized {} #[lang = "copy"] trait C...
(num: &mut isize) { *num = *num + 5; } #[start] fn main(mut argc: isize, _argv: *const *const u8) -> isize { let mut test = test(argc); unsafe { libc::printf(b"%ld\n\0" as *const u8 as *const i8, test.field); } update_num(&mut test.field); unsafe { libc::printf(b"%ld\n\0" as *co...
update_num
identifier_name
issue-84973-blacklist.rs
// Checks that certain traits for which we don't want to suggest borrowing // are blacklisted and don't cause the suggestion to be issued. #![feature(generators)] fn f_copy<T: Copy>(t: T) {} fn f_clone<T: Clone>(t: T) {} fn f_unpin<T: Unpin>(t: T) {} fn f_sized<T: Sized>(t: T) {} fn f_send<T: Send>(t: T) {} struct S...
}
random_line_split
issue-84973-blacklist.rs
// Checks that certain traits for which we don't want to suggest borrowing // are blacklisted and don't cause the suggestion to be issued. #![feature(generators)] fn
<T: Copy>(t: T) {} fn f_clone<T: Clone>(t: T) {} fn f_unpin<T: Unpin>(t: T) {} fn f_sized<T: Sized>(t: T) {} fn f_send<T: Send>(t: T) {} struct S; fn main() { f_copy("".to_string()); //~ ERROR: the trait bound `String: Copy` is not satisfied [E0277] f_clone(S); //~ ERROR: the trait bound `S: Clone` is not sat...
f_copy
identifier_name
issue-84973-blacklist.rs
// Checks that certain traits for which we don't want to suggest borrowing // are blacklisted and don't cause the suggestion to be issued. #![feature(generators)] fn f_copy<T: Copy>(t: T) {} fn f_clone<T: Clone>(t: T) {} fn f_unpin<T: Unpin>(t: T)
fn f_sized<T: Sized>(t: T) {} fn f_send<T: Send>(t: T) {} struct S; fn main() { f_copy("".to_string()); //~ ERROR: the trait bound `String: Copy` is not satisfied [E0277] f_clone(S); //~ ERROR: the trait bound `S: Clone` is not satisfied [E0277] f_unpin(static || { yield; }); //~^ ERROR: cannot be un...
{}
identifier_body
custom.js
$(document).ready(function() { $('.fancybox').fancybox(); $(".fancybox-effects-a").fancybox({ helpers: { title : { type : 'outside' }, overlay : { speedOut : 0 } } }); $(".fancybox-effects-b").fancybox({ openEffect : 'none', closeEffect : 'none', helpers : { title : { type : '...
helpers : { thumbs : { width: 75, height: 50 } } }); }); });
], {
random_line_split
__init__.py
""" Initialize the application. """ import logging logger = logging.getLogger(__name__) import appdirs import click import datetime import distutils.dir_util import os import putiopy import sqlite3 APP_NAME = 'putio-automator' APP_AUTHOR = 'datashaman' DIRS = appdirs.AppDirs(APP_NAME, APP_AUTHOR) from .db import cre...
if os.path.exists(search_path) and not os.path.isdir(search_path): config = search_path break return config def echo(level, message): log_func = getattr(logger, level) log_func(message) click.echo(message)
click.echo(message)
conditional_block
__init__.py
""" Initialize the application. """ import logging logger = logging.getLogger(__name__) import appdirs import click import datetime import distutils.dir_util import os import putiopy import sqlite3 APP_NAME = 'putio-automator' APP_AUTHOR = 'datashaman' DIRS = appdirs.AppDirs(APP_NAME, APP_AUTHOR) from .db import cre...
def find_config(verbose=False): "Search for config on wellknown paths" search_paths = [ os.path.join(os.getcwd(), 'config.py'), os.path.join(DIRS.user_data_dir, 'config.py'), os.path.join(DIRS.site_data_dir, 'config.py'), ] config = None for search_path in search_paths: ...
"Date handler for JSON serialization" if isinstance(obj, datetime.datetime) or isinstance(obj, datetime.date): return obj.isoformat() else: return None
identifier_body
__init__.py
""" Initialize the application. """ import logging logger = logging.getLogger(__name__) import appdirs import click import datetime import distutils.dir_util import os import putiopy import sqlite3 APP_NAME = 'putio-automator' APP_AUTHOR = 'datashaman' DIRS = appdirs.AppDirs(APP_NAME, APP_AUTHOR) from .db import cre...
(level, message): log_func = getattr(logger, level) log_func(message) click.echo(message)
echo
identifier_name
__init__.py
""" Initialize the application.
import appdirs import click import datetime import distutils.dir_util import os import putiopy import sqlite3 APP_NAME = 'putio-automator' APP_AUTHOR = 'datashaman' DIRS = appdirs.AppDirs(APP_NAME, APP_AUTHOR) from .db import create_db, database_path create_db() def date_handler(obj): "Date handler for JSON seri...
""" import logging logger = logging.getLogger(__name__)
random_line_split
path_parsing.rs
extern crate memchr; use self::memchr::{memchr, memrchr}; use memrnchr::memrnchr; use std::path::MAIN_SEPARATOR; use std::str; pub const SEP: u8 = MAIN_SEPARATOR as u8; lazy_static! { pub static ref SEP_STR: &'static str = str::from_utf8(&[SEP]).unwrap(); } // Returns the byte offset of the last byte that equals M...
#[inline(always)] pub fn contains_sep(bytes: &[u8]) -> bool { memchr(SEP, bytes) != None }
pub fn find_last_non_sep_pos(bytes: &[u8]) -> Option<usize> { memrnchr(SEP, bytes) } // Whether the given byte sequence contains a MAIN_SEPARATOR.
random_line_split
path_parsing.rs
extern crate memchr; use self::memchr::{memchr, memrchr}; use memrnchr::memrnchr; use std::path::MAIN_SEPARATOR; use std::str; pub const SEP: u8 = MAIN_SEPARATOR as u8; lazy_static! { pub static ref SEP_STR: &'static str = str::from_utf8(&[SEP]).unwrap(); } // Returns the byte offset of the last byte that equals M...
// Whether the given byte sequence contains a MAIN_SEPARATOR. #[inline(always)] pub fn contains_sep(bytes: &[u8]) -> bool { memchr(SEP, bytes) != None }
{ memrnchr(SEP, bytes) }
identifier_body
path_parsing.rs
extern crate memchr; use self::memchr::{memchr, memrchr}; use memrnchr::memrnchr; use std::path::MAIN_SEPARATOR; use std::str; pub const SEP: u8 = MAIN_SEPARATOR as u8; lazy_static! { pub static ref SEP_STR: &'static str = str::from_utf8(&[SEP]).unwrap(); } // Returns the byte offset of the last byte that equals M...
(bytes: &[u8]) -> bool { memchr(SEP, bytes) != None }
contains_sep
identifier_name
bootstrap.py
IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-b...
# parsing arguments def normalize_to_url(option, opt_str, value, parser): if value: if '://' not in value: # It doesn't smell like a URL. value = 'file://%s' % ( urllib.pathname2url( os.path.abspath(os.path.expanduser(value))),) if opt_str == '--downl...
distribute_source = 'http://python-distribute.org/distribute_setup.py'
random_line_split
bootstrap.py
subprocess from optparse import OptionParser if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: quote = str # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments...
sys.stdout.flush() sys.stderr.flush() print ("An error occurred when trying to install zc.buildout. " "Look above this message for any errors that " "were output by easy_install.") sys.exit(exitcode)
conditional_block
bootstrap.py
IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-b...
else: quote = str # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments. stdout, stderr = subprocess.Popen( [sys.executable, '-Sc', 'try:\n' ' import ConfigParser\n' 'except ImportError:\n' ' print 1\n' 'else:\n' ' print 0\n'], stdout=subproce...
if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c
identifier_body