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 |
|---|---|---|---|---|
api.py | import json
import bottle
from pyrouted.util import make_spec
def route(method, path):
def decorator(f):
f.http_route = path
f.http_method = method
return f
return decorator
class APIv1(object):
prefix = '/v1'
def __init__(self, ndb, config):
self.ndb = ndb
... |
return bottle.template('{{!ret}}', ret=json.dumps(ret))
| ret.append(line) | conditional_block |
bilibili.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
int_or_none,
unescapeHTML,
ExtractorError,
xpath_text,
)
class BiliBiliIE(InfoExtractor):
_VALID_URL = r'http://www\.bilibili\.(?:tv|com)/vide... | entries = []
for durl in doc.findall('./durl'):
size = xpath_text(durl, ['./filesize', './size'])
formats = [{
'url': durl.find('./url').text,
'filesize': int_or_none(size),
'ext': 'flv',
}]
backup_urls = du... | j.group('page_num') or '1'
view_data = self._download_json(
'http://api.bilibili.com/view?type=json&appkey=8e9fc618fbd41e28&id=%s&page=%s' % (video_id, page_num),
video_id)
if 'error' in view_data:
raise ExtractorError('%s said: %s' % (self.IE_NAME, view_data['error'... | identifier_body |
bilibili.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
int_or_none,
unescapeHTML,
ExtractorError,
xpath_text,
)
class | (InfoExtractor):
_VALID_URL = r'http://www\.bilibili\.(?:tv|com)/video/av(?P<id>\d+)(?:/index_(?P<page_num>\d+).html)?'
_TESTS = [{
'url': 'http://www.bilibili.tv/video/av1074402/',
'md5': '2c301e4dab317596e837c3e7633e7d86',
'info_dict': {
'id': '1554319',
'ext':... | BiliBiliIE | identifier_name |
bilibili.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
int_or_none,
unescapeHTML,
ExtractorError,
xpath_text,
)
class BiliBiliIE(InfoExtractor):
_VALID_URL = r'http://www\.bilibili\.(?:tv|com)/vide... | (durl, ['./filesize', './size'])
formats = [{
'url': durl.find('./url').text,
'filesize': int_or_none(size),
'ext': 'flv',
}]
backup_urls = durl.find('./backup_url')
if backup_urls is not None:
for backup_url... | )
entries = []
for durl in doc.findall('./durl'):
size = xpath_text | conditional_block |
bilibili.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
int_or_none,
unescapeHTML,
ExtractorError,
xpath_text,
)
class BiliBiliIE(InfoExtractor):
_VALID_URL = r'http://www\.bilibili\.(?:tv|com)/vide... |
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
page_num = mobj.group('page_num') or '1'
view_data = self._download_json(
'http://api.bilibili.com/view?type=json&appkey=8e9fc618fbd41e28&id=%s&page=%s' % (video_id, page_num... | }] | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(append)]
#![feature(arc_unique)]
#![feature(ascii)]
#![feature(as_slice)]
#![feature(as_unsafe_cell)]
#... | #![feature(plugin)]
#![feature(ref_slice)]
#![feature(rc_unique)]
#![feature(slice_patterns)]
#![feature(str_split_at)]
#![feature(str_utf16)]
#![feature(unicode)]
#![feature(vec_push_all)]
#![feature(slice_concat_ext)]
#![deny(unsafe_code)]
#![allow(non_snake_case)]
#![doc = "The script crate contains all matters DO... | #![feature(hashmap_hasher)]
#![feature(iter_arith)]
#![feature(mpsc_select)]
#![feature(nonzero)] | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(append)]
#![feature(arc_unique)]
#![feature(ascii)]
#![feature(as_slice)]
#![feature(as_unsafe_cell)]
#... | () {}
#[allow(unsafe_code)]
pub fn init() {
unsafe {
assert_eq!(js::jsapi::JS_Init(), 1);
}
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
perform_platform_specific_initialization();
}
| perform_platform_specific_initialization | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(append)]
#![feature(arc_unique)]
#![feature(ascii)]
#![feature(as_slice)]
#![feature(as_unsafe_cell)]
#... |
#[allow(unsafe_code)]
pub fn init() {
unsafe {
assert_eq!(js::jsapi::JS_Init(), 1);
}
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
perform_platform_specific_initialization();
}
| {} | identifier_body |
TwinkleAnimation.js | /**
* @file TwinkleAnimation.js
*
*
* @author Jonathan Lee Marcus
*
*
* @license Licensed under the MIT license.
**/
(function () {
"use strict";
var StarAnimation = require("./StarAnimation.js");
/**
* @class TwinkleAnimation
*
* @classdesc Twlinky animation t... | }
});
module.exports = this.TwinkleAnimation;
}).call(this); | random_line_split | |
TwinkleAnimation.js | /**
* @file TwinkleAnimation.js
*
*
* @author Jonathan Lee Marcus
*
*
* @license Licensed under the MIT license.
**/
(function () {
"use strict";
var StarAnimation = require("./StarAnimation.js");
/**
* @class TwinkleAnimation
*
* @classdesc Twlinky animation t... |
};
this.TwinkleAnimation.prototype = Object.create(StarAnimation.prototype, {
tick: {
enumerable: true,
writable: false,
value: function (timeNow) {
StarAnimation.prototype.tick.apply(this, arguments);
//zero the pixels before each draw!
for (var i=0; i<80; i++)
... | {
//for each twinkle, set a random location and initialize the birthtime to a random time within the last 1000 millisieconds
this.twink[i] = {"pixLoc":Math.floor(Math.random()*80),
"birthTime":(new Date().getTime() - (Math.random()*2000)),
"aliveTime":2000.0};
// for future pot... | conditional_block |
util.rs | use math::{Vec2, Vec2f};
use types::{WadCoord, WadInfo, WadName, ChildId, WadNameCast};
#[derive(Copy, Clone)]
pub enum WadType { Initial, Patch }
const IWAD_HEADER: &'static [u8] = b"IWAD";
const PWAD_HEADER: &'static [u8] = b"PWAD";
pub fn wad_type_from_info(wad_info: &WadInfo) -> Option<WadType> {
let id = &w... | Some(WadType::Initial)
} else if id == PWAD_HEADER {
Some(WadType::Patch)
} else {
None
}
}
pub fn is_untextured(name: &WadName) -> bool {
let bytes = name.as_bytes();
bytes[0] == b'-' && bytes[1] == 0
}
pub fn is_sky_flat(name: &WadName) -> bool {
name == &(&b"F_SKY1"[... | random_line_split | |
util.rs | use math::{Vec2, Vec2f};
use types::{WadCoord, WadInfo, WadName, ChildId, WadNameCast};
#[derive(Copy, Clone)]
pub enum WadType { Initial, Patch }
const IWAD_HEADER: &'static [u8] = b"IWAD";
const PWAD_HEADER: &'static [u8] = b"PWAD";
pub fn wad_type_from_info(wad_info: &WadInfo) -> Option<WadType> {
let id = &w... | {
((id & 0x7fff) as usize, id & 0x8000 != 0)
} | identifier_body | |
util.rs | use math::{Vec2, Vec2f};
use types::{WadCoord, WadInfo, WadName, ChildId, WadNameCast};
#[derive(Copy, Clone)]
pub enum WadType { Initial, Patch }
const IWAD_HEADER: &'static [u8] = b"IWAD";
const PWAD_HEADER: &'static [u8] = b"PWAD";
pub fn wad_type_from_info(wad_info: &WadInfo) -> Option<WadType> {
let id = &w... | else if id == PWAD_HEADER {
Some(WadType::Patch)
} else {
None
}
}
pub fn is_untextured(name: &WadName) -> bool {
let bytes = name.as_bytes();
bytes[0] == b'-' && bytes[1] == 0
}
pub fn is_sky_flat(name: &WadName) -> bool {
name == &(&b"F_SKY1"[..]).to_wad_name()
}
pub fn from_wa... | {
Some(WadType::Initial)
} | conditional_block |
util.rs | use math::{Vec2, Vec2f};
use types::{WadCoord, WadInfo, WadName, ChildId, WadNameCast};
#[derive(Copy, Clone)]
pub enum WadType { Initial, Patch }
const IWAD_HEADER: &'static [u8] = b"IWAD";
const PWAD_HEADER: &'static [u8] = b"PWAD";
pub fn | (wad_info: &WadInfo) -> Option<WadType> {
let id = &wad_info.identifier;
if id == IWAD_HEADER {
Some(WadType::Initial)
} else if id == PWAD_HEADER {
Some(WadType::Patch)
} else {
None
}
}
pub fn is_untextured(name: &WadName) -> bool {
let bytes = name.as_bytes();
byt... | wad_type_from_info | identifier_name |
index.js | 'use strict';
exports = module.exports = {};
exports.cookie = require('./cookie');
exports.createRandomString = require('./random-string');
exports.env = require('./env');
exports.errorHandler = require('./error-handler');
exports.errorMessages = require('./error-messages');
exports.logger = require('./logger');
expo... | exports.member = require('./member');
exports.notification = require('./notification');
exports.resolveMembers = require('./resolve-members'); | exports.permission = require('./permission');
exports.attachment = require('./attachment');
exports.category = require('./category');
exports.discussion = require('./discussion'); | random_line_split |
network.rs | use std::collections::HashMap;
use std::sync::mpsc::{Receiver, SyncSender};
use std::net::UdpSocket;
use processor::{InputProcessor, ConfigurableFilter};
/// # Network input
///
/// - listens on an UDP port for data, forward upstream
///
/// ### catapult.conf
///
/// ```
/// input {
/// network {
/// listenPort ... | (&self) -> Vec<&str> {
vec!["listenPort"]
}
}
impl InputProcessor for Network {
fn start(&self, config: &Option<HashMap<String,String>>) -> Receiver<String> {
self.requires_fields(config, self.mandatory_fields());
self.invoke(config, Network::handle_func)
}
fn handle_func(tx: SyncSender<String>, o... | mandatory_fields | identifier_name |
network.rs | use std::collections::HashMap;
use std::sync::mpsc::{Receiver, SyncSender};
use std::net::UdpSocket;
use processor::{InputProcessor, ConfigurableFilter};
/// # Network input
///
/// - listens on an UDP port for data, forward upstream
///
/// ### catapult.conf
///
/// ```
/// input {
/// network {
/// listenPort ... |
}
}
}
}
| {
println!("Unable to send line to processor: {}", e);
println!("{}", ll)
} | conditional_block |
network.rs | use std::collections::HashMap;
use std::sync::mpsc::{Receiver, SyncSender};
use std::net::UdpSocket;
use processor::{InputProcessor, ConfigurableFilter};
/// # Network input
/// | ///
/// ```
/// input {
/// network {
/// listenPort = 6667
/// }
/// }
/// ```
/// ### Parameters
///
/// - **listenPort**: UDP port to listen to
pub struct Network {
name: String
}
impl Network {
pub fn new(name: String) -> Network {
Network{ name: name }
}
}
impl ConfigurableFilter for Network ... | /// - listens on an UDP port for data, forward upstream
///
/// ### catapult.conf | random_line_split |
test_http_server.py | #!/usr/bin/env python
from __future__ import absolute_import
import urllib2
from pytomo import lib_youtube_download
from pytomo import start_pytomo
start_pytomo.configure_log_file('http_test')
ip_address_uri = ("http://173.194.5.107/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Calgorithm%2Cburst%2Cfactor... | resp.code = 200
resp.msg = "OK"
return resp
class MyHTTPHandler(urllib2.HTTPHandler):
def http_open(self, req):
print "mock opener"
return mock_response(req)
my_opener = urllib2.build_opener(MyHTTPHandler)
urllib2.install_opener(my_opener)
filedownloader = lib_youtube_dow... | if req.get_full_url() == ip_address_uri:
mock_file = open('test_pytomo/OdF-oiaICZI.flv')
resp = urllib2.addinfourl(mock_file,info ,
req.get_full_url()) | random_line_split |
test_http_server.py | #!/usr/bin/env python
from __future__ import absolute_import
import urllib2
from pytomo import lib_youtube_download
from pytomo import start_pytomo
start_pytomo.configure_log_file('http_test')
ip_address_uri = ("http://173.194.5.107/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Calgorithm%2Cburst%2Cfactor... | (urllib2.HTTPHandler):
def http_open(self, req):
print "mock opener"
return mock_response(req)
my_opener = urllib2.build_opener(MyHTTPHandler)
urllib2.install_opener(my_opener)
filedownloader = lib_youtube_download.FileDownloader(30)
h = filedownloader._do_download(ip_address_uri)
print h
#
#resp... | MyHTTPHandler | identifier_name |
test_http_server.py | #!/usr/bin/env python
from __future__ import absolute_import
import urllib2
from pytomo import lib_youtube_download
from pytomo import start_pytomo
start_pytomo.configure_log_file('http_test')
ip_address_uri = ("http://173.194.5.107/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Calgorithm%2Cburst%2Cfactor... |
class MyHTTPHandler(urllib2.HTTPHandler):
def http_open(self, req):
print "mock opener"
return mock_response(req)
my_opener = urllib2.build_opener(MyHTTPHandler)
urllib2.install_opener(my_opener)
filedownloader = lib_youtube_download.FileDownloader(30)
h = filedownloader._do_download(ip_address... | mock_file = open('test_pytomo/OdF-oiaICZI.flv')
resp = urllib2.addinfourl(mock_file,info ,
req.get_full_url())
resp.code = 200
resp.msg = "OK"
return resp | conditional_block |
test_http_server.py | #!/usr/bin/env python
from __future__ import absolute_import
import urllib2
from pytomo import lib_youtube_download
from pytomo import start_pytomo
start_pytomo.configure_log_file('http_test')
ip_address_uri = ("http://173.194.5.107/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Calgorithm%2Cburst%2Cfactor... |
class MyHTTPHandler(urllib2.HTTPHandler):
def http_open(self, req):
print "mock opener"
return mock_response(req)
my_opener = urllib2.build_opener(MyHTTPHandler)
urllib2.install_opener(my_opener)
filedownloader = lib_youtube_download.FileDownloader(30)
h = filedownloader._do_download(ip_address... | if req.get_full_url() == ip_address_uri:
mock_file = open('test_pytomo/OdF-oiaICZI.flv')
resp = urllib2.addinfourl(mock_file,info ,
req.get_full_url())
resp.code = 200
resp.msg = "OK"
return resp | identifier_body |
lan_access.py | # -*- coding:utf-8 -*-
from bottle import route, run
@route("/")
def | ():
return "OK!"
# hostデフォルト値は、127.0.0.1
# OK - localhost / 127.0.0.1
# NG - 192.168.0.10 / hostname
# run(port=8080, debug=True, reloader=True)
# run(host="localhost", port=8080, debug=True, reloader=True)
# OK - 192.168.0.10 / hostname
# NG - localhost / 127.0.0.1
run(host="192.168.0.10", port=808... | access | identifier_name |
lan_access.py | # -*- coding:utf-8 -*-
from bottle import route, run
@route("/")
def access():
|
# hostデフォルト値は、127.0.0.1
# OK - localhost / 127.0.0.1
# NG - 192.168.0.10 / hostname
# run(port=8080, debug=True, reloader=True)
# run(host="localhost", port=8080, debug=True, reloader=True)
# OK - 192.168.0.10 / hostname
# NG - localhost / 127.0.0.1
run(host="192.168.0.10", port=8080, debug=True, reload... | return "OK!" | identifier_body |
lan_access.py | # -*- coding:utf-8 -*-
from bottle import route, run
@route("/")
def access():
return "OK!"
|
# hostデフォルト値は、127.0.0.1
# OK - localhost / 127.0.0.1
# NG - 192.168.0.10 / hostname
# run(port=8080, debug=True, reloader=True)
# run(host="localhost", port=8080, debug=True, reloader=True)
# OK - 192.168.0.10 / hostname
# NG - localhost / 127.0.0.1
run(host="192.168.0.10", port=8080, debug=True, reloader... | random_line_split | |
ssf_reader.py | #!/usr/bin/python -*- coding:utf-8 -*-
__Author__ = "Riyaz Ahmad Bhat"
__Email__ = "riyaz.ah.bhat@gmail.com"
import re
from collections import namedtuple
from sanity_checker import SanityChecker
class DefaultList(list):
"""Equivalent of Default dictionaries for Indexing Errors."""
def __init__(self, defaul... |
def getAnnotations (self):
children_ = list()
for line in self.sentence.split("\n"):
nodeInfo = line.decode("utf-8").split("\t")
if nodeInfo[0].isdigit():
assert len(nodeInfo) == 4 # no need to process trash! FIXME
attributeValue_pairs = self.FSPairs(nodeInfo[3][4:-1])
attributes = se... | super(SSFReader, self).__init__()
self.id_ = int()
self.nodeList = list()
self.chunk_word = dict()
self.sentence = sentence
self.modifierModified = dict()
self.node = namedtuple('node',
('id', 'head', 'children', 'pos', 'poslcat', 'af', 'vpos', 'name','drel','parent',
'chunkId', 'chunkType', 'm... | identifier_body |
ssf_reader.py | #!/usr/bin/python -*- coding:utf-8 -*-
__Author__ = "Riyaz Ahmad Bhat"
__Email__ = "riyaz.ah.bhat@gmail.com"
import re
from collections import namedtuple
from sanity_checker import SanityChecker
class DefaultList(list):
"""Equivalent of Default dictionaries for Indexing Errors."""
def __init__(self, defaul... | h('coref_'),h('stype_'),h('voicetype_'),h('posn_')))
self.modifierModified[h('chunkId_')] = h('parent_')
self.chunk_word[h('chunkId_')] = h('head_')
else:
attributes = self.updateFSValues(attributeValue_pairs)
c = attributes.get #NOTE c -> child node attributes
children_.append(self.... | nodeInfo = line.decode("utf-8").split("\t")
if nodeInfo[0].isdigit():
assert len(nodeInfo) == 4 # no need to process trash! FIXME
attributeValue_pairs = self.FSPairs(nodeInfo[3][4:-1])
attributes = self.updateFSValues(attributeValue_pairs)
h = attributes.get #NOTE h -> head node attributes
elif ... | conditional_block |
ssf_reader.py | #!/usr/bin/python -*- coding:utf-8 -*-
__Author__ = "Riyaz Ahmad Bhat"
__Email__ = "riyaz.ah.bhat@gmail.com"
import re
from collections import namedtuple
from sanity_checker import SanityChecker
class DefaultList(list):
"""Equivalent of Default dictionaries for Indexing Errors."""
def __init__(self, defaul... | (SanityChecker):
def __init__ (self, sentence):
super(SSFReader, self).__init__()
self.id_ = int()
self.nodeList = list()
self.chunk_word = dict()
self.sentence = sentence
self.modifierModified = dict()
self.node = namedtuple('node',
('id', 'head', 'children', 'pos', 'poslcat', 'af', 'vpos', '... | SSFReader | identifier_name |
ssf_reader.py | #!/usr/bin/python -*- coding:utf-8 -*-
__Author__ = "Riyaz Ahmad Bhat"
__Email__ = "riyaz.ah.bhat@gmail.com"
import re
from collections import namedtuple
from sanity_checker import SanityChecker
class DefaultList(list):
"""Equivalent of Default dictionaries for Indexing Errors."""
def __init__(self, defaul... | def __getitem__(self, index):
try: return list.__getitem__(self, index)
except IndexError: return self.default
class SSFReader (SanityChecker):
def __init__ (self, sentence):
super(SSFReader, self).__init__()
self.id_ = int()
self.nodeList = list()
self.chunk_word = dict()
self.senten... | list.__init__(self)
| random_line_split |
plotting.py | import numpy as np
import matplotlib.pyplot as plt
from stimulus import *
from myintegrator import *
from functions import *
import matplotlib.gridspec as gridspec
import cPickle as pickle
#-------------------------------------------------------------------
#-------------------------------------------------------------... |
u_ret,uI_ret,connectivity_ret,WEI_ret,t_ret = pickle.load(open('dyn_retrieval_SA.p','rb'))
u_ret_PA,uI_ret_PA,connectivity_ret_PA,WEI_ret_PA,t_ret_PA = pickle.load(open('dyn_retrieval_PA.p','rb'))
#-------------------------------------------------------------------
#-----------------Stimulation of Populations---------... |
#integration | random_line_split |
plotting.py | import numpy as np
import matplotlib.pyplot as plt
from stimulus import *
from myintegrator import *
from functions import *
import matplotlib.gridspec as gridspec
import cPickle as pickle
#-------------------------------------------------------------------
#-------------------------------------------------------------... |
ax1A.set_xticks([])
ax1A.axvline(x=tmax,ymin=0,ymax=2.,linewidth=2,ls='--',color='gray',alpha=0.7)
#ax1A.set_xticklabels([0,50,100,150])
ax1A.set_ylim([0,1.8])
ax1A.set_xlim([0,250000])
ax1A.set_yticks([0,0.5,1.,1.5])
#ax1A.set_xlabel('Time (s)')
ax1A.set_ylabel('Synaptic Weights')
ax1A.set_title('(A)',y=1.04)
#---... | ax1A.plot(t,connectivity[:,i,i+2],'b',lw=3) | conditional_block |
simctrl.rs | // use mio;
// use mio::{ Handler };
// use std::cell::RefCell;
// use std::rc::Rc;
// pub trait Update : Handler {
// fn update(&mut self);
// fn run(&mut self, timeout : Self::Timeout, delay : u64) {
// let mut ev_cfg = mio::EventLoopConfig::new();
// ev_cfg.timer_tick_ms(10);
// let m... | pub const ZONG_SHU_JI_ZU_QI_LUN : usize = 4;
pub const ZONG_SHU_AN_DIAN : usize = 4;
pub const ZONG_SHU_NODE : usize = 23;
pub const ZONG_SHU_ZHI_LU : usize = 25;
pub const ZONG_SHU_FU_ZAI : usize = 21;
pub const ZONG_SHU_DUAN_LU_QI : usize = 38;
// pub const ZONG_SHU_SHOU_TI_DUI_JI_ZU : usize = 0;
// pub const ZONG_SH... | pub const ZONG_SHU_JI_ZU : usize = 13;
pub const ZONG_SHU_JI_ZU_CHAI_YOU : usize = 5; | random_line_split |
simctrl.rs | // use mio;
// use mio::{ Handler };
// use std::cell::RefCell;
// use std::rc::Rc;
// pub trait Update : Handler {
// fn update(&mut self);
// fn run(&mut self, timeout : Self::Timeout, delay : u64) {
// let mut ev_cfg = mio::EventLoopConfig::new();
// ev_cfg.timer_tick_ms(10);
// let m... | ,
Wu,
}
#[derive(PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum ZhanWeiType{
JiPang,
ZhuKongZhiPing,
JiZuKongZhiQi,
DianZhanKongZhiQi,
DianZhanJianKongTai,
JiKongTai,
BeiYongJiKongTai,
JiaoLian,
Admin,
Internal,
Wu,
}
#[derive(PartialEq, Copy, Clone, D... | ZhiLu | identifier_name |
seg_queue.rs | use std::sync::atomic::Ordering::{Acquire, Release, Relaxed};
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::fmt;
use std::{ptr, mem};
use std::cmp;
use std::cell::UnsafeCell;
use mem::epoch::{self, Atomic, Owned};
const SEG_SIZE: usize = 32;
/// A Michael-Scott queue that allocates "segments" (arrays of... |
}
if head.next.load(Relaxed, &guard).is_none() { return None }
}
}
}
#[cfg(test)]
mod test {
const CONC_COUNT: i64 = 1000000;
use scope;
use super::*;
#[test]
fn push_pop_1() {
let q: SegQueue<i64> = SegQueue::new();
q.push(37);
assert_... | {
unsafe {
let cell = (*head).data.get_unchecked(low).get();
loop {
if (*cell).1.load(Acquire) { break }
}
if low + 1 == SEG_SIZE {
loop {
... | conditional_block |
seg_queue.rs | use std::sync::atomic::Ordering::{Acquire, Release, Relaxed};
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::fmt;
use std::{ptr, mem};
use std::cmp;
use std::cell::UnsafeCell;
use mem::epoch::{self, Atomic, Owned};
const SEG_SIZE: usize = 32;
/// A Michael-Scott queue that allocates "segments" (arrays of... | let guard = epoch::pin();
loop {
let head = self.head.load(Acquire, &guard).unwrap();
loop {
let low = head.low.load(Relaxed);
if low >= cmp::min(head.high.load(Relaxed), SEG_SIZE) { break }
if head.low.compare_and_swap(low, low+1, ... | pub fn try_pop(&self) -> Option<T> { | random_line_split |
seg_queue.rs | use std::sync::atomic::Ordering::{Acquire, Release, Relaxed};
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::fmt;
use std::{ptr, mem};
use std::cmp;
use std::cell::UnsafeCell;
use mem::epoch::{self, Atomic, Owned};
const SEG_SIZE: usize = 32;
/// A Michael-Scott queue that allocates "segments" (arrays of... | () {
let q: SegQueue<i64> = SegQueue::new();
scope(|scope| {
scope.spawn(|| {
let mut next = 0;
while next < CONC_COUNT {
if let Some(elem) = q.try_pop() {
assert_eq!(elem, next);
next += 1;... | push_pop_many_spsc | identifier_name |
stack.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <whitequark@whitequark.org>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at y... |
#[test]
fn owned_stack() {
let stack = OwnedStack::new(1024);
assert_eq!(stack.base() as usize & (STACK_ALIGNMENT - 1), 0);
assert_eq!(stack.limit() as usize & (STACK_ALIGNMENT - 1), 0);
assert_eq!(stack.base() as usize - stack.limit() as usize, 1024);
}
#[test]
fn default_os_stack() {
let stack = OsStack::... | random_line_split | |
stack.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <whitequark@whitequark.org>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at y... |
#[test]
fn default_os_stack() {
let stack = OsStack::new(0).unwrap();
assert_eq!(stack.base() as usize & (STACK_ALIGNMENT - 1), 0);
assert_eq!(stack.limit() as usize & (STACK_ALIGNMENT - 1), 0);
// Make sure the topmost page of the stack, at least, is accessible.
unsafe { *(stack.base().offset(-1)) = 0; }
... | {
let stack = OwnedStack::new(1024);
assert_eq!(stack.base() as usize & (STACK_ALIGNMENT - 1), 0);
assert_eq!(stack.limit() as usize & (STACK_ALIGNMENT - 1), 0);
assert_eq!(stack.base() as usize - stack.limit() as usize, 1024);
} | identifier_body |
stack.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <whitequark@whitequark.org>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at y... | () {
unsafe {
let ptr = heap::allocate(16384, STACK_ALIGNMENT);
let mut slice = Box::from_raw(slice::from_raw_parts_mut(ptr, 16384));
let stack = SliceStack::new(&mut slice[4096..8192]);
assert_eq!(stack.base() as usize & (STACK_ALIGNMENT - 1), 0);
assert_eq!(stack.limit() as usize & (STACK_ALIGNM... | slice_aligned | identifier_name |
api.py | from allocine import allocine
from constants import *
from elcinema import elcinema
from imdb import imdby as Imdb
from rotten import rotten
from tmdb import tmdb
def search(query, site):
if site == "imdb":
provider = Imdb()
elif site == "elcinema":
provider = elcinema()
elif site == "rott... |
elif site == "themoviedatabase":
provider = tmdb(tmdb_key)
elif site == "allocine":
provider = allocine()
results = provider.search(query)
return results
def info(movie_id, site):
if site == "imdb":
provider = Imdb()
elif site == "elcinema":
provider = elcinema... | provider = rotten(rotten_key) | conditional_block |
api.py | from allocine import allocine
from constants import *
from elcinema import elcinema
from imdb import imdby as Imdb
from rotten import rotten
from tmdb import tmdb
def | (query, site):
if site == "imdb":
provider = Imdb()
elif site == "elcinema":
provider = elcinema()
elif site == "rottentomatoes":
provider = rotten(rotten_key)
elif site == "themoviedatabase":
provider = tmdb(tmdb_key)
elif site == "allocine":
provider = alloc... | search | identifier_name |
api.py | from allocine import allocine
from constants import *
from elcinema import elcinema
from imdb import imdby as Imdb |
def search(query, site):
if site == "imdb":
provider = Imdb()
elif site == "elcinema":
provider = elcinema()
elif site == "rottentomatoes":
provider = rotten(rotten_key)
elif site == "themoviedatabase":
provider = tmdb(tmdb_key)
elif site == "allocine":
prov... | from rotten import rotten
from tmdb import tmdb | random_line_split |
api.py | from allocine import allocine
from constants import *
from elcinema import elcinema
from imdb import imdby as Imdb
from rotten import rotten
from tmdb import tmdb
def search(query, site):
|
def info(movie_id, site):
if site == "imdb":
provider = Imdb()
elif site == "elcinema":
provider = elcinema()
elif site == "rottentomatoes":
provider = rotten(rotten_key)
elif site == "themoviedatabase":
provider = tmdb(tmdb_key)
elif site == "allocine":
pr... | if site == "imdb":
provider = Imdb()
elif site == "elcinema":
provider = elcinema()
elif site == "rottentomatoes":
provider = rotten(rotten_key)
elif site == "themoviedatabase":
provider = tmdb(tmdb_key)
elif site == "allocine":
provider = allocine()
results =... | identifier_body |
index.ts | /**
* Copyright 2019, OpenCensus Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or ... | export { isSampled, makeRandomSamplingDecision } from './common/sampling-util';
export { WindowWithOcwGlobals } from './trace/model/types';
export * from './trace/model/attribute-keys';
export { VERSION } from './version';
// Re-export types this uses from @opencensus/web-types.
export {
Annotation,
Attributes,
... | export { Span } from './trace/model/span';
export { Tracer } from './trace/model/tracer';
export { Tracing } from './trace/model/tracing'; | random_line_split |
index.js | 'use strict';
const Config = require('../../../config');
const UnsupportedMethods = require('./unsupportedMethods');
const SupportedMethod = require('./supportedMethod');
module.exports = function (settings) {
const exportEndpoint = {};
const path = Config.get('/apiUrlPrefix') + '/' + settings.name;
cons... |
const supportedMethod = SupportedMethod(server, proposedRequest, settings, params, path);
routes.push(supportedMethod);
});
const unsupportedMethods = UnsupportedMethods(settings, params, path);
routes.push(unsupportedMethods);
};
ur... | const params = url.params || '';
url.requests.forEach((proposedRequest) => { | random_line_split |
tailhook-config.py | # -*- coding: utf-8 -*-
from libqtile.manager import Key, Click, Drag, Screen, Group
from libqtile.command import lazy
from libqtile import layout, bar, widget, hook
from libqtile import xcbq
xcbq.keysyms["XF86AudioRaiseVolume"] = 0x1008ff13
xcbq.keysyms["XF86AudioLowerVolume"] = 0x1008ff11
xcbq.keysyms["XF86AudioMute... | indow.get_wm_type() == 'dialog'
or window.window.get_wm_transient_for()):
window.floating = True
| identifier_body | |
tailhook-config.py | # -*- coding: utf-8 -*-
from libqtile.manager import Key, Click, Drag, Screen, Group
from libqtile.command import lazy
from libqtile import layout, bar, widget, hook
from libqtile import xcbq
xcbq.keysyms["XF86AudioRaiseVolume"] = 0x1008ff13
xcbq.keysyms["XF86AudioLowerVolume"] = 0x1008ff11
xcbq.keysyms["XF86AudioMute... | (win):
patterns = (
('Яндекс.Почта', 'E-mail'),
('Gmail', 'E-mail'),
('SquirrelMail', 'E-mail'),
('zeromq', 'Docs'),
('PyYAML', 'Docs'),
('documentation', 'Docs'),
('-ietf-', 'Docs'),
('GNOME Live!', 'Docs'),
('Guide', 'Docs'),
)
fo... | window_sorter | identifier_name |
tailhook-config.py | # -*- coding: utf-8 -*-
from libqtile.manager import Key, Click, Drag, Screen, Group
from libqtile.command import lazy
from libqtile import layout, bar, widget, hook
from libqtile import xcbq
xcbq.keysyms["XF86AudioRaiseVolume"] = 0x1008ff13
xcbq.keysyms["XF86AudioLowerVolume"] = 0x1008ff11
xcbq.keysyms["XF86AudioMute... | top = bar.Bar(
[
widget.GroupBox(borderwidth=2,
font='Consolas',fontsize=18,
padding=1, margin_x=1, margin_y=1),
widget.Sep(),
widget.WindowName(
... | Screen( | random_line_split |
tailhook-config.py | # -*- coding: utf-8 -*-
from libqtile.manager import Key, Click, Drag, Screen, Group
from libqtile.command import lazy
from libqtile import layout, bar, widget, hook
from libqtile import xcbq
xcbq.keysyms["XF86AudioRaiseVolume"] = 0x1008ff13
xcbq.keysyms["XF86AudioLowerVolume"] = 0x1008ff11
xcbq.keysyms["XF86AudioMute... | d4"
keys = [
Key([mod], "j",
lazy.layout.down()),
Key([mod], "k",
lazy.layout.up()),
Key([mod, "shift"], "j",
lazy.layout.move_down()),
Key([mod, "shift"], "k",
lazy.layout.move_up()),
Key([mod, "control"], "j",
lazy.layout.section_down()),
Key([mod, "cont... | od = "mo | conditional_block |
Gruntfile.js | module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
var pkg = grunt.file.readJSON('package.json');
var colors = {
'red': '#F44336',
'pink': '#E91E63',
'purple': '#9C27B0',
'deep-purple': '#673AB7',
'indigo': '#3F51B5',
'blue': '#2196F3',
... | // Default task(s).
grunt.registerTask('default', ['clean', 'file-creator', 'imagemin', 'less', 'replace', 'cssmin', 'postcss']);
grunt.registerTask('test', ['default', 'fileExists']);
}; | random_line_split | |
reassign_modal.js | Template.reassign_modal.helpers({
fields: function() {
var userOptions = null;
var showOrg = true;
var instance = WorkflowManager.getInstance();
var space = db.spaces.findOne(instance.space);
var flow = db.flows.findOne({
'_id': instance.flow
});
var curSpaceUser = db.space_users.findOne({
s... |
var reason = $("#reassign_modal_text").val();
var user_ids = val.split(",");
InstanceManager.reassignIns(user_ids, reason);
Modal.hide(template);
},
}) | {
toastr.error(TAPi18n.__("instance_reassign_error_users_required"));
return;
} | conditional_block |
reassign_modal.js | Template.reassign_modal.helpers({
fields: function() {
var userOptions = null;
var showOrg = true;
var instance = WorkflowManager.getInstance();
var space = db.spaces.findOne(instance.space);
var flow = db.flows.findOne({
'_id': instance.flow
});
var curSpaceUser = db.space_users.findOne({
s... |
current_step_name: function() {
var s = InstanceManager.getCurrentStep();
var name;
if (s) {
name = s.name;
}
return name || '';
}
})
Template.reassign_modal.events({
'show.bs.modal #reassign_modal': function(event) {
var reassign_users = $("input[name='reassign_users']")[0];
reassign_users.v... | }, | random_line_split |
alarm_control_panel.py | """Support for NX584 alarm control panels."""
import logging
from nx584 import client
import requests
import voluptuous as vol
import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel import PLATFORM_SCHEMA
from homeassistant.components.alarm_control_panel.const i... |
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def code_format(self):
"""Return one or more digits/characters."""
return alarm.FORMAT_NUMBER
@property
def state(self):
"""Return the state of the device."""
... | """Init the nx584 alarm panel."""
self._hass = hass
self._name = name
self._url = url
self._alarm = client.Client(self._url)
# Do an initial list operation so that we will try to actually
# talk to the API and trigger a requests exception for setup_platform()
# t... | identifier_body |
alarm_control_panel.py | """Support for NX584 alarm control panels."""
import logging
from nx584 import client
import requests
import voluptuous as vol
import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel import PLATFORM_SCHEMA
from homeassistant.components.alarm_control_panel.const i... | (alarm.AlarmControlPanel):
"""Representation of a NX584-based alarm panel."""
def __init__(self, hass, url, name):
"""Init the nx584 alarm panel."""
self._hass = hass
self._name = name
self._url = url
self._alarm = client.Client(self._url)
# Do an initial list o... | NX584Alarm | identifier_name |
alarm_control_panel.py | """Support for NX584 alarm control panels."""
import logging
from nx584 import client
import requests
import voluptuous as vol
import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel import PLATFORM_SCHEMA
from homeassistant.components.alarm_control_panel.const i... |
elif bypassed:
self._state = STATE_ALARM_ARMED_HOME
else:
self._state = STATE_ALARM_ARMED_AWAY
for flag in part["condition_flags"]:
if flag == "Siren on":
self._state = STATE_ALARM_TRIGGERED
def alarm_disarm(self, code=None):
"""... | self._state = STATE_ALARM_DISARMED | conditional_block |
alarm_control_panel.py | """Support for NX584 alarm control panels."""
import logging
from nx584 import client
import requests
import voluptuous as vol
import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel import PLATFORM_SCHEMA
from homeassistant.components.alarm_control_panel.const i... | # to catch
self._alarm.list_zones()
self._state = None
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def code_format(self):
"""Return one or more digits/characters."""
return alarm.FORMAT_NUMBER
@... | self._url = url
self._alarm = client.Client(self._url)
# Do an initial list operation so that we will try to actually
# talk to the API and trigger a requests exception for setup_platform() | random_line_split |
convert_to_tfrecords.py | =[input_token.segment_id]))
for input_token in input_tokens
])
features['indicates_foreign_key'] = tf.train.FeatureList(
feature=foreign_key_features)
features['utterance_schema_alignment'] = tf.train.FeatureList(feature=[
tf.train.Feature(
int64_list=tf.train.Int64List... | app.run(main) | conditional_block | |
convert_to_tfrecords.py | .train.FeatureList(feature=[
tf.train.Feature(
int64_list=tf.train.Int64List(value=[input_token.segment_id]))
for input_token in input_tokens
])
features['indicates_foreign_key'] = tf.train.FeatureList(
feature=foreign_key_features)
features['utterance_schema_alignment'... | main | identifier_name | |
convert_to_tfrecords.py | 'wordpiece', 'index', 'copy_mask', 'segment_id',
'indicates_foreign_key', 'aligned'
])):
pass
class OutputAction(
collections.namedtuple('OutputAction', ['wordpiece', 'action_id', 'type'])):
pass
def add_context(key):
"""Adds context features required by the model."""
features = dict()
fe... | string_serial = ','.join([str(table) for table in model_input.tables])
if string_serial in self.table_cache and not random_permutation:
tokens_suffix, table_index_map, column_index_map = self.table_cache[
string_serial]
else:
# The input tokens contain the string to copy, rather than t... | converted_wordpiece_tokens = list()
for wordpiece in model_input.utterance_wordpieces:
converted_wordpiece_tokens.append(
InputToken(('##' if '##' in wordpiece.wordpiece else '') +
model_input.original_utterance[
wordpiece.span_start_index:wordpiece.span... | identifier_body |
convert_to_tfrecords.py | 'wordpiece', 'index', 'copy_mask', 'segment_id',
'indicates_foreign_key', 'aligned'
])):
pass
class OutputAction(
collections.namedtuple('OutputAction', ['wordpiece', 'action_id', 'type'])):
pass
def add_context(key):
"""Adds context features required by the model."""
features = dict()
fe... | self._get_vocab_index_or_unk(wordpiece.wordpiece), 1, 0, 0,
int(wordpiece.matches_to_schema)))
tokens = [
InputToken(BEG_TOK, self.input_vocabulary.index(BEG_TOK), 0, 0, 0, 0)
] + converted_wordpiece_tokens + [
InputToken(SEP_TOK, self.input_vocabulary.... | model_input.original_utterance[
wordpiece.span_start_index:wordpiece.span_end_index], | random_line_split |
plugin_test.py | # Copyright 2016 The TensorFlow 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 applica... | (self):
"""Tests that GET requests are unsupported."""
request = FakeRequest('GET', {
'node_names': json.dumps(['layers/Matmul', 'logits/Add']),
})
self.assertEqual(
405,
self.debugger_plugin._serve_health_pills_helper(request).status_code)
def testRequestsWithoutProperPostKey... | testGetRequestsUnsupported | identifier_name |
plugin_test.py | # Copyright 2016 The TensorFlow 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 applica... | test.main() | conditional_block | |
plugin_test.py | # Copyright 2016 The TensorFlow 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 applica... |
def setUp(self):
self.debugger_plugin = debugger_plugin.DebuggerPlugin()
self.unused_run_paths = {}
self.unused_logdir = '/logdir'
def testHealthPillsRouteProvided(self):
"""Tests that the plugin offers the route for requesting health pills."""
apps = self.debugger_plugin.get_plugin_apps(self.... |
class DebuggerPluginTest(test.TestCase): | random_line_split |
plugin_test.py | # Copyright 2016 The TensorFlow 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 applica... |
def testHealthPillsRouteProvided(self):
"""Tests that the plugin offers the route for requesting health pills."""
apps = self.debugger_plugin.get_plugin_apps(self.unused_run_paths,
self.unused_logdir)
self.assertIn('/health_pills', apps)
self.assertIsI... | self.debugger_plugin = debugger_plugin.DebuggerPlugin()
self.unused_run_paths = {}
self.unused_logdir = '/logdir' | identifier_body |
perf.rs | use crate::vm::{Code, VM};
use dora_parser::interner::Name;
#[cfg(target_os = "linux")]
pub fn | (code: &Code, vm: &VM, name: Name) {
use std::fs::OpenOptions;
use std::io::prelude::*;
let pid = unsafe { libc::getpid() };
let fname = format!("/tmp/perf-{}.map", pid);
let mut options = OpenOptions::new();
let mut file = options.create(true).append(true).open(&fname).unwrap();
let code... | register_with_perf | identifier_name |
perf.rs | use crate::vm::{Code, VM};
use dora_parser::interner::Name;
#[cfg(target_os = "linux")]
pub fn register_with_perf(code: &Code, vm: &VM, name: Name) {
use std::fs::OpenOptions;
use std::io::prelude::*;
let pid = unsafe { libc::getpid() };
let fname = format!("/tmp/perf-{}.map", pid); | let code_end = code.instruction_end().to_usize();
let name = vm.interner.str(name);
let line = format!(
"{:x} {:x} dora::{}\n",
code_start,
code_end - code_start,
name
);
file.write_all(line.as_bytes()).unwrap();
}
#[cfg(not(target_os = "linux"))]
pub fn register_wi... |
let mut options = OpenOptions::new();
let mut file = options.create(true).append(true).open(&fname).unwrap();
let code_start = code.instruction_start().to_usize(); | random_line_split |
perf.rs | use crate::vm::{Code, VM};
use dora_parser::interner::Name;
#[cfg(target_os = "linux")]
pub fn register_with_perf(code: &Code, vm: &VM, name: Name) {
use std::fs::OpenOptions;
use std::io::prelude::*;
let pid = unsafe { libc::getpid() };
let fname = format!("/tmp/perf-{}.map", pid);
let mut optio... | {
// nothing to do
} | identifier_body | |
bin.js | #!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var nugget = require('./')
var args = require('minimist')(process.argv.slice(2))
var urls = args._
if (urls.length === 0) {
console.log(fs.readFileSync(path.join(__dirname, 'usage.txt')).toString())
process.exit(1)
}
var opts = {
... |
process.exit(0)
})
| {
console.error('Error:', err)
process.exit(1)
} | conditional_block |
bin.js | #!/usr/bin/env node
|
var fs = require('fs')
var path = require('path')
var nugget = require('./')
var args = require('minimist')(process.argv.slice(2))
var urls = args._
if (urls.length === 0) {
console.log(fs.readFileSync(path.join(__dirname, 'usage.txt')).toString())
process.exit(1)
}
var opts = {
target: args.o || ... | random_line_split | |
twitter_server.py | import tweepy
import os
from flask import Flask, make_response, jsonify
CONSUMER_KEY = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_TOKEN']
CONSUMER_SECRET = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_SECRET']
app = Flask(__name__)
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
api = tweepy.API(auth)
@app.ro... |
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8888, debug=True)
| try:
user = api.get_user(username)
except tweepy.TweepError:
return make_response(jsonify({'error': 'no username %s' % (username)}), 404)
else:
json_data = {'avatar': user.profile_image_url}
return make_response(jsonify(json_data), 200) | identifier_body |
twitter_server.py | import tweepy
import os
from flask import Flask, make_response, jsonify
CONSUMER_KEY = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_TOKEN']
CONSUMER_SECRET = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_SECRET']
app = Flask(__name__)
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
api = tweepy.API(auth)
@app.ro... | (username):
try:
user = api.get_user(username)
except tweepy.TweepError:
return make_response(jsonify({'error': 'no username %s' % (username)}), 404)
else:
json_data = {'avatar': user.profile_image_url}
return make_response(jsonify(json_data), 200)
if __name__ == "__main__"... | get_user_avatar | identifier_name |
twitter_server.py | import tweepy
import os
from flask import Flask, make_response, jsonify
CONSUMER_KEY = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_TOKEN']
CONSUMER_SECRET = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_SECRET']
app = Flask(__name__)
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
api = tweepy.API(auth)
@app.ro... | app.run(host='0.0.0.0', port=8888, debug=True) | conditional_block | |
twitter_server.py | import tweepy
import os
from flask import Flask, make_response, jsonify
CONSUMER_KEY = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_TOKEN']
CONSUMER_SECRET = os.environ['CATCHMEMEALL_TWITTER_CONSUMER_SECRET']
app = Flask(__name__)
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
api = tweepy.API(auth)
@app.ro... |
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8888, debug=True) | return make_response(jsonify(json_data), 200)
| random_line_split |
Point.ts | /**
* The MIT License (MIT)
*
* Copyright (c) 2012-2018 DragonBones team and other contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including ... | identifier_body | ||
Point.ts | /**
* The MIT License (MIT)
*
* Copyright (c) 2012-2018 DragonBones team and other contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including ... | * @param y - The vertical coordinate.
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 创建一个 egret.Point 对象.若不传入任何参数,将会创建一个位于(0,0)位置的点。
* @param x - 该对象的x属性值,默认为 0.0。
* @param y - 该对象的y属性值,默认为 0.0。
* @version DragonBones 3.0
... | random_line_split | |
Point.ts | /**
* The MIT License (MIT)
*
* Copyright (c) 2012-2018 DragonBones team and other contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including ... | this.x = this.y = 0.0;
}
}
} | void {
| identifier_name |
iterator_vs_async_iterator.ts | value: T;
done: boolean;
}
// 同步迭代器对象
interface IIterator<T> {
next(value?: any): IIterationResult<T>;
return?(value?: any): IIterationResult<T>;
throw?(e?: any): IIterationResult<T>;
}
// 同步可迭代对象
interface IIterable<T> {
[Symbol.iterator](): IIterator<T>;
}
// [同步生成器对象] 既是同步可迭代对象又是同步迭代器对象
//... | // 这里为了不和nodejs 内部已经定义好的接口冲突,这里接口前我都加一个I
// 同步迭代器对象接口
// 同步迭代结果
interface IIterationResult<T> { | random_line_split | |
vec.rs | #[no_std];
#[no_core];
use zero;
pub trait OwnedVector<T> {
unsafe fn push_fast(&mut self, t: T);
unsafe fn len(&self) -> uint;
unsafe fn set_len(&mut self, newlen: uint);
unsafe fn as_mut_buf<U>(&self, f: &fn(*mut T, uint) -> U) -> U;
unsafe fn data(&self) -> *u8;
}
pub struct Vec<T> {
fill:... | (&mut self, t: T) {
let repr: **mut Vec<u8> = zero::transmute(self);
let fill = (**repr).fill;
(**repr).fill += zero::size_of::<T>();
let p = &(**repr).data as *u8 as uint;
let mut i = 0;
while i < zero::size_of::<T>() {
*((p+fill+i) as *mut u8) = *((&t as *T... | push_fast | identifier_name |
vec.rs | #[no_std];
#[no_core];
use zero;
pub trait OwnedVector<T> {
unsafe fn push_fast(&mut self, t: T);
unsafe fn len(&self) -> uint;
unsafe fn set_len(&mut self, newlen: uint);
unsafe fn as_mut_buf<U>(&self, f: &fn(*mut T, uint) -> U) -> U;
unsafe fn data(&self) -> *u8;
}
pub struct Vec<T> {
fill:... | let fill = (**repr).fill;
(**repr).fill += zero::size_of::<T>();
let p = &(**repr).data as *u8 as uint;
let mut i = 0;
while i < zero::size_of::<T>() {
*((p+fill+i) as *mut u8) = *((&t as *T as uint + i) as *mut u8);
i += 1;
}
}
unsafe fn... | #[inline]
unsafe fn push_fast(&mut self, t: T) {
let repr: **mut Vec<u8> = zero::transmute(self); | random_line_split |
vec.rs | #[no_std];
#[no_core];
use zero;
pub trait OwnedVector<T> {
unsafe fn push_fast(&mut self, t: T);
unsafe fn len(&self) -> uint;
unsafe fn set_len(&mut self, newlen: uint);
unsafe fn as_mut_buf<U>(&self, f: &fn(*mut T, uint) -> U) -> U;
unsafe fn data(&self) -> *u8;
}
pub struct Vec<T> {
fill:... |
}
| {
let repr: **mut Vec<u8> = zero::transmute(self);
&(**repr).data as *u8
} | identifier_body |
dsp.rs | //! Emulates the DSP used in the APU.
#![allow(dead_code)] // FIXME Implement the DSP
#[derive(Copy, Clone, Default)]
struct Voice {
// Registers
/// $x0 - Left channel volume
lvol: i8,
/// $x1 - Right channel volume
rvol: i8,
/// $x2 (low)/x3 (high) (14 bit)
pitch: u16,
/// $x4 -... | {
/// Continue playing with the next BRR block
Continue,
/// Jump to the block's loop address and set the ENDx flag for this voice
Loop,
/// Jump to the loop address, set ENDx, enter `Release`, set env to $000
Release,
}
struct BrrBlock {
/// 0-12 where 0 = silent and 12 = loudest
shif... | BrrLoop | identifier_name |
dsp.rs | //! Emulates the DSP used in the APU.
#![allow(dead_code)] // FIXME Implement the DSP
#[derive(Copy, Clone, Default)]
struct Voice {
// Registers
/// $x0 - Left channel volume
lvol: i8,
/// $x1 - Right channel volume
rvol: i8,
/// $x2 (low)/x3 (high) (14 bit)
pitch: u16,
/// $x4 -... | match reg & 0x0f {
0x00 => voice.lvol as u8,
0x01 => voice.rvol as u8,
0x02 => voice.pitch as u8,
0x03 => (voice.pitch >> 8) as u8,
0x04 => voice.source,
0x05 => voice.adsr1,
... | {
reg &= 0x7f;
match reg {
0x0c => self.lmvol,
0x1c => self.rmvol,
0x2c => self.levol,
0x3c => self.revol,
0x4c => self.keyon,
0x5c => self.keyoff,
0x6c => self.flags,
0x7c => self.endx,
0x0d => s... | identifier_body |
dsp.rs | //! Emulates the DSP used in the APU.
#![allow(dead_code)] // FIXME Implement the DSP
#[derive(Copy, Clone, Default)]
struct Voice {
// Registers
/// $x0 - Left channel volume
lvol: i8,
/// $x1 - Right channel volume
rvol: i8,
/// $x2 (low)/x3 (high) (14 bit)
pitch: u16,
/// $x4 -... | 0x4c => self.keyon = value,
0x5c => self.keyoff = value,
0x6c => self.flags = value,
0x7c => self.endx = value,
0x0d => self.efb = value,
0x2d => self.pmod = value,
0x3d => self.noise = value,
0x4d => self.echo = value,
... | 0x1c => self.rmvol = value,
0x2c => self.levol = value,
0x3c => self.revol = value, | random_line_split |
template.rs | /*
Example demonstrating Sending a Secure Message.
*/
// ------------------------------------------
// crates.io
// ------------------------------------------
#[macro_use]
extern crate serde_json;
// ------------------------------------------
// hyperledger crates
// ------------------------------------------
exter... |
fn prep(wallet_handle: i32, sender_vk: &str, receipt_vk: &str) {
let mut file = File::create(FILE).unwrap();
println!("Enter message");
let mut message = String::new();
io::stdin().read_line(&mut message).unwrap();
let encrypted_msg = crypto::auth_crypt(wallet_handle, &sender_vk, &receipt_vk, me... | {
let mut cmd = String::new();
println!("Who are you? ");
io::stdin().read_line(&mut cmd).unwrap();
let config = json!({ "id" : format!("{}-wallet", cmd) }).to_string();
wallet::create_wallet(&config, USEFUL_CREDENTIALS).wait().unwrap();
let wallet_handle: i32 = wallet::open_wallet(&config, US... | identifier_body |
template.rs | /*
Example demonstrating Sending a Secure Message.
*/
// ------------------------------------------
// crates.io
// ------------------------------------------
#[macro_use]
extern crate serde_json;
// ------------------------------------------
// hyperledger crates
// ------------------------------------------
exter... | file.write_all(&encrypted_msg).unwrap();
}
fn read(wallet_handle: i32, receipt_vk: &str) {
let mut file = File::open(FILE).unwrap();
let mut contents = Vec::new();
file.read_to_end(&mut contents).unwrap();
let (sender, decrypted_msg) = crypto::auth_decrypt(wallet_handle, &receipt_vk, &contents).w... | random_line_split | |
template.rs | /*
Example demonstrating Sending a Secure Message.
*/
// ------------------------------------------
// crates.io
// ------------------------------------------
#[macro_use]
extern crate serde_json;
// ------------------------------------------
// hyperledger crates
// ------------------------------------------
exter... | () {
let (wallet_handle, verkey, other_verkey) = init();
loop {
println!("ToDo");
let mut cmd = String::new();
io::stdin().read_line(&mut cmd).unwrap();
cmd = cmd.trim().to_string();
if cmd == "prep" {
prep(wallet_handle, &verkey, &other_verkey);
} ... | main | identifier_name |
utils.rs | are defined.
pub const DOM_PROTO_UNFORGEABLE_HOLDER_SLOT: u32 = 0;
/// The index of the slot that contains a reference to the ProtoOrIfaceArray.
// All DOM globals must have a slot at DOM_PROTOTYPE_SLOT.
pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
/// The flag set on the `JSClass`es for DOM gl... | }
let property = CString::new(property).unwrap();
if object.get().is_null() {
return Ok(false);
}
let mut found = false;
if !has_property(cx, object, &property, &mut found) {
return Err(());
}
if !found {
return Ok(false);
}
if !get_property(cx, object... | object: HandleObject,
property: &CString,
value: MutableHandleValue)
-> bool {
unsafe { JS_GetProperty(cx, object, property.as_ptr(), value) } | random_line_split |
utils.rs | defined.
pub const DOM_PROTO_UNFORGEABLE_HOLDER_SLOT: u32 = 0;
/// The index of the slot that contains a reference to the ProtoOrIfaceArray.
// All DOM globals must have a slot at DOM_PROTOTYPE_SLOT.
pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
/// The flag set on the `JSClass`es for DOM global... | (cx: *mut JSContext,
object: HandleObject,
property: &str,
rval: MutableHandleValue)
-> Result<bool, ()> {
fn has_property(cx: *mut JSContext,
object: HandleObject,
... | get_dictionary_property | identifier_name |
utils.rs | JSClass,
/// Associated data for DOM object reflectors.
pub dom_class: DOMClass,
}
impl Clone for DOMJSClass {
fn clone(&self) -> DOMJSClass {
*self
}
}
unsafe impl Sync for DOMJSClass {}
/// Returns the ProtoOrIfaceArray for the given global object.
/// Fails if `global` is not a DOM global ob... | {
assert!(JS_IsGlobalObject(obj.get()));
if !JS_ResolveStandardClass(cx, obj, id, rval) {
return false;
}
if *rval {
return true;
}
if !RUST_JSID_IS_STRING(id) {
*rval = false;
return true;
}
let string = RUST_JSID_TO_STRING(id);
if !JS_StringHasLatin... | identifier_body | |
utils.rs | defined.
pub const DOM_PROTO_UNFORGEABLE_HOLDER_SLOT: u32 = 0;
/// The index of the slot that contains a reference to the ProtoOrIfaceArray.
// All DOM globals must have a slot at DOM_PROTOTYPE_SLOT.
pub const DOM_PROTOTYPE_SLOT: u32 = js::JSCLASS_GLOBAL_SLOT_COUNT;
/// The flag set on the `JSClass`es for DOM global... |
}
Ok(())
}
/// Returns whether `proxy` has a property `id` on its prototype.
pub unsafe fn has_property_on_prototype(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
found: &mut bool)... | {
return Err(());
} | conditional_block |
algorithm.py | import hashlib
def hash_list():
return str(hashlib.algorithms_guaranteed)
def | (algorithm_array, text, pass_count):
result_dict = {}
# Type checking
if type(pass_count) is not int:
return [False, {"error": "Pass count should be of 'integer' type."}]
elif type(text) is not str:
return [False, {"error": "Text should be of 'string' type."}]
elif type(algorithm_arr... | hash_text | identifier_name |
algorithm.py | import hashlib
def hash_list():
return str(hashlib.algorithms_guaranteed)
def hash_text(algorithm_array, text, pass_count):
| return [True, result_dict]
| result_dict = {}
# Type checking
if type(pass_count) is not int:
return [False, {"error": "Pass count should be of 'integer' type."}]
elif type(text) is not str:
return [False, {"error": "Text should be of 'string' type."}]
elif type(algorithm_array) is not list:
return [False, {... | identifier_body |
algorithm.py | import hashlib
def hash_list():
return str(hashlib.algorithms_guaranteed)
def hash_text(algorithm_array, text, pass_count):
result_dict = {}
# Type checking
if type(pass_count) is not int:
return [False, {"error": "Pass count should be of 'integer' type."}] | elif type(text) is not str:
return [False, {"error": "Text should be of 'string' type."}]
elif type(algorithm_array) is not list:
return [False, {"error": "Algorithm list should be of 'list' type."}]
# Bounds checking
avail_alg_set = set(algorithm_array) & set(hashlib.algorithms_guarante... | random_line_split | |
algorithm.py | import hashlib
def hash_list():
return str(hashlib.algorithms_guaranteed)
def hash_text(algorithm_array, text, pass_count):
result_dict = {}
# Type checking
if type(pass_count) is not int:
return [False, {"error": "Pass count should be of 'integer' type."}]
elif type(text) is not str:
... |
# Bounds checking
avail_alg_set = set(algorithm_array) & set(hashlib.algorithms_guaranteed)
if pass_count > 1000000 or pass_count <= 0:
return [False, {"error": "Pass count should be larger than 0 and smaller than 1000000."}]
elif len(avail_alg_set) == 0:
return [False, {"error": "None ... | return [False, {"error": "Algorithm list should be of 'list' type."}] | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import os
from django.core.exceptions import ImproperlyConfigured
... | raise ImproperlyConfigured("Error! No configure in local_settings.")
local_configure = local_settings_ns["configure"]
local_configure(setup)
return setup
globals().update(Setup.configure(configure))
| base_settings.configure(setup)
local_settings_file = os.getenv("LOCAL_SETTINGS_FILE")
# Backward compatibility: Find from current directory, if
# LOCAL_SETTINGS_FILE environment variables is unset
if local_settings_file is None:
cand = os.path.join(os.path.dirname(__file__), "local_settings.py... | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import os
from django.core.exceptions import ImproperlyConfigured
... | globals().update(Setup.configure(configure)) | random_line_split | |
__init__.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import os
from django.core.exceptions import ImproperlyConfigured
... | (setup):
base_settings.configure(setup)
local_settings_file = os.getenv("LOCAL_SETTINGS_FILE")
# Backward compatibility: Find from current directory, if
# LOCAL_SETTINGS_FILE environment variables is unset
if local_settings_file is None:
cand = os.path.join(os.path.dirname(__file__), "loca... | configure | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import os
from django.core.exceptions import ImproperlyConfigured
... |
# Load local settings from file
if local_settings_file:
local_settings_ns = {
"__file__": local_settings_file,
}
with open(local_settings_file, "rb") as fp:
compiled = compile(fp.read(), local_settings_file, "exec")
exec(compiled, local_settings_ns)
... | local_settings_file = cand | conditional_block |
session.js | /**
* Session Configuration
* (sails.config.session)
*
* Sails session integration leans heavily on the great work already done by
* Express, but also unifies Socket.io with the Connect session store. It uses
* Connect's cookie parser to normalize configuration differences between Express
* and Socket.io and hoo... | * the example below is for 24 hours *
* *
***************************************************************************/
// cookie: {
// maxAge: 24 * 60 * 60 * 1000
// }
/*********************... | * *
* Set the session cookie expire time The maxAge is set by milliseconds, * | random_line_split |
dataWriter.ts | import * as uuidLib from 'uuid';
const topLogPrefix = 'larvituser: dataWriter.ts -';
export type DataWriterOptions = {
log?: LogInstance,
db: any,
};
export class DataWriter {
private lUtils: Utils;
private helpers: Helpers;
private log: LogInstance;
private db: any;
constructor(options: DataWriterOptions) {... | (userUuid: string, fields: Record<string, string | string[]>)
: Promise<void> {
const { helpers, lUtils } = this;
const logPrefix = `${topLogPrefix} addUserDataFields() -`;
let sql = 'INSERT INTO user_users_data (userUuid, fieldUuid, data) VALUES';
if (!Object.keys(fields).length) {
this.log.verbose(`${l... | addUserDataFields | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.