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 |
|---|---|---|---|---|
app.editadmin.ts | import {Component, NgModule, ViewChild, ViewContainerRef, ViewEncapsulation, OnDestroy, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from "@angular/forms/src/directives";
//import {FORM_DIRECTIVES, REACTI... | phone: [this.admindetails.phone, Validators.required],
zip: [this.admindetails.zip, Validators.required],
is_active: [this.admindetails.is_active]
});
}, error => {
console.log("Oooops!");
... | email: [this.admindetails.email, AppEditadmin.validateEmail],
address: [this.admindetails.address, Validators.required],
city: [this.admindetails.city, Validators.required],
state: [this.admindetails.state, Validators.requir... | random_line_split |
cbx-2to3.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Data filter converting CSTBox v2 event logs to v3 format.
Usage: ./cbx-2to3.py < /path/to/input/file > /path/to/output/file
"""
__author__ = 'Eric Pascual - CSTB (eric.pascual@cstb.fr)'
import fileinput
import json
for line in fileinput.input():
ts, var_type, v... | else:
data = "{}"
print('\t'.join((ts, var_type, var_name, value, data))) | data = json.dumps(dict([(k.lower(), v) for k, v in (pair.split('=') for pair in pairs)])) | random_line_split |
cbx-2to3.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Data filter converting CSTBox v2 event logs to v3 format.
Usage: ./cbx-2to3.py < /path/to/input/file > /path/to/output/file
"""
__author__ = 'Eric Pascual - CSTB (eric.pascual@cstb.fr)'
import fileinput
import json
for line in fileinput.input():
ts, var_type, v... | var_name = '.'.join((var_type, var_name))
data = data.strip().strip('{}')
if data:
pairs = data.split(',')
data = json.dumps(dict([(k.lower(), v) for k, v in (pair.split('=') for pair in pairs)]))
else:
data = "{}"
print('\t'.join((ts, var_type, var_name, value, data)))
| ar_name = var_name[5:]
| conditional_block |
load.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... | self.reader.read_plugin_metadata(vi);
self.plugins.macros.push(ExportedMacros {
crate_name: name,
macros: macros,
});
match (lib, registrar_symbol) {
(Some(lib), Some(symbol))
... | {
match vi.node {
ast::ViewItemExternCrate(name, _, _) => {
let mut plugin_phase = false;
for attr in vi.attrs.iter().filter(|a| a.check_name("phase")) {
let phases = attr.meta_item_list().unwrap_or(&[]);
if attr::contains_name... | identifier_body |
load.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... |
return plugins;
}
// note that macros aren't expanded yet, and therefore macros can't add plugins.
impl<'a, 'v> Visitor<'v> for PluginLoader<'a> {
fn visit_view_item(&mut self, vi: &ast::ViewItem) {
match vi.node {
ast::ViewItemExternCrate(name, _, _) => {
let mut plugin_ph... | }
None => ()
} | random_line_split |
load.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... | {
/// Source code of macros exported by the crate.
pub macros: Vec<String>,
/// Path to the shared library file.
pub lib: Option<Path>,
/// Symbol name of the plugin registrar function.
pub registrar_symbol: Option<String>,
}
/// Pointer to a registrar function.
pub type PluginRegistrarFun =
... | PluginMetadata | identifier_name |
io.rs | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may no... | (b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 0)
}
#[bench]
fn bench_seekable_mem_writer_001_0010(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 10)
}
#[bench]
fn bench_seekable_mem_writer_001_0100(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 10... | bench_seekable_mem_writer_001_0000 | identifier_name |
io.rs | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may no... | // currently are
let difference = self.pos as i64 - self.buf.len() as i64;
if difference > 0 {
self.buf.extend(repeat(0).take(difference as uint));
}
// Figure out what bytes will be used to overwrite what's currently
// there (lef... | random_line_split | |
io.rs | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not b... |
#[bench]
fn bench_seekable_mem_writer_001_0000(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 0)
}
#[bench]
fn bench_seekable_mem_writer_001_0010(b: &mut Bencher) {
do_bench_seekable_mem_writer(b, 1, 10)
}
#[bench]
fn bench_seekable_mem_writer_001_0100(b: &mut ... | {
let src: Vec<u8> = repeat(5).take(len).collect();
b.bytes = (times * len) as u64;
b.iter(|| {
let mut wr = SeekableMemWriter::new();
for _ in 0..times {
wr.write(&src).unwrap();
}
let v = wr.unwrap();
assert_eq!(v.le... | identifier_body |
io.rs | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not b... |
// Figure out what bytes will be used to overwrite what's currently
// there (left), and what will be appended on the end (right)
let cap = self.buf.len() - self.pos;
let (left, right) = if cap <= buf.len() {
(&buf[..cap], &buf[cap..])
} else... | {
self.buf.extend(repeat(0).take(difference as uint));
} | conditional_block |
PdfInfo.py | import subprocess
"""
ideas from https://gist.github.com/godber/7692812
"""
class PdfInfo:
| return row.split(':', 1)[1].strip()
def getPages(self):
return int(self.info['Pages'])
def getFileSizeInBytes(self):
return int(self.info['File size'][:-5].strip())
| def __init__(self, filepath):
self.filepath = filepath
self.info = {}
self.cmd = "pdfinfo"
self.process()
def process(self):
labels = ['Title', 'Author', 'Creator', 'Producer', 'CreationDate', \
'ModDate', 'Tagged', 'Pages', 'Encrypted', 'Page size', \
... | identifier_body |
PdfInfo.py | import subprocess
"""
ideas from https://gist.github.com/godber/7692812
"""
class PdfInfo:
def __init__(self, filepath):
self.filepath = filepath
self.info = {}
self.cmd = "pdfinfo"
self.process()
def process(self):
labels = ['Title', 'Author', 'Creator', 'Producer', '... |
def isEncrypted(self):
return False if (self.info['Encrypted'][:2]=="no") else True
def extract(self, row):
return row.split(':', 1)[1].strip()
def getPages(self):
return int(self.info['Pages'])
def getFileSizeInBytes(self):
return int(self.info['File size'][:-5]... | for label in labels:
if label in line:
self.info[label] = self.extract(line) | conditional_block |
PdfInfo.py | import subprocess
"""
ideas from https://gist.github.com/godber/7692812
"""
class PdfInfo:
def __init__(self, filepath):
self.filepath = filepath
self.info = {}
self.cmd = "pdfinfo"
self.process()
def process(self):
labels = ['Title', 'Author', 'Creator', 'Producer', '... | if label in line:
self.info[label] = self.extract(line)
def isEncrypted(self):
return False if (self.info['Encrypted'][:2]=="no") else True
def extract(self, row):
return row.split(':', 1)[1].strip()
def getPages(self):
return int(self.info[... | cmdOutput = subprocess.check_output([self.cmd, self.filepath])
for line in cmdOutput.splitlines():
for label in labels: | random_line_split |
PdfInfo.py | import subprocess
"""
ideas from https://gist.github.com/godber/7692812
"""
class PdfInfo:
def __init__(self, filepath):
self.filepath = filepath
self.info = {}
self.cmd = "pdfinfo"
self.process()
def process(self):
labels = ['Title', 'Author', 'Creator', 'Producer', '... | (self):
return int(self.info['Pages'])
def getFileSizeInBytes(self):
return int(self.info['File size'][:-5].strip())
| getPages | identifier_name |
index.d.ts | /// <reference types="node" />
export interface Header {
'Content-Type'?: string
'Content-Encoding'?: string
}
export type extensions = 'png' | 'pbf' | 'jpg' | 'webp'
/**
* Given a buffer of unknown data, return either a format as an extension
* string or false if the type cannot be determined.
*
* Potential... | export function dimensions(buffer: Buffer): [number, number] | boolean | * @returns {Array<number>|boolean} dimensions
*/ | random_line_split |
LogicalAnd.ts | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0 | * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.... | * | random_line_split |
gulpfile.js | var browserSync = require('browser-sync');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
// 静态服务器
gulp.task('browser-sync', function() {
browserSync.init({
files: "src/**",
server: {
baseDir: "sr... | var gulp = require('gulp'); | random_line_split | |
expr-block-generic-box1.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 ... | <T>(expected: @T, eq: compare<T>) {
let actual: @T = { expected };
assert!((eq(expected, actual)));
}
fn test_box() {
fn compare_box(b1: @bool, b2: @bool) -> bool {
info!("{}", *b1);
info!("{}", *b2);
return *b1 == *b2;
}
test_generic::<bool>(@true, compare_box);
}
pub fn m... | test_generic | identifier_name |
expr-block-generic-box1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // <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.
#[feature(managed_boxes)];
type compare<T> = 'static |@T, @T| -> bool;
fn test_generic<T>(expected: @T, eq: compare<T>) {
let actual: @T = { expecte... | // 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 | random_line_split |
expr-block-generic-box1.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 ... |
fn test_box() {
fn compare_box(b1: @bool, b2: @bool) -> bool {
info!("{}", *b1);
info!("{}", *b2);
return *b1 == *b2;
}
test_generic::<bool>(@true, compare_box);
}
pub fn main() { test_box(); }
| {
let actual: @T = { expected };
assert!((eq(expected, actual)));
} | identifier_body |
submission.effects.ts | import 'rxjs/add/operator/mergeMap';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Action } from '@ngrx/store'
import { Effect, Actions } from '@ngrx/effects';
import {
ActionTypes,
loadSubmissionsSuccess,
createSubmission,
createSubmissionSuccess,
updateSu... |
@Effect() createSubmission$ = this.actions$
.ofType(ActionTypes.CREATE_SUBMISSION)
.mergeMap(action => this.submissionService.createSubmission(action.payload))
.mergeMap(sub => this.submissionService.getSubmission(sub.id))
.map((sub:any) => createSubmissionSuccess(sub));
// Update the submission ... | { } | identifier_body |
submission.effects.ts | import 'rxjs/add/operator/mergeMap';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Action } from '@ngrx/store'
import { Effect, Actions } from '@ngrx/effects';
import {
ActionTypes,
loadSubmissionsSuccess,
createSubmission,
createSubmissionSuccess,
updateSu... | (
private actions$: Actions,
private submissionService:SubmissionService
) { }
@Effect() createSubmission$ = this.actions$
.ofType(ActionTypes.CREATE_SUBMISSION)
.mergeMap(action => this.submissionService.createSubmission(action.payload))
.mergeMap(sub => this.submissionService.getSubmission(su... | constructor | identifier_name |
submission.effects.ts | import 'rxjs/add/operator/mergeMap';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Action } from '@ngrx/store'
import { Effect, Actions } from '@ngrx/effects';
import {
ActionTypes,
loadSubmissionsSuccess,
createSubmission,
createSubmissionSuccess,
updateSu... |
@Effect() loadSubmissions$ = this.actions$
.ofType(ActionTypes.LOAD_SUBMISSIONS)
.mergeMap(() => this.submissionService.loadSubmissions())
// Dispatch action to load submission success
.map(submissions => loadSubmissionsSuccess(submissions))
@Effect({dispatch: false}) deleteSubmission$ = this.acti... | return updateSubmissionSuccess(submission)
}); | random_line_split |
daemonize.py | # -*- mode: python; coding: utf-8 -*-
#
# Copyright 2011 Andrej A Antonov <polymorphm@qmail.com>
#
# 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 the License, or
# (a... |
for fd in range(0, 3):
try:
os_close(fd)
except OSError:
pass
os_open(devnull, O_RDWR)
os_open(devnull, O_RDWR)
os_open(devnull, O_RDWR)
| exit(EX_OK) | conditional_block |
daemonize.py | # -*- mode: python; coding: utf-8 -*-
#
# Copyright 2011 Andrej A Antonov <polymorphm@qmail.com>
#
# 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 the License, or
# (a... | os_open(devnull, O_RDWR)
| from os import (
EX_OK,
devnull,
O_RDWR,
fork,
open as os_open,
close as os_close,
)
if fork():
exit(EX_OK)
for fd in range(0, 3):
try:
os_close(fd)
except OSError:
pass
os_open(devnull, O_RDWR... | identifier_body |
daemonize.py | # -*- mode: python; coding: utf-8 -*-
#
# Copyright 2011 Andrej A Antonov <polymorphm@qmail.com>
#
# 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 the License, or
# (a... | EX_OK,
devnull,
O_RDWR,
fork,
open as os_open,
close as os_close,
)
if fork():
exit(EX_OK)
for fd in range(0, 3):
try:
os_close(fd)
except OSError:
pass
os_open(devnull, O_RDWR)
os_open(dev... | assert unicode is not str
def daemonize():
from os import ( | random_line_split |
daemonize.py | # -*- mode: python; coding: utf-8 -*-
#
# Copyright 2011 Andrej A Antonov <polymorphm@qmail.com>
#
# 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 the License, or
# (a... | ():
from os import (
EX_OK,
devnull,
O_RDWR,
fork,
open as os_open,
close as os_close,
)
if fork():
exit(EX_OK)
for fd in range(0, 3):
try:
os_close(fd)
except OSError:
pass
os_open(devnull... | daemonize | identifier_name |
send_str_treemap.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut map: TreeMap<SendStr, uint> = TreeMap::new();
assert!(map.insert(Slice("foo"), 42));
assert!(!map.insert(Owned("foo".to_string()), 42));
assert!(!map.insert(Slice("foo"), 42));
assert!(!map.insert(Owned("foo".to_string()), 42));
assert!(!map.insert(Slice("foo"), 43));
assert!(!... | main | identifier_name |
send_str_treemap.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
assert!(!map.insert(Slice("abc"), a));
assert!(!map.insert(Owned("bcd".to_string()), b));
assert!(!map.insert(Slice("cde"), c));
assert!(!map.insert(Owned("def".to_string()), d));
assert!(!map.insert(Owned("abc".to_string()), a));
assert!(!map.insert(Slice("bcd"), b));
assert!(!map.insert(... |
assert!(map.insert(Slice("abc"), a));
assert!(map.insert(Owned("bcd".to_string()), b));
assert!(map.insert(Slice("cde"), c));
assert!(map.insert(Owned("def".to_string()), d)); | random_line_split |
send_str_treemap.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert!(map.insert(Owned("bcd".to_string()), b));
assert!(map.insert(Slice("cde"), c));
assert!(map.insert(Owned("def".to_string()), d));
assert!(!map.insert(Slice("abc"), a));
assert!(!map.insert(Owned("bcd".to_string()), b));
assert!(!map.insert(Slice("cde"), c));
assert!(!map.insert(Owne... | {
let mut map: TreeMap<SendStr, uint> = TreeMap::new();
assert!(map.insert(Slice("foo"), 42));
assert!(!map.insert(Owned("foo".to_string()), 42));
assert!(!map.insert(Slice("foo"), 42));
assert!(!map.insert(Owned("foo".to_string()), 42));
assert!(!map.insert(Slice("foo"), 43));
assert!(!map... | identifier_body |
api.py | import itertools
import json
import re
import flask
from flask import request
from web.cache import cache
import rethinkdb as r
import web.api.api_util as api_util
import db
import util
api = flask.Blueprint("api", __name__, url_prefix="/api")
r_conn = db.util.r_conn
def _should_skip_get_plugins_cache():
"""... |
else:
return api_util.api_not_found('No plugin with slug %s' % slug)
# TODO(david): Make it not so easy for an attacker to completely obliterate all
# of our tags, or at least be able to recover from it.
@api.route('/plugins/<slug>/tags', methods=['POST', 'PUT'])
def update_plugin_tags(slug):
dat... | return api_util.jsonify(db.plugins.to_json(plugin)) | conditional_block |
api.py | import itertools
import json
import re
import flask
from flask import request
from web.cache import cache
import rethinkdb as r
import web.api.api_util as api_util
import db
import util
api = flask.Blueprint("api", __name__, url_prefix="/api")
r_conn = db.util.r_conn
def _should_skip_get_plugins_cache():
"""... | (slug):
plugin = r.table('plugins').get(slug).run(r_conn())
if plugin:
return api_util.jsonify(db.plugins.to_json(plugin))
else:
return api_util.api_not_found('No plugin with slug %s' % slug)
# TODO(david): Make it not so easy for an attacker to completely obliterate all
# of our tags... | get_plugin | identifier_name |
api.py | import itertools
import json
import re
import flask
from flask import request
from web.cache import cache
import rethinkdb as r
import web.api.api_util as api_util
import db
import util
api = flask.Blueprint("api", __name__, url_prefix="/api")
r_conn = db.util.r_conn
def _should_skip_get_plugins_cache():
"""... |
def _apply_keyword_filters(results, tokens):
"""Filters results that match the given keywords (tokens).
Arguments:
results: List of search result plugins.
tokens: Keywords to filter results on.
Returns:
List of plugins that match the given keywords.
"""
if tokens:
... | """Consumes and applies tag filters (e.g. "tag:python") to search results.
Arguments:
results: List of search result plugins.
tokens: Remaining search text tokens that have not been consumed.
Returns:
(results, tokens): Results that match the given tag, and tokens
that have not... | identifier_body |
api.py | import itertools
import json
import re
import flask
from flask import request
from web.cache import cache
import rethinkdb as r
import web.api.api_util as api_util
import db
import util
api = flask.Blueprint("api", __name__, url_prefix="/api")
r_conn = db.util.r_conn
def _should_skip_get_plugins_cache():
"""... | tokens: Remaining search text tokens that have not been consumed.
Returns:
(results, tokens): Results that match the given category, and tokens
that have not been consumed.
"""
category_filter = lambda t: t.startswith('cat:')
category_tokens = filter(category_filter, tokens)
... | random_line_split | |
caret_jump.py | import sublime
import sublime_plugin
OPTIONS_LAST_REGEX = "jump_caret_last_regex"
class CaretJumpCommand(sublime_plugin.TextCommand):
def run(self, edit, jump=True, jump_to=None, repeat_previous_jump=False):
view = self.view
def get_next_sels(user_input):
new_sels = []
fo... |
selection = view.substr(view.sel()[0]) if view.sel() else ""
if jump_to:
select_next_regex(jump_to)
elif repeat_previous_jump:
jump_last_regex()
else:
default = selection if selection \
else self.view.settings().get(OPTIONS_LAST_REGE... | view.erase_regions("caret_jump_preview") | identifier_body |
caret_jump.py | import sublime
import sublime_plugin
OPTIONS_LAST_REGEX = "jump_caret_last_regex"
| def run(self, edit, jump=True, jump_to=None, repeat_previous_jump=False):
view = self.view
def get_next_sels(user_input):
new_sels = []
for sel in view.sel():
next_sel = view.find(user_input, sel.end(), sublime.IGNORECASE)
if next_sel.begin() ... |
class CaretJumpCommand(sublime_plugin.TextCommand): | random_line_split |
caret_jump.py | import sublime
import sublime_plugin
OPTIONS_LAST_REGEX = "jump_caret_last_regex"
class CaretJumpCommand(sublime_plugin.TextCommand):
def run(self, edit, jump=True, jump_to=None, repeat_previous_jump=False):
view = self.view
def get_next_sels(user_input):
new_sels = []
fo... | (user_input):
view.erase_regions("caret_jump_preview")
if not user_input:
# jump_last_regex()
return
self.view.settings().set(OPTIONS_LAST_REGEX, user_input)
new_sels = get_next_sels(user_input)
if jump and new_sels:
... | select_next_regex | identifier_name |
caret_jump.py | import sublime
import sublime_plugin
OPTIONS_LAST_REGEX = "jump_caret_last_regex"
class CaretJumpCommand(sublime_plugin.TextCommand):
def run(self, edit, jump=True, jump_to=None, repeat_previous_jump=False):
view = self.view
def get_next_sels(user_input):
new_sels = []
fo... |
view.sel().add_all(new_sels)
def input_changed(user_input):
new_sels = get_next_sels(user_input)
view.add_regions("caret_jump_preview",
new_sels,
"source, text",
"dot",
... | view.sel().clear() | conditional_block |
utils.js | var Utils = {
path: function(bucket, key) {
return bucket + '/' + (key ? key : '');
},
toQuery: function(query, riak) {
// use boolean strings since riak expects those
for (var k in query) {
if (typeof query[k] == 'boolean') {
query[k] = String(query[k]);
}
}
return r... | return val.toString();
}
return val;
});
},
ensure: function(obj) {
return obj || {};
},
isArray: function(o) {
return o && !(o.propertyIsEnumerable('length')) && typeof o === 'object' && typeof o.length === 'number';
},
// it always returns an array of phases, ev... | random_line_split | |
utils.js | var Utils = {
path: function(bucket, key) {
return bucket + '/' + (key ? key : '');
},
toQuery: function(query, riak) {
// use boolean strings since riak expects those
for (var k in query) {
if (typeof query[k] == 'boolean') {
query[k] = String(query[k]);
}
}
return r... | , d.value);
}
else {
target[k] = d.value;
}
}
}
});
}
}
// Return the modified object
return target;
}
}
// exports
module.exports = Utils | {
// Only deal with non-null/undefined values
if ( (source = arguments[i]) != null ) {
// Extend the base object
Object.getOwnPropertyNames(source).forEach(function(k){
var d = Object.getOwnPropertyDescriptor(source, k) || {value: source[k]};
if (d.get) {
targ... | conditional_block |
MLE1.py | ()
plt.plot(data0[:,0], np.ones(len(data0[:,0]))*0.0, '+r', label='Data 0 Class 0')
plt.plot(data1[:,0], np.ones(len(data1[:,0]))*0.1, '+g', label='Data 0 Class 1')
plt.plot(data2[:,0], np.ones(len(data2[:,0]))*0.2, '+b', label='Data 0 Class 2')
plt.plot(data0[:,1], np.ones(len(data0[:,1]))*1.0, 'xr', label='Data 1 Cl... |
cov0_self = np.array([[ cov_finder(data0[:,2], data0[:,2]), cov_finder(data0[:,2], data0[:,3]) ],
[ cov_finder(data0[:,3], data0[:,2]), cov_finder(data0[:,3], data0[:,3]) ]])
mx1_self = mean_find(data1[:,2])
my1_self = mean_find(data1[:,3])
cov1_self = np.array([[ cov_finder(data1[:,2], data1[... | """
Covariance matrix finding with formula E((x-mu(x)) * (y-mu(y)))
"""
if x.ndim is not 1:
return False
mean_x = mean_find(x)
mean_y = mean_find(y)
data = [ (x[j] - mean_x ) * ( y[j] - mean_y ) for j in range(len(x))]
return sum(data) / len(data) | identifier_body |
MLE1.py | ()
plt.plot(data0[:,0], np.ones(len(data0[:,0]))*0.0, '+r', label='Data 0 Class 0')
plt.plot(data1[:,0], np.ones(len(data1[:,0]))*0.1, '+g', label='Data 0 Class 1')
plt.plot(data2[:,0], np.ones(len(data2[:,0]))*0.2, '+b', label='Data 0 Class 2')
plt.plot(data0[:,1], np.ones(len(data0[:,1]))*1.0, 'xr', label='Data 1 Cl... | (x,y):
"""
Covariance matrix finding with formula E((x-mu(x)) * (y-mu(y)))
"""
if x.ndim is not 1:
return False
mean_x = mean_find(x)
mean_y = mean_find(y)
data = [ (x[j] - mean_x ) * ( y[j] - mean_y ) for j in range(len(x))]
return sum(data) / len(data)
cov0_self = np.arra... | cov_finder | identifier_name |
MLE1.py | 2.2, '.b', label='Data 2 Class 2')
plt.plot(data0[:,3], np.ones(len(data0[:,3]))*3.0, '1r', label='Data 3 Class 0')
plt.plot(data1[:,3], np.ones(len(data1[:,3]))*3.1, '1g', label='Data 3 Class 1')
plt.plot(data2[:,3], np.ones(len(data2[:,3]))*3.2, '1b', label='Data 3 Class 2')
plt.legend(fontsize=9, loc=3)
# Part 3:... | prop_t1 = gaussian_2d(each_data[2], each_data[3], mx0_train, my0_train, cov0_train)
prop_t2 = gaussian_2d(each_data[2], each_data[3], mx1_train, my1_train, cov1_train)
prop_t3 = gaussian_2d(each_data[2], each_data[3], mx2_train, my2_train, cov2_train)
if (prop_t1 > prop_t2) and (prop_t1 > prop_t3):
... | conditional_block | |
MLE1.py | .figure()
plt.plot(data0[:,0], np.ones(len(data0[:,0]))*0.0, '+r', label='Data 0 Class 0')
plt.plot(data1[:,0], np.ones(len(data1[:,0]))*0.1, '+g', label='Data 0 Class 1')
plt.plot(data2[:,0], np.ones(len(data2[:,0]))*0.2, '+b', label='Data 0 Class 2')
plt.plot(data0[:,1], np.ones(len(data0[:,1]))*1.0, 'xr', label='Da... | @cov'''
mx0_train = np.mean(data_train0[:,2])
my0_train = np.mean(data_train0[:,3])
mx1_train | ''' Second part of
homework.
Calculations :
@mean, | random_line_split |
test_parser.py | #! /usr/bin/env python
# (Force the script to use the latest build.)
#
# test_parser.py
import parser, traceback
_numFailed = 0
def | (t, fileName):
global _numFailed
print '----', fileName,
try:
ast = parser.suite(t)
tup = parser.ast2tuple(ast)
# this discards the first AST; a huge memory savings when running
# against a large source file like Tkinter.py.
ast = None
new = parser.tuple2ast(t... | testChunk | identifier_name |
test_parser.py | #! /usr/bin/env python
# (Force the script to use the latest build.)
#
# test_parser.py
import parser, traceback
_numFailed = 0
def testChunk(t, fileName):
| print 'o.k.'
def testFile(fileName):
t = open(fileName).read()
testChunk(t, fileName)
def test():
import sys
args = sys.argv[1:]
if not args:
import glob
args = glob.glob("*.py")
args.sort()
map(testFile, args)
sys.exit(_numFailed != 0)
if __name__ == ... | global _numFailed
print '----', fileName,
try:
ast = parser.suite(t)
tup = parser.ast2tuple(ast)
# this discards the first AST; a huge memory savings when running
# against a large source file like Tkinter.py.
ast = None
new = parser.tuple2ast(tup)
except pars... | identifier_body |
test_parser.py | #! /usr/bin/env python
# (Force the script to use the latest build.)
#
# test_parser.py
import parser, traceback
_numFailed = 0
def testChunk(t, fileName):
global _numFailed
print '----', fileName,
try:
ast = parser.suite(t)
tup = parser.ast2tuple(ast)
# this discards the first ... |
def test():
import sys
args = sys.argv[1:]
if not args:
import glob
args = glob.glob("*.py")
args.sort()
map(testFile, args)
sys.exit(_numFailed != 0)
if __name__ == '__main__':
test() | print 'o.k.'
def testFile(fileName):
t = open(fileName).read()
testChunk(t, fileName) | random_line_split |
test_parser.py | #! /usr/bin/env python
# (Force the script to use the latest build.)
#
# test_parser.py
import parser, traceback
_numFailed = 0
def testChunk(t, fileName):
global _numFailed
print '----', fileName,
try:
ast = parser.suite(t)
tup = parser.ast2tuple(ast)
# this discards the first ... | test() | conditional_block | |
ua_certificate_expiration_alarm.ts | /**
* @module node-opcua-address-space.AlarmsAndConditions
*/
import { DateTime } from "node-opcua-basic-types";
import { Certificate } from "node-opcua-crypto";
import { NodeId } from "node-opcua-nodeid";
import { DataType } from "node-opcua-variant";
import {
Duration,
Namespace,
UAVariableT,
} from ".... | namespace: Namespace,
options: any,
data: any
): UACertificateExpirationAlarm {
return UASystemOffNormalAlarm.instantiate(
namespace,
"CertificateExpirationAlarmType",
options, data) as UACertificateExpirationAlarm;
}
public getExpirationDate():... | stantiate(
| identifier_name |
ua_certificate_expiration_alarm.ts | /**
* @module node-opcua-address-space.AlarmsAndConditions
*/
import { DateTime } from "node-opcua-basic-types";
import { Certificate } from "node-opcua-crypto";
import { NodeId } from "node-opcua-nodeid";
import { DataType } from "node-opcua-variant";
import {
Duration,
Namespace,
UAVariableT,
} from ".... | expirationLimit?: UAVariableT<Duration, DataType.Double>;
// CertificateType – See Part 12 for definition of CertificateType.
// HasProperty Variable CertificateType NodeId PropertyType Mandatory
certificateType: UAVariableT<NodeId, DataType.NodeId>;
// Certificate is the certificate that is ... | // HasProperty Variable ExpirationLimit Duration PropertyType Optional | random_line_split |
setup.py | import subprocess
import sys
import setup_util
import os
def start(args, logfile, errfile):
try:
subprocess.check_call("mvn clean compile assembly:single", shell=True, cwd="netty", stderr=errfile, stdout=logfile)
subprocess.Popen("java -jar netty-example-0.1-jar-with-dependencies.jar".rsplit(" "), cwd="netty... |
return 0
| if 'netty-example' in line:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9) | conditional_block |
setup.py | import subprocess
import sys
import setup_util
import os
def start(args, logfile, errfile):
try:
subprocess.check_call("mvn clean compile assembly:single", shell=True, cwd="netty", stderr=errfile, stdout=logfile)
subprocess.Popen("java -jar netty-example-0.1-jar-with-dependencies.jar".rsplit(" "), cwd="netty... | if 'netty-example' in line:
pid = int(line.split(None, 2)[1])
os.kill(pid, 9)
return 0 | else:
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines(): | random_line_split |
setup.py | import subprocess
import sys
import setup_util
import os
def start(args, logfile, errfile):
try:
subprocess.check_call("mvn clean compile assembly:single", shell=True, cwd="netty", stderr=errfile, stdout=logfile)
subprocess.Popen("java -jar netty-example-0.1-jar-with-dependencies.jar".rsplit(" "), cwd="netty... | (logfile, errfile):
if os.name == 'nt':
subprocess.check_call("wmic process where \"CommandLine LIKE '%netty-example%'\" call terminate", stderr=errfile, stdout=logfile)
else:
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
i... | stop | identifier_name |
setup.py | import subprocess
import sys
import setup_util
import os
def start(args, logfile, errfile):
|
def stop(logfile, errfile):
if os.name == 'nt':
subprocess.check_call("wmic process where \"CommandLine LIKE '%netty-example%'\" call terminate", stderr=errfile, stdout=logfile)
else:
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines()... | try:
subprocess.check_call("mvn clean compile assembly:single", shell=True, cwd="netty", stderr=errfile, stdout=logfile)
subprocess.Popen("java -jar netty-example-0.1-jar-with-dependencies.jar".rsplit(" "), cwd="netty/target", stderr=errfile, stdout=logfile)
return 0
except subprocess.CalledProcessError:
... | identifier_body |
md5.rs |
fn reset(&mut self) {
self.s0 = 0x67452301;
self.s1 = 0xefcdab89;
self.s2 = 0x98badcfe;
self.s3 = 0x10325476;
}
fn process_block(&mut self, input: &[u8]) {
fn f(u: u32, v: u32, w: u32) -> u32 {
return (u & v) | (!u & w);
}
fn g(u: u32, ... | {
return Md5State {
s0: 0x67452301,
s1: 0xefcdab89,
s2: 0x98badcfe,
s3: 0x10325476
};
} | identifier_body | |
md5.rs | u32 {
return u ^ v ^ w;
}
fn i(u: u32, v: u32, w: u32) -> u32 {
return v ^ (u | !w);
}
fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 {
return (w + f(x, y, z) + m).rotate_left(s as uint) + x;
}
fn op_g(w: u32, x: u32... | () -> Md5 {
return Md5 {
length_bytes: 0,
buffer: FixedBuffer64::new(),
state: Md5State::new(),
finished: false
}
}
}
impl Digest for Md5 {
fn input(&mut self, input: &[u8]) {
assert!(!self.finished);
// Unlike Sha1 and Sha2, the l... | new | identifier_name |
md5.rs | 2) -> u32 {
return (w + h(x, y, z) + m).rotate_left(s as uint) + x;
}
fn op_i(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 {
return (w + i(x, y, z) + m).rotate_left(s as uint) + x;
}
let mut a = self.s0;
let mut b = self.s1;
let mut c =... | {
let self_state = &mut self.state;
self.buffer.standard_padding(8, |d: &[u8]| { self_state.process_block(d); });
write_u32_le(self.buffer.next(4), (self.length_bytes << 3) as u32);
write_u32_le(self.buffer.next(4), (self.length_bytes >> 29) as u32);
self_stat... | conditional_block | |
md5.rs | use digest::Digest;
// A structure that represents that state of a digest computation for the MD5 digest function
struct Md5State {
s0: u32,
s1: u32,
s2: u32,
s3: u32
}
impl Md5State {
fn new() -> Md5State {
return Md5State {
s0: 0x67452301,
s1: 0xefcdab89,
... |
use std::iter::range_step;
use cryptoutil::{write_u32_le, read_u32v_le, FixedBuffer, FixedBuffer64, StandardPadding}; | random_line_split | |
TimeUtils.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Utility class which exposes functions for managing date and time operations.
*/
export class TimeUtils {
/**
* return the current time in Unix time (seconds).
*/
static nowSeconds(): number... | return cachedAtSec > TimeUtils.nowSeconds();
}
/**
* Waits for t number of milliseconds
* @param t number
* @param value T
*/
static delay<T>(t: number, value?: T): Promise<T | void> {
return new Promise((resolve) => setTimeout(() => resolve(value), t));
}
} | * @param offset
*/
static wasClockTurnedBack(cachedAt: string): boolean {
const cachedAtSec = Number(cachedAt);
| random_line_split |
TimeUtils.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Utility class which exposes functions for managing date and time operations.
*/
export class TimeUtils {
/**
* return the current time in Unix time (seconds).
*/
static nowSeconds(): number... |
/**
* Waits for t number of milliseconds
* @param t number
* @param value T
*/
static delay<T>(t: number, value?: T): Promise<T | void> {
return new Promise((resolve) => setTimeout(() => resolve(value), t));
}
}
| {
const cachedAtSec = Number(cachedAt);
return cachedAtSec > TimeUtils.nowSeconds();
} | identifier_body |
TimeUtils.ts | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Utility class which exposes functions for managing date and time operations.
*/
export class TimeUtils {
/**
* return the current time in Unix time (seconds).
*/
static | (): number {
// Date.getTime() returns in milliseconds.
return Math.round(new Date().getTime() / 1000.0);
}
/**
* check if a token is expired based on given UTC time in seconds.
* @param expiresOn
*/
static isTokenExpired(expiresOn: string, offset: number): boolean {
... | nowSeconds | identifier_name |
resetImgSize.js | /**
* @author jerry
*/
(function(win,$){
/**
* param {object} require and todo param
* param.imageUrl {string} images
* param.width {NUmber} image width
* param.style {string} image height value:max | min
* param.height {Number} image height
* param.zoom {bool} if images size than param.width latter,is o... |
},
setWH=function(p,img){
var iw=img.width,ih=img.height;
var nw,nh;
if(iw<=p.width && ih <= p.height){
return [iw,ih];
}
var ratio=iw/ih;
if(iw>=ih){
if(iw>=p.width){
nw=p.width;
nh=nw/ratio;
}else if(ih>=p.height){
nh=p.height;
nw=ratio*nh;
}
}else{
if(ih>=p.height){
... | {
$.getScript(url,function(){
fn&&fn(win[method]);
});
} | conditional_block |
resetImgSize.js | /**
* @author jerry
*/ | * param.imageUrl {string} images
* param.width {NUmber} image width
* param.style {string} image height value:max | min
* param.height {Number} image height
* param.zoom {bool} if images size than param.width latter,is or not reset size
*/
var init=function(param,fn){
var defalts={};
$.extend(defalts,{... | (function(win,$){
/**
* param {object} require and todo param | random_line_split |
config.py | import os
DEFAULT_CHARACTER_PATH = os.path.join(
os.path.dirname(os.path.realpath(__file__)), 'characters')
CHARACTER_PATH = os.environ.get('HR_CHARACTER_PATH', DEFAULT_CHARACTER_PATH)
RESET_SESSION_BY_HELLO = False
SESSION_REMOVE_TIMEOUT = 3600 # Timeout seconds for a session to be removed
CHATBOT_LOG_DIR = os.... | config['SESSION_REMOVE_TIMEOUT'] = SESSION_REMOVE_TIMEOUT
config['CHATBOT_LOG_DIR'] = CHATBOT_LOG_DIR
config['SERVER_LOG_DIR'] = SERVER_LOG_DIR
config['HISTORY_DIR'] = HISTORY_DIR
config['CS_HOST'] = CS_HOST
config['CS_PORT'] = CS_PORT
config['CS_BOT'] = CS_BOT
config['HR_CHATBOT_AUTHKEY'] = HR_CHATBOT_AUTHKEY | config['CHARACTER_PATH'] = CHARACTER_PATH
config['RESET_SESSION_BY_HELLO'] = RESET_SESSION_BY_HELLO | random_line_split |
utils_memory.py | info).group(0)) |
def memtotal():
return read_from_meminfo('MemTotal')
def freememtotal():
return read_from_meminfo('MemFree')
def rounded_memtotal():
# Get total of all physical mem, in kbytes
usable_kbytes = memtotal()
# usable_kbytes is system's usable DRAM in kbytes,
# as reported by memtotal() from de... | random_line_split | |
utils_memory.py | info).group(0))
def memtotal():
return read_from_meminfo('MemTotal')
def freememtotal():
return read_from_meminfo('MemFree')
def rounded_memtotal():
# Get total of all physical mem, in kbytes
usable_kbytes = memtotal()
# usable_kbytes is system's usable DRAM in kbytes,
# as reported by m... | (sflag):
"""
sflag only can be set always, madvise or never.
"""
flags = ['always', 'madvise', 'never']
if sflag not in flags:
raise error.TestFail("specify wrong parameter")
UPSTREAM_THP_PATH = "/sys/kernel/mm/transparent_hugepage"
RH_THP_PATH = "/sys/kernel/mm/redhat_transparent_hu... | set_transparent_hugepage | identifier_name |
utils_memory.py | info).group(0))
def memtotal():
return read_from_meminfo('MemTotal')
def freememtotal():
return read_from_meminfo('MemFree')
def rounded_memtotal():
# Get total of all physical mem, in kbytes
usable_kbytes = memtotal()
# usable_kbytes is system's usable DRAM in kbytes,
# as reported by m... |
return numa_maps_dict
def get_buddy_info(chunk_sizes, nodes="all", zones="all"):
"""
Get the fragement status of the host. It use the same method
to get the page size in buddyinfo.
2^chunk_size * page_size
The chunk_sizes can be string make up by all orders that you want to check
splited... | numa_maps_dict[address] = number | conditional_block |
utils_memory.py | info).group(0))
def memtotal():
return read_from_meminfo('MemTotal')
def freememtotal():
return read_from_meminfo('MemFree')
def rounded_memtotal():
# Get total of all physical mem, in kbytes
usable_kbytes = memtotal()
# usable_kbytes is system's usable DRAM in kbytes,
# as reported by m... | :rtype: dict
"""
buddy_info = open("/proc/buddyinfo")
buddy_info_content = buddy_info.read()
buddy_info.close()
re_buddyinfo = "Node\s+"
if nodes == "all":
re_buddyinfo += "(\d+)"
else:
re_buddyinfo += "(%s)" % "|".join(nodes.split())
if not re.findall(re_buddyinfo,... | """
Get the fragement status of the host. It use the same method
to get the page size in buddyinfo.
2^chunk_size * page_size
The chunk_sizes can be string make up by all orders that you want to check
splited with blank or a mathematical expression with '>', '<' or '='.
For example:
The input... | identifier_body |
cstore.rs | , PathKind)>,
pub rlib: Option<(PathBuf, PathKind)>,
pub cnum: ast::CrateNum,
}
pub struct CStore {
metas: RefCell<FnvHashMap<ast::CrateNum, Rc<crate_metadata>>>,
/// Map from NodeId's of local extern crate statements to crate numbers
extern_mod_crate_map: RefCell<NodeMap<ast::CrateNum>>,
used_... | {
let len = (((slice[0] as u32) << 24) |
((slice[1] as u32) << 16) |
((slice[2] as u32) << 8) |
((slice[3] as u32) << 0)) as usize;
if len + 4 <= slice.len() {
&slice[4.. len + 4]
} else {
... | conditional_block | |
cstore.rs | local crate numbers (as generated during this session). Each external
// crate may refer to types in other external crates, and each has their
// own crate numbers.
pub type cnum_map = FnvHashMap<ast::CrateNum, ast::CrateNum>;
pub enum MetadataBlob {
MetadataVec(Bytes),
MetadataArchive(loader::ArchiveMetadata... |
// This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref. | random_line_split | |
cstore.rs | , Ref};
use std::rc::Rc;
use std::path::PathBuf;
use flate::Bytes;
use syntax::ast;
use syntax::codemap;
use syntax::parse::token;
use syntax::parse::token::IdentInterner;
use syntax::util::small_vector::SmallVector;
use ast_map;
// A map from external crate numbers (as decoded from some crate file) to
// local crate ... | {
MetadataVec(Bytes),
MetadataArchive(loader::ArchiveMetadata),
}
/// Holds information about a codemap::FileMap imported from another crate.
/// See creader::import_codemap() for more information.
pub struct ImportedFileMap {
/// This FileMap's byte-offset within the codemap of its original crate
pub... | MetadataBlob | identifier_name |
cstore.rs | , Ref};
use std::rc::Rc;
use std::path::PathBuf;
use flate::Bytes;
use syntax::ast;
use syntax::codemap;
use syntax::parse::token;
use syntax::parse::token::IdentInterner;
use syntax::util::small_vector::SmallVector;
use ast_map;
// A map from external crate numbers (as decoded from some crate file) to
// local crate ... |
// This method is used when generating the command line to pass through to
// system linker. The linker expects undefined symbols on the left of the
// command line to be defined in libraries on the right, not the other way
// around. For more info, see some comments in the add_used_library function
... | {
self.metas.borrow_mut().clear();
self.extern_mod_crate_map.borrow_mut().clear();
self.used_crate_sources.borrow_mut().clear();
self.used_libraries.borrow_mut().clear();
self.used_link_args.borrow_mut().clear();
} | identifier_body |
index.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = precss;
var _identity = require('utilise/identity');
var _identity2 = _interopRequireDefault(_identity);
var _client = require('utilise/client');
var _client2 = _interopRequireDefault(_client);
var _values = require('... |
var render = function render(ripple) {
return function (next) {
return function (host) {
var css = (0, _str2.default)((0, _attr2.default)(host, 'css')).split(' ').filter(Boolean),
root = host.shadowRoot || host,
head = document.head,
shadow = head.createShadowRoot && host.sha... | {
if (!_client2.default) return;
log('creating');
ripple.render = render(ripple)(ripple.render);
(0, _values2.default)(ripple.types).filter((0, _by2.default)('header', 'text/css')).map(function (type) {
return type.render = (0, _proxy2.default)(type.render, css(ripple));
});
return ripple;
} | identifier_body |
index.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = precss;
var _identity = require('utilise/identity');
var _identity2 = _interopRequireDefault(_identity);
var _client = require('utilise/client');
var _client2 = _interopRequireDefault(_client);
var _values = require('... | return function (host) {
var css = (0, _str2.default)((0, _attr2.default)(host, 'css')).split(' ').filter(Boolean),
root = host.shadowRoot || host,
head = document.head,
shadow = head.createShadowRoot && host.shadowRoot,
styles;
// this host does not have a css d... | random_line_split | |
index.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = precss;
var _identity = require('utilise/identity');
var _identity2 = _interopRequireDefault(_identity);
var _client = require('utilise/client');
var _client2 = _interopRequireDefault(_client);
var _values = require('... | (obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// -------------------------------------------
// Pre-applies Scoped CSS [css=name]
// -------------------------------------------
function precss(ripple) {
if (!_client2.default) return;
log('creating');
ripple.render = render(ripple)(ripple.rend... | _interopRequireDefault | identifier_name |
select-department.service.spec.ts | import { TestBed } from '@angular/core/testing';
import { SelectDepartmentService } from './select-department.service';
import { LocalStorageService } from 'src/app/utils/local-storage.service';
import { BehaviorSubject } from 'rxjs';
describe('Service : Select Department Unit Tests', () => {
let selectDepartmentSer... | );
});
}); | random_line_split | |
select-department.service.spec.ts | import { TestBed } from '@angular/core/testing';
import { SelectDepartmentService } from './select-department.service';
import { LocalStorageService } from 'src/app/utils/local-storage.service';
import { BehaviorSubject } from 'rxjs';
describe('Service : Select Department Unit Tests', () => {
let selectDepartmentSer... |
});
expect(selectDepartmentService.getUserSetDepartment()).toBe(
'CDM',
'service returned stub value'
);
});
it('should set and emit correct department', () => {
selectDepartmentService.setDepartment('CDM');
expect(selectDepartmentService.selectedDepartmentSource).toEqual(
mo... | {
return undefined;
} | conditional_block |
index-compiled.js | 'use strict';
function posix(path) {
return path.charAt(0) === '/';
};
function win32(path) | ;
module.exports = process.platform === 'win32' ? win32 : posix;
module.exports.posix = posix;
module.exports.win32 = win32;
//# sourceMappingURL=index-compiled.js.map | {
// https://github.com/joyent/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
var result = splitDeviceRe.exec(path);
var device = result[1] || '';
var isUnc = !!device && device.charAt(1) !== ':';
// UNC... | identifier_body |
index-compiled.js | 'use strict';
function posix(path) {
return path.charAt(0) === '/';
};
function win32(path) {
// https://github.com/joyent/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
var result = splitDeviceRe.exec(pa... |
//# sourceMappingURL=index-compiled.js.map | random_line_split | |
index-compiled.js | 'use strict';
function | (path) {
return path.charAt(0) === '/';
};
function win32(path) {
// https://github.com/joyent/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
var result = splitDeviceRe.exec(path);
var device = result[1] ... | posix | identifier_name |
sv.js | /* flatpickr v4.2.1, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.sv = {})));
}(this, (function (exports) { 'use strict';
var fp = typeof wi... | shorthand: [
"Jan",
"Feb",
"Mar",
"Apr",
"Maj",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec",
],
longhand: [
"Januari",
... | "Fredag",
"Lördag",
],
},
months: {
| random_line_split |
lazyload.js | /**
* Created by patricepaquette on 12/17/2013.
*/
angular.module("common")
.directive('lazyLoad', ['$window', '$q', function ($window, $q) {
function load_script(src) |
function lazyLoadApi(src) {
var deferred = $q.defer();
$window.initialize = function () {
deferred.resolve();
};
// thanks to Emil Stenström: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
if ($window.attachEvent) {
... | {
var s = document.createElement('script'); // use global document since Angular's $document is weak
s.src = src;
document.body.appendChild(s);
} | identifier_body |
lazyload.js | /**
* Created by patricepaquette on 12/17/2013.
*/
angular.module("common")
.directive('lazyLoad', ['$window', '$q', function ($window, $q) {
function load_script(src) {
var s = document.createElement('script'); // use global document since Angular's $document is weak
s.src = src;... | (src) {
var deferred = $q.defer();
$window.initialize = function () {
deferred.resolve();
};
// thanks to Emil Stenström: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
if ($window.attachEvent) {
$window.attachEv... | lazyLoadApi | identifier_name |
lazyload.js | /**
* Created by patricepaquette on 12/17/2013.
*/
angular.module("common")
.directive('lazyLoad', ['$window', '$q', function ($window, $q) {
function load_script(src) {
var s = document.createElement('script'); // use global document since Angular's $document is weak
s.src = src;... | return deferred.promise;
}
return {
restrict: 'E',
scope: {
src: "@src"
},
link: function (scope, element, attrs) { // function content is optional
// in this example, it shows how and when the promises are resol... |
$window.addEventListener('load', function(){
load_script(src);
}, false);
}
| conditional_block |
lazyload.js | /**
* Created by patricepaquette on 12/17/2013.
*/
angular.module("common")
.directive('lazyLoad', ['$window', '$q', function ($window, $q) {
function load_script(src) {
var s = document.createElement('script'); // use global document since Angular's $document is weak
s.src = src;... | src: "@src"
},
link: function (scope, element, attrs) { // function content is optional
// in this example, it shows how and when the promises are resolved
if ($window.google && $window.google.maps) {
} else {
l... | }
return {
restrict: 'E',
scope: { | random_line_split |
timezone.py | """Phone number to time zone mapping functionality
>>> import phonenumbers
>>> from phonenumbers.timezone import time_zones_for_number
>>> ro_number = phonenumbers.parse("+40721234567", "RO")
>>> tzlist = time_zones_for_number(ro_number)
>>> len(tzlist)
1
>>> str(tzlist[0])
'Europe/Bucharest'
>>> mx_number = phonenumb... | (numobj):
"""Returns a list of time zones to which a phone number belongs.
This method assumes the validity of the number passed in has already been
checked, and that the number is geo-localizable. We consider fixed-line
and mobile numbers possible candidates for geo-localization.
Arguments:
n... | time_zones_for_geographical_number | identifier_name |
timezone.py | """Phone number to time zone mapping functionality
>>> import phonenumbers
>>> from phonenumbers.timezone import time_zones_for_number
>>> ro_number = phonenumbers.parse("+40721234567", "RO")
>>> tzlist = time_zones_for_number(ro_number)
>>> len(tzlist)
1
>>> str(tzlist[0])
'Europe/Bucharest'
>>> mx_number = phonenumb... |
def _country_level_time_zones_for_number(numobj):
"""Returns the list of time zones corresponding to the country calling code of a number.
Arguments:
numobj -- the phone number to look up
Returns a list of the corresponding time zones or a single element list with the default
unknown time zone if... | """As time_zones_for_geographical_number() but explicitly checks the
validity of the number passed in.
Arguments:
numobj -- a valid phone number for which we want to get the time zones to which it belongs
Returns a list of the corresponding time zones or a single element list with the default
unkno... | identifier_body |
timezone.py | """Phone number to time zone mapping functionality
>>> import phonenumbers
>>> from phonenumbers.timezone import time_zones_for_number
>>> ro_number = phonenumbers.parse("+40721234567", "RO")
>>> tzlist = time_zones_for_number(ro_number)
>>> len(tzlist)
1
>>> str(tzlist[0])
'Europe/Bucharest'
>>> mx_number = phonenumb... | 2
>>> str(tzlist[0])
'America/Mazatlan'
>>> str(tzlist[1])
'America/Mexico_City'
"""
# Based very loosely on original Java code:
# java/geocoder/src/com/google/i18n/phonenumbers/PhoneNumberToTimeZonesMapper.java
# Copyright (C) 2013 The Libphonenumber Authors
#
# Licensed under the Apache License, Version 2.0 (t... | >>> len(tzlist) | random_line_split |
timezone.py | """Phone number to time zone mapping functionality
>>> import phonenumbers
>>> from phonenumbers.timezone import time_zones_for_number
>>> ro_number = phonenumbers.parse("+40721234567", "RO")
>>> tzlist = time_zones_for_number(ro_number)
>>> len(tzlist)
1
>>> str(tzlist[0])
'Europe/Bucharest'
>>> mx_number = phonenumb... |
return time_zones_for_geographical_number(numobj)
def _country_level_time_zones_for_number(numobj):
"""Returns the list of time zones corresponding to the country calling code of a number.
Arguments:
numobj -- the phone number to look up
Returns a list of the corresponding time zones or a single ... | return _country_level_time_zones_for_number(numobj) | conditional_block |
toggle.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
module.metadata = {
'stability': 'experimental',
'engines': {
'Firefox': '> 28'
}
};
cons... | ,
click: function click() {
return view.click(toWidgetId(this.id));
}
});
exports.ToggleButton = ToggleButton;
identify.define(ToggleButton, ({id}) => toWidgetId(id));
getNodeView.define(ToggleButton, button =>
view.nodeFor(toWidgetId(button.id))
);
var toggleButtonStateEvents = events.filter(stateEvents,... | {
return this.state().id;
} | identifier_body |
toggle.js | module.metadata = {
'stability': 'experimental',
'engines': {
'Firefox': '> 28'
}
};
const { Class } = require('../../core/heritage');
const { merge } = require('../../util/object');
const { Disposable } = require('../../core/disposable');
const { on, off, emit, setListeners } = require('../../event/core');
... | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
| random_line_split | |
toggle.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
module.metadata = {
'stability': 'experimental',
'engines': {
'Firefox': '> 28'
}
};
cons... | () {
return this.state().id;
},
click: function click() {
return view.click(toWidgetId(this.id));
}
});
exports.ToggleButton = ToggleButton;
identify.define(ToggleButton, ({id}) => toWidgetId(id));
getNodeView.define(ToggleButton, button =>
view.nodeFor(toWidgetId(button.id))
);
var toggleButtonStat... | id | identifier_name |
wallet_library.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! The following document is a minimalist version of Diem Wallet. Note that this Wallet does
//! not promote security as the mnemonic is stored in unencrypted form. In future iterations,
//! we will be releasing more robust Wallet impl... | (&self, address: &AccountAddress) -> Result<AuthenticationKey> {
if let Some(child) = self.addr_map.get(&address) {
Ok(self
.key_factory
.private_child(*child)?
.get_authentication_key())
} else {
Err(WalletError::DiemWalletGeneric(... | get_authentication_key | identifier_name |
wallet_library.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! The following document is a minimalist version of Diem Wallet. Note that this Wallet does
//! not promote security as the mnemonic is stored in unencrypted form. In future iterations,
//! we will be releasing more robust Wallet impl... | } | random_line_split | |
wallet_library.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! The following document is a minimalist version of Diem Wallet. Note that this Wallet does
//! not promote security as the mnemonic is stored in unencrypted form. In future iterations,
//! we will be releasing more robust Wallet impl... |
/// Return authentication key (AuthenticationKey) for an address in the wallet
pub fn get_authentication_key(&self, address: &AccountAddress) -> Result<AuthenticationKey> {
if let Some(child) = self.addr_map.get(&address) {
Ok(self
.key_factory
.private_chil... | {
if let Some(child) = self.addr_map.get(&address) {
Ok(self.key_factory.private_child(*child)?.get_private_key())
} else {
Err(WalletError::DiemWalletGeneric("missing address".to_string()).into())
}
} | identifier_body |
config.d.ts | redirectTo` is the url fragment which will replace the current matched segment.
* - `outlet` is the name of the outlet the component should be placed into.
* - `canActivate` is an array of DI tokens used to look up CanActivate handlers. See
* {@link CanActivate} for more info.
* - `canActivateChild` is an array o... | * component: User
* }]
* }]
* }]
* ```
*
* When navigating to `/team/11/user/jim`, the router will instantiate the wrapper component with
* the user component in it.
*
* An empty path route inherits its parent's params and data. This is because it cannot have its
* own params, and, as a result, i... | * path: '',
* component: WrapperCmp,
* children: [{
* path: 'user/:name', | random_line_split |
config.d.ts | /11/user/bob`, the router will create the team component with the user
* component in it.
*
* ### Multiple Outlets
*
* ```
* [{
* path: 'team/:id',
* component: Team
* }, {
* path: 'chat/:user',
* component: Chat
* outlet: 'aux'
* }]
* ```
*
* When navigating to `/team/11(aux:chat/jim)`, the r... | LoadedRouterConfig | identifier_name | |
delayed_gcode.py | # A simple timer for executing gcode templates
#
# Copyright (C) 2019 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
class DelayedGcode:
def __init__(self, config):
self.printer = config.get_printer()
self.reactor =... |
self.reactor.update_timer(self.timer_handler, waketime)
def load_config_prefix(config):
return DelayedGcode(config)
| waketime = self.reactor.monotonic() + self.duration | conditional_block |
delayed_gcode.py | # A simple timer for executing gcode templates
#
# Copyright (C) 2019 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
class DelayedGcode:
def __init__(self, config):
self.printer = config.get_printer()
self.reactor =... | (self):
waketime = self.reactor.NEVER
if self.duration:
waketime = self.reactor.monotonic() + self.duration
self.timer_handler = self.reactor.register_timer(
self._gcode_timer_event, waketime)
def _gcode_timer_event(self, eventtime):
self.inside_timer = True
... | _handle_ready | identifier_name |
delayed_gcode.py | # A simple timer for executing gcode templates
#
# Copyright (C) 2019 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
class DelayedGcode:
def __init__(self, config):
|
def _handle_ready(self):
waketime = self.reactor.NEVER
if self.duration:
waketime = self.reactor.monotonic() + self.duration
self.timer_handler = self.reactor.register_timer(
self._gcode_timer_event, waketime)
def _gcode_timer_event(self, eventtime):
self... | self.printer = config.get_printer()
self.reactor = self.printer.get_reactor()
self.name = config.get_name().split()[1]
self.gcode = self.printer.lookup_object('gcode')
gcode_macro = self.printer.load_object(config, 'gcode_macro')
self.timer_gcode = gcode_macro.load_template(confi... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.