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 |
|---|---|---|---|---|
macros.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/. */
/// See docs of the `procedural-masquerade` crate.
define_invoke_proc_macro!(cssparser_internal__invoke_proc_macro... | a>(buffer: &'a mut [u8], input: &'a str) -> Option<&'a str> {
if let Some(buffer) = buffer.get_mut(..input.len()) {
if let Some(first_uppercase) = input.bytes().position(|byte| matches!(byte, b'A'...b'Z')) {
buffer.copy_from_slice(input.as_bytes());
::std::ascii::AsciiExt::make_ascii... | nternal__to_lowercase<' | identifier_name |
macros.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/. */
/// See docs of the `procedural-masquerade` crate.
define_invoke_proc_macro!(cssparser_internal__invoke_proc_macro... | #[cfg(feature = "dummy_match_byte")]
macro_rules! match_byte {
($value:expr, $($rest:tt)* ) => {
match $value {
$(
$rest
)+
}
};
}
| if let Some(buffer) = buffer.get_mut(..input.len()) {
if let Some(first_uppercase) = input.bytes().position(|byte| matches!(byte, b'A'...b'Z')) {
buffer.copy_from_slice(input.as_bytes());
::std::ascii::AsciiExt::make_ascii_lowercase(&mut buffer[first_uppercase..]);
// `bu... | identifier_body |
macros.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/. */
/// See docs of the `procedural-masquerade` crate.
define_invoke_proc_macro!(cssparser_internal__invoke_proc_macro... | ( $input:expr, $( $match_body:tt )* ) => {
{
cssparser_internal__invoke_proc_macro! {
cssparser_internal__assert_ascii_lowercase__max_len!( $( $match_body )* )
}
{
// MAX_LENGTH is generated by cssparser_internal__assert_ascii_lowercase__m... | /// # fn parse_hsla(_: RangeFull) -> Result<(), String> { Ok(()) }
/// ```
#[macro_export]
macro_rules! match_ignore_ascii_case { | random_line_split |
macros.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/. */
/// See docs of the `procedural-masquerade` crate.
define_invoke_proc_macro!(cssparser_internal__invoke_proc_macro... | lse {
// Input is already lower-case
Some(input)
}
} else {
// Input is longer than buffer, which has the length of the longest expected string:
// none of the expected strings would match.
None
}
}
#[cfg(feature = "dummy_match_byte")]
macro_rules! match_... | buffer.copy_from_slice(input.as_bytes());
::std::ascii::AsciiExt::make_ascii_lowercase(&mut buffer[first_uppercase..]);
// `buffer` was initialized to a copy of `input` (which is &str so well-formed UTF-8)
// then lowercased (which preserves UTF-8 well-formedness)
... | conditional_block |
thrift_build.rs | // @generated by autocargo
use std::env;
use std::fs;
use std::path::Path;
use thrift_compiler::Config;
#[rustfmt::skip]
fn main() {
// Rerun if this gets rewritten.
println!("cargo:rerun-if-changed=thrift_build.rs");
let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR env not provided");
let out_di... |
let include_srcs = vec![
];
conf.include_srcs(include_srcs);
conf
};
conf
.run(&[
"eden_config.thrift"
])
.expect("Failed while running thrift compilation");
}
| {
conf.options(options);
} | conditional_block |
thrift_build.rs | // @generated by autocargo
use std::env;
use std::fs;
use std::path::Path;
use thrift_compiler::Config;
#[rustfmt::skip]
fn main() | .canonicalize()
.expect("Failed to canonicalize base_path");
// TODO: replace canonicalize() with std::path::absolute() when
// https://github.com/rust-lang/rust/pull/91673 is available (~Rust 1.60)
// and remove this block.
#[cfg(windows)]
let base_path =... | {
// Rerun if this gets rewritten.
println!("cargo:rerun-if-changed=thrift_build.rs");
let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR env not provided");
let out_dir: &Path = out_dir.as_ref();
fs::write(
out_dir.join("cratemap"),
"eden_config crate",
).expect("Failed to wr... | identifier_body |
thrift_build.rs | // @generated by autocargo
use std::env;
use std::fs;
use std::path::Path;
use thrift_compiler::Config;
#[rustfmt::skip]
fn main() {
// Rerun if this gets rewritten.
println!("cargo:rerun-if-changed=thrift_build.rs");
let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR env not provided");
let out_di... | let include_srcs = vec![
];
conf.include_srcs(include_srcs);
conf
};
conf
.run(&[
"eden_config.thrift"
])
.expect("Failed while running thrift compilation");
} | conf.options(options);
}
| random_line_split |
thrift_build.rs | // @generated by autocargo
use std::env;
use std::fs;
use std::path::Path;
use thrift_compiler::Config;
#[rustfmt::skip]
fn | () {
// Rerun if this gets rewritten.
println!("cargo:rerun-if-changed=thrift_build.rs");
let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR env not provided");
let out_dir: &Path = out_dir.as_ref();
fs::write(
out_dir.join("cratemap"),
"eden_config crate",
).expect("Failed to... | main | identifier_name |
utils_disk.py | 2) Parse the ini file with config parser
3) Modify the identifier of the default session that is going to be
executed on the config parser object
4) Re-write the config file to the disk
"""
self._copy_virtio_drivers(virtio_floppy)
txtsetup_oem = os.path.join(self.moun... | compare | identifier_name | |
utils_disk.py | ('Defaults', 'SCSI', virtio_oemsetup_id)
fp = open(txtsetup_oem, 'w')
parser.write(fp)
fp.close()
def setup_virtio_win2008(self, virtio_floppy):
"""
Setup the install floppy with the virtio storage drivers, win2008 style.
Win2008, Vista and 7 require peo... | self.g.umount_all() | conditional_block | |
utils_disk.py | os.makedirs(dst_dir)
for _ in files:
if _ in ignore:
continue
src_file = os.path.join(root, _)
dst_file = os.path.join(dst_dir, _)
if os.path.exists(dst_file):
if overwrite:
os.remove(dst_file)
... | for root, dirs, files in os.walk(src):
dst_dir = root.replace(src, dst)
if not os.path.exists(dst_dir): | random_line_split | |
utils_disk.py | return session.cmd_status(cmd, safe=True) == 0
return process.system(cmd, verbose=verbose) == 0
def umount(src, dst, fstype=None, verbose=False, session=None):
"""
Umount src from dst, if src really mounted under dst.
:param src: source device or directory
:param dst: mountpoint
:para... | mnt_pnt = tempfile.mkdtemp(prefix='cdrom_virtio_', dir=self.tmpdir)
mount(cdrom_virtio, mnt_pnt, options='loop,ro', verbose=DEBUG)
try:
copytree(mnt_pnt, self.mount, ignore='*.vfd')
cmd = 'mcopy -s -o -n -i %s ::/* %s' % (virtio_floppy, self.mount)
process.run... | """
Represents a CDROM disk that we can master according to our needs.
"""
def __init__(self, path, tmpdir):
self.mount = tempfile.mkdtemp(prefix='cdrom_virttest_', dir=tmpdir)
self.tmpdir = tmpdir
self.path = path
clean_old_image(path)
if not os.path.isdir(os.path.d... | identifier_body |
readline.js | 'use strict';
module.exports = function () {
var self = {
_ttyWrite : function (code, key) { this.ttyWrite.push({ code : code, key : key }); }
, _moveCursor : function (arg) { this.moveCursor.push(arg); }
, _wordLeft : function () { this.wordLeft++; }
, _wordRight : ... |
, _line : function () { this.lines++; }
, reset: function () {
this.ttyWrite = [];
this.moveCursor = [];
this.wordLeft = 0;
this.wordRight = 0;
this.deleteLeft = 0;
this.deleteRight = 0;
this.deleteWordLeft = 0;
... | random_line_split | |
app.component.spec.ts | /* tslint:disable:no-unused-variable */
import { AppComponent } from './app.component';
import {
it,
iit,
xit,
describe,
ddescribe,
xdescribe,
expect,
fakeAsync,
tick,
beforeEach,
inject,
injectAsync,
withProviders,
beforeEachProviders,
TestComponentBuilder
} from 'angular2/testing';
imp... | }));
it('should have expected <h1> text',
injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb.createAsync(AppComponent).then(fixture => {
// fixture.detectChanges(); // need for a binding; we don't have one
let h1 = fixture.debugElement.query(el =... | injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb.createAsync(AppComponent).then(fixture => {
expect(fixture.componentInstance instanceof AppComponent).toBe(true, 'should create AppComponent');
}); | random_line_split |
test_keyboard_interrupt.py | # Copyright 2016 Red Hat, Inc.
#
# 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... |
# pylint: disable=import-outside-toplevel
# isort: LOCAL
from stratis_cli._actions import _data
# pylint: disable=protected-access
stratis_cli._actions._data.Manager.Properties.Version.Get = (
raise_keyboard_interrupt
)
with self.assertRaises(Keybo... | """
Just raise the interrupt.
"""
raise KeyboardInterrupt() | identifier_body |
test_keyboard_interrupt.py | # Copyright 2016 Red Hat, Inc.
#
# 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... | (_):
"""
Just raise the interrupt.
"""
raise KeyboardInterrupt()
# pylint: disable=import-outside-toplevel
# isort: LOCAL
from stratis_cli._actions import _data
# pylint: disable=protected-access
stratis_cli._actions._data.Manager... | raise_keyboard_interrupt | identifier_name |
test_keyboard_interrupt.py | # Copyright 2016 Red Hat, Inc.
#
# 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... | at the calling method generated by dbus-python-client-gen.
"""
def raise_keyboard_interrupt(_):
"""
Just raise the interrupt.
"""
raise KeyboardInterrupt()
# pylint: disable=import-outside-toplevel
# isort: LOCAL
from stra... | The KeyboardInterrupt is most likely raised in the dbus-python
method which is actually communicating on the D-Bus, but it is
fairly difficult to get at that method. Instead settle for getting | random_line_split |
last_n_window_collector.py | ## @package last_n_window_collector
# Module caffe2.python.layers.last_n_window_collector
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, schema
from caffe2.python.layers.layers import M... |
self.next_blob = self.create_param(
param_name='next',
shape=[],
initializer=('ConstantFill',
{'value': 0, 'dtype': core.DataType.INT32}),
optimizer=model.NoOptim
)
self.mutex = self.create_param(
param_name='... | """
Collect last-N samples from input record. If you have complex data,
use PackRecords to pack it before using this layer.
This layer is not thread safe.
"""
def __init__(self, model, input_record, num_to_collect,
name='last_n_window_collector', **kwargs):
super(LastNWind... | identifier_body |
last_n_window_collector.py | ## @package last_n_window_collector
# Module caffe2.python.layers.last_n_window_collector
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, schema
from caffe2.python.layers.layers import M... | self.mutex = self.create_param(
param_name='mutex',
shape=None,
initializer=('CreateMutex',),
optimizer=model.NoOptim,
)
self.num_visited_blob = self.create_param(
param_name='num_visited',
shape=[],
initializer... | {'value': 0, 'dtype': core.DataType.INT32}),
optimizer=model.NoOptim
)
| random_line_split |
last_n_window_collector.py | ## @package last_n_window_collector
# Module caffe2.python.layers.last_n_window_collector
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, schema
from caffe2.python.layers.layers import M... | (self, net):
net.LastNWindowCollector(
[self.last_n, self.next_blob, self.input_record(), self.mutex,
self.num_visited_blob],
[self.last_n, self.next_blob, self.num_visited_blob],
num_to_collect=self.num_to_collect,
)
| add_ops | identifier_name |
checks.py | # Copyright (c) 2016, GohighSec
# 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 la... | # the call must have arguments
if not len(node.args):
return super(CheckLoggingFormatArgs, self).generic_visit(node)
# any argument should not be a tuple
for arg in node.args:
if isinstance(arg, ast.Tuple):
self.add_err... | random_line_split | |
checks.py | # Copyright (c) 2016, GohighSec
# 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 la... |
def _check_call_names(self, call_node, names):
if isinstance(call_node, ast.Call):
if isinstance(call_node.func, ast.Name):
if call_node.func.id in names:
return True
return False
class CheckLoggingFormatArgs(BaseASTChecker):
"""Check for impro... | """Add an error caused by a node to the list of errors for pep8."""
message = message or self.CHECK_DESC
error = (node.lineno, node.col_offset, message, self.__class__)
self._errors.append(error) | identifier_body |
checks.py | # Copyright (c) 2016, GohighSec
# 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 la... |
return obj_name + '.' + method_name
elif isinstance(node, six.string_types):
return node
else: # could be Subscript, Call or many more
return None
def visit_Call(self, node):
"""Look for the 'LOG.*' calls."""
# extract the obj_name and method_na... | return None | conditional_block |
checks.py | # Copyright (c) 2016, GohighSec
# 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 la... | (ast.NodeVisitor):
"""Provides a simple framework for writing AST-based checks.
Subclasses should implement visit_* methods like any other AST visitor
implementation. When they detect an error for a particular node the
method should call ``self.add_error(offending_node)``. Details about
where in th... | BaseASTChecker | identifier_name |
LoadApp.py | from .SlackIntegration import slackIntegration
import logging
from aiohttp import ClientSession
import asyncio
from time import perf_counter
class LoadApp():
def | (self):
self.logger = logging.getLogger('reliability')
self.app_visit_succeeded = 0
self.app_visit_failed = 0
self.tasks = []
async def get(self, url):
# To simulate differnt users accessing same app, do not reuse session
async with ClientSession() as session:
... | __init__ | identifier_name |
LoadApp.py | from .SlackIntegration import slackIntegration
import logging
from aiohttp import ClientSession
import asyncio
from time import perf_counter
class LoadApp():
def __init__(self):
self.logger = logging.getLogger('reliability')
self.app_visit_succeeded = 0
self.app_visit_failed = 0
se... | start = perf_counter()
loop.run_until_complete(asyncio.wait(loadApp.tasks))
end = perf_counter()
print(f"Perf of {concurrency} visits is: {end - start} second.") | random_line_split | |
LoadApp.py | from .SlackIntegration import slackIntegration
import logging
from aiohttp import ClientSession
import asyncio
from time import perf_counter
class LoadApp():
def __init__(self):
self.logger = logging.getLogger('reliability')
self.app_visit_succeeded = 0
self.app_visit_failed = 0
se... |
if __name__ == "__main__":
loadApp = LoadApp()
urls = ["https://www.google.com",]
concurrency = 10
loadApp.set_tasks(urls, concurrency)
loop = asyncio.get_event_loop()
start = perf_counter()
loop.run_until_complete(asyncio.wait(loadApp.tasks))
end = perf_counter()
print(f"Perf of {... | for url in urls:
for i in range(num):
task = asyncio.ensure_future(self.get(url))
self.tasks.append(task) | identifier_body |
LoadApp.py | from .SlackIntegration import slackIntegration
import logging
from aiohttp import ClientSession
import asyncio
from time import perf_counter
class LoadApp():
def __init__(self):
self.logger = logging.getLogger('reliability')
self.app_visit_succeeded = 0
self.app_visit_failed = 0
se... |
if __name__ == "__main__":
loadApp = LoadApp()
urls = ["https://www.google.com",]
concurrency = 10
loadApp.set_tasks(urls, concurrency)
loop = asyncio.get_event_loop()
start = perf_counter()
loop.run_until_complete(asyncio.wait(loadApp.tasks))
end = perf_counter()
print(f"Perf of {... | for i in range(num):
task = asyncio.ensure_future(self.get(url))
self.tasks.append(task) | conditional_block |
app.service.ts | import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
export interface InternalStateType {
[key: string]: any;
}
@Injectable()
export class AppState {
public idleTimeout = 5000;
public idleTimer: Subject<any> = new Subject();
public _state: InternalStateType = {};
private timeoutID;
c... |
}
| {
// simple object clone
return JSON.parse(JSON.stringify(object));
} | identifier_body |
app.service.ts | import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
export interface InternalStateType {
[key: string]: any;
}
@Injectable()
export class AppState {
public idleTimeout = 5000;
public idleTimer: Subject<any> = new Subject();
public _state: InternalStateType = {};
private timeoutID;
c... | (prop?: any) {
// use our state getter for the clone
const state = this.state;
return state.hasOwnProperty(prop) ? state[prop] : state;
}
public set(prop: string, value: any) {
// internally mutate our state
return (this._state[prop] = value);
}
public setupIdleTimer(idleTimeout) {
// c... | get | identifier_name |
app.service.ts | import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
export interface InternalStateType {
[key: string]: any;
}
@Injectable()
export class AppState {
public idleTimeout = 5000;
public idleTimer: Subject<any> = new Subject();
public _state: InternalStateType = {};
private timeoutID;
c... | public goInactive() {
// console.log('trying to go inative', this.idleTimer);
this.idleTimer.next({ idle: true });
}
public goActive(emit?: boolean) {
// TODO: Change the signature of the function to remove the emit param
// goActive should always make the app become active
// emit param is c... | random_line_split | |
issue-1049.rs | // Test overlong function signature
pub unsafe fn reborrow_mut(
&mut X: Abcde,
) -> Handle<NodeRef<marker::Mut, K, V, NodeType>, HandleType> {
}
pub fn merge(
mut X: Abcdef,
) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
}
impl Handle {
pub fn merge(
a: Abcd,
) -... |
}
// Long function without return type that should not be reformated.
fn veeeeeeeeeeeeeeeeeeeeery_long_name(a: FirstTypeeeeeeeeee, b: SecondTypeeeeeeeeeeeeeeeeeeeeeee) {}
fn veeeeeeeeeeeeeeeeeeeeeery_long_name(a: FirstTypeeeeeeeeee, b: SecondTypeeeeeeeeeeeeeeeeeeeeeee) {
}
fn veeeeeeeeeeeeeeeeeeeeeeery_long_name(
... | {
} | identifier_body |
issue-1049.rs | // Test overlong function signature
pub unsafe fn reborrow_mut(
&mut X: Abcde,
) -> Handle<NodeRef<marker::Mut, K, V, NodeType>, HandleType> {
}
pub fn | (
mut X: Abcdef,
) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
}
impl Handle {
pub fn merge(
a: Abcd,
) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
}
}
// Long function without return type that should not be reformated.
fn veeeeee... | merge | identifier_name |
issue-1049.rs | // Test overlong function signature
pub unsafe fn reborrow_mut(
&mut X: Abcde,
) -> Handle<NodeRef<marker::Mut, K, V, NodeType>, HandleType> {
}
|
impl Handle {
pub fn merge(
a: Abcd,
) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
}
}
// Long function without return type that should not be reformated.
fn veeeeeeeeeeeeeeeeeeeeery_long_name(a: FirstTypeeeeeeeeee, b: SecondTypeeeeeeeeeeeeeeeeeeeeeee) {}
fn veeeee... | pub fn merge(
mut X: Abcdef,
) -> Handle<NodeRef<marker::Mut<'a>, K, V, marker::Internal>, marker::Edge> {
} | random_line_split |
type_.rs | ::mem;
use std::ptr;
use std::cell::RefCell;
use libc::c_uint;
#[derive(Clone, Copy, PartialEq, Debug)]
#[repr(C)]
pub struct Type {
rf: TypeRef
}
macro_rules! ty {
($e:expr) => ( Type::from_ref(unsafe { $e }))
}
/// Wrapper for LLVM TypeRef
impl Type {
#[inline(always)]
pub fn from_ref(r: TypeRef) ... |
pub fn array_length(&self) -> usize {
unsafe {
llvm::LLVMGetArrayLength(self.to_ref()) as usize
}
}
pub fn field_types(&self) -> Vec<Type> {
unsafe {
let n_elts = llvm::LLVMCountStructElementTypes(self.to_ref()) as usize;
if n_elts == 0 {
... | {
unsafe {
llvm::LLVMGetVectorSize(self.to_ref()) as usize
}
} | identifier_body |
type_.rs | std::mem;
use std::ptr;
use std::cell::RefCell;
use libc::c_uint;
#[derive(Clone, Copy, PartialEq, Debug)]
#[repr(C)]
pub struct Type {
rf: TypeRef
}
macro_rules! ty {
($e:expr) => ( Type::from_ref(unsafe { $e }))
}
/// Wrapper for LLVM TypeRef
impl Type {
#[inline(always)]
pub fn from_ref(r: TypeR... | args.len() as c_uint, False))
}
pub fn variadic_func(args: &[Type], ret: &Type) -> Type {
let vec : &[TypeRef] = unsafe { mem::transmute(args) };
ty!(llvm::LLVMFunctionType(ret.to_ref(), vec.as_ptr(),
args.len() as c_uint, Tr... | pub fn func(args: &[Type], ret: &Type) -> Type {
let vec : &[TypeRef] = unsafe { mem::transmute(args) };
ty!(llvm::LLVMFunctionType(ret.to_ref(), vec.as_ptr(), | random_line_split |
type_.rs | ::mem;
use std::ptr;
use std::cell::RefCell;
use libc::c_uint;
#[derive(Clone, Copy, PartialEq, Debug)]
#[repr(C)]
pub struct Type {
rf: TypeRef
}
macro_rules! ty {
($e:expr) => ( Type::from_ref(unsafe { $e }))
}
/// Wrapper for LLVM TypeRef
impl Type {
#[inline(always)]
pub fn from_ref(r: TypeRef) ... | (&self) -> Type {
unsafe {
Type::from_ref(llvm::LLVMGetElementType(self.to_ref()))
}
}
/// Return the number of elements in `self` if it is a LLVM vector type.
pub fn vector_length(&self) -> usize {
unsafe {
llvm::LLVMGetVectorSize(self.to_ref()) as usize
... | element_type | identifier_name |
index.js | /**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot | * reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { PICTOGRAMS_URL } from 'services/config'
import View from 'components/View'
import Logo from 'components/Logo'
import messages from ... | random_line_split | |
index.js | /**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it... | extends React.PureComponent {
// eslint-disable-line react/prefer-stateless-function
render() {
return (
<View left={true} right={true} top={0}>
<h1 style={{ textAlign: 'center' }}>
<FormattedMessage {...messages.header} />
</h1>
<div style={{ textAlign: 'center' }}><img... | NotFound | identifier_name |
index.tsx | import React from 'react';
import styled from '@emotion/styled';
import orderBy from 'lodash/orderBy';
import space from 'app/styles/space';
import {Relay, RelayActivity} from 'app/types';
import ActivityList from './activityList';
import CardHeader from './cardHeader';
import {getRelaysByPublicKey} from './utils';
i... | const renderCardContent = (activities: Array<RelayActivity>) => {
if (!activities.length) {
return <WaitingActivity onRefresh={onRefresh} disabled={disabled} />;
}
return <ActivityList activities={activities} />;
};
return (
<Wrapper>
{Object.keys(relaysByPublicKey).map(relayByPublic... |
const relaysByPublicKey = getRelaysByPublicKey(orderedRelays, relayActivities);
| random_line_split |
index.tsx | import React from 'react';
import styled from '@emotion/styled';
import orderBy from 'lodash/orderBy';
import space from 'app/styles/space';
import {Relay, RelayActivity} from 'app/types';
import ActivityList from './activityList';
import CardHeader from './cardHeader';
import {getRelaysByPublicKey} from './utils';
i... |
return <ActivityList activities={activities} />;
};
return (
<Wrapper>
{Object.keys(relaysByPublicKey).map(relayByPublicKey => {
const {name, description, created, activities} = relaysByPublicKey[
relayByPublicKey
];
return (
<Card key={relayByPublicKey}>... | {
return <WaitingActivity onRefresh={onRefresh} disabled={disabled} />;
} | conditional_block |
MapFull.js | import React, {Component} from 'react';
import {connect} from 'react-redux';
class MapFull extends Component {
constructor() {
super();
this.state = {
htmlContent: null
};
}
componentDidMount() {
this.getMapHtml();
}
| (prevProps, prevState) {
if (!this.props.map || this.props.map.filehash !== prevProps.map.filehash) {
this.getMapHtml();
}
}
getMapHtml() {
const path = this.props.settings.html_url + this.props.map.filehash;
fetch(path).then(response => {
return response.text();
}).then(response =>... | componentDidUpdate | identifier_name |
MapFull.js | import React, {Component} from 'react';
import {connect} from 'react-redux';
class MapFull extends Component {
constructor() {
super();
this.state = {
htmlContent: null
};
}
componentDidMount() {
this.getMapHtml();
}
componentDidUpdate(prevProps, prevState) {
if (!this.props.map... |
}
getMapHtml() {
const path = this.props.settings.html_url + this.props.map.filehash;
fetch(path).then(response => {
return response.text();
}).then(response => {
this.setState({
htmlContent: response
});
});
}
getMarkup() {
return {__html: this.state.htmlContent... | {
this.getMapHtml();
} | conditional_block |
MapFull.js | import React, {Component} from 'react';
import {connect} from 'react-redux';
class MapFull extends Component {
constructor() {
super();
this.state = {
htmlContent: null
};
}
componentDidMount() {
this.getMapHtml();
} | this.getMapHtml();
}
}
getMapHtml() {
const path = this.props.settings.html_url + this.props.map.filehash;
fetch(path).then(response => {
return response.text();
}).then(response => {
this.setState({
htmlContent: response
});
});
}
getMarkup() {
return {... |
componentDidUpdate(prevProps, prevState) {
if (!this.props.map || this.props.map.filehash !== prevProps.map.filehash) { | random_line_split |
MapFull.js | import React, {Component} from 'react';
import {connect} from 'react-redux';
class MapFull extends Component {
constructor() {
super();
this.state = {
htmlContent: null
};
}
componentDidMount() |
componentDidUpdate(prevProps, prevState) {
if (!this.props.map || this.props.map.filehash !== prevProps.map.filehash) {
this.getMapHtml();
}
}
getMapHtml() {
const path = this.props.settings.html_url + this.props.map.filehash;
fetch(path).then(response => {
return response.text();
... | {
this.getMapHtml();
} | identifier_body |
jquery.peity.init.js | /**
* Theme: Ubold Admin Template
* Author: Coderthemes
* Component: Peity Chart
*
*/
!function($) {
"use strict";
var PeityChart = function() {};
//create line
PeityChart.prototype.createLine = function ($element, $strokeColor, $fillColor, $width ,$height) {
$($element).peity(... | $.PeityChart.init()
}(window.jQuery); | //initializing
function($) {
"use strict";
| random_line_split |
method-on-struct.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // lldb-command:print arg1
// lldb-check:[...]$13 = -9
// lldb-command:print arg2
// lldb-check:[...]$14 = -10
// lldb-command:continue
#![feature(box_syntax)]
#![omit_gdb_pretty_printer_section]
#[derive(Copy)]
struct Struct {
x: int
}
impl Struct {
fn self_by_ref(&self, arg1: int, arg2: int) -> int {
... | // lldb-command:continue
// OWNED MOVED
// lldb-command:print *self
// lldb-check:[...]$12 = Struct { x: 200 } | random_line_split |
method-on-struct.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (self: Box<Struct>, arg1: int, arg2: int) -> int {
zzz(); // #break
self.x + arg1 + arg2
}
}
fn main() {
let stack = Struct { x: 100 };
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
let owned = box Struct { x: 200 };
let _ = owned.self_by_ref(-5, -6);
... | self_owned | identifier_name |
views.py | import urllib
import telnetlib
import logging
import cjson
from models import BinaryResource
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django import forms
from django.contrib.auth import authenticate, login
from sana.mrs.openmrs import sendToOpenMRS
from sana.mrs.util i... |
else:
form = FakeProcedureSubmitForm()
if form.is_valid():
print "valid"
print form.cleaned_data
phoneId = form.cleaned_data['phone_id']
patientId = form.cleaned_data['patient_id']
procedureId = form.cleaned_data['procedure_id']
responses = form.cleaned... | form = FakeProcedureSubmitForm(request.POST) | conditional_block |
views.py | import urllib
import telnetlib
import logging
import cjson
from models import BinaryResource
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django import forms
from django.contrib.auth import authenticate, login
from sana.mrs.openmrs import sendToOpenMRS
from sana.mrs.util i... |
def procedure_submit(request):
"""For testing encounter submission"""
upload = request.FILES.get('data', None)
print upload
if request.method == 'POST' and upload is not None:
form = FakeProcedureSubmitForm(request.POST)
else:
form = FakeProcedureSubmitForm()
if form.is_valid... | """Encounter form for testing"""
responses = forms.CharField(required=True,
help_text='question,answer,question,answer,..')
procedure_id = forms.IntegerField(required=True, help_text="integers only")
phone_id = forms.CharField(max_length=255)
patient_id = forms.CharField(... | identifier_body |
views.py | import urllib
import telnetlib
import logging
import cjson
from models import BinaryResource
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django import forms
from django.contrib.auth import authenticate, login
from sana.mrs.openmrs import sendToOpenMRS
from sana.mrs.util i... | (request):
return render_to_response("notification_submit.html")
@enable_logging
def list_notifications(request):
"""For synching notifications with mobile clients.
Request Params
username
A valid username.
password
A valid password.
Parameters:
request... | notification_submit | identifier_name |
views.py | import urllib
import telnetlib
import logging
import cjson
from models import BinaryResource
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django import forms
from django.contrib.auth import authenticate, login
from sana.mrs.openmrs import sendToOpenMRS
from sana.mrs.util i... | phone_id = forms.CharField(max_length=255)
patient_id = forms.CharField(max_length=255)
#data = forms.FileField(required=True)
def procedure_submit(request):
"""For testing encounter submission"""
upload = request.FILES.get('data', None)
print upload
if request.method == 'POST' and upload ... | procedure_id = forms.IntegerField(required=True, help_text="integers only") | random_line_split |
coloursave.js | Selector + ']').checkboxradio();//http://www.qlambda.com/2012/06/jqm-refresh-jquery-mobile-select-menu.html
$('[name=' + tempSelector + ']').checkboxradio('disable');
} else {
$('[name=' + tempSelector + ']').attr('disabled',true);//.removeAttr("disabled");
... | #'+descriptionId).fadeOut('slow',
function() | conditional_block | |
coloursave.js | tempSelector);
if(tempSelector === undefined){
alert('Pls add name to this element');
}
tempObject = new Object;
tempObject[tempSelector]=gi(tempSelector);
tempArg=JSON.stringify(tempObject);
tempSelectParent = null;
tempURL = null;
if(tempSel... | ionId = '';
if(currentTarget){
//console.log('will hide ' + currentTarget);
descriptionId = currentTarget.substring(1) + '-wait';
if($('#'+descriptionId).length == 0){//na iPhone někdy zdvojovalo přidanou description
var newDetail = document.createElement('div');
newD... | identifier_body | |
coloursave.js | ave-context'));
//console.log(temp2);
if(IsJsonString(temp2)){
tempContext=temp2;
} else {
my_error_log(tempSelector + ' has invalid context. JSON expected. Received:' + temp2,3);
}
}
//for eventId analytics
... | l == null){
| identifier_name | |
coloursave.js | stage/api/v1/error_log/';
//var relativePathToBackyardJs = 'lib/backyard/deploy/backyard/js';
var relativePathToBackyardJs = '../deploy/backyard/js';
var localisationString = new Array();
localisationString['fill_in_red'] = 'Vyplňte červené pole'; // @TODO - customize někde v config
localisationString["sent_to_server"... | var tempSelectParent;
var tempURL;
var tempApiUrl;
var temp2;
$(document).ready(function() {
/*
if (typeof(my_error_log) != "function"){
// jQuery
$.getScript(relativePathToBackyardJs + '/' +'debug.js', function() //or the relative path to the calling html is needed??
{
... | random_line_split | |
module_common.py | # (c) 2013-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2015 Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible 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... | (module_data, module_path, strip_comments):
"""
Given the source of the module, convert it to a Jinja2 template to insert
module code and return whether it's a new or old style module.
"""
module_style = 'old'
if REPLACER in module_data:
module_style = 'new'
elif REPLACER_WINDOWS in... | _find_snippet_imports | identifier_name |
module_common.py | # (c) 2013-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2015 Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible 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... | output.write(ps_data)
snippet_names.append('powershell')
elif line.startswith('from ansible.module_utils.'):
tokens=line.split(".")
import_error = False
if len(tokens) != 3:
import_error = True
if " import *" not in line:
... | ps_data = _slurp(os.path.join(_SNIPPET_PATH, "powershell.ps1")) | random_line_split |
module_common.py | # (c) 2013-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2015 Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible 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... |
# POWERSHELL_COMMON
which results in the inclusion of the common code from powershell.ps1
"""
### TODO: Optimization ideas if this code is actually a source of slowness:
# * Fix comment stripping: Currently doesn't preserve shebangs and encoding info (but we unconditionally add encoding info)
... | """
Used to insert chunks of code into modules before transfer rather than
doing regular python imports. This allows for more efficient transfer in
a non-bootstrapping scenario by not moving extra files over the wire and
also takes care of embedding arguments in the transferred modules.
This versi... | identifier_body |
module_common.py | # (c) 2013-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2015 Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible 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... |
output = StringIO()
lines = module_data.split('\n')
snippet_names = []
for line in lines:
if REPLACER in line:
output.write(_slurp(os.path.join(_SNIPPET_PATH, "basic.py")))
snippet_names.append('basic')
if REPLACER_WINDOWS in line:
ps_data = _slurp... | module_style = 'non_native_want_json' | conditional_block |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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 ap... | *
* ## Notes
*
* - If provided `a >= b`, the function returns `NaN`.
*
* @param x - input value
* @param a - minimum support
* @param b - maximum support
* @returns evaluated logCDF
*
* @example
* var y = logcdf( 9.0, 0.0, 10.0 );
* // returns ~-0.105
*
* @example
* var y = logcdf( 0.5, 0.0, 2.0 );
*... | */
interface LogCDF {
/**
* Evaluates the logarithm of the cumulative distribution function (CDF) for a uniform distribution with minimum support `a` and maximum support `b` at a value `x`. | random_line_split |
client.py | OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Parent client for calling the Cloud Spanner API.
This is the base from which all interactions with the API occur.
In the hierarchy of API concepts
* a :class:`~google.cl... |
return self._database_admin_api
def copy(self):
"""Make a copy of this client.
Copies the local data stored as simple types but does not copy the
current state of any open connections with the Cloud Bigtable API.
:rtype: :class:`.Client`
:returns: A copy of the cu... | self._database_admin_api = DatabaseAdminClient(
credentials=self.credentials, client_info=_CLIENT_INFO
) | conditional_block |
client.py | google.api_core.gapic_v1 import client_info
# pylint: disable=line-too-long
from google.cloud.spanner_admin_database_v1.gapic.database_admin_client import ( # noqa
DatabaseAdminClient,
)
from google.cloud.spanner_admin_instance_v1.gapic.instance_admin_client import ( # noqa
InstanceAdminClient,
)
# pylint:... | _item_to_instance_config | identifier_name | |
client.py | OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Parent client for calling the Cloud Spanner API.
This is the base from which all interactions with the API occur.
In the hierarchy of API concepts
* a :class:`~google.cl... | """Helper for session-related API calls."""
if self._database_admin_api is None:
self._database_admin_api = DatabaseAdminClient(
credentials=self.credentials, client_info=_CLIENT_INFO
)
return self._database_admin_api
def copy(self):
"""Make a... | def database_admin_api(self): | random_line_split |
client.py | OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Parent client for calling the Cloud Spanner API.
This is the base from which all interactions with the API occur.
In the hierarchy of API concepts
* a :class:`~google.cl... |
@property
def database_admin_api(self):
"""Helper for session-related API calls."""
if self._database_admin_api is None:
self._database_admin_api = DatabaseAdminClient(
credentials=self.credentials, client_info=_CLIENT_INFO
)
return self._databas... | """Helper for session-related API calls."""
if self._instance_admin_api is None:
self._instance_admin_api = InstanceAdminClient(
credentials=self.credentials, client_info=_CLIENT_INFO
)
return self._instance_admin_api | identifier_body |
hero-form-reactive.component.ts | /* tslint:disable: member-ordering forin */
// #docregion
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { forbiddenNameValidator } from '../shared/forbidden-name.directive';
import { identityRevealedValidator } from '../shared/identity-rev... | 'alterEgo': new FormControl(this.hero.alterEgo),
'power': new FormControl(this.hero.power, Validators.required)
}, { validators: identityRevealedValidator }); // <-- add custom validator at the FormGroup level
}
get name() { return this.heroForm.get('name'); }
get power() { return this.heroForm... | Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i)
]), | random_line_split |
hero-form-reactive.component.ts | /* tslint:disable: member-ordering forin */
// #docregion
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { forbiddenNameValidator } from '../shared/forbidden-name.directive';
import { identityRevealedValidator } from '../shared/identity-rev... | () { return this.heroForm.get('power'); }
}
| power | identifier_name |
hero-form-reactive.component.ts | /* tslint:disable: member-ordering forin */
// #docregion
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { forbiddenNameValidator } from '../shared/forbidden-name.directive';
import { identityRevealedValidator } from '../shared/identity-rev... |
get name() { return this.heroForm.get('name'); }
get power() { return this.heroForm.get('power'); }
}
| {
this.heroForm = new FormGroup({
'name': new FormControl(this.hero.name, [
Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i)
]),
'alterEgo': new FormControl(this.hero.alterEgo),
'power': new FormControl(this.hero.power, Validators.required)... | identifier_body |
installer.py | # -*- coding: utf-8 -*-
import platform
import os
import sys
from .constants import (MYSTEM_BIN, MYSTEM_EXE, MYSTEM_DIR)
_TARBALL_URLS = {
'linux': {
'32bit': "http://download.cdn.yandex.net/mystem/mystem-3.0-linux3.5-32bit.tar.gz",
'64bit': "http://download.cdn.yandex.net/mystem/mystem-3.0-linux3... | """
if os.path.isfile(MYSTEM_BIN):
return
install(out)
def install(out=sys.stderr):
"""
Install mystem binary as :py:const:`~pymystem3.constants.MYSTEM_BIN`.
Overwrite if already installed.
"""
import requests
import tempfile
url = _get_tarball_url()
print("Inst... | """
Install mystem binary as :py:const:`~pymystem3.constants.MYSTEM_BIN`.
Do nothing if already installed. | random_line_split |
installer.py | # -*- coding: utf-8 -*-
import platform
import os
import sys
from .constants import (MYSTEM_BIN, MYSTEM_EXE, MYSTEM_DIR)
_TARBALL_URLS = {
'linux': {
'32bit': "http://download.cdn.yandex.net/mystem/mystem-3.0-linux3.5-32bit.tar.gz",
'64bit': "http://download.cdn.yandex.net/mystem/mystem-3.0-linux3... |
return url
| raise NotImplementedError("Your system is not supported. Feel free to report bug or make a pull request.") | conditional_block |
installer.py | # -*- coding: utf-8 -*-
import platform
import os
import sys
from .constants import (MYSTEM_BIN, MYSTEM_EXE, MYSTEM_DIR)
_TARBALL_URLS = {
'linux': {
'32bit': "http://download.cdn.yandex.net/mystem/mystem-3.0-linux3.5-32bit.tar.gz",
'64bit': "http://download.cdn.yandex.net/mystem/mystem-3.0-linux3... | (out=sys.stderr):
"""
Install mystem binary as :py:const:`~pymystem3.constants.MYSTEM_BIN`.
Overwrite if already installed.
"""
import requests
import tempfile
url = _get_tarball_url()
print("Installing mystem to %s from %s" % (MYSTEM_BIN, url), file=out)
if not os.path.isdir(MYS... | install | identifier_name |
installer.py | # -*- coding: utf-8 -*-
import platform
import os
import sys
from .constants import (MYSTEM_BIN, MYSTEM_EXE, MYSTEM_DIR)
_TARBALL_URLS = {
'linux': {
'32bit': "http://download.cdn.yandex.net/mystem/mystem-3.0-linux3.5-32bit.tar.gz",
'64bit': "http://download.cdn.yandex.net/mystem/mystem-3.0-linux3... |
def _get_tarball_url():
bits, _ = platform.architecture()
url = _get_on_prefix(_TARBALL_URLS, sys.platform)
if url is None:
raise NotImplementedError("Your system is not supported. Feel free to report bug or make a pull request.")
if isinstance(url, str):
return url
url = url.g... | for k, v in kvs.items():
if key.startswith(k):
return v
return None | identifier_body |
ractive-sortable.js | /*
Ractive-decorators-sortable
===========================
Version 0.1.2.
This plugin adds a 'sortable' decorator to Ractive, which enables
elements that correspond to array members to be re-ordered using
the HTML5 drag and drop API. Doing so will update the order
of the array.
=====... | node.removeEventListener( 'drop', removeTargetClass, false );
node.removeEventListener( 'dragover', preventDefault, false );
}
};
};
sortable.targetClass = 'droptarget';
errorMessage = 'The sortable decorator only works with elements that correspond to a... | random_line_split | |
ractive-sortable.js | /*
Ractive-decorators-sortable
===========================
Version 0.1.2.
This plugin adds a 'sortable' decorator to Ractive, which enables
elements that correspond to array members to be re-ordered using
the HTML5 drag and drop API. Doing so will update the order
of the array.
=====... |
// AMD?
else if ( typeof define === 'function' && define.amd ) {
define([ 'Ractive' ], factory );
}
// browser global
else if ( global.Ractive ) {
factory( global.Ractive );
}
else {
throw new Error( 'Could not find Ractive! It must be loaded before the Ractive-de... | {
factory( require( 'Ractive' ) );
} | conditional_block |
ip.py | from django.conf import settings
from .utils import is_valid_ip
from . import defaults as defs
NON_PUBLIC_IP_PREFIX = tuple([ip.lower() for ip in defs.IPWARE_NON_PUBLIC_IP_PREFIX])
TRUSTED_PROXY_LIST = tuple([ip.lower() for ip in getattr(settings, 'IPWARE_TRUSTED_PROXY_LIST', [])])
def get_ip(request, real_ip_only=... |
elif best_matched_ip.startswith(loopback) and not ip_str.startswith(loopback):
best_matched_ip = ip_str
return best_matched_ip
def get_real_ip(request, right_most_proxy=False):
"""
Returns client's best-matched `real` `externally-routable` ip-address, o... | best_matched_ip = ip_str | conditional_block |
ip.py | from django.conf import settings
from .utils import is_valid_ip
from . import defaults as defs
NON_PUBLIC_IP_PREFIX = tuple([ip.lower() for ip in defs.IPWARE_NON_PUBLIC_IP_PREFIX])
TRUSTED_PROXY_LIST = tuple([ip.lower() for ip in getattr(settings, 'IPWARE_TRUSTED_PROXY_LIST', [])])
def get_ip(request, real_ip_only=... | best_matched_ip = ip_str
return best_matched_ip
def get_real_ip(request, right_most_proxy=False):
"""
Returns client's best-matched `real` `externally-routable` ip-address, or None
@deprecated - Do not edit
"""
return get_ip(request, real_ip_only=True, right_most_p... | """
Returns client's best-matched ip-address, or None
@deprecated - Do not edit
"""
best_matched_ip = None
for key in defs.IPWARE_META_PRECEDENCE_ORDER:
value = request.META.get(key, request.META.get(key.replace('_', '-'), '')).strip()
if value is not None and value != '':
... | identifier_body |
ip.py | from django.conf import settings
from .utils import is_valid_ip
from . import defaults as defs
NON_PUBLIC_IP_PREFIX = tuple([ip.lower() for ip in defs.IPWARE_NON_PUBLIC_IP_PREFIX])
TRUSTED_PROXY_LIST = tuple([ip.lower() for ip in getattr(settings, 'IPWARE_TRUSTED_PROXY_LIST', [])])
def get_ip(request, real_ip_only=... | (request, right_most_proxy=False):
"""
Returns client's best-matched `real` `externally-routable` ip-address, or None
@deprecated - Do not edit
"""
return get_ip(request, real_ip_only=True, right_most_proxy=right_most_proxy)
def get_trusted_ip(request, right_most_proxy=False, trusted_proxies=TRUST... | get_real_ip | identifier_name |
ip.py | from django.conf import settings
from .utils import is_valid_ip
from . import defaults as defs
NON_PUBLIC_IP_PREFIX = tuple([ip.lower() for ip in defs.IPWARE_NON_PUBLIC_IP_PREFIX])
TRUSTED_PROXY_LIST = tuple([ip.lower() for ip in getattr(settings, 'IPWARE_TRUSTED_PROXY_LIST', [])])
def get_ip(request, real_ip_only=... | """
Returns client's best-matched `real` `externally-routable` ip-address, or None
@deprecated - Do not edit
"""
return get_ip(request, real_ip_only=True, right_most_proxy=right_most_proxy)
def get_trusted_ip(request, right_most_proxy=False, trusted_proxies=TRUSTED_PROXY_LIST):
"""
Returns... | random_line_split | |
ermcfg.py | '''
Config/Settings for ER Tweet Matching Service
'''
from datetime import date
# GLOBAL
# Maximum size a database can grow to (should be a multiple of 10MB)
MAX_DB_SIZE = 10485760 * 1000 * 100 # 10MB -> 10GB -> 1TB
## ER SERVICE
# Credentials
ER_USER = 'luis.rei@ijs.si'
ER_PASS = ''
# Log ER Requests?
ER_LOG =... | URLS_PER_PAGE = 200 # 200 should be the maximum set by the server
# Number of Events to ask for the URL in online mode
EVENTS_BATCH_SIZE = 40
## TWEET SERVICE
# Database that stores tweets and the archive files that have been read
TWEET_DB_FILENAME = 'tweets.db'
TWEET_DB_FILENAME = '/media/rei/data/er_match/tweets... | # Number of URLs to request per Page | random_line_split |
atomic-access-bool.rs | // Copyright 2016 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 ... | () {
unsafe {
assert_eq!(*ATOMIC.get_mut(), false);
ATOMIC.store(true, SeqCst);
assert_eq!(*ATOMIC.get_mut(), true);
ATOMIC.fetch_or(false, SeqCst);
assert_eq!(*ATOMIC.get_mut(), true);
ATOMIC.fetch_and(false, SeqCst);
assert_eq!(*ATOMIC.get_mut(), false);
... | main | identifier_name |
atomic-access-bool.rs | // Copyright 2016 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 ... | {
unsafe {
assert_eq!(*ATOMIC.get_mut(), false);
ATOMIC.store(true, SeqCst);
assert_eq!(*ATOMIC.get_mut(), true);
ATOMIC.fetch_or(false, SeqCst);
assert_eq!(*ATOMIC.get_mut(), true);
ATOMIC.fetch_and(false, SeqCst);
assert_eq!(*ATOMIC.get_mut(), false);
... | identifier_body | |
atomic-access-bool.rs | // Copyright 2016 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 ... |
static mut ATOMIC: AtomicBool = ATOMIC_BOOL_INIT;
fn main() {
unsafe {
assert_eq!(*ATOMIC.get_mut(), false);
ATOMIC.store(true, SeqCst);
assert_eq!(*ATOMIC.get_mut(), true);
ATOMIC.fetch_or(false, SeqCst);
assert_eq!(*ATOMIC.get_mut(), true);
ATOMIC.fetch_and(false,... | use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT};
use std::sync::atomic::Ordering::*; | random_line_split |
index.ts | import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {Component} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/scan';
import 'rxjs/... | scope: reg.scope
}
});
})
.catch(err => {
this.result = JSON.stringify({
error: `${err}`
})
});
}
checkServiceWorker(): void {
this.result = '';
na... | navigator['serviceWorker'].register(url)
.then(reg => {
this.result = JSON.stringify({
result: { | random_line_split |
index.ts | import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {Component} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/scan';
import 'rxjs/... | (): void {
let caches = window['caches'];
caches.keys().then(keys => this.result = JSON.stringify(keys));
}
installWorker(url): void {
navigator['serviceWorker'].register(url)
.then(reg => {
this.result = JSON.stringify({
result: {
... | loadCacheKeys | identifier_name |
dutycycleviz.py | Puschmann <andre.puschmann@tu-ilmenau.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distrib... |
def plot_beta(a, b):
Ly = []
Lx = []
mews = np.mgrid[0:1:100j]
for mew in mews:
Lx.append(mew)
Ly.append(beta(a, b, mew))
pl.plot(Lx, Ly, label="Beta: a=%f, b=%f" %(a,b))
# mu is location
# sigma is scale
# xi is shape
# U is input
# X = mu + sigma(U^-xi - 1) / xi (http://en.w... | e1 = ss.gamma(a + b)
e2 = ss.gamma(a)
e3 = ss.gamma(b)
e4 = mew ** (a - 1)
e5 = (1 - mew) ** (b - 1)
return (e1/(e2*e3)) * e4 * e5 | identifier_body |
dutycycleviz.py | option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU G... | main() | conditional_block | |
dutycycleviz.py | Puschmann <andre.puschmann@tu-ilmenau.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distrib... | (a, b):
Ly = []
Lx = []
mews = np.mgrid[0:1:100j]
for mew in mews:
Lx.append(mew)
Ly.append(beta(a, b, mew))
pl.plot(Lx, Ly, label="Beta: a=%f, b=%f" %(a,b))
# mu is location
# sigma is scale
# xi is shape
# U is input
# X = mu + sigma(U^-xi - 1) / xi (http://en.wikipedia.org/wik... | plot_beta | identifier_name |
dutycycleviz.py | Puschmann <andre.puschmann@tu-ilmenau.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distrib... |
return pl.plot(Lx, Ly, label="%s, DC=%.2f" % (desc, duty_cycle))
def main():
#plot_beta(0.1, 0.1)
#plot_beta(1, 1)
#plot_beta(2, 3)
#plot_beta(8, 4)
#plot_kumaraswamy(0.66, 20.8, "Sporadic use") # L1 case
#plot_kumaraswamy(0.17, 0.35, "Intermittent use, high-load after low-load pe... | #plt.axis( [0, 10, 0, 6])
pl.ylim(-0.1, 1.1)
pl.legend() | random_line_split |
test_chart_chartarea02.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
def test_create_file(self):
"""Test XlsxWriter chartarea properties."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
chart.axis_ids = [82933248, 82952960]
data = [
[1, 2, 3... | self.maxDiff = None
filename = 'chart_chartarea01.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_2_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {} | identifier_body |
test_chart_chartarea02.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | (self):
"""Test XlsxWriter chartarea properties."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
chart.axis_ids = [82933248, 82952960]
data = [
[1, 2, 3, 4, 5],
[2, 4... | test_create_file | identifier_name |
test_chart_chartarea02.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org |
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_chartarea01.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + ... | #
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
| random_line_split |
if.py | cars = ['audi', 'bmw', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
for c in cars:
if c=="audi":
print (c.title())
age1 = 12
age2 = 20
if (age1 > 10) and (age2 > 18):
print("all ok")
else:
print("Not ok")
if (age1 > 10) or (age2 >... |
else :
print("list is empty") | print("list is not empty") | conditional_block |
if.py | cars = ['audi', 'bmw', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
for c in cars:
if c=="audi":
print (c.title())
age1 = 12
age2 = 20
| print("all ok")
else:
print("Not ok")
if (age1 > 10) or (age2 > 18):
print("all ok")
else:
print("Not ok")
friends = ["onur", "cemal", "ali", "ayse", "yasar"]
if "cemal" in friends:
print("cemal is in the list")
if "kelali" not in friends:
print("kelali is not in the list")
age = 19
if a... | if (age1 > 10) and (age2 > 18): | random_line_split |
test-bundler-options.js | require('../../tool-env/install-babel.js');
var _ = require('underscore');
var assert = require('assert');
var bundler = require('../../isobuild/bundler.js');
var release = require('../../packaging/release.js');
var files = require('../../fs/files.js');
var catalog = require('../../packaging/catalog/catalog.js');
var ... | // As preparation, let's initialize the official catalog. It servers as our
// data store, so we will probably need it.
catalog.official.initialize();
var readManifest = function (tmpOutputDir) {
return JSON.parse(files.readFile(
files.pathJoin(tmpOutputDir, "programs", "web.browser", "program.json")... | return ret;
};
var runTest = function () { | random_line_split |
testNotifyTCPServer.py | #coding=utf-8
#-*- encoding: utf-8 -*-
import tornado.ioloop
import tornado.iostream
import socket
import struct
import NotifyTCPServer
def readPacketHeader():
stream.read_bytes(NotifyTCPServer.PACKET_HEADER_LEN, parsePacketHeader)
def parsePacketHeader(data):
sign,cmd,bodySize = struct.unpack('>2sHH', data)
p... | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
stream = tornado.iostream.IOStream(s)
stream.connect(("localhost", 9002), send_request)
#stream.connect(("221.180.20.232", 9002), send_request)
tornado.ioloop.IOLoop.instance().start() |
command=0 | random_line_split |
testNotifyTCPServer.py | #coding=utf-8
#-*- encoding: utf-8 -*-
import tornado.ioloop
import tornado.iostream
import socket
import struct
import NotifyTCPServer
def readPacketHeader():
stream.read_bytes(NotifyTCPServer.PACKET_HEADER_LEN, parsePacketHeader)
def parsePacketHeader(data):
sign,cmd,bodySize = struct.unpack('>2sHH', data)
p... | (cmd, msg):
data = bytes(msg)
stream.write(struct.pack(">2sHH", "NT", cmd, len(data)))
stream.write(data)
def send_request():
readPacketHeader()
send_register('591410cbf9614cbf9aaac4a871ddb466')
command=0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
stream = tornado.iostream.IOStream(s)
stream.c... | send_packet | identifier_name |
testNotifyTCPServer.py | #coding=utf-8
#-*- encoding: utf-8 -*-
import tornado.ioloop
import tornado.iostream
import socket
import struct
import NotifyTCPServer
def readPacketHeader():
stream.read_bytes(NotifyTCPServer.PACKET_HEADER_LEN, parsePacketHeader)
def parsePacketHeader(data):
sign,cmd,bodySize = struct.unpack('>2sHH', data)
p... |
readPacketHeader()
def send_register(userKey):
send_packet(NotifyTCPServer.NOTIFY_COMMAND_REGISTER, userKey)
def send_ping(msg):
send_packet(NotifyTCPServer.NOTIFY_COMMAND_PING, msg)
def send_packet(cmd, msg):
data = bytes(msg)
stream.write(struct.pack(">2sHH", "NT", cmd, len(data)))
stream.write(data)
... | send_ping(data) | conditional_block |
testNotifyTCPServer.py | #coding=utf-8
#-*- encoding: utf-8 -*-
import tornado.ioloop
import tornado.iostream
import socket
import struct
import NotifyTCPServer
def readPacketHeader():
stream.read_bytes(NotifyTCPServer.PACKET_HEADER_LEN, parsePacketHeader)
def parsePacketHeader(data):
sign,cmd,bodySize = struct.unpack('>2sHH', data)
p... |
def send_register(userKey):
send_packet(NotifyTCPServer.NOTIFY_COMMAND_REGISTER, userKey)
def send_ping(msg):
send_packet(NotifyTCPServer.NOTIFY_COMMAND_PING, msg)
def send_packet(cmd, msg):
data = bytes(msg)
stream.write(struct.pack(">2sHH", "NT", cmd, len(data)))
stream.write(data)
def send_request():
... | print "Data: %s" % str(data)
if command == NotifyTCPServer.NOTIFY_COMMAND_PING:
send_ping(data)
readPacketHeader() | identifier_body |
pico.py | #
# This file is part of pySMT.
#
# Copyright 2014 Andrea Micheli and Marco Gario
#
# 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
... |
@clear_pending_pop
def pop(self, levels=1):
for _ in xrange(levels):
picosat.picosat_pop(self.pico)
def exit(self):
if not self._destroyed:
self._destroyed = True
picosat.picosat_reset(self.pico)
| for _ in xrange(levels):
picosat.picosat_push(self.pico) | identifier_body |
pico.py | #
# This file is part of pySMT.
#
# Copyright 2014 Andrea Micheli and Marco Gario
#
# 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
... | return vid * mult
@clear_pending_pop
@catch_conversion_error
def add_assertion(self, formula, named=None):
# First, we get rid of True/False constants
formula = formula.simplify()
if formula.is_false():
picosat.picosat_add(self.pico, 0)
elif not formula.... |
vid = self._get_var_id(var) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.