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) room.add_microphone_array(mics) room.compute_rir() def test_issue_162_max_order_15():
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) room.add_microphone_array(mics) room.compute_rir() def test_issue_162_max_order_15(): compute_rir(15) 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
(): 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_state.TestStateDict() def test(): global test_stub,test_obj_dict vm = test_stub.create_arm_vm() test_obj_dict.add_vm(vm) vm.check() vm.suspend() vm.check() vm.resume() vm.check() vm.reboot() vm.check() l3_name=os.environ.get('l3PublicNetworkName') l3_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid vm.add_nic(l3_uuid) # vm.check() cpuNum = 2 memorySize = 666 * 1024 * 1024 new_offering = test_lib.lib_create_instance_offering(cpuNum = cpuNum,\ memorySize = memorySize) test_obj_dict.add_instance_offering(new_offering) vm.stop() vm.change_instance_offering(new_offering.uuid) vm.check() vm.start() vm.stop() vm.check() vm.reinit() vm.check() #time.sleep(5) test_lib.lib_robot_cleanup(test_obj_dict) test_util.test_pass('Create VM Test Success') #Will be called only if exception happens in test().
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_state.TestStateDict() def test(): global test_stub,test_obj_dict vm = test_stub.create_arm_vm() test_obj_dict.add_vm(vm) vm.check() vm.suspend() vm.check() vm.resume() vm.check() vm.reboot() vm.check() l3_name=os.environ.get('l3PublicNetworkName') l3_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid vm.add_nic(l3_uuid) # vm.check() cpuNum = 2 memorySize = 666 * 1024 * 1024 new_offering = test_lib.lib_create_instance_offering(cpuNum = cpuNum,\ memorySize = memorySize) test_obj_dict.add_instance_offering(new_offering) vm.stop() vm.change_instance_offering(new_offering.uuid) vm.check() vm.start() vm.stop() vm.check() vm.reinit() vm.check() #time.sleep(5) test_lib.lib_robot_cleanup(test_obj_dict) test_util.test_pass('Create VM Test Success') #Will be called only if exception happens in test(). def
(): 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_state.TestStateDict() def test(): global test_stub,test_obj_dict vm = test_stub.create_arm_vm() test_obj_dict.add_vm(vm) vm.check() vm.suspend() vm.check() vm.resume() vm.check() vm.reboot() vm.check() l3_name=os.environ.get('l3PublicNetworkName') l3_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid vm.add_nic(l3_uuid) # vm.check() cpuNum = 2 memorySize = 666 * 1024 * 1024 new_offering = test_lib.lib_create_instance_offering(cpuNum = cpuNum,\ memorySize = memorySize) test_obj_dict.add_instance_offering(new_offering) vm.stop() vm.change_instance_offering(new_offering.uuid) vm.check() vm.start() vm.stop() vm.check() vm.reinit() vm.check() #time.sleep(5) test_lib.lib_robot_cleanup(test_obj_dict) test_util.test_pass('Create VM Test Success') #Will be called only if exception happens in test(). def error_cleanup():
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.children('[fill]').removeAttr('fill'); // Output the "meat" of the SVG as group element. return '<g id="' + id + '">' + svg.children() + '</g>'; } })) .pipe(concat('vaadin-icons.html')) .pipe(modify({ fileModifier: function(file, contents) { // Enclose all icons in an iron-iconset-svg return `<link rel="import" href="../iron-icon/iron-icon.html"> <link rel="import" href="../iron-iconset-svg/iron-iconset-svg.html"> <iron-iconset-svg name="vaadin-icons" size="64"> <svg><defs> ` + contents + ` </defs></svg> </iron-iconset-svg> `; } })) .pipe(gulp.dest('.')); }); // Generates an AsciiDoc table of all icons from the JSON metadata. gulp.task('docs:table', ['download'], () => { const iconData = require('./bower_components/vaadin-icons-files/vaadin-font-icons.json'); console.log('[width="100%", options="header"]'); console.log('|======================'); console.log('| Icon | Name | Ligature | Unicode | Categories | Tags'); iconData.forEach((icon) => { console.log(`| image:img/png/${icon.name}.png[] | [propertyname]#${icon.name}# | ${icon.name} | ${icon.code} | ${icon.categories.join(', ')} | ${icon.meta.join(', ')}`); }); console.log('|======================'); });
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 *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'January 2013' __copyright__ = '(C) 2013, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import matplotlib.pyplot as plt import matplotlib.pylab as lab import numpy as np from processing.core.parameters import ParameterTable from processing.core.parameters import ParameterTableField from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.outputs import OutputHTML from processing.tools import vector from processing.tools import dataobjects class BarPlot(GeoAlgorithm): INPUT = 'INPUT' OUTPUT = 'OUTPUT' NAME_FIELD = 'NAME_FIELD' VALUE_FIELD = 'VALUE_FIELD' def defineCharacteristics(self): 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, self.tr('Category name field'), self.INPUT, ParameterTableField.DATA_TYPE_NUMBER)) self.addParameter(ParameterTableField(self.VALUE_FIELD, self.tr('Value field'), self.INPUT, ParameterTableField.DATA_TYPE_NUMBER)) self.addOutput(OutputHTML(self.OUTPUT, self.tr('Bar plot'))) def
(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.values(layer, namefieldname, valuefieldname) plt.close() ind = np.arange(len(values[namefieldname])) width = 0.8 plt.bar(ind, values[valuefieldname], width, color='r') plt.xticks(ind, values[namefieldname], rotation=45) plotFilename = output + '.png' lab.savefig(plotFilename) with open(output, 'w') as f: f.write('<html><img src="' + plotFilename + '"/></html>')
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 *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'January 2013' __copyright__ = '(C) 2013, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import matplotlib.pyplot as plt import matplotlib.pylab as lab import numpy as np from processing.core.parameters import ParameterTable from processing.core.parameters import ParameterTableField from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.outputs import OutputHTML from processing.tools import vector from processing.tools import dataobjects class BarPlot(GeoAlgorithm): INPUT = 'INPUT' OUTPUT = 'OUTPUT' NAME_FIELD = 'NAME_FIELD' VALUE_FIELD = 'VALUE_FIELD' def defineCharacteristics(self): 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, self.tr('Category name field'), self.INPUT, ParameterTableField.DATA_TYPE_NUMBER)) self.addParameter(ParameterTableField(self.VALUE_FIELD, self.tr('Value field'), self.INPUT, ParameterTableField.DATA_TYPE_NUMBER)) self.addOutput(OutputHTML(self.OUTPUT, self.tr('Bar plot'))) def processAlgorithm(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.values(layer, namefieldname, valuefieldname) plt.close() ind = np.arange(len(values[namefieldname])) width = 0.8 plt.bar(ind, values[valuefieldname], width, color='r') plt.xticks(ind, values[namefieldname], rotation=45) plotFilename = output + '.png' lab.savefig(plotFilename) with open(output, 'w') as f: f.write('<html><img src="' + plotFilename + '"/></html>')
identifier_body
BarPlot.py
# -*- coding: utf-8 -*- """ *************************************************************************** BarPlot.py --------------------- Date : January 2013 Copyright : (C) 2013 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'January 2013' __copyright__ = '(C) 2013, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import matplotlib.pyplot as plt import matplotlib.pylab as lab import numpy as np from processing.core.parameters import ParameterTable from processing.core.parameters import ParameterTableField from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.outputs import OutputHTML from processing.tools import vector from processing.tools import dataobjects class BarPlot(GeoAlgorithm): INPUT = 'INPUT' OUTPUT = 'OUTPUT' NAME_FIELD = 'NAME_FIELD'
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, self.tr('Category name field'), self.INPUT, ParameterTableField.DATA_TYPE_NUMBER)) self.addParameter(ParameterTableField(self.VALUE_FIELD, self.tr('Value field'), self.INPUT, ParameterTableField.DATA_TYPE_NUMBER)) self.addOutput(OutputHTML(self.OUTPUT, self.tr('Bar plot'))) def processAlgorithm(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.values(layer, namefieldname, valuefieldname) plt.close() ind = np.arange(len(values[namefieldname])) width = 0.8 plt.bar(ind, values[valuefieldname], width, color='r') plt.xticks(ind, values[namefieldname], rotation=45) plotFilename = output + '.png' lab.savefig(plotFilename) with open(output, 'w') as f: f.write('<html><img src="' + plotFilename + '"/></html>')
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 DIRB = 0x01 #PortB I/O direction, by pin. 0=output, 1=input BANKA = 0x12 #Register address for Bank A BANKB = 0x13 #Register address for Bank B # bus=smbus.SMBus(0) #Use '1' for newer Pi boards; # #Set up the 23017 for 16 output pins # bus.write_byte_data(ADDR, DIRA, 0); #all zeros = all outputs on Bank A # bus.write_byte_data(ADDR, DIRB, 0); #all zeros = all outputs on Bank B # def TurnOffLEDS (): # bus.write_byte_data(ADDR, BANKA, 0xFF) #set all columns high # bus.write_byte_data(ADDR, BANKB, 0x00) #set all rows low # def Set_Column(row, col): # bus.write_byte_data(ADDR, BANKA, col) # bus.write_byte_data(ADDR, BANKB, row) # # Initialise matrix # TurnOffLEDS() matrix = [0,0,0,0,0,0,0,0] power = [] # weighting = [2,2,8,8,16,32,64,64] # Change these according to taste weighting = [2,2,2,2,4,4,8,8] # Change these according to taste # Set up audio #wavfile = wave.open('test_stereo_16000Hz_16bit_PCM.wav','r') #wavfile = wave.open('Media-Convert_test5_PCM_Stereo_VBR_8SS_44100Hz.wav','r') wavfile = wave.open('Media-Convert_test2_PCM_Mono_VBR_8SS_48000Hz.wav','r') sample_rate = wavfile.getframerate() no_channels = wavfile.getnchannels() chunk = 4096 # Use a multiple of 8 # output = aa.PCM(aa.PCM_PLAYBACK, aa.PCM_NORMAL) # 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 = "||||||||"; levelEmpty = " "; levelStr = ""; for level in matrix: #level = 0; levelStr += levelFull[0: level] + levelEmpty [0:8-(level)] + " "; sys.stdout.write("\rlevel: " + levelStr); sys.stdout.flush(); def
(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 (ASCII string) to numpy array data = unpack("%dh"%(len(data)/2),data) data = np.array(data, dtype='h') # Apply FFT - real data fourier=np.fft.rfft(data) # Remove last element in array to make it the same size as chunk fourier=np.delete(fourier,len(fourier)-1) # Find average 'amplitude' for specific frequency ranges in Hz power = np.abs(fourier) matrix[0]= int(np.mean(power[piff(0) :piff(156):1])) matrix[1]= int(np.mean(power[piff(156) :piff(313):1])) matrix[2]= int(np.mean(power[piff(313) :piff(625):1])) matrix[3]= int(np.mean(power[piff(625) :piff(1250):1])) matrix[4]= int(np.mean(power[piff(1250) :piff(2500):1])) matrix[5]= int(np.mean(power[piff(2500) :piff(5000):1])) matrix[6]= int(np.mean(power[piff(5000) :piff(10000):1])) # Produces error, I guess to low sampling rate of the audio file # matrix[7]= int(np.mean(power[piff(10000):piff(20000):1])) # Tidy up column values for the LED matrix matrix=np.divide(np.multiply(matrix,weighting),1000000) # Set floor at 0 and ceiling at 8 for LED matrix matrix=matrix.clip(0,8) return matrix # Process audio file print "Processing....." data = wavfile.readframes(chunk) while data != '': # output.write(data) matrix = calculate_levels(data, chunk,sample_rate) if matrix == None: next; 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() # =========================
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 DIRB = 0x01 #PortB I/O direction, by pin. 0=output, 1=input BANKA = 0x12 #Register address for Bank A BANKB = 0x13 #Register address for Bank B # bus=smbus.SMBus(0) #Use '1' for newer Pi boards; # #Set up the 23017 for 16 output pins # bus.write_byte_data(ADDR, DIRA, 0); #all zeros = all outputs on Bank A # bus.write_byte_data(ADDR, DIRB, 0); #all zeros = all outputs on Bank B # def TurnOffLEDS (): # bus.write_byte_data(ADDR, BANKA, 0xFF) #set all columns high # bus.write_byte_data(ADDR, BANKB, 0x00) #set all rows low # def Set_Column(row, col): # bus.write_byte_data(ADDR, BANKA, col) # bus.write_byte_data(ADDR, BANKB, row) # # Initialise matrix # TurnOffLEDS() matrix = [0,0,0,0,0,0,0,0] power = [] # weighting = [2,2,8,8,16,32,64,64] # Change these according to taste weighting = [2,2,2,2,4,4,8,8] # Change these according to taste # Set up audio #wavfile = wave.open('test_stereo_16000Hz_16bit_PCM.wav','r') #wavfile = wave.open('Media-Convert_test5_PCM_Stereo_VBR_8SS_44100Hz.wav','r') wavfile = wave.open('Media-Convert_test2_PCM_Mono_VBR_8SS_48000Hz.wav','r')
# 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 = "||||||||"; levelEmpty = " "; levelStr = ""; for level in matrix: #level = 0; levelStr += levelFull[0: level] + levelEmpty [0:8-(level)] + " "; sys.stdout.write("\rlevel: " + levelStr); sys.stdout.flush(); 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 # Convert raw data (ASCII string) to numpy array data = unpack("%dh"%(len(data)/2),data) data = np.array(data, dtype='h') # Apply FFT - real data fourier=np.fft.rfft(data) # Remove last element in array to make it the same size as chunk fourier=np.delete(fourier,len(fourier)-1) # Find average 'amplitude' for specific frequency ranges in Hz power = np.abs(fourier) matrix[0]= int(np.mean(power[piff(0) :piff(156):1])) matrix[1]= int(np.mean(power[piff(156) :piff(313):1])) matrix[2]= int(np.mean(power[piff(313) :piff(625):1])) matrix[3]= int(np.mean(power[piff(625) :piff(1250):1])) matrix[4]= int(np.mean(power[piff(1250) :piff(2500):1])) matrix[5]= int(np.mean(power[piff(2500) :piff(5000):1])) matrix[6]= int(np.mean(power[piff(5000) :piff(10000):1])) # Produces error, I guess to low sampling rate of the audio file # matrix[7]= int(np.mean(power[piff(10000):piff(20000):1])) # Tidy up column values for the LED matrix matrix=np.divide(np.multiply(matrix,weighting),1000000) # Set floor at 0 and ceiling at 8 for LED matrix matrix=matrix.clip(0,8) return matrix # Process audio file print "Processing....." data = wavfile.readframes(chunk) while data != '': # output.write(data) matrix = calculate_levels(data, chunk,sample_rate) if matrix == None: next; 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() # =========================
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 DIRB = 0x01 #PortB I/O direction, by pin. 0=output, 1=input BANKA = 0x12 #Register address for Bank A BANKB = 0x13 #Register address for Bank B # bus=smbus.SMBus(0) #Use '1' for newer Pi boards; # #Set up the 23017 for 16 output pins # bus.write_byte_data(ADDR, DIRA, 0); #all zeros = all outputs on Bank A # bus.write_byte_data(ADDR, DIRB, 0); #all zeros = all outputs on Bank B # def TurnOffLEDS (): # bus.write_byte_data(ADDR, BANKA, 0xFF) #set all columns high # bus.write_byte_data(ADDR, BANKB, 0x00) #set all rows low # def Set_Column(row, col): # bus.write_byte_data(ADDR, BANKA, col) # bus.write_byte_data(ADDR, BANKB, row) # # Initialise matrix # TurnOffLEDS() matrix = [0,0,0,0,0,0,0,0] power = [] # weighting = [2,2,8,8,16,32,64,64] # Change these according to taste weighting = [2,2,2,2,4,4,8,8] # Change these according to taste # Set up audio #wavfile = wave.open('test_stereo_16000Hz_16bit_PCM.wav','r') #wavfile = wave.open('Media-Convert_test5_PCM_Stereo_VBR_8SS_44100Hz.wav','r') wavfile = wave.open('Media-Convert_test2_PCM_Mono_VBR_8SS_48000Hz.wav','r') sample_rate = wavfile.getframerate() no_channels = wavfile.getnchannels() chunk = 4096 # Use a multiple of 8 # output = aa.PCM(aa.PCM_PLAYBACK, aa.PCM_NORMAL) # 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 = "||||||||"; levelEmpty = " "; levelStr = ""; for level in matrix: #level = 0; levelStr += levelFull[0: level] + levelEmpty [0:8-(level)] + " "; sys.stdout.write("\rlevel: " + levelStr); sys.stdout.flush(); 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 # Convert raw data (ASCII string) to numpy array data = unpack("%dh"%(len(data)/2),data) data = np.array(data, dtype='h') # Apply FFT - real data fourier=np.fft.rfft(data) # Remove last element in array to make it the same size as chunk fourier=np.delete(fourier,len(fourier)-1) # Find average 'amplitude' for specific frequency ranges in Hz power = np.abs(fourier) matrix[0]= int(np.mean(power[piff(0) :piff(156):1])) matrix[1]= int(np.mean(power[piff(156) :piff(313):1])) matrix[2]= int(np.mean(power[piff(313) :piff(625):1])) matrix[3]= int(np.mean(power[piff(625) :piff(1250):1])) matrix[4]= int(np.mean(power[piff(1250) :piff(2500):1])) matrix[5]= int(np.mean(power[piff(2500) :piff(5000):1])) matrix[6]= int(np.mean(power[piff(5000) :piff(10000):1])) # Produces error, I guess to low sampling rate of the audio file # matrix[7]= int(np.mean(power[piff(10000):piff(20000):1])) # Tidy up column values for the LED matrix matrix=np.divide(np.multiply(matrix,weighting),1000000) # Set floor at 0 and ceiling at 8 for LED matrix matrix=matrix.clip(0,8) return matrix # Process audio file print "Processing....." data = wavfile.readframes(chunk) while data != '': # output.write(data) matrix = calculate_levels(data, chunk,sample_rate) if matrix == None:
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 DIRB = 0x01 #PortB I/O direction, by pin. 0=output, 1=input BANKA = 0x12 #Register address for Bank A BANKB = 0x13 #Register address for Bank B # bus=smbus.SMBus(0) #Use '1' for newer Pi boards; # #Set up the 23017 for 16 output pins # bus.write_byte_data(ADDR, DIRA, 0); #all zeros = all outputs on Bank A # bus.write_byte_data(ADDR, DIRB, 0); #all zeros = all outputs on Bank B # def TurnOffLEDS (): # bus.write_byte_data(ADDR, BANKA, 0xFF) #set all columns high # bus.write_byte_data(ADDR, BANKB, 0x00) #set all rows low # def Set_Column(row, col): # bus.write_byte_data(ADDR, BANKA, col) # bus.write_byte_data(ADDR, BANKB, row) # # Initialise matrix # TurnOffLEDS() matrix = [0,0,0,0,0,0,0,0] power = [] # weighting = [2,2,8,8,16,32,64,64] # Change these according to taste weighting = [2,2,2,2,4,4,8,8] # Change these according to taste # Set up audio #wavfile = wave.open('test_stereo_16000Hz_16bit_PCM.wav','r') #wavfile = wave.open('Media-Convert_test5_PCM_Stereo_VBR_8SS_44100Hz.wav','r') wavfile = wave.open('Media-Convert_test2_PCM_Mono_VBR_8SS_48000Hz.wav','r') sample_rate = wavfile.getframerate() no_channels = wavfile.getnchannels() chunk = 4096 # Use a multiple of 8 # output = aa.PCM(aa.PCM_PLAYBACK, aa.PCM_NORMAL) # 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):
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 # Convert raw data (ASCII string) to numpy array data = unpack("%dh"%(len(data)/2),data) data = np.array(data, dtype='h') # Apply FFT - real data fourier=np.fft.rfft(data) # Remove last element in array to make it the same size as chunk fourier=np.delete(fourier,len(fourier)-1) # Find average 'amplitude' for specific frequency ranges in Hz power = np.abs(fourier) matrix[0]= int(np.mean(power[piff(0) :piff(156):1])) matrix[1]= int(np.mean(power[piff(156) :piff(313):1])) matrix[2]= int(np.mean(power[piff(313) :piff(625):1])) matrix[3]= int(np.mean(power[piff(625) :piff(1250):1])) matrix[4]= int(np.mean(power[piff(1250) :piff(2500):1])) matrix[5]= int(np.mean(power[piff(2500) :piff(5000):1])) matrix[6]= int(np.mean(power[piff(5000) :piff(10000):1])) # Produces error, I guess to low sampling rate of the audio file # matrix[7]= int(np.mean(power[piff(10000):piff(20000):1])) # Tidy up column values for the LED matrix matrix=np.divide(np.multiply(matrix,weighting),1000000) # Set floor at 0 and ceiling at 8 for LED matrix matrix=matrix.clip(0,8) return matrix # Process audio file print "Processing....." data = wavfile.readframes(chunk) while data != '': # output.write(data) matrix = calculate_levels(data, chunk,sample_rate) if matrix == None: next; 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() # =========================
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_text = None self.update_text(text, **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.stray[::-1]:
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 = '' painter.drawText(pix.rect(), QC.Qt.AlignRight, t) painter.end() stray.setIcon(QG.QIcon(pix))
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_text = None self.update_text(text, **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.stray[::-1]: 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)
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 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.stray[::-1]: 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 = '' painter.drawText(pix.rect(), QC.Qt.AlignRight, t) 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_()
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.stray[::-1]: 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 = '' painter.drawText(pix.rect(), QC.Qt.AlignRight, t) 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_()
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::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
() { 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 { visitor_count = visitor_count + 1; } do spawn { let mut stream = stream; match stream { Some(ref mut s) => { match s.peer_name() { Some(pn) => {println(format!("Received connection from: [{:s}]", pn.to_str()));}, None => () } }, None => () } let mut buf = [0, ..500]; stream.read(buf); let request_str = str::from_utf8(buf); println(format!("Received request :\n{:s}", request_str)); let mut index: int = 0; let mut file_name = ~""; for splitted in request_str.split(' ') { if(index == 1) { file_name.push_str(splitted); break; } index = index + 1; } let mut response = ~""; let homepage = match file_name.len() { 1 => true, _ => false }; if(homepage) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype !html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> </body></html>\r\n"); } else { let mut valid = true; if(file_name.len() < 7) { valid = false; } if(valid) { let extension = file_name.slice_from(file_name.len() - 5).to_owned(); let html_extension = ~".html"; if(str::eq(&extension, &html_extension)) { let file_name_abs = file_name.slice_from(1); let path = Path::new(file_name_abs); let opened_file: Option<File>; if path.exists() && path.is_file() { opened_file = File::open(&path); } else { opened_file = None; } match opened_file { Some(html_file) => { let mut html_file_mut = html_file; let msg_bytes: ~[u8] = html_file_mut.read_to_end(); response.push_str(str::from_utf8(msg_bytes)); }, None => { println("not found!"); valid = false; } } } else { valid = false; } } if(!valid) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype !html><html><head><title>HTTP 403 Not Found</title> </head> <body> <h1>HTTP 403 Error</h1> <p>Sorry, the page you requested does not exist. Please check the url.</p> </body></html>\r\n"); } } stream.write(response.as_bytes()); println!("Connection terminates."); unsafe { println!("Visitor count: {:d}", visitor_count); } } } }
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::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)).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 { visitor_count = visitor_count + 1; } do spawn { let mut stream = stream; match stream { Some(ref mut s) => { match s.peer_name() { Some(pn) =>
, None => () } }, None => () } let mut buf = [0, ..500]; stream.read(buf); let request_str = str::from_utf8(buf); println(format!("Received request :\n{:s}", request_str)); let mut index: int = 0; let mut file_name = ~""; for splitted in request_str.split(' ') { if(index == 1) { file_name.push_str(splitted); break; } index = index + 1; } let mut response = ~""; let homepage = match file_name.len() { 1 => true, _ => false }; if(homepage) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype !html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> </body></html>\r\n"); } else { let mut valid = true; if(file_name.len() < 7) { valid = false; } if(valid) { let extension = file_name.slice_from(file_name.len() - 5).to_owned(); let html_extension = ~".html"; if(str::eq(&extension, &html_extension)) { let file_name_abs = file_name.slice_from(1); let path = Path::new(file_name_abs); let opened_file: Option<File>; if path.exists() && path.is_file() { opened_file = File::open(&path); } else { opened_file = None; } match opened_file { Some(html_file) => { let mut html_file_mut = html_file; let msg_bytes: ~[u8] = html_file_mut.read_to_end(); response.push_str(str::from_utf8(msg_bytes)); }, None => { println("not found!"); valid = false; } } } else { valid = false; } } if(!valid) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype !html><html><head><title>HTTP 403 Not Found</title> </head> <body> <h1>HTTP 403 Error</h1> <p>Sorry, the page you requested does not exist. Please check the url.</p> </body></html>\r\n"); } } stream.write(response.as_bytes()); println!("Connection terminates."); unsafe { println!("Visitor count: {:d}", visitor_count); } } } }
{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::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)).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 { visitor_count = visitor_count + 1; } do spawn { let mut stream = stream; match stream { Some(ref mut s) => { match s.peer_name() { Some(pn) => {println(format!("Received connection from: [{:s}]", pn.to_str()));}, None => () } }, None => () } let mut buf = [0, ..500]; stream.read(buf); let request_str = str::from_utf8(buf); println(format!("Received request :\n{:s}", request_str)); let mut index: int = 0; let mut file_name = ~""; for splitted in request_str.split(' ') { if(index == 1) { file_name.push_str(splitted); break; } index = index + 1; } let mut response = ~""; let homepage = match file_name.len() { 1 => true, _ => false }; if(homepage) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype !html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> </body></html>\r\n"); } else { let mut valid = true; if(file_name.len() < 7) { valid = false; } if(valid) { let extension = file_name.slice_from(file_name.len() - 5).to_owned(); let html_extension = ~".html"; if(str::eq(&extension, &html_extension)) { let file_name_abs = file_name.slice_from(1); let path = Path::new(file_name_abs); let opened_file: Option<File>; if path.exists() && path.is_file() { opened_file = File::open(&path); } else { opened_file = None; } match opened_file { Some(html_file) => { let mut html_file_mut = html_file; let msg_bytes: ~[u8] = html_file_mut.read_to_end(); response.push_str(str::from_utf8(msg_bytes)); }, None => { println("not found!"); valid = false; } } } else { valid = false; } } if(!valid) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype !html><html><head><title>HTTP 403 Not Found</title> </head> <body> <h1>HTTP 403 Error</h1> <p>Sorry, the page you requested does not exist. Please check the url.</p> </body></html>\r\n"); } } stream.write(response.as_bytes()); println!("Connection terminates."); unsafe { println!("Visitor count: {:d}", visitor_count); } } }
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)).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 { visitor_count = visitor_count + 1; } do spawn { let mut stream = stream; match stream { Some(ref mut s) => { match s.peer_name() { Some(pn) => {println(format!("Received connection from: [{:s}]", pn.to_str()));}, None => () } }, None => () } let mut buf = [0, ..500]; stream.read(buf); let request_str = str::from_utf8(buf); println(format!("Received request :\n{:s}", request_str)); let mut index: int = 0; let mut file_name = ~""; for splitted in request_str.split(' ') { if(index == 1) { file_name.push_str(splitted); break; } index = index + 1; } let mut response = ~""; let homepage = match file_name.len() { 1 => true, _ => false }; if(homepage) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype !html><html><head><title>Hello, Rust!</title> <style>body { background-color: #111; color: #FFEEAA } h1 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm red} h2 { font-size:2cm; text-align: center; color: black; text-shadow: 0 0 4mm green} </style></head> <body> <h1>Greetings, Krusty!</h1> </body></html>\r\n"); } else { let mut valid = true; if(file_name.len() < 7) { valid = false; } if(valid) { let extension = file_name.slice_from(file_name.len() - 5).to_owned(); let html_extension = ~".html"; if(str::eq(&extension, &html_extension)) { let file_name_abs = file_name.slice_from(1); let path = Path::new(file_name_abs); let opened_file: Option<File>; if path.exists() && path.is_file() { opened_file = File::open(&path); } else { opened_file = None; } match opened_file { Some(html_file) => { let mut html_file_mut = html_file; let msg_bytes: ~[u8] = html_file_mut.read_to_end(); response.push_str(str::from_utf8(msg_bytes)); }, None => { println("not found!"); valid = false; } } } else { valid = false; } } if(!valid) { response.push_str("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n <doctype !html><html><head><title>HTTP 403 Not Found</title> </head> <body> <h1>HTTP 403 Error</h1> <p>Sorry, the page you requested does not exist. Please check the url.</p> </body></html>\r\n"); } } stream.write(response.as_bytes()); println!("Connection terminates."); unsafe { println!("Visitor count: {:d}", visitor_count); } } } }
// 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 <[email protected]> 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 the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // #![forbid(unsafe_code)] #![deny( non_camel_case_types, non_snake_case, path_statements, trivial_numeric_casts, unstable_features, unused_allocation, unused_import_braces, unused_imports, unused_must_use, unused_mut, unused_qualifications, while_true, )] #[macro_use] extern crate libimagrt; simple_imag_application_binary!(libimaglinkcmd, ImagLink);
// 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 streamlink.utils import parse_json log = logging.getLogger(__name__) class Vimeo(Plugin): _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_re.search), validate.any( None, validate.Schema( validate.get(1), validate.transform(parse_json), validate.transform(html_unescape), validate.url(), ), ), ) _config_schema = validate.Schema( validate.transform(parse_json), { "request": { "files": { validate.optional("dash"): {"cdns": {validate.text: {"url": validate.url()}}}, validate.optional("hls"): {"cdns": {validate.text: {"url": validate.url()}}}, validate.optional("progressive"): validate.all( [{"url": validate.url(), "quality": validate.text}] ), }, validate.optional("text_tracks"): validate.all( [{"url": validate.text, "lang": validate.text}] ), } }, ) _player_schema = validate.Schema( validate.transform(_config_re.search), validate.any(None, validate.Schema(validate.get(1), _config_schema)), ) arguments = PluginArguments( PluginArgument( "mux-subtitles", action="store_true", help="Automatically mux available subtitles in to the output stream.", ) ) @classmethod def
(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 api_url: return data = self.session.http.get(api_url, schema=self._config_schema) videos = data["request"]["files"] streams = [] for stream_type in ("hls", "dash"): if stream_type not in videos: continue 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(): streams.append(stream) elif stream_type == "dash": p = urlparse(url) if p.path.endswith("dash.mpd"): # LIVE url = self.session.http.get(url).json()["url"] elif p.path.endswith("master.json"): # VOD url = url.replace("master.json", "master.mpd") else: log.error("Unsupported DASH path: {0}".format(p.path)) continue for stream in DASHStream.parse_manifest(self.session, url).items(): streams.append(stream) for stream in videos.get("progressive", []): streams.append((stream["quality"], HTTPStream(self.session, stream["url"]))) if self.get_option("mux_subtitles") and data["request"].get("text_tracks"): substreams = { s["lang"]: HTTPStream(self.session, "https://vimeo.com" + s["url"]) for s in data["request"]["text_tracks"] } for quality, stream in streams: yield quality, MuxedStream(self.session, stream, subtitles=substreams) else: for stream in streams: yield stream __plugin__ = Vimeo
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 streamlink.utils import parse_json log = logging.getLogger(__name__) class Vimeo(Plugin): _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_re.search), validate.any( None, validate.Schema( validate.get(1), validate.transform(parse_json), validate.transform(html_unescape), validate.url(), ), ), ) _config_schema = validate.Schema( validate.transform(parse_json), { "request": { "files": { validate.optional("dash"): {"cdns": {validate.text: {"url": validate.url()}}}, validate.optional("hls"): {"cdns": {validate.text: {"url": validate.url()}}}, validate.optional("progressive"): validate.all( [{"url": validate.url(), "quality": validate.text}] ), }, validate.optional("text_tracks"): validate.all( [{"url": validate.text, "lang": validate.text}] ), } }, ) _player_schema = validate.Schema( validate.transform(_config_re.search), validate.any(None, validate.Schema(validate.get(1), _config_schema)), ) arguments = PluginArguments( PluginArgument( "mux-subtitles", action="store_true", help="Automatically mux available subtitles in to the output stream.", ) ) @classmethod def can_handle_url(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 api_url: return data = self.session.http.get(api_url, schema=self._config_schema) videos = data["request"]["files"] streams = [] for stream_type in ("hls", "dash"): if stream_type not in videos:
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(): streams.append(stream) elif stream_type == "dash": p = urlparse(url) if p.path.endswith("dash.mpd"): # LIVE url = self.session.http.get(url).json()["url"] elif p.path.endswith("master.json"): # VOD url = url.replace("master.json", "master.mpd") else: log.error("Unsupported DASH path: {0}".format(p.path)) continue for stream in DASHStream.parse_manifest(self.session, url).items(): streams.append(stream) for stream in videos.get("progressive", []): streams.append((stream["quality"], HTTPStream(self.session, stream["url"]))) if self.get_option("mux_subtitles") and data["request"].get("text_tracks"): substreams = { s["lang"]: HTTPStream(self.session, "https://vimeo.com" + s["url"]) for s in data["request"]["text_tracks"] } for quality, stream in streams: yield quality, MuxedStream(self.session, stream, subtitles=substreams) else: for stream in streams: yield stream __plugin__ = Vimeo
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 streamlink.utils import parse_json log = logging.getLogger(__name__) class Vimeo(Plugin):
__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_re.search), validate.any( None, validate.Schema( validate.get(1), validate.transform(parse_json), validate.transform(html_unescape), validate.url(), ), ), ) _config_schema = validate.Schema( validate.transform(parse_json), { "request": { "files": { validate.optional("dash"): {"cdns": {validate.text: {"url": validate.url()}}}, validate.optional("hls"): {"cdns": {validate.text: {"url": validate.url()}}}, validate.optional("progressive"): validate.all( [{"url": validate.url(), "quality": validate.text}] ), }, validate.optional("text_tracks"): validate.all( [{"url": validate.text, "lang": validate.text}] ), } }, ) _player_schema = validate.Schema( validate.transform(_config_re.search), validate.any(None, validate.Schema(validate.get(1), _config_schema)), ) arguments = PluginArguments( PluginArgument( "mux-subtitles", action="store_true", help="Automatically mux available subtitles in to the output stream.", ) ) @classmethod def can_handle_url(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 api_url: return data = self.session.http.get(api_url, schema=self._config_schema) videos = data["request"]["files"] streams = [] for stream_type in ("hls", "dash"): if stream_type not in videos: continue 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(): streams.append(stream) elif stream_type == "dash": p = urlparse(url) if p.path.endswith("dash.mpd"): # LIVE url = self.session.http.get(url).json()["url"] elif p.path.endswith("master.json"): # VOD url = url.replace("master.json", "master.mpd") else: log.error("Unsupported DASH path: {0}".format(p.path)) continue for stream in DASHStream.parse_manifest(self.session, url).items(): streams.append(stream) for stream in videos.get("progressive", []): streams.append((stream["quality"], HTTPStream(self.session, stream["url"]))) if self.get_option("mux_subtitles") and data["request"].get("text_tracks"): substreams = { s["lang"]: HTTPStream(self.session, "https://vimeo.com" + s["url"]) for s in data["request"]["text_tracks"] } for quality, stream in streams: yield quality, MuxedStream(self.session, stream, subtitles=substreams) else: for stream in streams: yield stream
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 streamlink.utils import parse_json log = logging.getLogger(__name__) class Vimeo(Plugin): _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_re.search), validate.any( None, validate.Schema( validate.get(1), validate.transform(parse_json), validate.transform(html_unescape), validate.url(), ), ), ) _config_schema = validate.Schema( validate.transform(parse_json), { "request": {
validate.optional("progressive"): validate.all( [{"url": validate.url(), "quality": validate.text}] ), }, validate.optional("text_tracks"): validate.all( [{"url": validate.text, "lang": validate.text}] ), } }, ) _player_schema = validate.Schema( validate.transform(_config_re.search), validate.any(None, validate.Schema(validate.get(1), _config_schema)), ) arguments = PluginArguments( PluginArgument( "mux-subtitles", action="store_true", help="Automatically mux available subtitles in to the output stream.", ) ) @classmethod def can_handle_url(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 api_url: return data = self.session.http.get(api_url, schema=self._config_schema) videos = data["request"]["files"] streams = [] for stream_type in ("hls", "dash"): if stream_type not in videos: continue 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(): streams.append(stream) elif stream_type == "dash": p = urlparse(url) if p.path.endswith("dash.mpd"): # LIVE url = self.session.http.get(url).json()["url"] elif p.path.endswith("master.json"): # VOD url = url.replace("master.json", "master.mpd") else: log.error("Unsupported DASH path: {0}".format(p.path)) continue for stream in DASHStream.parse_manifest(self.session, url).items(): streams.append(stream) for stream in videos.get("progressive", []): streams.append((stream["quality"], HTTPStream(self.session, stream["url"]))) if self.get_option("mux_subtitles") and data["request"].get("text_tracks"): substreams = { s["lang"]: HTTPStream(self.session, "https://vimeo.com" + s["url"]) for s in data["request"]["text_tracks"] } for quality, stream in streams: yield quality, MuxedStream(self.session, stream, subtitles=substreams) else: for stream in streams: yield stream __plugin__ = Vimeo
"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::F32) { Ok(value) => value, Err(error) => panic!("{}", error), }; print(&a); } #[allow(unused_must_use)] fn
() { 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 compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CPU backend error: {}", e), }; } 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 error: {}", e), }; } if available.contains(&Backend::AF_BACKEND_OPENCL){ println!("Evaluating OpenCL Backend..."); let err = set_backend(Backend::AF_BACKEND_OPENCL); println!("There are {} OpenCL compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("OpenCL backend error: {}", e), }; } }
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::F32) { Ok(value) => value, Err(error) => panic!("{}", error), }; print(&a); } #[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)
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 error: {}", e), }; } if available.contains(&Backend::AF_BACKEND_OPENCL){ println!("Evaluating OpenCL Backend..."); let err = set_backend(Backend::AF_BACKEND_OPENCL); println!("There are {} OpenCL compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("OpenCL backend error: {}", e), }; } }
{ 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); println!("There are {} CPU compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CPU backend error: {}", e), }; } 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 error: {}", e), }; } if available.contains(&Backend::AF_BACKEND_OPENCL){ println!("Evaluating OpenCL Backend..."); let err = set_backend(Backend::AF_BACKEND_OPENCL); println!("There are {} OpenCL compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("OpenCL backend error: {}", e), }; } }
{ 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::F32) { Ok(value) => value, Err(error) => panic!("{}", error), }; print(&a); } #[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); println!("There are {} CPU compute devices", device_count().unwrap()); match err { Ok(_) => test_backend(), Err(e) => println!("CPU backend error: {}", e), }; } 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 error: {}", e), }; } if available.contains(&Backend::AF_BACKEND_OPENCL){ println!("Evaluating OpenCL Backend..."); let err = set_backend(Backend::AF_BACKEND_OPENCL);
}; } }
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, defaultPath, defaultTickFormat, ELabelOrientation, IAxis, TAxisValue, } from './YAxis'; const positionTick = (value: TAxisValue, scale: any, i: number, inverse: boolean = false, width = 10) => { const offset = isOfType<ScaleBand<any>>(scale, 'paddingInner') ? scale.bandwidth() / 2 : 0; let v = isOfType<ScaleBand<any>>(scale, 'paddingInner') ? Number(scale(String(i))) + offset : scale(value); if (inverse) { v = width - v; } 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, }) => { if (scale === 'linear' && values.length > 0 && typeof values[0] === 'string') { throw new Error('Linear axis can not accept string values'); } if (scale === 'band' && !padding) { console.warn('band scale provided without padding settings'); } const Scale = buildScale({ domain, length: width, padding, values, scale, range: [0, width], }); const transform = `${left}, ${top}`; const pathD = `M0,0 L${width},0`; const axisPath = { ...defaultPath, ...(path ?? {}) }; const { fill, opacity, stroke, strokeOpacity, strokeWidth } = axisPath; const d = Scale.domain() as [number, number]; const ticks = buildTicks(scale, values, d); return ( <g className="x-axis" transform={`translate(${transform})`} fill="none" fontSize="10" fontFamily="sans-serif" textAnchor="middle"> <path className="domain" stroke={stroke}
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 === 'function' ? tickFormat(label, i) : tickFormat; const tickLabel = labelFormat ? labelFormat('x', label, i) : label const textArray: string[] = textWrap(tickLabel, height, { 'font-size': thisFormat.fontSize }); return ( <g aria-hidden={scale !== 'band'} role={scale === 'band' ? 'row' : ''} key={`x-axis-${v}.${label}.${i}`} className="tick" opacity="1" textAnchor="middle" transform={`translate${tickOffset}`}> <line stroke={stroke} x1={0} y2={`${tickSize}`} fill="none" opacity={opacity} shapeRendering="auto" strokeOpacity="1" strokeWidth="1"> </line> { textArray.map((txt, j) => { const dx = textArray.length === 1 ? 0 : (textArray.length / 2 * 20) - (20 * j) - 10; const dy = textArray.length === 1 ? 20 : (20 * j) + 20; return <g key={j}> <text role={scale === 'band' ? 'columnheader' : ''} fill={thisFormat.stroke} fontSize={thisFormat.fontSize} textAnchor={labelOrientation === ELabelOrientation.HORIZONTAL ? 'middle' : 'start'} writingMode={labelOrientation === ELabelOrientation.HORIZONTAL ? 'horizontal-tb' : 'vertical-lr'} height={height} dy={labelOrientation === ELabelOrientation.HORIZONTAL ? dy : '20'} dx={labelOrientation === ELabelOrientation.HORIZONTAL ? '0' : dx}> {txt} </text> </g> })} </g> ) }) } </g> ) } export default XAxis;
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, defaultPath, defaultTickFormat, ELabelOrientation, IAxis, TAxisValue, } from './YAxis'; const positionTick = (value: TAxisValue, scale: any, i: number, inverse: boolean = false, width = 10) => { const offset = isOfType<ScaleBand<any>>(scale, 'paddingInner') ? scale.bandwidth() / 2 : 0; let v = isOfType<ScaleBand<any>>(scale, 'paddingInner') ? Number(scale(String(i))) + offset : scale(value); if (inverse)
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, }) => { if (scale === 'linear' && values.length > 0 && typeof values[0] === 'string') { throw new Error('Linear axis can not accept string values'); } if (scale === 'band' && !padding) { console.warn('band scale provided without padding settings'); } const Scale = buildScale({ domain, length: width, padding, values, scale, range: [0, width], }); const transform = `${left}, ${top}`; const pathD = `M0,0 L${width},0`; const axisPath = { ...defaultPath, ...(path ?? {}) }; const { fill, opacity, stroke, strokeOpacity, strokeWidth } = axisPath; const d = Scale.domain() as [number, number]; const ticks = buildTicks(scale, values, d); return ( <g className="x-axis" transform={`translate(${transform})`} fill="none" fontSize="10" fontFamily="sans-serif" textAnchor="middle"> <path className="domain" stroke={stroke} d={pathD} fill={fill} opacity={opacity} shapeRendering="auto" 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 === 'function' ? tickFormat(label, i) : tickFormat; const tickLabel = labelFormat ? labelFormat('x', label, i) : label const textArray: string[] = textWrap(tickLabel, height, { 'font-size': thisFormat.fontSize }); return ( <g aria-hidden={scale !== 'band'} role={scale === 'band' ? 'row' : ''} key={`x-axis-${v}.${label}.${i}`} className="tick" opacity="1" textAnchor="middle" transform={`translate${tickOffset}`}> <line stroke={stroke} x1={0} y2={`${tickSize}`} fill="none" opacity={opacity} shapeRendering="auto" strokeOpacity="1" strokeWidth="1"> </line> { textArray.map((txt, j) => { const dx = textArray.length === 1 ? 0 : (textArray.length / 2 * 20) - (20 * j) - 10; const dy = textArray.length === 1 ? 20 : (20 * j) + 20; return <g key={j}> <text role={scale === 'band' ? 'columnheader' : ''} fill={thisFormat.stroke} fontSize={thisFormat.fontSize} textAnchor={labelOrientation === ELabelOrientation.HORIZONTAL ? 'middle' : 'start'} writingMode={labelOrientation === ELabelOrientation.HORIZONTAL ? 'horizontal-tb' : 'vertical-lr'} height={height} dy={labelOrientation === ELabelOrientation.HORIZONTAL ? dy : '20'} dx={labelOrientation === ELabelOrientation.HORIZONTAL ? '0' : dx}> {txt} </text> </g> })} </g> ) }) } </g> ) } export default XAxis;
{ 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(); test3(); //当$(function(){window.test3=fn});时,报错! test4(); })(window); */ /** $(function(w){ w.saveUser(); saveBlog(); var util_v1 = new w.util_v1(); util_v1.ajax(); test1(); test2(); test3(); //当$(function(){window.test3=fn});时,报错! test4(); }(window)); */ //最保险的方式 $(function(){ window.saveUser(); saveBlog(); var util_v1 = new window.util_v1(); util_v1.ajax(); test1(); test2(); test3(); test4(); }); //note: 当在$(function(){window.test=fn;});赋值到window时,只能在$(function(){})中调用到window.test! //ques: /**Q1
// 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(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 True: attempt = attempt + 1 if attempt > 3: break headers={} headers["Host"] = "akb48-sousenkyo.jp" headers["User-Agent"] = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1" if cookie != "": headers["Cookie"] = cookie access = urllib2.Request(url=link, headers=headers) reconnect = 5 while True: try: response = urllib2.urlopen(access,timeout=timeout) except: reconnect = reconnect - 1 if reconnect <= 0: exit() else: break if "set-cookie" in response.headers:
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: if item[1] != "": data[item[0]] = item[1] data = urllib.urlencode(data) headers["Cookie"] = cookie headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Origin"] = "http://akb48-sousenkyo.jp" headers["Referer"] = link time.sleep(0.5) submit = urllib2.Request(url="http://akb48-sousenkyo.jp/vote_thanks.php",data=data,headers=headers) try: response = urllib2.urlopen(submit,timeout=timeout) except: result = u"ネットワークタイムアウト" continue if response.geturl() != "http://akb48-sousenkyo.jp/vote_thanks.php": result = u"お客様の端末は非推奨です" continue statuspage = response.read().decode('shift-jis').encode('utf-8') message = re.search(r'<p class="mb20">([\s\S]+?)</p>',statuspage).group(1) message = re.sub(r'\s*',"",message) if message.find('シリアルナンバーに誤りがあります。ご確認ください。') != -1: result = u"シリアルナンバーに誤りがあります" break elif message.find('入力されたシリアルナンバーは、既に投票されています。') != -1: timestr = re.search(r'投票日時:\d{4}年\d{2}月\d{2}日\d{2}時\d{2}分\d{2}秒',message).group(0) result = timestr.decode("utf-8") break elif message.find('入力されたシリアルナンバーは無効であるか既に投票済みです。') != -1: result = u"入力されたシリアルナンバーは無効であるか既に投票済みです" break elif message.find('ご投票いただきありがとうございました。') != -1: result = u"ご投票いただきありがとうございました" proxy = 1 attempt = 1 continue else: result = message.decode("utf-8") break return (result,proxy) allfiles = os.listdir('./xls/') if len(allfiles) == 0: print "no tickets need to check" exit() if os.path.exists("./output/") == False: os.mkdir("./output/") for filename in allfiles: tickets = [] data = xlrd.open_workbook('./xls/' + filename) sheet1 = data.sheets()[0] rows = sheet1.nrows columns = sheet1.ncols offsetx = 0 offsety = 0 for 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 = i%columns break for r in xrange(offsetx,rows): row = [] if type(sheet1.row_values(r)[offsety]) is unicode and type(sheet1.row_values(r)[offsety + 1]) is unicode: noblankcell1 = re.sub(u'[\s|(\u3000)|(\xa0)]*',"",sheet1.row_values(r)[offsety]) noblankcell2 = re.sub(u'[\s|(\u3000)|(\xa0)]*',"",sheet1.row_values(r)[offsety + 1]) if re.search(r'^\w{8}$',noblankcell1)!=None and re.search(r'^\w{8}$',noblankcell2)!=None: row.append(noblankcell1) row.append(noblankcell2) tickets.append(row) else: if noblankcell1 != "" and noblankcell2 != "": row.append(noblankcell1) row.append(noblankcell2) row.append(u'シリアルナンバーはそれぞれ8桁ずつ半角英数字で入力してください') tickets.append(row) print "[error]",filename,"line",r+1," ",noblankcell1,noblankcell2 else: print "[error]",filename,"line",r+1," ",sheet1.row_values(r)[offsety],sheet1.row_values(r)[offsety + 1] total = len(tickets) bits = len(str(total)) print "%s total %d"%(filename,total) output = [] for t in xrange(0,total): serial_code_1 = tickets[t][0] serial_code_2 = tickets[t][1] if len(tickets[t])==3: output.append([serial_code_1,serial_code_2,tickets[t][2],u"否"]) continue result = ticketcheck(1307,serial_code_1,serial_code_2) if result[1] == 1: miss = u"是" elif result[1] == 0: miss = u"否" print str(t+1).zfill(bits)," ",serial_code_1,serial_code_2," ",result[0],miss output.append([serial_code_1,serial_code_2,result[0],miss]) workbook = xlwt.Workbook() sheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True) style = xlwt.XFStyle() font = xlwt.Font() font.name = u'等线' # font.colour_index = 2 #red font.height = 14 * 20 #16 point font.bold = False for i in xrange(0,total): if output[i][3] == u'否' and re.search(u'投票日時',output[i][2]) != None: font.colour_index = 0 else: font.colour_index = 2 style.font = font sheet1.write(i,0,i+1,style) sheet1.write(i,1,output[i][0],style) sheet1.write(i,2,output[i][1],style) sheet1.write(i,3,output[i][2],style) sheet1.write(i,4,output[i][3],style) sheet1.write(i,5,u'nondanee',style) sheet1.col(0).width = 256 * 8 sheet1.col(1).width = 256 * 14 sheet1.col(2).width = 256 * 14 sheet1.col(3).width = 256 * 56 sheet1.col(4).width = 256 * 8 sheet1.col(5).width = 256 * 15 namepart = filename.split(".")[0] workbook.save('./output/' + namepart + "-checked.xls") print "Done"
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) attempt = 0 result = "" proxy = 0 while True: attempt = attempt + 1 if attempt > 3: break headers={} headers["Host"] = "akb48-sousenkyo.jp" headers["User-Agent"] = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1" if cookie != "": headers["Cookie"] = cookie access = urllib2.Request(url=link, headers=headers) reconnect = 5 while True: try: response = urllib2.urlopen(access,timeout=timeout) except: reconnect = reconnect - 1 if reconnect <= 0: exit() else: break if "set-cookie" in response.headers: cookie = response.headers["set-cookie"] 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: if item[1] != "": data[item[0]] = item[1] data = urllib.urlencode(data) headers["Cookie"] = cookie headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Origin"] = "http://akb48-sousenkyo.jp" headers["Referer"] = link time.sleep(0.5) submit = urllib2.Request(url="http://akb48-sousenkyo.jp/vote_thanks.php",data=data,headers=headers) try: response = urllib2.urlopen(submit,timeout=timeout) except: result = u"ネットワークタイムアウト" continue if response.geturl() != "http://akb48-sousenkyo.jp/vote_thanks.php": result = u"お客様の端末は非推奨です" continue statuspage = response.read().decode('shift-jis').encode('utf-8') message = re.search(r'<p class="mb20">([\s\S]+?)</p>',statuspage).group(1) message = re.sub(r'\s*',"",message) if message.find('シリアルナンバーに誤りがあります。ご確認ください。') != -1: result = u"シリアルナンバーに誤りがあります" break elif message.find('入力されたシリアルナンバーは、既に投票されています。') != -1: timestr = re.search(r'投票日時:\d{4}年\d{2}月\d{2}日\d{2}時\d{2}分\d{2}秒',message).group(0) result = timestr.decode("utf-8") break elif message.find('入力されたシリアルナンバーは無効であるか既に投票済みです。') != -1: result = u"入力されたシリアルナンバーは無効であるか既に投票済みです" break elif message.find('ご投票いただきありがとうございました。') != -1: result = u"ご投票いただきありがとうございました" proxy = 1 attempt = 1 continue else: result = message.decode("utf-8") break return (result,proxy) allfiles = os.listdir('./xls/') if len(allfiles) == 0: print "no tickets need to check" exit() if os.path.exists("./output/") == False: os.mkdir("./output/") for filename in allfiles: tickets = [] data = xlrd.open_workbook('./xls/' + filename) sheet1 = data.sheets()[0] rows = sheet1.nrows columns = sheet1.ncols offsetx = 0 offsety = 0 for 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 = i%columns break for r in xrange(offsetx,rows): row = [] if type(sheet1.row_values(r)[offsety]) is unicode and type(sheet1.row_values(r)[offsety + 1]) is unicode: noblankcell1 = re.sub(u'[\s|(\u3000)|(\xa0)]*',"",sheet1.row_values(r)[offsety]) noblankcell2 = re.sub(u'[\s|(\u3000)|(\xa0)]*',"",sheet1.row_values(r)[offsety + 1]) if re.search(r'^\w{8}$',noblankcell1)!=None and re.search(r'^\w{8}$',noblankcell2)!=None: row.append(noblankcell1) row.append(noblankcell2) tickets.append(row) else: if noblankcell1 != "" and noblankcell2 != "": row.append(noblankcell1) row.append(noblankcell2) row.append(u'シリアルナンバーはそれぞれ8桁ずつ半角英数字で入力してください') tickets.append(row) print "[error]",filename,"line",r+1," ",noblankcell1,noblankcell2 else: print "[error]",filename,"line",r+1," ",sheet1.row_values(r)[offsety],sheet1.row_values(r)[offsety + 1] total = len(tickets) bits = len(str(total)) print "%s total %d"%(filename,total) output = [] for t in xrange(0,total): serial_code_1 = tickets[t][0] serial_code_2 = tickets[t][1] if len(tickets[t])==3: output.append([serial_code_1,serial_code_2,tickets[t][2],u"否"]) continue result = ticketcheck(1307,serial_code_1,serial_code_2) if result[1] == 1: miss = u"是" elif result[1] == 0: miss = u"否" print str(t+1).zfill(bits)," ",serial_code_1,serial_code_2," ",result[0],miss output.append([serial_code_1,serial_code_2,result[0],miss]) workbook = xlwt.Workbook() sheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True) style = xlwt.XFStyle() font = xlwt.Font() font.name = u'等线' # font.colour_index = 2 #red font.height = 14 * 20 #16 point font.bold = False for i in xrange(0,total): if output[i][3] == u'否' and re.search(u'投票日時',output[i][2]) != None: font.colour_index = 0 else: font.colour_index = 2 style.font = font sheet1.write(i,0,i+1,style) sheet1.write(i,1,output[i][0],style) sheet1.write(i,2,output[i][1],style) sheet1.write(i,3,output[i][2],style) sheet1.write(i,4,output[i][3],style) sheet1.write(i,5,u'nondanee',style) sheet1.col(0).width = 256 * 8 sheet1.col(1).width = 256 * 14 sheet1.col(2).width = 256 * 14 sheet1.col(3).width = 256 * 56 sheet1.col(4).width = 256 * 8 sheet1.col(5).width = 256 * 15 namepart = filename.split(".")[0] workbook.save('./output/' + namepart + "-checked.xls") print "Done"
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(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 True: attempt = attempt + 1 if attempt > 3: break headers={} headers["Host"] = "akb48-sousenkyo.jp" headers["User-Agent"] = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1" if cookie != "": headers["Cookie"] = cookie access = urllib2.Request(url=link, headers=headers) reconnect = 5 while True: try: response = urllib2.urlopen(access,timeout=timeout) except: reconnect = reconnect - 1 if reconnect <= 0: exit() else: break if "set-cookie" in response.headers: cookie = response.headers["set-cookie"] 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: if item[1] != "": data[item[0]] = item[1] data = urllib.urlencode(data) headers["Cookie"] = cookie headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Origin"] = "http://akb48-sousenkyo.jp" headers["Referer"] = link time.sleep(0.5) submit = urllib2.Request(url="http://akb48-sousenkyo.jp/vote_thanks.php",data=data,headers=headers) try: response = urllib2.urlopen(submit,timeout=timeout) except: result = u"ネットワークタイムアウト" continue if response.geturl() != "http://akb48-sousenkyo.jp/vote_thanks.php": result = u"お客様の端末は非推奨です" continue statuspage = response.read().decode('shift-jis').encode('utf-8') message = re.search(r'<p class="mb20">([\s\S]+?)</p>',statuspage).group(1) message = re.sub(r'\s*',"",message) if message.find('シリアルナンバーに誤りがあります。ご確認ください。') != -1: result = u"シリアルナンバーに誤りがあります" break elif message.find('入力されたシリアルナンバーは、既に投票されています。') != -1: timestr = re.search(r'投票日時:\d{4}年\d{2}月\d{2}日\d{2}時\d{2}分\d{2}秒',message).group(0) result = timestr.decode("utf-8") break elif message.find('入力されたシリアルナンバーは無効であるか既に投票済みです。') != -1: result = u"入力されたシリアルナンバーは無効であるか既に投票済みです" break elif message.find('ご投票いただきありがとうございました。') != -1: result = u"ご投票いただきありがとうございました" proxy = 1 attempt = 1 continue else: result = message.decode("utf-8") break return (result,proxy) allfiles = os.listdir('./xls/') if len(allfiles) == 0: print "no tickets need to check" exit() if os.path.exists("./output/") == False: os.mkdir("./output/") for filename in allfiles: tickets = [] data = xlrd.open_workbook('./xls/' + filename) sheet1 = data.sheets()[0] rows = sheet1.nrows columns = sheet1.ncols offsetx = 0 offsety = 0 for 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 = i%columns break for r in xrange(offsetx,rows): row = [] if type(sheet1.row_values(r)[offsety]) is unicode and type(sheet1.row_values(r)[offsety + 1]) is unicode: noblankcell1 = re.sub(u'[\s|(\u3000)|(\xa0)]*',"",sheet1.row_values(r)[offsety]) noblankcell2 = re.sub(u'[\s|(\u3000)|(\xa0)]*',"",sheet1.row_values(r)[offsety + 1]) if re.search(r'^\w{8}$',noblankcell1)!=None and re.search(r'^\w{8}$',noblankcell2)!=None: row.append(noblankcell1) row.append(noblankcell2) tickets.append(row) else: if noblankcell1 != "" and noblankcell2 != "": row.append(noblankcell1) row.append(noblankcell2) row.append(u'シリアルナンバーはそれぞれ8桁ずつ半角英数字で入力してください') tickets.append(row) print "[error]",filename,"line",r+1," ",noblankcell1,noblankcell2 else: print "[error]",filename,"line",r+1," ",sheet1.row_values(r)[offsety],sheet1.row_values(r)[offsety + 1] total = len(tickets) bits = len(str(total)) print "%s total %d"%(filename,total) output = [] for t in xrange(0,total): serial_code_1 = tickets[t][0] serial_code_2 = tickets[t][1] if len(tickets[t])==3: output.append([serial_code_1,serial_code_2,tickets[t][2],u"否"]) continue result = ticketcheck(1307,serial_code_1,serial_code_2) if result[1] == 1: miss = u"是" elif result[1] == 0: miss = u"否" print str(t+1).zfill(bits)," ",serial_code_1,serial_code_2," ",result[0],miss output.append([serial_code_1,serial_code_2,result[0],miss]) workbook = xlwt.Workbook() sheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True) style = xlwt.XFStyle() font = xlwt.Font() font.name = u'等线' # font.colour_index = 2 #red font.height = 14 * 20 #16 point font.bold = False for i in xrange(0,total): if output[i][3] == u'否' and re.search(u'投票日時',output[i][2]) != None: font.colour_index = 0 else: font.colour_index = 2 style.font = font sheet1.write(i,0,i+1,style) sheet1.write(i,1,output[i][0],style) sheet1.write(i,2,output[i][1],style) sheet1.write(i,3,output[i][2],style) sheet1.write(i,4,output[i][3],style) sheet1.write(i,5,u'nondanee',style) sheet1.col(0).width = 256 * 8 sheet1.col(1).width = 256 * 14 sheet1.col(2).width = 256 * 14 sheet1.col(3).width = 256 * 56 sheet1.col(4).width = 256 * 8 sheet1.col(5).width = 256 * 15 namepart = filename.split(".")[0]
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 = i%columns break for r in xrange(offsetx,rows): row = [] if type(sheet1.row_values(r)[offsety]) is unicode and type(sheet1.row_values(r)[offsety + 1]) is unicode: noblankcell1 = re.sub(u'[\s|(\u3000)|(\xa0)]*',"",sheet1.row_values(r)[offsety]) noblankcell2 = re.sub(u'[\s|(\u3000)|(\xa0)]*',"",sheet1.row_values(r)[offsety + 1]) if re.search(r'^\w{8}$',noblankcell1)!=None and re.search(r'^\w{8}$',noblankcell2)!=None: row.append(noblankcell1) row.append(noblankcell2) tickets.append(row) else: if noblankcell1 != "" and noblankcell2 != "": row.append(noblankcell1) row.append(noblankcell2) row.append(u'シリアルナンバーはそれぞれ8桁ずつ半角英数字で入力してください') tickets.append(row) print "[error]",filename,"line",r+1," ",noblankcell1,noblankcell2 else: print "[error]",filename,"line",r+1," ",sheet1.row_values(r)[offsety],sheet1.row_values(r)[offsety + 1] total = len(tickets) bits = len(str(total)) print "%s total %d"%(filename,total) output = [] for t in xrange(0,total): serial_code_1 = tickets[t][0] serial_code_2 = tickets[t][1] if len(tickets[t])==3: output.append([serial_code_1,serial_code_2,tickets[t][2],u"否"]) continue result = ticketcheck(1307,serial_code_1,serial_code_2) if result[1] == 1: miss = u"是" elif result[1] == 0: miss = u"否" print str(t+1).zfill(bits)," ",serial_code_1,serial_code_2," ",result[0],miss output.append([serial_code_1,serial_code_2,result[0],miss]) workbook = xlwt.Workbook() sheet1 = workbook.add_sheet('sheet1',cell_overwrite_ok=True) style = xlwt.XFStyle() font = xlwt.Font() font.name = u'等线' # font.colour_index = 2 #red font.height = 14 * 20 #16 point font.bold = False for i in xrange(0,total): if output[i][3] == u'否' and re.search(u'投票日時',output[i][2]) != None: font.colour_index = 0 else: font.colour_index = 2 style.font = font sheet1.write(i,0,i+1,style) sheet1.write(i,1,output[i][0],style) sheet1.write(i,2,output[i][1],style) sheet1.write(i,3,output[i][2],style) sheet1.write(i,4,output[i][3],style) sheet1.write(i,5,u'nondanee',style) sheet1.col(0).width = 256 * 8 sheet1.col(1).width = 256 * 14 sheet1.col(2).width = 256 * 14 sheet1.col(3).width = 256 * 56 sheet1.col(4).width = 256 * 8 sheet1.col(5).width = 256 * 15 namepart = filename.split(".")[0] workbook.save('./output/' + namepart + "-checked.xls") print "Done"
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 True: attempt = attempt + 1 if attempt > 3: break headers={} headers["Host"] = "akb48-sousenkyo.jp" headers["User-Agent"] = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1" if cookie != "": headers["Cookie"] = cookie access = urllib2.Request(url=link, headers=headers) reconnect = 5 while True: try: response = urllib2.urlopen(access,timeout=timeout) except: reconnect = reconnect - 1 if reconnect <= 0: exit() else: break if "set-cookie" in response.headers: cookie = response.headers["set-cookie"] 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: if item[1] != "": data[item[0]] = item[1] data = urllib.urlencode(data) headers["Cookie"] = cookie headers["Content-Type"] = "application/x-www-form-urlencoded" headers["Origin"] = "http://akb48-sousenkyo.jp" headers["Referer"] = link time.sleep(0.5) submit = urllib2.Request(url="http://akb48-sousenkyo.jp/vote_thanks.php",data=data,headers=headers) try: response = urllib2.urlopen(submit,timeout=timeout) except: result = u"ネットワークタイムアウト" continue if response.geturl() != "http://akb48-sousenkyo.jp/vote_thanks.php": result = u"お客様の端末は非推奨です" continue statuspage = response.read().decode('shift-jis').encode('utf-8') message = re.search(r'<p class="mb20">([\s\S]+?)</p>',statuspage).group(1) message = re.sub(r'\s*',"",message) if message.find('シリアルナンバーに誤りがあります。ご確認ください。') != -1: result = u"シリアルナンバーに誤りがあります" break elif message.find('入力されたシリアルナンバーは、既に投票されています。') != -1: timestr = re.search(r'投票日時:\d{4}年\d{2}月\d{2}日\d{2}時\d{2}分\d{2}秒',message).group(0) result = timestr.decode("utf-8") break elif message.find('入力されたシリアルナンバーは無効であるか既に投票済みです。') != -1: result = u"入力されたシリアルナンバーは無効であるか既に投票済みです" break elif message.find('ご投票いただきありがとうございました。') != -1: result = u"ご投票いただきありがとうございました" proxy = 1 attempt = 1 continue else: result = message.decode("utf-8") break return (result,proxy) allfiles = os.listdir('./xls/') if len(allfiles) == 0: print "no tickets need to check" exit() if os.path.exists("./output/") == False: os.mkdir("./output/") for filename in allfiles: tickets = [] data = xlrd.open_workbook('./xls/' + filename) sheet1 = data.sheets()[0] rows = sheet1.nrows columns = sheet1.ncols offsetx = 0 offsety = 0 for
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">Через эту админку сотрудники сапорта работают с обращениями пользователей соц. сети. Мною была реализована вся верстка раздела и код на js.</div>' + '<div class="presentation_mb10">Особенности:</div>' + '<ul class="presentation-list">' + '<li>Интерфейс занимают всю высоту экрана монитора - резиновый по вертикали (На странице могут быть три внутреннии области со скролом );</li>' + '<li>Автоподгрузка новых тикетов;</li>' + '<li>Большое число кастомных элементов управления.</li>' + '</ul>' }, {img: 'i/works/ticket-admin2.png', description: '<div class="presentation_mb10"><strong>Админка массовых сбоев</strong></div>' + '<div class="presentation_mb10">Инструмент взаимодействия сотрудников сапорта и тестеровщиков. При наличие однотипных обращений пользователей, их тикеты групируются в массовый сбой. Который попадает к тестировщикам в виде таска в редмайн для исследования.</div>' }, {img: 'i/works/ticket-admin3.png', description: 'Диалог просмотра массового сбоя.'}, {img: 'i/works/ticket-admin4.png', description: 'Пример реализации кастомного выпадающего списка.'}, ] },{title: 'Отдел модерации \nПопапы жалоб, страница заблокированного пользователя', works: [ {img: 'i/works/complaint_popup.png', description: '<div class="presentation_mb10"><strong>Попап подачи жалоб на пользователя</strong></div>' + '<div class="">Мною была реализована вся frontend часть - верстка и код на js.</div>' },{img: 'i/works/abusePopups.jpg', description: '<div class="">Реализовано несколько кейсов с последовательной навигацией.</div>' },{img: 'i/works/complaint_popup1.png', description: '<div class="">Содержимое попапа - вопросник с готовыми ответами и возможностью отправить расширенное описание.</div>' }, {img: 'i/works/abuse_form.jpg', description: 'Различные варианты попапов жалоб на нарушения со стороны пользователей. Попапы показываются на странице пользователя.'}, {img: 'i/works/abuse_page.jpg', description: 'Страница заблокированного пользователя. Реализована в нескольких вариантах для удаленного пользователя и расширенной для сотрудников Фотостраны. Мною была реализована верстка (html/php).'}, ] },{title: 'Раздел помощи (FAQ)', works: [ {img: 'i/works/faq1.png', description: '<div class="presentation_mb10">В разделе помощи я занимался поддержкой старого кода, правил баги. Поэтому там моя верстка присутствует только фрагментами. К примеру этот опросник сверстан мной. Весь hover эффект при выборе количества звезд реализован только на css.</div>' + '<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/support/feedback/ask/" target="_blank">http://fotostrana.ru/support/feedback/ask/</a></div>'}, ] },{title: 'Раздел "Мои финансы"', works: [ {img: 'i/works/finroom.png', description: '<div class="presentation_mb10"><strong>Раздел "Мои финансы" страницы пользователя</strong></div>' + '<div class="presentation_mb10">Мною была реализована верстка и необходимый код на js.</div>' + '<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/finance/index/" target="_blank">http://fotostrana.ru/finance/index/</a></div>' }, {img: 'i/works/finroom2.png', description: '<div class="presentation_mb10">Для страницы было реализовано много различных блоков показываемые разным сегментам пользовательской аудитории.</div>'}, {img: 'i/works/finroom3.png', description: 'Так же мною были сверстаны различные попапы сопутсвующих премиальных услуг, доступные из этого раздела.'}, {img: 'i/works/autopay1.png', description: 'Попап услуги &laquo;Автоплатеж&raquo;'}, {img: 'i/works/fotocheck.png', description: 'СМС информирование'}, {img: 'i/works/finroom4.png', description: ''}, ] },{title: 'Финансовый попап \nПопап пополнения счета пользователя', works: [ {img: 'i/works/finpopup1.png', description: '<div class="presentation_mb10">Попап с большим количеством переходов и кастомными элементами управления.</div>' + '<div class="presentation_mb10">Мною была сделана необходимая верстка и js код.</div>' }, {img: 'i/works/finpopup2.png', description: '<div class="presentation_mb10">Из сложных деталей интерфейса:</div>' + '<ul class="presentation-list">' + '<li>"резиновые" кнопки ввода необходимой суммы Фотомани, с возможностью указать произвольную сумму;</li>' + '<li>контроль за вводом и валидация пользовательских данных.</li>' + '</ul>' }, {img: 'i/works/finpopup3.png', description: ''}, ] },{title: 'Сервис "Я модератор"', works: [ {img: 'i/works/imoderator1.jpg', description: '<div class="presentation_mb10"><strong>Сервис "Я модератор"</strong> - пользователям за вознаграждение передается часть модерируемого контента.</div>' + '<div class="">Мною была выполнена вся верстка и весь js код. Из сложных деталей интерфеса - флип часы, реализованные с использованием css3 animation.</div>' }, {img: 'i/works/imoderator2.jpg', description: '<div class="presentation_mb10">В приложении реализовано несколько режимов модерации, в том числе и полно экранный режим (резиновый, скрывающий стандартный лэйаут страниц соц. сети).</div>' + '<div class="">Так же в приложении реализованы инструменты для мотивации "качественной" оценки фотографий пользователями. Используются тестовые проверочные изображения, принудительная отправка в режим обучения и поиск дубликатов изображений в Google/Yandex.</div>' }, ] },{title: 'Сервис "Голосование"', works: [ {img: 'i/works/contest.jpg', description: '<div class="presentation_mb10"><strong>Сервис "Голосование"</strong> - один из основных по доходности сервисов Фотостраны с большой аудиторией</div>' + '<div class="presentation_mb10">В этом сервисе, я занимался поддержкой старого кода и версткой скидочных акций и сезонных мероприятий по активизации пользовательской активности приуроченные к праздникам, мероприятиям (Новый год, Олимпийские игры, 8-е марта, день всех влюбленных, 23 февраля, 12 апреля и др.)</div>' + '<div class="presentation_mb10">Так же мною был переделан механизм рендеринга фотостены.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/" target="_blank">www.fotostrana.ru/contest/</a></div>' }, {img: 'i/works/contest1.jpg', description: ''}, ] },{title: 'Игровой сервис "Битва кланов"', works: [ {img: 'i/works/clan1.jpg', description: '<div class="presentation_mb10"><strong>Игровой сервис "Битва Кланов"</strong> - игровой под сервис голосования. Игра в форме квеста.</div>' + '<div>В этом сервисе я делал верстку и js код. Много кейсов, много попапов, много backbon-а. Используется sass, require.js, backbone.</div>' }, {img: 'i/works/clan2.jpg', description: '<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/clan2/" target="_blank">www.fotostrana.ru/contest/clan2/</a></div>'}, {img: 'i/works/clan4.jpg', description: 'В сервисе много сложных интерфейсных решений, как на пример поле ввода сообщения в чат. Реализовано ограничение на длину вводимого сообщения и авторесайз высоты textarea.'}, {img: 'i/works/clan3.jpg', description: ''}, ] },{title: 'Сервис "Элитное голосование"', works: [ {img: 'i/works/elite1.jpg', description: '<div class="presentation_mb10"><strong>Игровой сервис "Элитное голосование"</strong> - игровой под сервис голосования, доступный несколько дней в месяце для активных участников основного голосования.</div>' + '<div>В этом сервисе я делал верстку и js код. Внешнее оформление переделывалось мною к каждому запуску сервиса.</div>'}, {img: 'i/works/elite2.jpg', description: ''}, ] },{title: 'Сервис "Люди"\nДейтинговый сервис Фотостраны', works: [ {img: 'i/works/people1.jpg', description: '<div class="presentation_mb10"><strong>Дейтинговый сервис "Люди"</strong> - на протяжении полу года поддерживал фронтенд сервиса - исправлял баги, верстал рекламные банеры и попапы.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/people/" target="_blank">fotostrana.ru/people/</a></div>'}, {img: 'i/works/people2.jpg', description: ''}, ] },{title: 'Сообщества и пиновый интерфейс', works: [ {img: 'i/works/community1.jpg', description: '<div class="presentation_mb10">Некоторое время работал над версткой сообществ и пиновым интерфейсом. Концепция пинов была позаимствована у другого сервиса Pinterest. Занимался проектом начиная с первого прототипа и до предрелизной подготовкой.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/public/" target="_blank">fotostrana.ru/public/</a></div>'}, ] },{title: 'Сайт http://www.blik-cleaning.ru/', works: [ {img: 'i/works/cleaning.jpg', description: '<div class="presentation_mb10"><strong>Разработка сайта клининговой компании</strong></div>' + '<div>Сайт сделан на CMS WordPress с оригинальной темой. </div>'}, {img: 'i/works/cleaning1.jpg', description: ''}, ] },{title: 'Сайт http://www.promalp.name/', works: [ {img: 'i/works/promalp1.jpg', description: '<div class="presentation_mb10"><strong>Сайт компании занимающейся промышленным альпинизмом.</strong></div>' + '<div>Сайт сделан на node.js (express). Полностью реализован мною.</div>'}, {img: 'i/works/promalp2.jpg', description: 'Страница с портфолио.'}, {img: 'i/works/promalp3.jpg', description: 'Форма заявки.'}, ] },{title: 'Расширение для браузера chrome Netmarks', works: [ {img: 'i/works/netmarks.jpg', description: '<div class="presentation_mb10"><strong>Chrome extension "NetMarks"</strong></div>' + '<div class="presentation_mb10">Расширение для удобной работы с браузерными закладками в виде выпадающего меню.</div>' + '<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/netmarks/boepmphdpbdnficfifejnkejlljcefjb" target="_blank">Chrome store</a></div>' }, ] },{title: 'Приложение для браузера chrome Deposit.calc', works: [ {img: 'i/works/depcalc1.jpg', description: '<div class="presentation_mb10"><strong>Deposit.calc</strong></div>' + '<div class="presentation_mb10">Приложение позволяющее расчитать доход по вкладу с пополнениями. Используется собственный оригинальный алгоритм расчета.</div>' + '<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/депозитный-калькулятор/cibblnjekngmoeiehohbkmcbfijpcjdj" target="_blank">Chrome store</a></div>'}, {img: 'i/works/depcalc2.jpg', description: 'Для вывода графиков был использован highcharts.'}, ] }, ]; var View = m3toolkit.View, CollectionView = m3toolkit.CollectionView, BlockView = m3toolkit.BlockView, _base = { // @param {Int} Index // @return {Model} model from collection by index getAnother: function(index){ return this.slideCollection.at(index); } }; var SlideModel = Backbone.Model.extend({ defaults: { title: '', works: [], index: undefined, next: undefined, prev: undefined } }); var SlidesCollection = Backbone.Collection.extend({ model: SlideModel, initialize: function(list){ var i = 0, len = list.length indexedList = list.map(function(item){ item.index = i; if(i > 0){ item.prev = i - 1; } if(i < len - 1){ item.next = i + 1; } if(Array.isArray(item.works)){ item.frontImage = item.works[0].img; } i++; return item; }); Backbone.Collection.prototype.initialize.call(this, indexedList); } }); var WorkItemModel = Backbone.Model.extend({ defaults: { img: '', description: '' } }); var WorkItemsCollections = Backbone.Collection.extend({ model: WorkItemModel }); var WorkItemPreview = View.extend({ className: 'presentation_work-item clearfix', template: _.template( '<img src="<%=img%>" class="Stretch m3-vertical "/>' + '<% if(obj.description){ %>' + '<div class="presentation_work-item_description"><%=obj.description%></div>' + '<% }%>' ) }); var SlideView = View.extend({ className: 'presentation_slide-wrap', template: _.template( '<div style="background-image: url(<%=obj.frontImage%>)" class="presentation_front-image"></div>' + '<div class="presentation_front-image_hover"></div>' ), events: { click: function(e){ _base.openFullScreenPresentation(this.model); } },
}); 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="presentation_fullscreen-slide_next" data-co="next">' + '<div class="presentation_fullscreen-slide_nav-btn presentation_fullscreen-slide_nav-btn_next "></div>' + '</div>' + '<div class="presentation_fullscreen-slide_prev" data-co="prev">' + '<div class="presentation_fullscreen-slide_nav-btn"></div>'+ '</div>' + '<pre class="presentation_fullscreen-slide_title" data-co="title"></pre>' + '<div class="" data-co="works" style=""></div>' + '</div>', events: { 'click [data-bind=close]': function(){ _base.hideFullScreenPresentation(); }, 'click [data-co=next]': function(){ var nextIndex = this.model.get('next'); nextIndex != undefined && this._navigateTo(nextIndex); }, 'click [data-co=prev]': function(){ var prevIndex = this.model.get('prev'); prevIndex != undefined && this._navigateTo(prevIndex); }, }, _navigateTo: function(index){ var prevModel =_base.getAnother(index); if(prevModel){ var data = prevModel.toJSON(); this.model.set(prevModel.toJSON()); } }, initialize: function(){ BlockView.prototype.initialize.call(this); this.controls.prev[this.model.get('prev') != undefined ? 'show': 'hide'](); this.controls.next[this.model.get('next') ? 'show': 'hide'](); var workItemsCollection = new WorkItemsCollections(this.model.get('works')); this.children.workCollection = new CollectionView({ collection: workItemsCollection, el: this.controls.works }, WorkItemPreview); this.listenTo(this.model, 'change:works', function(model){ console.log('Works Changed'); workItemsCollection.reset(model.get('works')); }); }, defineBindings: function(){ this._addComputed('works', 'works', function(control, model){ console.log('Refresh works'); var worksList = model.get('works'); console.dir(worksList); }); this._addTransform('title', function(control, model, value){ console.log('Set new Title: `%s`', value); control.text(value); }); this._addTransform('next', function(control, model, value){ control[value ? 'show': 'hide'](); }); this._addTransform('prev', function(control, model, value){ control[value != undefined ? 'show': 'hide'](); }); } }); var PresentationApp = View.extend({ className: 'presentation-wrap', template: '<div class="presentation-wrap_header">' + '<div class="presentation-wrap_header-container">' + '<div class="presentation-wrap_header-title clearfix">' + /*'<div class="presentation-wrap_header-contacts">' + '<div class="">Контакты для связи:</div>' + '<div class="">8 (960) 243 14 03</div>' + '<div class="">[email protected]</div>' + '</div>' +*/ '<h2 class="presentation_header1">Портфолио презентация</h2>' + '<div class="presentation_liter1">Фронтенд разработчика Николая Мальцева</div>' + '<div class="presentation_liter1">8 (960) 243 14 03, [email protected]</div>' + '<div class="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>' + '</div>' + '<div data-bind="fullscreen" class="presentation_fullscreen-slide" style="display: none;"></div>', initialize: function(){ View.prototype.initialize.call(this); var $slides = this.$('[data-bind=slides]'), $body = this.$('[data-bind=body]'), slideCollection = new SlidesCollection(slides); _base.app = this; _base.slideCollection = slideCollection; this.children['slides'] = new CollectionView({ collection: slideCollection, el: $slides }, SlideView); this.children['fullscreen'] = new FullscreenSlideView({ el: this.$('[data-bind=fullscreen]'), model: new SlideModel() }); _base.openFullScreenPresentation = function(model){ $body.addClass('presentation-fix-body'); this.children['fullscreen'].$el.show(); this.children['fullscreen'].model.set(model.toJSON()); // TODO store vertical position }.bind(this); _base.hideFullScreenPresentation = function(){ this.children['fullscreen'].$el.hide(); $body.removeClass('presentation-fix-body'); }.bind(this); } }); var app = new PresentationApp({ el: '#app' }); }());
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">Через эту админку сотрудники сапорта работают с обращениями пользователей соц. сети. Мною была реализована вся верстка раздела и код на js.</div>' + '<div class="presentation_mb10">Особенности:</div>' + '<ul class="presentation-list">' + '<li>Интерфейс занимают всю высоту экрана монитора - резиновый по вертикали (На странице могут быть три внутреннии области со скролом );</li>' + '<li>Автоподгрузка новых тикетов;</li>' + '<li>Большое число кастомных элементов управления.</li>' + '</ul>' }, {img: 'i/works/ticket-admin2.png', description: '<div class="presentation_mb10"><strong>Админка массовых сбоев</strong></div>' + '<div class="presentation_mb10">Инструмент взаимодействия сотрудников сапорта и тестеровщиков. При наличие однотипных обращений пользователей, их тикеты групируются в массовый сбой. Который попадает к тестировщикам в виде таска в редмайн для исследования.</div>' }, {img: 'i/works/ticket-admin3.png', description: 'Диалог просмотра массового сбоя.'}, {img: 'i/works/ticket-admin4.png', description: 'Пример реализации кастомного выпадающего списка.'}, ] },{title: 'Отдел модерации \nПопапы жалоб, страница заблокированного пользователя', works: [ {img: 'i/works/complaint_popup.png', description: '<div class="presentation_mb10"><strong>Попап подачи жалоб на пользователя</strong></div>' + '<div class="">Мною была реализована вся frontend часть - верстка и код на js.</div>' },{img: 'i/works/abusePopups.jpg', description: '<div class="">Реализовано несколько кейсов с последовательной навигацией.</div>' },{img: 'i/works/complaint_popup1.png', description: '<div class="">Содержимое попапа - вопросник с готовыми ответами и возможностью отправить расширенное описание.</div>' }, {img: 'i/works/abuse_form.jpg', description: 'Различные варианты попапов жалоб на нарушения со стороны пользователей. Попапы показываются на странице пользователя.'}, {img: 'i/works/abuse_page.jpg', description: 'Страница заблокированного пользователя. Реализована в нескольких вариантах для удаленного пользователя и расширенной для сотрудников Фотостраны. Мною была реализована верстка (html/php).'}, ] },{title: 'Раздел помощи (FAQ)', works: [ {img: 'i/works/faq1.png', description: '<div class="presentation_mb10">В разделе помощи я занимался поддержкой старого кода, правил баги. Поэтому там моя верстка присутствует только фрагментами. К примеру этот опросник сверстан мной. Весь hover эффект при выборе количества звезд реализован только на css.</div>' + '<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/support/feedback/ask/" target="_blank">http://fotostrana.ru/support/feedback/ask/</a></div>'}, ] },{title: 'Раздел "Мои финансы"', works: [ {img: 'i/works/finroom.png', description: '<div class="presentation_mb10"><strong>Раздел "Мои финансы" страницы пользователя</strong></div>' + '<div class="presentation_mb10">Мною была реализована верстка и необходимый код на js.</div>' + '<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/finance/index/" target="_blank">http://fotostrana.ru/finance/index/</a></div>' }, {img: 'i/works/finroom2.png', description: '<div class="presentation_mb10">Для страницы было реализовано много различных блоков показываемые разным сегментам пользовательской аудитории.</div>'}, {img: 'i/works/finroom3.png', description: 'Так же мною были сверстаны различные попапы сопутсвующих премиальных услуг, доступные из этого раздела.'}, {img: 'i/works/autopay1.png', description: 'Попап услуги &laquo;Автоплатеж&raquo;'}, {img: 'i/works/fotocheck.png', description: 'СМС информирование'}, {img: 'i/works/finroom4.png', description: ''}, ] },{title: 'Финансовый попап \nПопап пополнения счета пользователя', works: [ {img: 'i/works/finpopup1.png', description: '<div class="presentation_mb10">Попап с большим количеством переходов и кастомными элементами управления.</div>' + '<div class="presentation_mb10">Мною была сделана необходимая верстка и js код.</div>' }, {img: 'i/works/finpopup2.png', description: '<div class="presentation_mb10">Из сложных деталей интерфейса:</div>' + '<ul class="presentation-list">' + '<li>"резиновые" кнопки ввода необходимой суммы Фотомани, с возможностью указать произвольную сумму;</li>' + '<li>контроль за вводом и валидация пользовательских данных.</li>' + '</ul>' }, {img: 'i/works/finpopup3.png', description: ''}, ] },{title: 'Сервис "Я модератор"', works: [ {img: 'i/works/imoderator1.jpg', description: '<div class="presentation_mb10"><strong>Сервис "Я модератор"</strong> - пользователям за вознаграждение передается часть модерируемого контента.</div>' + '<div class="">Мною была выполнена вся верстка и весь js код. Из сложных деталей интерфеса - флип часы, реализованные с использованием css3 animation.</div>' }, {img: 'i/works/imoderator2.jpg', description: '<div class="presentation_mb10">В приложении реализовано несколько режимов модерации, в том числе и полно экранный режим (резиновый, скрывающий стандартный лэйаут страниц соц. сети).</div>' + '<div class="">Так же в приложении реализованы инструменты для мотивации "качественной" оценки фотографий пользователями. Используются тестовые проверочные изображения, принудительная отправка в режим обучения и поиск дубликатов изображений в Google/Yandex.</div>' }, ] },{title: 'Сервис "Голосование"', works: [ {img: 'i/works/contest.jpg', description: '<div class="presentation_mb10"><strong>Сервис "Голосование"</strong> - один из основных по доходности сервисов Фотостраны с большой аудиторией</div>' + '<div class="presentation_mb10">В этом сервисе, я занимался поддержкой старого кода и версткой скидочных акций и сезонных мероприятий по активизации пользовательской активности приуроченные к праздникам, мероприятиям (Новый год, Олимпийские игры, 8-е марта, день всех влюбленных, 23 февраля, 12 апреля и др.)</div>' + '<div class="presentation_mb10">Так же мною был переделан механизм рендеринга фотостены.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/" target="_blank">www.fotostrana.ru/contest/</a></div>' }, {img: 'i/works/contest1.jpg', description: ''}, ] },{title: 'Игровой сервис "Битва кланов"', works: [ {img: 'i/works/clan1.jpg', description: '<div class="presentation_mb10"><strong>Игровой сервис "Битва Кланов"</strong> - игровой под сервис голосования. Игра в форме квеста.</div>' + '<div>В этом сервисе я делал верстку и js код. Много кейсов, много попапов, много backbon-а. Используется sass, require.js, backbone.</div>' }, {img: 'i/works/clan2.jpg', description: '<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/clan2/" target="_blank">www.fotostrana.ru/contest/clan2/</a></div>'}, {img: 'i/works/clan4.jpg', description: 'В сервисе много сложных интерфейсных решений, как на пример поле ввода сообщения в чат. Реализовано ограничение на длину вводимого сообщения и авторесайз высоты textarea.'}, {img: 'i/works/clan3.jpg', description: ''}, ] },{title: 'Сервис "Элитное голосование"', works: [ {img: 'i/works/elite1.jpg', description: '<div class="presentation_mb10"><strong>Игровой сервис "Элитное голосование"</strong> - игровой под сервис голосования, доступный несколько дней в месяце для активных участников основного голосования.</div>' + '<div>В этом сервисе я делал верстку и js код. Внешнее оформление переделывалось мною к каждому запуску сервиса.</div>'}, {img: 'i/works/elite2.jpg', description: ''}, ] },{title: 'Сервис "Люди"\nДейтинговый сервис Фотостраны', works: [ {img: 'i/works/people1.jpg', description: '<div class="presentation_mb10"><strong>Дейтинговый сервис "Люди"</strong> - на протяжении полу года поддерживал фронтенд сервиса - исправлял баги, верстал рекламные банеры и попапы.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/people/" target="_blank">fotostrana.ru/people/</a></div>'}, {img: 'i/works/people2.jpg', description: ''}, ] },{title: 'Сообщества и пиновый интерфейс', works: [ {img: 'i/works/community1.jpg', description: '<div class="presentation_mb10">Некоторое время работал над версткой сообществ и пиновым интерфейсом. Концепция пинов была позаимствована у другого сервиса Pinterest. Занимался проектом начиная с первого прототипа и до предрелизной подготовкой.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/public/" target="_blank">fotostrana.ru/public/</a></div>'}, ] },{title: 'Сайт http://www.blik-cleaning.ru/', works: [ {img: 'i/works/cleaning.jpg', description: '<div class="presentation_mb10"><strong>Разработка сайта клининговой компании</strong></div>' + '<div>Сайт сделан на CMS WordPress с оригинальной темой. </div>'}, {img: 'i/works/cleaning1.jpg', description: ''}, ] },{title: 'Сайт http://www.promalp.name/', works: [ {img: 'i/works/promalp1.jpg', description: '<div class="presentation_mb10"><strong>Сайт компании занимающейся промышленным альпинизмом.</strong></div>' + '<div>Сайт сделан на node.js (express). Полностью реализован мною.</div>'}, {img: 'i/works/promalp2.jpg', description: 'Страница с портфолио.'}, {img: 'i/works/promalp3.jpg', description: 'Форма заявки.'}, ] },{title: 'Расширение для браузера chrome Netmarks', works: [ {img: 'i/works/netmarks.jpg', description: '<div class="presentation_mb10"><strong>Chrome extension "NetMarks"</strong></div>' + '<div class="presentation_mb10">Расширение для удобной работы с браузерными закладками в виде выпадающего меню.</div>' + '<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/netmarks/boepmphdpbdnficfifejnkejlljcefjb" target="_blank">Chrome store</a></div>' }, ] },{title: 'Приложение для браузера chrome Deposit.calc', works: [ {img: 'i/works/depcalc1.jpg', description: '<div class="presentation_mb10"><strong>Deposit.calc</strong></div>' + '<div class="presentation_mb10">Приложение позволяющее расчитать доход по вкладу с пополнениями. Используется собственный оригинальный алгоритм расчета.</div>' + '<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/депозитный-калькулятор/cibblnjekngmoeiehohbkmcbfijpcjdj" target="_blank">Chrome store</a></div>'}, {img: 'i/works/depcalc2.jpg', description: 'Для вывода графиков был использован highcharts.'}, ] }, ]; var View = m3toolkit.View, CollectionView = m3toolkit.CollectionView, BlockView = m3toolkit.BlockView, _base = { // @param {Int} Index // @return {Model} model from collection by index getAnother: function(index){ return this.slideCollection.at(index); } }; var SlideModel = Backbone.Model.extend({ defaults: { title: '', works: [], index: undefined, next: undefined, prev: undefined } }); var SlidesCollection = Backbone.Collection.extend({ model: SlideModel, initialize: function(list){ var i = 0, len = list.length indexedList = list.map(function(item){ item.index = i; if(i > 0){ item.prev = i - 1; } if(i < len - 1){ item.next = i + 1; } if(Array.isArray(item.works)){ item.frontImage = item.works[0].img; } i++; return item; }); Backbone.Collection.prototype.initialize.call(this, indexedList); } }); var WorkItemModel = Backbone.Model.extend({ defaults: { img: '', description: '' } }); var WorkItemsCollections = Backbone.Collection.extend({ model: WorkItemModel }); var WorkItemPreview = View.extend({ className: 'presentation_work-item clearfix', template: _.template( '<img src="<%=img%>" class="Stretch m3-vertical "/>' + '<% if(obj.description){ %>' + '<div class="presentation_work-item_description"><%=obj.description%></div>' + '<% }%>' ) }); var SlideView = View.extend({ className: 'presentation_slide-wrap', template: _.template( '<div style="background-image: url(<%=obj.frontImage%>)" class="presentation_front-image"></div>' + '<div class="presentation_front-image_hover"></div>' ), events: { click: function(e){ _base.openFullScreenPresentation(this.model); } }, }); 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="presentation_fullscreen-slide_next" data-co="next">' + '<div class="presentation_fullscreen-slide_nav-btn presentation_fullscreen-slide_nav-btn_next "></div>' + '</div>' + '<div class="presentation_fullscreen-slide_prev" data-co="prev">' + '<div class="presentation_fullscreen-slide_nav-btn"></div>'+ '</div>' + '<pre class="presentation_fullscreen-slide_title" data-co="title"></pre>' + '<div class="" data-co="works" style=""></div>' + '</div>', events: { 'click [data-bind=close]': function(){ _base.hideFullScreenPresentation(); }, 'click [data-co=next]': function(){ var nextIndex = this.model.get('next'); nextIndex != undefined && this._navigateTo(nextIndex); }, 'click [data-co=prev]': function(){ var prevIndex = this.model.get('prev'); prevIndex != undefined && this._navigateTo(prevIndex); }, }, _navigateTo: function(index){ var prevModel =_base.getAnother(index); if(prevModel){ var data = prevModel.toJSON(); this.model.set(prevModel.toJSON()); } }, initialize: function(){ BlockView.prototype.initialize.call(this); this.controls.prev[this.model.get('prev') != undefined ? 'show': 'hide'](); this.controls.next[this.model.get('next') ? 'show': 'hide'](); var workItemsCollection = new WorkItemsCollections(this.model.get('works')); this.children.workCollection = new CollectionView({ collection: workItemsCollection, el: this.controls.works }, WorkItemPreview); this.listenTo(this.model, 'change:works', function(model){ console.log('Works Changed'); workItemsCollection.reset(model.get('works')); }); }, defineBindings: function(){ this._addComputed('works', 'works', function(control, model){ console.log('Refresh works'); var worksList = model.get('works'); console.dir(worksList); }); this._addTransform('title', function(control, model, value){ console.log('Set new Title: `%s`', value); control.text(value); }); this._addTransform('next', function(control, model, value){ control[value ? 'show': 'hide'](); }); this._addTransform('prev', function(control, model, value){ control[value != undefined ? 'show': 'hide'](); }); } }); var PresentationApp = View.extend({ className: 'presentation-wrap', template: '<div class="presentation-wrap_header">' + '<div class="presentation-wrap_header-container">' + '<div class="presentation-wrap_header-title clearfix">' + /*'<div class="presentation-wrap_header-contacts">' + '<div class="">Контакты для связи:</div>' + '<div class="">8 (960) 243 14 03</div>' + '<div class="">[email protected]</div>' + '</div>' +*/ '<h2 class="presentation_header1">Портфолио презентация</h2>' + '<div class="presentation_liter1">Фронтенд разработчика Николая Мальцева</div>' + '<div class="presentation_liter1">8 (960) 243 14 03, ns
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>' + '</div>' + '<div data-bind="fullscreen" class="presentation_fullscreen-slide" style="display: none;"></div>', initialize: function(){ View.prototype.initialize.call(this); var $slides = this.$('[data-bind=slides]'), $body = this.$('[data-bind=body]'), slideCollection = new SlidesCollection(slides); _base.app = this; _base.slideCollection = slideCollection; this.children['slides'] = new CollectionView({ collection: slideCollection, el: $slides }, SlideView); this.children['fullscreen'] = new FullscreenSlideView({ el: this.$('[data-bind=fullscreen]'), model: new SlideModel() }); _base.openFullScreenPresentation = function(model){ $body.addClass('presentation-fix-body'); this.children['fullscreen'].$el.show(); this.children['fullscreen'].model.set(model.toJSON()); // TODO store vertical position }.bind(this); _base.hideFullScreenPresentation = function(){ this.children['fullscreen'].$el.hide(); $body.removeClass('presentation-fix-body'); }.bind(this); } }); var app = new PresentationApp({ el: '#app' }); }());
[email protected]</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_password', 'password') 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): 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): # try: self.driver.get(self.live_server_url) self.driver.find_element_by_link_text("Login").click() form = self.driver.find_element_by_tag_name("form") username_field = self.driver.find_element_by_id("id_username") username_field.send_keys("Bob") password_field = self.driver.find_element_by_id("id_password") password_field.send_keys("password") form.submit() self.assertIn('Bob', self.driver.page_source) self.assertIn('Library', self.driver.page_source) self.assertIn('Stream', self.driver.page_source) self.assertIn('Log out', self.driver.page_source) # user now logs off, a thoroughly satisfied user. self.driver.find_element_by_link_text("Log out").click() self.assertIn('Logged out', self.driver.page_source) # except Exception as e: # self.driver.save_screenshot('SCREEN_DUMP_LOCATION.png') # raise e def test_login_unauthorized_user(self): self.driver.get(self.live_server_url) self.driver.find_element_by_link_text("Login").click() form = self.driver.find_element_by_tag_name("form") username_field = self.driver.find_element_by_id("id_username") username_field.send_keys("Not a user") password_field = self.driver.find_element_by_id("id_password") password_field.send_keys("fake password") form.submit() self.assertIn('Please enter a correct username and password', self.driver.page_source) def test_random_image(self): self.driver.get(self.live_server_url) self.assertIn('default_stock_photo', self.driver.page_source)
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.django.DjangoModelFactory): class Meta: model = User django_get_or_create = ('username',) username = 'Bob' password = factory.PostGenerationMethodCall('set_password', 'password') class TestLogin(LiveServerTestCase): def setUp(self): self.driver = webdriver.Firefox() super(TestLogin, self).setUp() self.bob = UserFactory.create() def
(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): # try: self.driver.get(self.live_server_url) self.driver.find_element_by_link_text("Login").click() form = self.driver.find_element_by_tag_name("form") username_field = self.driver.find_element_by_id("id_username") username_field.send_keys("Bob") password_field = self.driver.find_element_by_id("id_password") password_field.send_keys("password") form.submit() self.assertIn('Bob', self.driver.page_source) self.assertIn('Library', self.driver.page_source) self.assertIn('Stream', self.driver.page_source) self.assertIn('Log out', self.driver.page_source) # user now logs off, a thoroughly satisfied user. self.driver.find_element_by_link_text("Log out").click() self.assertIn('Logged out', self.driver.page_source) # except Exception as e: # self.driver.save_screenshot('SCREEN_DUMP_LOCATION.png') # raise e def test_login_unauthorized_user(self): self.driver.get(self.live_server_url) self.driver.find_element_by_link_text("Login").click() form = self.driver.find_element_by_tag_name("form") username_field = self.driver.find_element_by_id("id_username") username_field.send_keys("Not a user") password_field = self.driver.find_element_by_id("id_password") password_field.send_keys("fake password") form.submit() self.assertIn('Please enter a correct username and password', self.driver.page_source) def test_random_image(self): self.driver.get(self.live_server_url) self.assertIn('default_stock_photo', self.driver.page_source)
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.django.DjangoModelFactory):
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): 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): # try: self.driver.get(self.live_server_url) self.driver.find_element_by_link_text("Login").click() form = self.driver.find_element_by_tag_name("form") username_field = self.driver.find_element_by_id("id_username") username_field.send_keys("Bob") password_field = self.driver.find_element_by_id("id_password") password_field.send_keys("password") form.submit() self.assertIn('Bob', self.driver.page_source) self.assertIn('Library', self.driver.page_source) self.assertIn('Stream', self.driver.page_source) self.assertIn('Log out', self.driver.page_source) # user now logs off, a thoroughly satisfied user. self.driver.find_element_by_link_text("Log out").click() self.assertIn('Logged out', self.driver.page_source) # except Exception as e: # self.driver.save_screenshot('SCREEN_DUMP_LOCATION.png') # raise e def test_login_unauthorized_user(self): self.driver.get(self.live_server_url) self.driver.find_element_by_link_text("Login").click() form = self.driver.find_element_by_tag_name("form") username_field = self.driver.find_element_by_id("id_username") username_field.send_keys("Not a user") password_field = self.driver.find_element_by_id("id_password") password_field.send_keys("fake password") form.submit() self.assertIn('Please enter a correct username and password', self.driver.page_source) def test_random_image(self): self.driver.get(self.live_server_url) self.assertIn('default_stock_photo', self.driver.page_source)
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 static VIC_INTENABLE: *mut u32 = (0x10140000 + 0x010) as *mut u32; pub static mut CURSOR_X: u32 = 0; pub static mut CURSOR_Y: u32 = 0; pub static CURSOR_HEIGHT: u32 = 16; pub static CURSOR_WIDTH: u32 = 8; pub static mut CURSOR_COLOR: u32 = 0x000000FF; pub static mut FG_COLOR: u32 = 0x00FFFFFF; pub static mut BG_COLOR: u32 = 0xF0000000; pub static mut CURSOR_BUFFER: [u32, ..8*16] = [0x00FF0000, ..8*16]; pub static mut SAVE_X: u32 = 0; pub static mut SAVE_Y: u32 = 0; pub static START_ADDR: u32 = 1024*1024; pub static mut SCREEN_WIDTH: u32 = 0; pub static mut SCREEN_HEIGHT: u32 = 0; pub unsafe fn init(width: u32, height: u32) { 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_WIDTH == 800 && SCREEN_HEIGHT == 600) { ws(0x10000010, 0x2CAC); ws(0x10120000, 0x1313A4C4); ws(0x10120004, 0x0505F657); ws(0x10120008, 0x071F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } // 640x480 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html else if (SCREEN_WIDTH == 640 && SCREEN_HEIGHT == 480) { ws(0x10000010, 0x2C77); ws(0x10120000, 0x3F1F3F9C); ws(0x10120004, 0x090B61DF); ws(0x10120008, 0x067F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } set_bg(0x000000); set_fg(0xFAFCFF); set_cursor_color(0xFAFCFF); fill_bg(); sgash::drawstr(&"sgash> "); draw_cursor(); } 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*(SCREEN_WIDTH*SCREEN_HEIGHT - CURSOR_HEIGHT*SCREEN_WIDTH); while i < 4*SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR + (i as u32)) as *mut u32) = BG_COLOR; i += 4; } CURSOR_X = 0x0u32; CURSOR_Y -= CURSOR_HEIGHT; } pub unsafe fn draw_char(c: char) { if CURSOR_X+(SCREEN_WIDTH*CURSOR_Y) >= SCREEN_WIDTH*SCREEN_HEIGHT { scrollup(); } 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*(CURSOR_X + CURSOR_WIDTH - i + SCREEN_WIDTH*(CURSOR_Y + j)); //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + SCREEN_WIDTH*CURSOR_Y) - 4*i + 4*SCREEN_WIDTH*j if ((map[j] >> 4*i) & 1) == 1 { *(addr as *mut u32) = FG_COLOR; } else { *(addr as *mut u32) = BG_COLOR; } addr+= 4; i += 1; } addr -= 4*(SCREEN_WIDTH+i); i = 0; j += 1; } } pub unsafe fn backup() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); CURSOR_BUFFER[i + j*8] = *(addr as *mut u32); i += 1; } i = 0; j += 1; } SAVE_X = CURSOR_X; SAVE_Y = CURSOR_Y; } pub unsafe fn restore() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(SAVE_X + i + SCREEN_WIDTH*(SAVE_Y + j)); *(addr as *mut u32) = CURSOR_BUFFER[i + j*8]; i += 1; } i = 0; j += 1; } } pub unsafe fn draw_cursor() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); *(addr as *mut u32) = CURSOR_COLOR; i += 1; } i = 0; j += 1; } } pub unsafe fn paint(color: u32) { let mut i = 0; 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) | value; } #[allow(dead_code)] pub unsafe fn
(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 static VIC_INTENABLE: *mut u32 = (0x10140000 + 0x010) as *mut u32; pub static mut CURSOR_X: u32 = 0; pub static mut CURSOR_Y: u32 = 0; pub static CURSOR_HEIGHT: u32 = 16; pub static CURSOR_WIDTH: u32 = 8; pub static mut CURSOR_COLOR: u32 = 0x000000FF; pub static mut FG_COLOR: u32 = 0x00FFFFFF; pub static mut BG_COLOR: u32 = 0xF0000000; pub static mut CURSOR_BUFFER: [u32, ..8*16] = [0x00FF0000, ..8*16]; pub static mut SAVE_X: u32 = 0; pub static mut SAVE_Y: u32 = 0; pub static START_ADDR: u32 = 1024*1024; pub static mut SCREEN_WIDTH: u32 = 0; pub static mut SCREEN_HEIGHT: u32 = 0; pub unsafe fn init(width: u32, height: u32) { 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_WIDTH == 800 && SCREEN_HEIGHT == 600) { ws(0x10000010, 0x2CAC); ws(0x10120000, 0x1313A4C4); ws(0x10120004, 0x0505F657); ws(0x10120008, 0x071F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } // 640x480 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html else if (SCREEN_WIDTH == 640 && SCREEN_HEIGHT == 480) { ws(0x10000010, 0x2C77); ws(0x10120000, 0x3F1F3F9C); ws(0x10120004, 0x090B61DF); ws(0x10120008, 0x067F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } set_bg(0x000000); set_fg(0xFAFCFF); set_cursor_color(0xFAFCFF); fill_bg(); sgash::drawstr(&"sgash> "); draw_cursor(); } 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*(SCREEN_WIDTH*SCREEN_HEIGHT - CURSOR_HEIGHT*SCREEN_WIDTH); while i < 4*SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR + (i as u32)) as *mut u32) = BG_COLOR; i += 4; } CURSOR_X = 0x0u32; CURSOR_Y -= CURSOR_HEIGHT; } pub unsafe fn draw_char(c: char) { if CURSOR_X+(SCREEN_WIDTH*CURSOR_Y) >= SCREEN_WIDTH*SCREEN_HEIGHT { scrollup(); } 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*(CURSOR_X + CURSOR_WIDTH - i + SCREEN_WIDTH*(CURSOR_Y + j)); //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + SCREEN_WIDTH*CURSOR_Y) - 4*i + 4*SCREEN_WIDTH*j if ((map[j] >> 4*i) & 1) == 1 { *(addr as *mut u32) = FG_COLOR; } else { *(addr as *mut u32) = BG_COLOR; } addr+= 4; i += 1; } addr -= 4*(SCREEN_WIDTH+i); i = 0; j += 1; } } pub unsafe fn backup() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); CURSOR_BUFFER[i + j*8] = *(addr as *mut u32); i += 1; } i = 0; j += 1; } SAVE_X = CURSOR_X; SAVE_Y = CURSOR_Y; } pub unsafe fn restore() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(SAVE_X + i + SCREEN_WIDTH*(SAVE_Y + j)); *(addr as *mut u32) = CURSOR_BUFFER[i + j*8]; i += 1; } i = 0; j += 1; } } pub unsafe fn draw_cursor() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); *(addr as *mut u32) = CURSOR_COLOR; i += 1; } i = 0; j += 1; } }
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) | value; } #[allow(dead_code)] pub unsafe fn wh(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; }
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 static VIC_INTENABLE: *mut u32 = (0x10140000 + 0x010) as *mut u32; pub static mut CURSOR_X: u32 = 0; pub static mut CURSOR_Y: u32 = 0; pub static CURSOR_HEIGHT: u32 = 16; pub static CURSOR_WIDTH: u32 = 8; pub static mut CURSOR_COLOR: u32 = 0x000000FF; pub static mut FG_COLOR: u32 = 0x00FFFFFF; pub static mut BG_COLOR: u32 = 0xF0000000; pub static mut CURSOR_BUFFER: [u32, ..8*16] = [0x00FF0000, ..8*16]; pub static mut SAVE_X: u32 = 0; pub static mut SAVE_Y: u32 = 0; pub static START_ADDR: u32 = 1024*1024; pub static mut SCREEN_WIDTH: u32 = 0; pub static mut SCREEN_HEIGHT: u32 = 0; pub unsafe fn init(width: u32, height: u32) { 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_WIDTH == 800 && SCREEN_HEIGHT == 600) { ws(0x10000010, 0x2CAC); ws(0x10120000, 0x1313A4C4); ws(0x10120004, 0x0505F657); ws(0x10120008, 0x071F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } // 640x480 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html else if (SCREEN_WIDTH == 640 && SCREEN_HEIGHT == 480) { ws(0x10000010, 0x2C77); ws(0x10120000, 0x3F1F3F9C); ws(0x10120004, 0x090B61DF); ws(0x10120008, 0x067F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } set_bg(0x000000); set_fg(0xFAFCFF); set_cursor_color(0xFAFCFF); fill_bg(); sgash::drawstr(&"sgash> "); draw_cursor(); } 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*(SCREEN_WIDTH*SCREEN_HEIGHT - CURSOR_HEIGHT*SCREEN_WIDTH); while i < 4*SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR + (i as u32)) as *mut u32) = BG_COLOR; i += 4; } CURSOR_X = 0x0u32; CURSOR_Y -= CURSOR_HEIGHT; } pub unsafe fn draw_char(c: char) { if CURSOR_X+(SCREEN_WIDTH*CURSOR_Y) >= SCREEN_WIDTH*SCREEN_HEIGHT
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*(CURSOR_X + CURSOR_WIDTH - i + SCREEN_WIDTH*(CURSOR_Y + j)); //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + SCREEN_WIDTH*CURSOR_Y) - 4*i + 4*SCREEN_WIDTH*j if ((map[j] >> 4*i) & 1) == 1 { *(addr as *mut u32) = FG_COLOR; } else { *(addr as *mut u32) = BG_COLOR; } addr+= 4; i += 1; } addr -= 4*(SCREEN_WIDTH+i); i = 0; j += 1; } } pub unsafe fn backup() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); CURSOR_BUFFER[i + j*8] = *(addr as *mut u32); i += 1; } i = 0; j += 1; } SAVE_X = CURSOR_X; SAVE_Y = CURSOR_Y; } pub unsafe fn restore() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(SAVE_X + i + SCREEN_WIDTH*(SAVE_Y + j)); *(addr as *mut u32) = CURSOR_BUFFER[i + j*8]; i += 1; } i = 0; j += 1; } } pub unsafe fn draw_cursor() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); *(addr as *mut u32) = CURSOR_COLOR; i += 1; } i = 0; j += 1; } } pub unsafe fn paint(color: u32) { let mut i = 0; 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) | value; } #[allow(dead_code)] pub unsafe fn wh(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; }
{ 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 static VIC_INTENABLE: *mut u32 = (0x10140000 + 0x010) as *mut u32; pub static mut CURSOR_X: u32 = 0; pub static mut CURSOR_Y: u32 = 0; pub static CURSOR_HEIGHT: u32 = 16; pub static CURSOR_WIDTH: u32 = 8; pub static mut CURSOR_COLOR: u32 = 0x000000FF; pub static mut FG_COLOR: u32 = 0x00FFFFFF; pub static mut BG_COLOR: u32 = 0xF0000000; pub static mut CURSOR_BUFFER: [u32, ..8*16] = [0x00FF0000, ..8*16]; pub static mut SAVE_X: u32 = 0; pub static mut SAVE_Y: u32 = 0; pub static START_ADDR: u32 = 1024*1024; pub static mut SCREEN_WIDTH: u32 = 0; pub static mut SCREEN_HEIGHT: u32 = 0; pub unsafe fn init(width: u32, height: u32)
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*(SCREEN_WIDTH*SCREEN_HEIGHT - CURSOR_HEIGHT*SCREEN_WIDTH); while i < 4*SCREEN_WIDTH*SCREEN_HEIGHT { *((START_ADDR + (i as u32)) as *mut u32) = BG_COLOR; i += 4; } CURSOR_X = 0x0u32; CURSOR_Y -= CURSOR_HEIGHT; } pub unsafe fn draw_char(c: char) { if CURSOR_X+(SCREEN_WIDTH*CURSOR_Y) >= SCREEN_WIDTH*SCREEN_HEIGHT { scrollup(); } 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*(CURSOR_X + CURSOR_WIDTH - i + SCREEN_WIDTH*(CURSOR_Y + j)); //let addr = START_ADDR + 4*(CURSOR_X + CURSOR_WIDTH + SCREEN_WIDTH*CURSOR_Y) - 4*i + 4*SCREEN_WIDTH*j if ((map[j] >> 4*i) & 1) == 1 { *(addr as *mut u32) = FG_COLOR; } else { *(addr as *mut u32) = BG_COLOR; } addr+= 4; i += 1; } addr -= 4*(SCREEN_WIDTH+i); i = 0; j += 1; } } pub unsafe fn backup() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); CURSOR_BUFFER[i + j*8] = *(addr as *mut u32); i += 1; } i = 0; j += 1; } SAVE_X = CURSOR_X; SAVE_Y = CURSOR_Y; } pub unsafe fn restore() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(SAVE_X + i + SCREEN_WIDTH*(SAVE_Y + j)); *(addr as *mut u32) = CURSOR_BUFFER[i + j*8]; i += 1; } i = 0; j += 1; } } pub unsafe fn draw_cursor() { let mut i = 0; let mut j = 0; while j < CURSOR_HEIGHT { while i < CURSOR_WIDTH { let addr = START_ADDR + 4*(CURSOR_X + i + SCREEN_WIDTH*(CURSOR_Y + j)); *(addr as *mut u32) = CURSOR_COLOR; i += 1; } i = 0; j += 1; } } pub unsafe fn paint(color: u32) { let mut i = 0; 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) | value; } #[allow(dead_code)] pub unsafe fn wh(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; }
{ 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_WIDTH == 800 && SCREEN_HEIGHT == 600) { ws(0x10000010, 0x2CAC); ws(0x10120000, 0x1313A4C4); ws(0x10120004, 0x0505F657); ws(0x10120008, 0x071F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } // 640x480 // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/CACCCFBF.html else if (SCREEN_WIDTH == 640 && SCREEN_HEIGHT == 480) { ws(0x10000010, 0x2C77); ws(0x10120000, 0x3F1F3F9C); ws(0x10120004, 0x090B61DF); ws(0x10120008, 0x067F1800); /* See http://forum.osdev.org/viewtopic.php?p=195000 */ ws(0x10120010, START_ADDR); /* See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0161e/I911024.html */ ws(0x10120018, 0x82B); } set_bg(0x000000); set_fg(0xFAFCFF); set_cursor_color(0xFAFCFF); fill_bg(); sgash::drawstr(&"sgash> "); draw_cursor(); }
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 = Engine(dirs=[TEMPLATE_DIR]) def test_basic_context(self): 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.html') self.assertEqual(template.origin.template_name, 'index.html') def test_loader_priority(self): """ #21460 -- Check that the order of template loader works. """ loaders = [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') def test_cached_loader_priority(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', ]), ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n')
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 = Engine(dirs=[TEMPLATE_DIR]) def test_basic_context(self): 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.html') self.assertEqual(template.origin.template_name, 'index.html') def test_loader_priority(self): """ #21460 -- Check that the order of template loader works. """ loaders = [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') def
(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', ]), ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n')
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 = Engine(dirs=[TEMPLATE_DIR]) def test_basic_context(self):
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.html') self.assertEqual(template.origin.template_name, 'index.html') def test_loader_priority(self): """ #21460 -- Check that the order of template loader works. """ loaders = [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') def test_cached_loader_priority(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', ]), ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n')
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 GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import os import glob from distutils.core import setup import py2exe def datas(): r = [] if os.name == 'nt':
return r setup(service=["OpenERPServerService"], options={"py2exe":{"excludes":["Tkconstants","Tkinter","tcl", "_imagingtk","PIL._imagingtk", "ImageTk", "PIL.ImageTk", "FixTk"], "skip_archive": 1, "optimize": 2,}}, data_files=datas(), ) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
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 GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import os import glob from distutils.core import setup import py2exe def datas():
setup(service=["OpenERPServerService"], options={"py2exe":{"excludes":["Tkconstants","Tkinter","tcl", "_imagingtk","PIL._imagingtk", "ImageTk", "PIL.ImageTk", "FixTk"], "skip_archive": 1, "optimize": 2,}}, data_files=datas(), ) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
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 GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import os import glob from distutils.core import setup import py2exe
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", "ImageTk", "PIL.ImageTk", "FixTk"], "skip_archive": 1, "optimize": 2,}}, data_files=datas(), ) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
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 GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import os import glob from distutils.core import setup import py2exe def
(): 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", "ImageTk", "PIL.ImageTk", "FixTk"], "skip_archive": 1, "optimize": 2,}}, data_files=datas(), ) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
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' import { BaseChooseBranchDialog } from './base-choose-branch-dialog' export abstract class RebaseChooseBranchDialog extends BaseChooseBranchDialog { private rebasePreview: RebasePreview | null = null protected start = () => { const { selectedBranch } = this.state const { repository, currentBranch } = this.props if (!selectedBranch) { return } if ( this.rebasePreview === null || this.rebasePreview.kind !== ComputedAction.Clean ) { return } if (!this.canStart()) { return } this.props.dispatcher.startRebase( repository, selectedBranch, currentBranch, this.rebasePreview.commits ) } protected canStart = (): boolean => { return ( this.state.selectedBranch !== null && !this.selectedBranchIsCurrentBranch() && this.selectedBranchIsAheadOfCurrentBranch() ) } private
() { const currentBranch = this.props.currentBranch const { selectedBranch } = this.state return ( selectedBranch !== null && currentBranch !== null && selectedBranch.name === currentBranch.name ) } private selectedBranchIsAheadOfCurrentBranch() { return this.rebasePreview !== null && this.rebasePreview.kind === ComputedAction.Clean ? this.rebasePreview.commits.length > 0 : false } protected getSubmitButtonToolTip = () => { return this.selectedBranchIsCurrentBranch() ? 'You are not able to rebase this branch onto itself' : !this.selectedBranchIsAheadOfCurrentBranch() ? 'There are no commits on the current branch to rebase' : undefined } protected getDialogTitle = (branchName: string) => { return ( <> Rebase <strong>{branchName}</strong> </> ) } protected renderActionStatusIcon = () => { return ( <ActionStatusIcon status={this.rebasePreview} classNamePrefix="merge-status" /> ) } protected updateStatus = async (baseBranch: Branch) => { const { currentBranch: targetBranch, repository } = this.props updateRebasePreview(baseBranch, targetBranch, repository, rebasePreview => { this.rebasePreview = rebasePreview this.updateRebaseStatusPreview(baseBranch) }) } private updateRebaseStatusPreview(baseBranch: Branch) { this.setState({ statusPreview: this.getRebaseStatusPreview(baseBranch) }) } private getRebaseStatusPreview(baseBranch: Branch): JSX.Element | null { if (this.rebasePreview == null) { return null } const { currentBranch } = this.props if (this.rebasePreview.kind === ComputedAction.Loading) { return this.renderLoadingRebaseMessage() } if (this.rebasePreview.kind === ComputedAction.Clean) { return this.renderCleanRebaseMessage( currentBranch, baseBranch, this.rebasePreview.commits.length ) } 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 rebase. Check you have chosen a valid branch.</> } private renderCleanRebaseMessage( currentBranch: Branch, baseBranch: Branch, commitsToRebase: number ) { if (commitsToRebase <= 0) { return ( <> This branch is up to date with{` `} <strong>{currentBranch.name}</strong> </> ) } const pluralized = commitsToRebase === 1 ? 'commit' : 'commits' return ( <> This will update <strong>{currentBranch.name}</strong> {` by applying its `} <strong>{` ${commitsToRebase} ${pluralized}`}</strong> {` on top of `} <strong>{baseBranch.name}</strong> </> ) } }
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' import { BaseChooseBranchDialog } from './base-choose-branch-dialog' export abstract class RebaseChooseBranchDialog extends BaseChooseBranchDialog { private rebasePreview: RebasePreview | null = null protected start = () => { const { selectedBranch } = this.state const { repository, currentBranch } = this.props if (!selectedBranch) { return } if ( this.rebasePreview === null || this.rebasePreview.kind !== ComputedAction.Clean ) { return } if (!this.canStart()) { return } this.props.dispatcher.startRebase( repository, selectedBranch, currentBranch, this.rebasePreview.commits ) } protected canStart = (): boolean => { return ( this.state.selectedBranch !== null && !this.selectedBranchIsCurrentBranch() && this.selectedBranchIsAheadOfCurrentBranch() ) } private selectedBranchIsCurrentBranch() { const currentBranch = this.props.currentBranch const { selectedBranch } = this.state return ( selectedBranch !== null && currentBranch !== null && selectedBranch.name === currentBranch.name ) } private selectedBranchIsAheadOfCurrentBranch() { return this.rebasePreview !== null && this.rebasePreview.kind === ComputedAction.Clean ? this.rebasePreview.commits.length > 0 : false } protected getSubmitButtonToolTip = () => { return this.selectedBranchIsCurrentBranch() ? 'You are not able to rebase this branch onto itself' : !this.selectedBranchIsAheadOfCurrentBranch() ? 'There are no commits on the current branch to rebase' : undefined } protected getDialogTitle = (branchName: string) => { return ( <> Rebase <strong>{branchName}</strong> </> ) } protected renderActionStatusIcon = () => { return ( <ActionStatusIcon status={this.rebasePreview} classNamePrefix="merge-status" /> ) } protected updateStatus = async (baseBranch: Branch) => { const { currentBranch: targetBranch, repository } = this.props updateRebasePreview(baseBranch, targetBranch, repository, rebasePreview => { this.rebasePreview = rebasePreview this.updateRebaseStatusPreview(baseBranch) }) } private updateRebaseStatusPreview(baseBranch: Branch) { this.setState({ statusPreview: this.getRebaseStatusPreview(baseBranch) }) } private getRebaseStatusPreview(baseBranch: Branch): JSX.Element | null { if (this.rebasePreview == null) { return null } const { currentBranch } = this.props if (this.rebasePreview.kind === ComputedAction.Loading) { return this.renderLoadingRebaseMessage() } if (this.rebasePreview.kind === ComputedAction.Clean)
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 rebase. Check you have chosen a valid branch.</> } private renderCleanRebaseMessage( currentBranch: Branch, baseBranch: Branch, commitsToRebase: number ) { if (commitsToRebase <= 0) { return ( <> This branch is up to date with{` `} <strong>{currentBranch.name}</strong> </> ) } const pluralized = commitsToRebase === 1 ? 'commit' : 'commits' return ( <> This will update <strong>{currentBranch.name}</strong> {` by applying its `} <strong>{` ${commitsToRebase} ${pluralized}`}</strong> {` on top of `} <strong>{baseBranch.name}</strong> </> ) } }
{ 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' import { BaseChooseBranchDialog } from './base-choose-branch-dialog' export abstract class RebaseChooseBranchDialog extends BaseChooseBranchDialog { private rebasePreview: RebasePreview | null = null protected start = () => { const { selectedBranch } = this.state const { repository, currentBranch } = this.props if (!selectedBranch) { return } if ( this.rebasePreview === null || this.rebasePreview.kind !== ComputedAction.Clean ) { return } if (!this.canStart()) { return } this.props.dispatcher.startRebase( repository, selectedBranch, currentBranch, this.rebasePreview.commits ) } protected canStart = (): boolean => { return ( this.state.selectedBranch !== null && !this.selectedBranchIsCurrentBranch() && this.selectedBranchIsAheadOfCurrentBranch() ) } private selectedBranchIsCurrentBranch() { const currentBranch = this.props.currentBranch const { selectedBranch } = this.state return ( selectedBranch !== null && currentBranch !== null && selectedBranch.name === currentBranch.name ) } private selectedBranchIsAheadOfCurrentBranch() { return this.rebasePreview !== null && this.rebasePreview.kind === ComputedAction.Clean ? this.rebasePreview.commits.length > 0 : false } protected getSubmitButtonToolTip = () => { return this.selectedBranchIsCurrentBranch() ? 'You are not able to rebase this branch onto itself' : !this.selectedBranchIsAheadOfCurrentBranch() ? 'There are no commits on the current branch to rebase' : undefined } protected getDialogTitle = (branchName: string) => { return ( <> Rebase <strong>{branchName}</strong> </> ) } protected renderActionStatusIcon = () => { return ( <ActionStatusIcon status={this.rebasePreview} classNamePrefix="merge-status" /> ) } protected updateStatus = async (baseBranch: Branch) => { const { currentBranch: targetBranch, repository } = this.props updateRebasePreview(baseBranch, targetBranch, repository, rebasePreview => { this.rebasePreview = rebasePreview this.updateRebaseStatusPreview(baseBranch) }) } private updateRebaseStatusPreview(baseBranch: Branch) { this.setState({ statusPreview: this.getRebaseStatusPreview(baseBranch) }) } private getRebaseStatusPreview(baseBranch: Branch): JSX.Element | null { if (this.rebasePreview == null) { return null
} const { currentBranch } = this.props if (this.rebasePreview.kind === ComputedAction.Loading) { return this.renderLoadingRebaseMessage() } if (this.rebasePreview.kind === ComputedAction.Clean) { return this.renderCleanRebaseMessage( currentBranch, baseBranch, this.rebasePreview.commits.length ) } 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 rebase. Check you have chosen a valid branch.</> } private renderCleanRebaseMessage( currentBranch: Branch, baseBranch: Branch, commitsToRebase: number ) { if (commitsToRebase <= 0) { return ( <> This branch is up to date with{` `} <strong>{currentBranch.name}</strong> </> ) } const pluralized = commitsToRebase === 1 ? 'commit' : 'commits' return ( <> This will update <strong>{currentBranch.name}</strong> {` by applying its `} <strong>{` ${commitsToRebase} ${pluralized}`}</strong> {` on top of `} <strong>{baseBranch.name}</strong> </> ) } }
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' import { BaseChooseBranchDialog } from './base-choose-branch-dialog' export abstract class RebaseChooseBranchDialog extends BaseChooseBranchDialog { private rebasePreview: RebasePreview | null = null protected start = () => { const { selectedBranch } = this.state const { repository, currentBranch } = this.props if (!selectedBranch) { return } if ( this.rebasePreview === null || this.rebasePreview.kind !== ComputedAction.Clean ) { return } if (!this.canStart())
this.props.dispatcher.startRebase( repository, selectedBranch, currentBranch, this.rebasePreview.commits ) } protected canStart = (): boolean => { return ( this.state.selectedBranch !== null && !this.selectedBranchIsCurrentBranch() && this.selectedBranchIsAheadOfCurrentBranch() ) } private selectedBranchIsCurrentBranch() { const currentBranch = this.props.currentBranch const { selectedBranch } = this.state return ( selectedBranch !== null && currentBranch !== null && selectedBranch.name === currentBranch.name ) } private selectedBranchIsAheadOfCurrentBranch() { return this.rebasePreview !== null && this.rebasePreview.kind === ComputedAction.Clean ? this.rebasePreview.commits.length > 0 : false } protected getSubmitButtonToolTip = () => { return this.selectedBranchIsCurrentBranch() ? 'You are not able to rebase this branch onto itself' : !this.selectedBranchIsAheadOfCurrentBranch() ? 'There are no commits on the current branch to rebase' : undefined } protected getDialogTitle = (branchName: string) => { return ( <> Rebase <strong>{branchName}</strong> </> ) } protected renderActionStatusIcon = () => { return ( <ActionStatusIcon status={this.rebasePreview} classNamePrefix="merge-status" /> ) } protected updateStatus = async (baseBranch: Branch) => { const { currentBranch: targetBranch, repository } = this.props updateRebasePreview(baseBranch, targetBranch, repository, rebasePreview => { this.rebasePreview = rebasePreview this.updateRebaseStatusPreview(baseBranch) }) } private updateRebaseStatusPreview(baseBranch: Branch) { this.setState({ statusPreview: this.getRebaseStatusPreview(baseBranch) }) } private getRebaseStatusPreview(baseBranch: Branch): JSX.Element | null { if (this.rebasePreview == null) { return null } const { currentBranch } = this.props if (this.rebasePreview.kind === ComputedAction.Loading) { return this.renderLoadingRebaseMessage() } if (this.rebasePreview.kind === ComputedAction.Clean) { return this.renderCleanRebaseMessage( currentBranch, baseBranch, this.rebasePreview.commits.length ) } 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 rebase. Check you have chosen a valid branch.</> } private renderCleanRebaseMessage( currentBranch: Branch, baseBranch: Branch, commitsToRebase: number ) { if (commitsToRebase <= 0) { return ( <> This branch is up to date with{` `} <strong>{currentBranch.name}</strong> </> ) } const pluralized = commitsToRebase === 1 ? 'commit' : 'commits' return ( <> This will update <strong>{currentBranch.name}</strong> {` by applying its `} <strong>{` ${commitsToRebase} ${pluralized}`}</strong> {` on top of `} <strong>{baseBranch.name}</strong> </> ) } }
{ return }
conditional_block
mailer.js
// mailer.js var nodemailer = require('nodemailer'); var smtpTransport = nodemailer.createTransport("SMTP", { service: "Mandrill", debug: true, auth: { user: "[email protected]", pass: "k-AdDVcsNJ9oj8QYATVNGQ" } }); exports.sendEmailConfirmation = function(emailaddress, username, firstname, expiremoment, token){ var mailOptions = { from: "[email protected]", // sender address to: emailaddress, // list of receivers subject: "Confirm email and start Ativinos", // Subject line text: 'Hi ' +firstname+ ', your account, ' +username+ ', will be enabled after you confirm your email. Your account will be deleted by ' + expiremoment + ' if you do not verify email before then. To verify your email, visit http://www.ativinos.com/emailverify?token=' + token + '&username=' + username, html: 'Hi ' +firstname+ ', your account, ' +username+ ', will be enabled after you confirm your email. Your account will be deleted by ' + expiremoment + ' if you do not verify email before then. To verify your email, visit <a href="http://www.ativinos.com/emailverify?token=' + token + '&username=' + username + '">http://www.ativinos.com/emailverify?token=' + token + '&username=' + username + '</a>', } smtpTransport.sendMail(mailOptions, function(error, response){ if(error)
}) }
{ console.log(error); }
conditional_block
mailer.js
// mailer.js var nodemailer = require('nodemailer'); var smtpTransport = nodemailer.createTransport("SMTP", { service: "Mandrill",
debug: true, auth: { user: "[email protected]", pass: "k-AdDVcsNJ9oj8QYATVNGQ" } }); exports.sendEmailConfirmation = function(emailaddress, username, firstname, expiremoment, token){ var mailOptions = { from: "[email protected]", // sender address to: emailaddress, // list of receivers subject: "Confirm email and start Ativinos", // Subject line text: 'Hi ' +firstname+ ', your account, ' +username+ ', will be enabled after you confirm your email. Your account will be deleted by ' + expiremoment + ' if you do not verify email before then. To verify your email, visit http://www.ativinos.com/emailverify?token=' + token + '&username=' + username, html: 'Hi ' +firstname+ ', your account, ' +username+ ', will be enabled after you confirm your email. Your account will be deleted by ' + expiremoment + ' if you do not verify email before then. To verify your email, visit <a href="http://www.ativinos.com/emailverify?token=' + token + '&username=' + username + '">http://www.ativinos.com/emailverify?token=' + token + '&username=' + username + '</a>', } smtpTransport.sendMail(mailOptions, function(error, response){ if(error){ console.log(error); } }) }
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 = [] successCount = 0 maxPerSearch = 500 last = 0 lastStatus = 0 def loadArguments(self, argv): options, rem = getopt.getopt(argv, 'x:s:q:o:m:', ['extension=', 'signature=', 'search=', 'output=', 'max=']) for opt, arg in options: if opt in ('-x'): self.extension = arg elif opt in ('-s'): self.signature=[] for x in range(len(arg)/2): self.signature.append(int(arg[(x*2):(x*2+2)], 16)) elif opt in ('-q'): self.searchChars=[] for x in range(len(arg)): self.searchChars.append(arg[x]) if opt in ('-o'): self.outputDir = arg if opt in ('-m'): self.maxPerSearch = int(arg) def
(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.downloaded))+ " DOWNLOADED: 0" else: print strftime("%Y-%m-%d %H:%M:%S", gmtime()) + " --- TOTAL: " + str(len(self.downloaded))+ " DOWNLOADED: " + str(len(os.listdir(self.outputDir + self.extension))) def loadList(self): if os.path.isfile("list_" + self.extension + ".txt"): with open("list_" + self.extension + ".txt") as f: for line in f: self.downloaded.append(line.strip()) if os.path.isdir(self.outputDir + self.extension): self.successCount = len(os.listdir(self.outputDir + self.extension)) def readStatus(self): if os.path.isfile("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt"): with open("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt") as f: x = 0 for line in f: if x<len(self.searchChars): self.searchChars[x] = line.strip() x += 1 def start(self): self.loadList() self.readStatus() self.search() def downloadFile(self, url): fDir=self.outputDir + self.extension local_file = None if not os.path.isdir(fDir): os.makedirs(fDir) try: f = urllib2.urlopen(url, timeout=10) for x in range(len(self.signature)): if ord(f.read(1))!=self.signature[x]: f.close() raise local_file=open("%s/file%08d.%s" % (fDir, self.successCount, self.extension), "wb") for x in range(len(self.signature)): local_file.write(chr(self.signature[x])) local_file.write(f.read()) local_file.close() f.close() except KeyboardInterrupt: raise except: if local_file != None: local_file.close() for x in xrange(10): try: if os.path.isfile("%s/file%08d.%s" % (fDir, self.successCount, self.extension)): os.remove("%s/file%08d.%s" % (fDir, self.successCount, self.extension)) break except: if x==9: 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 searchCharsText(self): result = "" for x in range(len(self.searchChars)): result += self.searchChars[x] return result def search(self): if self.extension == None or self.extension == "": print "ERROR: No extension specified!" return if len(self.signature) == 0: print "WARNING: No signature specified - THERE WILL BE LOT OF FALSE RESULTS :(" print "Starting with search" print "---------------------" print "Extension: " + self.extension print "Signature: " + self.signatureText() print "Starting search base: " + self.searchCharsText() print "Output dir: " + self.outputDir + self.extension print "Max results per search: " + str(self.maxPerSearch) self.searchReal("") def searchReal(self, chars): 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 in range(len(self.searchChars)): self.searchChars[x]='a' f = open("list_" + self.extension + ".txt", "a") f_s = open("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt", "w") for x in range(len(chars)): f_s.write(chars[x]+"\n") 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=filetype%3A' + self.extension + '+' + chars + '&num=100&btnG=Google+Search') else: r=requests.get('http://www.google.ee/search?hl=en&q=filetype%3A' + self.extension + '+' + chars + '&num=100&start=' + str(num)) break except: r=0 pos=r.content.find('<a href="') while pos != -1: pos2_a=r.content.find('"', pos+16) pos2_b=r.content.find('&amp;', pos+16) if pos2_a == -1: pos2 = pos2_b elif pos2_b == -1: pos2 = pos2_a else: pos2 = min (pos2_a, pos2_b) if pos2 == -1: break; url = r.content[pos+16:pos2] if url.find('.google.') == -1 and url.startswith('http'): blocked = False if url not in self.downloaded: self.downloadFile(url) self.downloaded.append(url) f.write(url + "\n") pos_a=r.content.find('<a href="', pos+1) pos_b=r.content.find('a href="/url?q=', pos+1) if pos_a == -1: pos = pos_b elif pos_b == -1: pos = pos_a else: pos=min(pos_a, pos_b) self.currentStatusReport() if len(self.downloaded)==self.last: if num == 0: time.sleep(15) break else: self.last = len(self.downloaded) num = num + 100 time.sleep(5) print "Total: " + str(len(self.downloaded)) if blocked: print "Come on Google!!! You are arming my research when you block me! Will wait for 2 hours :(" time.sleep(7200) obj = Downloader() obj.loadArguments(sys.argv[1:]) obj.start()
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 = [] successCount = 0 maxPerSearch = 500 last = 0 lastStatus = 0 def loadArguments(self, argv): options, rem = getopt.getopt(argv, 'x:s:q:o:m:', ['extension=', 'signature=', 'search=', 'output=', 'max=']) for opt, arg in options: if opt in ('-x'): self.extension = arg elif opt in ('-s'): self.signature=[] for x in range(len(arg)/2): self.signature.append(int(arg[(x*2):(x*2+2)], 16)) elif opt in ('-q'): self.searchChars=[] for x in range(len(arg)): self.searchChars.append(arg[x]) if opt in ('-o'): self.outputDir = arg if opt in ('-m'): self.maxPerSearch = int(arg) def currentStatusReport(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.downloaded))+ " DOWNLOADED: 0" else: print strftime("%Y-%m-%d %H:%M:%S", gmtime()) + " --- TOTAL: " + str(len(self.downloaded))+ " DOWNLOADED: " + str(len(os.listdir(self.outputDir + self.extension))) def loadList(self): if os.path.isfile("list_" + self.extension + ".txt"): with open("list_" + self.extension + ".txt") as f: for line in f: self.downloaded.append(line.strip()) if os.path.isdir(self.outputDir + self.extension): self.successCount = len(os.listdir(self.outputDir + self.extension)) def readStatus(self): if os.path.isfile("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt"): with open("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt") as f: x = 0 for line in f: if x<len(self.searchChars): self.searchChars[x] = line.strip() x += 1 def start(self): self.loadList() self.readStatus() self.search() def downloadFile(self, url): fDir=self.outputDir + self.extension local_file = None if not os.path.isdir(fDir): os.makedirs(fDir) try: f = urllib2.urlopen(url, timeout=10) for x in range(len(self.signature)): if ord(f.read(1))!=self.signature[x]: f.close() raise local_file=open("%s/file%08d.%s" % (fDir, self.successCount, self.extension), "wb") for x in range(len(self.signature)): local_file.write(chr(self.signature[x])) local_file.write(f.read()) local_file.close() f.close() except KeyboardInterrupt: raise except: if local_file != None: local_file.close() for x in xrange(10): try: if os.path.isfile("%s/file%08d.%s" % (fDir, self.successCount, self.extension)): os.remove("%s/file%08d.%s" % (fDir, self.successCount, self.extension)) break except: if x==9: 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 searchCharsText(self): result = "" for x in range(len(self.searchChars)): result += self.searchChars[x] return result def search(self): if self.extension == None or self.extension == "": print "ERROR: No extension specified!" return if len(self.signature) == 0: print "WARNING: No signature specified - THERE WILL BE LOT OF FALSE RESULTS :(" print "Starting with search" print "---------------------" print "Extension: " + self.extension print "Signature: " + self.signatureText() print "Starting search base: " + self.searchCharsText() print "Output dir: " + self.outputDir + self.extension print "Max results per search: " + str(self.maxPerSearch) self.searchReal("") def searchReal(self, chars): 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 in range(len(self.searchChars)): self.searchChars[x]='a' f = open("list_" + self.extension + ".txt", "a") f_s = open("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt", "w") for x in range(len(chars)):
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=filetype%3A' + self.extension + '+' + chars + '&num=100&btnG=Google+Search') else: r=requests.get('http://www.google.ee/search?hl=en&q=filetype%3A' + self.extension + '+' + chars + '&num=100&start=' + str(num)) break except: r=0 pos=r.content.find('<a href="') while pos != -1: pos2_a=r.content.find('"', pos+16) pos2_b=r.content.find('&amp;', pos+16) if pos2_a == -1: pos2 = pos2_b elif pos2_b == -1: pos2 = pos2_a else: pos2 = min (pos2_a, pos2_b) if pos2 == -1: break; url = r.content[pos+16:pos2] if url.find('.google.') == -1 and url.startswith('http'): blocked = False if url not in self.downloaded: self.downloadFile(url) self.downloaded.append(url) f.write(url + "\n") pos_a=r.content.find('<a href="', pos+1) pos_b=r.content.find('a href="/url?q=', pos+1) if pos_a == -1: pos = pos_b elif pos_b == -1: pos = pos_a else: pos=min(pos_a, pos_b) self.currentStatusReport() if len(self.downloaded)==self.last: if num == 0: time.sleep(15) break else: self.last = len(self.downloaded) num = num + 100 time.sleep(5) print "Total: " + str(len(self.downloaded)) if blocked: print "Come on Google!!! You are arming my research when you block me! Will wait for 2 hours :(" time.sleep(7200) obj = Downloader() obj.loadArguments(sys.argv[1:]) obj.start()
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 = [] successCount = 0 maxPerSearch = 500 last = 0 lastStatus = 0 def loadArguments(self, argv): options, rem = getopt.getopt(argv, 'x:s:q:o:m:', ['extension=', 'signature=', 'search=', 'output=', 'max=']) for opt, arg in options: if opt in ('-x'): self.extension = arg elif opt in ('-s'): self.signature=[] for x in range(len(arg)/2): self.signature.append(int(arg[(x*2):(x*2+2)], 16)) elif opt in ('-q'): self.searchChars=[] for x in range(len(arg)): self.searchChars.append(arg[x]) if opt in ('-o'): self.outputDir = arg if opt in ('-m'): self.maxPerSearch = int(arg) def currentStatusReport(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.downloaded))+ " DOWNLOADED: 0" else: print strftime("%Y-%m-%d %H:%M:%S", gmtime()) + " --- TOTAL: " + str(len(self.downloaded))+ " DOWNLOADED: " + str(len(os.listdir(self.outputDir + self.extension))) def loadList(self): if os.path.isfile("list_" + self.extension + ".txt"): with open("list_" + self.extension + ".txt") as f: for line in f: self.downloaded.append(line.strip()) if os.path.isdir(self.outputDir + self.extension): self.successCount = len(os.listdir(self.outputDir + self.extension)) def readStatus(self): if os.path.isfile("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt"): with open("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt") as f: x = 0 for line in f: if x<len(self.searchChars): self.searchChars[x] = line.strip() x += 1 def start(self): self.loadList() self.readStatus() self.search() def downloadFile(self, url): fDir=self.outputDir + self.extension local_file = None if not os.path.isdir(fDir): os.makedirs(fDir) try: f = urllib2.urlopen(url, timeout=10) for x in range(len(self.signature)): if ord(f.read(1))!=self.signature[x]: f.close() raise local_file=open("%s/file%08d.%s" % (fDir, self.successCount, self.extension), "wb") for x in range(len(self.signature)): local_file.write(chr(self.signature[x])) local_file.write(f.read()) local_file.close() f.close() except KeyboardInterrupt: raise except: if local_file != None: local_file.close() for x in xrange(10): try: if os.path.isfile("%s/file%08d.%s" % (fDir, self.successCount, self.extension)): os.remove("%s/file%08d.%s" % (fDir, self.successCount, self.extension))
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 searchCharsText(self): result = "" for x in range(len(self.searchChars)): result += self.searchChars[x] return result def search(self): if self.extension == None or self.extension == "": print "ERROR: No extension specified!" return if len(self.signature) == 0: print "WARNING: No signature specified - THERE WILL BE LOT OF FALSE RESULTS :(" print "Starting with search" print "---------------------" print "Extension: " + self.extension print "Signature: " + self.signatureText() print "Starting search base: " + self.searchCharsText() print "Output dir: " + self.outputDir + self.extension print "Max results per search: " + str(self.maxPerSearch) self.searchReal("") def searchReal(self, chars): 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 in range(len(self.searchChars)): self.searchChars[x]='a' f = open("list_" + self.extension + ".txt", "a") f_s = open("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt", "w") for x in range(len(chars)): f_s.write(chars[x]+"\n") 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=filetype%3A' + self.extension + '+' + chars + '&num=100&btnG=Google+Search') else: r=requests.get('http://www.google.ee/search?hl=en&q=filetype%3A' + self.extension + '+' + chars + '&num=100&start=' + str(num)) break except: r=0 pos=r.content.find('<a href="') while pos != -1: pos2_a=r.content.find('"', pos+16) pos2_b=r.content.find('&amp;', pos+16) if pos2_a == -1: pos2 = pos2_b elif pos2_b == -1: pos2 = pos2_a else: pos2 = min (pos2_a, pos2_b) if pos2 == -1: break; url = r.content[pos+16:pos2] if url.find('.google.') == -1 and url.startswith('http'): blocked = False if url not in self.downloaded: self.downloadFile(url) self.downloaded.append(url) f.write(url + "\n") pos_a=r.content.find('<a href="', pos+1) pos_b=r.content.find('a href="/url?q=', pos+1) if pos_a == -1: pos = pos_b elif pos_b == -1: pos = pos_a else: pos=min(pos_a, pos_b) self.currentStatusReport() if len(self.downloaded)==self.last: if num == 0: time.sleep(15) break else: self.last = len(self.downloaded) num = num + 100 time.sleep(5) print "Total: " + str(len(self.downloaded)) if blocked: print "Come on Google!!! You are arming my research when you block me! Will wait for 2 hours :(" time.sleep(7200) obj = Downloader() obj.loadArguments(sys.argv[1:]) obj.start()
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 = [] successCount = 0 maxPerSearch = 500 last = 0 lastStatus = 0 def loadArguments(self, argv): options, rem = getopt.getopt(argv, 'x:s:q:o:m:', ['extension=', 'signature=', 'search=', 'output=', 'max=']) for opt, arg in options: if opt in ('-x'): self.extension = arg elif opt in ('-s'): self.signature=[] for x in range(len(arg)/2): self.signature.append(int(arg[(x*2):(x*2+2)], 16)) elif opt in ('-q'): self.searchChars=[] for x in range(len(arg)): self.searchChars.append(arg[x]) if opt in ('-o'): self.outputDir = arg if opt in ('-m'): self.maxPerSearch = int(arg) def currentStatusReport(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.downloaded))+ " DOWNLOADED: 0" else: print strftime("%Y-%m-%d %H:%M:%S", gmtime()) + " --- TOTAL: " + str(len(self.downloaded))+ " DOWNLOADED: " + str(len(os.listdir(self.outputDir + self.extension))) def loadList(self): if os.path.isfile("list_" + self.extension + ".txt"): with open("list_" + self.extension + ".txt") as f: for line in f: self.downloaded.append(line.strip()) if os.path.isdir(self.outputDir + self.extension): self.successCount = len(os.listdir(self.outputDir + self.extension)) def readStatus(self): if os.path.isfile("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt"): with open("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt") as f: x = 0 for line in f: if x<len(self.searchChars): self.searchChars[x] = line.strip() x += 1 def start(self): self.loadList() self.readStatus() self.search() def downloadFile(self, url): fDir=self.outputDir + self.extension local_file = None if not os.path.isdir(fDir): os.makedirs(fDir) try: f = urllib2.urlopen(url, timeout=10) for x in range(len(self.signature)): if ord(f.read(1))!=self.signature[x]: f.close() raise local_file=open("%s/file%08d.%s" % (fDir, self.successCount, self.extension), "wb") for x in range(len(self.signature)): local_file.write(chr(self.signature[x])) local_file.write(f.read()) local_file.close() f.close() except KeyboardInterrupt: raise except: if local_file != None: local_file.close() for x in xrange(10): try: if os.path.isfile("%s/file%08d.%s" % (fDir, self.successCount, self.extension)): os.remove("%s/file%08d.%s" % (fDir, self.successCount, self.extension)) break except: if x==9: 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 searchCharsText(self): result = "" for x in range(len(self.searchChars)): result += self.searchChars[x] return result def search(self): if self.extension == None or self.extension == "": print "ERROR: No extension specified!" return if len(self.signature) == 0: print "WARNING: No signature specified - THERE WILL BE LOT OF FALSE RESULTS :(" print "Starting with search" print "---------------------" print "Extension: " + self.extension print "Signature: " + self.signatureText() print "Starting search base: " + self.searchCharsText() print "Output dir: " + self.outputDir + self.extension print "Max results per search: " + str(self.maxPerSearch) self.searchReal("") def searchReal(self, chars):
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 in range(len(self.searchChars)): self.searchChars[x]='a' f = open("list_" + self.extension + ".txt", "a") f_s = open("status" + self.extension + "_" + str(len(self.searchChars)) + ".txt", "w") for x in range(len(chars)): f_s.write(chars[x]+"\n") 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=filetype%3A' + self.extension + '+' + chars + '&num=100&btnG=Google+Search') else: r=requests.get('http://www.google.ee/search?hl=en&q=filetype%3A' + self.extension + '+' + chars + '&num=100&start=' + str(num)) break except: r=0 pos=r.content.find('<a href="') while pos != -1: pos2_a=r.content.find('"', pos+16) pos2_b=r.content.find('&amp;', pos+16) if pos2_a == -1: pos2 = pos2_b elif pos2_b == -1: pos2 = pos2_a else: pos2 = min (pos2_a, pos2_b) if pos2 == -1: break; url = r.content[pos+16:pos2] if url.find('.google.') == -1 and url.startswith('http'): blocked = False if url not in self.downloaded: self.downloadFile(url) self.downloaded.append(url) f.write(url + "\n") pos_a=r.content.find('<a href="', pos+1) pos_b=r.content.find('a href="/url?q=', pos+1) if pos_a == -1: pos = pos_b elif pos_b == -1: pos = pos_a else: pos=min(pos_a, pos_b) self.currentStatusReport() if len(self.downloaded)==self.last: if num == 0: time.sleep(15) break else: self.last = len(self.downloaded) num = num + 100 time.sleep(5) print "Total: " + str(len(self.downloaded)) if blocked: print "Come on Google!!! You are arming my research when you block me! Will wait for 2 hours :(" time.sleep(7200)
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}}{{#tcprule}} -A INPUT -s {{source}}/32 -p tcp -m tcp --dport {{dport}} -m state --state NEW,ESTABLISHED -j ACCEPT {{/tcprule}}{{#allrule}} -A INPUT -p {{protocol}} -m {{protocol}} --dport {{dport}} -j ACCEPT {{/allrule}}{{/rule}} COMMIT """ import pystache import datetime # securityGroups are a hash of "security groups" and a list of boxes in each # group securityGroups = {'Database': ['aerolith-pg'], 'Web': ['aerolith-web'], 'Wordpress': ['AerolithWP'], 'Dev': ['ubuntu-512mb-sfo1-01'] } # groupRules tell you for each security groups, which security groups # can connect to it and what ports # note all of these have port 22 (ssh) open by default (see template above) groupRules = {'Web': [('all', 80), ('all', 443), ('all', 21), ('all', 20), ('all', '61052:61057'), ('all', 8080)], 'Redis': [('Web', 6379), ('all', 80)], 'Database': [('Web', 5432)], 'Dev': [('all', 80), ('all', 443)] } def gen_firewall(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, 'protocol': 'tcp'}) else: for server in servers: # for each server in the security group in question # add its private ip to the firewall if server['name'] in securityGroups[subrule[0]]: port = subrule[1] context['rule']['tcprule'].append( {'source': server['networks']['v4'][0]['ip_address'], 'dport': port }) res = pystache.render(template, context) f = open('iptables.' + securityGroup + '.rules', 'wb')
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}}{{#tcprule}} -A INPUT -s {{source}}/32 -p tcp -m tcp --dport {{dport}} -m state --state NEW,ESTABLISHED -j ACCEPT {{/tcprule}}{{#allrule}} -A INPUT -p {{protocol}} -m {{protocol}} --dport {{dport}} -j ACCEPT {{/allrule}}{{/rule}} COMMIT """ import pystache import datetime # securityGroups are a hash of "security groups" and a list of boxes in each # group securityGroups = {'Database': ['aerolith-pg'], 'Web': ['aerolith-web'], 'Wordpress': ['AerolithWP'], 'Dev': ['ubuntu-512mb-sfo1-01'] } # groupRules tell you for each security groups, which security groups # can connect to it and what ports # note all of these have port 22 (ssh) open by default (see template above) groupRules = {'Web': [('all', 80), ('all', 443), ('all', 21), ('all', 20), ('all', '61052:61057'), ('all', 8080)], 'Redis': [('Web', 6379), ('all', 80)], 'Database': [('Web', 5432)], 'Dev': [('all', 80), ('all', 443)] } def
(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, 'protocol': 'tcp'}) else: for server in servers: # for each server in the security group in question # add its private ip to the firewall if server['name'] in securityGroups[subrule[0]]: port = subrule[1] context['rule']['tcprule'].append( {'source': server['networks']['v4'][0]['ip_address'], 'dport': port }) res = pystache.render(template, context) f = open('iptables.' + securityGroup + '.rules', 'wb') f.write(res) f.close() return res
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}}{{#tcprule}} -A INPUT -s {{source}}/32 -p tcp -m tcp --dport {{dport}} -m state --state NEW,ESTABLISHED -j ACCEPT {{/tcprule}}{{#allrule}} -A INPUT -p {{protocol}} -m {{protocol}} --dport {{dport}} -j ACCEPT {{/allrule}}{{/rule}} COMMIT """ import pystache import datetime # securityGroups are a hash of "security groups" and a list of boxes in each # group securityGroups = {'Database': ['aerolith-pg'], 'Web': ['aerolith-web'], 'Wordpress': ['AerolithWP'], 'Dev': ['ubuntu-512mb-sfo1-01'] } # groupRules tell you for each security groups, which security groups # can connect to it and what ports # note all of these have port 22 (ssh) open by default (see template above) groupRules = {'Web': [('all', 80), ('all', 443), ('all', 21), ('all', 20), ('all', '61052:61057'), ('all', 8080)], 'Redis': [('Web', 6379), ('all', 80)], 'Database': [('Web', 5432)], 'Dev': [('all', 80), ('all', 443)] } def gen_firewall(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, 'protocol': 'tcp'}) else: for server in servers: # for each server in the security group in question # add its private ip to the firewall if server['name'] in securityGroups[subrule[0]]: port = subrule[1] context['rule']['tcprule'].append( {'source': server['networks']['v4'][0]['ip_address'], 'dport': port }) res = pystache.render(template, context) f = open('iptables.' + securityGroup + '.rules', 'wb') f.write(res) f.close() return res
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}}{{#tcprule}} -A INPUT -s {{source}}/32 -p tcp -m tcp --dport {{dport}} -m state --state NEW,ESTABLISHED -j ACCEPT {{/tcprule}}{{#allrule}} -A INPUT -p {{protocol}} -m {{protocol}} --dport {{dport}} -j ACCEPT {{/allrule}}{{/rule}} COMMIT """ import pystache import datetime # securityGroups are a hash of "security groups" and a list of boxes in each # group securityGroups = {'Database': ['aerolith-pg'], 'Web': ['aerolith-web'], 'Wordpress': ['AerolithWP'], 'Dev': ['ubuntu-512mb-sfo1-01'] } # groupRules tell you for each security groups, which security groups # can connect to it and what ports # note all of these have port 22 (ssh) open by default (see template above) groupRules = {'Web': [('all', 80), ('all', 443), ('all', 21), ('all', 20), ('all', '61052:61057'), ('all', 8080)], 'Redis': [('Web', 6379), ('all', 80)], 'Database': [('Web', 5432)], 'Dev': [('all', 80), ('all', 443)] } def gen_firewall(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, 'protocol': 'tcp'}) else: for server in servers: # for each server in the security group in question # add its private ip to the firewall if server['name'] in securityGroups[subrule[0]]:
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 with the questionable alignment #[derive(Debug)] struct Inner { c64: u64 } // This is the type that contains the type with the // questionable alignment, for testing #[derive(Debug)] struct Outer { c8: u8, t: Inner } #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "emscripten", target_os = "freebsd", target_os = "fuchsia",
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 m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } #[cfg(target_env = "sgx")] mod m { #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> usize { 8 } 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); println!("align inner = {:?}", rusti::min_align_of::<Inner>()); println!("size outer = {:?}", mem::size_of::<Outer>()); println!("y = {:?}", y); // per clang/gcc the alignment of `Inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::m::align()); // per clang/gcc the size of `Outer` should be 12 // because `Inner`s alignment was 4. assert_eq!(mem::size_of::<Outer>(), m::m::size()); assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); } }
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 with the questionable alignment #[derive(Debug)] struct Inner { c64: u64 } // This is the type that contains the type with the // questionable alignment, for testing #[derive(Debug)] struct Outer { c8: u8, t: Inner } #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "emscripten", target_os = "freebsd", target_os = "fuchsia", target_os = "linux", target_os = "macos", 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 m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } #[cfg(target_env = "sgx")] mod m { #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> usize { 8 } pub fn
() -> 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 = {:?}", rusti::min_align_of::<Inner>()); println!("size outer = {:?}", mem::size_of::<Outer>()); println!("y = {:?}", y); // per clang/gcc the alignment of `Inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::m::align()); // per clang/gcc the size of `Outer` should be 12 // because `Inner`s alignment was 4. assert_eq!(mem::size_of::<Outer>(), m::m::size()); assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); } }
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 with the questionable alignment #[derive(Debug)] struct Inner { c64: u64 } // This is the type that contains the type with the // questionable alignment, for testing #[derive(Debug)] struct Outer { c8: u8, t: Inner } #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "emscripten", target_os = "freebsd", target_os = "fuchsia", target_os = "linux", target_os = "macos", 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 m { pub fn align() -> usize { 8 } pub fn size() -> usize { 16 } } } #[cfg(target_env = "sgx")] mod m { #[cfg(target_arch = "x86_64")] pub mod m { pub fn align() -> usize
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); println!("align inner = {:?}", rusti::min_align_of::<Inner>()); println!("size outer = {:?}", mem::size_of::<Outer>()); println!("y = {:?}", y); // per clang/gcc the alignment of `Inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::m::align()); // per clang/gcc the size of `Outer` should be 12 // because `Inner`s alignment was 4. assert_eq!(mem::size_of::<Outer>(), m::m::size()); assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); } }
{ 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(null); } } return grid; }; Board.marks = ["x", "o"]; Board.prototype.isEmptyPos = function (pos) { 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; colIdx++) { if (this.isEmptyPos([rowIdx, colIdx])) { return false; } } } return true; }; Board.prototype.placeMark = function (pos, mark) { if (!this.isEmptyPos(pos)) { throw new MoveError("Is not an empty position!"); } 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] : " " ); } strs.push(marks.join("|") + "\n"); } console.log(strs.join("-----\n")); }; Board.prototype.winner = function () { var posSeqs = [ // horizontals [[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2]], // verticals [[0, 0], [1, 0], [2, 0]], [[0, 1], [1, 1], [2, 1]], [[0, 2], [1, 2], [2, 2]], // diagonals [[0, 0], [1, 1], [2, 2]], [[2, 0], [1, 1], [0, 2]] ]; for (var i = 0; i < posSeqs.length; i++) { var winner = this.winnerHelper(posSeqs[i]); if (winner != null) { return winner; } } return null; }; Board.prototype.winnerHelper = function (posSeq) { for (var markIdx = 0; markIdx < Board.marks.length; markIdx++) { var targetMark = Board.marks[markIdx]; var winner = true; for (var posIdx = 0; posIdx < 3; posIdx++) { var pos = posSeq[posIdx]; var mark = this.grid[pos[0]][pos[1]]; if (mark != targetMark) { winner = false; } } if (winner) { return targetMark; } } return null; }; module.exports = Board;
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([]); for (var j = 0; j < 3; j++) { grid[i].push(null); } } return grid; }; Board.marks = ["x", "o"]; Board.prototype.isEmptyPos = function (pos) { 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; colIdx++) { if (this.isEmptyPos([rowIdx, colIdx])) { return false; } } } return true; }; Board.prototype.placeMark = function (pos, mark) { if (!this.isEmptyPos(pos))
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] : " " ); } strs.push(marks.join("|") + "\n"); } console.log(strs.join("-----\n")); }; Board.prototype.winner = function () { var posSeqs = [ // horizontals [[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2]], // verticals [[0, 0], [1, 0], [2, 0]], [[0, 1], [1, 1], [2, 1]], [[0, 2], [1, 2], [2, 2]], // diagonals [[0, 0], [1, 1], [2, 2]], [[2, 0], [1, 1], [0, 2]] ]; for (var i = 0; i < posSeqs.length; i++) { var winner = this.winnerHelper(posSeqs[i]); if (winner != null) { return winner; } } return null; }; Board.prototype.winnerHelper = function (posSeq) { for (var markIdx = 0; markIdx < Board.marks.length; markIdx++) { var targetMark = Board.marks[markIdx]; var winner = true; for (var posIdx = 0; posIdx < 3; posIdx++) { var pos = posSeq[posIdx]; var mark = this.grid[pos[0]][pos[1]]; if (mark != targetMark) { winner = false; } } if (winner) { return targetMark; } } return null; }; module.exports = Board;
{ 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([]); for (var j = 0; j < 3; j++) { grid[i].push(null); } } return grid; }; Board.marks = ["x", "o"];
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; colIdx++) { if (this.isEmptyPos([rowIdx, colIdx])) { return false; } } } return true; }; Board.prototype.placeMark = function (pos, mark) { if (!this.isEmptyPos(pos)) { throw new MoveError("Is not an empty position!"); } 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] : " " ); } strs.push(marks.join("|") + "\n"); } console.log(strs.join("-----\n")); }; Board.prototype.winner = function () { var posSeqs = [ // horizontals [[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2]], // verticals [[0, 0], [1, 0], [2, 0]], [[0, 1], [1, 1], [2, 1]], [[0, 2], [1, 2], [2, 2]], // diagonals [[0, 0], [1, 1], [2, 2]], [[2, 0], [1, 1], [0, 2]] ]; for (var i = 0; i < posSeqs.length; i++) { var winner = this.winnerHelper(posSeqs[i]); if (winner != null) { return winner; } } return null; }; Board.prototype.winnerHelper = function (posSeq) { for (var markIdx = 0; markIdx < Board.marks.length; markIdx++) { var targetMark = Board.marks[markIdx]; var winner = true; for (var posIdx = 0; posIdx < 3; posIdx++) { var pos = posSeq[posIdx]; var mark = this.grid[pos[0]][pos[1]]; if (mark != targetMark) { winner = false; } } if (winner) { return targetMark; } } return null; }; module.exports = Board;
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.marks = ["x", "o"]; Board.prototype.isEmptyPos = function (pos) { 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; colIdx++) { if (this.isEmptyPos([rowIdx, colIdx])) { return false; } } } return true; }; Board.prototype.placeMark = function (pos, mark) { if (!this.isEmptyPos(pos)) { throw new MoveError("Is not an empty position!"); } 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] : " " ); } strs.push(marks.join("|") + "\n"); } console.log(strs.join("-----\n")); }; Board.prototype.winner = function () { var posSeqs = [ // horizontals [[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2]], // verticals [[0, 0], [1, 0], [2, 0]], [[0, 1], [1, 1], [2, 1]], [[0, 2], [1, 2], [2, 2]], // diagonals [[0, 0], [1, 1], [2, 2]], [[2, 0], [1, 1], [0, 2]] ]; for (var i = 0; i < posSeqs.length; i++) { var winner = this.winnerHelper(posSeqs[i]); if (winner != null) { return winner; } } return null; }; Board.prototype.winnerHelper = function (posSeq) { for (var markIdx = 0; markIdx < Board.marks.length; markIdx++) { var targetMark = Board.marks[markIdx]; var winner = true; for (var posIdx = 0; posIdx < 3; posIdx++) { var pos = posSeq[posIdx]; var mark = this.grid[pos[0]][pos[1]]; if (mark != targetMark) { winner = false; } } if (winner) { return targetMark; } } return null; }; module.exports = 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 "chalk"; import { Creds, Opts, TestGetBoolean } from "./types"; import { time_log2 } from "./time_log"; import { Page } from "puppeteer"; const puppeteer = require("puppeteer"); export const is_admin = async function (creds: Creds, opts: Opts, page: Page): Promise<TestGetBoolean> { let pfcounts: TestGetBoolean = new TestGetBoolean(); if (opts.skip && opts.skip.test(this_file)) { debuglog("skipping test: " + this_file); pfcounts.skip += 1; return pfcounts; } 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 pfcounts.result = false; try { let sel = '*[cocalc-test="admin"]'; await page.waitForSelector(sel, { timeout: 2000 }); debuglog("found Admin tab");
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); pfcounts.pass += 1; } catch (e) { pfcounts.fail += 1; console.log(chalk.red(`ERROR: ${e.message}`)); } return pfcounts; };
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 "chalk"; import { Creds, Opts, TestGetBoolean } from "./types"; import { time_log2 } from "./time_log"; import { Page } from "puppeteer"; const puppeteer = require("puppeteer"); export const is_admin = async function (creds: Creds, opts: Opts, page: Page): Promise<TestGetBoolean> { let pfcounts: TestGetBoolean = new TestGetBoolean(); if (opts.skip && opts.skip.test(this_file)) {
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 pfcounts.result = false; try { let sel = '*[cocalc-test="admin"]'; await page.waitForSelector(sel, { timeout: 2000 }); debuglog("found Admin tab"); 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); pfcounts.pass += 1; } catch (e) { pfcounts.fail += 1; console.log(chalk.red(`ERROR: ${e.message}`)); } return pfcounts; };
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, identity, parseNumber, NUMBER_KEYS, filterNumericKeys} from './utils'; @Component({ selector: 'my-input', template: ` <my-input-layout [label]="label" [errors]="errors" [note]="note" [disabled]="disabled"> <input *ngIf="type !== 'textarea'" #input [attr.max]="max" [attr.maxlength]="maxlength" [attr.min]="min" [attr.minlength]="minlength" [attr.name]="name" [readonly]="readonly" [required]="required" [disabled]="disabled" [type]="type" [(ngModel)]="valueView" (focus)="onFocus($event)" (blur)="onBlur($event)" (change)="onChange($event)"> <textarea *ngIf="type === 'textarea'" #input [attr.max]="max" [attr.maxlength]="maxlength" [attr.min]="min" [attr.minlength]="minlength" [attr.name]="name" [readonly]="readonly" [required]="required" [disabled]="disabled" [(ngModel)]="valueView" (focus)="onFocus($event)" (blur)="onBlur($event)" (change)="onChange($event)"></textarea> </my-input-layout> `, host: {'[class.my-focused]': 'focused', '(click)': 'onClick()'}, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InputComponent), multi: true }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => InputComponent), multi: true } ] }) export class InputComponent implements ControlValueAccessor, Validator, OnChanges { parseValueFn = identity; filterKeysFn = identity; _type: string; _value: string | number; _errors: string[]; _focused: boolean; @ViewChild('input') _inputEl: ElementRef; @Input() max: string | number; @Input() min: string | number; @Input() maxlength: string | number; @Input() minlength: string | number; @Input() readonly: boolean; @Input() required: boolean; @Input() disabled: boolean; @Input() label: string; @Input() note: string; @Input() name: string; @Input() get type() { return this._type; } set type(type: string) { this._type = type; if(type === 'number') { this.parseValueFn = parseNumber; this.filterKeysFn = filterNumericKeys; } else { this.parseValueFn = identity; this.filterKeysFn = identity; } } @Input() get value() { return this._value; } set value(value: string | number) { this._value = this.parseValueFn(value); } get valueView() { return this._value; } set valueView(value: string | number) { this.value = value; this.onChangedFn(this.value); this.valueChange.emit(this.value); } get focused() { return this._focused; } set focused(focused: boolean) { this._focused = focused; } onClick() { this._renderer.invokeElementMethod(this._inputEl.nativeElement, 'focus'); } @Input() get errors() { return this._errors; } set errors(errors: string[]) { if(errors !== this._errors) { this._errors = errors || []; this.errorsChange.emit(this.errors); } } @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) { }
(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.filterKeysFn(event); } //OnChanges ngOnChanges(changes: {[key: string]: SimpleChange}) { } //Validator validateFn: Function = noop; validate(ctrl: AbstractControl) : {[key: string]: any} { return this.validateFn(ctrl); } 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) => void) : void { this.onChangedFn = fn; } registerOnTouched(fn: () => void) : void { this.onTouchedFn = fn; } setDisabledState(isDisabled: boolean) : void { this.disabled = isDisabled; } }
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, identity, parseNumber, NUMBER_KEYS, filterNumericKeys} from './utils'; @Component({ selector: 'my-input', template: ` <my-input-layout [label]="label" [errors]="errors" [note]="note" [disabled]="disabled"> <input *ngIf="type !== 'textarea'" #input [attr.max]="max" [attr.maxlength]="maxlength" [attr.min]="min" [attr.minlength]="minlength" [attr.name]="name" [readonly]="readonly" [required]="required" [disabled]="disabled" [type]="type" [(ngModel)]="valueView" (focus)="onFocus($event)" (blur)="onBlur($event)" (change)="onChange($event)"> <textarea *ngIf="type === 'textarea'" #input [attr.max]="max" [attr.maxlength]="maxlength" [attr.min]="min" [attr.minlength]="minlength" [attr.name]="name" [readonly]="readonly" [required]="required" [disabled]="disabled" [(ngModel)]="valueView" (focus)="onFocus($event)" (blur)="onBlur($event)" (change)="onChange($event)"></textarea> </my-input-layout> `, host: {'[class.my-focused]': 'focused', '(click)': 'onClick()'}, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InputComponent), multi: true }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => InputComponent), multi: true } ] }) export class InputComponent implements ControlValueAccessor, Validator, OnChanges { parseValueFn = identity; filterKeysFn = identity; _type: string; _value: string | number; _errors: string[]; _focused: boolean; @ViewChild('input') _inputEl: ElementRef; @Input() max: string | number; @Input() min: string | number; @Input() maxlength: string | number; @Input() minlength: string | number; @Input() readonly: boolean; @Input() required: boolean; @Input() disabled: boolean; @Input() label: string; @Input() note: string; @Input() name: string; @Input() get type() { return this._type; } set type(type: string) { this._type = type; if(type === 'number') { this.parseValueFn = parseNumber; this.filterKeysFn = filterNumericKeys; } else { this.parseValueFn = identity; this.filterKeysFn = identity; } } @Input() get value() { return this._value; } set value(value: string | number) { this._value = this.parseValueFn(value); } get valueView() { return this._value; } set valueView(value: string | number) { this.value = value; this.onChangedFn(this.value); this.valueChange.emit(this.value); } get focused() { return this._focused; } set focused(focused: boolean) { this._focused = focused; } onClick() { this._renderer.invokeElementMethod(this._inputEl.nativeElement, 'focus'); } @Input() get errors() { return this._errors; } set errors(errors: string[]) { if(errors !== this._errors) { this._errors = errors || []; this.errorsChange.emit(this.errors); } } @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.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.filterKeysFn(event); } //OnChanges ngOnChanges(changes: {[key: string]: SimpleChange}) { } //Validator validateFn: Function = noop; validate(ctrl: AbstractControl) : {[key: string]: any}
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) => void) : void { this.onChangedFn = fn; } registerOnTouched(fn: () => void) : void { this.onTouchedFn = fn; } setDisabledState(isDisabled: boolean) : void { this.disabled = isDisabled; } }
{ 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, identity, parseNumber, NUMBER_KEYS, filterNumericKeys} from './utils'; @Component({ selector: 'my-input', template: ` <my-input-layout [label]="label" [errors]="errors" [note]="note" [disabled]="disabled"> <input *ngIf="type !== 'textarea'" #input [attr.max]="max" [attr.maxlength]="maxlength" [attr.min]="min" [attr.minlength]="minlength" [attr.name]="name" [readonly]="readonly" [required]="required" [disabled]="disabled" [type]="type" [(ngModel)]="valueView" (focus)="onFocus($event)" (blur)="onBlur($event)" (change)="onChange($event)"> <textarea *ngIf="type === 'textarea'" #input [attr.max]="max" [attr.maxlength]="maxlength" [attr.min]="min" [attr.minlength]="minlength" [attr.name]="name" [readonly]="readonly" [required]="required" [disabled]="disabled" [(ngModel)]="valueView" (focus)="onFocus($event)" (blur)="onBlur($event)" (change)="onChange($event)"></textarea> </my-input-layout> `, host: {'[class.my-focused]': 'focused', '(click)': 'onClick()'}, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InputComponent), multi: true }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => InputComponent), multi: true } ] }) export class InputComponent implements ControlValueAccessor, Validator, OnChanges { parseValueFn = identity; filterKeysFn = identity; _type: string; _value: string | number; _errors: string[]; _focused: boolean; @ViewChild('input') _inputEl: ElementRef; @Input() max: string | number; @Input() min: string | number; @Input() maxlength: string | number; @Input() minlength: string | number; @Input() readonly: boolean; @Input() required: boolean; @Input() disabled: boolean; @Input() label: string; @Input() note: string; @Input() name: string; @Input() get type() { return this._type; } set type(type: string) { this._type = type; if(type === 'number') { this.parseValueFn = parseNumber; this.filterKeysFn = filterNumericKeys; } else { this.parseValueFn = identity; this.filterKeysFn = identity; } } @Input() get value() { return this._value; } set value(value: string | number) { this._value = this.parseValueFn(value); } get valueView() { return this._value; } set valueView(value: string | number) { this.value = value; this.onChangedFn(this.value); this.valueChange.emit(this.value); } get focused() { return this._focused; } set focused(focused: boolean) { this._focused = focused; } onClick() { this._renderer.invokeElementMethod(this._inputEl.nativeElement, 'focus'); } @Input() get errors() { return this._errors; } set errors(errors: string[]) { if(errors !== this._errors) { this._errors = errors || []; this.errorsChange.emit(this.errors); } } @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.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.filterKeysFn(event); } //OnChanges ngOnChanges(changes: {[key: string]: SimpleChange}) { } //Validator validateFn: Function = noop; validate(ctrl: AbstractControl) : {[key: string]: any} { return this.validateFn(ctrl); } 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) => void) : void { this.onChangedFn = fn;
} 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, identity, parseNumber, NUMBER_KEYS, filterNumericKeys} from './utils'; @Component({ selector: 'my-input', template: ` <my-input-layout [label]="label" [errors]="errors" [note]="note" [disabled]="disabled"> <input *ngIf="type !== 'textarea'" #input [attr.max]="max" [attr.maxlength]="maxlength" [attr.min]="min" [attr.minlength]="minlength" [attr.name]="name" [readonly]="readonly" [required]="required" [disabled]="disabled" [type]="type" [(ngModel)]="valueView" (focus)="onFocus($event)" (blur)="onBlur($event)" (change)="onChange($event)"> <textarea *ngIf="type === 'textarea'" #input [attr.max]="max" [attr.maxlength]="maxlength" [attr.min]="min" [attr.minlength]="minlength" [attr.name]="name" [readonly]="readonly" [required]="required" [disabled]="disabled" [(ngModel)]="valueView" (focus)="onFocus($event)" (blur)="onBlur($event)" (change)="onChange($event)"></textarea> </my-input-layout> `, host: {'[class.my-focused]': 'focused', '(click)': 'onClick()'}, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => InputComponent), multi: true }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => InputComponent), multi: true } ] }) export class InputComponent implements ControlValueAccessor, Validator, OnChanges { parseValueFn = identity; filterKeysFn = identity; _type: string; _value: string | number; _errors: string[]; _focused: boolean; @ViewChild('input') _inputEl: ElementRef; @Input() max: string | number; @Input() min: string | number; @Input() maxlength: string | number; @Input() minlength: string | number; @Input() readonly: boolean; @Input() required: boolean; @Input() disabled: boolean; @Input() label: string; @Input() note: string; @Input() name: string; @Input() get type() { return this._type; } set type(type: string) { this._type = type; if(type === 'number') { this.parseValueFn = parseNumber; this.filterKeysFn = filterNumericKeys; } else { this.parseValueFn = identity; this.filterKeysFn = identity; } } @Input() get value() { return this._value; } set value(value: string | number) { this._value = this.parseValueFn(value); } get valueView() { return this._value; } set valueView(value: string | number) { this.value = value; this.onChangedFn(this.value); this.valueChange.emit(this.value); } get focused() { return this._focused; } set focused(focused: boolean) { this._focused = focused; } onClick() { this._renderer.invokeElementMethod(this._inputEl.nativeElement, 'focus'); } @Input() get errors() { return this._errors; } set errors(errors: string[]) { if(errors !== this._errors)
} @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.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.filterKeysFn(event); } //OnChanges ngOnChanges(changes: {[key: string]: SimpleChange}) { } //Validator validateFn: Function = noop; validate(ctrl: AbstractControl) : {[key: string]: any} { return this.validateFn(ctrl); } 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) => void) : void { this.onChangedFn = fn; } registerOnTouched(fn: () => void) : void { this.onTouchedFn = fn; } setDisabledState(isDisabled: boolean) : void { this.disabled = isDisabled; } }
{ 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 writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const config = require('./config'); // TODO: Load the trace-agent and start it // Trace must be started before any other code in the // application. require('@google-cloud/trace-agent').start({ projectId: config.get('GCLOUD_PROJECT') }); // END TODO require('@google-cloud/debug-agent').start({ allowExpressions: true, projectId: config.get('GCLOUD_PROJECT') }); const path = require('path'); const express = require('express'); const scores = require('./gcp/spanner'); const {ErrorReporting} = require('@google-cloud/error-reporting'); const errorReporting = new ErrorReporting({ projectId: config.get('GCLOUD_PROJECT')
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')); // Quizzes API app.use('/api/quizzes', require('./api')); // Display the home page app.get('/', (req, res) => { res.render('home.pug'); }); // Display the Leaderboard app.get('/leaderboard', (req, res) => { scores.getLeaderboard().then(scores => { res.render('leaderboard.pug', { scores }); }); }); // Use Stackdriver Error Reporting with Express app.use(errorReporting.express); // Basic 404 handler app.use((req, res) => { res.status(404).send('Not Found'); }); // Basic error handler app.use((err, req, res, next) => { /* jshint unused:false */ console.error(err); // If our routes specified a specific response, then send that. Otherwise, // send a generic message so as not to leak anything. res.status(500).send(err.response || 'Something broke!'); }); if (module === require.main) { // Start the server const server = app.listen(config.get('PORT'), () => { const port = server.address().port; console.log(`App listening on port ${port}`); }); } module.exports = app;
});
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 writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; const config = require('./config'); // TODO: Load the trace-agent and start it // Trace must be started before any other code in the // application. require('@google-cloud/trace-agent').start({ projectId: config.get('GCLOUD_PROJECT') }); // END TODO require('@google-cloud/debug-agent').start({ allowExpressions: true, projectId: config.get('GCLOUD_PROJECT') }); const path = require('path'); const express = require('express'); const scores = require('./gcp/spanner'); const {ErrorReporting} = require('@google-cloud/error-reporting'); const errorReporting = new ErrorReporting({ projectId: config.get('GCLOUD_PROJECT') }); 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')); // Quizzes API app.use('/api/quizzes', require('./api')); // Display the home page app.get('/', (req, res) => { res.render('home.pug'); }); // Display the Leaderboard app.get('/leaderboard', (req, res) => { scores.getLeaderboard().then(scores => { res.render('leaderboard.pug', { scores }); }); }); // Use Stackdriver Error Reporting with Express app.use(errorReporting.express); // Basic 404 handler app.use((req, res) => { res.status(404).send('Not Found'); }); // Basic error handler app.use((err, req, res, next) => { /* jshint unused:false */ console.error(err); // If our routes specified a specific response, then send that. Otherwise, // send a generic message so as not to leak anything. res.status(500).send(err.response || 'Something broke!'); }); if (module === require.main)
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> { 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.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; } }
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: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T> add<T>(arg: any): Promise<T>
}
{ 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.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; }
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: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T> add<T>(arg: any): Promise<T> { 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)
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.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.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; } }
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 the target resource."] #[doc=""] #[doc="# ABNF"] #[doc="```plain"] #[doc="Accept-Ranges = acceptable-ranges"] #[doc="acceptable-ranges = 1#range-unit / \"none\""] #[doc=""] #[doc="# Example values"] #[doc="* `bytes`"] #[doc="* `none`"] #[doc="* `unknown-unit`"] #[doc="```"] #[doc=""] #[doc="# Examples"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set(AcceptRanges(vec![RangeUnit::Bytes]));"] #[doc="```"] #[doc="```"] #[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="let mut headers = Headers::new();"] #[doc="headers.set("] #[doc=" AcceptRanges(vec!["] #[doc=" RangeUnit::Unregistered(\"nibbles\".to_owned()),"] #[doc=" RangeUnit::Bytes,"] #[doc=" RangeUnit::Unregistered(\"doublets\".to_owned()),"] #[doc=" RangeUnit::Unregistered(\"quadlets\".to_owned()),"] #[doc=" ])"] #[doc=");"] #[doc="```"] (AcceptRanges, "Accept-Ranges") => (RangeUnit)+ test_acccept_ranges { test_header!(test1, vec![b"bytes"]); test_header!(test2, vec![b"none"]); test_header!(test3, vec![b"unknown-unit"]); test_header!(test4, vec![b"bytes, unknown-unit"]); } } /// Range Units, described in [RFC7233](http://tools.ietf.org/html/rfc7233#section-2) /// /// A representation can be partitioned into subranges according to /// various structural units, depending on the structure inherent in the /// representation's media type. /// /// # ABNF /// ```plain /// range-unit = bytes-unit / other-range-unit /// bytes-unit = "bytes" /// other-range-unit = token /// ``` #[derive(Clone, Debug, Eq, PartialEq)] pub enum
{ /// 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<Self> { match s { "bytes" => Ok(RangeUnit::Bytes), "none" => Ok(RangeUnit::None), // FIXME: Check if s is really a Token _ => Ok(RangeUnit::Unregistered(s.to_owned())), } } } 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), } } }
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 the target resource."] #[doc=""] #[doc="# ABNF"] #[doc="```plain"] #[doc="Accept-Ranges = acceptable-ranges"] #[doc="acceptable-ranges = 1#range-unit / \"none\""] #[doc=""] #[doc="# Example values"] #[doc="* `bytes`"] #[doc="* `none`"] #[doc="* `unknown-unit`"] #[doc="```"] #[doc=""] #[doc="# Examples"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set(AcceptRanges(vec![RangeUnit::Bytes]));"] #[doc="```"] #[doc="```"] #[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="let mut headers = Headers::new();"] #[doc="headers.set("] #[doc=" AcceptRanges(vec!["] #[doc=" RangeUnit::Unregistered(\"nibbles\".to_owned()),"] #[doc=" RangeUnit::Bytes,"] #[doc=" RangeUnit::Unregistered(\"doublets\".to_owned()),"] #[doc=" RangeUnit::Unregistered(\"quadlets\".to_owned()),"] #[doc=" ])"] #[doc=");"] #[doc="```"] (AcceptRanges, "Accept-Ranges") => (RangeUnit)+ test_acccept_ranges { test_header!(test1, vec![b"bytes"]); test_header!(test2, vec![b"none"]); test_header!(test3, vec![b"unknown-unit"]); test_header!(test4, vec![b"bytes, unknown-unit"]); } } /// Range Units, described in [RFC7233](http://tools.ietf.org/html/rfc7233#section-2) /// /// A representation can be partitioned into subranges according to /// various structural units, depending on the structure inherent in the /// representation's media type. /// /// # ABNF /// ```plain /// range-unit = bytes-unit / other-range-unit /// bytes-unit = "bytes" /// other-range-unit = token /// ``` #[derive(Clone, Debug, Eq, PartialEq)] pub enum RangeUnit { /// 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<Self>
} 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 the target resource."] #[doc=""] #[doc="# ABNF"] #[doc="```plain"] #[doc="Accept-Ranges = acceptable-ranges"] #[doc="acceptable-ranges = 1#range-unit / \"none\""] #[doc=""] #[doc="# Example values"] #[doc="* `bytes`"] #[doc="* `none`"] #[doc="* `unknown-unit`"] #[doc="```"] #[doc=""] #[doc="# Examples"] #[doc="```"] #[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set(AcceptRanges(vec![RangeUnit::Bytes]));"] #[doc="```"]
#[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="let mut headers = Headers::new();"] #[doc="headers.set("] #[doc=" AcceptRanges(vec!["] #[doc=" RangeUnit::Unregistered(\"nibbles\".to_owned()),"] #[doc=" RangeUnit::Bytes,"] #[doc=" RangeUnit::Unregistered(\"doublets\".to_owned()),"] #[doc=" RangeUnit::Unregistered(\"quadlets\".to_owned()),"] #[doc=" ])"] #[doc=");"] #[doc="```"] (AcceptRanges, "Accept-Ranges") => (RangeUnit)+ test_acccept_ranges { test_header!(test1, vec![b"bytes"]); test_header!(test2, vec![b"none"]); test_header!(test3, vec![b"unknown-unit"]); test_header!(test4, vec![b"bytes, unknown-unit"]); } } /// Range Units, described in [RFC7233](http://tools.ietf.org/html/rfc7233#section-2) /// /// A representation can be partitioned into subranges according to /// various structural units, depending on the structure inherent in the /// representation's media type. /// /// # ABNF /// ```plain /// range-unit = bytes-unit / other-range-unit /// bytes-unit = "bytes" /// other-range-unit = token /// ``` #[derive(Clone, Debug, Eq, PartialEq)] pub enum RangeUnit { /// 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<Self> { match s { "bytes" => Ok(RangeUnit::Bytes), "none" => Ok(RangeUnit::None), // FIXME: Check if s is really a Token _ => Ok(RangeUnit::Unregistered(s.to_owned())), } } } 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), } } }
#[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 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PYPOWER. If not, see <http://www.gnu.org/licenses/>. """ Defines a profit maximisation task. """ import logging from pybrain.rl.environments import Task from pyreto.discrete.task import ProfitTask as DiscreteProfitTask from pylon import PQ, PV logger = logging.getLogger(__name__) class ProfitTask(DiscreteProfitTask): """ Defines a task for continuous sensor and action spaces. """ def
(self, environment, maxSteps=24, discount=None): super(ProfitTask, self).__init__(environment, maxSteps, discount) #---------------------------------------------------------------------- # "Task" interface: #---------------------------------------------------------------------- #: Limits for scaling of sensors. self.sensor_limits = self._getSensorLimits() #: Limits for scaling of actors. self.actor_limits = self._getActorLimits() #-------------------------------------------------------------------------- # "Task" interface: #-------------------------------------------------------------------------- # def getObservation(self): # """ A filtered mapping to getSample of the underlying environment. """ # # sensors = self.env.getSensors() # print "SENSORS:", sensors # if self.sensor_limits: # sensors = self.normalize(sensors) # # return sensors def performAction(self, action): """ Execute one action. """ # print "ACTION:", action self.t += 1 Task.performAction(self, action) # self.addReward() self.samples += 1 #-------------------------------------------------------------------------- # "ProfitTask" interface: #-------------------------------------------------------------------------- def _getActorLimits(self): """ Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)], one tuple per parameter, giving min and max for that parameter. """ actorLimits = [] for _ in range(self.env.numOffbids): for _ in self.env.generators: actorLimits.append((0.0, self.env.maxMarkup)) 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(self): """ Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)], one tuple per parameter, giving min and max for that parameter. """ limits = [] limits.extend(self._getTotalDemandLimits()) # limits.extend(self._getDemandLimits()) # limits.extend(self._getPriceLimits()) # limits.extend(self._getVoltageSensorLimits()) # limits.extend(self._getVoltageMagnitudeLimits()) # limits.extend(self._getVoltageAngleLimits()) # limits.extend(self._getVoltageLambdaLimits()) # limits.extend(self._getFlowLimits()) logger.debug("Sensor limits: %s" % limits) return limits # limits = [] # # # Market sensor limits. # limits.append((1e-6, BIGNUM)) # f # pLimit = 0.0 # for g in self.env.generators: # if g.is_load: # pLimit += self.env._g0[g]["p_min"] # else: # pLimit += self.env._g0[g]["p_max"] # limits.append((0.0, pLimit)) # quantity ## cost = max([g.total_cost(pLimit, ## self.env._g0[g]["p_cost"], ## self.env._g0[g]["pcost_model"]) \ ## for g in self.env.generators]) # cost = self.env.generators[0].total_cost(pLimit, # self.env._g0[g]["p_cost"], self.env._g0[g]["pcost_model"]) # limits.append((0.0, cost)) # mcp # # # Case sensor limits. ## limits.extend([(-180.0, 180.0) for _ in case.buses]) # Va # limits.extend([(0.0, BIGNUM) for _ in case.buses]) # P_lambda # # limits.extend([(-b.rate_a, b.rate_a) for b in case.branches]) # Pf ## limits.extend([(-BIGNUM, BIGNUM) for b in case.branches]) # mu_f # # limits.extend([(g.p_min, g.p_max) for g in case.generators]) # Pg ## limits.extend([(-BIGNUM, BIGNUM) for g in case.generators]) # Pg_max ## limits.extend([(-BIGNUM, BIGNUM) for g in case.generators]) # Pg_min def _getTotalDemandLimits(self): Pdmax = sum([b.p_demand for b in self.env.market.case.buses]) return [(self.env.Pd_min, Pdmax)] def _getDemandLimits(self): limits = [(0.0, b.p_demand) for b in self.env.market.case.buses if b.type == PQ] return limits def _getPriceLimits(self): mcpLimit = (0.0, self.env.market.priceCap) sysLimit = (0.0, self.fmax) return [mcpLimit, sysLimit] def _getVoltageSensorLimits(self): limits = [] for bus in self.env.market.case.connected_buses: if bus.type == PV: limits.append(None) else: limits.append((bus.v_min, bus.v_max)) return limits def _getVoltageMagnitudeLimits(self): limits = [] Vmax = [b.v_max for b in self.env.market.case.connected_buses] Vmin = [b.v_min for b in self.env.market.case.connected_buses] limits.extend(zip(Vmin, Vmax)) # nb = len(self.env.market.case.connected_buses) # limits.extend([(-180.0, 180.0)] * nb) return limits def _getVoltageAngleLimits(self): limits = [] nb = len(self.env.market.case.connected_buses) limits.extend([(-180.0, 180.0)] * nb) return limits def _getVoltageLambdaLimits(self): nb = len(self.env.market.case.connected_buses) return [None] * nb def _getFlowLimits(self): rateA = [l.rate_a for l in self.env.market.case.online_branches] neg_rateA = [-1.0 * r for r in rateA] limits = zip(neg_rateA, rateA) # limits.extend(zip(neg_rateA, rateA)) return limits
__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 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PYPOWER. If not, see <http://www.gnu.org/licenses/>. """ Defines a profit maximisation task. """ import logging from pybrain.rl.environments import Task
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) #---------------------------------------------------------------------- # "Task" interface: #---------------------------------------------------------------------- #: Limits for scaling of sensors. self.sensor_limits = self._getSensorLimits() #: Limits for scaling of actors. self.actor_limits = self._getActorLimits() #-------------------------------------------------------------------------- # "Task" interface: #-------------------------------------------------------------------------- # def getObservation(self): # """ A filtered mapping to getSample of the underlying environment. """ # # sensors = self.env.getSensors() # print "SENSORS:", sensors # if self.sensor_limits: # sensors = self.normalize(sensors) # # return sensors def performAction(self, action): """ Execute one action. """ # print "ACTION:", action self.t += 1 Task.performAction(self, action) # self.addReward() self.samples += 1 #-------------------------------------------------------------------------- # "ProfitTask" interface: #-------------------------------------------------------------------------- def _getActorLimits(self): """ Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)], one tuple per parameter, giving min and max for that parameter. """ actorLimits = [] for _ in range(self.env.numOffbids): for _ in self.env.generators: actorLimits.append((0.0, self.env.maxMarkup)) 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(self): """ Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)], one tuple per parameter, giving min and max for that parameter. """ limits = [] limits.extend(self._getTotalDemandLimits()) # limits.extend(self._getDemandLimits()) # limits.extend(self._getPriceLimits()) # limits.extend(self._getVoltageSensorLimits()) # limits.extend(self._getVoltageMagnitudeLimits()) # limits.extend(self._getVoltageAngleLimits()) # limits.extend(self._getVoltageLambdaLimits()) # limits.extend(self._getFlowLimits()) logger.debug("Sensor limits: %s" % limits) return limits # limits = [] # # # Market sensor limits. # limits.append((1e-6, BIGNUM)) # f # pLimit = 0.0 # for g in self.env.generators: # if g.is_load: # pLimit += self.env._g0[g]["p_min"] # else: # pLimit += self.env._g0[g]["p_max"] # limits.append((0.0, pLimit)) # quantity ## cost = max([g.total_cost(pLimit, ## self.env._g0[g]["p_cost"], ## self.env._g0[g]["pcost_model"]) \ ## for g in self.env.generators]) # cost = self.env.generators[0].total_cost(pLimit, # self.env._g0[g]["p_cost"], self.env._g0[g]["pcost_model"]) # limits.append((0.0, cost)) # mcp # # # Case sensor limits. ## limits.extend([(-180.0, 180.0) for _ in case.buses]) # Va # limits.extend([(0.0, BIGNUM) for _ in case.buses]) # P_lambda # # limits.extend([(-b.rate_a, b.rate_a) for b in case.branches]) # Pf ## limits.extend([(-BIGNUM, BIGNUM) for b in case.branches]) # mu_f # # limits.extend([(g.p_min, g.p_max) for g in case.generators]) # Pg ## limits.extend([(-BIGNUM, BIGNUM) for g in case.generators]) # Pg_max ## limits.extend([(-BIGNUM, BIGNUM) for g in case.generators]) # Pg_min def _getTotalDemandLimits(self): Pdmax = sum([b.p_demand for b in self.env.market.case.buses]) return [(self.env.Pd_min, Pdmax)] def _getDemandLimits(self): limits = [(0.0, b.p_demand) for b in self.env.market.case.buses if b.type == PQ] return limits def _getPriceLimits(self): mcpLimit = (0.0, self.env.market.priceCap) sysLimit = (0.0, self.fmax) return [mcpLimit, sysLimit] def _getVoltageSensorLimits(self): limits = [] for bus in self.env.market.case.connected_buses: if bus.type == PV: limits.append(None) else: limits.append((bus.v_min, bus.v_max)) return limits def _getVoltageMagnitudeLimits(self): limits = [] Vmax = [b.v_max for b in self.env.market.case.connected_buses] Vmin = [b.v_min for b in self.env.market.case.connected_buses] limits.extend(zip(Vmin, Vmax)) # nb = len(self.env.market.case.connected_buses) # limits.extend([(-180.0, 180.0)] * nb) return limits def _getVoltageAngleLimits(self): limits = [] nb = len(self.env.market.case.connected_buses) limits.extend([(-180.0, 180.0)] * nb) return limits def _getVoltageLambdaLimits(self): nb = len(self.env.market.case.connected_buses) return [None] * nb def _getFlowLimits(self): rateA = [l.rate_a for l in self.env.market.case.online_branches] neg_rateA = [-1.0 * r for r in rateA] limits = zip(neg_rateA, rateA) # limits.extend(zip(neg_rateA, rateA)) return limits
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 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PYPOWER. If not, see <http://www.gnu.org/licenses/>. """ Defines a profit maximisation task. """ import logging from pybrain.rl.environments import Task from pyreto.discrete.task import ProfitTask as DiscreteProfitTask 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) #---------------------------------------------------------------------- # "Task" interface: #---------------------------------------------------------------------- #: Limits for scaling of sensors. self.sensor_limits = self._getSensorLimits() #: Limits for scaling of actors. self.actor_limits = self._getActorLimits() #-------------------------------------------------------------------------- # "Task" interface: #-------------------------------------------------------------------------- # def getObservation(self): # """ A filtered mapping to getSample of the underlying environment. """ # # sensors = self.env.getSensors() # print "SENSORS:", sensors # if self.sensor_limits: # sensors = self.normalize(sensors) # # return sensors def performAction(self, action): """ Execute one action. """ # print "ACTION:", action self.t += 1 Task.performAction(self, action) # self.addReward() self.samples += 1 #-------------------------------------------------------------------------- # "ProfitTask" interface: #-------------------------------------------------------------------------- def _getActorLimits(self): """ Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)], one tuple per parameter, giving min and max for that parameter. """ actorLimits = [] for _ in range(self.env.numOffbids):
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(self): """ Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)], one tuple per parameter, giving min and max for that parameter. """ limits = [] limits.extend(self._getTotalDemandLimits()) # limits.extend(self._getDemandLimits()) # limits.extend(self._getPriceLimits()) # limits.extend(self._getVoltageSensorLimits()) # limits.extend(self._getVoltageMagnitudeLimits()) # limits.extend(self._getVoltageAngleLimits()) # limits.extend(self._getVoltageLambdaLimits()) # limits.extend(self._getFlowLimits()) logger.debug("Sensor limits: %s" % limits) return limits # limits = [] # # # Market sensor limits. # limits.append((1e-6, BIGNUM)) # f # pLimit = 0.0 # for g in self.env.generators: # if g.is_load: # pLimit += self.env._g0[g]["p_min"] # else: # pLimit += self.env._g0[g]["p_max"] # limits.append((0.0, pLimit)) # quantity ## cost = max([g.total_cost(pLimit, ## self.env._g0[g]["p_cost"], ## self.env._g0[g]["pcost_model"]) \ ## for g in self.env.generators]) # cost = self.env.generators[0].total_cost(pLimit, # self.env._g0[g]["p_cost"], self.env._g0[g]["pcost_model"]) # limits.append((0.0, cost)) # mcp # # # Case sensor limits. ## limits.extend([(-180.0, 180.0) for _ in case.buses]) # Va # limits.extend([(0.0, BIGNUM) for _ in case.buses]) # P_lambda # # limits.extend([(-b.rate_a, b.rate_a) for b in case.branches]) # Pf ## limits.extend([(-BIGNUM, BIGNUM) for b in case.branches]) # mu_f # # limits.extend([(g.p_min, g.p_max) for g in case.generators]) # Pg ## limits.extend([(-BIGNUM, BIGNUM) for g in case.generators]) # Pg_max ## limits.extend([(-BIGNUM, BIGNUM) for g in case.generators]) # Pg_min def _getTotalDemandLimits(self): Pdmax = sum([b.p_demand for b in self.env.market.case.buses]) return [(self.env.Pd_min, Pdmax)] def _getDemandLimits(self): limits = [(0.0, b.p_demand) for b in self.env.market.case.buses if b.type == PQ] return limits def _getPriceLimits(self): mcpLimit = (0.0, self.env.market.priceCap) sysLimit = (0.0, self.fmax) return [mcpLimit, sysLimit] def _getVoltageSensorLimits(self): limits = [] for bus in self.env.market.case.connected_buses: if bus.type == PV: limits.append(None) else: limits.append((bus.v_min, bus.v_max)) return limits def _getVoltageMagnitudeLimits(self): limits = [] Vmax = [b.v_max for b in self.env.market.case.connected_buses] Vmin = [b.v_min for b in self.env.market.case.connected_buses] limits.extend(zip(Vmin, Vmax)) # nb = len(self.env.market.case.connected_buses) # limits.extend([(-180.0, 180.0)] * nb) return limits def _getVoltageAngleLimits(self): limits = [] nb = len(self.env.market.case.connected_buses) limits.extend([(-180.0, 180.0)] * nb) return limits def _getVoltageLambdaLimits(self): nb = len(self.env.market.case.connected_buses) return [None] * nb def _getFlowLimits(self): rateA = [l.rate_a for l in self.env.market.case.online_branches] neg_rateA = [-1.0 * r for r in rateA] limits = zip(neg_rateA, rateA) # limits.extend(zip(neg_rateA, rateA)) return limits
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 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PYPOWER. If not, see <http://www.gnu.org/licenses/>. """ Defines a profit maximisation task. """ import logging from pybrain.rl.environments import Task from pyreto.discrete.task import ProfitTask as DiscreteProfitTask 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):
#-------------------------------------------------------------------------- # "Task" interface: #-------------------------------------------------------------------------- # def getObservation(self): # """ A filtered mapping to getSample of the underlying environment. """ # # sensors = self.env.getSensors() # print "SENSORS:", sensors # if self.sensor_limits: # sensors = self.normalize(sensors) # # return sensors def performAction(self, action): """ Execute one action. """ # print "ACTION:", action self.t += 1 Task.performAction(self, action) # self.addReward() self.samples += 1 #-------------------------------------------------------------------------- # "ProfitTask" interface: #-------------------------------------------------------------------------- def _getActorLimits(self): """ Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)], one tuple per parameter, giving min and max for that parameter. """ actorLimits = [] for _ in range(self.env.numOffbids): for _ in self.env.generators: actorLimits.append((0.0, self.env.maxMarkup)) 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(self): """ Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)], one tuple per parameter, giving min and max for that parameter. """ limits = [] limits.extend(self._getTotalDemandLimits()) # limits.extend(self._getDemandLimits()) # limits.extend(self._getPriceLimits()) # limits.extend(self._getVoltageSensorLimits()) # limits.extend(self._getVoltageMagnitudeLimits()) # limits.extend(self._getVoltageAngleLimits()) # limits.extend(self._getVoltageLambdaLimits()) # limits.extend(self._getFlowLimits()) logger.debug("Sensor limits: %s" % limits) return limits # limits = [] # # # Market sensor limits. # limits.append((1e-6, BIGNUM)) # f # pLimit = 0.0 # for g in self.env.generators: # if g.is_load: # pLimit += self.env._g0[g]["p_min"] # else: # pLimit += self.env._g0[g]["p_max"] # limits.append((0.0, pLimit)) # quantity ## cost = max([g.total_cost(pLimit, ## self.env._g0[g]["p_cost"], ## self.env._g0[g]["pcost_model"]) \ ## for g in self.env.generators]) # cost = self.env.generators[0].total_cost(pLimit, # self.env._g0[g]["p_cost"], self.env._g0[g]["pcost_model"]) # limits.append((0.0, cost)) # mcp # # # Case sensor limits. ## limits.extend([(-180.0, 180.0) for _ in case.buses]) # Va # limits.extend([(0.0, BIGNUM) for _ in case.buses]) # P_lambda # # limits.extend([(-b.rate_a, b.rate_a) for b in case.branches]) # Pf ## limits.extend([(-BIGNUM, BIGNUM) for b in case.branches]) # mu_f # # limits.extend([(g.p_min, g.p_max) for g in case.generators]) # Pg ## limits.extend([(-BIGNUM, BIGNUM) for g in case.generators]) # Pg_max ## limits.extend([(-BIGNUM, BIGNUM) for g in case.generators]) # Pg_min def _getTotalDemandLimits(self): Pdmax = sum([b.p_demand for b in self.env.market.case.buses]) return [(self.env.Pd_min, Pdmax)] def _getDemandLimits(self): limits = [(0.0, b.p_demand) for b in self.env.market.case.buses if b.type == PQ] return limits def _getPriceLimits(self): mcpLimit = (0.0, self.env.market.priceCap) sysLimit = (0.0, self.fmax) return [mcpLimit, sysLimit] def _getVoltageSensorLimits(self): limits = [] for bus in self.env.market.case.connected_buses: if bus.type == PV: limits.append(None) else: limits.append((bus.v_min, bus.v_max)) return limits def _getVoltageMagnitudeLimits(self): limits = [] Vmax = [b.v_max for b in self.env.market.case.connected_buses] Vmin = [b.v_min for b in self.env.market.case.connected_buses] limits.extend(zip(Vmin, Vmax)) # nb = len(self.env.market.case.connected_buses) # limits.extend([(-180.0, 180.0)] * nb) return limits def _getVoltageAngleLimits(self): limits = [] nb = len(self.env.market.case.connected_buses) limits.extend([(-180.0, 180.0)] * nb) return limits def _getVoltageLambdaLimits(self): nb = len(self.env.market.case.connected_buses) return [None] * nb def _getFlowLimits(self): rateA = [l.rate_a for l in self.env.market.case.online_branches] neg_rateA = [-1.0 * r for r in rateA] limits = zip(neg_rateA, rateA) # limits.extend(zip(neg_rateA, rateA)) return limits
super(ProfitTask, self).__init__(environment, maxSteps, discount) #---------------------------------------------------------------------- # "Task" interface: #---------------------------------------------------------------------- #: Limits for scaling of sensors. self.sensor_limits = self._getSensorLimits() #: Limits for scaling of actors. self.actor_limits = self._getActorLimits()
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 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 } createArgument(): Argument { return { contents: this.text } } }
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.iSpeech this.iArgument = cursor.iArgument this.text = 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 }
(): 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 } createArgument(): Argument { return { contents: this.text } } }
{ 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 we can make an ambient/global definition in * this file for now. For example declare module 'my-module' { export function doesSomething(value: string): string; } * If you are using a CommonJS module that is using module.exports then you will have to write your * types using export = yourObjectOrFunction with a namespace above it * notice how we have to create a namespace that is equal to the function we're * assigning the export to declare module 'jwt-decode' { function jwtDecode(token: string): any; namespace jwtDecode {} export = jwtDecode; } * * If you're prototying and you will fix the types later you can also declare it as type any * declare var assert: any;
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 the @types * */ // support NodeJS modules without type definitions declare module '*'; /* // for legacy tslint etc to understand rename 'modern-lru' with your package // then comment out `declare module '*';`. For each create module copy/paste // this method of creating an `any` module type definition declare module 'modern-lru' { let x: any; export = x; } */ // Extra variables that live on Global that will be replaced by webpack DefinePlugin declare var ENV: string; interface WebpackModule { hot: { data?: any, idle: any, accept(dependencies?: string | string[], callback?: (updatedDependencies?: any) => void): void; decline(deps?: any | string | string[]): void; dispose(callback?: (data?: any) => void): void; addDisposeHandler(callback?: (data?: any) => void): void; removeDisposeHandler(callback?: (data?: any) => void): void; check(autoApply?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void; apply(options?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void; status(callback?: (status?: string) => void): void | string; removeStatusHandler(callback?: (status?: string) => void): void; }; } interface WebpackRequire { (id: string): any; (paths: string[], callback: (...modules: any[]) => void): void; ensure(ids: string[], callback: (req: WebpackRequire) => void, chunkName?: string): void; context(directory: string, useSubDirectories?: boolean, regExp?: RegExp): WebpackContext; } interface WebpackContext extends WebpackRequire { keys(): string[]; } interface ErrorStackTraceLimit { stackTraceLimit: number; } // Extend typings interface NodeRequire extends WebpackRequire {} interface ErrorConstructor extends ErrorStackTraceLimit {} interface NodeModule extends WebpackModule {}
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 y = self.y - other.y z = self.z - other.z return Vector(x, y, z) def dot_product(self, other): return self.x * other.x + self.y * other.y + self.z * other.z def cross_product(self, other): zero = Vector(0, 0, 0) x = self.y * other.z - self.z * other.y y = self.z * other.x - self.x * other.z z = self.x * other.y - self.y * other.x return zero.subtract(Vector(x, y, z)) def value(self): xx = math.pow(self.x, 2) yy = math.pow(self.y, 2) zz = math.pow(self.z, 2) return math.sqrt(xx + yy + zz) def torsional_angle(a, b, c, d): ab = a.subtract(b) bc = b.subtract(c) cd = c.subtract(d) x = ab.cross_product(bc) y = bc.cross_product(cd) cosine = x.dot_product(y) / (x.value() * y.value())
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__ == '__main__': # pragma: no cover main() class TestCode(unittest.TestCase): def generalized_test(self, which): sys.stdin = open(__file__.replace('.py', f'.{which}.in'), 'r') sys.stdout = io.StringIO() expected = open(__file__.replace('.py', f'.{which}.out'), 'r') main() self.assertEqual(sys.stdout.getvalue(), expected.read()) for handle in [sys.stdin, sys.stdout, expected]: handle.close() def test_0(self): self.generalized_test('0')
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 y = self.y - other.y z = self.z - other.z return Vector(x, y, z) def dot_product(self, other): return self.x * other.x + self.y * other.y + self.z * other.z def cross_product(self, other): zero = Vector(0, 0, 0) x = self.y * other.z - self.z * other.y y = self.z * other.x - self.x * other.z z = self.x * other.y - self.y * other.x return zero.subtract(Vector(x, y, z)) def value(self): xx = math.pow(self.x, 2) yy = math.pow(self.y, 2) zz = math.pow(self.z, 2) return math.sqrt(xx + yy + zz) def torsional_angle(a, b, c, d): ab = a.subtract(b) bc = b.subtract(c) cd = c.subtract(d) x = ab.cross_product(bc) y = bc.cross_product(cd) cosine = x.dot_product(y) / (x.value() * y.value()) return math.degrees(math.acos(cosine)) 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__ == '__main__': # pragma: no cover main() class TestCode(unittest.TestCase): def generalized_test(self, which): sys.stdin = open(__file__.replace('.py', f'.{which}.in'), 'r') sys.stdout = io.StringIO() expected = open(__file__.replace('.py', f'.{which}.out'), 'r') main() self.assertEqual(sys.stdout.getvalue(), expected.read()) for handle in [sys.stdin, sys.stdout, expected]: handle.close() def test_0(self):
self.generalized_test('0')
identifier_body