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 |
|---|---|---|---|---|
class_study5.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
私有方法和私有字段
私有字段:self.__Thailand
私有字段是不能直接被对象和类进行访问的,需要通过动态方法访问
同样私有字段也是可以通过特性的方法访问的
私有方法:
私有方法是不能直接被对象和类进行访问的,通过使用动态方法进行访问
japan._Provice__sha() #显示调用私有方法,但是不建议这么使用
私有字段使用字段,可以让被人访问,但是不可以让别人改动
'''
class Provice:... | identifier_body | ||
class_study5.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
私有方法和私有字段
私有字段:self.__Thailand
私有字段是不能直接被对象和类进行访问的,需要通过动态方法访问
同样私有字段也是可以通过特性的方法访问的
私有方法:
私有方法是不能直接被对象和类进行访问的,通过使用动态方法进行访问
japan._Provice__sha() #显示调用私有方法,但是不建议这么使用
私有字段使用字段,可以让被人访问,但是不可以让别人改动
'''
class Provice:... | def show(self): #访问私有字段
print self.__Thailand
def __sha(self): #定义私有方法
print '我是Alex'
def Foo2(self): #通过动态方法访问私有方法
self.__sha()
@property #通过特性访问私有字段
def Thailand(self):
re... | self.__Thailand = flag #私有字段
| random_line_split |
class_study5.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
私有方法和私有字段
私有字段:self.__Thailand
私有字段是不能直接被对象和类进行访问的,需要通过动态方法访问
同样私有字段也是可以通过特性的方法访问的
私有方法:
私有方法是不能直接被对象和类进行访问的,通过使用动态方法进行访问
japan._Provice__sha() #显示调用私有方法,但是不建议这么使用
私有字段使用字段,可以让被人访问,但是不可以让别人改动
'''
class Provice:... | 济南','习近平')
japan = Provice('日本','东京','安倍',True)
#print japan.__Thailand #访问报错 AttributeError: Provice instance has no attribute '__Thailand'
#对象是不能直接访问私有字段的
japan.show() #私有字段需要使用动态方法进行访问输出
japan.Foo2() #私有方法通过使用动态方法进行访问输出
japan._Provice__sha() #显示调用私有方法,但是不建议这么使用
print japan.Th... | 东',' | identifier_name |
accesslog.js | /**
* @param {string} value
* @returns {RegExp}
* */
/**
* @param {RegExp | string } re
* @returns {string}
*/
function source(re) {
if (!re) return null;
if (typeof re === "string") return re;
return re.source;
}
/**
* @param {...(RegExp | string) } args
* @returns {string}
*/
function concat(...args... | (_hljs) {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
const HTTP_VERBS = [
"GET",
"POST",
"HEAD",
"PUT",
"DELETE",
"CONNECT",
"OPTIONS",
"PATCH",
"TRACE"
];
return {
name: 'Apache Access Log',
contains: [
// IP
{
className: 'number... | accesslog | identifier_name |
accesslog.js | /**
* @param {string} value
* @returns {RegExp}
* */
/**
* @param {RegExp | string } re
* @returns {string}
*/
function source(re) {
if (!re) return null;
if (typeof re === "string") return re;
return re.source;
}
/**
* @param {...(RegExp | string) } args
* @returns {string}
*/
function concat(...args... |
/*
Language: Apache Access Log
Author: Oleg Efimov <efimovov@gmail.com>
Description: Apache/Nginx Access Logs
Website: https://httpd.apache.org/docs/2.4/logs.html#accesslog
Audit: 2020
*/
/** @type LanguageFn */
function accesslog(_hljs) {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
const H... | */
function either(...args) {
const joined = '(' + args.map((x) => source(x)).join("|") + ")";
return joined;
} | random_line_split |
accesslog.js | /**
* @param {string} value
* @returns {RegExp}
* */
/**
* @param {RegExp | string } re
* @returns {string}
*/
function source(re) {
if (!re) return null;
if (typeof re === "string") return re;
return re.source;
}
/**
* @param {...(RegExp | string) } args
* @returns {string}
*/
function concat(...args... |
/**
* Any of the passed expresssions may match
*
* Creates a huge this | this | that | that match
* @param {(RegExp | string)[] } args
* @returns {string}
*/
function either(...args) {
const joined = '(' + args.map((x) => source(x)).join("|") + ")";
return joined;
}
/*
Language: Apache Access Log
Author:... | {
const joined = args.map((x) => source(x)).join("");
return joined;
} | identifier_body |
user.py | #!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: magic
"""
from django.contrib import admin
from blog.models import User
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext, ugettext_lazy as _
class BlogUserAdmin(UserAdmin):
filesets = (
(None, {'fields': ... | )
admin.site.register(User, BlogUserAdmin) | }), | random_line_split |
user.py | #!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: magic
"""
from django.contrib import admin
from blog.models import User
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext, ugettext_lazy as _
class BlogUserAdmin(UserAdmin):
|
admin.site.register(User, BlogUserAdmin) | filesets = (
(None, {'fields': ('username', 'email', 'password')}),
(_('Personal info'), {'fields': ('email', 'qq', 'phone')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important da... | identifier_body |
user.py | #!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: magic
"""
from django.contrib import admin
from blog.models import User
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext, ugettext_lazy as _
class | (UserAdmin):
filesets = (
(None, {'fields': ('username', 'email', 'password')}),
(_('Personal info'), {'fields': ('email', 'qq', 'phone')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
... | BlogUserAdmin | identifier_name |
index.ts | export { W3W_REGEX } from './constants';
export {
autosuggest,
AutosuggestOptions,
AutosuggestResponse,
} from './requests/autosuggest';
export { autosuggestSelection } from './requests/autosuggest-selection';
export {
availableLanguages,
AvailableLanguagesResponse,
} from './requests/available-languages';
ex... | gridSection,
gridSectionGeoJson,
GridSectionGeoJsonResponse,
GridSectionJsonResponse,
} from './requests/grid-section';
export {
Bounds,
Coordinates,
LocationJsonResponse,
LocationGeoJsonResponse,
LocationProperties,
ResponseFormat,
} from './types';
export {
setOptions,
getOptions,
ApiOptions... | convertToCoordinatesGeoJson,
} from './requests/convert-to-coordinates';
export { | random_line_split |
Settings.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved. | */
import Editor from 'tinymce/core/api/Editor';
const shouldIndentOnTab = (editor: Editor) => editor.getParam('lists_indent_on_tab', true);
const getForcedRootBlock = (editor: Editor): string => {
const block = editor.getParam('forced_root_block', 'p');
if (block === false) {
return '';
} else if (block ... | * Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/ | random_line_split |
Settings.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Editor from 'tinymce/core/api/Editor';
const shouldIndentOnTa... |
};
const getForcedRootBlockAttrs = (editor: Editor): Record<string, string> => editor.getParam('forced_root_block_attrs', {});
export {
shouldIndentOnTab,
getForcedRootBlock,
getForcedRootBlockAttrs
};
| {
return block;
} | conditional_block |
travis_test_script.py | import sys, subprocess, time
"""
This script is made as a wrapper for sc2 bots to set a timeout to the bots (in case they cant find the last enemy structure or the game is ending in a draw)
Usage:
cd into python-sc2/ directory
docker build -t test_image -f test/Dockerfile .
docker run test_image -c "python test/travi... |
print("Exiting with exit code 0")
exit(0)
# Exit code 1: game crashed I think
print("Exiting with exit code 1")
exit(1)
# Exit code 2: bot was not launched
print("Exiting with exit code 2")
exit(2) | print("Exiting with exit code 3")
exit(3) | conditional_block |
travis_test_script.py | import sys, subprocess, time
""" | docker build -t test_image -f test/Dockerfile .
docker run test_image -c "python test/travis_test_script.py test/autotest_bot.py"
"""
retries = 2
timeout_time = 3*60 # My maxout bot took 110 - 140 real seconds for 7 minutes in game time
if len(sys.argv) > 1:
# Attempt to run process with retries and timeouts
... | This script is made as a wrapper for sc2 bots to set a timeout to the bots (in case they cant find the last enemy structure or the game is ending in a draw)
Usage:
cd into python-sc2/ directory | random_line_split |
poly.rs | // Copyright (C) 2020 Inderjit Gill <email@indy.io>
// This file is part of Seni
// Seni 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 l... | (
render_list: &mut RenderList,
matrix: &Matrix,
coords: &[(f32, f32)],
colours: &[Rgb],
uvm: &UvMapping,
) -> Result<()> {
let num_vertices = coords.len();
if colours.len() != num_vertices {
error!("render_poly: coords and colours length mismatch");
return Err(Error::Geometr... | render | identifier_name |
poly.rs | // Copyright (C) 2020 Inderjit Gill <email@indy.io>
// This file is part of Seni
// Seni 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 l... | rpg.add_vertex(matrix, x, y, &colours[i], uvm.map[4], uvm.map[5])
}
Ok(())
}
| {
let num_vertices = coords.len();
if colours.len() != num_vertices {
error!("render_poly: coords and colours length mismatch");
return Err(Error::Geometry);
} else if num_vertices < 3 {
return Ok(());
}
let (x, y) = coords[0];
render_list.prepare_to_add_triangle_strip(m... | identifier_body |
poly.rs | // Copyright (C) 2020 Inderjit Gill <email@indy.io>
// This file is part of Seni
// Seni 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 l... | use crate::render_list::RenderList;
use crate::rgb::Rgb;
use crate::uvmapper::UvMapping;
use log::error;
pub fn render(
render_list: &mut RenderList,
matrix: &Matrix,
coords: &[(f32, f32)],
colours: &[Rgb],
uvm: &UvMapping,
) -> Result<()> {
let num_vertices = coords.len();
if colours.len()... | use crate::error::{Error, Result};
use crate::matrix::Matrix; | random_line_split |
era_prep.py | #!/usr/bin/env python
""" This module preprocesses ERA-Interim data, units, accumulated to instantaneous values and timestep interpolation for 6 h to 3 h values.
Example:
as import:
| Attributes:
wd = "/home/joel/sim/topomap_test/"
plotshp = TRUE
Todo:
"""
path2script = "./rsrc/toposcale_pre2.R"
# main
def main(wd, startDate, endDate):
"""Main entry point for the script."""
run_rscript_fileout(path2script,[wd, startDate, endDate])
# functions
def run_rscript_stdout(path2scrip... | from getERA import era_prep as prep
prep.main(wd, config['main']['startDate'], config['main']['endDate'])
| random_line_split |
era_prep.py | #!/usr/bin/env python
""" This module preprocesses ERA-Interim data, units, accumulated to instantaneous values and timestep interpolation for 6 h to 3 h values.
Example:
as import:
from getERA import era_prep as prep
prep.main(wd, config['main']['startDate'], config['main']['endDate'])
... | import sys
wd = sys.argv[1]
startDate = sys.argv[2]
endDate = sys.argv[3]
main(wd, startDate, endDate) | conditional_block | |
era_prep.py | #!/usr/bin/env python
""" This module preprocesses ERA-Interim data, units, accumulated to instantaneous values and timestep interpolation for 6 h to 3 h values.
Example:
as import:
from getERA import era_prep as prep
prep.main(wd, config['main']['startDate'], config['main']['endDate'])
... | (wd, startDate, endDate):
"""Main entry point for the script."""
run_rscript_fileout(path2script,[wd, startDate, endDate])
# functions
def run_rscript_stdout(path2script , args):
""" Function to define comands to run an Rscript. Returns an object. """
import subprocess
command = 'Rscript'
c... | main | identifier_name |
era_prep.py | #!/usr/bin/env python
""" This module preprocesses ERA-Interim data, units, accumulated to instantaneous values and timestep interpolation for 6 h to 3 h values.
Example:
as import:
from getERA import era_prep as prep
prep.main(wd, config['main']['startDate'], config['main']['endDate'])
... |
# calling main
if __name__ == '__main__':
import sys
wd = sys.argv[1]
startDate = sys.argv[2]
endDate = sys.argv[3]
main(wd, startDate, endDate)
| """ Function to define comands to run an Rscript. Outputs a file. """
import subprocess
command = 'Rscript'
cmd = [command, path2script] + args
print("Running:" + str(cmd))
subprocess.check_output(cmd) | identifier_body |
files.py | import six
#==============================================================================
# https://docs.python.org/2/library/csv.html
#==============================================================================
if six.PY2:
import csv
import codecs
import cStringIO
class UTF8Recoder:
"""... | (self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
... | __init__ | identifier_name |
files.py | import six
#==============================================================================
# https://docs.python.org/2/library/csv.html
#==============================================================================
if six.PY2:
import csv
import codecs
import cStringIO
class UTF8Recoder:
"""... |
def next(self):
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
... | f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds) | identifier_body |
files.py | import six
#==============================================================================
# https://docs.python.org/2/library/csv.html
#==============================================================================
if six.PY2:
| A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
... | import csv
import codecs
import cStringIO
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
retu... | conditional_block |
files.py | import six
#==============================================================================
# https://docs.python.org/2/library/csv.html
#==============================================================================
if six.PY2:
import csv
import codecs
import cStringIO
class UTF8Recoder:
"""... | """
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincre... | """
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding. | random_line_split |
shell.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
import atexit
import os
import platform
import warnings
import py4j
from pyspark import SparkConf
from pyspark.context import SparkContext
from pyspark.sql import SparkSession, SQLContext
if os.environ.get("SPARK_EXECUTOR_URI"):
SparkContext.setSystemProperty("spark.executor.uri", os.environ["SPARK_EXECUTOR_URI... | random_line_split | |
shell.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
else:
spark = SparkSession.builder.getOrCreate()
except py4j.protocol.Py4JError:
if conf.get('spark.sql.catalogImplementation', '').lower() == 'hive':
warnings.warn("Fall back to non-hive support because failing to access HiveConf, "
"please make sure you build spark with ... | SparkContext._jvm.org.apache.hadoop.hive.conf.HiveConf()
spark = SparkSession.builder\
.enableHiveSupport()\
.getOrCreate() | conditional_block |
__init__.py | """The met component."""
from datetime import timedelta
import logging
from random import randrange
import metno
from homeassistant.const import (
CONF_ELEVATION,
CONF_LATITUDE,
CONF_LONGITUDE,
EVENT_CORE_CONFIG_UPDATE,
LENGTH_FEET,
LENGTH_METERS,
)
from homeassistant.core import Config, HomeA... | hass.data[DOMAIN][config_entry.entry_id].untrack_home()
hass.data[DOMAIN].pop(config_entry.entry_id)
return True
class MetDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching Met data."""
def __init__(self, hass, config_entry):
"""Initialize global Met data updater."... | """Unload a config entry."""
await hass.config_entries.async_forward_entry_unload(config_entry, "weather") | random_line_split |
__init__.py | """The met component."""
from datetime import timedelta
import logging
from random import randrange
import metno
from homeassistant.const import (
CONF_ELEVATION,
CONF_LATITUDE,
CONF_LONGITUDE,
EVENT_CORE_CONFIG_UPDATE,
LENGTH_FEET,
LENGTH_METERS,
)
from homeassistant.core import Config, HomeA... |
class MetWeatherData:
"""Keep data for Met.no weather entities."""
def __init__(self, hass, config, is_metric):
"""Initialise the weather entity data."""
self.hass = hass
self._config = config
self._is_metric = is_metric
self._weather_data = None
self.current_... | self._unsub_track_home()
self._unsub_track_home = None | conditional_block |
__init__.py | """The met component."""
from datetime import timedelta
import logging
from random import randrange
import metno
from homeassistant.const import (
CONF_ELEVATION,
CONF_LATITUDE,
CONF_LONGITUDE,
EVENT_CORE_CONFIG_UPDATE,
LENGTH_FEET,
LENGTH_METERS,
)
from homeassistant.core import Config, HomeA... | (self, hass, config, is_metric):
"""Initialise the weather entity data."""
self.hass = hass
self._config = config
self._is_metric = is_metric
self._weather_data = None
self.current_weather_data = {}
self.daily_forecast = None
self.hourly_forecast = None
... | __init__ | identifier_name |
__init__.py | """The met component."""
from datetime import timedelta
import logging
from random import randrange
import metno
from homeassistant.const import (
CONF_ELEVATION,
CONF_LATITUDE,
CONF_LONGITUDE,
EVENT_CORE_CONFIG_UPDATE,
LENGTH_FEET,
LENGTH_METERS,
)
from homeassistant.core import Config, HomeA... |
def track_home(self):
"""Start tracking changes to HA home setting."""
if self._unsub_track_home:
return
async def _async_update_weather_data(_event=None):
"""Update weather data."""
self.weather.init_data()
await self.async_refresh()
... | """Class to manage fetching Met data."""
def __init__(self, hass, config_entry):
"""Initialize global Met data updater."""
self._unsub_track_home = None
self.weather = MetWeatherData(
hass, config_entry.data, hass.config.units.is_metric
)
self.weather.init_data()... | identifier_body |
sph_hamsi_test.rs | extern crate sphlib;
extern crate libc;
use sphlib::{sph_hamsi, utils};
#[test]
fn will_be_224_hash() {
let dest = sph_hamsi::hamsi224_init_load_close("");
let actual = utils::to_hex_hash(&dest);
assert_eq!("b9f6eb1a9b990373f9d2cb125584333c69a3d41ae291845f05da221f", actual.to_string());
}
#[test]
fn wi... |
#[test]
fn will_be_384_hash() {
let dest = sph_hamsi::hamsi384_init_load_close("");
let actual = utils::to_hex_hash(&dest);
assert_eq!("3943cd34e3b96b197a8bf4bac7aa982d18530dd12f41136b26d7e88759255f21153f4a4bd02e523612b8427f9dd96c8d", actual.to_string());
}
#[test]
fn will_be_512_hash() {
let dest ... | {
let dest = sph_hamsi::hamsi256_init_load_close("");
let actual = utils::to_hex_hash(&dest);
assert_eq!("750e9ec469f4db626bee7e0c10ddaa1bd01fe194b94efbabebd24764dc2b13e9", actual.to_string());
} | identifier_body |
sph_hamsi_test.rs | extern crate sphlib;
extern crate libc;
use sphlib::{sph_hamsi, utils};
#[test]
fn | () {
let dest = sph_hamsi::hamsi224_init_load_close("");
let actual = utils::to_hex_hash(&dest);
assert_eq!("b9f6eb1a9b990373f9d2cb125584333c69a3d41ae291845f05da221f", actual.to_string());
}
#[test]
fn will_be_256_hash() {
let dest = sph_hamsi::hamsi256_init_load_close("");
let actual = utils::... | will_be_224_hash | identifier_name |
sph_hamsi_test.rs | extern crate sphlib;
extern crate libc;
use sphlib::{sph_hamsi, utils};
#[test]
fn will_be_224_hash() {
let dest = sph_hamsi::hamsi224_init_load_close("");
let actual = utils::to_hex_hash(&dest);
assert_eq!("b9f6eb1a9b990373f9d2cb125584333c69a3d41ae291845f05da221f", actual.to_string());
}
#[test]
fn wi... | }
#[test]
fn will_be_512_hash() {
let dest = sph_hamsi::hamsi512_init_load_close("");
let actual = utils::to_hex_hash(&dest);
assert_eq!("5cd7436a91e27fc809d7015c3407540633dab391127113ce6ba360f0c1e35f404510834a551610d6e871e75651ea381a8ba628af1dcf2b2be13af2eb6247290f", actual.to_string());
} | #[test]
fn will_be_384_hash() {
let dest = sph_hamsi::hamsi384_init_load_close("");
let actual = utils::to_hex_hash(&dest);
assert_eq!("3943cd34e3b96b197a8bf4bac7aa982d18530dd12f41136b26d7e88759255f21153f4a4bd02e523612b8427f9dd96c8d", actual.to_string()); | random_line_split |
test_json_protocol.py | # -*- coding: utf-8 -*-
from thriftpy.protocol import TJSONProtocol
from thriftpy.thrift import TPayload, TType
from thriftpy.transport import TMemoryBuffer
from thriftpy._compat import u
import thriftpy.protocol.json as proto
class TItem(TPayload):
thrift_spec = {
1: (TType.I32, "id"),
2: (TTyp... | obj = {"ratio": 0.618}
spec = [TType.STRING, TType.DOUBLE]
json = proto.map_to_json(obj, spec)
assert [{"key": "ratio", "value": 0.618}] == json
def test_list_to_obj():
val = [4, 8, 4, 12, 67]
spec = TType.I32
obj = proto.list_to_obj(val, spec)
assert [4, 8, 4, 12, 67] == obj
def t... |
def test_map_to_json(): | random_line_split |
test_json_protocol.py | # -*- coding: utf-8 -*-
from thriftpy.protocol import TJSONProtocol
from thriftpy.thrift import TPayload, TType
from thriftpy.transport import TMemoryBuffer
from thriftpy._compat import u
import thriftpy.protocol.json as proto
class TItem(TPayload):
thrift_spec = {
1: (TType.I32, "id"),
2: (TTyp... |
def test_struct_to_json():
obj = TItem(id=13, phones=["5234", "12346456"])
json = proto.struct_to_json(obj)
assert {"id": 13, "phones": ["5234", "12346456"]} == json
def test_struct_to_obj():
json = {"id": 13, "phones": ["5234", "12346456"]}
obj = TItem()
obj = proto.struct_to_obj(json, o... | val = [4, 8, 4, 12, 67]
spec = TType.I32
json = proto.list_to_json(val, spec)
assert [4, 8, 4, 12, 67] == json | identifier_body |
test_json_protocol.py | # -*- coding: utf-8 -*-
from thriftpy.protocol import TJSONProtocol
from thriftpy.thrift import TPayload, TType
from thriftpy.transport import TMemoryBuffer
from thriftpy._compat import u
import thriftpy.protocol.json as proto
class TItem(TPayload):
thrift_spec = {
1: (TType.I32, "id"),
2: (TTyp... | (TPayload):
thrift_spec = {
1: (TType.STRING, "name")
}
default_spec = [("name", None)]
trans = TMemoryBuffer()
p = TJSONProtocol(trans)
foo = Foo(name=u('pão de açúcar'))
foo.write(p)
foo2 = Foo()
foo2.read(p)
assert foo == foo2
| Foo | identifier_name |
events.js | function runTest(config,qualifier) | event.messageType,
[ 'license-request', 'individualization-request' ] );
config.messagehandler( event.messageType, event.message ).then( function( response ) {
waitForEventAndRunStep('keystatuseschange', mediaKeySession, test.step_func(process... | {
var testname = testnamePrefix( qualifier, config.keysystem ) + ', basic events';
var configuration = getSimpleConfigurationForContent( config.content );
if ( config.initDataType && config.initData ) configuration.initDataTypes = [ config.initDataType ]
async_test(function(test)
{
var i... | identifier_body |
events.js | function runTest(config,qualifier) {
var testname = testnamePrefix( qualifier, config.keysystem ) + ', basic events';
var configuration = getSimpleConfigurationForContent( config.content );
if ( config.initDataType && config.initData ) configuration.initDataTypes = [ config.initDataType ]
async_test... | return mediaKeySession.generateRequest(initDataType, initData);
})).catch(test.step_func(function(error) {
forceTestFailureFromPromise(test, error);
}));
}, testname );
} | return access.createMediaKeys();
}).then(test.step_func(function(mediaKeys) {
mediaKeySession = mediaKeys.createSession();
waitForEventAndRunStep('message', mediaKeySession, test.step_func(processMessage), test); | random_line_split |
events.js | function | (config,qualifier) {
var testname = testnamePrefix( qualifier, config.keysystem ) + ', basic events';
var configuration = getSimpleConfigurationForContent( config.content );
if ( config.initDataType && config.initData ) configuration.initDataTypes = [ config.initDataType ]
async_test(function(test)
... | runTest | identifier_name |
conf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
#
# This file is based upon the file generated by sphinx-quickstart. However,
# where sphinx-quickstart hardcodes values in this file that you input, this
# file has been changed to pull from your module's metadata module.
#
# This file is execfile(... | # The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any pat... | random_line_split | |
Gruntfile.js | /* recebe o objeto grunt como parâmetro*/
module.exports = function(grunt) {
grunt.initConfig({
clean: {
dist: {
src: 'dist'
}
},
copy: {
public: {
cwd: 'public',
src: '**',
dest: 'dist',
expand: true
}
},
useminPrepare: {
html: 'dist/**/*.html'
},
usemin: {
h... | options: {
watchTask: true,
server: {
baseDir: "public"
}
}
}
}
});
grunt.registerTask('dist', ['clean', 'copy']);
grunt.registerTask('minifica', ['useminPrepare', 'concat', 'uglify', 'cssmin', 'rev:imagens','rev:minificados', 'usemin', 'imagemin']);
grunt.registerTask... | src: ['public/**/*']
}, | random_line_split |
jqt.activityIndicator.js | /*
_/ _/_/ _/_/_/_/_/ _/
_/ _/ _/ _/_/ _/ _/ _/_/_/ _/_/_/
_/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/
_/ ... | clear();
context.save();
context.translate(xPos, yPos);
for (var i = 0; i < numberOfBars; i++) {
var angle = 2 * ((offset + i) % numberOfBars) * Math.PI / numberOfBars;
context.save();
context.translate((innerRadius * Math.sin(-angle)), (innerRadius * Math.cos(-angle)));
context.... |
function draw(offset) { | random_line_split |
jqt.activityIndicator.js | /*
_/ _/_/ _/_/_/_/_/ _/
_/ _/ _/ _/_/ _/ _/ _/_/_/ _/_/_/
_/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/
_/ ... | ;
offset = (offset + direction) % numberOfBars;
draw(offset);
setTimeout(animate, speed);
};
function start(){
animating = true;
animate();
};
function stop(){
animating = false;
clear();
};
return {
start: start,
stop: stop
};
}; | {return;} | conditional_block |
jqt.activityIndicator.js | /*
_/ _/_/ _/_/_/_/_/ _/
_/ _/ _/ _/_/ _/ _/ _/_/_/ _/_/_/
_/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/
_/ ... | ;
function start(){
animating = true;
animate();
};
function stop(){
animating = false;
clear();
};
return {
start: start,
stop: stop
};
}; | {
if (!animating) {return;};
offset = (offset + direction) % numberOfBars;
draw(offset);
setTimeout(animate, speed);
} | identifier_body |
jqt.activityIndicator.js | /*
_/ _/_/ _/_/_/_/_/ _/
_/ _/ _/ _/_/ _/ _/ _/_/_/ _/_/_/
_/ _/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/
_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/
_/ ... | (canvas) {
var animating = false;
var barHeight = $(canvas).attr('barHeight') - 0;
var barWidth = $(canvas).attr('barWidth') - 0;
var color = $(canvas).css('color');
var context = $(canvas).get(0).getContext('2d');
var direction = $(canvas).attr('direction');
var innerRadius = $(canvas).attr('innerRadius'... | activityIndicator | identifier_name |
match.rs | name",
"type",
"value",
"scopeid"),
true,
true),
};
match x{
y=>{/*Block wit... | }
sfEvtKeyPressed => {
let e = unsafe { event.key.as_ref() };
KeyPressed {
code: unsafe { ::std::mem::transmute(e.code) },
alt: e.alt.to_bool(),
ctrl: e.control.to_bool(),
shift: e.shift.to_bool(),
s... | {
Some(match type_ {
sfEvtClosed => Closed,
sfEvtResized => {
let e = unsafe { *event.size.as_ref() };
Resized {
width: e.width,
height: e.height,
}
}
sfEvtLostFocus => LostFocus,
sfEvtGainedFocus => GainedF... | identifier_body |
match.rs | {
match a {
b => {}
c => { }
d => {
}
e => {
}
// collapsing here is safe
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff => {
}
// collapsing here exceeds line length
fffffffffffffffff... | issue525 | identifier_name | |
match.rs | qualname",
"type",
"value",
"scopeid"),
true,
true),
};
match x{
y=>{/*Block... | m => {
} n => { } o =>
{
}
p => { // Don't collapse me
} q => { } r =>
{
}
s => 0, // s comment
// t comment
t => 1,
u => 2,
v => {
} /* funky block
* comment */
// final comment
}
}
... | // }
// l => {
// // comment with ws below
//
// } | random_line_split |
HTMLViewer.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014 Technische Universität Berlin,
Fakultät IV - Elektrotechnik und Informatik,
Fachgebiet Regelungssysteme,
Einsteinufer 17, D-10587 Berlin, Germany
This file is part of PaPI.
PaPI is free software: you can redistribute it and/or modify
it under the term... | def cb_execute(self, Data=None, block_name = None, plugin_uname = None):
# Do main work here!
# If this plugin is an IOP plugin, then there will be no Data parameter because it wont get data
# If this plugin is a DPP, then it will get Data with data
# param: Data is a Data hash and ... | ss
| identifier_body |
HTMLViewer.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014 Technische Universität Berlin,
Fakultät IV - Elektrotechnik und Informatik,
Fachgebiet Regelungssysteme,
Einsteinufer 17, D-10587 Berlin, Germany
This file is part of PaPI.
PaPI is free software: you can redistribute it and/or modify
it under the term... | elf, name, value):
# attetion: value is a string and need to be processed !
# if name == 'irgendeinParameter':
# do that .... with value
pass
def cb_quit(self):
# do something before plugin will close, e.a. close connections ...
pass
def cb_get_plugin_configu... | _set_parameter(s | identifier_name |
HTMLViewer.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014 Technische Universität Berlin,
Fakultät IV - Elektrotechnik und Informatik,
Fachgebiet Regelungssysteme,
Einsteinufer 17, D-10587 Berlin, Germany
This file is part of PaPI.
PaPI is free software: you can redistribute it and/or modify
it under the term... | 'tooltip': "Set to 1 if the content is an url that should be loaded",
'advanced' : 'HTML'
},
}
return config
def cb_plugin_meta_updated(self):
"""
Whenever the meta information is updated this function is called (if implemented).
... | random_line_split | |
HTMLViewer.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014 Technische Universität Berlin,
Fakultät IV - Elektrotechnik und Informatik,
Fachgebiet Regelungssysteme,
Einsteinufer 17, D-10587 Berlin, Germany
This file is part of PaPI.
PaPI is free software: you can redistribute it and/or modify
it under the term... | else:
self.WebView.setHtml(content)
self.WebView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.WebView.customContextMenuRequested.connect(self.show_context_menu)
return True
def show_context_menu(self, pos):
gloPos = self.WebView.mapToGlobal(pos)
... | l = QtCore.QUrl(content)
self.WebView.load(url)
| conditional_block |
saveSimu.py | #!/usr/bin/python
import Sofa
import Flexible.IO
import sys,os
datadir=os.path.dirname(os.path.realpath(__file__))+"/data/"
nbFrames = 10
nbGaussPoints = 1
file_Dof= datadir + "dofs.py"
file_SF= datadir + "SF.py"
file_GP= datadir + "GP.py"
# scene creation method
def createScene(rootNode):
rootNode.createObject('... |
return 0
def onKeyPressed(self,k):
if self.dof==None or self.sf==None or self.gp==None:
return 0
if ord(k)==32: # ctrl+SPACE
Flexible.IO.export_AffineFrames(self.dof, file_Dof)
Flexible.IO.export_ImageShapeFunction(self.node, self.sf, file_SF)
Flexible.IO.export_GaussPoints(self.gp, file_GP)
... | print "PythonScriptController: components in variables not found"
return 0 | conditional_block |
saveSimu.py | #!/usr/bin/python
import Sofa
import Flexible.IO
import sys,os
datadir=os.path.dirname(os.path.realpath(__file__))+"/data/"
nbFrames = 10
nbGaussPoints = 1
file_Dof= datadir + "dofs.py"
file_SF= datadir + "SF.py"
file_GP= datadir + "GP.py"
# scene creation method
def createScene(rootNode):
rootNode.createObject('... | if self.dof==None or self.sf==None or self.gp==None:
return 0
if ord(k)==32: # ctrl+SPACE
Flexible.IO.export_AffineFrames(self.dof, file_Dof)
Flexible.IO.export_ImageShapeFunction(self.node, self.sf, file_SF)
Flexible.IO.export_GaussPoints(self.gp, file_GP)
print "Simulation state saved";
return ... | identifier_body | |
saveSimu.py | #!/usr/bin/python
import Sofa
import Flexible.IO
import sys,os
datadir=os.path.dirname(os.path.realpath(__file__))+"/data/"
nbFrames = 10
nbGaussPoints = 1
file_Dof= datadir + "dofs.py"
file_SF= datadir + "SF.py"
file_GP= datadir + "GP.py"
# scene creation method
def createScene(rootNode):
rootNode.createObject('... |
class simu_save(Sofa.PythonScriptController):
def createGraph(self,node):
self.node=node
self.dof = node.getObject(self.findData('variables').value[0][0])
self.sf = node.getObject(self.findData('variables').value[1][0])
self.gp = node.getObject(self.findData('variables').value[2][0])
if self.dof==None or s... | #----------------------------------------------------------------------------------------------------------------------------------------- | random_line_split |
saveSimu.py | #!/usr/bin/python
import Sofa
import Flexible.IO
import sys,os
datadir=os.path.dirname(os.path.realpath(__file__))+"/data/"
nbFrames = 10
nbGaussPoints = 1
file_Dof= datadir + "dofs.py"
file_SF= datadir + "SF.py"
file_GP= datadir + "GP.py"
# scene creation method
def createScene(rootNode):
rootNode.createObject('... | (Sofa.PythonScriptController):
def createGraph(self,node):
self.node=node
self.dof = node.getObject(self.findData('variables').value[0][0])
self.sf = node.getObject(self.findData('variables').value[1][0])
self.gp = node.getObject(self.findData('variables').value[2][0])
if self.dof==None or self.sf==None or ... | simu_save | identifier_name |
index.js | import React, { Component } from 'react';
import { TouchableHighlight, Text } from 'react-native';
import All from 'rnx-ui/All';
import ImgRollView from 'rnx-ui/ImgRollView';
import Alert from 'rnx-ui/Alert';
import { NavBar, Icon } from '../../component';
import Router from '../../router';
import style from './styl... | (data) {
const { uriSelected } = data;
this.setState({ uriSelected });
}
toggleURIList() {
this.setState({
visible: !this.state.visible,
});
}
render() {
const { uriSelected, visible } = this.state;
return (
<All>
<NavBar title="ImgRollView" />
<ImgRollView... | onSelect | identifier_name |
index.js | import React, { Component } from 'react';
import { TouchableHighlight, Text } from 'react-native';
import All from 'rnx-ui/All';
import ImgRollView from 'rnx-ui/ImgRollView';
import Alert from 'rnx-ui/Alert';
import { NavBar, Icon } from '../../component';
import Router from '../../router';
import style from './styl... | onPress={this.toggleURIList}
/>
</All>
);
}
}
Router.register('ImgRollView', Page);
export default Page; | random_line_split | |
index.js | import React, { Component } from 'react';
import { TouchableHighlight, Text } from 'react-native';
import All from 'rnx-ui/All';
import ImgRollView from 'rnx-ui/ImgRollView';
import Alert from 'rnx-ui/Alert';
import { NavBar, Icon } from '../../component';
import Router from '../../router';
import style from './styl... |
onSelect(data) {
const { uriSelected } = data;
this.setState({ uriSelected });
}
toggleURIList() {
this.setState({
visible: !this.state.visible,
});
}
render() {
const { uriSelected, visible } = this.state;
return (
<All>
<NavBar title="ImgRollView" />
... | {
super(props);
this.state = {
uriSelected: [],
visible: false,
};
this.onSelect = this.onSelect.bind(this);
this.toggleURIList = this.toggleURIList.bind(this);
} | identifier_body |
views.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.core.urlresolvers import reverse
from django.views.generic import DetailView, ListView, RedirectView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import User
class UserDetailView(Login... | (self):
return reverse("users:detail",
kwargs={"username": self.request.user.username})
def get_object(self):
# Only get the User record for the user making the request
return User.objects.get(username=self.request.user.username)
class UserListView(LoginRequiredMixi... | get_success_url | identifier_name |
views.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.core.urlresolvers import reverse
from django.views.generic import DetailView, ListView, RedirectView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import User
class UserDetailView(Login... |
class UserUpdateView(LoginRequiredMixin, UpdateView):
fields = ['name', ]
# we already imported User in the view code above, remember?
model = User
# send the user back to their own page after a successful update
def get_success_url(self):
return reverse("users:detail",
... | return reverse("users:detail",
kwargs={"username": self.request.user.username}) | identifier_body |
views.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.core.urlresolvers import reverse
from django.views.generic import DetailView, ListView, RedirectView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import User
class UserDetailView(Login... | # Only get the User record for the user making the request
return User.objects.get(username=self.request.user.username)
class UserListView(LoginRequiredMixin, ListView):
model = User
# These next two lines tell the view to index lookups by username
slug_field = "username"
slug_url_kwar... |
def get_object(self): | random_line_split |
resources.py | # Autogenerated by the mkresources management command 2014-11-13 23:53
from tastypie.resources import ModelResource
from tastypie.fields import ToOneField, ToManyField
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from ietf import api
from ietf.message.models import * # pyflakes:ignore
from ietf.pers... | (ModelResource):
by = ToOneField(PersonResource, 'by')
message = ToOneField(MessageResource, 'message')
class Meta:
queryset = SendQueue.objects.all()
serializer = api.Serializer()
#resource_name = 'sendqueue'
filtering = {
"id": ALL,
... | SendQueueResource | identifier_name |
resources.py | # Autogenerated by the mkresources management command 2014-11-13 23:53
from tastypie.resources import ModelResource
from tastypie.fields import ToOneField, ToManyField
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from ietf import api
from ietf.message.models import * # pyflakes:ignore
from ietf.pers... | "related_docs": ALL_WITH_RELATIONS,
}
api.message.register(MessageResource())
from ietf.person.resources import PersonResource
class SendQueueResource(ModelResource):
by = ToOneField(PersonResource, 'by')
message = ToOneField(MessageResource, 'message')
class Meta... | "related_groups": ALL_WITH_RELATIONS, | random_line_split |
resources.py | # Autogenerated by the mkresources management command 2014-11-13 23:53
from tastypie.resources import ModelResource
from tastypie.fields import ToOneField, ToManyField
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from ietf import api
from ietf.message.models import * # pyflakes:ignore
from ietf.pers... |
api.message.register(SendQueueResource())
| by = ToOneField(PersonResource, 'by')
message = ToOneField(MessageResource, 'message')
class Meta:
queryset = SendQueue.objects.all()
serializer = api.Serializer()
#resource_name = 'sendqueue'
filtering = {
"id": ALL,
"time": ALL,
... | identifier_body |
TreeTraversal.py | import Queue
class Graph:
def __init__(self, number_of_vertices):
self.number_of_vertices = number_of_vertices
self.vertex_details = {}
self.visited = {}
def add_edge(self, vertex_label, edge):
if self.vertex_details.has_key(vertex_label):
self.vertex_details[vertex_label].append(edge)
else:
self.... | ():
g = Graph(4)
g.add_edge(0, 1);
g.add_edge(0, 2);
g.add_edge(1, 2);
g.add_edge(2, 0);
g.add_edge(2, 3);
g.add_edge(3, 3);
# bfs_trace = g.bfs(2)
# g.print_bfs(bfs_trace)
g.dfs(2)
if __name__ == '__main__':
main()
| main | identifier_name |
TreeTraversal.py | import Queue
class Graph:
def __init__(self, number_of_vertices):
self.number_of_vertices = number_of_vertices
self.vertex_details = {}
self.visited = {}
def add_edge(self, vertex_label, edge):
if self.vertex_details.has_key(vertex_label):
self.vertex_details[vertex_label].append(edge)
else:
self.... |
def dfs(self, vertex):
self.visited[vertex] = 1
print vertex," ",
adjacent_vertices = self.vertex_details[vertex]
for adjacent_vertex in adjacent_vertices:
if self.visited[adjacent_vertex] == 0:
self.dfs(adjacent_vertex)
def print_bfs(self, bfs_trace):
print bfs_trace
def main():
g = Graph(4)
g... | print "Starting breath first search from vertex: ", starting_vertex
bfs_queue = Queue.Queue()
bfs_trace = []
bfs_queue.put(starting_vertex)
self.visited[starting_vertex] = 1
while(not bfs_queue.empty()):
current_vertex = bfs_queue.get()
bfs_trace.append(current_vertex)
adjacent_vertices = self.vert... | identifier_body |
TreeTraversal.py | import Queue
class Graph:
def __init__(self, number_of_vertices):
self.number_of_vertices = number_of_vertices
self.vertex_details = {}
self.visited = {}
def add_edge(self, vertex_label, edge):
if self.vertex_details.has_key(vertex_label):
self.vertex_details[vertex_label].append(edge)
else:
self.... |
return bfs_trace
def dfs(self, vertex):
self.visited[vertex] = 1
print vertex," ",
adjacent_vertices = self.vertex_details[vertex]
for adjacent_vertex in adjacent_vertices:
if self.visited[adjacent_vertex] == 0:
self.dfs(adjacent_vertex)
def print_bfs(self, bfs_trace):
print bfs_trace
def main... | current_vertex = bfs_queue.get()
bfs_trace.append(current_vertex)
adjacent_vertices = self.vertex_details[current_vertex]
for adjacent_vertex in adjacent_vertices:
if self.visited[adjacent_vertex] == 0:
bfs_queue.put(adjacent_vertex)
self.visited[adjacent_vertex] = 1 | conditional_block |
TreeTraversal.py | import Queue
class Graph:
def __init__(self, number_of_vertices):
self.number_of_vertices = number_of_vertices
self.vertex_details = {}
self.visited = {}
def add_edge(self, vertex_label, edge):
if self.vertex_details.has_key(vertex_label):
self.vertex_details[vertex_label].append(edge)
else:
self.... |
def main():
g = Graph(4)
g.add_edge(0, 1);
g.add_edge(0, 2);
g.add_edge(1, 2);
g.add_edge(2, 0);
g.add_edge(2, 3);
g.add_edge(3, 3);
# bfs_trace = g.bfs(2)
# g.print_bfs(bfs_trace)
g.dfs(2)
if __name__ == '__main__':
main() | random_line_split | |
char_indexing.rs | use std::ops::Range;
pub(crate) trait CharIndexable<'b> {
fn char_index(&'b self, range: Range<usize>) -> &'b str;
}
pub struct CharIndexableStr<'a> {
s: &'a str,
indices: Vec<usize>,
}
impl CharIndexableStr<'_> {
pub(crate) fn char_count(&self) -> usize {
self.indices.len()
}
}
impl<'a>... | (s: &'a str) -> Self {
CharIndexableStr {
indices: s.char_indices().map(|(i, _c)| i).collect(),
s,
}
}
}
impl<'a, 'b: 'a> CharIndexable<'b> for CharIndexableStr<'a> {
fn char_index(&'b self, range: Range<usize>) -> &'b str {
if range.end >= self.indices.len() {
... | from | identifier_name |
char_indexing.rs | use std::ops::Range;
pub(crate) trait CharIndexable<'b> {
fn char_index(&'b self, range: Range<usize>) -> &'b str;
}
pub struct CharIndexableStr<'a> {
s: &'a str,
indices: Vec<usize>,
}
impl CharIndexableStr<'_> {
pub(crate) fn char_count(&self) -> usize {
self.indices.len()
}
}
impl<'a>... |
}
}
| {
&self.s[self.indices[range.start]..self.indices[range.end]]
} | conditional_block |
char_indexing.rs | use std::ops::Range;
pub(crate) trait CharIndexable<'b> {
fn char_index(&'b self, range: Range<usize>) -> &'b str;
}
pub struct CharIndexableStr<'a> {
s: &'a str,
indices: Vec<usize>,
}
impl CharIndexableStr<'_> {
pub(crate) fn char_count(&self) -> usize {
self.indices.len()
}
}
impl<'a>... | &self.s[self.indices[range.start]..self.indices[range.end]]
}
}
} | &self.s[self.indices[range.start]..]
} else { | random_line_split |
estr-slice.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 ... |
info!(a);
assert!(a < b);
assert!(a <= b);
assert!(a != b);
assert!(b >= a);
assert!(b > a);
info!(b);
assert!(a < c);
assert!(a <= c);
assert!(a != c);
assert!(c >= a);
assert!(c > a);
info!(c);
assert!(c < cc);
assert!(c <= cc);
assert!(c != cc);
... | {
let x = &"hello";
let v = &"hello";
let y : &str = &"there";
info!(x);
info!(y);
assert_eq!(x[0], 'h' as u8);
assert_eq!(x[4], 'o' as u8);
let z : &str = &"thing";
assert_eq!(v, x);
assert!(x != z);
let a = &"aaaa";
let b = &"bbbb";
let c = &"cccc";
let cc ... | identifier_body |
estr-slice.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 ... | assert!(c > a);
info!(c);
assert!(c < cc);
assert!(c <= cc);
assert!(c != cc);
assert!(cc >= c);
assert!(cc > c);
info!(cc);
} | assert!(a <= c);
assert!(a != c);
assert!(c >= a); | random_line_split |
estr-slice.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = &"hello";
let v = &"hello";
let y : &str = &"there";
info!(x);
info!(y);
assert_eq!(x[0], 'h' as u8);
assert_eq!(x[4], 'o' as u8);
let z : &str = &"thing";
assert_eq!(v, x);
assert!(x != z);
let a = &"aaaa";
let b = &"bbbb";
let c = &"cccc";
let ... | main | identifier_name |
localizations.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | return false;
}
return true;
} | random_line_split | |
localizations.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
if (localization.localizedLanguageName && typeof localization.localizedLanguageName !== 'string') {
return false;
}
return true;
}
| {
return false;
} | conditional_block |
localizations.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (localization: ILocalization): boolean {
if (typeof localization.languageId !== 'string') {
return false;
}
if (!Array.isArray(localization.translations) || localization.translations.length === 0) {
return false;
}
for (const translation of localization.translations) {
if (typeof translation.id !== 'string')... | isValidLocalization | identifier_name |
localizations.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
return true;
}
| {
if (typeof localization.languageId !== 'string') {
return false;
}
if (!Array.isArray(localization.translations) || localization.translations.length === 0) {
return false;
}
for (const translation of localization.translations) {
if (typeof translation.id !== 'string') {
return false;
}
if (typeof tr... | identifier_body |
hash-chain.py | #-*- coding: utf-8 -*-
class Hash():
def __init__(self):
self.size = 20
self.slots = []
for i in xrange(0, 20):
self.slots.append([])
def __setitem__(self, key, value):
chain = self.slots[self.hash(key)]
for data in chain:
if data[0] == key:
... |
raise ValueError("Key %s if not found." % key)
def hash(self, key):
return self.stoi(key) % self.size
def stoi(self, key):
inte = 0
for c in key:
inte = inte + ord(c)
return inte
h = Hash()
h["fuck"] = val = {"name": "jerry"}
h["ucfk"] = val2 = {"name": "l... | if data[0] == key:
del chain[i]
return True | conditional_block |
hash-chain.py | #-*- coding: utf-8 -*-
class Hash():
def __init__(self):
self.size = 20
self.slots = []
for i in xrange(0, 20):
self.slots.append([])
def __setitem__(self, key, value):
chain = self.slots[self.hash(key)]
for data in chain:
if data[0] == key:
... | assert h["uoy"] == "sucks"
h.delete("you")
assert h["you"] == None
h["uoy"] = "Fool"
assert h["uoy"] == "Fool" | h["uoy"] = "sucks"
assert h["you"] == "cool" | random_line_split |
hash-chain.py | #-*- coding: utf-8 -*-
class | ():
def __init__(self):
self.size = 20
self.slots = []
for i in xrange(0, 20):
self.slots.append([])
def __setitem__(self, key, value):
chain = self.slots[self.hash(key)]
for data in chain:
if data[0] == key:
data[1] = value
... | Hash | identifier_name |
hash-chain.py | #-*- coding: utf-8 -*-
class Hash():
def __init__(self):
|
def __setitem__(self, key, value):
chain = self.slots[self.hash(key)]
for data in chain:
if data[0] == key:
data[1] = value
return True
chain.append([key, value])
def __getitem__(self, key):
chain = self.slots[self.hash(key)]
... | self.size = 20
self.slots = []
for i in xrange(0, 20):
self.slots.append([]) | identifier_body |
quick_test.py | import sys
import os
from ..data.molecular_species import molecular_species
from ..data.reaction_mechanism_class import reaction_mechanism
from ..data.condition_class import condition
from ..data.reagent import reagent
from ..data.puzzle_class import puzzle
from ..data.solution_class import solution
def | (class_obj):
return class_obj.__name__
# depends on JSON base class
for class_being_tested in [molecular_species, condition, reaction_mechanism, reagent, puzzle, solution]:
system_output = sys.stdout # store stdout
sys.stdout = open(os.getcwd() + "/testing_result_" + name(class_being_tested) + ".txt", "w") # pipe t... | name | identifier_name |
quick_test.py | import sys
import os
from ..data.molecular_species import molecular_species
from ..data.reaction_mechanism_class import reaction_mechanism
from ..data.condition_class import condition
from ..data.reagent import reagent
from ..data.puzzle_class import puzzle
from ..data.solution_class import solution
def name(class_obj... | print("FAILED", name(class_being_tested), sep=" ") | conditional_block | |
quick_test.py | import sys
import os
from ..data.molecular_species import molecular_species
from ..data.reaction_mechanism_class import reaction_mechanism
from ..data.condition_class import condition
from ..data.reagent import reagent
from ..data.puzzle_class import puzzle
from ..data.solution_class import solution
def name(class_obj... | test_result = class_being_tested.test()
sys.stdout.close() # close file
sys.stdout = system_output #replace stdout
if test_result:
print("PASSED", name(class_being_tested), sep=" ")
else:
print("FAILED", name(class_being_tested), sep=" ") | sys.stdout = open(os.getcwd() + "/testing_result_" + name(class_being_tested) + ".txt", "w") # pipe to file | random_line_split |
quick_test.py | import sys
import os
from ..data.molecular_species import molecular_species
from ..data.reaction_mechanism_class import reaction_mechanism
from ..data.condition_class import condition
from ..data.reagent import reagent
from ..data.puzzle_class import puzzle
from ..data.solution_class import solution
def name(class_obj... |
# depends on JSON base class
for class_being_tested in [molecular_species, condition, reaction_mechanism, reagent, puzzle, solution]:
system_output = sys.stdout # store stdout
sys.stdout = open(os.getcwd() + "/testing_result_" + name(class_being_tested) + ".txt", "w") # pipe to file
test_result = class_being_teste... | return class_obj.__name__ | identifier_body |
moosetree.py | # moosetree.py ---
#
# Filename: moosetree.py
# Description:
# Author: subhasis ray
# Maintainer:
# Created: Tue Jun 23 18:54:14 2009 (+0530)
# Version:
# Last-Updated: Sun Jul 5 01:35:11 2009 (+0530)
# By: subhasis ray
# Update #: 137
# URL:
# Keywords:
# Compatibility:
#
#
# Commentary:
#
... | (self, text):
self.setText(0, QtCore.QString(self.mooseObj_.name))
class MooseTreeWidget(QtGui.QTreeWidget):
def __init__(self, *args):
QtGui.QTreeWidget.__init__(self, *args)
self.rootObject = moose.Neutral('/')
self.itemList = []
self.setupTree(self.rootObject, self, self.itemList)
self.setCurrentIt... | updateSlot | identifier_name |
moosetree.py | # moosetree.py ---
#
# Filename: moosetree.py
# Description:
# Author: subhasis ray
# Maintainer:
# Created: Tue Jun 23 18:54:14 2009 (+0530)
# Version:
# Last-Updated: Sun Jul 5 01:35:11 2009 (+0530)
# By: subhasis ray
# Update #: 137
# URL:
# Keywords:
# Compatibility:
#
#
# Commentary:
#
... |
def setupTree(self, mooseObject, parent, itemlist):
item = MooseTreeItem(parent)
item.setMooseObject(mooseObject)
itemlist.append(item)
for child in mooseObject.children():
childObj = moose.Neutral(child)
self.setupTree(childObj, item, itemlist)
return item
def recreateTree(self):
sel... | QtGui.QTreeWidget.__init__(self, *args)
self.rootObject = moose.Neutral('/')
self.itemList = []
self.setupTree(self.rootObject, self, self.itemList)
self.setCurrentItem(self.itemList[0]) # Make root the default item | identifier_body |
moosetree.py | # moosetree.py ---
#
# Filename: moosetree.py
# Description:
# Author: subhasis ray
# Maintainer:
# Created: Tue Jun 23 18:54:14 2009 (+0530)
# Version:
# Last-Updated: Sun Jul 5 01:35:11 2009 (+0530)
# By: subhasis ray
# Update #: 137
# URL:
# Keywords:
# Compatibility:
#
#
# Commentary:
#
... |
else:
raise Error
self.setText(0, QtCore.QString(self.mooseObj_.name))
self.setToolTip(0, QtCore.QString('class:' + self.mooseObj_.className))
def getMooseObject(self):
return self.mooseObj_
def updateSlot(self, text):
self.setText(0, QtCore.QString(self.mooseObj_.name))
class MooseTreeWidget(QtGu... | self.mooseObj_ = mooseObject | conditional_block |
moosetree.py | # moosetree.py ---
#
# Filename: moosetree.py
# Description:
# Author: subhasis ray
# Maintainer:
# Created: Tue Jun 23 18:54:14 2009 (+0530)
# Version:
# Last-Updated: Sun Jul 5 01:35:11 2009 (+0530)
# By: subhasis ray
# Update #: 137
# URL:
# Keywords: | # Compatibility:
#
#
# Commentary:
#
#
#
#
# Change log:
#
#
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3, or
# (at your option) any later version.
#
# Thi... | random_line_split | |
infer_regusage.rs | //! Infers how each function uses every register
//! For every function, patch all of its call sites to ignore registers that the
//! callee doesn't read and to preserve register values that the callee
//! preserves. Then, record which registers it reads and which registers it
//! preserves.
//!
//! After this, all fun... | (
&self,
call_node: <SSAStorage as SSA>::ValueRef,
fn_addr: u64,
fn_map: &mut BTreeMap<u64, RadecoFunction>,
) -> Option<()> {
// bail on indirect or weird call
let (call_tgt_addr, call_reg_map) = direct_call_info(fn_map[&fn_addr].ssa(), call_node)?;
// remov... | patch_call_node | identifier_name |
infer_regusage.rs | //! Infers how each function uses every register
//! For every function, patch all of its call sites to ignore registers that the
//! callee doesn't read and to preserve register values that the callee
//! preserves. Then, record which registers it reads and which registers it
//! preserves.
//!
//! After this, all fun... |
}
}
None
}
}
impl Inferer {
pub fn new(reginfo: SubRegisterFile) -> Inferer {
Inferer {
reginfo: reginfo,
analyzed: HashSet::new(),
}
}
/// Using the callconv info we've gathered so far, patch-up call sites to
/// to remove argu... | {
self.patch_fn(fn_addr, &mut rmod.functions);
let rfn = &mut rmod.functions.get_mut(&fn_addr).unwrap();
let mut dce = DCE::new();
dce.analyze(rfn, Some(all));
let mut combiner = Combiner::new();
co... | conditional_block |
infer_regusage.rs | //! Infers how each function uses every register
//! For every function, patch all of its call sites to ignore registers that the
//! callee doesn't read and to preserve register values that the callee
//! preserves. Then, record which registers it reads and which registers it
//! preserves.
//!
//! After this, all fun... | ret.set_all_ignored();
for regid in ssa.regfile.iter_register_ids() {
// ignore registers not in entry regstate
if let Some(&(reg_val_entry, _)) = entry_regstate.get(regid) {
// bail if a register isn't present in exit regstate
let &(reg_val_exit,... | let entry_regstate = utils::register_state_info(entry_regstate_node, ssa);
let exit_regstate = utils::register_state_info(exit_regstate_node, ssa);
let mut ret = reginfo.new_register_usage(); | random_line_split |
infer_regusage.rs | //! Infers how each function uses every register
//! For every function, patch all of its call sites to ignore registers that the
//! callee doesn't read and to preserve register values that the callee
//! preserves. Then, record which registers it reads and which registers it
//! preserves.
//!
//! After this, all fun... |
fn patch_call_node(
&self,
call_node: <SSAStorage as SSA>::ValueRef,
fn_addr: u64,
fn_map: &mut BTreeMap<u64, RadecoFunction>,
) -> Option<()> {
// bail on indirect or weird call
let (call_tgt_addr, call_reg_map) = direct_call_info(fn_map[&fn_addr].ssa(), call_n... | {
radeco_trace!("patching calls in fn: {}", fn_map[&fn_addr].name);
for node in fn_map[&fn_addr].ssa().inorder_walk() {
if let Ok(NodeType::Op(ir::MOpcode::OpCall)) =
fn_map[&fn_addr].ssa().node_data(node).map(|nd| nd.nt)
{
self.patch_call_node(nod... | identifier_body |
server.py | import socket
from PIL import Image
import io
import os
def string_to_byte(hex_input):
return bytearray.fromhex(hex_input)
def serve():
host = ""
port = 5001
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.bind((host, port))
my_socket.listen(1)
conn, address = ... |
print("Read hex bytes: ", len(decoded_data_buffer))
image_bytes = string_to_byte(decoded_data_buffer)
print("Read bytes: ", len(image_bytes))
img = Image.open(io.BytesIO(bytes(image_bytes)))
imageName = "test" + ".jpg"
img.save(imageName)
print("Saved image: "... | missing_bytes = expected_size - hexBytesCount
data = conn.recv(missing_bytes if missing_bytes < 1024 else 1024)
if not data:
break
print("Read ", hexBytesCount, " out of ", expected_size)
last_read_size = len(data)
hexBytesCount += last_read_s... | conditional_block |
server.py | import socket
from PIL import Image
import io
import os
def string_to_byte(hex_input):
return bytearray.fromhex(hex_input)
| port = 5001
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.bind((host, port))
my_socket.listen(1)
conn, address = my_socket.accept()
decoded_data_buffer = ""
decoded_data = ""
print("Connection from: " + str(address))
# Keep on reading untill the program f... |
def serve():
host = "" | random_line_split |
server.py | import socket
from PIL import Image
import io
import os
def string_to_byte(hex_input):
|
def serve():
host = ""
port = 5001
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.bind((host, port))
my_socket.listen(1)
conn, address = my_socket.accept()
decoded_data_buffer = ""
decoded_data = ""
print("Connection from: " + str(address))
# Keep o... | return bytearray.fromhex(hex_input) | identifier_body |
server.py | import socket
from PIL import Image
import io
import os
def string_to_byte(hex_input):
return bytearray.fromhex(hex_input)
def | ():
host = ""
port = 5001
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.bind((host, port))
my_socket.listen(1)
conn, address = my_socket.accept()
decoded_data_buffer = ""
decoded_data = ""
print("Connection from: " + str(address))
# Keep on reading un... | serve | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.