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 |
|---|---|---|---|---|
porter_segment.py | Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,zh-TW;q=0.2",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"Cookie": "PHPSESSID=web3~fdf535b2518f7f061780d987bb65934a; _gat=1; io=onpREhr-L-d7pRxJHvSF; Hm_lvt_e23800c454aa573c0ccb16b52665ac26=1508383051,1508500169,1508563643,1508565378; Hm_lpvt_e23800c454a... | self._session.headers['Referer'] = 'https://segmentfault.com/write?freshman=1'
if(self._session.headers.has_key('Origin')):
del self._session.headers['Origin']
del self._session.headers['Content-Length']
del self._session.headers['Content-Type']
res = ''
|
def getTags(self,tagname):
## 标签处理 | random_line_split |
porter_segment.py | ._session.headers = self.initHeader()
print self._session.headers
self.filenameList = {}
def loadConfig(self):
# 获取配置文件
currentProject = os.path.dirname(sys.path[0])
configStr = os.path.abspath( os.path.join(currentProject,'config.json'))
data_file = open(configStr)
data = json.load(data_file)
s... | daliao/Desktop/zhida | conditional_block | |
porter_segment.py | Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,zh-TW;q=0.2",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"Cookie": "PHPSESSID=web3~fdf535b2518f7f061780d987bb65934a; _gat=1; io=onpREhr-L-d7pRxJHvSF; Hm_lvt_e23800c454aa573c0ccb16b52665ac26=1508383051,1508500169,1508563643,1508565378; Hm_lpvt_e23800c454a... | h, 'w')
cookies = self._session.headers
json.dump(cookies, file)
file.close()
def dirCb(self,dirname):
for line in os.listdir(dirname):
filename = os.path.abspath(os.path.join(dirname, line))
if(os.path.isdir(filename)):
self.dirCb(filename)
else:
pattern = re.compile(r"(\d+... | (cookiepat | identifier_name |
porter_segment.py | Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,zh-TW;q=0.2",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"Cookie": "PHPSESSID=web3~fdf535b2518f7f061780d987bb65934a; _gat=1; io=onpREhr-L-d7pRxJHvSF; Hm_lvt_e23800c454aa573c0ccb16b52665ac26=1508383051,1508500169,1508563643,1508565378; Hm_lpvt_e23800c454a... | dirname, line))
if(os.path.isdir(filename)):
self.dirCb(filename)
else:
pattern = re.compile(r"(\d+)-(\d+)-(\d+)-(\S+.md)")
result = pattern.findall(filename)
if (len(result) != 0):
tags = filename.split('_posts')[1]
# print tags
tagname = ''
for tag in tags.split(os.sep):
... | cookies = self._session.headers
json.dump(cookies, file)
file.close()
def dirCb(self,dirname):
for line in os.listdir(dirname):
filename = os.path.abspath(os.path.join( | identifier_body |
version.py | # ormbad.version
# Helper module for ORMBad version information
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Thu Aug 13 12:38:42 2015 -0400
#
# Copyright (C) 2015 Tipsy Bear Studios
# For license information, see LICENSE.txt
# |
##########################################################################
## Versioning
##########################################################################
__version_info__ = {
'major': 0,
'minor': 1,
'micro': 0,
'releaselevel': 'final',
'serial': 0,
}
def get_version(short=False):
"... | # ID: version.py [] benjamin@bengfort.com $
"""
Helper module for ORMBad version information.
""" | random_line_split |
version.py | # ormbad.version
# Helper module for ORMBad version information
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Thu Aug 13 12:38:42 2015 -0400
#
# Copyright (C) 2015 Tipsy Bear Studios
# For license information, see LICENSE.txt
#
# ID: version.py [] benjamin@bengfort.com $
"""
Helper module for ORM... | """
Returns the version from the version info.
"""
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != '... | identifier_body | |
version.py | # ormbad.version
# Helper module for ORMBad version information
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Thu Aug 13 12:38:42 2015 -0400
#
# Copyright (C) 2015 Tipsy Bear Studios
# For license information, see LICENSE.txt
#
# ID: version.py [] benjamin@bengfort.com $
"""
Helper module for ORM... | (short=False):
"""
Returns the version from the version info.
"""
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['... | get_version | identifier_name |
version.py | # ormbad.version
# Helper module for ORMBad version information
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Thu Aug 13 12:38:42 2015 -0400
#
# Copyright (C) 2015 Tipsy Bear Studios
# For license information, see LICENSE.txt
#
# ID: version.py [] benjamin@bengfort.com $
"""
Helper module for ORM... |
return ''.join(vers)
| vers.append('%s%i' % (__version_info__['releaselevel'][0],
__version_info__['serial'])) | conditional_block |
issue-3447.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | next: None
};
println!("{}", ls.element);
} | let ls = list {
element: S, | random_line_split |
issue-3447.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
pub fn main() {
let ls = list {
element: S,
next: None
};
println!("{}", ls.element);
}
| {
let newList = list {
element: element,
next: None
};
self.next = Some(box RefCell::new(newList));
} | identifier_body |
issue-3447.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self, element: T) {
let newList = list {
element: element,
next: None
};
self.next = Some(box RefCell::new(newList));
}
}
pub fn main() {
let ls = list {
element: S,
next: None
};
println!("{}", ls.element);
}
| addEnd | identifier_name |
lib.rs | otemplates.org/) code generator *v0.1.8*.
//!
//! Everything else about the *replicapool* *v1_beta2* API can be found at the
//! [official documentation site](https://developers.google.com/compute/docs/instance-groups/manager/v1beta2).
//! The original source code is [on github](https://github.com/Byron/google-apis-rs... | //! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
//!
//! ## Optional Parts in Server-Requests
//!
//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and
//! [decodable](trait.ResponseResult.html) via ... | //! | random_line_split |
predictions.js | var express = require('express');
var router = express.Router();
var childProcess = require('child_process'),
jav;
router.get('/', function(req, res, next) {
var idModel = req.query.idModel,
predResult;
| console.log(error.stack);
console.log('Error code: '+error.code);
console.log('Signal received: '+error.signal);
}
predResult = JSON.parse(stdout);
res.json(predResult);
});
jav.on('exit', function (code) {
console.log('Child process exited with exit code '+ code);
//res.send... | jav = childProcess.exec('java -jar C:\\Users\\AegisLabs\\irfan-db\\Dropbox\\THESIS\\c0d3\\TwitterPredictionWithSVR\\dist\\TwitterPredictionWithSVR.jar '+idModel+' jml_respon_pertahap timestamp', function (error, stdout, stderr) {
if (error) { | random_line_split |
predictions.js | var express = require('express');
var router = express.Router();
var childProcess = require('child_process'),
jav;
router.get('/', function(req, res, next) {
var idModel = req.query.idModel,
predResult;
jav = childProcess.exec('java -jar C:\\Users\\AegisLabs\\irfan-db\\Dropbox\\THESIS\\c0d3\\TwitterPr... |
predResult = JSON.parse(stdout);
res.json(predResult);
});
jav.on('exit', function (code) {
console.log('Child process exited with exit code '+ code);
//res.send(predResult);
});
});
router.get('/listHashtag', function(req, res, next){
var idUser = req.query.idUser;
var UserHashtag = [
... | {
console.log(error.stack);
console.log('Error code: '+error.code);
console.log('Signal received: '+error.signal);
} | conditional_block |
git_gc.rs | //! Tests for git garbage collection.
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;
use std::process::Command;
use cargo_test_support::git;
use cargo_test_support::paths;
use cargo_test_support::project;
use cargo_test_support::registry::Package;
use url::Url;
fn find_index() -> PathBuf {
let dir =... |
None => return,
}
run_test(Some(&env::join_paths(&paths).unwrap()));
}
| {
paths.remove(i);
} | conditional_block |
git_gc.rs | //! Tests for git garbage collection.
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;
use std::process::Command;
use cargo_test_support::git;
use cargo_test_support::paths;
use cargo_test_support::project;
use cargo_test_support::registry::Package;
use url::Url;
fn find_index() -> PathBuf {
let dir =... | fn run_test(path_env: Option<&OsStr>) {
const N: usize = 50;
let foo = project()
.file(
"Cargo.toml",
r#"
[package]
name = "foo"
version = "0.0.1"
authors = []
[dependencies]
bar = "... | random_line_split | |
git_gc.rs | //! Tests for git garbage collection.
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;
use std::process::Command;
use cargo_test_support::git;
use cargo_test_support::paths;
use cargo_test_support::project;
use cargo_test_support::registry::Package;
use url::Url;
fn find_index() -> PathBuf {
let dir =... | () {
let path = env::var_os("PATH").unwrap_or_default();
let mut paths = env::split_paths(&path).collect::<Vec<_>>();
let idx = paths
.iter()
.position(|p| p.join("git").exists() || p.join("git.exe").exists());
match idx {
Some(i) => {
paths.remove(i);
}
... | avoid_using_git | identifier_name |
git_gc.rs | //! Tests for git garbage collection.
use std::env;
use std::ffi::OsStr;
use std::path::PathBuf;
use std::process::Command;
use cargo_test_support::git;
use cargo_test_support::paths;
use cargo_test_support::project;
use cargo_test_support::registry::Package;
use url::Url;
fn find_index() -> PathBuf {
let dir =... |
#[cargo_test]
fn avoid_using_git() {
let path = env::var_os("PATH").unwrap_or_default();
let mut paths = env::split_paths(&path).collect::<Vec<_>>();
let idx = paths
.iter()
.position(|p| p.join("git").exists() || p.join("git.exe").exists());
match idx {
Some(i) => {
... | {
if Command::new("git").arg("--version").output().is_err() {
return;
}
run_test(None);
} | identifier_body |
Modal.d.ts | import * as React from 'react';
import { StandardProps } from '..';
import { BackdropProps } from './Backdrop';
import { TransitionDuration, TransitionHandlers } from '../internal/transition';
export interface ModalProps extends StandardProps<
React.HtmlHTMLAttributes<HTMLDivElement> & Partial<TransitionHandlers>,
... | onRequestClose?: React.ReactEventHandler<{}>;
show?: boolean;
}
export type ModalClassKey =
| 'root'
| 'hidden'
;
declare const Modal: React.ComponentType<ModalProps>;
export default Modal; | ignoreBackdropClick?: boolean;
ignoreEscapeKeyUp?: boolean;
modalManager?: Object;
onBackdropClick?: React.ReactEventHandler<{}>;
onEscapeKeyUp?: React.ReactEventHandler<{}>; | random_line_split |
test_parserForINSIDE.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
import unittest
import logging
import json
from cameo.parserForINSIDE import ParserForINSIDE
"""
測試 解析 硬塞的 頁面
"""
class ParserForI... | parser = ParserForINSIDE()
parser.parseTagPage()
"""
#測試 解析 news.html 以找出更多 tag
def test_findMoreTagByParseNewsPage(self):
logging.info("ParserForINSIDETest.test_findMoreTagByParseNewsPage")
parser = ParserForINSIDE()
parser.findMoreTagByParseNewsPage()
#測試 解... | random_line_split | |
test_parserForINSIDE.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
import unittest
import logging
import json
from cameo.parserForINSIDE import ParserForINSIDE
"""
測試 解析 硬塞的 頁面
"""
class ParserForI... | g.basicConfig(level=logging.INFO)
pass
#收尾
def tearDown(self):
pass
"""
#測試 解析 index.html
def test_parseIndexPage(self):
logging.info("ParserForINSIDETest.test_parseIndexPage")
parser = ParserForINSIDE()
parser.parseIndexPage()
"""
#測試 解析 tag.... | oggin | identifier_name |
test_parserForINSIDE.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
import unittest
import logging
import json
from cameo.parserForINSIDE import ParserForINSIDE
"""
測試 解析 硬塞的 頁面
"""
class ParserForI... | conditional_block | ||
test_parserForINSIDE.py | # -*- coding: utf-8 -*-
"""
Copyright (C) 2015, MuChu Hsu
Contributed by Muchu Hsu (muchu1983@gmail.com)
This file is part of BSD license
<https://opensource.org/licenses/BSD-3-Clause>
"""
import unittest
import logging
import json
from cameo.parserForINSIDE import ParserForINSIDE
"""
測試 解析 硬塞的 頁面
"""
class ParserForI... | def test_findMoreTagByParseNewsPage(self):
logging.info("ParserForINSIDETest.test_findMoreTagByParseNewsPage")
parser = ParserForINSIDE()
parser.findMoreTagByParseNewsPage()
#測試 解析 news.html 並建立 news.json
def test_parseNewsPageThenCreateNewsJson(self):
logging.info("Pars... | logging.basicConfig(level=logging.INFO)
pass
#收尾
def tearDown(self):
pass
"""
#測試 解析 index.html
def test_parseIndexPage(self):
logging.info("ParserForINSIDETest.test_parseIndexPage")
parser = ParserForINSIDE()
parser.parseIndexPage()
"""
#測... | identifier_body |
writeJointRos.py | #!/usr/bin/env python
import roslib;
import rospy
import serial
import time
#COM.baudrate=115200
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import JointState
global COM
def callback(data):
|
def listener():
# in ROS, nodes are unique named. If two nodes with the same
# node are launched, the previous one is kicked off. The
# anonymous=True flag means that rospy will choose a unique
# name for our 'listener' node so that multiple listeners can
# run simultaenously.
rospy.init... | rospy.loginfo(rospy.get_caller_id()+"I heard %s",data.position)
global COM
buffer=[]
j =[0.7,0.5,0.0,0.2,-0.4,1.5]
j[0]=data.position[0]
while 1:
A = COM.read(1)
print A
buffer.append(A)
if A == '\n':
if "A" in buffer:
#print "GOT an A: ", buffer
#... | identifier_body |
writeJointRos.py | #!/usr/bin/env python
import roslib;
import rospy
import serial
import time
#COM.baudrate=115200
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import JointState
global COM
def callback(data):
rospy.loginfo(rospy.get_caller_id()+"I heard %s",data.position)
global COM
buffer=[]
j =[0.7,0.5,... | ():
# in ROS, nodes are unique named. If two nodes with the same
# node are launched, the previous one is kicked off. The
# anonymous=True flag means that rospy will choose a unique
# name for our 'listener' node so that multiple listeners can
# run simultaenously.
rospy.init_node('listener', ... | listener | identifier_name |
writeJointRos.py | #!/usr/bin/env python
import roslib;
import rospy
import serial
import time
#COM.baudrate=115200
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import JointState
global COM
def callback(data):
rospy.loginfo(rospy.get_caller_id()+"I heard %s",data.position)
global COM
buffer=[]
j =[0.7,0.5,... |
def listener():
# in ROS, nodes are unique named. If two nodes with the same
# node are launched, the previous one is kicked off. The
# anonymous=True flag means that rospy will choose a unique
# name for our 'listener' node so that multiple listeners can
# run simultaenously.
rospy.init... | if "A" in buffer:
#print "GOT an A: ", buffer
#print "data pos 0:", data.position
S = str(data.position[0]) + ',' + str(data.position[1]) + ',' + str(j[2]) + ',' + str(j[3]) + ',' + str(j[4]) + ',' + str(j[5]) + "\r\n"
print "SENDING:",S
COM.write(S)
return
... | conditional_block |
writeJointRos.py | #!/usr/bin/env python
import roslib;
import rospy
import serial
import time
#COM.baudrate=115200 |
global COM
def callback(data):
rospy.loginfo(rospy.get_caller_id()+"I heard %s",data.position)
global COM
buffer=[]
j =[0.7,0.5,0.0,0.2,-0.4,1.5]
j[0]=data.position[0]
while 1:
A = COM.read(1)
print A
buffer.append(A)
if A == '\n':
if "A" in buffer:
#p... |
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import JointState | random_line_split |
hbFontaineListController.js | (function() {
angular.module('hb5').controller('HbFontaineListController', ['$attrs', '$scope', 'GeoxmlService', '$routeParams', '$log', '$filter', '$timeout', 'hbAlertMessages', 'hbUtil', function($attrs, $scope, GeoxmlService, $routeParams, $log, $filter, $timeout, hbAlertMessages, hbUtil) {
$log.debug... | */
$scope.$watch('[search,predicate,reverse]', function(newSearch, oldSearch) {
//$log.debug(">>>>> HbFontaineListController search, predicate or reverse UPDATED <<<<< \n" + angular.toJson(newSearch) );
if ($scope.elfins!=null) {
$scope.filteredElfins = filterSortElfins($scope.elfins, $scope.sea... | };
/**
* Update filtered collection when search or sorting criteria are modified. | random_line_split |
hbFontaineListController.js | (function() {
angular.module('hb5').controller('HbFontaineListController', ['$attrs', '$scope', 'GeoxmlService', '$routeParams', '$log', '$filter', '$timeout', 'hbAlertMessages', 'hbUtil', function($attrs, $scope, GeoxmlService, $routeParams, $log, $filter, $timeout, hbAlertMessages, hbUtil) {
$log.debug... |
}, true);
/**
* elfins can result from queries taking possibly seconds to tens of seconds to complete.
* This requires watching for elfins result availability before computing filteredElfins.length.
*/
$scope.$watch('elfins', function() {
if ($scope.elfins!=null) {
$scope.fi... | {
$scope.filteredElfins = filterSortElfins($scope.elfins, $scope.search, $scope.predicate, $scope.reverse);
} | conditional_block |
addtrack.py | """
//=========================================================
// OOMidi
// OpenOctave Midi and Audio Editor
// (C) Copyright 2009 Mathias Gyllengahm (lunar_shuttle@users.sf.net)
//=========================================================
"""
import Pyro.core
import time
oom=Pyro.core.getProxyForURI('PYRONAME://:... | oom.addInput("aninput")
oom.setMute("aninput", False)
oom.setAudioTrackVolume("aninput",1.0)
oom.deleteTrack("amiditrack")
oom.deleteTrack("awavetrack")
oom.deleteTrack("anoutput")
oom.deleteTrack("aninput")
time.sleep(1) | oom.addWaveTrack("awavetrack")
oom.addOutput("anoutput") | random_line_split |
addtrack.py | """
//=========================================================
// OOMidi
// OpenOctave Midi and Audio Editor
// (C) Copyright 2009 Mathias Gyllengahm (lunar_shuttle@users.sf.net)
//=========================================================
"""
import Pyro.core
import time
oom=Pyro.core.getProxyForURI('PYRONAME://:... |
for i in range(0, 10):
print i
oom.addMidiTrack("amiditrack")
oom.addWaveTrack("awavetrack")
oom.addOutput("anoutput")
oom.addInput("aninput")
oom.setMute("aninput", False)
oom.setAudioTrackVolume("aninput",1.0)
oom.deleteTrack("amiditrack")
oom.deleteTrack("awave... | oom.deleteTrack("amiditrack" + str(i)) | conditional_block |
union_with_anon_struct.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union foo {
pub bar: foo__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo__bindgen_ty_1 {
pub a: ::std::os::raw::c_uin... | unsafe {
&(*(::std::ptr::null::<foo__bindgen_ty_1>())).b as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(foo__bindgen_ty_1),
"::",
stringify!(b)
)
);
}
#[test]
fn bindgen_test_layout_foo() {
... | random_line_split | |
union_with_anon_struct.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union foo {
pub bar: foo__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo__bindgen_ty_1 {
pub a: ::std::os::raw::c_uin... |
impl Default for foo {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
| {
assert_eq!(
::std::mem::size_of::<foo>(),
8usize,
concat!("Size of: ", stringify!(foo))
);
assert_eq!(
::std::mem::align_of::<foo>(),
4usize,
concat!("Alignment of ", stringify!(foo))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<foo>())).ba... | identifier_body |
union_with_anon_struct.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Copy, Clone)]
pub union foo {
pub bar: foo__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct foo__bindgen_ty_1 {
pub a: ::std::os::raw::c_uin... | () {
assert_eq!(
::std::mem::size_of::<foo__bindgen_ty_1>(),
8usize,
concat!("Size of: ", stringify!(foo__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<foo__bindgen_ty_1>(),
4usize,
concat!("Alignment of ", stringify!(foo__bindgen_ty_1))
);
asse... | bindgen_test_layout_foo__bindgen_ty_1 | identifier_name |
533646c7af38_remove_unused_attr_status.py | # Copyright 2015 Mirantis, 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, s... | try:
op.add_column(
t_name,
sql.Column(
COLUMN_NAME,
# NOTE(vponomaryov): original type of attr was enum. But
# alembic is buggy with enums [1], so use string type
# instead. Anyway we have no rea... | conditional_block | |
533646c7af38_remove_unused_attr_status.py | # Copyright 2015 Mirantis, 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, s... | for t_name in TABLE_NAMES:
try:
op.add_column(
t_name,
sql.Column(
COLUMN_NAME,
# NOTE(vponomaryov): original type of attr was enum. But
# alembic is buggy with enums [1], so use string type
... | identifier_body | |
533646c7af38_remove_unused_attr_status.py | # Copyright 2015 Mirantis, 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, s... | from oslo_log import log
import sqlalchemy as sql
from manila.common import constants
from manila.i18n import _LE
LOG = log.getLogger(__name__)
COLUMN_NAME = 'status'
TABLE_NAMES = ('network_allocations', 'security_services')
def upgrade():
for t_name in TABLE_NAMES:
try:
op.drop_column(t_na... | from alembic import op | random_line_split |
533646c7af38_remove_unused_attr_status.py | # Copyright 2015 Mirantis, 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, s... | ():
for t_name in TABLE_NAMES:
try:
op.add_column(
t_name,
sql.Column(
COLUMN_NAME,
# NOTE(vponomaryov): original type of attr was enum. But
# alembic is buggy with enums [1], so use string type
... | downgrade | identifier_name |
ajax.js | /**
* Ajax函数
*/
// 创建一个XMLHttpRequest对象
var createXHR;
if (window.XMLHttpRequest) {
createXHR = function() {
return new XMLHttpRequest();
};
} else if (window.ActiveXObject) {
createXHR = function() {
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
// 发起异步请求,默认为GET请求
function aja... | async = opts.async || true,
data = opts.data || null,
headers = opts.headers || {};
var xhr = createXHR();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
opts.onsuccess && opts.onsuccess(xhr.responseText);
} else {
... | identifier_body | |
ajax.js | /**
* Ajax函数
*/
// 创建一个XMLHttpRequest对象
var createXHR;
if (window.XMLHttpRequest) {
createXHR = function() {
return new XMLHttpRequest();
};
} else if (window.ActiveXObject) {
createXHR | ET请求
function ajax(url, opts) {
var type = opts.type || 'get',
async = opts.async || true,
data = opts.data || null,
headers = opts.headers || {};
var xhr = createXHR();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
opts.on... | = function() {
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
// 发起异步请求,默认为G | conditional_block |
ajax.js | /**
* Ajax函数
*/
// 创建一个XMLHttpRequest对象
var createXHR;
if (window.XMLHttpRequest) {
createXHR = function() {
return new XMLHttpRequest();
};
} else if (window.ActiveXObject) {
createXHR = function() {
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
// 发起异步请求,默认为GET请求
function aja... | | 'get',
async = opts.async || true,
data = opts.data || null,
headers = opts.headers || {};
var xhr = createXHR();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
opts.onsuccess && opts.onsuccess(xhr.responseText);
} els... | pe | | identifier_name |
ajax.js | /**
* Ajax函数
*/
// 创建一个XMLHttpRequest对象
var createXHR;
if (window.XMLHttpRequest) {
createXHR = function() {
return new XMLHttpRequest();
};
} else if (window.ActiveXObject) {
createXHR = function() {
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
// 发起异步请求,默认为GET请求
function aja... | } | random_line_split | |
setup.py | #!/usr/bin/env python
# Copyright 2013-2015 Julian Metzler
"""
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, either version 3 of the License, or
(at your option) any later version.
This pro... | metadata = {}
with open('tweetpony/metadata.py') as f:
exec(f.read(), metadata)
setup(
name = metadata['name'],
version = metadata['version'],
description = metadata['description'],
license = metadata['license'],
author = metadata['author'],
author_email = metadata['author_email'],
install_requires = metadata[... |
from setuptools import setup, find_packages
| random_line_split |
CurrentScenarioContext.tsx | import {CircularProgress} from '@material-ui/core';
import IWeights from '@shared/interface/IWeights';
import {TPvf} from '@shared/interface/Problem/IPvf';
import {ILinearPvf} from '@shared/interface/Pvfs/ILinearPvf';
import IMcdaScenario from '@shared/interface/Scenario/IMcdaScenario';
import {TPreferences} from '@sha... | (criterionId: string): void {
setAdvancedPvfCriterionId(criterionId);
setActiveView('advancedPvf');
}
function setPvf(criterionId: string, pvf: TPvf): void {
const newPvfs = {...pvfs, [criterionId]: pvf};
setPvfs(newPvfs);
const newScenario = createScenarioWithPvf(
criterionId,
pvf,... | goToAdvancedPvf | identifier_name |
CurrentScenarioContext.tsx | import {CircularProgress} from '@material-ui/core';
import IWeights from '@shared/interface/IWeights';
import {TPvf} from '@shared/interface/Problem/IPvf';
import {ILinearPvf} from '@shared/interface/Pvfs/ILinearPvf';
import IMcdaScenario from '@shared/interface/Scenario/IMcdaScenario';
import {TPreferences} from '@sha... |
setElicitationMethod(
determineElicitationMethod(currentScenario.state.prefs)
);
}
}, [configuredRanges, currentScenario, filteredCriteria, getWeights]);
function getPvf(criterionId: string): TPvf {
return pvfs[criterionId];
}
function resetPreferences(scenario: IMcdaScenario) {
... | {
getWeights(currentScenario, newPvfs);
} | conditional_block |
CurrentScenarioContext.tsx | import {CircularProgress} from '@material-ui/core';
import IWeights from '@shared/interface/IWeights';
import {TPvf} from '@shared/interface/Problem/IPvf';
import {ILinearPvf} from '@shared/interface/Pvfs/ILinearPvf';
import IMcdaScenario from '@shared/interface/Scenario/IMcdaScenario';
import {TPreferences} from '@sha... | }>();
const {setError} = useContext(ErrorContext);
const {
settings: {randomSeed}
} = useContext(SettingsContext);
const {
filteredCriteria,
filteredWorkspace,
getCriterion,
configuredRanges,
getConfiguredRange
} = useContext(CurrentSubproblemContext);
const {getScenario, updateS... | const {workspaceId, subproblemId, scenarioId} = useParams<{
workspaceId: string;
subproblemId: string;
scenarioId: string; | random_line_split |
CurrentScenarioContext.tsx | import {CircularProgress} from '@material-ui/core';
import IWeights from '@shared/interface/IWeights';
import {TPvf} from '@shared/interface/Problem/IPvf';
import {ILinearPvf} from '@shared/interface/Pvfs/ILinearPvf';
import IMcdaScenario from '@shared/interface/Scenario/IMcdaScenario';
import {TPreferences} from '@sha... | const {getScenario, updateScenarios} = useContext(ScenariosContext);
const [currentScenario, setCurrentScenario] = useState<IMcdaScenario>(
getScenario(scenarioId)
);
const [pvfs, setPvfs] = useState<Record<string, TPvf>>();
const disableWeightsButtons = !areAllPvfsSet(filteredCriteria, pvfs);
const [a... | {
const history = useHistory();
const {workspaceId, subproblemId, scenarioId} = useParams<{
workspaceId: string;
subproblemId: string;
scenarioId: string;
}>();
const {setError} = useContext(ErrorContext);
const {
settings: {randomSeed}
} = useContext(SettingsContext);
const {
filter... | identifier_body |
search-modal.component.ts | import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {RutrackerService} from '../core/rutracker.service';
import * as _ from 'lodash';
declare const UIkit: any;
@Component({
selector: 'magnet-search-modal',
templateUrl: './search-modal.component.html',
styleUrls: ['./search-modal... | (form) {
this.rutrackerService.searchByTitle(form.searchQuery, result => {
this.searchResult = _.orderBy(result, [(item) => parseInt(item.seeds, 10), (item) => item.title], ['asc', 'desc']).reverse();
this.searchResultEvent.emit(this.searchResult);
});
this.searchMode = true;
this.toggleS... | search | identifier_name |
search-modal.component.ts | import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {RutrackerService} from '../core/rutracker.service';
import * as _ from 'lodash';
declare const UIkit: any;
@Component({
selector: 'magnet-search-modal',
templateUrl: './search-modal.component.html',
styleUrls: ['./search-modal... |
ngOnInit() {
}
}
| {
this.rutrackerService.searchByTitle(form.searchQuery, result => {
this.searchResult = _.orderBy(result, [(item) => parseInt(item.seeds, 10), (item) => item.title], ['asc', 'desc']).reverse();
this.searchResultEvent.emit(this.searchResult);
});
this.searchMode = true;
this.toggleSearchMo... | identifier_body |
search-modal.component.ts | import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {RutrackerService} from '../core/rutracker.service';
import * as _ from 'lodash';
declare const UIkit: any;
@Component({
selector: 'magnet-search-modal',
templateUrl: './search-modal.component.html',
styleUrls: ['./search-modal... | @Output() searchResultEvent = new EventEmitter<boolean>();
public searchQuery: string;
public searchResult;
constructor(private rutrackerService: RutrackerService) {
}
public search(form) {
this.rutrackerService.searchByTitle(form.searchQuery, result => {
this.searchResult = _.orderBy(result, [... | })
export class SearchModalComponent implements OnInit {
@Input() searchMode;
@Output() toggleSearchModeEvent = new EventEmitter<boolean>(); | random_line_split |
mozambique.py | # -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Authors: dr-prodigy <maurizio.... | MZ(Mozambique):
pass
class MOZ(Mozambique):
pass
| bserved and year > 1974:
if k.weekday() == SUN:
self[k + rd(days=1)] = v + " (PONTE)"
class | conditional_block |
mozambique.py | # -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Authors: dr-prodigy <maurizio.... | HolidayBase.__init__(self, **kwargs)
def _populate(self, year):
if year > 1974:
self[date(year, 1, 1)] = "Ano novo"
e = easter(year)
good_friday = e - rd(days=2)
self[good_friday] = "Sexta-feira Santa"
# carnival is the Tuesday before As... |
class Mozambique(HolidayBase):
country = "MZ"
def __init__(self, **kwargs): | random_line_split |
mozambique.py | # -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Authors: dr-prodigy <maurizio.... | ue):
pass
| biq | identifier_name |
mozambique.py | # -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Authors: dr-prodigy <maurizio.... | MOZ(Mozambique):
pass
| ass | identifier_body |
socketpair_helper.py | import socket
# Figuring out what errors could come out of a socket. There are three
# different situations. Python 3 post-PEP3151 will define and use
# BlockingIOError and InterruptedError from sockets. For Python pre-PEP3151
# both OSError and socket.error can be raised except on Windows where
# WindowsError can als... | ssock, _ = lsock.accept()
except:
csock.close()
raise
finally:
lsock.close()
return (ssock, csock) | csock.connect((addr, port))
except _CONNECT_ERROR:
pass
csock.setblocking(True) | random_line_split |
socketpair_helper.py | import socket
# Figuring out what errors could come out of a socket. There are three
# different situations. Python 3 post-PEP3151 will define and use
# BlockingIOError and InterruptedError from sockets. For Python pre-PEP3151
# both OSError and socket.error can be raised except on Windows where
# WindowsError can als... |
else:
raise ValueError("Only AF_INET and AF_INET6 socket address "
"families are supported")
if type != socket.SOCK_STREAM:
raise ValueError("Only SOCK_STREAM socket type is supported")
if proto != 0:
raise ValueError("Only protoc... | host = '::1' | conditional_block |
socketpair_helper.py | import socket
# Figuring out what errors could come out of a socket. There are three
# different situations. Python 3 post-PEP3151 will define and use
# BlockingIOError and InterruptedError from sockets. For Python pre-PEP3151
# both OSError and socket.error can be raised except on Windows where
# WindowsError can als... | try:
lsock.bind((host, 0))
lsock.listen(1)
# On IPv6, ignore flow_info and scope_id
addr, port = lsock.getsockname()[:2]
csock = socket.socket(family, type, proto)
try:
csock.setblocking(False)
try:
... | """A socket pair usable as a self-pipe, for Windows.
Origin: https://gist.github.com/4325783, by Geert Jansen.
Public domain.
"""
if family == socket.AF_INET:
host = '127.0.0.1'
elif family == socket.AF_INET6:
host = '::1'
else:
raise ... | identifier_body |
socketpair_helper.py | import socket
# Figuring out what errors could come out of a socket. There are three
# different situations. Python 3 post-PEP3151 will define and use
# BlockingIOError and InterruptedError from sockets. For Python pre-PEP3151
# both OSError and socket.error can be raised except on Windows where
# WindowsError can als... | (family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0):
"""A socket pair usable as a self-pipe, for Windows.
Origin: https://gist.github.com/4325783, by Geert Jansen.
Public domain.
"""
if family == socket.AF_INET:
host = '127.0.0.1'
elif family == socket.... | socketpair | identifier_name |
common.rs | /*
* Copyright 2014 The Android Open Source Project
*
* 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 applica... | #pragma rs java_package_name(android.hardware.camera2.cts)
#pragma rs_fp_relaxed
typedef uchar3 yuvx_444; // interleaved YUV. (y,u,v) per pixel. use .x/.y/.z to read
typedef uchar3 yuvf_420; // flexible YUV (4:2:0). use rsGetElementAtYuv to read.
#define convert_yuvx_444 convert_uchar3
#define convert_yuvf_420 __erro... |
#pragma version(1) | random_line_split |
Layout.tsx | import Colors from "v2/Assets/Colors"
import { avantgarde } from "v2/Assets/Fonts"
import { Component } from "react";
import styled from "styled-components"
import MultiStateButton, {
MultiButtonState,
} from "../../Buttons/MultiStateButton"
import { media } from "../../Helpers"
import StyledTitle from "../../Title"
... | </NextButton>
</StickyButtonContainer>
</FixedButttonContainer>
</Container>
)
}
} | {buttonText} | random_line_split |
Layout.tsx | import Colors from "v2/Assets/Colors"
import { avantgarde } from "v2/Assets/Fonts"
import { Component } from "react";
import styled from "styled-components"
import MultiStateButton, {
MultiButtonState,
} from "../../Buttons/MultiStateButton"
import { media } from "../../Helpers"
import StyledTitle from "../../Title"
... | () {
const disabled = !this.props.onNextButtonPressed
const buttonText = this.props.isLastStep ? "finished" : "next"
return (
<Container>
<MainTitle>{this.props.title} </MainTitle>
<Subtitle titleSize="xxsmall">{this.props.subtitle}</Subtitle>
<ItemContainer>{this.props.childre... | render | identifier_name |
connection.js | const EventEmitter = require("events");
const ssh2 = require("ssh2");
const Client = ssh2.Client;
class Connection extends EventEmitter {
constructor (connectOptions, dimensions) {
this.connectOptions = connectOptions;
this.dimensions = dimensions;
this.errorCallback = errorCallback;
if (!this.errorCallback) ... |
onErrorData (data) {
this.emit("data", data);
this.emit("stderr", data);
}
onClose () {
this.emit("info", "Connection stream closed");
this.connection.end();
this.stream = null;
}
}
module.exports = Connection; | {
this.emit("data", data);
this.emit("stdout", data);
} | identifier_body |
connection.js | const EventEmitter = require("events");
const ssh2 = require("ssh2");
const Client = ssh2.Client;
class Connection extends EventEmitter {
constructor (connectOptions, dimensions) {
this.connectOptions = connectOptions;
this.dimensions = dimensions;
this.errorCallback = errorCallback;
if (!this.errorCallback) ... | if (err)
return errorCallback();
this.emit("info", "Connection successful");
this.stream = stream;
stream
.on("close", this.onClose.bind(this))
.on("data", this.onData.bind(this))
.stderr.on("data", onErrorData.bind(this));
}
onData (data) {
this.emit("data", data);
this.emit("stdout", data);
... | console.warn("Connection not established! (write)");
}
}
// Events
onConnect (err, stream) { | random_line_split |
connection.js | const EventEmitter = require("events");
const ssh2 = require("ssh2");
const Client = ssh2.Client;
class | extends EventEmitter {
constructor (connectOptions, dimensions) {
this.connectOptions = connectOptions;
this.dimensions = dimensions;
this.errorCallback = errorCallback;
if (!this.errorCallback) {
this.errorCallback = function () {};
}
this.stream = null;
this.connection = new Client();
}
ready ... | Connection | identifier_name |
template_preparser.ts | import {HtmlElementAst} from './html_ast';
import {isBlank, isPresent} from 'angular2/src/core/facade/lang';
const NG_CONTENT_SELECT_ATTR = 'select';
const NG_CONTENT_ELEMENT = 'ng-content';
const LINK_ELEMENT = 'link';
const LINK_STYLE_REL_ATTR = 'rel';
const LINK_STYLE_HREF_ATTR = 'href';
const LINK_STYLE_REL_VALUE ... | {
if (isBlank(selectAttr) || selectAttr.length === 0) {
return '*';
}
return selectAttr;
} | identifier_body | |
template_preparser.ts | import {HtmlElementAst} from './html_ast';
import {isBlank, isPresent} from 'angular2/src/core/facade/lang';
const NG_CONTENT_SELECT_ATTR = 'select';
const NG_CONTENT_ELEMENT = 'ng-content';
const LINK_ELEMENT = 'link';
const LINK_STYLE_REL_ATTR = 'rel';
const LINK_STYLE_HREF_ATTR = 'href';
const LINK_STYLE_REL_VALUE ... | else if (attr.name == NG_NON_BINDABLE_ATTR) {
nonBindable = true;
}
});
selectAttr = normalizeNgContentSelect(selectAttr);
var nodeName = ast.name;
var type = PreparsedElementType.OTHER;
if (nonBindable) {
type = PreparsedElementType.NON_BINDABLE;
} else if (nodeName == NG_CONTENT_ELEMENT) {
... | {
relAttr = attr.value;
} | conditional_block |
template_preparser.ts | import {HtmlElementAst} from './html_ast';
import {isBlank, isPresent} from 'angular2/src/core/facade/lang';
const NG_CONTENT_SELECT_ATTR = 'select';
const NG_CONTENT_ELEMENT = 'ng-content';
const LINK_ELEMENT = 'link';
const LINK_STYLE_REL_ATTR = 'rel';
const LINK_STYLE_HREF_ATTR = 'href';
const LINK_STYLE_REL_VALUE ... | {
constructor(public type: PreparsedElementType, public selectAttr: string,
public hrefAttr: string) {}
}
function normalizeNgContentSelect(selectAttr: string): string {
if (isBlank(selectAttr) || selectAttr.length === 0) {
return '*';
}
return selectAttr;
}
| PreparsedElement | identifier_name |
template_preparser.ts | import {HtmlElementAst} from './html_ast';
import {isBlank, isPresent} from 'angular2/src/core/facade/lang';
const NG_CONTENT_SELECT_ATTR = 'select';
const NG_CONTENT_ELEMENT = 'ng-content';
const LINK_ELEMENT = 'link';
const LINK_STYLE_REL_ATTR = 'rel';
const LINK_STYLE_HREF_ATTR = 'href';
const LINK_STYLE_REL_VALUE ... | if (attr.name == NG_CONTENT_SELECT_ATTR) {
selectAttr = attr.value;
} else if (attr.name == LINK_STYLE_HREF_ATTR) {
hrefAttr = attr.value;
} else if (attr.name == LINK_STYLE_REL_ATTR) {
relAttr = attr.value;
} else if (attr.name == NG_NON_BINDABLE_ATTR) {
nonBindable = true;
... | ast.attrs.forEach(attr => { | random_line_split |
test_exceptions.py | from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
from .test_extends import inheritance_templates
class ExceptionsTests(SimpleTestCase):
@setup({'exception01': "{% extends 'nonexistent' %}"})
def test_exception01(... |
else:
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('exception02')
@setup(
{'exception03': "{% extends 'inheritance01' %}"
"{% block first %}2{% endblock %}{% extends 'inheritance16' %}"},
inheritance_t... | with self.assertRaises(TemplateDoesNotExist):
self.engine.render_to_string('exception02') | conditional_block |
test_exceptions.py | from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
from .test_extends import inheritance_templates
class ExceptionsTests(SimpleTestCase):
@setup({'exception01': "{% extends 'nonexistent' %}"})
def test_exception01(... |
@setup({'exception05': '{% block first %}{{ block.super }}{% endblock %}'})
def test_exception05(self):
"""
Raise exception for block.super used in base template
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string('exception05') | """
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('exception04')
| random_line_split |
test_exceptions.py | from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
from .test_extends import inheritance_templates
class ExceptionsTests(SimpleTestCase):
@setup({'exception01': "{% extends 'nonexistent' %}"})
def test_exception01(... |
@setup(
{'exception03': "{% extends 'inheritance01' %}"
"{% block first %}2{% endblock %}{% extends 'inheritance16' %}"},
inheritance_templates,
)
def test_exception03(self):
"""
Raise exception for extra {% extends %} tags
"""
... | """
Raise exception for invalid variable template name
"""
if self.engine.string_if_invalid:
with self.assertRaises(TemplateDoesNotExist):
self.engine.render_to_string('exception02')
else:
with self.assertRaises(TemplateSyntaxError):
... | identifier_body |
test_exceptions.py | from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
from .test_extends import inheritance_templates
class ExceptionsTests(SimpleTestCase):
@setup({'exception01': "{% extends 'nonexistent' %}"})
def | (self):
"""
Raise exception for invalid template name
"""
with self.assertRaises(TemplateDoesNotExist):
self.engine.render_to_string('exception01')
@setup({'exception02': '{% extends nonexistent %}'})
def test_exception02(self):
"""
Raise ex... | test_exception01 | identifier_name |
Ru_ru.js | ать по:',
SEARCH_BY_NAME: 'имени...',
FILTER_BY_TAG: 'тегу...',
BROWSE_GENRES: 'Обзор',
LOOKING_AT_GENRE: 'Вы смотрите по жанру:',
MARK_COMPLETED: 'Уже просмотрено!',
NO_TVSHOWS_FOUND: 'ТВ-шоу пока недоступно',
NO_MOVIES_FOUND: 'Кино пока недоступно',
WATCHLIST: 'Посмотреть позже'
},
VIDE... | OLDEST_UPDATED: 'Последнее обновление'
},
FAQ: {
UPLOAD_VIDEO: {
TITLE: 'Как я могу загрузить видео?',
TEXT: "Вы можете загружать видео, перейдя в меню «Управление». Выберите, что вы хотите загрузить: фильм, телешоу или другое видео. Выберите соответствующее подменю "+
"в левой част... | random_line_split | |
ioriocli.py | #!/usr/bin/env python3
'''ioriodb CLI client to interact with the api from the command line'''
from __future__ import print_function
import time
import json
import argparse
import iorio
def get_arg_parser():
'''build the cli arg parser'''
parser = argparse.ArgumentParser(description='Iorio DB CLI')
parser... |
return result
def handle_stats(args):
'''get events'''
def fun(conn):
'''fun that does the work'''
response = conn.stats()
stats = response.body
node_stats = stats['node']
abs1 = node_stats['abs1']
abs2 = node_stats['abs2']
keys = ['error_logger_qu... | val1 = dict1.get(key)
val2 = dict2.get(key)
if isinstance(val1, int) and isinstance(val2, int):
result[key] = val2 - val1 | conditional_block |
ioriocli.py | #!/usr/bin/env python3
'''ioriodb CLI client to interact with the api from the command line'''
from __future__ import print_function
import time
import json
import argparse
import iorio
def get_arg_parser():
'''build the cli arg parser'''
parser = argparse.ArgumentParser(description='Iorio DB CLI')
parser... |
def handle_post_event(args):
'''post a new event'''
post_or_patch(args, 'send')
def handle_patch_event(args):
'''patch a new event'''
post_or_patch(args, 'send_patch')
def handle_get_events(args):
'''get events'''
bucket = args.bucket
stream = args.stream
limit = args.limit
from... | '''avoid duplication'''
bucket = args.bucket
stream = args.stream
content_type = args.content_type
data_raw = args.data
data = parse_data_from_raw(data_raw)
def fun(conn):
'''fun that does the work'''
function = getattr(conn, name)
for _ in range(args.count):
... | identifier_body |
ioriocli.py | #!/usr/bin/env python3
'''ioriodb CLI client to interact with the api from the command line'''
from __future__ import print_function
import time
import json
import argparse
import iorio
def get_arg_parser():
'''build the cli arg parser'''
parser = argparse.ArgumentParser(description='Iorio DB CLI')
parser... | stream = args.stream
content_type = args.content_type
data_raw = args.data
data = parse_data_from_raw(data_raw)
def fun(conn):
'''fun that does the work'''
function = getattr(conn, name)
for _ in range(args.count):
result = function(bucket, stream, data, conten... | random_line_split | |
ioriocli.py | #!/usr/bin/env python3
'''ioriodb CLI client to interact with the api from the command line'''
from __future__ import print_function
import time
import json
import argparse
import iorio
def get_arg_parser():
'''build the cli arg parser'''
parser = argparse.ArgumentParser(description='Iorio DB CLI')
parser... | (conn):
'''fun that does the work'''
return conn.list_buckets()
do_when_authenticated(args, fun)
def diff_keys(dict1, dict2, keys):
'''calculate differebce between key on d2 and d1'''
result = {}
for key in keys:
val1 = dict1.get(key)
val2 = dict2.get(key)
if i... | fun | identifier_name |
stop.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... | }
actions
}
}
impl fmt::Display for Action {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"[Action] [StopRecording] Server #{}",
self.server_id
)
}
}
| {
info!("{} Stopping audio recording...", self);
if let Some(channel_name) = server.channel_name(&self.voice_channel_id) {
// Notify all users in the current voice channel
for member in server.channel_voice_members(&self.voice_channel_id) {
... | conditional_block |
stop.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... | {
server_id: ServerId,
voice_channel_id: ChannelId,
}
impl Action {
pub fn new(
server_id: ServerId,
voice_channel_id: ChannelId
) -> Box<Action> {
Box::new(Action {
server_id: server_id,
voice_channel_id: voice_channel_id
})
}
}
impl Actio... | Action | identifier_name |
stop.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... | server_id: ServerId,
voice_channel_id: ChannelId
) -> Box<Action> {
Box::new(Action {
server_id: server_id,
voice_channel_id: voice_channel_id
})
}
}
impl ActionHandler for Action {
fn run(&mut self, bot: &mut Bot, _: &BotConfig, queue: &mut EventQue... | random_line_split | |
stop.rs | // STD Dependencies -----------------------------------------------------------
use std::fmt;
// Discord Dependencies -------------------------------------------------------
use discord::model::{ChannelId, ServerId};
// Internal Dependencies ------------------------------------------------------
use ::bot::{Bot, Bo... |
server.stop_recording_voice(queue);
}
}
actions
}
}
impl fmt::Display for Action {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"[Action] [StopRecording] Server #{}",
self.server_id
)
}... | {
let mut actions: Vec<Box<ActionHandler>> = Vec::new();
if let Some(server) = bot.get_server(&self.server_id) {
info!("{} Stopping audio recording...", self);
if let Some(channel_name) = server.channel_name(&self.voice_channel_id) {
// Notify all users in th... | identifier_body |
cookie_reader.py | ########################################################################################################################
#
# cookie_reader.py
#
# Purpose: read cookies from the web browser (currently only Chrome supported) and make them into Python objects
#
# Author: Braxton J. Schafer (bjschafer) [bjs]
#
# Creation d... |
def read_teams(self):
decoded = self._get_json()
for team in decoded:
yield (team['name'], team['format'], [pokemon(t) for t in team['team']])
if __name__ == '__main__':
c = cookie_reader()
for t in c.read_teams():
print(t) | raw_json = str(self._read_from_database())
raw_json = raw_json[3:-3]
raw_json = raw_json.replace('\\x00', '')
return json.loads(raw_json) | identifier_body |
cookie_reader.py | ########################################################################################################################
#
# cookie_reader.py
#
# Purpose: read cookies from the web browser (currently only Chrome supported) and make them into Python objects
#
# Author: Braxton J. Schafer (bjschafer) [bjs]
#
# Creation d... | raw_json = raw_json.replace('\\x00', '')
return json.loads(raw_json)
def read_teams(self):
decoded = self._get_json()
for team in decoded:
yield (team['name'], team['format'], [pokemon(t) for t in team['team']])
if __name__ == '__main__':
c = cookie_reader()
... | def _get_json(self):
raw_json = str(self._read_from_database())
raw_json = raw_json[3:-3] | random_line_split |
cookie_reader.py | ########################################################################################################################
#
# cookie_reader.py
#
# Purpose: read cookies from the web browser (currently only Chrome supported) and make them into Python objects
#
# Author: Braxton J. Schafer (bjschafer) [bjs]
#
# Creation d... | (self):
raw_json = str(self._read_from_database())
raw_json = raw_json[3:-3]
raw_json = raw_json.replace('\\x00', '')
return json.loads(raw_json)
def read_teams(self):
decoded = self._get_json()
for team in decoded:
yield (team['name'], team['format'], ... | _get_json | identifier_name |
cookie_reader.py | ########################################################################################################################
#
# cookie_reader.py
#
# Purpose: read cookies from the web browser (currently only Chrome supported) and make them into Python objects
#
# Author: Braxton J. Schafer (bjschafer) [bjs]
#
# Creation d... |
if __name__ == '__main__':
c = cookie_reader()
for t in c.read_teams():
print(t) | yield (team['name'], team['format'], [pokemon(t) for t in team['team']]) | conditional_block |
index.bak.js | /*global module,require,__dirname*/
(function routesIndex(module, require, __dirname) {
"use strict";
var express = require('express');
var router = express.Router();
var _ = require('lodash');
var middleware = {
'': ['license'],
'/': ['about']
};
var dir = function(absPa... |
}
}
//var reader = require(srcDir + '/io/reader');
//middleware.forEach(function(def) {
// if(typeof def === 'string') {
// router.use(require('./router/' + def));
// }
//});
var jsonResponse = function(req, res, realRes) {
res.json(_.extend(req.response,... | {
router.use(route, require(routeDir + middleware[route]));
} | conditional_block |
index.bak.js | /*global module,require,__dirname*/
(function routesIndex(module, require, __dirname) {
"use strict";
var express = require('express');
var router = express.Router();
var _ = require('lodash');
var middleware = {
'': ['license'],
'/': ['about']
};
var dir = function(absPa... | // var data = {};
//
// var datasets = ['kanjidic'];
//
// if (!!req.query.dataset) {
// if (!(req.query.dataset instanceof Array)) {
// req.query.dataset = [req.query.dataset];
// }
//
// for (var i = 0; i < re... | //});
//router.get('/kanji', function(req, res, next) {
//
// try { | random_line_split |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyYtopt(PythonPackage):
| depends_on('py-ray', type=('build', 'run'))
depends_on('py-mpi4py@3.0.0:', type=('build', 'run'))
| """Ytopt package implements search using Random Forest (SuRF), an autotuning
search method developed within Y-Tune ECP project."""
maintainers = ['Kerilk']
homepage = "https://github.com/ytopt-team/ytopt"
url = "https://github.com/ytopt-team/ytopt/archive/refs/tags/v0.0.1.tar.gz"
version(... | identifier_body |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (PythonPackage):
"""Ytopt package implements search using Random Forest (SuRF), an autotuning
search method developed within Y-Tune ECP project."""
maintainers = ['Kerilk']
homepage = "https://github.com/ytopt-team/ytopt"
url = "https://github.com/ytopt-team/ytopt/archive/refs/tags/v0.0.1.... | PyYtopt | identifier_name |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyYtopt(PythonPackage):
"""Ytopt package implements search using Random Forest (SuRF), an ... | homepage = "https://github.com/ytopt-team/ytopt"
url = "https://github.com/ytopt-team/ytopt/archive/refs/tags/v0.0.1.tar.gz"
version('0.0.2', sha256='5a624aa678b976ff6ef867610bafcb0dfd5c8af0d880138ca5d56d3f776e6d71')
version('0.0.1', sha256='3ca616922c8e76e73f695a5ddea5dd91b0103eada726185f008343cc... | maintainers = ['Kerilk']
| random_line_split |
main.py | # HRGRN WebServices
# Copyright (C) 2016 Xinbin Dai, Irina Belyaeva
# This file is part of HRGRN WebServices API.
#
# HRGRN API 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... | (args):
session = Session()
# get service url
svc_url = svc.get_svc_base_url()
params = {'listall': 'T', 'format':'json'}
try:
with timer.Timer() as t:
log.info("Service URL:" + svc_url)
# execute request
response = rh.build_payload(svc_url, params,... | list | identifier_name |
main.py | # HRGRN WebServices
# Copyright (C) 2016 Xinbin Dai, Irina Belyaeva
# This file is part of HRGRN WebServices API.
#
# HRGRN API 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... |
except ValueError as e:
error_msg = "ValueError Exception:" + e.message
log.error(error_msg, exc_info=True)
raise Exception(error_msg)
except requests.exceptions.HTTPError as e:
error_msg = "HTTPError Exception:" + e.message
log.error(error_msg, exc_info... | session = Session()
# get service url
svc_url = svc.get_svc_base_url()
params = {'listall': 'T', 'format':'json'}
try:
with timer.Timer() as t:
log.info("Service URL:" + svc_url)
# execute request
response = rh.build_payload(svc_url, params, session)
... | identifier_body |
main.py | # HRGRN WebServices
# Copyright (C) 2016 Xinbin Dai, Irina Belyaeva
# This file is part of HRGRN WebServices API.
#
# HRGRN API 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... | """
import json
import requests
import logging
import timer as timer
from requests.exceptions import ConnectionError
from requests import Session
import service as svc
import request_handler as rh
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
# This function act... |
"""
Main Module | random_line_split |
main.py | # HRGRN WebServices
# Copyright (C) 2016 Xinbin Dai, Irina Belyaeva
# This file is part of HRGRN WebServices API.
#
# HRGRN API 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... |
except ValueError as e:
error_msg = "ValueError Exception:" + e.message
log.error(error_msg, exc_info=True)
raise Exception(error_msg)
except requests.exceptions.HTTPError as e:
error_msg = "HTTPError Exception:" + e.message
log.error(error_msg, exc_inf... | raise Exception("Response cannot be null!") | conditional_block |
membership.py | # @@ maybe these should go in a team.py
from zope.interface import Interface, Attribute
from zope.interface import implements
from Products.TeamSpace.interfaces.membership import ITeamMembership
class | (ITeamMembership):
"""
Interface provided by OpenMembership objects.
"""
class IMembershipTransitionEvent(Interface):
"""
A membership object has made a workflow transition to a new state
"""
transition = Attribute('name of the transition')
obj = Attribute('object that made said trans... | IOpenMembership | identifier_name |
membership.py | # @@ maybe these should go in a team.py
from zope.interface import Interface, Attribute
from zope.interface import implements
from Products.TeamSpace.interfaces.membership import ITeamMembership
class IOpenMembership(ITeamMembership):
"""
Interface provided by OpenMembership objects.
"""
class IMembershi... |
Does nothing if the invitation doesn't exist.
"""
def removeAllInvitesForAddress(address):
"""
Removes registration of all invitations for the specified
email address.
Does nothing if no invitations exist for the specified
address.
"""
def conv... | """
Removes the invitation registered for the specified email
address and project id. | random_line_split |
membership.py | # @@ maybe these should go in a team.py
from zope.interface import Interface, Attribute
from zope.interface import implements
from Products.TeamSpace.interfaces.membership import ITeamMembership
class IOpenMembership(ITeamMembership):
"""
Interface provided by OpenMembership objects.
"""
class IMembershi... |
def getInvitesByProject(proj_id):
"""
Returns a BTree, keys are email addresses, values are
timestamps of when the invitation was extended.
"""
def addInvitation(address, proj_id):
"""
Registers an invitation to the specified email address for the
speci... | """
Returns a BTree, keys are project ids, values are timestamps
of when the invitation was extended.
""" | identifier_body |
extended_execute_process.ts | import * as dotenv from "dotenv"
import * as winston from "winston"
import { registerDebugAction } from "../actions/debug/debug"
import "../actions/index.ts"
import * as Hub from "../hub/index"
dotenv.config()
registerDebugAction()
async function execute(jsonPayload: any) {
const req = JSON.parse(jsonPayload)
co... |
return action.execute(request)
}
process.on("message", (req) => {
execute(req)
.then((val) => { process.send!(val) })
.catch((err) => {
const stringErr = JSON.stringify(err)
winston.error("Error on child: " + stringErr)
process.send!({success: false, message: stringErr})
})
})
| {
throw "action is not extended"
} | conditional_block |
extended_execute_process.ts | import * as dotenv from "dotenv"
import * as winston from "winston"
import { registerDebugAction } from "../actions/debug/debug"
import "../actions/index.ts"
import * as Hub from "../hub/index"
dotenv.config()
registerDebugAction()
async function execute(jsonPayload: any) |
process.on("message", (req) => {
execute(req)
.then((val) => { process.send!(val) })
.catch((err) => {
const stringErr = JSON.stringify(err)
winston.error("Error on child: " + stringErr)
process.send!({success: false, message: stringErr})
})
})
| {
const req = JSON.parse(jsonPayload)
const request = Hub.ActionRequest.fromIPC(req)
const action = await Hub.findExtendedAction(req.actionId, {lookerVersion: req.lookerVersion})
if (action === null) {
throw "action is not extended"
}
return action.execute(request)
} | identifier_body |
extended_execute_process.ts | import * as dotenv from "dotenv"
import * as winston from "winston"
import { registerDebugAction } from "../actions/debug/debug"
import "../actions/index.ts"
import * as Hub from "../hub/index"
dotenv.config()
registerDebugAction()
async function | (jsonPayload: any) {
const req = JSON.parse(jsonPayload)
const request = Hub.ActionRequest.fromIPC(req)
const action = await Hub.findExtendedAction(req.actionId, {lookerVersion: req.lookerVersion})
if (action === null) {
throw "action is not extended"
}
return action.execute(request)
}
process.on("mess... | execute | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.