file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
test_issue_162.py | import numpy as np
import pyroomacoustics as pra
def compute_rir(order):
fromPos = np.zeros((3))
toPos = np.ones((3, 1))
roomSize = np.array([3, 3, 3])
room = pra.ShoeBox(roomSize, fs=1000, absorption=0.95, max_order=order)
room.add_source(fromPos)
mics = pra.MicrophoneArray(toPos, room.fs)
... |
def test_issue_162_max_order_31():
compute_rir(31)
def test_issue_162_max_order_32():
compute_rir(32)
def test_issue_162_max_order_50():
compute_rir(50)
def test_issue_162_max_order_75():
compute_rir(75)
| compute_rir(15) | identifier_body |
test_issue_162.py | import numpy as np
import pyroomacoustics as pra
def compute_rir(order):
fromPos = np.zeros((3))
toPos = np.ones((3, 1))
roomSize = np.array([3, 3, 3])
room = pra.ShoeBox(roomSize, fs=1000, absorption=0.95, max_order=order)
room.add_source(fromPos)
mics = pra.MicrophoneArray(toPos, room.fs)
... | ():
compute_rir(75)
| test_issue_162_max_order_75 | identifier_name |
test_arm_vm.py | '''
New Integration Test for creating KVM VM.
@author: Youyk
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import os
# import arm.test_stub as test_stub
test_stub = test_lib.lib_get_test_stub()
test_obj_dict = test_st... | global test_obj_dict
test_lib.lib_error_cleanup(test_obj_dict) | def error_cleanup(): | random_line_split |
test_arm_vm.py | '''
New Integration Test for creating KVM VM.
@author: Youyk
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import os
# import arm.test_stub as test_stub
test_stub = test_lib.lib_get_test_stub()
test_obj_dict = test_st... | ():
global test_obj_dict
test_lib.lib_error_cleanup(test_obj_dict)
| error_cleanup | identifier_name |
test_arm_vm.py | '''
New Integration Test for creating KVM VM.
@author: Youyk
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import os
# import arm.test_stub as test_stub
test_stub = test_lib.lib_get_test_stub()
test_obj_dict = test_st... | global test_obj_dict
test_lib.lib_error_cleanup(test_obj_dict) | identifier_body | |
gulpfile.js | 'use strict';
var gulp = require('gulp');
var bower = require('gulp-bower');
var modify = require('gulp-modify');
var cheerio = require('cheerio');
var concat = require('gulp-concat');
gulp.task('download', function() {
// Download vaadin icon files using bower
return bower({}, [['vaadin/vaadin-icons-files']]);
}... | return gulp.src(['bower_components/vaadin-icons-files/svg/*.svg'], {base: '.'})
.pipe(modify({
fileModifier: function(file, contents) {
var id = file.path.replace(/.*\/(.*).svg/,'$1');
var svg = cheerio.load(contents, { xmlMode: true })('svg');
// Remove fill attributes.
svg.... |
gulp.task('default', ['download'], function() { | random_line_split |
BarPlot.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
BarPlot.py
---------------------
Date : January 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot com
******************************... | (self, progress):
layer = dataobjects.getObjectFromUri(
self.getParameterValue(self.INPUT))
namefieldname = self.getParameterValue(self.NAME_FIELD)
valuefieldname = self.getParameterValue(self.VALUE_FIELD)
output = self.getOutputValue(self.OUTPUT)
values = vector.va... | processAlgorithm | identifier_name |
BarPlot.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
BarPlot.py
---------------------
Date : January 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot com
******************************... | layer = dataobjects.getObjectFromUri(
self.getParameterValue(self.INPUT))
namefieldname = self.getParameterValue(self.NAME_FIELD)
valuefieldname = self.getParameterValue(self.VALUE_FIELD)
output = self.getOutputValue(self.OUTPUT)
values = vector.values(layer, namefieldname,... | identifier_body | |
BarPlot.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
BarPlot.py
---------------------
Date : January 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot com
******************************... | self.name, self.i18n_name = self.trAlgorithm('Bar plot')
self.group, self.i18n_group = self.trAlgorithm('Graphics')
self.addParameter(ParameterTable(self.INPUT, self.tr('Input table')))
self.addParameter(ParameterTableField(self.NAME_FIELD,
... | VALUE_FIELD = 'VALUE_FIELD'
def defineCharacteristics(self): | random_line_split |
fft.py | #!/usr/bin/env python
# 8 band Audio equaliser from wav file
# import alsaaudio as aa
# import smbus
from struct import unpack
import numpy as np
import wave
from time import sleep
import sys
ADDR = 0x20 #The I2C address of MCP23017
DIRA = 0x00 #PortA I/O direction, by pin. 0=output, 1=input
DIR... | (data, chunk, sample_rate):
#print ("[calculate_levels] chunk=%s, sample_rate: %s, len(data)=%s" % (chunk, sample_rate, len(data)));
if(len(data) != chunk):
print ("\n[calculate_levels] skiping: chunk=%s != len(data)=%s" % (chunk, len(data)));
return None;
global matrix
# Convert raw data (ASCI... | calculate_levels | identifier_name |
fft.py | #!/usr/bin/env python
# 8 band Audio equaliser from wav file
# import alsaaudio as aa
# import smbus
from struct import unpack
import numpy as np
import wave
from time import sleep
import sys
ADDR = 0x20 #The I2C address of MCP23017
DIRA = 0x00 #PortA I/O direction, by pin. 0=output, 1=input
DIR... | # output.setchannels(no_channels)
# output.setrate(sample_rate)
# output.setformat(aa.PCM_FORMAT_S16_LE)
# output.setperiodsize(chunk)
# Return power array index corresponding to a particular frequency
def piff(val):
return int(2*chunk*val/sample_rate)
def print_intensity(matrix):
levelFull = "||||||||";
lev... |
sample_rate = wavfile.getframerate()
no_channels = wavfile.getnchannels()
chunk = 4096 # Use a multiple of 8
# output = aa.PCM(aa.PCM_PLAYBACK, aa.PCM_NORMAL) | random_line_split |
fft.py | #!/usr/bin/env python
# 8 band Audio equaliser from wav file
# import alsaaudio as aa
# import smbus
from struct import unpack
import numpy as np
import wave
from time import sleep
import sys
ADDR = 0x20 #The I2C address of MCP23017
DIRA = 0x00 #PortA I/O direction, by pin. 0=output, 1=input
DIR... |
print_intensity(matrix);
# for i in range (0,8):
# Set_Column((1<<matrix[i])-1,0xFF^(1<<i))
sleep(0.1);
data = wavfile.readframes(chunk)
# TurnOffLEDS()
# =========================
| next; | conditional_block |
fft.py | #!/usr/bin/env python
# 8 band Audio equaliser from wav file
# import alsaaudio as aa
# import smbus
from struct import unpack
import numpy as np
import wave
from time import sleep
import sys
ADDR = 0x20 #The I2C address of MCP23017
DIRA = 0x00 #PortA I/O direction, by pin. 0=output, 1=input
DIR... |
def calculate_levels(data, chunk, sample_rate):
#print ("[calculate_levels] chunk=%s, sample_rate: %s, len(data)=%s" % (chunk, sample_rate, len(data)));
if(len(data) != chunk):
print ("\n[calculate_levels] skiping: chunk=%s != len(data)=%s" % (chunk, len(data)));
return None;
global matrix
# ... | levelFull = "||||||||";
levelEmpty = " ";
levelStr = "";
for level in matrix:
#level = 0;
levelStr += levelFull[0: level] + levelEmpty [0:8-(level)] + " ";
sys.stdout.write("\rlevel: " + levelStr);
sys.stdout.flush(); | identifier_body |
systray.py | import PyQt4.QtGui as QG
import PyQt4.QtCore as QC
def chunk(seq, size):
for i in xrange(0, len(seq), size):
yield seq[i:i+size]
class TextSysTray(object):
def __init__(self, parent, text, ntray=2, **kwargs):
self.stray = [QG.QSystemTrayIcon(parent) for _ in xrange(ntray)]
self._curr_... |
if __name__ == "__main__":
app = QG.QApplication([])
win = QG.QDialog()
trayicon = TextSysTray(win, '888.8', chunk_size=3)
trayicon.show()
win.show()
app.exec_()
| pix = QG.QPixmap(24, 16)
pix.fill(QC.Qt.transparent)
self.pix.append(pix)
painter = QG.QPainter()
painter.begin(pix)
painter.setPen(color)
try:
t = next(tc)
except StopIteration:
t = ''
paint... | conditional_block |
systray.py | import PyQt4.QtGui as QG
import PyQt4.QtCore as QC
def chunk(seq, size):
for i in xrange(0, len(seq), size):
yield seq[i:i+size]
class TextSysTray(object):
def __init__(self, parent, text, ntray=2, **kwargs):
self.stray = [QG.QSystemTrayIcon(parent) for _ in xrange(ntray)]
self._curr_... | painter.end()
stray.setIcon(QG.QIcon(pix))
if __name__ == "__main__":
app = QG.QApplication([])
win = QG.QDialog()
trayicon = TextSysTray(win, '888.8', chunk_size=3)
trayicon.show()
win.show()
app.exec_() | except StopIteration:
t = ''
painter.drawText(pix.rect(), QC.Qt.AlignRight, t) | random_line_split |
systray.py | import PyQt4.QtGui as QG
import PyQt4.QtCore as QC
def | (seq, size):
for i in xrange(0, len(seq), size):
yield seq[i:i+size]
class TextSysTray(object):
def __init__(self, parent, text, ntray=2, **kwargs):
self.stray = [QG.QSystemTrayIcon(parent) for _ in xrange(ntray)]
self._curr_text = None
self.update_text(text, **kwargs)
def... | chunk | identifier_name |
systray.py | import PyQt4.QtGui as QG
import PyQt4.QtCore as QC
def chunk(seq, size):
for i in xrange(0, len(seq), size):
yield seq[i:i+size]
class TextSysTray(object):
def __init__(self, parent, text, ntray=2, **kwargs):
|
def show(self):
for stray in self.stray:
stray.show()
def update_text(self, text, color=QC.Qt.black, chunk_size=1):
if text == self._curr_text:
return
self._curr_text = text
self.pix = []
tc = chunk(text, chunk_size)
for stray in self.s... | self.stray = [QG.QSystemTrayIcon(parent) for _ in xrange(ntray)]
self._curr_text = None
self.update_text(text, **kwargs) | identifier_body |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... | () {
let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap();
let mut acceptor = net::tcp::TcpListener::bind(addr).listen();
println(format!("Listening on [{:s}] ...", addr.to_str()));
for stream in acceptor.incoming() {
// Spawn a task to handle the connection
unsa... | main | identifier_name |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... | ,
None => ()
}
},
None => ()
}
let mut buf = [0, ..500];
stream.read(buf);
let request_str = str::from_utf8(buf);
println(format!("Received request :\n{:s}"... | {println(format!("Received connection from: [{:s}]", pn.to_str()));} | conditional_block |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... |
}
| {
let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)).unwrap();
let mut acceptor = net::tcp::TcpListener::bind(addr).listen();
println(format!("Listening on [{:s}] ...", addr.to_str()));
for stream in acceptor.incoming() {
// Spawn a task to handle the connection
unsafe ... | identifier_body |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
// | // Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::io::*;
use std::io::net::ip::{SocketAddr};
use std::{str};
static IP: &'static str = "127.0.0.1";
static PORT: int = 4414;
static mut visitor_count: int = 0;
fn main() {
let addr = from_str::<SocketAddr>(format!("{:s}:{:d}", IP, PORT)... | // University of Virginia - cs4414 Spring 2014 | random_line_split |
bin.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
// | // 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of ... | // This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version | random_line_split |
vimeo.py | import logging
import re
from streamlink.compat import html_unescape, urlparse
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import validate
from streamlink.stream import DASHStream, HLSStream, HTTPStream
from streamlink.stream.ffmpegmux import MuxedStream
from stream... | (cls, url):
return cls._url_re.match(url)
def _get_streams(self):
if "player.vimeo.com" in self.url:
data = self.session.http.get(self.url, schema=self._player_schema)
else:
api_url = self.session.http.get(self.url, schema=self._config_url_schema)
if not ... | can_handle_url | identifier_name |
vimeo.py | import logging
import re
from streamlink.compat import html_unescape, urlparse
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import validate
from streamlink.stream import DASHStream, HLSStream, HTTPStream
from streamlink.stream.ffmpegmux import MuxedStream
from stream... |
for _, video_data in videos[stream_type]["cdns"].items():
log.trace("{0!r}".format(video_data))
url = video_data.get("url")
if stream_type == "hls":
for stream in HLSStream.parse_variant_playlist(self.session, url).items():
... | continue | conditional_block |
vimeo.py | import logging
import re
from streamlink.compat import html_unescape, urlparse
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import validate
from streamlink.stream import DASHStream, HLSStream, HTTPStream
from streamlink.stream.ffmpegmux import MuxedStream
from stream... |
__plugin__ = Vimeo
| _url_re = re.compile(r"https?://(player\.vimeo\.com/video/\d+|(www\.)?vimeo\.com/.+)")
_config_url_re = re.compile(r'(?:"config_url"|\bdata-config-url)\s*[:=]\s*(".+?")')
_config_re = re.compile(r"var\s+config\s*=\s*({.+?})\s*;")
_config_url_schema = validate.Schema(
validate.transform(_config_url_r... | identifier_body |
vimeo.py | import logging
import re
from streamlink.compat import html_unescape, urlparse
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import validate
from streamlink.stream import DASHStream, HLSStream, HTTPStream
from streamlink.stream.ffmpegmux import MuxedStream
from stream... | validate.optional("progressive"): validate.all(
[{"url": validate.url(), "quality": validate.text}]
),
},
validate.optional("text_tracks"): validate.all(
[{"url": validate.text, "lang": validate.text}]
... | "files": {
validate.optional("dash"): {"cdns": {validate.text: {"url": validate.url()}}},
validate.optional("hls"): {"cdns": {validate.text: {"url": validate.url()}}}, | random_line_split |
unified.rs | extern crate arrayfire as af;
use af::*;
#[allow(unused_must_use)]
fn test_backend(){
info();
let num_rows: u64 = 10;
let num_cols: u64 = 10;
let dims = Dim4::new(&[num_rows, num_cols, 1, 1]);
println!("Create a 10-by-10 matrix of random floats on the compute device");
let a = match randu(dims, Aftype::... | () {
println!("There are {:?} available backends", get_backend_count().unwrap());
let available = get_available_backends().unwrap();
if available.contains(&Backend::AF_BACKEND_CPU){
println!("Evaluating CPU Backend...");
let err = set_backend(Backend::AF_BACKEND_CPU);
println!("There are {} CPU compu... | main | identifier_name |
unified.rs | extern crate arrayfire as af;
use af::*;
#[allow(unused_must_use)]
fn test_backend(){
info();
let num_rows: u64 = 10;
let num_cols: u64 = 10;
let dims = Dim4::new(&[num_rows, num_cols, 1, 1]);
println!("Create a 10-by-10 matrix of random floats on the compute device");
let a = match randu(dims, Aftype::... |
if available.contains(&Backend::AF_BACKEND_CUDA){
println!("Evaluating CUDA Backend...");
let err = set_backend(Backend::AF_BACKEND_CUDA);
println!("There are {} CUDA compute devices", device_count().unwrap());
match err {
Ok(_) => test_backend(),
Err(e) => println!("CUDA backend ... | {
println!("Evaluating CPU Backend...");
let err = set_backend(Backend::AF_BACKEND_CPU);
println!("There are {} CPU compute devices", device_count().unwrap());
match err {
Ok(_) => test_backend(),
Err(e) => println!("CPU backend error: {}", e),
};
} | conditional_block |
unified.rs | extern crate arrayfire as af;
use af::*;
#[allow(unused_must_use)]
fn test_backend() |
#[allow(unused_must_use)]
fn main() {
println!("There are {:?} available backends", get_backend_count().unwrap());
let available = get_available_backends().unwrap();
if available.contains(&Backend::AF_BACKEND_CPU){
println!("Evaluating CPU Backend...");
let err = set_backend(Backend::AF_BACKEND_CPU);
... | {
info();
let num_rows: u64 = 10;
let num_cols: u64 = 10;
let dims = Dim4::new(&[num_rows, num_cols, 1, 1]);
println!("Create a 10-by-10 matrix of random floats on the compute device");
let a = match randu(dims, Aftype::F32) {
Ok(value) => value,
Err(error) => panic!("{}", error),
};
print(&a)... | identifier_body |
unified.rs | extern crate arrayfire as af;
use af::*;
#[allow(unused_must_use)]
fn test_backend(){
info();
let num_rows: u64 = 10;
let num_cols: u64 = 10;
let dims = Dim4::new(&[num_rows, num_cols, 1, 1]);
println!("Create a 10-by-10 matrix of random floats on the compute device");
let a = match randu(dims, Aftype::... | };
}
} | println!("There are {} OpenCL compute devices", device_count().unwrap());
match err {
Ok(_) => test_backend(),
Err(e) => println!("OpenCL backend error: {}", e), | random_line_split |
XAxis.tsx | import { extent } from 'd3-array';
import { ScaleBand } from 'd3-scale';
import React, { FC } from 'react';
import { buildTicks } from '../utils/axis';
import { isOfType } from '../utils/isOfType';
import textWrap from '../utils/svgTextWrap';
import { defaultPadding } from './Bars/Bars';
import {
buildScale,
defau... | strokeOpacity={strokeOpacity}
strokeWidth={strokeWidth}
></path>
{
ticks.map((v, i) => {
const tickOffset = positionTick(v, Scale, i, inverse, width);
const label = scale === 'band' ? String(values[i]) : String(v);
const thisFormat = typeof tickFormat =... | d={pathD}
fill={fill}
opacity={opacity}
shapeRendering="auto" | random_line_split |
XAxis.tsx | import { extent } from 'd3-array';
import { ScaleBand } from 'd3-scale';
import React, { FC } from 'react';
import { buildTicks } from '../utils/axis';
import { isOfType } from '../utils/isOfType';
import textWrap from '../utils/svgTextWrap';
import { defaultPadding } from './Bars/Bars';
import {
buildScale,
defau... |
return `(${v}, 0)`
}
const XAxis: FC<IAxis> = ({
labelFormat,
values = [],
tickSize = 2,
width,
height,
path,
top = 0,
left = 0,
scale = 'band',
domain,
padding = defaultPadding,
tickFormat = defaultTickFormat,
labelOrientation = ELabelOrientation.HORIZONTAL,
inverse = false,
}) => {
i... | {
v = width - v;
} | conditional_block |
app2.js | /**
(function(){
window.saveUser();
saveBlog();
var util_v1 = new window.util_v1();
util_v1.ajax();
test1();
test2();
test3(); //当$(function(){window.test3=fn});时,报错!
test4();
})();
**/
/**
(function(w){
w.saveUser();
saveBlog();
var util_v1 = new w.util_v1();
util_v1.ajax();
test1();
test2();
t... | // ok
$(function(){
test();
});
// fail
$(function(w){
w.test();
}(window));
// fail
(function(){
test();
})();
*/ | $(function(){
window.test = function(){
alert('test');
};
}); | random_line_split |
sort-down.js | const createSortDownIcon = (button) => {
button.firstChild.remove();
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('height', '12');
svg.setAttribute('viewBox', '0 0 503 700');
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); | button.appendChild(svg);
};
export default createSortDownIcon; | path.setAttribute('d', `M43.302,409.357h418.36c37.617,0,56.426,45.527,29.883,72.07l-209.18,209.18c-16.523,16.523-43.243,16.523-59.59,0
L13.419,481.428C-13.124,454.885,5.685,409.357,43.302,409.357z`);
svg.appendChild(path);
| random_line_split |
formatscript.py | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 09 10:36:56 2017
@author: Nzix
"""
import urllib,urllib2,re,datetime,time,random,xlrd,xlwt,os
cookie = ""
def ticketcheck(membercode,serial_code_1,serial_code_2):
timeout = 3
global cookie
if type(membercode) is int:
membercode = str(memberco... |
votepage = response.read().decode('shift-jis').encode('utf-8')
data = {}
data["serial_code_1"] = serial_code_1
data["serial_code_2"] = serial_code_2
form = re.findall(r'<input type="hidden" name="([^"]+)" value="([^"]*)"',votepage)
for item in form:
... | cookie = response.headers["set-cookie"] | conditional_block |
formatscript.py | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 09 10:36:56 2017
@author: Nzix
"""
import urllib,urllib2,re,datetime,time,random,xlrd,xlwt,os
cookie = ""
def | (membercode,serial_code_1,serial_code_2):
timeout = 3
global cookie
if type(membercode) is int:
membercode = str(membercode)
teamcode = membercode[0] + "0" + membercode[1]
link = "http://akb48-sousenkyo.jp/vote.php?membercode=%s&parent=team&parentkey=%s"%(membercode,teamcode)
atte... | ticketcheck | identifier_name |
formatscript.py | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 09 10:36:56 2017
@author: Nzix
"""
import urllib,urllib2,re,datetime,time,random,xlrd,xlwt,os
cookie = ""
def ticketcheck(membercode,serial_code_1,serial_code_2):
timeout = 3
global cookie
if type(membercode) is int:
membercode = str(memberco... | workbook.save('./output/' + namepart + "-checked.xls")
print "Done" | random_line_split | |
formatscript.py | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 09 10:36:56 2017
@author: Nzix
"""
import urllib,urllib2,re,datetime,time,random,xlrd,xlwt,os
cookie = ""
def ticketcheck(membercode,serial_code_1,serial_code_2):
| i in xrange(0,rows*columns):
if type(sheet1.cell_value(i//columns,i%columns)) is unicode:
noblankcell = re.sub(u'[\s|(\u3000)|(\xa0)]*',"",sheet1.cell_value(i//columns,i%columns))
if re.search(r'^\w{8}$',noblankcell) != None:
offsetx = i//columns
offsety ... | timeout = 3
global cookie
if type(membercode) is int:
membercode = str(membercode)
teamcode = membercode[0] + "0" + membercode[1]
link = "http://akb48-sousenkyo.jp/vote.php?membercode=%s&parent=team&parentkey=%s"%(membercode,teamcode)
attempt = 0
result = ""
proxy = 0
while Tr... | identifier_body |
presentation.js | (function(){
var slides = [
{title: 'Работы для отдела Клиентского сервиса и сапорта ФС\nТикетная админка, админка массовых сбоев',
works: [
{img: 'i/works/ticket-admin.png', description:
'<div class="presentation_mb10"><strong>Тикетная админка</strong></div>' +
'<div class="presentation_mb10">Чер... | });
var FullscreenSlideView = BlockView.extend({
className: 'presentation_fullscreen-slide',
template:
'<div class="presentation_fullscreen-slide_back"></div>' +
'<div class="presentation_fullscreen-slide_close" data-bind="close"></div>' +
'<div class="presentation_fullscreen-slide_wrap">' +
'<div class... | random_line_split | |
presentation.js | (function(){
var slides = [
{title: 'Работы для отдела Клиентского сервиса и сапорта ФС\nТикетная админка, админка массовых сбоев',
works: [
{img: 'i/works/ticket-admin.png', description:
'<div class="presentation_mb10"><strong>Тикетная админка</strong></div>' +
'<div class="presentation_mb10">Чер... | lass="presentation_liter1"><a href="http://matraska231.herokuapp.com/?portfolio=1#cv" target="_blank">Резюме</a></div>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="presentation-wrap_body" data-bind="body">' +
'<div class="presentation-wrap_slide clearfix" data-bind="slides">' +
'</div>... | malcev@bk.ru</div>' +
'<div c | conditional_block |
tests_selenium.py | from __future__ import print_function
from django.test import LiveServerTestCase
from selenium import webdriver
import os
|
SCREEN_DUMP_LOCATION = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'screendumps'
)
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
django_get_or_create = ('username',)
username = 'Bob'
password = factory.PostGenerationMethodCall('set_pass... | from django.contrib.auth.models import User
import factory
| random_line_split |
tests_selenium.py | from __future__ import print_function
from django.test import LiveServerTestCase
from selenium import webdriver
import os
from django.contrib.auth.models import User
import factory
SCREEN_DUMP_LOCATION = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'screendumps'
)
class UserFactory(factory.djang... | (self):
self.driver.quit()
super(TestLogin, self).tearDown()
def test_unauthorized_index(self):
self.driver.get(self.live_server_url)
self.assertIn('Login', self.driver.page_source)
self.assertIn('Register', self.driver.page_source)
def test_authorized_index(self):
... | tearDown | identifier_name |
tests_selenium.py | from __future__ import print_function
from django.test import LiveServerTestCase
from selenium import webdriver
import os
from django.contrib.auth.models import User
import factory
SCREEN_DUMP_LOCATION = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'screendumps'
)
class UserFactory(factory.djang... |
class TestLogin(LiveServerTestCase):
def setUp(self):
self.driver = webdriver.Firefox()
super(TestLogin, self).setUp()
self.bob = UserFactory.create()
def tearDown(self):
self.driver.quit()
super(TestLogin, self).tearDown()
def test_unauthorized_index(self):
... | class Meta:
model = User
django_get_or_create = ('username',)
username = 'Bob'
password = factory.PostGenerationMethodCall('set_password', 'password') | identifier_body |
mod.rs | /* io::mod.rs */
use core::mem::volatile_store;
use kernel::sgash;
mod font;
/* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */
pub static UART0: *mut u32 = 0x101f1000 as *mut u32;
pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32;
#[allow(dead_code)]
pub stati... | (addr: u32, value: u32)
{
*(addr as *mut u32) = value;
}
pub unsafe fn set_fg(color: u32)
{
FG_COLOR = color;
}
pub unsafe fn set_bg(color: u32)
{
BG_COLOR = color;
}
pub unsafe fn set_cursor_color(color: u32)
{
CURSOR_COLOR = color;
}
| wh | identifier_name |
mod.rs | /* io::mod.rs */
use core::mem::volatile_store;
use kernel::sgash;
mod font;
/* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */
pub static UART0: *mut u32 = 0x101f1000 as *mut u32;
pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32;
#[allow(dead_code)]
pub stati... | while i < SCREEN_WIDTH*SCREEN_HEIGHT
{
*((START_ADDR as u32 + i*4) as *mut u32) = color;
i+=1;
}
}
pub unsafe fn fill_bg()
{
paint(BG_COLOR);
}
#[allow(dead_code)]
pub unsafe fn read(addr: u32) -> u32
{
*(addr as *mut u32)
}
pub unsafe fn ws(addr: u32, value: u32)
{
*(addr as *mut u32) = *(addr as *mut u32... | pub unsafe fn paint(color: u32)
{
let mut i = 0; | random_line_split |
mod.rs | /* io::mod.rs */
use core::mem::volatile_store;
use kernel::sgash;
mod font;
/* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */
pub static UART0: *mut u32 = 0x101f1000 as *mut u32;
pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32;
#[allow(dead_code)]
pub stati... |
let font_offset = (c as u8) - 0x20;
let map = font::bitmaps[font_offset];
let mut i = -1;
let mut j = 0;
let mut addr = START_ADDR + 4*(CURSOR_X + /*CURSOR_WIDTH +*/ 1 + SCREEN_WIDTH*CURSOR_Y + CURSOR_HEIGHT*SCREEN_WIDTH);
while j < CURSOR_HEIGHT {
while i < CURSOR_WIDTH {
//let addr = START_ADDR + 4*(CURS... | {
scrollup();
} | conditional_block |
mod.rs | /* io::mod.rs */
use core::mem::volatile_store;
use kernel::sgash;
mod font;
/* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/BBABEGGE.html */
pub static UART0: *mut u32 = 0x101f1000 as *mut u32;
pub static UART0_IMSC: *mut u32 = (0x101f1000 + 0x038) as *mut u32;
#[allow(dead_code)]
pub stati... |
pub unsafe fn write_char(c: char, address: *mut u32) {
volatile_store(address, c as u32);
}
pub unsafe fn scrollup()
{
let mut i = CURSOR_HEIGHT*SCREEN_WIDTH;
while i < (SCREEN_WIDTH*SCREEN_HEIGHT) {
*((START_ADDR + ((i-16*SCREEN_WIDTH)*4)) as *mut u32) = *((START_ADDR+(i*4)) as *u32);
i += 1;
}
i = 4*(SCR... | {
SCREEN_WIDTH = width;
SCREEN_HEIGHT= height;
sgash::init();
/* For the following magic values, see
* http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACHEDGD.html
*/
// 800x600
// See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html
if (SCREEN_WIDT... | identifier_body |
test_engine.py | import os
from django.template import Context
from django.template.engine import Engine
from django.test import SimpleTestCase
from .utils import ROOT, TEMPLATE_DIR
OTHER_DIR = os.path.join(ROOT, 'other_templates')
class RenderToStringTest(SimpleTestCase):
def setUp(self):
self.engine = ... | """
Check that the order of template loader works. Refs #21460.
"""
loaders = [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]),
]... | identifier_body | |
test_engine.py | import os
from django.template import Context
from django.template.engine import Engine
from django.test import SimpleTestCase
from .utils import ROOT, TEMPLATE_DIR
OTHER_DIR = os.path.join(ROOT, 'other_templates')
class RenderToStringTest(SimpleTestCase):
def setUp(self):
self.engine = ... | (self):
"""
Check that the order of template loader works. Refs #21460.
"""
loaders = [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
... | test_cached_loader_priority | identifier_name |
test_engine.py | import os
from django.template import Context
from django.template.engine import Engine
from django.test import SimpleTestCase
from .utils import ROOT, TEMPLATE_DIR
OTHER_DIR = os.path.join(ROOT, 'other_templates')
class RenderToStringTest(SimpleTestCase):
def setUp(self):
self.engine = ... | self.assertEqual(
self.engine.render_to_string('test_context.html', {'obj': 'test'}),
'obj:test\n',
)
class LoaderTests(SimpleTestCase):
def test_origin(self):
engine = Engine(dirs=[TEMPLATE_DIR], debug=True)
template = engine.get_template('index.... | random_line_split | |
setup.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... |
return r
setup(service=["OpenERPServerService"],
options={"py2exe":{"excludes":["Tkconstants","Tkinter","tcl",
"_imagingtk","PIL._imagingtk",
"ImageTk", "PIL.ImageTk",
"FixTk"],
... | r.append(("Microsoft.VC90.CRT", glob.glob('C:\Microsoft.VC90.CRT\*.*'))) | conditional_block |
setup.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... |
setup(service=["OpenERPServerService"],
options={"py2exe":{"excludes":["Tkconstants","Tkinter","tcl",
"_imagingtk","PIL._imagingtk",
"ImageTk", "PIL.ImageTk",
"FixTk"],
"skip_a... | r = []
if os.name == 'nt':
r.append(("Microsoft.VC90.CRT", glob.glob('C:\Microsoft.VC90.CRT\*.*')))
return r | identifier_body |
setup.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... | if os.name == 'nt':
r.append(("Microsoft.VC90.CRT", glob.glob('C:\Microsoft.VC90.CRT\*.*')))
return r
setup(service=["OpenERPServerService"],
options={"py2exe":{"excludes":["Tkconstants","Tkinter","tcl",
"_imagingtk","PIL._imagingtk",
... | def datas():
r = [] | random_line_split |
setup.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... | ():
r = []
if os.name == 'nt':
r.append(("Microsoft.VC90.CRT", glob.glob('C:\Microsoft.VC90.CRT\*.*')))
return r
setup(service=["OpenERPServerService"],
options={"py2exe":{"excludes":["Tkconstants","Tkinter","tcl",
"_imagingtk","PIL._imagingtk",
... | datas | identifier_name |
rebase-choose-branch-dialog.tsx | import React from 'react'
import { Branch } from '../../../models/branch'
import { ComputedAction } from '../../../models/computed-action'
import { RebasePreview } from '../../../models/rebase'
import { ActionStatusIcon } from '../../lib/action-status-icon'
import { updateRebasePreview } from '../../lib/update-branch'
... | () {
const currentBranch = this.props.currentBranch
const { selectedBranch } = this.state
return (
selectedBranch !== null &&
currentBranch !== null &&
selectedBranch.name === currentBranch.name
)
}
private selectedBranchIsAheadOfCurrentBranch() {
return this.rebasePreview !==... | selectedBranchIsCurrentBranch | identifier_name |
rebase-choose-branch-dialog.tsx | import React from 'react'
import { Branch } from '../../../models/branch'
import { ComputedAction } from '../../../models/computed-action'
import { RebasePreview } from '../../../models/rebase'
import { ActionStatusIcon } from '../../lib/action-status-icon'
import { updateRebasePreview } from '../../lib/update-branch'
... |
if (this.rebasePreview.kind === ComputedAction.Invalid) {
return this.renderInvalidRebaseMessage()
}
return null
}
private renderLoadingRebaseMessage() {
return <>Checking for ability to rebase automatically…</>
}
private renderInvalidRebaseMessage() {
return <>Unable to start reb... | {
return this.renderCleanRebaseMessage(
currentBranch,
baseBranch,
this.rebasePreview.commits.length
)
} | identifier_body |
rebase-choose-branch-dialog.tsx | import React from 'react'
import { Branch } from '../../../models/branch'
import { ComputedAction } from '../../../models/computed-action'
import { RebasePreview } from '../../../models/rebase'
import { ActionStatusIcon } from '../../lib/action-status-icon'
import { updateRebasePreview } from '../../lib/update-branch'
... | }
const { currentBranch } = this.props
if (this.rebasePreview.kind === ComputedAction.Loading) {
return this.renderLoadingRebaseMessage()
}
if (this.rebasePreview.kind === ComputedAction.Clean) {
return this.renderCleanRebaseMessage(
currentBranch,
baseBranch,
t... | random_line_split | |
rebase-choose-branch-dialog.tsx | import React from 'react'
import { Branch } from '../../../models/branch'
import { ComputedAction } from '../../../models/computed-action'
import { RebasePreview } from '../../../models/rebase'
import { ActionStatusIcon } from '../../lib/action-status-icon'
import { updateRebasePreview } from '../../lib/update-branch'
... |
this.props.dispatcher.startRebase(
repository,
selectedBranch,
currentBranch,
this.rebasePreview.commits
)
}
protected canStart = (): boolean => {
return (
this.state.selectedBranch !== null &&
!this.selectedBranchIsCurrentBranch() &&
this.selectedBranchIsAhe... | {
return
} | conditional_block |
mailer.js | // mailer.js
var nodemailer = require('nodemailer');
var smtpTransport = nodemailer.createTransport("SMTP", {
service: "Mandrill",
debug: true,
auth: {
user: "evanroman1@gmail.com",
pass: "k-AdDVcsNJ9oj8QYATVNGQ"
}
});
exports.sendEmailConfirmation = function(emailaddress, username, firs... |
})
}
| {
console.log(error);
} | conditional_block |
mailer.js | // mailer.js
var nodemailer = require('nodemailer');
var smtpTransport = nodemailer.createTransport("SMTP", {
service: "Mandrill", | debug: true,
auth: {
user: "evanroman1@gmail.com",
pass: "k-AdDVcsNJ9oj8QYATVNGQ"
}
});
exports.sendEmailConfirmation = function(emailaddress, username, firstname, expiremoment, token){
var mailOptions = {
from: "confirm@ativinos.com", // sender address
to: emailaddress, ... | random_line_split | |
Download.py | import requests
import time
import string
import os.path
import urllib2
import sys
import getopt
from time import gmtime, strftime
#variables
class Downloader:
extension = "pdf"
signature = [0x25, 0x50, 0x44, 0x46]
searchChars = ['a', 'a']
outputDir = "downloaded_"
downloaded = []
successCou... | (self):
if len(self.downloaded) % 10 != 0 or len(self.downloaded) == self.lastStatus:
return
self.lastStatus = len(self.downloaded)
if not os.path.isdir(self.outputDir + self.extension):
print strftime("%Y-%m-%d %H:%M:%S", gmtime()) + " --- TOTAL: " + str(len(self.downloa... | currentStatusReport | identifier_name |
Download.py | import requests
import time
import string
import os.path
import urllib2
import sys
import getopt
from time import gmtime, strftime
#variables
class Downloader:
extension = "pdf"
signature = [0x25, 0x50, 0x44, 0x46]
searchChars = ['a', 'a']
outputDir = "downloaded_"
downloaded = []
successCou... |
f_s.close()
num = 0
blocked = True
print '---' + chars + '---'
while num < self.maxPerSearch:
r = 0
while True:
try:
if num == 0:
r=requests.get('http://www.google.ee/search?hl=en&q=fil... | f_s.write(chars[x]+"\n") | conditional_block |
Download.py | import requests
import time
import string
import os.path
import urllib2
import sys
import getopt
from time import gmtime, strftime
#variables
class Downloader:
extension = "pdf"
signature = [0x25, 0x50, 0x44, 0x46]
searchChars = ['a', 'a']
outputDir = "downloaded_"
downloaded = []
successCou... | raise
time.sleep(1)
return
self.successCount += 1
def signatureText(self):
result = ""
for x in range(len(self.signature)):
result += "%0.2X" % self.signature[x]
return result
def searchCharsT... | break
except:
if x==9: | random_line_split |
Download.py | import requests
import time
import string
import os.path
import urllib2
import sys
import getopt
from time import gmtime, strftime
#variables
class Downloader:
extension = "pdf"
signature = [0x25, 0x50, 0x44, 0x46]
searchChars = ['a', 'a']
outputDir = "downloaded_"
downloaded = []
successCou... |
obj = Downloader()
obj.loadArguments(sys.argv[1:])
obj.start() | if len(chars) < len(self.searchChars):
for char in string.ascii_lowercase:
self.searchReal(chars + char)
return
for x in range(len(self.searchChars)):
if ord(chars[x])<ord(self.searchChars[x]):
return
for x i... | identifier_body |
gen_firewall.py | template = """# Generated on {{dt}}
*filter
:INPUT DROP
:FORWARD ACCEPT
:OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
{{#rule}}... | return res | f.write(res)
f.close()
| random_line_split |
gen_firewall.py | template = """# Generated on {{dt}}
*filter
:INPUT DROP
:FORWARD ACCEPT
:OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
{{#rule}}... | (securityGroup, servers):
context = {'rule': {'tcprule': [], 'allrule': []},
'dt': str(datetime.datetime.now())}
rule = groupRules[securityGroup]
for subrule in rule:
if subrule[0] == 'all':
port = subrule[1]
context['rule']['allrule'].append({'dport': port,
... | gen_firewall | identifier_name |
gen_firewall.py | template = """# Generated on {{dt}}
*filter
:INPUT DROP
:FORWARD ACCEPT
:OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
{{#rule}}... | context = {'rule': {'tcprule': [], 'allrule': []},
'dt': str(datetime.datetime.now())}
rule = groupRules[securityGroup]
for subrule in rule:
if subrule[0] == 'all':
port = subrule[1]
context['rule']['allrule'].append({'dport': port,
... | identifier_body | |
gen_firewall.py | template = """# Generated on {{dt}}
*filter
:INPUT DROP
:FORWARD ACCEPT
:OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
{{#rule}}... |
res = pystache.render(template, context)
f = open('iptables.' + securityGroup + '.rules', 'wb')
f.write(res)
f.close()
return res
| port = subrule[1]
context['rule']['tcprule'].append(
{'source': server['networks']['v4'][0]['ip_address'],
'dport': port
}) | conditional_block |
rec-align-u64.rs | // run-pass
#![allow(dead_code)]
#![allow(unused_unsafe)]
// ignore-wasm32-bare seems unimportant to test
// Issue #2303
#![feature(intrinsics)]
use std::mem;
mod rusti {
extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> usize;
pub fn min_align_of<T>() -> usize;
}
}
// This is the type... | target_os = "netbsd",
target_os = "openbsd",
target_os = "solaris",
target_os = "vxworks"))]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> usize { 4 }
pub fn size() -> usize { 12 }
}
#[cfg(not(target_arch = "x86"))]
pub mod... | target_os = "linux",
target_os = "macos", | random_line_split |
rec-align-u64.rs | // run-pass
#![allow(dead_code)]
#![allow(unused_unsafe)]
// ignore-wasm32-bare seems unimportant to test
// Issue #2303
#![feature(intrinsics)]
use std::mem;
mod rusti {
extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> usize;
pub fn min_align_of<T>() -> usize;
}
}
// This is the type... | () -> usize { 16 }
}
}
#[cfg(target_os = "windows")]
mod m {
pub mod m {
pub fn align() -> usize { 8 }
pub fn size() -> usize { 16 }
}
}
pub fn main() {
unsafe {
let x = Outer {c8: 22, t: Inner {c64: 44}};
let y = format!("{:?}", x);
println!("align inner = {:... | size | identifier_name |
rec-align-u64.rs | // run-pass
#![allow(dead_code)]
#![allow(unused_unsafe)]
// ignore-wasm32-bare seems unimportant to test
// Issue #2303
#![feature(intrinsics)]
use std::mem;
mod rusti {
extern "rust-intrinsic" {
pub fn pref_align_of<T>() -> usize;
pub fn min_align_of<T>() -> usize;
}
}
// This is the type... |
pub fn size() -> usize { 16 }
}
}
#[cfg(target_os = "windows")]
mod m {
pub mod m {
pub fn align() -> usize { 8 }
pub fn size() -> usize { 16 }
}
}
pub fn main() {
unsafe {
let x = Outer {c8: 22, t: Inner {c64: 44}};
let y = format!("{:?}", x);
printl... | { 8 } | identifier_body |
board.js | var MoveError = require("./moveError");
function | () {
this.grid = Board.makeGrid();
}
Board.isValidPos = function (pos) {
return (
(0 <= pos[0]) && (pos[0] < 3) && (0 <= pos[1]) && (pos[1] < 3)
);
};
Board.makeGrid = function () {
var grid = [];
for (var i = 0; i < 3; i++) {
grid.push([]);
for (var j = 0; j < 3; j++) {
grid[i].push(nul... | Board | identifier_name |
board.js | var MoveError = require("./moveError");
function Board () {
this.grid = Board.makeGrid();
}
Board.isValidPos = function (pos) {
return (
(0 <= pos[0]) && (pos[0] < 3) && (0 <= pos[1]) && (pos[1] < 3)
);
};
Board.makeGrid = function () {
var grid = [];
for (var i = 0; i < 3; i++) {
grid.push([]);
... |
this.grid[pos[0]][pos[1]] = mark;
};
Board.prototype.print = function () {
var strs = [];
for (var rowIdx = 0; rowIdx < 3; rowIdx++) {
var marks = [];
for (var colIdx = 0; colIdx < 3; colIdx++) {
marks.push(
this.grid[rowIdx][colIdx] ? this.grid[rowIdx][colIdx] : " "
);
}
s... | {
throw new MoveError("Is not an empty position!");
} | conditional_block |
board.js | var MoveError = require("./moveError");
function Board () {
this.grid = Board.makeGrid();
}
Board.isValidPos = function (pos) {
return (
(0 <= pos[0]) && (pos[0] < 3) && (0 <= pos[1]) && (pos[1] < 3)
);
};
Board.makeGrid = function () {
var grid = [];
for (var i = 0; i < 3; i++) {
grid.push([]);
... | if (!Board.isValidPos(pos)) {
throw new MoveError("Is not valid position!");
}
return (this.grid[pos[0]][pos[1]] === null);
};
Board.prototype.isOver = function () {
if (this.winner() != null) {
return true;
}
for (var rowIdx = 0; rowIdx < 3; rowIdx++) {
for (var colIdx = 0; colIdx < 3; colId... | Board.prototype.isEmptyPos = function (pos) { | random_line_split |
board.js | var MoveError = require("./moveError");
function Board () |
Board.isValidPos = function (pos) {
return (
(0 <= pos[0]) && (pos[0] < 3) && (0 <= pos[1]) && (pos[1] < 3)
);
};
Board.makeGrid = function () {
var grid = [];
for (var i = 0; i < 3; i++) {
grid.push([]);
for (var j = 0; j < 3; j++) {
grid[i].push(null);
}
}
return grid;
};
Board... | {
this.grid = Board.makeGrid();
} | identifier_body |
gui_is_admin.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
const path = require("path");
const this_file: string = path.basename(__filename, ".js");
const debuglog = require("util").debuglog("cc-" + this_file);
import chalk from "chal... | pfcounts.result = true;
} catch (e) {
if (e instanceof puppeteer.errors.TimeoutError) {
debuglog(`not Admin: ${e.message}`);
} else {
console.log(chalk.red(`not timeout ERROR: ${e.message}`));
throw e;
}
}
await time_log2(this_file, tm_is_admin, creds, opts);... | random_line_split | |
gui_is_admin.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
const path = require("path");
const this_file: string = path.basename(__filename, ".js");
const debuglog = require("util").debuglog("cc-" + this_file);
import chalk from "chal... | try {
const tm_is_admin = process.hrtime.bigint();
// look for "Help" button, just to make sure we're in the right place
let sel = '*[cocalc-test="account"]';
await page.waitForSelector(sel);
debuglog("found Account tab");
// look for "Admin" button - return true if it's found within 2 sec
... | debuglog("skipping test: " + this_file);
pfcounts.skip += 1;
return pfcounts;
}
| conditional_block |
input.component.ts | import {
Component, OnInit, forwardRef, Input, Output, ViewChild, ElementRef, Renderer,
HostBinding, HostListener, EventEmitter, OnChanges, SimpleChange } from '@angular/core';
import {
AbstractControl, ControlValueAccessor, Validator,
NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
import {noop, id... | (event:FocusEvent) {
this.focused = false;
this.onTouchedFn();
this.blur.emit(event);
}
onFocus(event:FocusEvent) {
this.focused = true;
this.focus.emit(event);
}
onChange(event: Event) {}
@HostListener('keypress', ['$event'])
keypress(event: KeyboardEvent) {
event && this.filterK... | onBlur | identifier_name |
input.component.ts | import {
Component, OnInit, forwardRef, Input, Output, ViewChild, ElementRef, Renderer,
HostBinding, HostListener, EventEmitter, OnChanges, SimpleChange } from '@angular/core';
import {
AbstractControl, ControlValueAccessor, Validator,
NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
import {noop, id... |
onValidatorChangeFn: Function = noop;
registerOnValidatorChange(fn: () => void) : void {
this.onValidatorChangeFn = fn;
}
//ControlValueAccessor
onChangedFn: Function = noop;
onTouchedFn: Function = noop;
writeValue(value: any) : void {
this.value = value;
}
registerOnChange(fn: (_: any) ... | {
return this.validateFn(ctrl);
} | identifier_body |
input.component.ts | import {
Component, OnInit, forwardRef, Input, Output, ViewChild, ElementRef, Renderer,
HostBinding, HostListener, EventEmitter, OnChanges, SimpleChange } from '@angular/core';
import {
AbstractControl, ControlValueAccessor, Validator,
NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
import {noop, id... | }
setDisabledState(isDisabled: boolean) : void {
this.disabled = isDisabled;
}
} | }
registerOnTouched(fn: () => void) : void {
this.onTouchedFn = fn; | random_line_split |
input.component.ts | import {
Component, OnInit, forwardRef, Input, Output, ViewChild, ElementRef, Renderer,
HostBinding, HostListener, EventEmitter, OnChanges, SimpleChange } from '@angular/core';
import {
AbstractControl, ControlValueAccessor, Validator,
NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
import {noop, id... |
}
@Output() errorsChange = new EventEmitter<string[]>(true);
@Output() valueChange = new EventEmitter<number | string>();
@Output() blur = new EventEmitter<FocusEvent>();
@Output() focus = new EventEmitter<FocusEvent>();
constructor(protected _renderer: Renderer) { }
onBlur(event:FocusEvent) {
this... | {
this._errors = errors || [];
this.errorsChange.emit(this.errors);
} | conditional_block |
app.js | // Copyright 2017, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wr... |
const app = express();
// Static files
app.use(express.static('frontend/public/'));
app.disable('etag');
app.set('views', path.join(__dirname, 'web-app/views'));
app.set('view engine', 'pug');
app.set('trust proxy', true);
app.set('json spaces', 2);
// Questions
app.use('/questions', require('./web-app/questions'))... | }); | random_line_split |
app.js | // Copyright 2017, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wr... |
module.exports = app;
| {
// Start the server
const server = app.listen(config.get('PORT'), () => {
const port = server.address().port;
console.log(`App listening on port ${port}`);
});
} | conditional_block |
promise-queue.ts | export class PromiseQueue {
private queue: Promise<any> = Promise.resolve();
private _length: number = 0;
get | (): number { return this._length; }
constructor(readonly name: string = 'Queue') { }
add<T>(task: () => T): Promise<T>
add<T>(promise: PromiseLike<T>): Promise<T>
add<T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>
add<T>(arg: any): Promise<T... | length | identifier_name |
promise-queue.ts | export class PromiseQueue {
private queue: Promise<any> = Promise.resolve();
private _length: number = 0;
get length(): number { return this._length; }
constructor(readonly name: string = 'Queue') { }
add<T>(task: () => T): Promise<T>
add<T>(promise: PromiseLike<T>): Promise<T>
add<T>(executor: (resolv... |
}
| {
this._length++
console.log(`${this.name} add: ${this._length}`);
if (typeof arg.then == 'function') {
this.queue = this.queue.then(() => arg); // promise
} else if (0 < arg.length) {
this.queue = this.queue.then(() => new Promise<T>(arg)); // executor
} else {
this.queue = this.q... | identifier_body |
promise-queue.ts | export class PromiseQueue {
private queue: Promise<any> = Promise.resolve();
private _length: number = 0;
get length(): number { return this._length; }
constructor(readonly name: string = 'Queue') { }
add<T>(task: () => T): Promise<T>
add<T>(promise: PromiseLike<T>): Promise<T>
add<T>(executor: (resolv... | else {
this.queue = this.queue.then(arg); // task
}
let ret = this.queue;
this.queue = this.queue.catch((reason) => {
console.error(reason);
});
this.queue = this.queue.then(() => {
this._length--;
console.log(`${this.name} done: ${this._length}`);
});
return ret;
... | {
this.queue = this.queue.then(() => new Promise<T>(arg)); // executor
} | conditional_block |
promise-queue.ts |
constructor(readonly name: string = 'Queue') { }
add<T>(task: () => T): Promise<T>
add<T>(promise: PromiseLike<T>): Promise<T>
add<T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>
add<T>(arg: any): Promise<T> {
this._length++
console.l... | export class PromiseQueue {
private queue: Promise<any> = Promise.resolve();
private _length: number = 0;
get length(): number { return this._length; } | random_line_split | |
accept_ranges.rs | use std::fmt::{self, Display};
use std::str::FromStr;
header! {
#[doc="`Accept-Ranges` header, defined in"]
#[doc="[RFC7233](http://tools.ietf.org/html/rfc7233#section-2.3)"]
#[doc=""]
#[doc="The `Accept-Ranges` header field allows a server to indicate that it"]
#[doc="supports range requests for t... | {
/// Indicating byte-range requests are supported.
Bytes,
/// Reserved as keyword, indicating no ranges are supported.
None,
/// The given range unit is not registered at IANA.
Unregistered(String),
}
impl FromStr for RangeUnit {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<S... | RangeUnit | identifier_name |
accept_ranges.rs | use std::fmt::{self, Display};
use std::str::FromStr;
header! {
#[doc="`Accept-Ranges` header, defined in"]
#[doc="[RFC7233](http://tools.ietf.org/html/rfc7233#section-2.3)"]
#[doc=""]
#[doc="The `Accept-Ranges` header field allows a server to indicate that it"]
#[doc="supports range requests for t... |
}
impl Display for RangeUnit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RangeUnit::Bytes => f.write_str("bytes"),
RangeUnit::None => f.write_str("none"),
RangeUnit::Unregistered(ref x) => f.write_str(&x),
}
}
}
| {
match s {
"bytes" => Ok(RangeUnit::Bytes),
"none" => Ok(RangeUnit::None),
// FIXME: Check if s is really a Token
_ => Ok(RangeUnit::Unregistered(s.to_owned())),
}
} | identifier_body |
accept_ranges.rs | use std::fmt::{self, Display};
use std::str::FromStr;
header! {
#[doc="`Accept-Ranges` header, defined in"]
#[doc="[RFC7233](http://tools.ietf.org/html/rfc7233#section-2.3)"]
#[doc=""]
#[doc="The `Accept-Ranges` header field allows a server to indicate that it"]
#[doc="supports range requests for t... | #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set(AcceptRanges(vec![RangeUnit::None]));"]
#[doc="```"]
#[doc="```"]
#[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"]
#[doc=""]
#[doc="l... | #[doc="```"] | random_line_split |
task.py | # Copyright (C) 2007-2010 Richard Lincoln
#
# PYPOWER is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# PYPOWER is distributed in the... | (self, environment, maxSteps=24, discount=None):
super(ProfitTask, self).__init__(environment, maxSteps, discount)
#----------------------------------------------------------------------
# "Task" interface:
#----------------------------------------------------------------------
... | __init__ | identifier_name |
task.py | # Copyright (C) 2007-2010 Richard Lincoln
#
# PYPOWER is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# PYPOWER is distributed in the... | from pylon import PQ, PV
logger = logging.getLogger(__name__)
class ProfitTask(DiscreteProfitTask):
""" Defines a task for continuous sensor and action spaces.
"""
def __init__(self, environment, maxSteps=24, discount=None):
super(ProfitTask, self).__init__(environment, maxSteps, discount)
... |
from pyreto.discrete.task import ProfitTask as DiscreteProfitTask
| random_line_split |
task.py | # Copyright (C) 2007-2010 Richard Lincoln
#
# PYPOWER is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# PYPOWER is distributed in the... |
for _ in range(self.env.numOffbids):
for _ in self.env.generators:
if self.env.maxWithhold is not None:
actorLimits.append((0.0, self.env.maxWithhold))
logger.debug("Actor limits: %s" % actorLimits)
return actorLimits
def _getSensorLimits... | for _ in self.env.generators:
actorLimits.append((0.0, self.env.maxMarkup)) | conditional_block |
task.py | # Copyright (C) 2007-2010 Richard Lincoln
#
# PYPOWER is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# PYPOWER is distributed in the... |
#--------------------------------------------------------------------------
# "Task" interface:
#--------------------------------------------------------------------------
# def getObservation(self):
# """ A filtered mapping to getSample of the underlying environment. """
#
# sensors = ... | super(ProfitTask, self).__init__(environment, maxSteps, discount)
#----------------------------------------------------------------------
# "Task" interface:
#----------------------------------------------------------------------
#: Limits for scaling of sensors.
self.sensor_l... | identifier_body |
edit.service.ts | // View-model for editing arguments.
import { Cursor, Argument } from 'app/flow.model'
| export class EditService {
// Editing coordinates
iArgumentGroup = -1
iSpeech = -1
iArgument = -1
text = ''
startEditing(cursor: Cursor, text) {
this.iArgumentGroup = cursor.iArgumentGroup
this.iSpeech = cursor.iSpeech
this.iArgument = cursor.iArgument
this.text = text
}
// Set argumen... | random_line_split | |
edit.service.ts | // View-model for editing arguments.
import { Cursor, Argument } from 'app/flow.model'
export class EditService {
// Editing coordinates
iArgumentGroup = -1
iSpeech = -1
iArgument = -1
text = ''
startEditing(cursor: Cursor, text) {
this.iArgumentGroup = cursor.iArgumentGroup
this.iSpeech = cursor.... | (): Argument {
return { contents: this.text }
}
} | createArgument | identifier_name |
edit.service.ts | // View-model for editing arguments.
import { Cursor, Argument } from 'app/flow.model'
export class EditService {
// Editing coordinates
iArgumentGroup = -1
iSpeech = -1
iArgument = -1
text = ''
startEditing(cursor: Cursor, text) |
// Set argument coordinates to sentinel values.
stopEditing() {
this.iArgumentGroup = -1
this.iSpeech = -1
this.iArgument = -1
}
isEditing(iArgumentGroup, iSpeech, iArgument) {
return this.iArgumentGroup == iArgumentGroup
&& this.iSpeech == iSpeech
&& this.iArgument == iArgument
... | {
this.iArgumentGroup = cursor.iArgumentGroup
this.iSpeech = cursor.iSpeech
this.iArgument = cursor.iArgument
this.text = text
} | identifier_body |
custom-typings.d.ts | /*
* Custom Type Definitions
* When including 3rd party modules you also need to include the type definition for the module
* if they don't provide one within the module. You can try to install it with @types
npm install @types/node
npm install @types/lodash
* If you can't find the type definition in the registry... | declare var _: any;
declare var $: any;
*
* If you're importing a module that uses Node.js modules which are CommonJS you need to import as
* in the files such as main.browser.ts or any file within app/
*
import * as _ from 'lodash'
* You can include your type definitions in this file until you create one for t... | random_line_split | |
test_class_2_find_the_torsional_angle.py | #!/usr/bin/env python3
# https://www.hackerrank.com/challenges/class-2-find-the-torsional-angle
import io
import math
import sys
import unittest
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def subtract(self, other):
x = self.x - other.x
... |
def main():
a = Vector(*tuple(map(float, input().strip().split())))
b = Vector(*tuple(map(float, input().strip().split())))
c = Vector(*tuple(map(float, input().strip().split())))
d = Vector(*tuple(map(float, input().strip().split())))
print('%.2f' % torsional_angle(a, b, c, d))
if __name__ == '... | return math.degrees(math.acos(cosine)) | random_line_split |
test_class_2_find_the_torsional_angle.py | #!/usr/bin/env python3
# https://www.hackerrank.com/challenges/class-2-find-the-torsional-angle
import io
import math
import sys
import unittest
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def subtract(self, other):
x = self.x - other.x
... | self.generalized_test('0') | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.