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 |
|---|---|---|---|---|
graphite.py | """
homeassistant.components.graphite
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Component that records all events and state changes and feeds the data to
a graphite installation.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/graphite/
"""
import logging
import... |
_LOGGER.debug('Sending to graphite: %s', lines)
try:
self._send_to_graphite('\n'.join(lines))
except socket.gaierror:
_LOGGER.error('Unable to connect to host %s', self._host)
except socket.error:
_LOGGER.exception('Failed to send data to graphite')
... | return | conditional_block |
graphite.py | """
homeassistant.components.graphite
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Component that records all events and state changes and feeds the data to
a graphite installation.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/graphite/
"""
import logging
import... | (self, hass, host, port, prefix):
super(GraphiteFeeder, self).__init__(daemon=True)
self._hass = hass
self._host = host
self._port = port
# rstrip any trailing dots in case they think they
# need it
self._prefix = prefix.rstrip('.')
self._queue = queue.Que... | __init__ | identifier_name |
multiplexed.rs | SafeProcessor = Box<dyn TProcessor + Send + Sync>;
/// A `TProcessor` that can demux service calls to multiple underlying
/// Thrift services.
///
/// Users register service-specific `TProcessor` instances with a
/// `TMultiplexedProcessor`, and then register that processor with a server
/// implementation. Following ... | else {
stored.processors.insert(name, processor);
Ok(())
}
} else {
Err(format!("cannot overwrite existing processor for service {}", name).into())
}
}
fn process_message(
&self,
msg_ident: &TMessageIdentifier,
i_p... | {
if stored.default_processor.is_none() {
stored.processors.insert(name, processor.clone());
stored.default_processor = Some(processor.clone());
Ok(())
} else {
Err("cannot reset default processor".into())
... | conditional_block |
multiplexed.rs | SafeProcessor = Box<dyn TProcessor + Send + Sync>;
/// A `TProcessor` that can demux service calls to multiple underlying
/// Thrift services.
///
/// Users register service-specific `TProcessor` instances with a
/// `TMultiplexedProcessor`, and then register that processor with a server
/// implementation. Following ... | () {
let ident_name = "foo:bar_call";
let (serv, call) = split_ident_name(&ident_name);
assert_eq!(serv, Some("foo"));
assert_eq!(call, "bar_call");
}
#[test]
fn should_return_full_ident_if_no_separator_exists() {
let ident_name = "bar_call";
let (serv, call)... | should_split_name_into_proper_separator_and_service_call | identifier_name |
multiplexed.rs | SafeProcessor = Box<dyn TProcessor + Send + Sync>;
/// A `TProcessor` that can demux service calls to multiple underlying
/// Thrift services.
///
/// Users register service-specific `TProcessor` instances with a
/// `TMultiplexedProcessor`, and then register that processor with a server
/// implementation. Following ... | let mut proxy_i_prot = TStoredInputProtocol::new(i_prot, new_msg_ident);
(*arc).process(&mut proxy_i_prot, o_prot)
}
None => Err(missing_processor_message(svc_name).into()),
}
}
}
impl TProcessor for TMultiplexedProcessor {
fn process(
&s... | {
let (svc_name, svc_call) = split_ident_name(&msg_ident.name);
debug!("routing svc_name {:?} svc_call {}", &svc_name, &svc_call);
let processor: Option<Arc<ThreadSafeProcessor>> = {
let stored = self.stored.lock().unwrap();
if let Some(name) = svc_name {
... | identifier_body |
multiplexed.rs | // under the License.
use log::debug;
use std::collections::HashMap;
use std::convert::Into;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::sync::{Arc, Mutex};
use crate::protocol::{TInputProtocol, TMessageIdentifier, TOutputProtocol, TStoredInputProtocol};
use super::{handle_process_result, TProcessor};
... | random_line_split | ||
hello.py | import requests, urllib, httplib, base64
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/search", methods=['POST', 'GET'])
def callAPI():
error = None
_url = 'https://api.projectoxford.ai/vision/v1.0/... | # data = response.read()
# print(data)
# conn.close()
#
# print 'hello'
# conn.request("POST", "/vision/v1.0/ocr?%s" % params, {"url":"http://example.com/images/test.jpg"}, headers)
# response = conn.getresponse()
# data = response.read()
# print(data)
# conn.close()
except Exce... | return returnVal
#
# conn = httplib.HTTPSConnection('api.projectoxford.ai')
# conn.request("POST", "/vision/v1.0/ocr?%s" % paramsIn, "{body}", headersIn)
# response = conn.getresponse() | random_line_split |
hello.py | import requests, urllib, httplib, base64
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/search", methods=['POST', 'GET'])
def callAPI():
error = None
_url = 'https://api.projectoxford.ai/vision/v1.0/... | app.run(host='0.0.0.0') | conditional_block | |
hello.py | import requests, urllib, httplib, base64
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/search", methods=['POST', 'GET'])
def | ():
error = None
_url = 'https://api.projectoxford.ai/vision/v1.0/ocr' #https://api.projectoxford.ai/vision/v1.0/ocr[?language][&detectOrientation ]
_key = "f8968ffd96d2475cb7ec347c51f24e3e" #Here you have to paste your primary key it is a header
_maxNumRetries = 10
bodyURL = request.args.get('uri','')
print(bod... | callAPI | identifier_name |
hello.py | import requests, urllib, httplib, base64
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/search", methods=['POST', 'GET'])
def callAPI():
|
try:
r = requests.post(_url, json=data,\
params=paramsIn, headers=headersIn)
print r.json()
returnVal = {"data": r.json()}
return returnVal
#
# conn = httplib.HTTPSConnection('api.projectoxford.ai')
# conn.request("POST", "/vision/v1.0/ocr?%s" % paramsIn, "{body}", headersIn)
# response = ... | error = None
_url = 'https://api.projectoxford.ai/vision/v1.0/ocr' #https://api.projectoxford.ai/vision/v1.0/ocr[?language][&detectOrientation ]
_key = "f8968ffd96d2475cb7ec347c51f24e3e" #Here you have to paste your primary key it is a header
_maxNumRetries = 10
bodyURL = request.args.get('uri','')
print(bodyURL)... | identifier_body |
setup.py | import os
import platform
import itertools
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), "json_rest", "__version__.py")) as version_file:
exec(version_file.read())
_INSTALL_REQUIREMENTS = ["python-cjson", "pyforge", "sentinels"]
if platform.python_version() < '2.7':... |
setup(name="json_rest",
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python :: 2.7",
],
description="Utility for REST/JSON based web services",
... | _INSTALL_REQUIREMENTS.append('unittest2') | conditional_block |
setup.py | import os
import platform
import itertools
from setuptools import setup, find_packages | _INSTALL_REQUIREMENTS = ["python-cjson", "pyforge", "sentinels"]
if platform.python_version() < '2.7':
_INSTALL_REQUIREMENTS.append('unittest2')
setup(name="json_rest",
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved ... |
with open(os.path.join(os.path.dirname(__file__), "json_rest", "__version__.py")) as version_file:
exec(version_file.read())
| random_line_split |
full-api.test.ts | import * as cli from '../cli';
import { compileInMemory } from './utils';
describe('full api test', () => {
let namespaces: string;
beforeAll(async () => {
namespaces = await cli.buildTypeScriptFromSources([
`
syntax = "proto3";
package test;
service Service {
rpc Sin... | `,
});
expect(result.errors).toEqual([]);
expect(result.ok).toBe(true);
});
}); | }); | random_line_split |
NavBar.js | 'use strict';
import React from 'react-native'
import {
AppRegistry,
Component,
Navigator,
ToolbarAndroid,
View,
} from 'react-native';
import globalStyle, { colors } from './globalStyle';
class NavBar extends Component {
| () {
this.props.navigator.push({
name: 'home',
sceneConfig: Navigator.SceneConfigs.FloatFromLeft,
});
}
getToolbarActions(route) {
const actionsByRoute = {
'home': [],
'boop-view': [{
title: 'Back',
show: 'always'
}],
}
if (actionsByRoute[route.name... | onClickBackToHome | identifier_name |
NavBar.js | 'use strict';
import React from 'react-native'
import {
AppRegistry,
Component,
Navigator,
ToolbarAndroid,
View,
} from 'react-native';
import globalStyle, { colors } from './globalStyle';
class NavBar extends Component {
onClickBackToHome() {
this.props.navigator.push({
name: 'home',
sc... |
return [];
}
render() {
const { navigator } = this.props;
const currentRoute = navigator.getCurrentRoutes()[navigator.getCurrentRoutes().length - 1];
const toolbarActions = this.getToolbarActions(currentRoute);
return (
<ToolbarAndroid
style={globalStyle.toolbar}
title='... | {
return actionsByRoute[route.name];
} | conditional_block |
NavBar.js | 'use strict';
import React from 'react-native'
import {
AppRegistry,
Component,
Navigator,
ToolbarAndroid,
View,
} from 'react-native';
import globalStyle, { colors } from './globalStyle';
class NavBar extends Component {
onClickBackToHome() |
getToolbarActions(route) {
const actionsByRoute = {
'home': [],
'boop-view': [{
title: 'Back',
show: 'always'
}],
}
if (actionsByRoute[route.name]) {
return actionsByRoute[route.name];
}
return [];
}
render() {
const { navigator } = this.props;
... | {
this.props.navigator.push({
name: 'home',
sceneConfig: Navigator.SceneConfigs.FloatFromLeft,
});
} | identifier_body |
NavBar.js | 'use strict';
import React from 'react-native'
import {
AppRegistry,
Component,
Navigator,
ToolbarAndroid,
View,
} from 'react-native';
import globalStyle, { colors } from './globalStyle';
class NavBar extends Component {
onClickBackToHome() {
this.props.navigator.push({
name: 'home',
sc... | 'boop-view': [{
title: 'Back',
show: 'always'
}],
}
if (actionsByRoute[route.name]) {
return actionsByRoute[route.name];
}
return [];
}
render() {
const { navigator } = this.props;
const currentRoute = navigator.getCurrentRoutes()[navigator.getCurrentRoutes... | const actionsByRoute = {
'home': [], | random_line_split |
permission.rs | use std::{error::Error as StdError, fmt, io::Write, str::FromStr};
use diesel::{backend::Backend, deserialize, serialize, sql_types::Text};
#[derive(AsExpression, Clone, Copy, Debug, Eq, FromSqlRow, Hash, PartialEq)]
#[sql_type = "Text"]
pub enum Permission {
MakePost,
MakeMediaPost,
MakeComment,
Foll... | (&self) -> Option<&dyn StdError> {
None
}
}
| cause | identifier_name |
permission.rs | use std::{error::Error as StdError, fmt, io::Write, str::FromStr};
use diesel::{backend::Backend, deserialize, serialize, sql_types::Text};
#[derive(AsExpression, Clone, Copy, Debug, Eq, FromSqlRow, Hash, PartialEq)]
#[sql_type = "Text"]
pub enum Permission {
MakePost,
MakeMediaPost,
MakeComment,
Foll... |
}
impl<DB> deserialize::FromSql<Text, DB> for Permission
where
DB: Backend<RawValue = [u8]>,
{
fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
deserialize::FromSql::<Text, DB>::from_sql(bytes).and_then(|string: String| {
string
.parse::<Permission>(... | {
serialize::ToSql::<Text, DB>::to_sql(&format!("{}", self), out)
} | identifier_body |
permission.rs | use std::{error::Error as StdError, fmt, io::Write, str::FromStr};
use diesel::{backend::Backend, deserialize, serialize, sql_types::Text};
#[derive(AsExpression, Clone, Copy, Debug, Eq, FromSqlRow, Hash, PartialEq)]
#[sql_type = "Text"]
pub enum Permission {
MakePost,
MakeMediaPost,
MakeComment,
Foll... | DB: Backend,
{
fn to_sql<W: Write>(&self, out: &mut serialize::Output<W, DB>) -> serialize::Result {
serialize::ToSql::<Text, DB>::to_sql(&format!("{}", self), out)
}
}
impl<DB> deserialize::FromSql<Text, DB> for Permission
where
DB: Backend<RawValue = [u8]>,
{
fn from_sql(bytes: Option<&DB... | impl<DB> serialize::ToSql<Text, DB> for Permission
where | random_line_split |
box_vec.rs | #![warn(clippy::all)]
#![allow(clippy::boxed_local, clippy::needless_pass_by_value)]
#![allow(clippy::blacklisted_name)]
macro_rules! boxit {
($init:expr, $x:ty) => {
let _: Box<$x> = Box::new($init);
};
}
fn test_macro() {
boxit!(Vec::new(), Vec<u8>);
}
pub fn test(foo: Box<Vec<bool>>) {
prin... | } | test2(Box::new(|v| println!("{:?}", v)));
test_macro();
test_local_not_linted(); | random_line_split |
box_vec.rs | #![warn(clippy::all)]
#![allow(clippy::boxed_local, clippy::needless_pass_by_value)]
#![allow(clippy::blacklisted_name)]
macro_rules! boxit {
($init:expr, $x:ty) => {
let _: Box<$x> = Box::new($init);
};
}
fn test_macro() {
boxit!(Vec::new(), Vec<u8>);
}
pub fn | (foo: Box<Vec<bool>>) {
println!("{:?}", foo.get(0))
}
pub fn test2(foo: Box<dyn Fn(Vec<u32>)>) {
// pass if #31 is fixed
foo(vec![1, 2, 3])
}
pub fn test_local_not_linted() {
let _: Box<Vec<bool>>;
}
fn main() {
test(Box::new(Vec::new()));
test2(Box::new(|v| println!("{:?}", v)));
test_m... | test | identifier_name |
box_vec.rs | #![warn(clippy::all)]
#![allow(clippy::boxed_local, clippy::needless_pass_by_value)]
#![allow(clippy::blacklisted_name)]
macro_rules! boxit {
($init:expr, $x:ty) => {
let _: Box<$x> = Box::new($init);
};
}
fn test_macro() {
boxit!(Vec::new(), Vec<u8>);
}
pub fn test(foo: Box<Vec<bool>>) {
prin... | {
test(Box::new(Vec::new()));
test2(Box::new(|v| println!("{:?}", v)));
test_macro();
test_local_not_linted();
} | identifier_body | |
expression-parser.service.ts | // Copyright 2020 The Oppia Authors. 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 ap... | {
parse = parser.parse;
SyntaxError = parser.SyntaxError;
}
angular.module('oppia').factory(
'ServiceName', downgradeInjectable(ExpressionParserService)
);
| ExpressionParserService | identifier_name |
expression-parser.service.ts | // Copyright 2020 The Oppia Authors. 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 ap... | ); | angular.module('oppia').factory(
'ServiceName', downgradeInjectable(ExpressionParserService) | random_line_split |
models.py | from __future__ import unicode_literals
from django.db import models
from django.core.paginator import Paginator, PageNotAnInteger
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailimages.edit_... |
content_panels = Page.content_panels + [
FieldPanel('intro'),
]
| context = super(EventIndexPage, self).get_context(request)
context['event_entries'] = EventPage.objects.child_of(self).live()
return context | identifier_body |
models.py | from __future__ import unicode_literals
from django.db import models
from django.core.paginator import Paginator, PageNotAnInteger
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailimages.edit_... | class EventIndexPage(Page):
intro = RichTextField(blank=True)
def get_context(self, request):
context = super(EventIndexPage, self).get_context(request)
context['event_entries'] = EventPage.objects.child_of(self).live()
return context
content_panels = Page.content_panels + [
... | FieldPanel('address'),
FieldPanel('intro'),
FieldPanel('body', classname="full"),
]
| random_line_split |
models.py | from __future__ import unicode_literals
from django.db import models
from django.core.paginator import Paginator, PageNotAnInteger
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailimages.edit_... | (self, request):
context = super(EventIndexPage, self).get_context(request)
context['event_entries'] = EventPage.objects.child_of(self).live()
return context
content_panels = Page.content_panels + [
FieldPanel('intro'),
]
| get_context | identifier_name |
tensor_util.py | = [
'assert_same_float_dtype',
'assert_scalar_int',
'convert_to_tensor_or_sparse_tensor',
'is_tensor',
'reduce_sum_n',
'with_shape',
'with_same_shape']
def | (items, expected_type=None):
r"""Asserts all items are of the same base type.
Args:
items: List of graph items (e.g., `Variable`, `Tensor`, `SparseTensor`,
`Operation`, or `IndexedSlices`). Can include `None` elements, which
will be ignored.
expected_type: Expected type. If not specified, a... | _assert_same_base_type | identifier_name |
tensor_util.py | = [
'assert_same_float_dtype',
'assert_scalar_int',
'convert_to_tensor_or_sparse_tensor',
'is_tensor',
'reduce_sum_n',
'with_shape',
'with_same_shape']
def _assert_same_base_type(items, expected_type=None):
r"""Asserts all items are of the same base type.
Args:
items: List of gra... | if expected_shape.dtype.base_dtype != dtypes.int32:
raise ValueError(
'Invalid dtype %s for shape %s expected of tensor %s.' % (
expected_shape.dtype, expected_shape, tensor.name))
if isinstance(expected_shape, (list, tuple)):
if not expected_shape:
expected_shape = np.asar... | """Asserts tensor has expected shape.
If tensor shape and expected_shape, are fully defined, assert they match.
Otherwise, add assert op that will validate the shape when tensor is
evaluated, and set shape on tensor.
Args:
expected_shape: Expected shape to assert, as a 1D array of ints, or tensor
... | identifier_body |
tensor_util.py | = [
'assert_same_float_dtype',
'assert_scalar_int',
'convert_to_tensor_or_sparse_tensor',
'is_tensor',
'reduce_sum_n',
'with_shape',
'with_same_shape']
def _assert_same_base_type(items, expected_type=None):
r"""Asserts all items are of the same base type.
Args:
items: List of gra... |
actual_shape = | if expected_shape.ndim > 1:
raise ValueError(
'Invalid rank %s for shape %s expected of tensor %s.' % (
expected_shape.ndim, expected_shape, tensor.name))
if expected_shape.dtype != np.int32:
raise ValueError(
'Invalid dtype %s for shape %s expected of tensor %s.' % (
... | conditional_block |
tensor_util.py | same type,
validates that type is `dtype` (if supplied), and returns the type. Type must
be `dtypes.float32` or `dtypes.float64`. If neither `tensors` nor
`dtype` is supplied, default to `dtypes.float32`.
Args:
tensors: Tensors of input values. Can include `None` elements, which will be
ignored.
... | as_ref: True if we want the result as a ref tensor. Only used if a new
`Tensor` is created.
Returns: | random_line_split | |
vmc_stats_emulator.py | #!/usr/bin/env python2.6
# This file is part of VoltDB.
# Copyright (C) 2008-2018 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to... | except AttributeError:
err_ct += 1
if err_ct >= max_errors:
if pause_on_error:
raw_input("Press any key to continue...")
else:
print "%s: Too many errors - I'm out of here" % tid
return (... | err_ct = 0
tid = str(threading.current_thread().name)
print ts() + " Starting thread " + tid
i = 1
http = httplib2.Http(cache=None, timeout=15.0)
#while forever
while ( i > 0 ) :
if not i % 100:
print "%s %s Loop Count: %4d" % (ts(), tid, i)
for a in arguments:
... | identifier_body |
vmc_stats_emulator.py | #!/usr/bin/env python2.6
# This file is part of VoltDB.
# Copyright (C) 2008-2018 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to... | (max_errors=1, sleep_time=0):
err_ct = 0
tid = str(threading.current_thread().name)
print ts() + " Starting thread " + tid
i = 1
http = httplib2.Http(cache=None, timeout=15.0)
#while forever
while ( i > 0 ) :
if not i % 100:
print "%s %s Loop Count: %4d" % (ts(), tid, i)
... | push_it | identifier_name |
vmc_stats_emulator.py | #!/usr/bin/env python2.6
# This file is part of VoltDB.
# Copyright (C) 2008-2018 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to... | err_ct += 1
except AttributeError:
err_ct += 1
if err_ct >= max_errors:
if pause_on_error:
raw_input("Press any key to continue...")
else:
print "%s: Too many errors - I'm out of here" % ... | print "%s %s Request# %d - Error getting %s\n\thttp_status=%s\tresponse=%s" % (ts(), tid, i, a, response['status'], statusstring) | random_line_split |
vmc_stats_emulator.py | #!/usr/bin/env python2.6
# This file is part of VoltDB.
# Copyright (C) 2008-2018 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to... |
else:
print "%s: Too many errors - I'm out of here" % tid
return (-1)
time.sleep(sleep_time)
i += 1
threads = []
for i in range(thr):
t = threading.Thread(target=push_it, args=(1,sleep_time))
t.daemon=True
threads.append(t)
for t in ... | raw_input("Press any key to continue...") | conditional_block |
patchRouteFilterRule.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.... | }
},
routeFilterRuleType: {
required: true,
isConstant: true,
serializedName: 'properties.routeFilterRuleType',
defaultValue: 'Community',
type: {
name: 'String'
}
},
communities: {
... | {
return {
required: false,
serializedName: 'PatchRouteFilterRule',
type: {
name: 'Composite',
className: 'PatchRouteFilterRule',
modelProperties: {
id: {
required: false,
serializedName: 'id',
type: {
name: 'Strin... | identifier_body |
patchRouteFilterRule.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.... | extends models['SubResource'] {
constructor() {
super();
}
/**
* Defines the metadata of PatchRouteFilterRule
*
* @returns {object} metadata of PatchRouteFilterRule
*
*/
mapper() {
return {
required: false,
serializedName: 'PatchRouteFilterRule',
type: {
name: ... | PatchRouteFilterRule | identifier_name |
patchRouteFilterRule.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.... | type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
etag: {
required: false,
... | provisioningState: {
required: false,
readOnly: true,
serializedName: 'properties.provisioningState', | random_line_split |
twitter_json_parser.py | #!/usr/bin/python
import json
from pprint import pprint
import re
import urllib
import time
from geopy import geocoders
import Image
import os
# TODO: handle test cases
# testcases:
# hollywood & vine, hollywood and vine
# order of operations: hashtag, img, address, other text.
# hashtag allcaps or lowercase
# upload... |
else:
print("file already exists. Skipping %s") % DIR_FINISHED_IMGS + '/' + IMG_NAME
return
return
| try:
file = urllib.urlretrieve(img_url, DIR_FINISHED_IMGS + '/' + IMG_NAME)
print("Saved: %s" % DIR_FINISHED_IMGS + '/' + IMG_NAME)
except IOError, e:
print 'could not retrieve %s' % IMG_NAME
try:
im = Image.open(DIR_FINISHED_IMGS + '/' + IMG_NAME)
# TODO: need to figure out what thumbn... | conditional_block |
twitter_json_parser.py | #!/usr/bin/python
import json
from pprint import pprint
import re
import urllib
import time
from geopy import geocoders
import Image
import os
# TODO: handle test cases
# testcases:
# hollywood & vine, hollywood and vine
# order of operations: hashtag, img, address, other text.
# hashtag allcaps or lowercase
# upload... |
print("--------------------------------------------------------") # DEBUG
else:
print("file already exists. Skipping %s") % DIR_FINISHED_IMGS + '/' + IMG_NAME
return
return
| DIR_FINISHED_IMGS = '../data_finished_images'
IMG_NAME = lat + '_' + lng + '_.PNG'
if (False == os.path.isfile(DIR_FINISHED_IMGS + '/' + IMG_NAME)):
# save url to disk with address as filename
try:
file = urllib.urlretrieve(img_url, DIR_FINISHED_IMGS + '/' + IMG_NAME)
print("Saved: %s" % DIR_... | identifier_body |
twitter_json_parser.py | #!/usr/bin/python
import json
from pprint import pprint
import re
import urllib
import time
from geopy import geocoders
import Image
import os
# TODO: handle test cases
# testcases:
# hollywood & vine, hollywood and vine
# order of operations: hashtag, img, address, other text.
# hashtag allcaps or lowercase
# upload... | file = urllib.urlretrieve(img_url, DIR_FINISHED_IMGS + '/' + IMG_NAME)
print("Saved: %s" % DIR_FINISHED_IMGS + '/' + IMG_NAME)
except IOError, e:
print 'could not retrieve %s' % IMG_NAME
try:
im = Image.open(DIR_FINISHED_IMGS + '/' + IMG_NAME)
# TODO: need to figure out what thumbnail s... |
if (False == os.path.isfile(DIR_FINISHED_IMGS + '/' + IMG_NAME)):
# save url to disk with address as filename
try: | random_line_split |
twitter_json_parser.py | #!/usr/bin/python
import json
from pprint import pprint
import re
import urllib
import time
from geopy import geocoders
import Image
import os
# TODO: handle test cases
# testcases:
# hollywood & vine, hollywood and vine
# order of operations: hashtag, img, address, other text.
# hashtag allcaps or lowercase
# upload... | (self, input_data):
g = geocoders.GoogleV3()
tweet_data = []
processed_tweets = []
with open(input_data) as f:
for line in f:
if line.strip():
tweet_data = json.loads(line)
tweet = tweet_data["text"]
# scrub out any @mentions or #hashtags to leave behind address / text
... | get_data_from_tweets | identifier_name |
desktop.py | # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import subprocess
from typing import Sequence
from pants.util.osutil import get_os_name
class IdeaNotFoundException(Exception):
"""Could not find Idea executable."""
cla... |
subprocess.Popen(["nohup", cmd, file_])
def _linux_open(files: Sequence[str]) -> None:
cmd = "xdg-open"
if not _cmd_exists(cmd):
raise OpenError(
"The program '{}' isn't in your PATH. Please install and re-run this "
"goal.".format(cmd)
)
for f in list(files):
... | raise OpenError(
"The program '{}' isn't in your PATH. Please install and re-run this "
"goal.".format(cmd)
) | conditional_block |
desktop.py | # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import subprocess
from typing import Sequence
from pants.util.osutil import get_os_name
class IdeaNotFoundException(Exception):
"""Could not find Idea executable."""
cla... | "The program '{}' isn't in your PATH. Please install and re-run this "
"goal.".format(cmd)
)
subprocess.Popen(["nohup", cmd, file_])
def _linux_open(files: Sequence[str]) -> None:
cmd = "xdg-open"
if not _cmd_exists(cmd):
raise OpenError(
"The program '{... | random_line_split | |
desktop.py | # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import subprocess
from typing import Sequence
from pants.util.osutil import get_os_name
class IdeaNotFoundException(Exception):
"""Could not find Idea executable."""
cla... | """Attempts to open the given files using the preferred desktop viewer or editor.
:raises :class:`OpenError`: if there is a problem opening any of the files.
"""
if files:
osname = get_os_name()
opener = _OPENER_BY_OS.get(osname)
if opener:
opener(files)
else:
... | identifier_body | |
desktop.py | # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import subprocess
from typing import Sequence
from pants.util.osutil import get_os_name
class IdeaNotFoundException(Exception):
"""Could not find Idea executable."""
cla... | (file_: str, lookup_paths: list) -> None:
"""Attempts to open the given files using the preferred desktop viewer or editor.
:raises :class:`OpenError`: if there is a problem opening any of the files.
"""
if file_:
osname = get_os_name()
opener = _IDEA_BY_OS.get(osname)
if opener... | idea_open | identifier_name |
elf.rs | //! ELF executables
use collections::{String, Vec};
use core::{ptr, str};
use common::slice::GetSlice;
#[cfg(target_arch = "x86")]
use goblin::elf32::{header, program_header};
#[cfg(target_arch = "x86_64")]
use goblin::elf64::{header, program_header};
/// An ELF executable
pub struct Elf<'a> {
pub data: &'a [... | }
pub unsafe fn load_segments(&self) -> Vec<program_header::ProgramHeader> {
let mut segments = Vec::new();
let header = &*(self.data.as_ptr() as usize as *const header::Header);
for i in 0..header.e_phnum {
let segment = ptr::read((self.data.as_ptr() as usize + header.e_p... | } | random_line_split |
elf.rs | //! ELF executables
use collections::{String, Vec};
use core::{ptr, str};
use common::slice::GetSlice;
#[cfg(target_arch = "x86")]
use goblin::elf32::{header, program_header};
#[cfg(target_arch = "x86_64")]
use goblin::elf64::{header, program_header};
/// An ELF executable
pub struct | <'a> {
pub data: &'a [u8],
}
impl<'a> Elf<'a> {
/// Create a ELF executable from data
pub fn from(data: &'a [u8]) -> Result<Elf<'a>, String> {
if data.len() < header::SIZEOF_EHDR {
Err(format!("Elf: Not enough data: {} < {}", data.len(), header::SIZEOF_EHDR))
} else if data.get_... | Elf | identifier_name |
elf.rs | //! ELF executables
use collections::{String, Vec};
use core::{ptr, str};
use common::slice::GetSlice;
#[cfg(target_arch = "x86")]
use goblin::elf32::{header, program_header};
#[cfg(target_arch = "x86_64")]
use goblin::elf64::{header, program_header};
/// An ELF executable
pub struct Elf<'a> {
pub data: &'a [... |
}
| {
let header = &*(self.data.as_ptr() as usize as *const header::Header);
header.e_entry as usize
} | identifier_body |
elf.rs | //! ELF executables
use collections::{String, Vec};
use core::{ptr, str};
use common::slice::GetSlice;
#[cfg(target_arch = "x86")]
use goblin::elf32::{header, program_header};
#[cfg(target_arch = "x86_64")]
use goblin::elf64::{header, program_header};
/// An ELF executable
pub struct Elf<'a> {
pub data: &'a [... | else if data.get_slice(..header::SELFMAG) != header::ELFMAG {
Err(format!("Elf: Invalid magic: {:?} != {:?}", data.get_slice(..4), header::ELFMAG))
} else if data.get(header::EI_CLASS) != Some(&header::ELFCLASS) {
Err(format!("Elf: Invalid architecture: {:?} != {:?}", data.get(header::E... | {
Err(format!("Elf: Not enough data: {} < {}", data.len(), header::SIZEOF_EHDR))
} | conditional_block |
qualified.rs | use syn::ext::IdentExt;
use syn::parse::{ParseStream, Result};
use syn::{Ident, LitStr, Token};
pub struct QualifiedName {
pub segments: Vec<Ident>,
}
impl QualifiedName {
pub fn parse_unquoted(input: ParseStream) -> Result<Self> {
let mut segments = Vec::new();
let mut trailing_punct = true;
... | Ok(QualifiedName { segments })
} else {
lit.parse_with(Self::parse_unquoted)
}
} else {
Self::parse_unquoted(input)
}
}
} | if input.peek(LitStr) {
let lit: LitStr = input.parse()?;
if lit.value().is_empty() {
let segments = Vec::new(); | random_line_split |
qualified.rs | use syn::ext::IdentExt;
use syn::parse::{ParseStream, Result};
use syn::{Ident, LitStr, Token};
pub struct QualifiedName {
pub segments: Vec<Ident>,
}
impl QualifiedName {
pub fn parse_unquoted(input: ParseStream) -> Result<Self> {
let mut segments = Vec::new();
let mut trailing_punct = true;
... | (input: ParseStream) -> Result<Self> {
if input.peek(LitStr) {
let lit: LitStr = input.parse()?;
if lit.value().is_empty() {
let segments = Vec::new();
Ok(QualifiedName { segments })
} else {
lit.parse_with(Self::parse_unquoted)... | parse_quoted_or_unquoted | identifier_name |
qualified.rs | use syn::ext::IdentExt;
use syn::parse::{ParseStream, Result};
use syn::{Ident, LitStr, Token};
pub struct QualifiedName {
pub segments: Vec<Ident>,
}
impl QualifiedName {
pub fn parse_unquoted(input: ParseStream) -> Result<Self> {
let mut segments = Vec::new();
let mut trailing_punct = true;
... |
}
}
| {
Self::parse_unquoted(input)
} | conditional_block |
SrvStartRebuyGracePeriodDataSerializer.ts |
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder";
import { BitsReader } from "../../../../utils/BitsReader";
import { SerializerUtils } from "../../../../utils/SerializerUtils";
import { SrvStartRebuyGracePeriodData } from "../data/SrvStartRebuyGracePeriodData";
import { PokerSeatGraceData } f... | (buffer: ArrayBufferBuilder, data: SrvStartRebuyGracePeriodData): void {
PokerSeatGraceDataSerializer.serialize(buffer, data.graceVO);
}
public static deserialize(buffer: ArrayBufferBuilder, data: SrvStartRebuyGracePeriodData): void {
data.graceVO = new PokerSeatGraceData(data);
Poke... | serialize | identifier_name |
SrvStartRebuyGracePeriodDataSerializer.ts |
import { PokerSeatGraceDataSerializer } from "../serializers/PokerSeatGraceDataSerializer";
export class SrvStartRebuyGracePeriodDataSerializer {
public static serialize(buffer: ArrayBufferBuilder, data: SrvStartRebuyGracePeriodData): void {
PokerSeatGraceDataSerializer.serialize(buffer, data.graceVO);
}
... | import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder";
import { BitsReader } from "../../../../utils/BitsReader";
import { SerializerUtils } from "../../../../utils/SerializerUtils";
import { SrvStartRebuyGracePeriodData } from "../data/SrvStartRebuyGracePeriodData";
import { PokerSeatGraceData } fr... | random_line_split | |
shield.py | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Shield"
prefix = "shield"
class Action(BaseAction):
def | (self, action: str = None) -> None:
super().__init__(prefix, action)
class ARN(BaseARN):
def __init__(self, resource: str = "", region: str = "", account: str = "") -> None:
super().__init__(
service=prefix, resource=resource, region=region, account=account
)
AssociateDRTLogB... | __init__ | identifier_name |
shield.py | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Shield"
prefix = "shield"
class Action(BaseAction):
def __init__(self, action: str = None) -> None:
super(... | "UpdateApplicationLayerAutomaticResponse"
)
UpdateEmergencyContactSettings = Action("UpdateEmergencyContactSettings")
UpdateProtectionGroup = Action("UpdateProtectionGroup")
UpdateSubscription = Action("UpdateSubscription") | ListTagsForResource = Action("ListTagsForResource")
TagResource = Action("TagResource")
UntagResource = Action("UntagResource")
UpdateApplicationLayerAutomaticResponse = Action( | random_line_split |
shield.py | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Shield"
prefix = "shield"
class Action(BaseAction):
|
class ARN(BaseARN):
def __init__(self, resource: str = "", region: str = "", account: str = "") -> None:
super().__init__(
service=prefix, resource=resource, region=region, account=account
)
AssociateDRTLogBucket = Action("AssociateDRTLogBucket")
AssociateDRTRole = Action("Associate... | def __init__(self, action: str = None) -> None:
super().__init__(prefix, action) | identifier_body |
storeProvider.tsx | import * as React from 'react';
import {Provider} from 'react-redux';
import {createStore} from '@emeraldwallet/store';
import {ApiMock, BackendMock, VaultMock} from "./backendMock";
import {StoryContext, StoryFn} from "@storybook/addons/dist/types";
import {IApi, WalletStateStorage} from "@emeraldwallet/core";
import ... | }
next(entryId: EntryId, type: AddressRole): Promise<WalletState> {
return Promise.resolve({accountIndexes: []});
}
update(entryId: EntryId, receive: number | undefined, change: number | undefined): Promise<WalletState | undefined> {
return Promise.resolve(undefined);
}
}
const defaultBackend = ne... |
class WalletStateMock implements WalletStateStorage {
load(): Promise<WalletState> {
return Promise.resolve({accountIndexes: []}); | random_line_split |
storeProvider.tsx | import * as React from 'react';
import {Provider} from 'react-redux';
import {createStore} from '@emeraldwallet/store';
import {ApiMock, BackendMock, VaultMock} from "./backendMock";
import {StoryContext, StoryFn} from "@storybook/addons/dist/types";
import {IApi, WalletStateStorage} from "@emeraldwallet/core";
import ... | implements WalletStateStorage {
load(): Promise<WalletState> {
return Promise.resolve({accountIndexes: []});
}
next(entryId: EntryId, type: AddressRole): Promise<WalletState> {
return Promise.resolve({accountIndexes: []});
}
update(entryId: EntryId, receive: number | undefined, change: number | und... | WalletStateMock | identifier_name |
storeProvider.tsx | import * as React from 'react';
import {Provider} from 'react-redux';
import {createStore} from '@emeraldwallet/store';
import {ApiMock, BackendMock, VaultMock} from "./backendMock";
import {StoryContext, StoryFn} from "@storybook/addons/dist/types";
import {IApi, WalletStateStorage} from "@emeraldwallet/core";
import ... |
class WalletStateMock implements WalletStateStorage {
load(): Promise<WalletState> {
return Promise.resolve({accountIndexes: []});
}
next(entryId: EntryId, type: AddressRole): Promise<WalletState> {
return Promise.resolve({accountIndexes: []});
}
update(entryId: EntryId, receive: number | undefine... | {
return new ApiMock(
new VaultMock(backend.vault)
)
} | identifier_body |
ftpDownloader-test.py | # -*- coding: utf-8 -*-
"""
Created on Sat May 21 16:43:47 2016
@author: Pratik
"""
from ftplib import FTP
import os
# login and download file from ftp site and retrieve file (use default params)
def ftpDownloader(filename, host="ftp.pyclass.com", user="student@pyclass.com", passwd="student123"):
| ftp = FTP(host) # get the host url of ftp site
ftp.login(user, passwd) # login with username and password
ftp.cwd('Data') # change directory to Data
os.chdir("/Users/Pratik/Documents/Pratik/Work/practice/py-data-analysis") # change directory
print(ftp.nlst()) ... | identifier_body | |
ftpDownloader-test.py | # -*- coding: utf-8 -*-
"""
Created on Sat May 21 16:43:47 2016
@author: Pratik
"""
from ftplib import FTP
import os
# login and download file from ftp site and retrieve file (use default params)
def | (filename, host="ftp.pyclass.com", user="student@pyclass.com", passwd="student123"):
ftp = FTP(host) # get the host url of ftp site
ftp.login(user, passwd) # login with username and password
ftp.cwd('Data') # change directory to Data
os.chdir("/Users/Pratik/Docume... | ftpDownloader | identifier_name |
ftpDownloader-test.py | # -*- coding: utf-8 -*-
"""
Created on Sat May 21 16:43:47 2016
| import os
# login and download file from ftp site and retrieve file (use default params)
def ftpDownloader(filename, host="ftp.pyclass.com", user="student@pyclass.com", passwd="student123"):
ftp = FTP(host) # get the host url of ftp site
ftp.login(user, passwd) # login with username and... | @author: Pratik
"""
from ftplib import FTP | random_line_split |
main.rs | use std::env; | #[cfg(not(unix))]
mod platform {
use std::ffi::OsString;
pub const BUFFER_CAPACITY: usize = 16 * 1024;
pub fn to_bytes(os_str: OsString) -> Vec<u8> {
os_str.into_string().expect("non utf-8 argument only supported on unix").into()
}
}
#[cfg(unix)]
mod platform {
use std::ffi::OsString;
... | use std::io::{self, Write};
use std::process;
use std::borrow::Cow;
| random_line_split |
main.rs | use std::env;
use std::io::{self, Write};
use std::process;
use std::borrow::Cow;
#[cfg(not(unix))]
mod platform {
use std::ffi::OsString;
pub const BUFFER_CAPACITY: usize = 16 * 1024;
pub fn to_bytes(os_str: OsString) -> Vec<u8> {
os_str.into_string().expect("non utf-8 argument only supported on ... | <'a>(buffer: &'a mut [u8], output: &'a [u8]) -> &'a [u8] {
if output.len() > buffer.len() / 2 {
return output;
}
let mut buffer_size = output.len();
buffer[..buffer_size].clone_from_slice(output);
while buffer_size < buffer.len() / 2 {
let (left, right) = buffer.split_at_mut(buffer... | fill_up_buffer | identifier_name |
main.rs | use std::env;
use std::io::{self, Write};
use std::process;
use std::borrow::Cow;
#[cfg(not(unix))]
mod platform {
use std::ffi::OsString;
pub const BUFFER_CAPACITY: usize = 16 * 1024;
pub fn to_bytes(os_str: OsString) -> Vec<u8> {
os_str.into_string().expect("non utf-8 argument only supported on ... |
let mut buffer_size = output.len();
buffer[..buffer_size].clone_from_slice(output);
while buffer_size < buffer.len() / 2 {
let (left, right) = buffer.split_at_mut(buffer_size);
right[..buffer_size].clone_from_slice(left);
buffer_size *= 2;
}
&buffer[..buffer_size]
}
fn ... | {
return output;
} | conditional_block |
main.rs | use std::env;
use std::io::{self, Write};
use std::process;
use std::borrow::Cow;
#[cfg(not(unix))]
mod platform {
use std::ffi::OsString;
pub const BUFFER_CAPACITY: usize = 16 * 1024;
pub fn to_bytes(os_str: OsString) -> Vec<u8> |
}
#[cfg(unix)]
mod platform {
use std::ffi::OsString;
pub const BUFFER_CAPACITY: usize = 64 * 1024;
pub fn to_bytes(os_str: OsString) -> Vec<u8> {
use std::os::unix::ffi::OsStringExt;
os_str.into_vec()
}
}
use platform::*;
fn fill_up_buffer<'a>(buffer: &'a mut [u8], output: &'a [u8]... | {
os_str.into_string().expect("non utf-8 argument only supported on unix").into()
} | identifier_body |
9201001.js | /*
This file is part of the HeavenMS MapleStory Server
Copyleft (L) 2017 RonanLana
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Sof... | }
}
} | random_line_split | |
9201001.js | /*
This file is part of the HeavenMS MapleStory Server
Copyleft (L) 2017 RonanLana
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Sof... |
var nanaLoc;
var mapids = [100000000, 103000000, 102000000, 101000000, 200000000, 220000000];
var questItems = [4000001, 4000037, 4000215, 4000026, 4000070, 4000128];
var questExp = [2000, 5000, 10000, 17000, 22000, 30000];
function processNanaQuest() {
if(cm.haveItem(questItems[nanaLoc], 50)) {
if(cm.ca... | {
var mapid = player.getMap().getId();
for(var i = 0; i < mapids.length; i++) {
if(mapid == mapids[i]) {
return i;
}
}
return -1;
} | identifier_body |
9201001.js | /*
This file is part of the HeavenMS MapleStory Server
Copyleft (L) 2017 RonanLana
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Sof... | (player) {
var mapid = player.getMap().getId();
for(var i = 0; i < mapids.length; i++) {
if(mapid == mapids[i]) {
return i;
}
}
return -1;
}
var nanaLoc;
var mapids = [100000000, 103000000, 102000000, 101000000, 200000000, 220000000];
var questItems = [4000001, 400... | getNanaLocation | identifier_name |
9201001.js | /*
This file is part of the HeavenMS MapleStory Server
Copyleft (L) 2017 RonanLana
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Sof... | cm.gainExp(questExp[nanaLoc] * cm.getPlayer().getExpRate());
cm.completeQuest(100401 + nanaLoc);
}
cm.dispose();
} else {
state = 0;
cm.sendAcceptDecline("... | {
if(!cm.isQuestStarted(100400)) {
cm.sendOk("Hello #b#h0##k, I'm #p9201001# the fairy of Love.");
cm.dispose();
return;
}
nanaLoc = getNanaLocation(cm.getPlayer());
if(nanaLoc == -1) {
cm.sendOk... | conditional_block |
indexer.py | import pyes
import os
from models import *
from sqlalchemy import select
from downloader import download
import utils
import re
import time
class Search(object):
def __init__(self,host,index,map_name,mapping=None,id_key=None):
self.es = pyes.ES(host)
self.index = index
self.map_name = map_... |
if __name__ == '__main__':
initial_index()
| host = '127.0.0.1:9200'
index = 'bill-index'
map_name = 'bill-type'
initdb()
session = DBSession()
revision = (session.query(BillRevision).get(rev_id)
)
temp = convert_to_document(revision)
search = Search(host,index,map_name)
search.index_item(temp) | identifier_body |
indexer.py | import pyes
import os
from models import *
from sqlalchemy import select
from downloader import download
import utils
import re
import time
class Search(object):
def __init__(self,host,index,map_name,mapping=None,id_key=None):
self.es = pyes.ES(host)
self.index = index
self.map_name = map_... |
return temp
def initial_index():
host = '127.0.0.1:9200'
index = 'bill-index'
map_name = 'bill-type'
mapping = {
'document':{
'type':'attachment',
'fields':{
"title" : { "store" : "yes" },
"file" : {
"term_vecto... | temp['document'] = pyes.file_to_attachment(full_path) | conditional_block |
indexer.py | import pyes
import os
from models import *
from sqlalchemy import select
from downloader import download
import utils
import re
import time
class Search(object):
def __init__(self,host,index,map_name,mapping=None,id_key=None):
self.es = pyes.ES(host)
self.index = index
self.map_name = map_... | 'type':'integer',
'store':'yes'
}
}
search = Search(host,index,map_name,mapping)
search.create_index()
initdb()
session = DBSession()
revision = (session.query(BillRevision)
.join((BillRevision.bill,Bill)).all()
)
for rev... | },
'id':{ | random_line_split |
indexer.py | import pyes
import os
from models import *
from sqlalchemy import select
from downloader import download
import utils
import re
import time
class Search(object):
def __init__(self,host,index,map_name,mapping=None,id_key=None):
self.es = pyes.ES(host)
self.index = index
self.map_name = map_... | ():
host = '127.0.0.1:9200'
index = 'bill-index'
map_name = 'bill-type'
mapping = {
'document':{
'type':'attachment',
'fields':{
"title" : { "store" : "yes" },
"file" : {
"term_vector":"with_positions_offsets",
... | initial_index | identifier_name |
index.ts | import { BBox } from "@turf/helpers";
import { coordEach } from "@turf/meta";
/**
* Takes a set of features, calculates the bbox of all input features, and returns a bounding box.
*
* @name bbox
* @param {GeoJSON} geojson any GeoJSON object
* @returns {BBox} bbox extent in [minX, minY, maxX, maxY] order
* @examp... | (geojson: any): BBox {
const result: BBox = [Infinity, Infinity, -Infinity, -Infinity];
coordEach(geojson, (coord) => {
if (result[0] > coord[0]) { result[0] = coord[0]; }
if (result[1] > coord[1]) { result[1] = coord[1]; }
if (result[2] < coord[0]) { result[2] = coord[0]; }
if (... | bbox | identifier_name |
index.ts | import { BBox } from "@turf/helpers";
import { coordEach } from "@turf/meta";
/**
* Takes a set of features, calculates the bbox of all input features, and returns a bounding box.
*
* @name bbox
* @param {GeoJSON} geojson any GeoJSON object
* @returns {BBox} bbox extent in [minX, minY, maxX, maxY] order
* @examp... |
if (result[3] < coord[1]) { result[3] = coord[1]; }
});
return result;
}
| { result[2] = coord[0]; } | conditional_block |
index.ts | import { BBox } from "@turf/helpers";
import { coordEach } from "@turf/meta";
/**
* Takes a set of features, calculates the bbox of all input features, and returns a bounding box.
*
* @name bbox
* @param {GeoJSON} geojson any GeoJSON object
* @returns {BBox} bbox extent in [minX, minY, maxX, maxY] order
* @examp... | return result;
} | }); | random_line_split |
index.ts | import { BBox } from "@turf/helpers";
import { coordEach } from "@turf/meta";
/**
* Takes a set of features, calculates the bbox of all input features, and returns a bounding box.
*
* @name bbox
* @param {GeoJSON} geojson any GeoJSON object
* @returns {BBox} bbox extent in [minX, minY, maxX, maxY] order
* @examp... | {
const result: BBox = [Infinity, Infinity, -Infinity, -Infinity];
coordEach(geojson, (coord) => {
if (result[0] > coord[0]) { result[0] = coord[0]; }
if (result[1] > coord[1]) { result[1] = coord[1]; }
if (result[2] < coord[0]) { result[2] = coord[0]; }
if (result[3] < coord[1])... | identifier_body | |
libdump1090.rs | // Pitot - a customizable aviation information receiver
// Copyright (C) 2017-2018 Datong Sun (dndx@idndx.com)
//
// 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 Lice... |
pub fn process_data(&mut self, buf: &[u8]) {
unsafe { dump1090_process(buf.as_ptr(), buf.len()) }
}
pub fn parsed_as_mut_ref(&mut self) -> &mut VecDeque<TrafficData> {
&mut self.parsed
}
fn push_message(&mut self, msg: TrafficData) {
trace!("got a Mode S message: {:?}", m... | {
// this has to be boxed to get the address of self for callback
// now
let me = Box::new(Self {
parsed: VecDeque::new(),
});
unsafe {
if dump1090_init(callback, &*me as *const _ as *const c_void) != 0 {
panic!("unable to init libdump1090... | identifier_body |
libdump1090.rs | // Pitot - a customizable aviation information receiver
// Copyright (C) 2017-2018 Datong Sun (dndx@idndx.com)
//
// 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 Lice... | _ => None,
},
on_ground: match traffic.airground_valid {
1 => Some(traffic.on_ground == 1),
_ => None,
},
source: TrafficSource::ES,
};
(*inst).push_message(msg);
}
} | nacp: match traffic.nacp_valid {
1 => Some(traffic.nacp as u8), | random_line_split |
libdump1090.rs | // Pitot - a customizable aviation information receiver
// Copyright (C) 2017-2018 Datong Sun (dndx@idndx.com)
//
// 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 Lice... | {
addr: u32,
altitude: i32,
gnss_delta: i32,
heading: u32,
speed: u32,
vs: i32,
squawk: u32,
callsign: *const u8,
category: u32,
lat: f64,
lon: f64,
nic: u32,
nacp: u32,
on_ground: u8,
addr_type: u8,
altitude_valid: u8,
altitude_is_baro: u8,
gnss... | TrafficT | identifier_name |
factories.py | """
Factories for Program Enrollment tests.
"""
from __future__ import absolute_import
from uuid import uuid4
import factory
from factory.django import DjangoModelFactory
from opaque_keys.edx.keys import CourseKey
from lms.djangoapps.program_enrollments import models
from student.tests.factories import CourseEnrollm... |
program_enrollment = factory.SubFactory(ProgramEnrollmentFactory)
course_enrollment = factory.SubFactory(CourseEnrollmentFactory)
course_key = factory.LazyAttribute(
lambda pce: (
pce.course_enrollment.course_id
if pce.course_enrollment
else PROGRAM_COURSE_ENROL... | model = models.ProgramCourseEnrollment | identifier_body |
factories.py | """
Factories for Program Enrollment tests.
"""
from __future__ import absolute_import
from uuid import uuid4
import factory
from factory.django import DjangoModelFactory
from opaque_keys.edx.keys import CourseKey
from lms.djangoapps.program_enrollments import models
from student.tests.factories import CourseEnrollm... | if pce.course_enrollment
else PROGRAM_COURSE_ENROLLMENT_DEFAULT_COURSE_KEY
)
)
status = 'active' | lambda pce: (
pce.course_enrollment.course_id | random_line_split |
factories.py | """
Factories for Program Enrollment tests.
"""
from __future__ import absolute_import
from uuid import uuid4
import factory
from factory.django import DjangoModelFactory
from opaque_keys.edx.keys import CourseKey
from lms.djangoapps.program_enrollments import models
from student.tests.factories import CourseEnrollm... | (object):
model = models.ProgramEnrollment
user = factory.SubFactory(UserFactory)
external_user_key = None
program_uuid = factory.LazyFunction(uuid4)
curriculum_uuid = factory.LazyFunction(uuid4)
status = 'enrolled'
PROGRAM_COURSE_ENROLLMENT_DEFAULT_COURSE_KEY = (
CourseKey.from_strin... | Meta | identifier_name |
messenger_contact_add.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com>
#
# 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) an... |
self._ab.ContactAdd(self._callback,
self._errback,
self._scenario,
self.contact_info,
invite_info,
self.auto_manage_allow_list)
| raise NotImplementedError("Network ID '%s' is not implemented" %
self.network_id) | conditional_block |
messenger_contact_add.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com>
#
# 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) an... | (BaseScenario):
def __init__(self, ab, callback, errback,
account='',
network_id=NetworkID.MSN,
contact_type=ContactType.REGULAR,
contact_info={},
invite_display_name='',
invite_message=''):
"""Adds a messe... | MessengerContactAddScenario | identifier_name |
messenger_contact_add.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com>
#
# 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) an... |
self._ab = ab
self.account = account
self.network_id = network_id
self.contact_type = contact_type
self.contact_info = contact_info
self.invite_display_name = invite_display_name
self.invite_message = invite_message
self.auto_manage_allow_list = True
... | @param ab: the address book service
@param callback: tuple(callable, *args)
@param errback: tuple(callable, *args)"""
BaseScenario.__init__(self, Scenario.CONTACT_SAVE, callback, errback) | random_line_split |
messenger_contact_add.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com>
#
# 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) an... |
def execute(self):
invite_info = { 'display_name' : self.invite_display_name,
'invite_message' : self.invite_message }
if self.network_id == NetworkID.MSN:
self.contact_info['passport_name'] = self.account
self.contact_info['contact_type'] = self.co... | """Adds a messenger contact and updates the address book.
@param ab: the address book service
@param callback: tuple(callable, *args)
@param errback: tuple(callable, *args)"""
BaseScenario.__init__(self, Scenario.CONTACT_SAVE, callback, errback)
self._ab = ab
... | identifier_body |
reference.py | # -*- coding: utf-8 -*-
# Zeobuilder is an extensible GUI-toolkit for molecular model construction.
# Copyright (C) 2007 - 2012 Toon Verstraelen <Toon.Verstraelen@UGent.be>, Center
# for Molecular Modeling (CMM), Ghent University, Ghent, Belgium; all rights
# reserved unless otherwise stated.
#
# This file is part of Z... | (Node):
info = NodeInfo("SelectTargets")
overlay_icon = load_image("reference.svg", (20, 20))
def __init__(self, prefix):
Node.__init__(self)
self.target = None
self.prefix = prefix
self.icon = self.overlay_icon
def set_target(self, target):
if self.target is No... | Reference | identifier_name |
reference.py | # -*- coding: utf-8 -*-
# Zeobuilder is an extensible GUI-toolkit for molecular model construction.
# Copyright (C) 2007 - 2012 Toon Verstraelen <Toon.Verstraelen@UGent.be>, Center
# for Molecular Modeling (CMM), Ghent University, Ghent, Belgium; all rights
# reserved unless otherwise stated.
#
# This file is part of Z... | Reference.set_model(self, model, parent, index)
if self.target is not None: self.connect_bridge()
def unset_model(self):
Reference.unset_model(self)
if self.target is not None: self.disconnect_bridge()
#
# Targets
#
def define_target(self, new_target):
Refe... | def set_model(self, model, parent, index): | random_line_split |
reference.py | # -*- coding: utf-8 -*-
# Zeobuilder is an extensible GUI-toolkit for molecular model construction.
# Copyright (C) 2007 - 2012 Toon Verstraelen <Toon.Verstraelen@UGent.be>, Center
# for Molecular Modeling (CMM), Ghent University, Ghent, Belgium; all rights
# reserved unless otherwise stated.
#
# This file is part of Z... |
old_target = self.target
if self.model is not None:
old_target.references.remove(self)
self.target = None
self.icon = self.overlay_icon
self.parent.undefine_target(self, old_target)
def check_target(self, new_target):
if isinstance(new_target, Reference)... | raise TargetError("Reference has no target to undefine.") | conditional_block |
reference.py | # -*- coding: utf-8 -*-
# Zeobuilder is an extensible GUI-toolkit for molecular model construction.
# Copyright (C) 2007 - 2012 Toon Verstraelen <Toon.Verstraelen@UGent.be>, Center
# for Molecular Modeling (CMM), Ghent University, Ghent, Belgium; all rights
# reserved unless otherwise stated.
#
# This file is part of Z... | if self.target is not None:
return self.target.get_frame_relative_to(other).t
else:
return None | identifier_body | |
WebSocketService.ts | /*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* 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 progr... |
readonly lockWebsocket = () => {
this.apiClient.transport.ws.lock();
};
readonly unlockWebsocket = () => {
this.apiClient.transport.ws.unlock();
};
/**
* Establish the WebSocket connection.
* @param onNotification Function to be called on incoming notifications
* @returns Resolves once the... | this.apiClient.disconnect();
}; | random_line_split |
WebSocketService.ts | /*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* 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 progr... | (onNotification: OnNotificationCallback, onConnect: OnConnect): Promise<void> {
this.apiClient.context.clientId = this.clientId;
this.apiClient.removeListener(APIClient.TOPIC.ON_LOGOUT, this.disconnect);
this.apiClient.on(APIClient.TOPIC.ON_LOGOUT, this.disconnect);
this.apiClient.transport.ws.removeAl... | connect | identifier_name |
WebSocketService.ts | /*
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* 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 progr... | amplify.publish(WebAppEvents.WARNING.SHOW, Warnings.TYPE.NO_INTERNET);
return;
}
case WEBSOCKET_STATE.OPEN: {
amplify.publish(WebAppEvents.CONNECTION.ONLINE);
amplify.publish(WebAppEvents.WARNING.DISMISS, Warnings.TYPE.NO_INTERNET);
amplify.publish(WebAp... | {
this.apiClient.context.clientId = this.clientId;
this.apiClient.removeListener(APIClient.TOPIC.ON_LOGOUT, this.disconnect);
this.apiClient.on(APIClient.TOPIC.ON_LOGOUT, this.disconnect);
this.apiClient.transport.ws.removeAllListeners();
this.apiClient.transport.ws.on(WebSocketClient.TOPIC.ON_MESS... | identifier_body |
command.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
def wrapper(*argv, **kwargs):
# Ensure stdout is captured
kwargs["stdout"] = subprocess.PIPE
return strip_it(f(*argv, **kwargs).stdout)
return wrapper
class Command:
""" A runnable command.
Class inheriting from the Command class must provide the bin
... | return x.strip() if self.strip else x | identifier_body |
command.py | # to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the L... | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.