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 |
|---|---|---|---|---|
router-stubs.ts |
import { Component, Directive, Injectable, Input } from '@angular/core';
import { NavigationExtras } from '@angular/router';
// Only implements params and part of snapshot.params
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
// export for convenience.
export { ActivatedRoute, Router, RouterLink, RouterOutle... | {
@Input('routerLink') linkParams: any;
navigatedTo: any = null;
onClick() {
this.navigatedTo = this.linkParams;
}
}
@Directive({
selector: '[routerLinkActive]'
})
export class RouterLinkActiveStubDirective {
@Input('routerLinkActive') linkParams: any;
}
@Component({ selector: 'router-outlet', templ... | RouterLinkStubDirective | identifier_name |
router-stubs.ts | import { Component, Directive, Injectable, Input } from '@angular/core';
import { NavigationExtras } from '@angular/router';
// Only implements params and part of snapshot.params
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
// export for convenience.
export { ActivatedRoute, Router, RouterLink, RouterOutlet... | }
}
@Directive({
selector: '[routerLinkActive]'
})
export class RouterLinkActiveStubDirective {
@Input('routerLinkActive') linkParams: any;
}
@Component({ selector: 'router-outlet', template: '' })
export class RouterOutletStubComponent { }
@Injectable()
export class RouterStub {
navigate(commands: any[], ex... | @Input('routerLink') linkParams: any;
navigatedTo: any = null;
onClick() {
this.navigatedTo = this.linkParams; | random_line_split |
unaryop_gpu.ts | /**
* @license
* Copyright 2017 Google Inc. 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 a... | (aShape: number[], opSnippet: string) {
this.outputShape = aShape;
this.userCode = `
float unaryOperation(float x) {
${opSnippet}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`;
}
}
const CHECK_NAN_SNIP... | constructor | identifier_name |
unaryop_gpu.ts | /**
* @license
* Copyright 2017 Google Inc. 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 a... |
export const CEIL = `return ceil(x);`;
export const FLOOR = `return floor(x);`;
export const SIGN = `
if (isnan(x)) { return 0.0; }
return sign(x);
`;
export const IS_NAN = `return float(isnan(x));`;
export const IS_INF = `return float(isinf(x));`;
export const IS_FINITE = `return float(!isnan(x) && !isinf(x)... | return x > 0.0 ? 1.0 : float(${alpha});
`;
}
export const NEG = `return -x;`; | random_line_split |
digital_ocean_account_facts.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = ty... | (module):
rest = DigitalOceanHelper(module)
response = rest.get("account")
if response.status_code != 200:
module.fail_json(msg="Failed to fetch 'account' facts due to error : %s" % response.json['message'])
module.exit_json(changed=False, data=response.json["account"])
def main():
argum... | core | identifier_name |
digital_ocean_account_facts.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = ty... |
module.exit_json(changed=False, data=response.json["account"])
def main():
argument_spec = DigitalOceanHelper.digital_ocean_argument_spec()
module = AnsibleModule(argument_spec=argument_spec)
try:
core(module)
except Exception as e:
module.fail_json(msg=to_native(e), exception=fo... | module.fail_json(msg="Failed to fetch 'account' facts due to error : %s" % response.json['message']) | conditional_block |
digital_ocean_account_facts.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = ty... | "status": "active",
"status_message": "",
"uuid": "aaaaaaaaaaaaaa"
}
'''
from traceback import format_exc
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.digital_ocean import DigitalOceanHelper
from ansible.module_utils._text import to_native
def core(module... | random_line_split | |
digital_ocean_account_facts.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = ty... |
if __name__ == '__main__':
main()
| argument_spec = DigitalOceanHelper.digital_ocean_argument_spec()
module = AnsibleModule(argument_spec=argument_spec)
try:
core(module)
except Exception as e:
module.fail_json(msg=to_native(e), exception=format_exc()) | identifier_body |
collection_artifact.py | from __future__ import absolute_import
import json
from changes.config import db
from changes.constants import Result
from changes.models.jobplan import JobPlan
from changes.utils.http import build_web_uri
from .base import ArtifactHandler, ArtifactParseError
class | (ArtifactHandler):
"""
Base class artifact handler for collection (jobs.json and tests.json) files.
Does the required job expansion. Subclasses are expected to set
cls.FILENAMES to the handleable files in question.
"""
def process(self, fp, artifact):
try:
phase_config = jso... | CollectionArtifactHandler | identifier_name |
collection_artifact.py | from __future__ import absolute_import | from changes.config import db
from changes.constants import Result
from changes.models.jobplan import JobPlan
from changes.utils.http import build_web_uri
from .base import ArtifactHandler, ArtifactParseError
class CollectionArtifactHandler(ArtifactHandler):
"""
Base class artifact handler for collection (job... |
import json
| random_line_split |
collection_artifact.py | from __future__ import absolute_import
import json
from changes.config import db
from changes.constants import Result
from changes.models.jobplan import JobPlan
from changes.utils.http import build_web_uri
from .base import ArtifactHandler, ArtifactParseError
class CollectionArtifactHandler(ArtifactHandler):
""... |
class TestsJsonHandler(CollectionArtifactHandler):
# only match in the root directory
FILENAMES = ('/tests.json',)
| _, implementation = JobPlan.get_build_step_for_job(job_id=self.step.job_id)
try:
implementation.expand_jobs(self.step, phase_config)
except ArtifactParseError:
uri = build_web_uri('/find_build/{0}/'.format(self.step.job.build_id.hex))
self.logger.w... | conditional_block |
collection_artifact.py | from __future__ import absolute_import
import json
from changes.config import db
from changes.constants import Result
from changes.models.jobplan import JobPlan
from changes.utils.http import build_web_uri
from .base import ArtifactHandler, ArtifactParseError
class CollectionArtifactHandler(ArtifactHandler):
""... | FILENAMES = ('/tests.json',) | identifier_body | |
chats.js | const sanitizeHtml = require('sanitize-html');
const Chat = require('./../rtm-client');
const ChatModels = require('./../models/chats');
// Controller to send messages from client to slack api
const chatController = {
sendMessageToSlack(req, res) {
// Will need to get user slack token at some point
console.... |
};
module.exports = chatController;
| {
// console.log('loadMessagesFromDatabase called');
const query = { room_id: room };
ChatModels.ChatRoom.find(query, (err, data) => {
// console.log('chatRoom from db results: ', data);
if (data[0] === undefined) {
return;
}
socket.emit('chat room archive', data[0].messages)... | identifier_body |
chats.js | const sanitizeHtml = require('sanitize-html');
const Chat = require('./../rtm-client');
const ChatModels = require('./../models/chats');
// Controller to send messages from client to slack api
const chatController = {
sendMessageToSlack(req, res) {
// Will need to get user slack token at some point
console.... | }
};
module.exports = chatController; | }
socket.emit('chat room archive', data[0].messages);
}); | random_line_split |
chats.js | const sanitizeHtml = require('sanitize-html');
const Chat = require('./../rtm-client');
const ChatModels = require('./../models/chats');
// Controller to send messages from client to slack api
const chatController = {
sendMessageToSlack(req, res) {
// Will need to get user slack token at some point
console.... | (req, res) {
// Maybe have Slack --> client handled in rtm-client.js?
// Should this emit something and pass value to socket.io?
// Or use HTML5 push api?
},
sendMessageToDatabase(socket, data) {
// sanitize the message before saving!
console.log('chat.controller sendMessageToDatabase data: ', d... | sendMessagesToClient | identifier_name |
chats.js | const sanitizeHtml = require('sanitize-html');
const Chat = require('./../rtm-client');
const ChatModels = require('./../models/chats');
// Controller to send messages from client to slack api
const chatController = {
sendMessageToSlack(req, res) {
// Will need to get user slack token at some point
console.... |
socket.emit('chat room archive', data[0].messages);
});
}
};
module.exports = chatController;
| {
return;
} | conditional_block |
notofonts.py | import os
from fontbakery.profiles.universal import UNIVERSAL_PROFILE_CHECKS
from fontbakery.checkrunner import Section, WARN, PASS #, INFO, ERROR, SKIP, FAIL
from fontbakery.callable import check #, disable
from fontbakery.message import Message
from fontbakery.fonts_profile import profile_factory
from fontbakery.con... | yield PASS, "All cmap subtables look good!"
@check(
id = 'com.google.fonts/check/unicode_range_bits',
rationale = """
When the UnicodeRange bits on the OS/2 table are not properly set, some programs running on Windows may not recognize the font and use a system fallback font instead. For that ... | f" encoding={subtable.platEncID}), which it shouldn't have.")
if passed: | random_line_split |
notofonts.py | import os
from fontbakery.profiles.universal import UNIVERSAL_PROFILE_CHECKS
from fontbakery.checkrunner import Section, WARN, PASS #, INFO, ERROR, SKIP, FAIL
from fontbakery.callable import check #, disable
from fontbakery.message import Message
from fontbakery.fonts_profile import profile_factory
from fontbakery.con... | Message("bad-range-bit",
f'UnicodeRange bit {bit} "{range_name}" should be {set_unset} because'
f' cmap has {num_chars} of the {range_size} codepoints in this range.')
profile.auto_register(globals())
profile.test_expected_checks(NOTOFO... | """Ensure UnicodeRange bits are properly set."""
from fontbakery.constants import UNICODERANGE_DATA
from fontbakery.utils import (compute_unicoderange_bits,
unicoderange_bit_name,
chars_in_range)
expected_unicoderange = compute_unicoderange... | identifier_body |
notofonts.py | import os
from fontbakery.profiles.universal import UNIVERSAL_PROFILE_CHECKS
from fontbakery.checkrunner import Section, WARN, PASS #, INFO, ERROR, SKIP, FAIL
from fontbakery.callable import check #, disable
from fontbakery.message import Message
from fontbakery.fonts_profile import profile_factory
from fontbakery.con... | (ttFont, unicoderange, preferred_cmap):
"""Ensure UnicodeRange bits are properly set."""
from fontbakery.constants import UNICODERANGE_DATA
from fontbakery.utils import (compute_unicoderange_bits,
unicoderange_bit_name,
chars_in_range)
... | com_google_fonts_check_unicode_range_bits | identifier_name |
notofonts.py | import os
from fontbakery.profiles.universal import UNIVERSAL_PROFILE_CHECKS
from fontbakery.checkrunner import Section, WARN, PASS #, INFO, ERROR, SKIP, FAIL
from fontbakery.callable import check #, disable
from fontbakery.message import Message
from fontbakery.fonts_profile import profile_factory
from fontbakery.con... |
for subtable in ttFont['cmap'].tables:
if (subtable.format,
subtable.platformID,
subtable.platEncID) not in EXPECTED_SUBTABLES:
passed = False
yield WARN,\
Message("unexpected-subtable",
f"'cmap' has a subtable of"... | EXPECTED_SUBTABLES.extend([
# Adobe says historically some programs used these to identify
# the script in the font. The encodingID is the quickdraw
# script manager code. These are dummy tables.
(6, PlatformID.MACINTOSH, MacintoshEncodingID.JAPANESE),
(6, P... | conditional_block |
cost_to_csv.py | #! /usr/bin/python
# Copyright 2015 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.
import argparse
import logging
import os
import sys
from processing import (SitesFromDir, WarmGraph, ColdGraph)
def | ():
logging.basicConfig(level=logging.ERROR)
parser = argparse.ArgumentParser(
description=('Convert a directory created by ./analyze.py fetch '
'to a CSV.'))
parser.add_argument('--datadir', required=True)
parser.add_argument('--csv', required=True)
parser.add_argument('--noads', act... | main | identifier_name |
cost_to_csv.py | #! /usr/bin/python
# Copyright 2015 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.
import argparse
import logging
import os
import sys
from processing import (SitesFromDir, WarmGraph, ColdGraph)
def main():
logging.b... | parser.add_argument('--csv', required=True)
parser.add_argument('--noads', action='store_true')
args = parser.parse_args()
sites = SitesFromDir(args.datadir)
with open(args.csv, 'w') as output:
output.write('site,kind,cost\n')
for site in sites:
print site
warm = WarmGraph(args.datadir, si... | random_line_split | |
cost_to_csv.py | #! /usr/bin/python
# Copyright 2015 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.
import argparse
import logging
import os
import sys
from processing import (SitesFromDir, WarmGraph, ColdGraph)
def main():
logging.b... |
if __name__ == '__main__':
main()
| print site
warm = WarmGraph(args.datadir, site)
if args.noads:
warm.Set(node_filter=warm.FilterAds)
cold = ColdGraph(args.datadir, site)
if args.noads:
cold.Set(node_filter=cold.FilterAds)
output.write('%s,%s,%s\n' % (site, 'warm', warm.Cost()))
warm.Set(cache_all=Tru... | conditional_block |
cost_to_csv.py | #! /usr/bin/python
# Copyright 2015 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.
import argparse
import logging
import os
import sys
from processing import (SitesFromDir, WarmGraph, ColdGraph)
def main():
| warm.Set(cache_all=True)
output.write('%s,%s,%s\n' % (site, 'warm-cache', warm.Cost()))
output.write('%s,%s,%s\n' % (site, 'cold', cold.Cost()))
cold.Set(cache_all=True)
output.write('%s,%s,%s\n' % (site, 'cold-cache', cold.Cost()))
if __name__ == '__main__':
main()
| logging.basicConfig(level=logging.ERROR)
parser = argparse.ArgumentParser(
description=('Convert a directory created by ./analyze.py fetch '
'to a CSV.'))
parser.add_argument('--datadir', required=True)
parser.add_argument('--csv', required=True)
parser.add_argument('--noads', action='s... | identifier_body |
mtUnitTests.py | #import unittest
import mt
import queue
import _thread
import time
class DummySocket:
def __init__(self, ID):
self.id = ID
self.lastMsg = ""
def send(self, msg):
print(self.id+":",msg)
self.lastMsg = msg
def close(self):
print(self.id+": CLOSE CALLED")
self... |
listenerObj = mt.ListenerThread(data)
def sender():
time.sleep(1)
data.put("Hello, World")
time.sleep(0.1)
listenerObj.add(s2)
time.sleep(1)
data.put("Hello, World 2")
time.sleep(1)
listenerObj.removeIP("0"... | s2 = DummySocket("1") | random_line_split |
mtUnitTests.py | #import unittest
import mt
import queue
import _thread
import time
class DummySocket:
def __init__(self, ID):
self.id = ID
self.lastMsg = ""
def send(self, msg):
print(self.id+":",msg)
self.lastMsg = msg
def close(self):
print(self.id+": CLOSE CALLED")
self... | (self):
return self.id, 0
##class TestMt(unittest.TestCase):
##
## def test_listener_thread(self):
## data = queue.Queue()
## s1 = DummySocket("0")
## s2 = DummySocket("1")
##
## listenerObj = mt.ListenerThread(data)
##
## def sender():
## time.sleep(1)
## ... | getpeername | identifier_name |
mtUnitTests.py | #import unittest
import mt
import queue
import _thread
import time
class DummySocket:
|
##class TestMt(unittest.TestCase):
##
## def test_listener_thread(self):
## data = queue.Queue()
## s1 = DummySocket("0")
## s2 = DummySocket("1")
##
## listenerObj = mt.ListenerThread(data)
##
## def sender():
## time.sleep(1)
## data.put("Hello, World")
##... | def __init__(self, ID):
self.id = ID
self.lastMsg = ""
def send(self, msg):
print(self.id+":",msg)
self.lastMsg = msg
def close(self):
print(self.id+": CLOSE CALLED")
self.lastMsg = "CLOSED"
def getpeername(self):
return self.id, 0 | identifier_body |
diffEditorInput.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
super.dispose();
}
} | {
this.cachedModel.dispose();
this.cachedModel = null;
} | conditional_block |
diffEditorInput.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (candidates: string[]): string {
return this.forceOpenAsBinary ? BINARY_DIFF_EDITOR_ID : TEXT_DIFF_EDITOR_ID;
}
private createModel(refresh?: boolean): TPromise<DiffEditorModel> {
// Join resolve call over two inputs and build diff editor model
return TPromise.join([
this.originalInput.resolve(),
this.m... | getPreferredEditorId | identifier_name |
diffEditorInput.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
getPreferredEditorId(candidates: string[]): string {
return this.forceOpenAsBinary ? BINARY_DIFF_EDITOR_ID : TEXT_DIFF_EDITOR_ID;
}
private createModel(refresh?: boolean): TPromise<DiffEditorModel> {
// Join resolve call over two inputs and build diff editor model
return TPromise.join([
this.originalInp... | {
// Create Model - we never reuse our cached model if refresh is true because we cannot
// decide for the inputs within if the cached model can be reused or not. There may be
// inputs that need to be loaded again and thus we always recreate the model and dispose
// the previous one - if any.
return this.cr... | identifier_body |
diffEditorInput.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | static readonly ID = 'workbench.editors.diffEditorInput';
private cachedModel: DiffEditorModel;
constructor(name: string, description: string, original: EditorInput, modified: EditorInput, private forceOpenAsBinary?: boolean) {
super(name, description, original, modified);
}
getTypeId(): string {
return Dif... | export class DiffEditorInput extends SideBySideEditorInput {
| random_line_split |
player.rs | /*
Controls the Player Behaviour
*/
use polar_game::object::{Part,Object,};
use polar_game::object::{Point};
use polar_game::GameSetup;
use rand;
use rand::distributions::IndependentSample;
use rand::distributions::range::Range;
use std::f64::consts::PI;
pub struct Player{
pub position: Point,
parts: Vec<Part... | (&self) -> Point{
self.position
}
fn get_render_parts(&self) -> Vec<Part>{
let mut part_vec: Vec<Part> = Vec::new();
if !self.destroyed{
for p in self.parts.iter(){
let p_shift = Part{
radial: p.radial + Point{x: self.position.x, y: self.p... | get_position | identifier_name |
player.rs | /*
Controls the Player Behaviour
*/
use polar_game::object::{Part,Object,};
use polar_game::object::{Point};
use polar_game::GameSetup;
use rand;
use rand::distributions::IndependentSample;
use rand::distributions::range::Range;
use std::f64::consts::PI;
pub struct Player{
pub position: Point,
parts: Vec<Part... |
else{
time_passed = time_passed /5.0;
for i in 0..100{
let radial_shift = Point{x: self.destruct_dirs[i].x, y: self.destruct_dirs[i].x};
let angle_shift = Point{x: self.destruct_dirs[i].y, y: self.destruct_dirs[i].y};
self.destruct_parts... | {
self.position = self.position + shift.mult(time_passed);
self.position.x = self.position.x.min(game_setup.radial_max - game_setup.player_width.x).max(0.0);
} | conditional_block |
player.rs | /*
Controls the Player Behaviour
*/
use polar_game::object::{Part,Object,};
use polar_game::object::{Point};
use polar_game::GameSetup;
use rand;
use rand::distributions::IndependentSample;
use rand::distributions::range::Range;
use std::f64::consts::PI;
pub struct Player{
pub position: Point,
parts: Vec<Part... | destroyed: false,}
}
pub fn update_position(&mut self, shift: Point, mut time_passed: f64, game_setup: GameSetup){
if !self.destroyed{
self.position = self.position + shift.mult(time_passed);
self.position.x = self.position.x.min(game_setup.radial_max - game_setup... | color: [1.0, 1.0, 1.0, 1.0]}];
Player{position: Point{x: start.x, y: start.y},
parts: prts,
destruct_parts: Vec::new(),
destruct_dirs: Vec::new(), | random_line_split |
player.rs | /*
Controls the Player Behaviour
*/
use polar_game::object::{Part,Object,};
use polar_game::object::{Point};
use polar_game::GameSetup;
use rand;
use rand::distributions::IndependentSample;
use rand::distributions::range::Range;
use std::f64::consts::PI;
pub struct Player{
pub position: Point,
parts: Vec<Part... |
fn get_collision_parts(&self) -> Vec<Part>{
let mut parts: Vec<Part> = Vec::new();
if !self.destroyed{
parts = self.get_render_parts();
}
parts
}
}
impl Player{
pub fn new(start: Point, width: Point) -> Player{
let prts = vec![Part{radial: Point{x: 0.0,... | {
let mut part_vec: Vec<Part> = Vec::new();
if !self.destroyed{
for p in self.parts.iter(){
let p_shift = Part{
radial: p.radial + Point{x: self.position.x, y: self.position.x},
angle: p.angle + Point{x: self.position.y, y: self.positio... | identifier_body |
resource-assign-is-not-copy.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 ... | } | random_line_split | |
resource-assign-is-not-copy.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 ... | () {
let i = @mut 0;
// Even though these look like copies, they are guaranteed not to be
{
let a = r(i);
let b = (a, 10);
let (c, _d) = b;
info!(c);
}
assert_eq!(*i, 1);
}
| main | identifier_name |
manager.py | def __init__(self, config):
self._config = config
self._port_info = {}
self._relays = {} # (tcprelay, udprelay)
self._loop = eventloop.EventLoop()
self._dns_resolver = asyncdns.DNSResolver()
self._dns_resolver.add_to_loop(self._loop)
self._last_day = datetime.d... | elif command == 'remove':
assert 'server_port' in a_config
assert type(a_config['server_port']) is int
self.remove_user(a_config)
self._send_control_data(b'ok')
elif command == 'ping':... | eventloop.POLL_IN:
data, self._control_client_addr = sock.recvfrom(BUF_SIZE)
parsed = self._parse_command(data)
if parsed:
command, config = parsed
a_config = self._config.copy()
if config:
# let the command overrid... | identifier_body |
manager.py | def __init__(self, config):
self._config = config
self._port_info = {}
self._relays = {} # (tcprelay, udprelay)
self._loop = eventloop.EventLoop()
self._dns_resolver = asyncdns.DNSResolver()
self._dns_resolver.add_to_loop(self._loop)
self._last_day = datetim... | import time
import threading
import struct
from shadowsocks import encrypt
logging.basicConfig(level=5,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
enc = []
eventloop.TIMEOUT_PRECISION = 1
def run_server... | random_line_split | |
manager.py | def __init__(self, config):
self._config = config
self._port_info = {}
self._relays = {} # (tcprelay, udprelay)
self._loop = eventloop.EventLoop()
self._dns_resolver = asyncdns.DNSResolver()
self._dns_resolver.add_to_loop(self._loop)
self._last_day = datetim... | _socket.sendto(data, self._control_client_addr)
except (socket.error, OSError, IOError) as e:
error_no = eventloop.errno_from_exception(e)
if error_no in (errno.EAGAIN, errno.EINPROGRESS,
errno.EWOULDBLOCK):
return
... | self._control | identifier_name |
manager.py | def __init__(self, config):
self._config = config
self._port_info = {}
self._relays = {} # (tcprelay, udprelay)
self._loop = eventloop.EventLoop()
self._dns_resolver = asyncdns.DNSResolver()
self._dns_resolver.add_to_loop(self._loop)
self._last_day = datetim... | f add_user(self, config):
port = int(config['server_port'])
if port in self._port_info:
logging.error("user already exists at %s:%d" % (config['server'], port))
return
logging.info("adding user at %s:%d" % (config['server'], port))
self._port_info[port] = config
... | LIMIT_MULTIPLE
self.add_user(a_config)
de | conditional_block |
borrowck-lend-flow-loop.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 ... | // Here we check that when you break out of an inner loop, the
// borrows that go out of scope as you exit the inner loop are
// removed from the bitset.
while cond() {
while cond() {
// this borrow is limited to the scope of `r`...
let r: &'r mut uint = produce();
... | }
}
fn loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) { | random_line_split |
borrowck-lend-flow-loop.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 ... | () {
// In this instance, the borrow encompasses the entire loop.
let mut v = ~3;
let mut x = &mut v;
**x += 1;
loop {
borrow(v); //~ ERROR cannot borrow
}
}
fn block_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire closure call.
let mut v = ~3;... | loop_overarching_alias_mut | identifier_name |
borrowck-lend-flow-loop.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 borrow_mut(_v: &mut int) {}
fn cond() -> bool { fail2!() }
fn produce<T>() -> T { fail2!(); }
fn inc(v: &mut ~int) {
*v = ~(**v + 1);
}
fn loop_overarching_alias_mut() {
// In this instance, the borrow encompasses the entire loop.
let mut v = ~3;
let mut x = &mut v;
**x += 1;
loop {
... | {} | identifier_body |
borrowck-lend-flow-loop.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 loop_break_pops_scopes<'r>(_v: &'r mut [uint], f: &fn(&'r mut uint) -> bool) {
// Here we check that when you break out of an inner loop, the
// borrows that go out of scope as you exit the inner loop are
// removed from the bitset.
while cond() {
while cond() {
// this... | {
x = &mut v; //~ ERROR cannot borrow
} | conditional_block |
solver060.rs | // COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use std::collections::HashMap;
use euler::algorithm::long::{concatenation, pow_10, square};
use euler::algorithm::prime::{generator_wheel, miller_rabin, prime_sieve};
use euler::Solver;
// The primes 3, 7, 109, and 673, a... | if set.len() >= size || add_prime_to_set(set, size, primes, cache) {
true
} else {
set.pop();
false
}
})
}
| {
let last_prime = *primes.last().unwrap();
let is_prime = |c| if c < last_prime {
primes.binary_search(&c).is_ok()
} else if c < square(last_prime) {
prime_sieve(c, primes)
} else {
miller_rabin(c)
};
let concatenation_list = |p| primes.iter().filter(|&&prime| prime > p ... | identifier_body |
solver060.rs | // COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use std::collections::HashMap;
use euler::algorithm::long::{concatenation, pow_10, square};
use euler::algorithm::prime::{generator_wheel, miller_rabin, prime_sieve};
use euler::Solver;
// The primes 3, 7, 109, and 673, a... | (&self) -> isize {
let (mut set, primes) = (vec![], generator_wheel().take_while(|&p| p < pow_10(self.n - 1)).collect::<Vec<_>>());
add_prime_to_set(&mut set, self.n as _, &primes, &mut HashMap::new());
set.iter().sum()
}
}
fn add_prime_to_set<'a>(set: &mut Vec<isize>, size: usize, primes: ... | solve | identifier_name |
solver060.rs | // COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use std::collections::HashMap;
use euler::algorithm::long::{concatenation, pow_10, square};
use euler::algorithm::prime::{generator_wheel, miller_rabin, prime_sieve};
use euler::Solver;
// The primes 3, 7, 109, and 673, a... | // Closure that takes an element of the set and does the intersection with the concatenations of other elements.
// The outcome is the primes that form concatenations with all elements of the set. From there, try to increase the size of the set by recursion.
let candidates = |p| cache.get(p).unwrap().iter()... | // Memoization of the prime concatenations for a 25% speedup, despite increasing code complexity significantly
set.last().iter().for_each(|&&p| { cache.entry(p).or_insert_with(|| concatenation_list(p)); });
| random_line_split |
solver060.rs | // COPYRIGHT (C) 2017 barreiro. All Rights Reserved.
// Rust solvers for Project Euler problems
use std::collections::HashMap;
use euler::algorithm::long::{concatenation, pow_10, square};
use euler::algorithm::prime::{generator_wheel, miller_rabin, prime_sieve};
use euler::Solver;
// The primes 3, 7, 109, and 673, a... |
})
}
| {
set.pop();
false
} | conditional_block |
dirac-dms-put-and-register-request.py | #!/bin/env python
""" create and put 'PutAndRegister' request with a single local file
warning: make sure the file you want to put is accessible from DIRAC production hosts,
i.e. put file on network fs (AFS or NFS), otherwise operation will fail!!!
"""
__RCSID__ = "$Id: $"
import os
from DIRAC.Core.Base... |
PFN = os.path.abspath( PFN )
size = os.path.getsize( PFN )
adler32 = fileAdler( PFN )
request = Request()
request.RequestName = requestName
putAndRegister = Operation()
putAndRegister.Type = "PutAndRegister"
putAndRegister.TargetSE = targetSE
opFile = File()
opFile.LFN = LFN
opFile.PFN = PFN
... | gLogger.error( "%s is not a file" % PFN )
DIRAC.exit( -1 ) | conditional_block |
dirac-dms-put-and-register-request.py | #!/bin/env python
""" create and put 'PutAndRegister' request with a single local file
warning: make sure the file you want to put is accessible from DIRAC production hosts,
i.e. put file on network fs (AFS or NFS), otherwise operation will fail!!!
"""
__RCSID__ = "$Id: $"
import os
from DIRAC.Core.Base... | if not os.path.exists( PFN ):
gLogger.error( "%s does not exist" % PFN )
DIRAC.exit( -1 )
if not os.path.isfile( PFN ):
gLogger.error( "%s is not a file" % PFN )
DIRAC.exit( -1 )
PFN = os.path.abspath( PFN )
size = os.path.getsize( PFN )
adler32 = fileAdler( PFN )
request = Request()
req... | from DIRAC.RequestManagementSystem.Client.ReqClient import ReqClient
from DIRAC.Core.Utilities.Adler import fileAdler
| random_line_split |
__init__.py | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from flask.ext.redis import Redis
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
redis1 ... | redis1.init_app(app)
from .main import main as main_blueprint
# from .main.common import common
app.register_blueprint(main_blueprint)
# app.register_blueprint(common)
return app | random_line_split | |
__init__.py | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from flask.ext.redis import Redis
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
redis1 ... | (config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
app.config['REDIS_HOST'] = 'localhost'
app.config['REDIS_PORT'] = 6379
app.config['REDIS_DB'] = 0
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db... | create_app | identifier_name |
__init__.py | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config
from flask.ext.redis import Redis
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
redis1 ... | return app
| app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
app.config['REDIS_HOST'] = 'localhost'
app.config['REDIS_PORT'] = 6379
app.config['REDIS_DB'] = 0
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
... | identifier_body |
string_slice.py | print("123"[0:1])
print("123"[0:2])
print("123"[:1])
print("123"[1:])
# Idiom for copying sequence
print("123"[:])
print("123"[:-1])
# Weird cases
print("123"[0:0])
print("123"[1:0])
print("123"[1:1])
print("123"[-1:-1])
print("123"[-3:])
print("123"[-3:3]) | # Range check testing, don't segfault, please ;-)
print("123"[:1000000])
print("123"[1000000:])
print("123"[:-1000000])
print("123"[-1000000:])
# No IndexError!
print(""[1:1])
print(""[-1:-1])
# bytes
print(b"123"[0:2]) | print("123"[0:])
print("123"[:0])
print("123"[:-3])
print("123"[:-4]) | random_line_split |
test_cheat_sheet_plus.py | """The macros below aren't reliable (e.g., some fail if ``arg_string`` is `None`)
or safe (``include`` doesn't guard against circular reference). For a more complete example, see
`the code used in the sandbox <http://code.google.com/p/urlminer/source/browse/examples/wiki/macros.py>`_.
"""
import genshi.builder as... |
assert template % text2html(text) == rendered | random_line_split | |
test_cheat_sheet_plus.py | """The macros below aren't reliable (e.g., some fail if ``arg_string`` is `None`)
or safe (``include`` doesn't guard against circular reference). For a more complete example, see
`the code used in the sandbox <http://code.google.com/p/urlminer/source/browse/examples/wiki/macros.py>`_.
"""
import genshi.builder as... | (arg_string,body,isblock):
page = Page(arg_string.strip())
return bldr.tag.pre(page.get_raw_body(),class_='plain')
def include_source(arg_string,body,isblock):
page = Page(arg_string.strip())
return bldr.tag.pre(text2html.render(page.get_raw_body()))
def source(arg_string,body,isblock):
r... | include_raw | identifier_name |
test_cheat_sheet_plus.py | """The macros below aren't reliable (e.g., some fail if ``arg_string`` is `None`)
or safe (``include`` doesn't guard against circular reference). For a more complete example, see
`the code used in the sandbox <http://code.google.com/p/urlminer/source/browse/examples/wiki/macros.py>`_.
"""
import genshi.builder as... |
else:
return page_name
## Start of macros
def include(arg_string,body,isblock):
page = Page(arg_string.strip())
return text2html.generate(page.get_raw_body())
def include_raw(arg_string,body,isblock):
page = Page(arg_string.strip())
return bldr.tag.pre(page.get_raw_body()... | return 'FrontPage' | conditional_block |
test_cheat_sheet_plus.py | """The macros below aren't reliable (e.g., some fail if ``arg_string`` is `None`)
or safe (``include`` doesn't guard against circular reference). For a more complete example, see
`the code used in the sandbox <http://code.google.com/p/urlminer/source/browse/examples/wiki/macros.py>`_.
"""
import genshi.builder as... |
def get_raw_body(self):
try:
f = open(os.path.join(self.root,self.name + '.txt'),'r')
s = f.read()
f.close()
return s
except IOError:
return None
def exists(self):
try:
f = open(os.path.join(self.root... | self.name = page_name | identifier_body |
NavigationHeader.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* Facebook,... | key={name + '_' + key}
style={[
styles[name],
{ marginTop: this.props.statusBarHeight },
styleInterpolator(props),
]}>
{subView}
</Animated.View>
);
}
static HEIGHT = APPBAR_HEIGHT + STATUSBAR_HEIGHT;
static Title = NavigationHeaderTitle;
... | const pointerEvents = offset !== 0 || isStale ? 'none' : 'box-none';
return (
<Animated.View
pointerEvents={pointerEvents} | random_line_split |
NavigationHeader.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* Facebook,... | extends React.Component<DefaultProps, Props, any> {
props: Props;
static defaultProps = {
renderTitleComponent: (props: SubViewProps) => {
const title = String(props.scene.route.title || '');
return <NavigationHeaderTitle>{title}</NavigationHeaderTitle>;
},
renderLeftComponent: (props: S... | NavigationHeader | identifier_name |
NavigationHeader.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* Facebook,... |
const subViewProps = {...props, onNavigateBack: this.props.onNavigateBack};
const subView = renderer(subViewProps);
if (subView === null) {
return null;
}
const pointerEvents = offset !== 0 || isStale ? 'none' : 'box-none';
return (
<Animated.View
pointerEvents={pointerEve... | {
// Scene is far away from the active scene. Hides it to avoid unnecessary
// rendering.
return null;
} | conditional_block |
privileges.js | * 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful... | /**
* PhilaeCMS
* Copyright (C) 2014 Daniel Budick
* | random_line_split | |
010-libphotofloat.js | (function() {
/* constructor */
function PhotoFloat() {
this.albumCache = [];
}
/* public member functions */
PhotoFloat.prototype.album = function(subalbum, callback, error) {
var cacheKey, ajaxOptions, self;
if (typeof subalbum.photos !== "undefined" && subalbum.photos !== null) {
callback(subalbum);
... | PhotoFloat.prototype.cleanHash = PhotoFloat.cleanHash;
/* expose class globally */
window.PhotoFloat = PhotoFloat;
}()); | PhotoFloat.prototype.trimExtension = PhotoFloat.trimExtension; | random_line_split |
010-libphotofloat.js | (function() {
/* constructor */
function PhotoFloat() |
/* public member functions */
PhotoFloat.prototype.album = function(subalbum, callback, error) {
var cacheKey, ajaxOptions, self;
if (typeof subalbum.photos !== "undefined" && subalbum.photos !== null) {
callback(subalbum);
return;
}
if (Object.prototype.toString.call(subalbum).slice(8, -1) === "Stri... | {
this.albumCache = [];
} | identifier_body |
010-libphotofloat.js | (function() {
/* constructor */
function | () {
this.albumCache = [];
}
/* public member functions */
PhotoFloat.prototype.album = function(subalbum, callback, error) {
var cacheKey, ajaxOptions, self;
if (typeof subalbum.photos !== "undefined" && subalbum.photos !== null) {
callback(subalbum);
return;
}
if (Object.prototype.toString.call(s... | PhotoFloat | identifier_name |
league.js | import {LEAGUE_BY_SUMMONER_FULL, LEAGUE_BY_SUMMONER, LEAGUE_BY_TEAM_FULL, LEAGUE_BY_TEAM, CHALLENGER_LEAGUE} from '../Constants';
export const League = {
getBySummonerId(summonerId, options) {
return Object.assign({}, options, {
id: summonerId,
uri: LEAGUE_BY_SUMMONER_FULL
});
},
getEntriesB... | ,
getByTeamId(teamId, options) {
return Object.assign({}, options, {
id: teamId,
uri: LEAGUE_BY_TEAM_FULL
});
},
getEntriesByTeamId(teamId, options) {
return Object.assign({}, options, {
id: teamId,
uri: LEAGUE_BY_TEAM
});
},
getChallenger(type, options) {
return... | {
return Object.assign({}, options, {
id: summonerId,
uri: LEAGUE_BY_SUMMONER
});
} | identifier_body |
league.js | import {LEAGUE_BY_SUMMONER_FULL, LEAGUE_BY_SUMMONER, LEAGUE_BY_TEAM_FULL, LEAGUE_BY_TEAM, CHALLENGER_LEAGUE} from '../Constants';
export const League = {
getBySummonerId(summonerId, options) {
return Object.assign({}, options, {
id: summonerId,
uri: LEAGUE_BY_SUMMONER_FULL
});
},
getEntriesB... | uri: LEAGUE_BY_TEAM_FULL
});
},
getEntriesByTeamId(teamId, options) {
return Object.assign({}, options, {
id: teamId,
uri: LEAGUE_BY_TEAM
});
},
getChallenger(type, options) {
return Object.assign({}, options, {
uri: CHALLENGER_LEAGUE,
query: {
type: type ... | },
getByTeamId(teamId, options) {
return Object.assign({}, options, {
id: teamId, | random_line_split |
league.js | import {LEAGUE_BY_SUMMONER_FULL, LEAGUE_BY_SUMMONER, LEAGUE_BY_TEAM_FULL, LEAGUE_BY_TEAM, CHALLENGER_LEAGUE} from '../Constants';
export const League = {
getBySummonerId(summonerId, options) {
return Object.assign({}, options, {
id: summonerId,
uri: LEAGUE_BY_SUMMONER_FULL
});
},
getEntriesB... | (teamId, options) {
return Object.assign({}, options, {
id: teamId,
uri: LEAGUE_BY_TEAM_FULL
});
},
getEntriesByTeamId(teamId, options) {
return Object.assign({}, options, {
id: teamId,
uri: LEAGUE_BY_TEAM
});
},
getChallenger(type, options) {
return Object.assign({... | getByTeamId | identifier_name |
sftp_client.py | #!/usr/bin/env python3.4
#
# Copyright (c) 2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/... | ():
with (yield from asyncssh.connect('localhost')) as conn:
with (yield from conn.start_sftp_client()) as sftp:
yield from sftp.get('example.txt')
try:
asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
sys.exit('SFTP operation failed: ' ... | run_client | identifier_name |
sftp_client.py | #!/usr/bin/env python3.4
#
# Copyright (c) 2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/... |
try:
asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
sys.exit('SFTP operation failed: ' + str(exc))
| with (yield from asyncssh.connect('localhost')) as conn:
with (yield from conn.start_sftp_client()) as sftp:
yield from sftp.get('example.txt') | identifier_body |
sftp_client.py | #!/usr/bin/env python3.4
#
# Copyright (c) 2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/... |
try:
asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
sys.exit('SFTP operation failed: ' + str(exc)) | @asyncio.coroutine
def run_client():
with (yield from asyncssh.connect('localhost')) as conn:
with (yield from conn.start_sftp_client()) as sftp:
yield from sftp.get('example.txt') | random_line_split |
extractor.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with
// this file, You can obtain one at https://mozilla.org/MPL/2.0/.
use message::Message;
use error::{Error, Result};
use common::{find_string, escape_string};
use std::collections::H... | () -> Extractor {
Extractor {
messages: HashMap::new(),
orig_strings: HashMap::new(),
}
}
/// Returns a hashmap mapping the original strings (as used by `lformat!`)
/// to escaped strings. Only contains strings that are different and
/// must thus be handled.
... | new | identifier_name |
extractor.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with
// this file, You can obtain one at https://mozilla.org/MPL/2.0/.
use message::Message;
use error::{Error, Result};
use common::{find_string, escape_string};
use std::collections::H... |
if self.messages.contains_key(msg.as_str()) {
self.messages.get_mut(&msg).unwrap().add_source(filename.as_str(), line);
} else {
let mut message = Message::new(msg.as_str());
message.add_source(filename.as_str(), line);
... | {
self.orig_strings.insert(orig_msg, msg.clone());
} | conditional_block |
extractor.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with
// this file, You can obtain one at https://mozilla.org/MPL/2.0/.
use message::Message;
use error::{Error, Result};
use common::{find_string, escape_string};
use std::collections::H... |
if self.messages.contains_key(msg.as_str()) {
self.messages.get_mut(&msg).unwrap().add_source(filename.as_str(), line);
} else {
let mut message = Message::new(msg.as_str());
message.add_source(filename.as_str(), line);
... | random_line_split | |
vulkano_gralloc.rs | };
use vulkano::instance::{Instance, InstanceCreationError, InstanceExtensions, Version};
use vulkano::memory::{
DedicatedAlloc, DeviceMemoryAllocError, DeviceMemoryBuilder, DeviceMemoryMapping,
ExternalMemoryHandleType, MemoryRequirements,
};
use vulkano::memory::pool::AllocFromRequirementsFilter;
use vulka... | use vulkano::device::{Device, DeviceCreationError, DeviceExtensions};
use vulkano::image::{
sys, ImageCreateFlags, ImageCreationError, ImageDimensions, ImageUsage, SampleCount, | random_line_split | |
vulkano_gralloc.rs | , size: usize) -> VulkanoMapping {
VulkanoMapping { mapping, size }
}
}
unsafe impl MappedRegion for VulkanoMapping {
/// Used for passing this region for hypervisor memory mappings. We trust crosvm to use this
/// safely.
fn as_ptr(&self) -> *mut u8 {
unsafe { self.mapping.as_ptr() }
... |
fn get_image_memory_requirements(
&mut self,
info: ImageAllocationInfo,
) -> RutabagaResult<ImageMemoryRequirements> {
let mut reqs: ImageMemoryRequirements = Default::default();
let (unsafe_image, memory_requirements) = unsafe { self.create_image(info)? };
let device... | {
for device in self.devices.values() {
if !device.enabled_extensions().ext_external_memory_dma_buf {
return false;
}
}
true
} | identifier_body |
vulkano_gralloc.rs | , size: usize) -> VulkanoMapping {
VulkanoMapping { mapping, size }
}
}
unsafe impl MappedRegion for VulkanoMapping {
/// Used for passing this region for hypervisor memory mappings. We trust crosvm to use this
/// safely.
fn as_ptr(&self) -> *mut u8 {
unsafe { self.mapping.as_ptr() }
... | (&self) -> bool {
for device in self.devices.values() {
if !device.enabled_extensions().ext_external_memory_dma_buf {
return false;
}
}
true
}
fn get_image_memory_requirements(
&mut self,
info: ImageAllocationInfo,
) -> Rutaba... | supports_dmabuf | identifier_name |
config.py | """
flist = cp.get("formatters", "keys")
if not len(flist):
return {}
flist = string.split(flist, ",")
flist = _strip_spaces(flist)
formatters = {}
for form in flist:
sectname = "formatter_%s" % form
opts = cp.options(sectname)
if "format" in opts:
... | server = rcvr(port=port, handler=hdlr)
global _listener
logging._acquireLock()
_listener = server
logging._releaseLock()
server.serve_until_stopped() | identifier_body | |
config.py | (C) 2001-2008 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away!
"""
import sys, logging, logging.handlers, string, socket, struct, os, traceback, types
try:
import thread
import threading
except ImportError:
thread = None
from SocketServer import ThreadingTCPS... |
for h in root.handlers[:]:
root.removeHandler(h)
hlist = cp.get(sectname, "handlers")
if len(hlist):
hlist = string.split(hlist, ",")
hlist = _strip_spaces(hlist)
for hand in hlist:
log.addHandler(handlers[hand])
#and now the others...
#we don... | level = cp.get(sectname, "level")
log.setLevel(logging._levelNames[level]) | conditional_block |
config.py | (C) 2001-2008 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away!
"""
import sys, logging, logging.handlers, string, socket, struct, os, traceback, types
try:
import thread
import threading
except ImportError:
thread = None
from SocketServer import ThreadingTCPS... | (cp, formatters):
"""Install and return handlers"""
hlist = cp.get("handlers", "keys")
if not len(hlist):
return {}
hlist = string.split(hlist, ",")
hlist = _strip_spaces(hlist)
handlers = {}
fixups = [] #for inter-handler references
for hand in hlist:
sectname ... | _install_handlers | identifier_name |
config.py | (C) 2001-2008 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away!
"""
import sys, logging, logging.handlers, string, socket, struct, os, traceback, types
try:
import thread
import threading
except ImportError:
thread = None
from SocketServer import ThreadingTCPS... | for h, t in fixups:
h.setTarget(handlers[t])
return handlers
def _install_loggers(cp, handlers, disable_existing_loggers):
"""Create and install loggers"""
# configure the root first
llist = cp.get("loggers", "keys")
llist = string.split(llist, ",")
llist = map(lambda x... | handlers[hand] = h
#now all handlers are loaded, fixup inter-handler references...
| random_line_split |
delete-droplet.spec.ts | import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { createContext } from '../../common';
import {deleteDroplet} from './delete-droplet';
import * as MOCK from './delete-droplet.mock';
describe('droplet', () => {
const DROPLET_ID = 123;
const URL = `/droplets/${DROPLET_ID}`;
const TO... | const context = createContext({
axios,
token: TOKEN,
});
beforeEach(() => {
mock.resetHistory();
});
describe('delete-droplet', () => {
it('should be a fn', () => {
expect(typeof deleteDroplet).toBe('function');
});
it('should return a fn', () => {
expect(typeof deleteDropl... | undefined,
MOCK.response.headers,
); | random_line_split |
test_worker.py | # -*- coding: utf-8 -*-
import unittest
from zombase import worker
class FakeDbSession(object):
def | (self):
self.has_been_committed = False
def commit(self):
self.has_been_committed = True
class FakeForeman(object):
def __init__(self):
self._dbsession = FakeDbSession()
class FakeMapping(object):
a_prop = 12
a_req_prop = 'bla'
class BaseTestWorker(unittest.TestCase):
... | __init__ | identifier_name |
test_worker.py | # -*- coding: utf-8 -*-
import unittest
from zombase import worker
class FakeDbSession(object):
def __init__(self):
self.has_been_committed = False
def commit(self):
self.has_been_committed = True
class FakeForeman(object):
def __init__(self):
self._dbsession = FakeDbSession()... |
class BaseTestWorker(unittest.TestCase):
def setUp(self):
self.dbsession = FakeDbSession()
def tearDown(self):
del self.dbsession
class TestRawWorker(BaseTestWorker):
def test_init(self):
worker.RawWorker(self.dbsession)
class TestSupervisedWorker(BaseTestWorker):
def ... | a_prop = 12
a_req_prop = 'bla' | identifier_body |
test_worker.py | # -*- coding: utf-8 -*-
import unittest
from zombase import worker
class FakeDbSession(object):
def __init__(self):
self.has_been_committed = False
def commit(self):
self.has_been_committed = True
class FakeForeman(object):
def __init__(self):
self._dbsession = FakeDbSession()... | foreman,
managed_sqla_map=FakeMapping,
managed_sqla_map_name='fake',
)
a_worker._get(sqla_obj=FakeMapping()) | foreman = FakeForeman()
a_worker = worker.MappingManagingWorker( | random_line_split |
functions_6f.js | var searchData=
[ | ['operator_21_3d',['operator!=',['../struct_a_c_t_k_1_1_color.html#a7c06f24e8d2e0f88a5c4c63e2639d6f0',1,'ACTK::Color::operator!=()'],['../struct_a_c_t_k_1_1_color_mask.html#aee46d6e92b1005a9ec6f4a1204fefd69',1,'ACTK::ColorMask::operator!=()'],['../struct_a_c_t_k_1_1_clear_state.html#ab13fc63ba272b07bbdb857d5454754e9'... | random_line_split | |
fileService.ts | > {
// 1.) create folder
let absolutePath = this.toAbsolutePath(resource);
return pfs.mkdirp(absolutePath).then(() => {
// 2.) resolve
return this.resolve(resource);
});
}
public rename(resource: uri, newName: string): TPromise<IFileStat> {
let newPath = paths.join(paths.dirname(resource.fsPath), n... | {
return pfs.stat(absolutePath).then((stat: fs.Stats) => {
if (stat.isDirectory()) {
return TPromise.wrapError(new Error('Expected file is actually a directory'));
}
// Dirty write prevention
if (typeof options.mtime === 'number' && typeof options.etag === 'string' && options.mtime < stat... | conditional_block | |
fileService.ts | .resolveFileStreamContent(resource, etag, enc));
}
private doResolveContent<T extends IBaseStat>(resource: uri, options: IResolveContentOptions, contentResolver: (resource: uri, etag?: string, enc?: string) => TPromise<T>): TPromise<T> {
let absolutePath = this.toAbsolutePath(resource);
// 1.) detect mimes
re... | (resource: uri, newName: string): TPromise<IFileStat> {
let newPath = paths.join(paths.dirname(resource.fsPath), newName);
return this.moveFile(resource, uri.file(newPath));
}
public moveFile(source: uri, target: uri, overwrite?: boolean): TPromise<IFileStat> {
return this.moveOrCopyFile(source, target, false... | rename | identifier_name |
fileService.ts | .resolveFileStreamContent(resource, etag, enc));
}
private doResolveContent<T extends IBaseStat>(resource: uri, options: IResolveContentOptions, contentResolver: (resource: uri, etag?: string, enc?: string) => TPromise<T>): TPromise<T> {
let absolutePath = this.toAbsolutePath(resource);
// 1.) detect mimes
re... |
public rename(resource: uri, newName: string): TPromise<IFileStat> {
let newPath = paths.join(paths.dirname(resource.fsPath), newName);
return this.moveFile(resource, uri.file(newPath));
}
public moveFile(source: uri, target: uri, overwrite?: boolean): TPromise<IFileStat> {
return this.moveOrCopyFile(sourc... | {
// 1.) create folder
let absolutePath = this.toAbsolutePath(resource);
return pfs.mkdirp(absolutePath).then(() => {
// 2.) resolve
return this.resolve(resource);
});
} | identifier_body |
fileService.ts | : TPromise<void>;
// Write fast if we do UTF 8 without BOM
if (!addBom && encodingToWrite === encoding.UTF8) {
writeFilePromise = pfs.writeFile(absolutePath, value, encoding.UTF8);
}
// Otherwise use encoding lib
else {
let encoded = encoding.encode(value, encodingToWrite, { addBO... |
private checkFile(absolutePath: string, options: IUpdateContentOptions): TPromise<boolean /* exists */> { | random_line_split | |
opts.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | use extra::getopts;
let args = args.tail();
let opts = ~[
getopts::optflag("c"), // CPU rendering
getopts::optopt("o"), // output file
getopts::optopt("r"), // rendering backend
getopts::optopt("s"), // size of tiles
getopts::optopt("t"), ... | random_line_split | |
opts.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | (args: &[~str]) -> Opts {
use extra::getopts;
let args = args.tail();
let opts = ~[
getopts::optflag("c"), // CPU rendering
getopts::optopt("o"), // output file
getopts::optopt("r"), // rendering backend
getopts::optopt("s"), // size of tiles
... | from_cmdline_args | identifier_name |
opts.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... |
}
None => SkiaBackend
};
let tile_size: uint = match opt_match.opt_str("s") {
Some(tile_size_str) => FromStr::from_str(tile_size_str).unwrap(),
None => 512,
};
let n_render_threads: uint = match opt_match.opt_str("t") {
Some(n_render_threads_str) => FromStr::fr... | {
fail!(~"unknown backend type")
} | conditional_block |
opts.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Configuration options for a single run of the servo application. Created
//! from command line arguments.
use... | let urls = if opt_match.free.is_empty() {
fail!(~"servo asks that you provide 1 or more URLs")
} else {
opt_match.free.clone()
};
let render_backend = match opt_match.opt_str("r") {
Some(backend_str) => {
if backend_str == ~"direct2d" {
Direct2DBacken... | {
use extra::getopts;
let args = args.tail();
let opts = ~[
getopts::optflag("c"), // CPU rendering
getopts::optopt("o"), // output file
getopts::optopt("r"), // rendering backend
getopts::optopt("s"), // size of tiles
getopts::optopt("t"), ... | identifier_body |
partial_ord.rs | 3 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 http://opensourc... | (cx: &mut ExtCtxt,
span: Span,
op: OrderingOp,
self_arg_tags: &[ast::Ident]) -> P<ast::Expr> {
let lft = cx.expr_ident(span, self_arg_tags[0]);
let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1]));
... | some_ordering_collapsed | identifier_name |
partial_ord.rs | 3 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 http://opensourc... | let ordering_ty = Literal(path_std!(cx, core::cmp::Ordering));
let ret_ty = Literal(Path::new_(pathvec_std!(cx, core::option::Option),
None,
vec![Box::new(ordering_ty)],
true));
let inline = cx.meta_... | {
macro_rules! md {
($name:expr, $op:expr, $equal:expr) => { {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
MethodDef {
name: $name,
generics: LifetimeBounds::empty(),
... | identifier_body |
partial_ord.rs | 13 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 http://opensour... | FIXME #6449: These `if`s could/should be `match`es.
*/
cs_fold(
// foldr nests the if-elses correctly, leaving the first field
// as the outermost one, and the last as the innermost.
false,
|cx, span, old, self_f, other_fs| {
// let __test = new;
// if... | }
} else {
__test
}
| random_line_split |
Generate_text.py | import time
import numpy as np
from collections import Counter
from collections import defaultdict
import matplotlib.pyplot as plt
def unzip(pairs):
"""
Splits list of pairs (tuples) into separate lists
Parameter(s)
--------------
pairs(list of tuples):
List of pairs to be split
... | List containing the second term of all pairs
Example(s)
--------------
pairs = [("a", 1), ("b", 2)] --> ["a", "b"] and [1, 2]
"""
return tuple(zip(*pairs))
def normalize(counter):
"""
Convert counter to a list of (letter, frequency) pairs, sorted in descendi... | --------------
list 1:
List containing the first term of all pairs
list 2: | random_line_split |
Generate_text.py | import time
import numpy as np
from collections import Counter
from collections import defaultdict
import matplotlib.pyplot as plt
def unzip(pairs):
|
"""
return tuple(zip(*pairs))
def normalize(counter):
"""
Convert counter to a list of (letter, frequency) pairs, sorted in descending order of frequency
Parameter(s)
--------------
counter (Counter-instance):
Counter to be converted. Letters and their # of occurren... | """
Splits list of pairs (tuples) into separate lists
Parameter(s)
--------------
pairs(list of tuples):
List of pairs to be split
Return(s)
--------------
list 1:
List containing the first term of all pairs
list 2:
List containing the second te... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.