file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
mod.rs
extern crate android_glue; use libc; use std::ffi::{CString}; use std::sync::mpsc::{Receiver, channel}; use {CreationError, Event, MouseCursor}; use CreationError::OsError; use events::ElementState::{Pressed, Released}; use events::Event::{MouseInput, MouseMoved}; use events::MouseButton; use std::collections::VecDeq...
} else { Some(( unsafe { ffi::ANativeWindow_getWidth(native_window) } as u32, unsafe { ffi::ANativeWindow_getHeight(native_window) } as u32 )) } } pub fn get_outer_size(&self) -> Option<(u32, u32)> { self.get_inner_size() } ...
pub fn get_inner_size(&self) -> Option<(u32, u32)> { let native_window = unsafe { android_glue::get_native_window() }; if native_window.is_null() { None
random_line_split
deriving-meta-multiple.rs
// xfail-fast // 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 // <...
() { use core::hash::{Hash, HashUtil}; // necessary for IterBytes check let a = Foo {bar: 4, baz: -3}; a == a; // check for Eq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness a.hash(); // check for IterBytes impl w/o testing its correctness }
main
identifier_name
deriving-meta-multiple.rs
// xfail-fast // 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. //
// <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. #[deriving(Eq)] #[deriving(Clone)] #[deriving(IterBytes)] struct Foo { bar: uint, baz: int } pub fn main() { use core::hash::{Hash, HashUtil}...
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
deriving-meta-multiple.rs
// xfail-fast // 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 // <...
{ use core::hash::{Hash, HashUtil}; // necessary for IterBytes check let a = Foo {bar: 4, baz: -3}; a == a; // check for Eq impl w/o testing its correctness a.clone(); // check for Clone impl w/o testing its correctness a.hash(); // check for IterBytes impl w/o testing its correctness }
identifier_body
derive_input_object.rs
#![allow(clippy::match_wild_err_arm)] use crate::{ result::{GraphQLScope, UnsupportedAttribute}, util::{self, span_container::SpanContainer, RenameRule}, }; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields}; pub fn impl_input_object(ast: ...
if let Some(duplicates) = crate::util::duplicate::Duplicate::find_by_key(&fields, |field| &field.name) { error.duplicate(duplicates.iter()) } if !attrs.interfaces.is_empty() { attrs.interfaces.iter().for_each(|elm| { error.unsupported_attribute(elm.span(), Unsuppor...
{ error.not_empty(ast_span); }
conditional_block
derive_input_object.rs
#![allow(clippy::match_wild_err_arm)] use crate::{ result::{GraphQLScope, UnsupportedAttribute}, util::{self, span_container::SpanContainer, RenameRule}, }; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields}; pub fn
(ast: syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> { let ast_span = ast.span(); let fields = match ast.data { Data::Struct(data) => match data.fields { Fields::Named(named) => named.named, _ => { return Err( error.custom_e...
impl_input_object
identifier_name
derive_input_object.rs
#![allow(clippy::match_wild_err_arm)] use crate::{ result::{GraphQLScope, UnsupportedAttribute}, util::{self, span_container::SpanContainer, RenameRule}, }; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields}; pub fn impl_input_object(ast: ...
{ let ast_span = ast.span(); let fields = match ast.data { Data::Struct(data) => match data.fields { Fields::Named(named) => named.named, _ => { return Err( error.custom_error(ast_span, "all fields must be named, e.g., `test: String`") ...
identifier_body
derive_input_object.rs
#![allow(clippy::match_wild_err_arm)] use crate::{ result::{GraphQLScope, UnsupportedAttribute}, util::{self, span_container::SpanContainer, RenameRule}, }; use proc_macro2::TokenStream; use quote::{quote, ToTokens}; use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields}; pub fn impl_input_object(ast: ...
description: field_attrs.description.map(SpanContainer::into_inner), deprecation: None, resolver_code, is_type_inferred: true, is_async: false, default, span, }) }) .collect::<Vec<...
args: Vec::new(),
random_line_split
config.js
/** * #config * * Copyright (c)2011, by Branko Vukelic * * Configuration methods and settings for Postfinance. All startup configuration * settings are set using the `config.configure()` and `config.option()` * methods. Most options can only be set once, and subsequent attempts to set * them will result in an ...
* treated as a constant (i.e., read-only). */ var settings = {}; settings.pmlist=['creditcart','postfinance card','paypal'] settings.pspid = ''; settings.apiPassword = ''; settings.apiUser = ''; settings.currency = 'CHF'; settings.allowedCurrencies = ['CHF']; settings.shaWithSecret=true; // do not append secret in sh...
* Only `currency` option can be set multiple times. All other options can only * be set once using the ``config.configure()`` method. * * The ``apiVersion`` setting is present for conveinence and is should be
random_line_split
config.js
/** * #config * * Copyright (c)2011, by Branko Vukelic * * Configuration methods and settings for Postfinance. All startup configuration * settings are set using the `config.configure()` and `config.option()` * methods. Most options can only be set once, and subsequent attempts to set * them will result in an ...
}; /** * ## config.configure(opts) * *Set global Postfinance configuration options* * * This method should be used before using any of the Postfinance's functions. It * sets the options in the `settings` object, and performs basic validation * of the options before doing so. * * Unless you also pass it the `...
{ util.debug(message); }
conditional_block
get.rs
extern crate tftp; use std::io::BufWriter; use std::fs::OpenOptions; use std::path::Path; use std::net::{SocketAddr, IpAddr, Ipv4Addr}; use std::process::exit; use std::env; use tftp::client::get; use tftp::packet::Mode; fn
() { let args: Vec<_> = env::args().collect(); if args.len() != 2 { println!("Usage: {} PATH", args.get(0).unwrap()); return } let file_path = args[1].clone(); let mut file_options = OpenOptions::new(); file_options.truncate(true).create(true).write(true); let file = match fi...
main
identifier_name
get.rs
extern crate tftp; use std::io::BufWriter; use std::fs::OpenOptions; use std::path::Path; use std::net::{SocketAddr, IpAddr, Ipv4Addr}; use std::process::exit; use std::env; use tftp::client::get; use tftp::packet::Mode; fn main() { let args: Vec<_> = env::args().collect(); if args.len() != 2 { print...
get(&Path::new(&file_path), Mode::Octet, &mut writer); }
random_line_split
get.rs
extern crate tftp; use std::io::BufWriter; use std::fs::OpenOptions; use std::path::Path; use std::net::{SocketAddr, IpAddr, Ipv4Addr}; use std::process::exit; use std::env; use tftp::client::get; use tftp::packet::Mode; fn main()
{ let args: Vec<_> = env::args().collect(); if args.len() != 2 { println!("Usage: {} PATH", args.get(0).unwrap()); return } let file_path = args[1].clone(); let mut file_options = OpenOptions::new(); file_options.truncate(true).create(true).write(true); let file = match file_...
identifier_body
vcr.py
# Copyright 2016 Osvaldo Santana Neto # # 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 ...
(request): if not request.body: return request body = request.body.decode() body = USER_REGEX.sub(r'<usuario>teste</usuario>', body) body = PASS_REGEX.sub(r'<senha>****</senha>', body) request.body = body.encode() return request FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "...
replace_auth
identifier_name
vcr.py
# Copyright 2016 Osvaldo Santana Neto # # 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 ...
FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "fixtures") vcr = VCR( record_mode='once', serializer='yaml', cassette_library_dir=os.path.join(FIXTURES_DIR, 'cassettes'), path_transformer=VCR.ensure_suffix('.yaml'), match_on=['method'], before_record_request=replace_auth, )
if not request.body: return request body = request.body.decode() body = USER_REGEX.sub(r'<usuario>teste</usuario>', body) body = PASS_REGEX.sub(r'<senha>****</senha>', body) request.body = body.encode() return request
identifier_body
vcr.py
# Copyright 2016 Osvaldo Santana Neto # # 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 ...
)
path_transformer=VCR.ensure_suffix('.yaml'), match_on=['method'], before_record_request=replace_auth,
random_line_split
vcr.py
# Copyright 2016 Osvaldo Santana Neto # # 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 ...
body = request.body.decode() body = USER_REGEX.sub(r'<usuario>teste</usuario>', body) body = PASS_REGEX.sub(r'<senha>****</senha>', body) request.body = body.encode() return request FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "fixtures") vcr = VCR( record_mode='once', seriali...
return request
conditional_block
root.d.ts
import PreviousMap from './previous-map'; import Container from './container'; import * as postcss from './postcss'; import Result from './result'; import Node from './node'; export default class
extends Container implements postcss.Root { /** * Returns a string representing the node's type. Possible values are * root, atrule, rule, decl or comment. */ type: string; rawCache: { [key: string]: any; }; /** * Represents a CSS file and contains all its parsed nodes. ...
Root
identifier_name
root.d.ts
import PreviousMap from './previous-map'; import Container from './container'; import * as postcss from './postcss'; import Result from './result'; import Node from './node'; export default class Root extends Container implements postcss.Root { /** * Returns a string representing the node's type. Possible valu...
*/ remove(child?: Node | number): Root; /** * Deprecated. Use Root#source.input.map. */ prevMap(): PreviousMap; }
* Deprecated. Use Root#removeChild.
random_line_split
config.py
#!/usr/bin/env python # # Original filename: config.py # # Author: Tim Brandt # Email: tbrandt@astro.princeton.edu # Date: August 2011 # # Summary: Set configuration parameters to sensible values. # import re from subprocess import *
def config(nframes, framesize): ################################################################### # Fetch the total amount of physical system memory in bytes. # This is the second entry on the second line of the standard # output of the 'free' command. ###########################################...
import multiprocessing import numpy as np
random_line_split
config.py
#!/usr/bin/env python # # Original filename: config.py # # Author: Tim Brandt # Email: tbrandt@astro.princeton.edu # Date: August 2011 # # Summary: Set configuration parameters to sensible values. # import re from subprocess import * import multiprocessing import numpy as np def config(nframes, framesize): ####...
print "\nGetting system parameters, setting pipeline execution parameters..." osver = Popen(["uname", "-a"], stdout=PIPE).stdout.read() if osver.startswith("Linux"): print "You are running Linux." elif osver.startswith("Darwin"): print "You are running Mac OS-X." else: print "You...
identifier_body
config.py
#!/usr/bin/env python # # Original filename: config.py # # Author: Tim Brandt # Email: tbrandt@astro.princeton.edu # Date: August 2011 # # Summary: Set configuration parameters to sensible values. # import re from subprocess import * import multiprocessing import numpy as np def
(nframes, framesize): ################################################################### # Fetch the total amount of physical system memory in bytes. # This is the second entry on the second line of the standard # output of the 'free' command. ######################################################...
config
identifier_name
config.py
#!/usr/bin/env python # # Original filename: config.py # # Author: Tim Brandt # Email: tbrandt@astro.princeton.edu # Date: August 2011 # # Summary: Set configuration parameters to sensible values. # import re from subprocess import * import multiprocessing import numpy as np def config(nframes, framesize): ####...
else: print "Your operating system is not recognized." if osver.startswith("Linux"): mem = Popen(["free", "-b"], stdout=PIPE).stdout.read() mem = int(mem.split('\n')[1].split()[1]) elif osver.startswith("Darwin"): mem = Popen(["vm_stat"], stdout=PIPE).stdout.read().split('\...
print "You are running Mac OS-X."
conditional_block
Final_P4_1and2.py
#Final Exam Problem 4-2 import random, pylab # You are given this function def getMeanAndStd(X): mean = sum(X)/float(len(X)) tot = 0.0 for x in X: tot += (x - mean)**2 std = (tot/len(X))**0.5 return mean, std # You are given this class class Die(object): def __init__(self, valList): ...
else: run = 1 longest_runs.append(longest) makeHistogram(longest_runs, 10, 'Longest Run', 'Frequency', \ 'Frequency of Longest Consecutive Dice Rolls') return sum(longest_runs)/len(longest_runs) # One test case print(getAverage...
run += 1 if run > longest: longest = run
conditional_block
Final_P4_1and2.py
#Final Exam Problem 4-2 import random, pylab # You are given this function def getMeanAndStd(X): mean = sum(X)/float(len(X)) tot = 0.0 for x in X: tot += (x - mean)**2 std = (tot/len(X))**0.5 return mean, std # You are given this class class Die(object): def __init__(self, valList): ...
# Implement this -- Coding Part 1 of 2 def makeHistogram(values, numBins, xLabel, yLabel, title=None): """ - values, a sequence of numbers - numBins, a positive int - xLabel, yLabel, title, are strings - Produces a histogram of values with numBins bins and the indicated labels for ...
return random.choice(self.possibleVals)
identifier_body
Final_P4_1and2.py
#Final Exam Problem 4-2 import random, pylab # You are given this function def getMeanAndStd(X): mean = sum(X)/float(len(X)) tot = 0.0 for x in X: tot += (x - mean)**2 std = (tot/len(X))**0.5 return mean, std # You are given this class class Die(object): def __init__(self, valList): ...
(die, numRolls, numTrials): """ - die, a Die - numRolls, numTrials, are positive ints - Calculates the expected mean value of the longest run of a number over numTrials runs of numRolls rolls. - Calls makeHistogram to produce a histogram of the longest runs for all the trials...
getAverage
identifier_name
Final_P4_1and2.py
#Final Exam Problem 4-2 import random, pylab # You are given this function def getMeanAndStd(X): mean = sum(X)/float(len(X)) tot = 0.0 for x in X:
std = (tot/len(X))**0.5 return mean, std # You are given this class class Die(object): def __init__(self, valList): """ valList is not empty """ self.possibleVals = valList[:] def roll(self): return random.choice(self.possibleVals) # Implement this -- Coding Part 1 of 2 def mak...
tot += (x - mean)**2
random_line_split
htmlTest.js
/*globals describe, it, beforeEach, afterEach */ var assert = require("assert"), fs = require('fs'), _ = require('underscore'), path = require("path"), Html = require("../lib/html.js"), describeReporting = require("../../../test/helpers.js").describeReporting; describeReporting(path.join(__dirnam...
}); }); });
done(); });
random_line_split
profile-addresses.component.ts
/// <reference types="@types/google-maps" /> import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Injector, Input, OnInit, ViewChild } from '@angular/core'; import { AddressView } from 'app/api/models'; import { Breakpoint } from 'app/core/layout.service'; import { BaseComponent } from 'app/shared/b...
if (breakpoints.has('xl')) { return 400; } else if (breakpoints.has('gt-xs')) { return 340; } else { return 'auto'; } } private showMap() { const container = this.mapContainer.nativeElement as HTMLElement; this.map = new google.maps.Map(container, { mapTypeControl: f...
random_line_split
profile-addresses.component.ts
/// <reference types="@types/google-maps" /> import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Injector, Input, OnInit, ViewChild } from '@angular/core'; import { AddressView } from 'app/api/models'; import { Breakpoint } from 'app/core/layout.service'; import { BaseComponent } from 'app/shared/b...
@ViewChild('mapContainer') mapContainer: ElementRef; map: google.maps.Map; private allInfoWindows: google.maps.InfoWindow[] = []; @Input() addresses: AddressView[]; locatedAddresses: AddressView[]; ngOnInit() { super.ngOnInit(); this.locatedAddresses = (this.addresses || []).filter(a => a.loca...
{ super(injector); }
identifier_body
profile-addresses.component.ts
/// <reference types="@types/google-maps" /> import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Injector, Input, OnInit, ViewChild } from '@angular/core'; import { AddressView } from 'app/api/models'; import { Breakpoint } from 'app/core/layout.service'; import { BaseComponent } from 'app/shared/b...
else { return 'auto'; } } private showMap() { const container = this.mapContainer.nativeElement as HTMLElement; this.map = new google.maps.Map(container, { mapTypeControl: false, streetViewControl: false, minZoom: 2, maxZoom: 17, styles: this.uiLayout.googleMapStyle...
{ return 340; }
conditional_block
profile-addresses.component.ts
/// <reference types="@types/google-maps" /> import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Injector, Input, OnInit, ViewChild } from '@angular/core'; import { AddressView } from 'app/api/models'; import { Breakpoint } from 'app/core/layout.service'; import { BaseComponent } from 'app/shared/b...
(breakpoints: Set<Breakpoint>): number | 'auto' { if (breakpoints.has('xl')) { return 400; } else if (breakpoints.has('gt-xs')) { return 340; } else { return 'auto'; } } private showMap() { const container = this.mapContainer.nativeElement as HTMLElement; this.map = new go...
singleMapWidth
identifier_name
f.js
/** * for(var p in Script.scripts) { * * var script = Script.scripts[p]; * var handle = script.handle; * var base = script.base; * var limit = base + script.extent; * * print(script+"\n"); * * for(var i = base; i < limit; i++) { * var pc = jsd.GetClosestPC(handle,i) * var hasc...
"{"+ " if(text != \\\"\\\")"+ " text += \\\",\\\";"+ " text += p;"+ "}"+ "return text;"; reval(name+" = new Function(\"ob\",\""+fun+"\")"); // show(name); retval = _reval([name+"("+"arguments.callee"+")"]); reval("delete "+name); return re...
"for(var p in ob)"+
random_line_split
f.js
/** * for(var p in Script.scripts) { * * var script = Script.scripts[p]; * var handle = script.handle; * var base = script.base; * var limit = base + script.extent; * * print(script+"\n"); * * for(var i = base; i < limit; i++) { * var pc = jsd.GetClosestPC(handle,i) * var has...
function e(a) { return eval(a); }
{ var retval = ""; var name = "___UNIQUE_NAME__"; var fun = ""+ "var text = \\\"\\\";"+ "for(var p in ob)"+ "{"+ " if(text != \\\"\\\")"+ " text += \\\",\\\";"+ " text += p;"+ "}"+ "return text;"; reval(name+" = new Function(\"...
identifier_body
f.js
/** * for(var p in Script.scripts) { * * var script = Script.scripts[p]; * var handle = script.handle; * var base = script.base; * var limit = base + script.extent; * * print(script+"\n"); * * for(var i = base; i < limit; i++) { * var pc = jsd.GetClosestPC(handle,i) * var has...
(a) { return eval(a); }
e
identifier_name
chat_markers.py
# Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com> # # This file is part of nbxmpp. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 3 # of the License, or (at your opt...
BaseModule): def __init__(self, client): BaseModule.__init__(self, client) self._client = client self.handlers = [ StanzaHandler(name='message', callback=self._process_message_marker, ns=Namespace.CHATMARKERS, ...
hatMarkers(
identifier_name
chat_markers.py
# Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com> # # This file is part of nbxmpp. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 3 # of the License, or (at your opt...
def _process_message_marker(self, _client, stanza, properties): type_ = stanza.getTag('received', namespace=Namespace.CHATMARKERS) if type_ is None: type_ = stanza.getTag('displayed', namespace=Namespace.CHATMARKERS) if type_ is None: type_ = stanza.getTag('a...
aseModule.__init__(self, client) self._client = client self.handlers = [ StanzaHandler(name='message', callback=self._process_message_marker, ns=Namespace.CHATMARKERS, priority=15), ]
identifier_body
chat_markers.py
# Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com> # # This file is part of nbxmpp. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 3 # of the License, or (at your opt...
id_ = type_.getAttr('id') if id_ is None: self._log.warning('Chatmarker without id') self._log.warning(stanza) return properties.marker = ChatMarker(name, id_)
random_line_split
chat_markers.py
# Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com> # # This file is part of nbxmpp. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 3 # of the License, or (at your opt...
name = type_.getName() id_ = type_.getAttr('id') if id_ is None: self._log.warning('Chatmarker without id') self._log.warning(stanza) return properties.marker = ChatMarker(name, id_)
ype_ = stanza.getTag('acknowledged', namespace=Namespace.CHATMARKERS) if type_ is None: return
conditional_block
plot_holoviews.py
# Use holoviews to plot the particle distribution at given time from pathlib import Path import numpy as np import xarray as xr import holoviews as hv from postladim import ParticleFile hv.extension("bokeh") # --- Settings --- tstep = 40 # Time step to show # Output file (and type) output_file = "line_hv.png" #out...
hv.save(h, filename=output_file)
h.opts(toolbar=None)
conditional_block
plot_holoviews.py
# Use holoviews to plot the particle distribution at given time from pathlib import Path import numpy as np import xarray as xr import holoviews as hv from postladim import ParticleFile hv.extension("bokeh") # --- Settings --- tstep = 40 # Time step to show # Output file (and type) output_file = "line_hv.png" #out...
hv.save(h, filename=output_file)
random_line_split
require-dependencies.test.ts
import {lint, ruleType} from '../../../src/rules/require-dependencies'; import {Severity} from '../../../src/types/severity'; describe('require-dependencies Unit Tests', () => { describe('a rule type value should be exported', () => { test('it should equal "standard"', () => { expect(ruleType).toStrictEqua...
});
random_line_split
lifetimes_as_part_of_type.rs
#![allow(warnings)] // **Exercise 1.** For the method `get`, identify at least 4 lifetimes // that must be inferred. // // **Exercise 2.** Modify the signature of `get` such that the method // `get` fails to compile with a lifetime inference error. // // **Exercise 3.** Modify the signature of `get` such that the // `...
} #[test] // START SOLUTION #[should_panic] // END SOLUTION fn do_not_compile() { let map: Map<char, String> = Map::new(); let r; let key = &'c'; r = map.get(key); panic!("If this test is running, your program compiled, and that's bad!"); }
{ let matching_pair: Option<&(K, V)> = <[_]>::iter(&self.elements) .rev() .find(|pair| pair.0 == *key); matching_pair.map(|pair| &pair.1) }
identifier_body
lifetimes_as_part_of_type.rs
#![allow(warnings)] // **Exercise 1.** For the method `get`, identify at least 4 lifetimes // that must be inferred. // // **Exercise 2.** Modify the signature of `get` such that the method // `get` fails to compile with a lifetime inference error. // // **Exercise 3.** Modify the signature of `get` such that the // `...
() { let map: Map<char, String> = Map::new(); let r; let key = &'c'; r = map.get(key); panic!("If this test is running, your program compiled, and that's bad!"); }
do_not_compile
identifier_name
lifetimes_as_part_of_type.rs
#![allow(warnings)] // **Exercise 1.** For the method `get`, identify at least 4 lifetimes
// // **Exercise 2.** Modify the signature of `get` such that the method // `get` fails to compile with a lifetime inference error. // // **Exercise 3.** Modify the signature of `get` such that the // `do_not_compile` test fails to compile with a lifetime error // (but `get` does not have any errors). // // **Exercise ...
// that must be inferred.
random_line_split
issue-14589.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn send(&self, _: T) {} } trait Foo { fn dummy(&self) { }} struct Output(int); impl Foo for Output {}
{}
identifier_body
issue-14589.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T>(_: T) {} struct Test<T> { marker: std::marker::PhantomData<T> } impl<T> Test<T> { fn new() -> Test<T> { Test { marker: ::std::marker::PhantomData } } fn foo(_: T) {} fn send(&self, _: T) {} } trait Foo { fn dummy(&self) { }} struct Output(int); impl Foo for Output {}
send
identifier_name
issue-14589.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
struct Output(int); impl Foo for Output {}
random_line_split
base_inequality_op.py
# encoding: utf-8 # # # 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/. # # Contact: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import absolute_import, divis...
(self, map_): return self.__class__([self.lhs.map(map_), self.rhs.map(map_)]) def missing(self, lang): return FALSE def partial_eval(self, lang): lhs = self.lhs.partial_eval(lang) rhs = self.rhs.partial_eval(lang) if is_literal(lhs) and is_literal(rhs): ret...
map
identifier_name
base_inequality_op.py
# encoding: utf-8 # # # 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/. # # Contact: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import absolute_import, divis...
op = None def __init__(self, terms): Expression.__init__(self, terms) self.lhs, self.rhs = terms @property def name(self): return self.op def __data__(self): if is_op(self.lhs, Variable) and is_literal(self.rhs): return {self.op: {self.lhs.var, self.rhs...
class BaseInequalityOp(Expression): has_simple_form = True data_type = T_BOOLEAN
random_line_split
base_inequality_op.py
# encoding: utf-8 # # # 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/. # # Contact: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import absolute_import, divis...
def __eq__(self, other): if not isinstance(other, self.__class__): return False return self.op == other.op and self.lhs == other.lhs and self.rhs == other.rhs def vars(self): return self.lhs.vars() | self.rhs.vars() def map(self, map_): return self.__class__([...
return {self.op: [self.lhs.__data__(), self.rhs.__data__()]}
conditional_block
base_inequality_op.py
# encoding: utf-8 # # # 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/. # # Contact: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import absolute_import, divis...
has_simple_form = True data_type = T_BOOLEAN op = None def __init__(self, terms): Expression.__init__(self, terms) self.lhs, self.rhs = terms @property def name(self): return self.op def __data__(self): if is_op(self.lhs, Variable) and is_literal(self.rhs): ...
identifier_body
cexceptions.py
# -*- coding: utf-8 -*- # # Copyright (c) 2014 Netheos (http://www.netheos.net) # # 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 req...
return ret class CAuthenticationError(CHttpError): """http 401 error""" pass
ret += ' msg=%s' % self.message
conditional_block
cexceptions.py
# -*- coding: utf-8 -*- # # Copyright (c) 2014 Netheos (http://www.netheos.net) # # 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 req...
class CHttpError(CStorageError): """Raised when providers server answers non OK answers""" def __init__(self, request_method, request_path, status_code, reason, message=None): super(CHttpError, self).__init__(message) self.request_method = re...
super(CFileNotFoundError, self).__init__(message) self.path = c_path
identifier_body
cexceptions.py
# -*- coding: utf-8 -*- # # Copyright (c) 2014 Netheos (http://www.netheos.net) # # 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 req...
(self, message, cause=None): super(CStorageError, self).__init__(message) self.cause = cause def __str__(self): ret = "%s(%s)" % (self.__class__, self.message) if self.cause: ret += " (caused by %r)" % (self.cause,) return ret class CInvalidFileTypeError(CStora...
__init__
identifier_name
cexceptions.py
# -*- coding: utf-8 -*- # # Copyright (c) 2014 Netheos (http://www.netheos.net) # # 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 req...
"""Raised when performing an operation on a folder when a blob is expected, or when operating on a blob and a folder is expected. Also raised when downloading provider special files (eg google drive native docs).""" def __init__(self, c_path, expected_blob, message=None): """:param c_path: the ...
class CInvalidFileTypeError(CStorageError):
random_line_split
s3.js
import("crypto"); jimport("com.amazonaws.services.s3.model.CannedAccessControlList"); jimport("com.amazonaws.services.s3.model.GeneratePresignedUrlRequest"); jimport("org.apache.commons.codec.binary.Hex"); jimport("java.io.ByteArrayInputStream"); jimport("java.io.ByteArrayOutputStream"); S3 = null; function _init()...
(n) { return n < 10 ? '0' + n.toString() : n.toString() } var utcDateStr = pad(expirationDate.getUTCFullYear()) + pad(expirationDate.getUTCMonth() + 1) + pad(expirationDate.getUTCDate()); var s3Policy = crypto.convertToBase64(JSON.stringify( _getS3Policy(domain, localPadId, userId, expirationDate...
pad
identifier_name
s3.js
import("crypto"); jimport("com.amazonaws.services.s3.model.CannedAccessControlList"); jimport("com.amazonaws.services.s3.model.GeneratePresignedUrlRequest"); jimport("org.apache.commons.codec.binary.Hex"); jimport("java.io.ByteArrayInputStream"); jimport("java.io.ByteArrayOutputStream"); S3 = null; function _init()...
function getBucketName(bucketName) { if (appjet.config["s3." + bucketName]) { return appjet.config["s3." + bucketName]; } return bucketName; } function list(bucketName) { _init(); return S3.listObjects(getBucketName(bucketName)).getObjectSummaries().toArray(); } function put(bucketName, keyName, bytes...
{ if (S3 == null) { S3 = new com.amazonaws.services.s3.AmazonS3Client( new com.amazonaws.auth.BasicAWSCredentials( appjet.config.awsUser, appjet.config.awsPass)); } }
identifier_body
s3.js
import("crypto"); jimport("com.amazonaws.services.s3.model.CannedAccessControlList"); jimport("com.amazonaws.services.s3.model.GeneratePresignedUrlRequest"); jimport("org.apache.commons.codec.binary.Hex"); jimport("java.io.ByteArrayInputStream"); jimport("java.io.ByteArrayOutputStream"); S3 = null; function _init()...
} function getURL(bucketName, keyName, useHTTP) { return (useHTTP?"http":"https") + "://s3.amazonaws.com/" + getBucketName(bucketName) + "/" + keyName; } function getPresignedURL(bucketName, keyName, durationValidMs) { var expiration = new java.util.Date(); expiration.setTime(expiration.getTime() + durationVal...
{ S3.setObjectAcl(getBucketName(bucketName), keyName, CannedAccessControlList.PublicRead); }
conditional_block
s3.js
import("crypto"); jimport("com.amazonaws.services.s3.model.CannedAccessControlList"); jimport("com.amazonaws.services.s3.model.GeneratePresignedUrlRequest"); jimport("org.apache.commons.codec.binary.Hex"); jimport("java.io.ByteArrayInputStream"); jimport("java.io.ByteArrayOutputStream"); S3 = null; function _init() ...
/** * This signature allows the user to upload a file to the bucket that begins with a specific * key (domain_localPadId_userId_), enforces only image uploads up to a max size of 20MB. */ function _getS3Policy(domain, localPadId, userId, expirationDate, utcDateStr) { var isoDate = expirationDate.toISOString(); ...
var AWS_REQUEST = 'aws4_request';
random_line_split
test_crossdomain.py
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com> # # 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 applicabl...
(self): url = self.account_client._get_base_version_url() + "crossdomain.xml" resp, body = self.account_client.raw_request(url, "GET") self.account_client._error_checker(resp, body) body = body.decode() self.assertTrue(body.startswith(self.xml_start) and ...
test_get_crossdomain_policy
identifier_name
test_crossdomain.py
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com> # # 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 applicabl...
url = self.account_client._get_base_version_url() + "crossdomain.xml" resp, body = self.account_client.raw_request(url, "GET") self.account_client._error_checker(resp, body) body = body.decode() self.assertTrue(body.startswith(self.xml_start) and body.endswith(se...
identifier_body
test_crossdomain.py
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com> # # 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 applicabl...
self.assertIn('content-length', resp) self.assertIn('content-type', resp) self.assertIn('x-trans-id', resp) self.assertIn('date', resp) # Check only the format of common headers with custom matcher self.assertThat(resp, custom_matchers.AreAllWellFormatted())
# existence of response header is checked without a custom matcher.
random_line_split
data_types.py
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Various custom data types for use throughout the unexpected pass finder.""" from __future__ import print_function import collections import copy import f...
"""Typed map for string types -> ExpectationBuilderMap. This results in a dict in the following format: { expectation_file1 (str): { expectation1 (data_types.Expectation): { builder_name1 (str): { step_name1 (str): stats1 (data_types.BuildStats), step_name2 (str): stats2 (da...
random_line_split
data_types.py
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Various custom data types for use throughout the unexpected pass finder.""" from __future__ import print_function import collections import copy import f...
(self, grouped_results, builder, expectation_files): """Adds all results in |grouped_results| to |self|. Args: grouped_results: A dict mapping test name (str) to a list of data_types.Result objects for that test. builder: A string containing the name of the builder |grouped_results| ...
_AddGroupedResults
identifier_name
data_types.py
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Various custom data types for use throughout the unexpected pass finder.""" from __future__ import print_function import collections import copy import f...
def Merge(self, other_map, reference_map=None): """Merges |other_map| into self. Args: other_map: A BaseTypedMap whose contents will be merged into self. reference_map: A dict containing the information that was originally in self. Used for ensuring that a single expectation/builder/s...
for k, v in self.items(): for nested_value in v.IterToValueType(value_type): yield (k, ) + nested_value
conditional_block
data_types.py
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Various custom data types for use throughout the unexpected pass finder.""" from __future__ import print_function import collections import copy import f...
def IterBuilderStepMaps(self): """Iterates over all BuilderStepMaps contained in the map. Returns: A generator yielding tuples in the form (expectation_file (str), expectation (Expectation), builder_map (BuilderStepMap)) """ return self.IterToValueType(BuilderStepMap) def AddResultLi...
return ExpectationBuilderMap
identifier_body
MediaMetadata.ts
import _ from 'lodash'; MediaMetadata.$inject = ['userList', 'archiveService', 'metadata']; export function MediaMetadata(userList, archiveService, metadata) { return { scope: { item: '=', }, templateUrl: 'scripts/apps/archive/views/metadata-view.html', link: function(s...
}, }; }
random_line_split
MediaMetadata.ts
import _ from 'lodash'; MediaMetadata.$inject = ['userList', 'archiveService', 'metadata']; export function MediaMetadata(userList, archiveService, metadata) { return { scope: { item: '=', }, templateUrl: 'scripts/apps/archive/views/metadata-view.html', link: function(s...
() { var qcodes = []; metadata.getFilteredCustomVocabularies(qcodes).then((cvs) => { scope.cvs = _.sortBy(cvs, 'priority'); scope.genreInCvs = _.map(cvs, 'schema_field').indexOf('genre') !== -1; scope.placeInCvs = _.map(cvs, 's...
reloadData
identifier_name
MediaMetadata.ts
import _ from 'lodash'; MediaMetadata.$inject = ['userList', 'archiveService', 'metadata']; export function MediaMetadata(userList, archiveService, metadata) { return { scope: { item: '=', }, templateUrl: 'scripts/apps/archive/views/metadata-view.html', link: function(s...
scope.getLocaleName = function(terms, scheme) { const term = terms.find((element) => element.scheme === scheme); if (!term) { return 'None'; } if (term.translations && scope.item.language && term.tran...
{ var qcodes = []; metadata.getFilteredCustomVocabularies(qcodes).then((cvs) => { scope.cvs = _.sortBy(cvs, 'priority'); scope.genreInCvs = _.map(cvs, 'schema_field').indexOf('genre') !== -1; scope.placeInCvs = _.map(cvs, 'sche...
identifier_body
MediaMetadata.ts
import _ from 'lodash'; MediaMetadata.$inject = ['userList', 'archiveService', 'metadata']; export function MediaMetadata(userList, archiveService, metadata) { return { scope: { item: '=', }, templateUrl: 'scripts/apps/archive/views/metadata-view.html', link: function(s...
return term.name; }; }, }; }
{ return term.translations.name[scope.item.language]; }
conditional_block
index.js
/** * CORS middleware for koa2 * * @param {Object} [options] * - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is request Origin header * - {Array} exposeHeaders `Access-Control-Expose-Headers` * - {String|Number} maxAge `Access-Control-Max-Age` in seconds * - {Boolean} credentials `Ac...
ctx.remove('Access-Control-Allow-Credentials'); } else { ctx.set('Access-Control-Allow-Credentials', 'true'); } } // Access-Control-Expose-Headers if (options.exposeHeaders) { ctx.set('Access-Control-Expose-Headers', options.exposeHeaders.join(',')); ...
// Access-Control-Allow-Credentials if (options.credentials === true) { if (origin === '*') { // `credentials` can't be true when the `origin` is set to `*`
random_line_split
index.js
/** * CORS middleware for koa2 * * @param {Object} [options] * - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is request Origin header * - {Array} exposeHeaders `Access-Control-Expose-Headers` * - {String|Number} maxAge `Access-Control-Max-Age` in seconds * - {Boolean} credentials `Ac...
if (!origin) { return await next(); } // Access-Control-Allow-Origin ctx.set('Access-Control-Allow-Origin', origin); if (ctx.method === 'OPTIONS') { // Preflight Request if (!ctx.get('Access-Control-Request-Method')) { return await next(); } // Access-Contro...
{ origin = options.origin || ctx.get('Origin') || '*'; }
conditional_block
builder.rs
// Copyright 2019 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
nonterm.builder_into(), ))); self } pub fn add_named_nonterm( &mut self, name: impl BuilderInto<Name>, nonterm: impl BuilderInto<E::NonTerm>, ) -> &mut Self { self.elems.push(ProdElement::new_with_name( name.builder_into(), Elem::NonTerm(nonterm.builder_into()), ...
nonterm: impl BuilderInto<E::NonTerm>, ) -> &mut Self { self .elems .push(ProdElement::new_empty(Elem::NonTerm(
random_line_split
builder.rs
// Copyright 2019 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
} // ---------------- pub struct GrammarBuilder<E: ElemTypes> { start: E::NonTerm, rules: Vec<RuleInner<E>>, action_map: BTreeMap<E::ActionKey, E::ActionValue>, } impl<E: ElemTypes> GrammarBuilder<E> { fn new(start: E::NonTerm) -> Self { GrammarBuilder { start, rules: Vec::new(), actio...
{ let action_key = action_key.builder_into(); self .action_map .insert(action_key.clone(), action_value.builder_into()); self.prods.push(ProdInner { action_key, elements: elems.builder_into(), }); self }
identifier_body
builder.rs
// Copyright 2019 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
( &mut self, action_key: impl BuilderInto<E::ActionKey>, action_value: impl BuilderInto<E::ActionValue>, elems: impl BuilderInto<Vec<ProdElement<E>>>, ) -> &mut Self { let action_key = action_key.builder_into(); self .action_map .insert(action_key.clone(), action_value.builder_into...
add_prod_with_elems
identifier_name
module.ts
import { PostgresDatasource } from './datasource'; import { PostgresQueryCtrl } from './query_ctrl'; import { PostgresConfigCtrl } from './config_ctrl'; import { PostgresQuery } from './types'; import { DataSourcePlugin } from '@grafana/data'; const defaultQuery = `SELECT extract(epoch from time_column) AS time, t...
this.annotation.rawQuery = this.annotation.rawQuery || defaultQuery; } } export const plugin = new DataSourcePlugin<PostgresDatasource, PostgresQuery>(PostgresDatasource) .setQueryCtrl(PostgresQueryCtrl) .setConfigCtrl(PostgresConfigCtrl) .setAnnotationQueryCtrl(PostgresAnnotationsQueryCtrl);
/** @ngInject */ constructor($scope: any) { this.annotation = $scope.ctrl.annotation;
random_line_split
module.ts
import { PostgresDatasource } from './datasource'; import { PostgresQueryCtrl } from './query_ctrl'; import { PostgresConfigCtrl } from './config_ctrl'; import { PostgresQuery } from './types'; import { DataSourcePlugin } from '@grafana/data'; const defaultQuery = `SELECT extract(epoch from time_column) AS time, t...
($scope: any) { this.annotation = $scope.ctrl.annotation; this.annotation.rawQuery = this.annotation.rawQuery || defaultQuery; } } export const plugin = new DataSourcePlugin<PostgresDatasource, PostgresQuery>(PostgresDatasource) .setQueryCtrl(PostgresQueryCtrl) .setConfigCtrl(PostgresConfigCtrl) .setAn...
constructor
identifier_name
qidian_ranking.py
#!/usr/bin/env python import time from talonspider import Spider, Item, TextField, AttrField from talonspider.utils import get_random_user_agent import os os.environ['MODE'] = 'PRO' from owllook.database.mongodb import MotorBase from owllook.utils.tools import async_callback class RankingItem(Item): target_item ...
(Item): top_name = TextField(css_select='h4>a') other_name = TextField(css_select='a.name') class QidianRankingSpider(Spider): start_urls = ["http://r.qidian.com/?chn=" + str(url) for url in [-1, 21, 1, 2, 22, 4, 15, 6, 5, 7, 8, 9, 10, 12]] headers = { "User-Agent": get_random_user_agent() ...
NameItem
identifier_name
qidian_ranking.py
#!/usr/bin/env python import time from talonspider import Spider, Item, TextField, AttrField from talonspider.utils import get_random_user_agent import os os.environ['MODE'] = 'PRO' from owllook.database.mongodb import MotorBase from owllook.utils.tools import async_callback class RankingItem(Item): target_item ...
class QidianRankingSpider(Spider): start_urls = ["http://r.qidian.com/?chn=" + str(url) for url in [-1, 21, 1, 2, 22, 4, 15, 6, 5, 7, 8, 9, 10, 12]] headers = { "User-Agent": get_random_user_agent() } set_mul = True qidian_type = { '-1': '全部类别', '21': '玄幻', '1': '奇...
top_name = TextField(css_select='h4>a') other_name = TextField(css_select='a.name')
identifier_body
qidian_ranking.py
#!/usr/bin/env python import time from talonspider import Spider, Item, TextField, AttrField from talonspider.utils import get_random_user_agent import os os.environ['MODE'] = 'PRO' from owllook.database.mongodb import MotorBase from owllook.utils.tools import async_callback class RankingItem(Item): target_item ...
res_dic['data'] = result res_dic['target_url'] = res.url res_dic['type'] = self.qidian_type.get(res.url.split('=')[-1]) res_dic['spider'] = "qidian" async_callback(self.save, res_dic=res_dic) async def save(self, **kwargs): # 存进数据库 res_dic = kwargs.get('res_d...
} result.append(data)
random_line_split
qidian_ranking.py
#!/usr/bin/env python import time from talonspider import Spider, Item, TextField, AttrField from talonspider.utils import get_random_user_agent import os os.environ['MODE'] = 'PRO' from owllook.database.mongodb import MotorBase from owllook.utils.tools import async_callback class RankingItem(Item): target_item ...
s_dic['type'] = self.qidian_type.get(res.url.split('=')[-1]) res_dic['spider'] = "qidian" async_callback(self.save, res_dic=res_dic) async def save(self, **kwargs): # 存进数据库 res_dic = kwargs.get('res_dic') try: motor_db = MotorBase().db await motor_db....
index, value in enumerate(item.book_list[:10]): item_data = NameItem.get_item(html_etree=value) name = item_data.get('top_name') or item_data.get('other_name') each_book_list.append({ 'num': index + 1, 'name': name }...
conditional_block
utils.rs
use snafu::{ResultExt, Snafu}; use std::path::{Path, PathBuf}; use tokio::fs; use tokio::io::AsyncWriteExt; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { #[snafu(display("Invalid Download URL: {} ({})", source, details))] InvalidUrl { details: String, source: url::Pa...
let mut resp = reqwest::get(url) .await .context(DownloadSnafu { details: format!("could not download url {}", url), })? .error_for_status() .context(DownloadSnafu { details: format!("download response error for {}", url), })?; while let ...
.context(InvalidIOSnafu { details: format!("could no create file for download {}", path.display()), })? });
random_line_split
utils.rs
use snafu::{ResultExt, Snafu}; use std::path::{Path, PathBuf}; use tokio::fs; use tokio::io::AsyncWriteExt; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { #[snafu(display("Invalid Download URL: {} ({})", source, details))] InvalidUrl { details: String, source: url::Pa...
Ok(()) } pub async fn create_dir_if_not_exists_rec(path: &Path) -> Result<(), Error> { let mut head = PathBuf::new(); for fragment in path { head.push(fragment); create_dir_if_not_exists(&head).await?; } Ok(()) } /// Downloads the file identified by the url and saves it to the ...
{ fs::create_dir(path).await.context(InvalidIOSnafu { details: format!("could no create directory {}", path.display()), })?; }
conditional_block
utils.rs
use snafu::{ResultExt, Snafu}; use std::path::{Path, PathBuf}; use tokio::fs; use tokio::io::AsyncWriteExt; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { #[snafu(display("Invalid Download URL: {} ({})", source, details))] InvalidUrl { details: String, source: url::Pa...
(path: &Path, url: &str) -> Result<(), Error> { let mut file = tokio::io::BufWriter::new({ fs::OpenOptions::new() .append(true) .create(true) .open(&path) .await .context(InvalidIOSnafu { details: format!("could no create file for d...
download_to_file
identifier_name
cluster.py
# -*- coding: utf-8 -*- """ 聚类和EM算法 ~~~~~~~~~~~~~~~~ 聚类 :copyright: (c) 2016 by the huaxz1986. :license: lgpl-3.0, see LICENSE for more details. """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_blobs # from .agglomerative_clustering impor...
labels=np.unique(labels_true) fig=plt.figure() ax=fig.add_subplot(1,1,1) colors='rgbyckm' # 每个簇的样本标记不同的颜色 for i,label in enumerate(labels): position=labels_true==label ax.scatter(X[position,0],X[position,1],label="cluster %d"%label, color=colors[i%len(colors)]) ax.legend(loc="...
''' X,labels_true=data
random_line_split
cluster.py
# -*- coding: utf-8 -*- """ 聚类和EM算法 ~~~~~~~~~~~~~~~~ 聚类 :copyright: (c) 2016 by the huaxz1986. :license: lgpl-3.0, see LICENSE for more details. """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_blobs # from .agglomerative_clustering impor...
test_DBSCAN(X,labels_true) # 调用 test_DBSCAN 函数 # test_DBSCAN_epsilon(X,labels_true) # 调用 test_DBSCAN_epsilon 函数 # test_DBSCAN_min_samples(X,labels_true) # 调用 test_DBSCAN_min_samples 函数 # test_AgglomerativeClustering(X,labels_true) # 调用 test_AgglomerativeClustering 函数 # test_AgglomerativeClustering_n...
conditional_block
cluster.py
# -*- coding: utf-8 -*- """ 聚类和EM算法 ~~~~~~~~~~~~~~~~ 聚类 :copyright: (c) 2016 by the huaxz1986. :license: lgpl-3.0, see LICENSE for more details. """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_blobs # from .agglomerative_clustering impor...
调用 test_Kmeans_n_init 函数 # test_DBSCAN(X,labels_true) # 调用 test_DBSCAN 函数 # test_DBSCAN_epsilon(X,labels_true) # 调用 test_DBSCAN_epsilon 函数 # test_DBSCAN_min_samples(X,labels_true) # 调用 test_DBSCAN_min_samples 函数 # test_AgglomerativeClustering(X,labels_true) # 调用 test_AgglomerativeClustering 函数 #...
1) colors='rgbyckm' # 每个簇的样本标记不同的颜色 for i,label in enumerate(labels): position=labels_true==label ax.scatter(X[position,0],X[position,1],label="cluster %d"%label, color=colors[i%len(colors)]) ax.legend(loc="best",framealpha=0.5) ax.set_xlabel("X[0]") ax.set_ylabel("Y[1]") ax.s...
identifier_body
cluster.py
# -*- coding: utf-8 -*- """ 聚类和EM算法 ~~~~~~~~~~~~~~~~ 聚类 :copyright: (c) 2016 by the huaxz1986. :license: lgpl-3.0, see LICENSE for more details. """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_blobs # from .agglomerative_clustering impor...
_subplot(1,1,1) colors='rgbyckm' # 每个簇的样本标记不同的颜色 for i,label in enumerate(labels): position=labels_true==label ax.scatter(X[position,0],X[position,1],label="cluster %d"%label, color=colors[i%len(colors)]) ax.legend(loc="best",framealpha=0.5) ax.set_xlabel("X[0]") ax.set_ylabel("Y[...
x=fig.add
identifier_name
sr.js
/*
For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'colorbutton', 'sr', { auto: 'Аутоматски', bgColorTitle: 'Боја позадине', colors: { '000': 'Black', '800000': 'Maroon', '8B4513': 'Saddle Brown', '2F4F4F': 'Dark Slate Gray', '008080': 'Teal', '000080': '...
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
random_line_split
capture-clauses-boxed-closures.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let mut sum = 0u; let elems = [ 1u, 2, 3, 4, 5 ]; each(elems, |val| sum += *val); assert_eq!(sum, 15); }
main
identifier_name
capture-clauses-boxed-closures.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { let mut sum = 0u; let elems = [ 1u, 2, 3, 4, 5 ]; each(elems, |val| sum += *val); assert_eq!(sum, 15); }
{ for val in x.iter() { f(val) } }
identifier_body
capture-clauses-boxed-closures.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { let mut sum = 0u; let elems = [ 1u, 2, 3, 4, 5 ]; each(elems, |val| sum += *val); assert_eq!(sum, 15); }
random_line_split
ComputerPanel.js
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distribut...
boxSizing: 'border-box', objectFit: 'contain', overflow: 'hidden' } })
height: '100%', maxHeight: '250px',
random_line_split
ComputerPanel.js
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distribut...
() { if (preview.isLoading) { return ( <div aria-live="polite"> <Text color="secondary">{formatMessage('Generating preview...')}</Text> </div> ) } else if (preview.error) { return ( <div className={css(styles.previewContainer)} aria-live="polite"> <T...
renderPreview
identifier_name
ComputerPanel.js
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distribut...
setFile(file) setHasUploadedFile(true) }} onDropRejected={() => { setMessages( messages.concat({ text: formatMessage('Invalid file type'), type: 'error' }) ) }} messages={messages} label=...
{ setMessages([]) }
conditional_block
ComputerPanel.js
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distribut...
ComputerPanel.propTypes = { theFile: instanceOf(File), setFile: func.isRequired, hasUploadedFile: bool, setHasUploadedFile: func.isRequired, accept: oneOfType([string, arrayOf(string)]), label: string.isRequired } export const styles = StyleSheet.create({ previewContainer: { maxHeight: '250px', ...
{ const [messages, setMessages] = useState([]) const [preview, setPreview] = useState({preview: null, isLoading: false}) useEffect(() => { if (!theFile || preview.isLoading || preview.preview || preview.error) return async function getPreview() { setPreview({preview: null, isLoading: true}) ...
identifier_body
no-capture-arc.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// <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. // error-pattern: use of moved value extern mod extra; use extra::arc; use std::task; fn main() { let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let...
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
no-capture-arc.rs
// Copyright 2012-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-MI...
{ let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let arc_v = arc::Arc::new(v); do task::spawn() { let v = arc_v.get(); assert_eq!(v[3], 4); }; assert_eq!((arc_v.get())[2], 3); info2!("{:?}", arc_v); }
identifier_body
no-capture-arc.rs
// Copyright 2012-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-MI...
() { let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let arc_v = arc::Arc::new(v); do task::spawn() { let v = arc_v.get(); assert_eq!(v[3], 4); }; assert_eq!((arc_v.get())[2], 3); info2!("{:?}", arc_v); }
main
identifier_name