code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function test_strategy self begin assert equal call strategy tuple 6 6 6 6 1 6 tuple 25.0 tuple 6 6 6 6 assert equal call strategy tuple 6 6 6 6 5 6 tuple 25.0 tuple 6 6 6 6 assert equal call strategy tuple 6 6 6 6 6 6 tuple 30.0 tuple 6 6 6 6 6 assert equal call strategy tuple 6 6 6 5 5 6 tuple 20.0 tuple 6 6 6 call a...
def test_strategy(self): self.assertEqual(strategy((6, 6, 6, 6, 1), 6), (25.0, (6, 6, 6, 6))) self.assertEqual(strategy((6, 6, 6, 6, 5), 6), (25.0, (6, 6, 6, 6))) self.assertEqual(strategy((6, 6, 6, 6, 6), 6), (30.0, (6, 6, 6, 6, 6))) self.assertEqual(strategy((6, 6, 6, 5, 5), 6), (20.0,...
Python
nomic_cornstack_python_v1
function maxDifference arr begin set n = length arr set max_diff = arr at 1 - arr at 0 for i in range 0 n begin for j in range i + 1 n begin if arr at j - arr at i > max_diff begin set max_diff = arr at j - arr at i end end end return max_diff end function set arr = list 3 8 9 6 4 10 print call maxDifference arr
def maxDifference(arr): n = len(arr) max_diff = arr[1] - arr[0] for i in range(0, n): for j in range(i + 1, n): if (arr[j] - arr[i] > max_diff): max_diff = arr[j] - arr[i] return max_diff arr = [3, 8, 9, 6, 4, 10] print( maxDifference(arr))
Python
flytech_python_25k
function drive_leds begin set next = rotator at 3 == 1 set next = rotator at 2 == 1 set next = rotator at 1 == 1 set next = rotator at 0 == 1 end function
def drive_leds(): pins.D4.next = rotator[3] == 1 pins.D3.next = rotator[2] == 1 pins.D2.next = rotator[1] == 1 pins.D1.next = rotator[0] == 1
Python
nomic_cornstack_python_v1
comment calculate chi square and fisher exact on the file with 4 descriptive comment entries and 4 data entries: Cntrl A, Cntrl B, Cndtn A, Cndtn B. import scipy.stats import numpy as np from numpy import * from array import * import string set file = open LOCATION_INPUT + INPUT string r set newfile = open LOCATION_OUT...
#calculate chi square and fisher exact on the file with 4 descriptive # entries and 4 data entries: Cntrl A, Cntrl B, Cndtn A, Cndtn B. ################################################################### import scipy.stats import numpy as np from numpy import * from array import * import string file = open(LOCATION_I...
Python
zaydzuhri_stack_edu_python
import os import sys import urllib from time import sleep set url = string http://cpaexam.cicpa.org.cn function getcode url begin return call getcode end function while platform == string darwin begin try begin set status = call getcode url if status in list 200 301 begin for i in range 10 begin call system string say ...
import os import sys import urllib from time import sleep url = "http://cpaexam.cicpa.org.cn" def getcode(url): return urllib.urlopen(url).getcode() while sys.platform == 'darwin': try: status = getcode(url) if status in [200, 301]: for i in range(10): ...
Python
zaydzuhri_stack_edu_python
function bind_attribute self location attrib_name begin if _program_id is not none begin raise call RuntimeError string Error while trying to call bind_attribute for an already compiled shader program. end set _attributes at location = attrib_name end function
def bind_attribute(self, location, attrib_name): if self._program_id is not None: raise RuntimeError("Error while trying to call bind_attribute "\ "for an already compiled shader program.""") self._attributes[location] = attrib_name
Python
nomic_cornstack_python_v1
function War A B N begin set score = 0 set i = 0 set j = 0 while i < N and j < N begin set c = 0 while j < N and A at i > B at j begin set j = j + 1 set c = c + 1 end set score = score + c set i = i + 1 set j = j + 1 end return score end function function DWar A B N begin set i = 0 set j = 0 set score = 0 comment Fase ...
def War (A, B, N): score = 0 i = 0 j = 0 while i<N and j<N: c = 0 while j<N and A[i]>B[j]: j += 1 c += 1 score += c i += 1 j += 1 return score def DWar (A, B, N): i = 0 j = 0 score = 0 # Fase 1 big removal while N>=1 and B[-1] > A[-1]: A.pop(0) B.pop() N = A.__len...
Python
zaydzuhri_stack_edu_python
function delete_notification request noti_id begin set user = user delete return call redirect string show_notifications end function
def delete_notification(request, noti_id): user = request.user Notification.objects.filter(id=noti_id, user=user).delete() return redirect('show_notifications')
Python
nomic_cornstack_python_v1
function contact_list self contact_list begin set _contact_list = contact_list end function
def contact_list(self, contact_list): self._contact_list = contact_list
Python
nomic_cornstack_python_v1
function add_player self player_id player_state begin assert player_id not in player_states set player_states at player_id = player_state end function comment logger.info("TRYING TO GET GAME STATE") comment import ipdb; ipdb.set_trace() comment self.game_state.player_states.set(player_id, player_state, sync=True) comme...
def add_player(self, player_id, player_state): assert player_id not in self.game_state.player_states self.game_state.player_states[player_id] = player_state #logger.info("TRYING TO GET GAME STATE") # import ipdb; ipdb.set_trace() # self.game_state.player_states.set(player_id, pla...
Python
nomic_cornstack_python_v1
function load_fbf file_name in_dir=string . begin comment get the data from the file set var_workspace = call Workspace dir=in_dir set fbf_attr_name = split file_name string . at 0 set raw_data = var_workspace at fbf_attr_name at slice : : return tuple raw_data fbf_attr_name end function
def load_fbf (file_name, in_dir='.') : # get the data from the file var_workspace = Workspace.Workspace(dir=in_dir) fbf_attr_name = file_name.split(".")[0] raw_data = var_workspace[fbf_attr_name][:] return raw_data, fbf_attr_name
Python
nomic_cornstack_python_v1
function _gather_utxos self value begin set remaining_value = value set gathered_utxo = set for utxo in filter lambda utxo -> not pending values _my_utxo begin if remaining_value <= 0 begin break end set remaining_value = remaining_value - value add gathered_utxo utxo end if remaining_value > 0 begin raise call ValueEr...
def _gather_utxos(self, value: int) -> tuple[set[UTXO], int]: remaining_value = value gathered_utxo = set() for utxo in filter(lambda utxo: not utxo.pending, self._my_utxo.values()): if remaining_value <= 0: break remaining_value -= utxo.value ...
Python
nomic_cornstack_python_v1
function is_processor_mcdram_available self begin try begin return call is_processor_mcdram_available end except AttributeError begin return false end end function
def is_processor_mcdram_available(self): try: return self._device.is_processor_mcdram_available() except AttributeError: return False
Python
nomic_cornstack_python_v1
function comment self text begin set circuit = self while not has attribute circuit string get_qregs begin set circuit = circuit end set qubits = list comprehension tuple qregister j for qregister in values call get_qregs for j in range length qregister return call _attach call Comment text qubits self end function
def comment(self, text:str): circuit = self while not hasattr(circuit, 'get_qregs'): circuit = circuit.circuit qubits = [(qregister, j) for qregister in circuit.get_qregs().values() for j in range(len(qregister)) ] return self._attach(Comment(text, qubits, self))
Python
nomic_cornstack_python_v1
function _set_minth self v load=false begin if has attribute v string _utype begin set v = call _utype v end try begin set t = call YANGDynClass v base=call RestrictedClassType base_type=long restriction_dict=dict string range list string 0..18446744073709551615 int_size=64 is_leaf=true yang_name=string minth parent=se...
def _set_minth(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="minth", parent=self, path_helper=self._path_helper, extmetho...
Python
nomic_cornstack_python_v1
import sys set id = 0 function fileToLineInfoArray infile begin with open infile string r as data begin set lines = read lines data end return list comprehension tuple length split line string - 1 strip line for line in lines end function function makeId begin global id set id = id + 1 return format string n{} id end f...
import sys id = 0 def fileToLineInfoArray( infile ): with open( infile, 'r' ) as data: lines = data.readlines() return [ ( len( line.split('\t') ) - 1, line.strip() ) for line in lines ] def makeId(): global id id += 1 return 'n{}'.format( id ) def buildTree...
Python
zaydzuhri_stack_edu_python
function get_penalty state action winrate_predictor begin if call violate_rule state action begin return - 1 end return 0 end function
def get_penalty(state, action, winrate_predictor): if violate_rule(state, action): return -1 return 0
Python
nomic_cornstack_python_v1
import gi call require_version string Gtk string 3.0 from gi.repository import Gtk as gtk class MainWindow extends Window begin function __init__ self begin call __init__ self title=string GtkFilechooserButton Demo call set_default_size 200 150 set scrolled_win = call ScrolledWindow add self scrolled_win set vbox = cal...
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk as gtk class MainWindow(gtk.Window): def __init__(self): gtk.Window.__init__(self, title='GtkFilechooserButton Demo') self.set_default_size(200, 150) self.scrolled_win = gtk.ScrolledWindow() self.add(self.scrolled_win) ...
Python
zaydzuhri_stack_edu_python
function max_metric self begin if call empty_list metric_data begin comment empty dict return dictionary end else begin return max metric_data key=lambda x -> maxsize / x at string comm_vol end end function
def max_metric(self) -> Dict: if self.empty_list(self.metric_data): return dict() # empty dict else: return max(self.metric_data, key=lambda x: x["queue"].maxsize / x["comm_vol"])
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt set yy_pred = gbdty_pred set yy_real = gbdty_test function sample y begin import random set index = random sample range length y 800 return index end function set index = random sample yy_pred set y_pred_sample = yy_pred at index set y_real_sample = iloc at index set samples = zip y_real...
import matplotlib.pyplot as plt yy_pred = gbdty_pred yy_real = gbdty_test def sample(y): import random index=random.sample(range(len(y)),800) return index index = sample(yy_pred) y_pred_sample = yy_pred[index] y_real_sample = yy_real.iloc[index] samples = zip(y_real_sample,y_pred_sample) samples = sor...
Python
zaydzuhri_stack_edu_python
class Circuit begin set name = string set location = string set country = string function __init__ self name location country begin set name = name set location = location set country = country end function function __str__ self begin return format string Circuit: {} --- Locality: {} --- Country: {} name location co...
class Circuit: name = "" location = "" country = "" def __init__(self, name, location, country): self.name = name self.location = location self.country = country def __str__(self): return "Circuit: {} --- Locality: {} --- Country: {}".format( self.name, ...
Python
zaydzuhri_stack_edu_python
function test_get_absolute_url self begin set account = call AccountFactory username=string billy assert equal call get_absolute_url string /pinboard/billy/ end function
def test_get_absolute_url(self): account = AccountFactory(username="billy") self.assertEqual(account.get_absolute_url(), "/pinboard/billy/")
Python
nomic_cornstack_python_v1
function convert_epsg_3857_to_epsg_4326 x y begin set longitude = x * factor1 set latitude = factor2 * call atan exp y * factor3 - 90 return tuple latitude longitude end function
def convert_epsg_3857_to_epsg_4326(x, y): longitude = x * factor1 latitude = factor2 * math.atan(math.exp(y * factor3)) - 90 return latitude, longitude
Python
nomic_cornstack_python_v1
comment app.py - a minimal flask api using flask_restful from flask import Flask from flask import request import os import requests set servidorA = string http://34.122.6.193/ set servidorB = string http://35.232.235.137/ set app = call Flask __name__ decorator call route string /imp methods=list string POST function ...
# app.py - a minimal flask api using flask_restful from flask import Flask from flask import request import os import requests servidorA = 'http://34.122.6.193/' servidorB = 'http://35.232.235.137/' app = Flask(__name__) @app.route('/imp', methods=['POST']) def imp(): json = request.form.to_dict() # Consultar ...
Python
zaydzuhri_stack_edu_python
function get_offices begin set offices = call Office set all_offices = call fetch_all_offices if not all_offices begin return call make_response call jsonify dict string status 404 ; string error string There are no registered offices yet 404 end set response = call jsonify dict string status 200 ; string data all_offi...
def get_offices(): offices = office_model.Office() all_offices = offices.fetch_all_offices() if not all_offices: return make_response(jsonify({ 'status':404, 'error':'There are no registered offices yet' }),404) response = jsonify({ 'status':...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np function load_data file verbose=false begin set data = read csv format string {0}.csv file if verbose begin print string * * 100 print string print info print string print string * * 100 print string print call shape print string print string * * 100 print string print head data e...
import pandas as pd import numpy as np def load_data(file,verbose=False): data=pd.read_csv('{0}.csv'.format(file)) if verbose: print('\n*'*100) print('\n') print(data.info()) print('\n') print('\n*'*100) print('\n') print(data.shape()) print('\n')...
Python
zaydzuhri_stack_edu_python
import pygame import random import os class Hero extends Sprite begin function __init__ self begin set image_adress = join path string Game string grass.png set my_image = call convert_alpha set my_image = call scale my_image tuple 50 50 set x = 300 set y = 20 set rect = call Rect x + 14 y + 37 20 15 end function funct...
import pygame import random import os class Hero(pygame.sprite.Sprite): def __init__(self): self.image_adress = os.path.join('Game', 'grass.png') self.my_image = pygame.image.load(self.image_adress).convert_alpha() self.my_image = pygame.transform.scale(self.my_image, (50, 50)) ...
Python
zaydzuhri_stack_edu_python
function plotTermApparitionInTimeWithOrder tweets topTermOrder=0 granularity=3600 dyadic=true begin set firstTweet = min tweets key=lambda tweet -> time set lastTweet = max tweets key=lambda tweet -> time set lastIndex = integer call delay firstTweet / granularity set agg = dict set tuple TFIDFVectors TweetPerTermMap ...
def plotTermApparitionInTimeWithOrder(tweets,topTermOrder=0, granularity=3600, dyadic=True) : firstTweet=min(tweets, key=lambda tweet : tweet.time) lastTweet=max(tweets, key=lambda tweet : tweet.time) lastIndex=int(lastTweet.delay(firstTweet)/granularity) agg={} TFIDFVectors,TweetPerTermMap=getTweet...
Python
nomic_cornstack_python_v1
function secondsLeft self begin return if expression secondsPassed >= secondsTotal then 0 else secondsTotal - secondsPassed end function
def secondsLeft(self)->int: return 0 if self.secondsPassed >= self.secondsTotal else self.secondsTotal - self.secondsPassed
Python
nomic_cornstack_python_v1
function test_militaryconflicts_get self begin set query_string = list tuple string label string label_example tuple string page 1 tuple string per_page 100 set headers = dict string Accept string application/json set response = open string /v0.0.1/militaryconflicts method=string GET headers=headers query_string=query_...
def test_militaryconflicts_get(self): query_string = [('label', 'label_example'), ('page', 1), ('per_page', 100)] headers = { 'Accept': 'application/json', } response = self.client.open( '/v0.0.1/militaryconflicts',...
Python
nomic_cornstack_python_v1
function thread_priority self begin return call Demapper_ATSC_sptr_thread_priority self end function
def thread_priority(self): return _mack_sdr_rossi_swig.Demapper_ATSC_sptr_thread_priority(self)
Python
nomic_cornstack_python_v1
function get_pv_args name session=none call=none begin string Get PV arguments for a VM .. code-block:: bash salt-cloud -a get_pv_args xenvm01 if call == string function begin raise call SaltCloudException string This function must be called with -a or --action. end if session is none begin debug string New session bei...
def get_pv_args(name, session=None, call=None): ''' Get PV arguments for a VM .. code-block:: bash salt-cloud -a get_pv_args xenvm01 ''' if call == 'function': raise SaltCloudException( 'This function must be called with -a or --action.' ) if session is Non...
Python
jtatman_500k
comment -*- coding: utf-8 -*- comment Filename: csort.py comment ----------------------------------- comment Revision: 2.0 comment Date: 2017-11-06 comment Author: mpdesign comment description: 排序算法库 comment ----------------------------------- import sys comment 快速排序算法 function quickSort data order=string asc by=string...
# -*- coding: utf-8 -*- # Filename: csort.py # ----------------------------------- # Revision: 2.0 # Date: 2017-11-06 # Author: mpdesign # description: 排序算法库 # ----------------------------------- import sys # 快速排序算法 def quickSort(data, order='asc', by=''): if len(data) > 1000: ...
Python
zaydzuhri_stack_edu_python
function map self func pds begin comment Tell the slaves to enter the map() with the current pds_id & func. comment Get pds_id of dataset we want to operate on set pds_id = pds_id comment Generate a new pds_id to be used by the slaves for the resultant PDS set pds_id_new = call __generate_new_pds_id set data = tuple pd...
def map(self, func, pds): # Tell the slaves to enter the map() with the current pds_id & func. #Get pds_id of dataset we want to operate on pds_id = pds.pds_id #Generate a new pds_id to be used by the slaves for the resultant PDS pds_id_new = self.__generate_new_pds_id() ...
Python
nomic_cornstack_python_v1
function scrub_swap self begin comment TODO: Load the file information from __init__ by discovering the swap comment area's content to avoid doing it each time here if _swap_size > max_swap_size and swap_dir begin set stats = dictionary comprehension name : call stat for dir_entry in call scandir swap_dir set data_file...
def scrub_swap(self): # TODO: Load the file information from __init__ by discovering the swap # area's content to avoid doing it each time here if self._swap_size > self.max_swap_size and self.swap_dir: stats = { dir_entry.name: dir_entry.stat() for di...
Python
nomic_cornstack_python_v1
function _process_result self result begin if string errorCode in result begin call _process_error result end else begin return result end end function
def _process_result(self, result): if "errorCode" in result: self._process_error(result) else: return result
Python
nomic_cornstack_python_v1
class myPoint begin function __init__ self xCoord yCoord begin set xCoord = xCoord set yCoord = yCoord end function function getX self begin return xCoord end function function getY self begin return yCoord end function end class set noOfPoints = integer call raw_input set pointList = list for i in range 0 noOfPoints ...
class myPoint(): def __init__(self,xCoord,yCoord): self.xCoord = xCoord self.yCoord = yCoord def getX(self): return self.xCoord def getY(self): return self.yCoord noOfPoints = int(raw_input()) pointList = [] for i in range (0, noOfPoints): s = raw_input() ...
Python
zaydzuhri_stack_edu_python
function test_is_virtual0001 self monkeypatch begin function fake_collect_dmesg_lines _ begin return list string real mem = 17074860032 (16283MB) string avail mem = 16550350848 (15783MB) string virtio3 at pci0 dev 4 function 0 "OpenBSD VMM Control" rev 0x00 end function set attribute OpenBSDPlatform string _collect_dme...
def test_is_virtual0001(self, monkeypatch): def fake_collect_dmesg_lines(_): return [ 'real mem = 17074860032 (16283MB)', 'avail mem = 16550350848 (15783MB)', 'virtio3 at pci0 dev 4 function 0 "OpenBSD VMM Control" rev 0x00', ] mon...
Python
nomic_cornstack_python_v1
function faixa_notas lista begin set lista1 = list set lista2 = list set lista3 = list set listaf = list a c b set x = 0 while x < length lista begin set a = length lista1 set b = length lista2 set c = length lista3 if lista at x < 5 begin append lista1 x end else if lista at x > 7 begin append lista3 x end else beg...
def faixa_notas(lista): lista1=[] lista2=[] lista3=[] listaf=[a,c,b] x=0 while x<len(lista): a=len(lista1) b=len(lista2) c=len(lista3) if lista[x]<5: lista1.append(x) elif lista[x]>7: lista3.append(x) else: lista...
Python
zaydzuhri_stack_edu_python
comment print 5**5 function story **kwds begin return string Once upon a time, there was a %(job)s called %(name)s. % kwds end function
#print 5**5 def story(**kwds): return 'Once upon a time, there was a %(job)s called %(name)s.' %kwds
Python
zaydzuhri_stack_edu_python
from flask import request from functools import wraps from time import gmtime , strftime from jose import jwt comment Format error response and append status code function get_token_auth_header begin string Obtains the Access Token from the Authorization Header set auth = get headers string Authorization none if not au...
from flask import request from functools import wraps from time import gmtime, strftime from jose import jwt # Format error response and append status code def get_token_auth_header(): """Obtains the Access Token from the Authorization Header """ auth = request.headers.get("Authorization", None) if no...
Python
zaydzuhri_stack_edu_python
import os , json from Channels import Channel from Listeners import ListenerFactory from Senders import SenderFactory function read_channels_from_configfile configfile begin if not exists path configfile or not is file path configfile begin raise call ConfigFileError string Non-existent configuration file specified end...
import os, json from Channels import Channel from Listeners import ListenerFactory from Senders import SenderFactory def read_channels_from_configfile(configfile): if not os.path.exists(configfile) or not os.path.isfile(configfile): raise ConfigFileError("Non-existent configuration file specified") wi...
Python
zaydzuhri_stack_edu_python
function create_heat_map self ax=none block=true begin figure set ax = call heatmap data=data fmt=string cmap=string RdYlGn linewidths=0.3 ax=ax call invert_yaxis set xlabel=string Books index ylabel=string Books values over iterations title=string Heat map for the prediction result of each book over iterations end fu...
def create_heat_map(self, ax=None, block=True): plt.figure() ax = sns.heatmap(data=self.data, fmt="", cmap='RdYlGn', linewidths=0.3, ax=ax) ax.invert_yaxis() ax.set(xlabel='Books index', ylabel='Books values over iterations', title='Heat map for the prediction result' ...
Python
nomic_cornstack_python_v1
import sys import struct import time import binascii comment You can use this method to exit on failure conditions. function bork msg begin exit msg end function comment Some constants. You shouldn't need to change these. set MAGIC = 2343432205 set VERSION = 1 if length argv < 2 begin exit string Usage: python stub.py ...
import sys import struct import time import binascii # You can use this method to exit on failure conditions. def bork(msg): sys.exit(msg) # Some constants. You shouldn't need to change these. MAGIC = 0x8BADF00D VERSION = 1 if len(sys.argv) < 2: sys.exit("Usage: python stub.py input_file.fpff") # Normally ...
Python
zaydzuhri_stack_edu_python
function register_object self begin comment push to core set core = call DataoneCore uuid string data package try begin add DBSession core commit DBSession flush DBSession call refresh core end except any begin rollback DBSession raise end comment push to obsolete set obsolete = call DataoneObsolete id try begin add DB...
def register_object(self): #push to core core = DataoneCore(self.uuid, 'data package') try: DBSession.add(core) DBSession.commit() DBSession.flush() DBSession.refresh(core) except: DBSession.rollback() raise ...
Python
nomic_cornstack_python_v1
from collections import deque function solution bridge_length weight truck_weights begin set answer = 0 set bridge = deque list 0 * bridge_length set truck_weights = deque truck_weights while length truck_weights != 0 or length bridge != 0 begin call popleft set tmp = 0 if truck_weights begin if sum bridge + truck_weig...
from collections import deque def solution(bridge_length, weight, truck_weights): answer = 0 bridge = deque([0] * bridge_length) truck_weights = deque(truck_weights) while len(truck_weights) != 0 or len(bridge) != 0: bridge.popleft() tmp = 0 if truck_weights: ...
Python
zaydzuhri_stack_edu_python
function _find_all_groups items require_bam=true begin string Find all groups set all_groups = list for data in items begin set batches = call _get_batches data require_bam append all_groups batches end return all_groups end function
def _find_all_groups(items, require_bam=True): """Find all groups """ all_groups = [] for data in items: batches = _get_batches(data, require_bam) all_groups.append(batches) return all_groups
Python
jtatman_500k
function allocate_pacs visible_special_pellet visible_normal_pellet pac_list width height initial_pallets_list begin set allocation_list = list for pellet in visible_special_pellet begin if length pac_list == 0 begin break end set node = list pellet at 0 pellet at 1 set nodes = list comprehension list x at string x x ...
def allocate_pacs(visible_special_pellet, visible_normal_pellet, pac_list, width, height, initial_pallets_list): allocation_list = [] for pellet in visible_special_pellet: if len(pac_list) == 0: break node = [pellet[0], pellet[1]] nodes = [[x['x'], x['y']] for x in pac_lis...
Python
nomic_cornstack_python_v1
from numpy import dot , sum , tile , linalg from numpy.linalg import inv comment KALMAN FILTER ALGORITHM comment PREDICTION STEP comment INPUT: X(mean state estimate of previous step); P(state covariance of previous step); A(transition n x n matrix); Q(process noise covariance matrix); B(input effect matrix); U(control...
from numpy import dot, sum, tile, linalg from numpy.linalg import inv ### KALMAN FILTER ALGORITHM ### PREDICTION STEP # INPUT: X(mean state estimate of previous step); P(state covariance of previous step); A(transition n x n matrix); Q(process noise covariance matrix); B(input effect matrix); U(control input) de...
Python
zaydzuhri_stack_edu_python
function signalify_fetch_all queryset parser=none **context begin string Signal lazy load when `QuerySet._fetch_all` fetches rows. Note: patch `_fetch_all` instead of `iterator` since, as of Django 1.11, the former is used for all fetches while the latter is not. set func = _fetch_all decorator wraps func function wrap...
def signalify_fetch_all(queryset, parser=None, **context): """Signal lazy load when `QuerySet._fetch_all` fetches rows. Note: patch `_fetch_all` instead of `iterator` since, as of Django 1.11, the former is used for all fetches while the latter is not. """ func = queryset._fetch_all @functools.w...
Python
jtatman_500k
function retrieve_bumps_docs begin if exists BUMPS_SOURCE begin print string === Retrieve BUMPS Docs === set filenames = glob call joinpath BUMPS_SOURCE string dream-*.png comment filenames = [joinpath(BUMPS_SOURCE, "optimizer.rst")] comment filenames += glob(joinpath(BUMPS_SOURCE, "dream-*.png")) comment filenames += ...
def retrieve_bumps_docs(): if exists(BUMPS_SOURCE): print("=== Retrieve BUMPS Docs ===") filenames = glob(joinpath(BUMPS_SOURCE, "dream-*.png")) #filenames = [joinpath(BUMPS_SOURCE, "optimizer.rst")] #filenames += glob(joinpath(BUMPS_SOURCE, "dream-*.png")) #filenames += glob...
Python
nomic_cornstack_python_v1
from google.appengine.ext import db comment Google App Engine database driver class AppEngineDriver begin function __init__ self begin pass end function function query self query begin pass end function function execute self query params=false begin return call Resource call GqlQuery query end function function __del__...
from google.appengine.ext import db #Google App Engine database driver class AppEngineDriver: def __init__(self): pass def query(self, query): pass def execute(self, query, params=False): return Resource(db.GqlQuery(query)) def __del__(self): pass class Resource: ...
Python
zaydzuhri_stack_edu_python
function __ne__ self other begin return not self == other end function
def __ne__(self, other): return not self == other
Python
nomic_cornstack_python_v1
comment !/usr/bin/python string Usage: sudo ./portchecker-with-netstat.py The purpose of this script is to determine if there are any unexpected running applications that have ports open for listening. Its goal is to detect if the machine has been compromised. import socket import subprocess import re import syslog com...
#!/usr/bin/python """Usage: sudo ./portchecker-with-netstat.py The purpose of this script is to determine if there are any unexpected running applications that have ports open for listening. Its goal is to detect if the machine has been compromised.""" import socket import subprocess import re import syslog # # Updat...
Python
zaydzuhri_stack_edu_python
function _generate_phrases self sentences begin set phrase_list = set comment Create contender phrases from sentences. for sentence in sentences begin set word_list = call _tokenize sentence comment word_list = [word.lower() for word in wordpunct_tokenize(sentence)] update phrase_list call _get_phrase_list_from_words w...
def _generate_phrases(self, sentences): phrase_list = set() # Create contender phrases from sentences. for sentence in sentences: word_list = self.tokenizer._tokenize(sentence) # word_list = [word.lower() for word in wordpunct_tokenize(sentence)] phrase_list.u...
Python
nomic_cornstack_python_v1
for num1 in array begin set num2 = num1 - k if num2 in lookup begin print num1 num2 end end
for num1 in array: num2 = num1 - k if num2 in lookup: print(num1, num2)
Python
zaydzuhri_stack_edu_python
function _remove_dead_threads self begin for thread in _threads begin if not is alive thread begin remove _threads thread end end end function
def _remove_dead_threads(self) -> None: for thread in self._threads: if not thread.is_alive(): self._threads.remove(thread)
Python
nomic_cornstack_python_v1
comment @lc app=leetcode.cn id=477 lang=python comment [477] 汉明距离总和 comment https://leetcode-cn.com/problems/total-hamming-distance/description/ comment algorithms comment Medium (49.77%) comment Likes: 89 comment Dislikes: 0 comment Total Accepted: 6.2K comment Total Submissions: 12.2K comment Testcase Example: '[4,14...
# # @lc app=leetcode.cn id=477 lang=python # # [477] 汉明距离总和 # # https://leetcode-cn.com/problems/total-hamming-distance/description/ # # algorithms # Medium (49.77%) # Likes: 89 # Dislikes: 0 # Total Accepted: 6.2K # Total Submissions: 12.2K # Testcase Example: '[4,14,2]' # # 两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。 # ...
Python
zaydzuhri_stack_edu_python
import re set str = string aabbc12345def567 set match = search string (\d{1,5}).(\d{1,5}) str print call group 0 print call group 1 print call group 2 set m = match string (?P<first_name>\w+) (?P<last_name>\w+) string Henry Chen print call group string first_name print call group string last_name print call group 1 pri...
import re str='aabbc12345def567' match = re.search(r'(\d{1,5}).(\d{1,5})', str) print(match.group(0)) print(match.group(1)) print(match.group(2)) m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Henry Chen") print(m.group('first_name')) print(m.group('last_name')) print(m.group(1)) print(m.group(2))
Python
zaydzuhri_stack_edu_python
function energy_left self begin return get _battery_summary string energy_left end function
def energy_left(self) -> float: return self._battery_summary.get("energy_left")
Python
nomic_cornstack_python_v1
string This is the loadable seq2seq trainer library that is in charge of training details, loss compute, and statistics. See train.py for a use case of this library. Note: To make this a general library, we implement *only* mechanism things here(i.e. what to do), and leave the strategy things to users(i.e. how to do it...
""" This is the loadable seq2seq trainer library that is in charge of training details, loss compute, and statistics. See train.py for a use case of this library. Note: To make this a general library, we implement *only* mechanism things here(i.e. what to do), and leave the strategy ...
Python
zaydzuhri_stack_edu_python
class Solution begin function find132pattern1 self nums begin string :type nums: List[int] :rtype: bool set l = length nums if l < 3 begin return false end set s3 = - decimal string inf set i = l - 1 while i >= 0 begin if i > 0 and nums at i - 1 > nums at i begin set s3 = max list comprehension x for x in nums at slice...
class Solution: def find132pattern1(self, nums): """ :type nums: List[int] :rtype: bool """ l=len(nums) if l<3: return False s3=-float('inf') i=l-1 while i>=0: if i>0 and nums[i-1]>nums[i]: s3=max([x for ...
Python
zaydzuhri_stack_edu_python
function _estimate_frames_per_graph self seq_name begin set num_frames = length unique set num_detects = shape at 0 set avg_detects_per_frame = num_detects / decimal num_frames set expected_frames_per_graph = round dataset_params at string max_detects / avg_detects_per_frame return min expected_frames_per_graph dataset...
def _estimate_frames_per_graph(self, seq_name): num_frames = len(self.dataset.seq_det_dfs[seq_name].frame.unique()) num_detects = self.dataset.seq_det_dfs[seq_name].shape[0] avg_detects_per_frame = num_detects / float(num_frames) expected_frames_per_graph = round(self.dataset.dataset_pa...
Python
nomic_cornstack_python_v1
comment !/bin/python3 import sys function cats_and_a_mouse x y z begin if absolute x - z < absolute y - z begin return string Cat A end else if absolute x - z > absolute y - z begin return string Cat B end else begin return string Mouse C end end function function main begin set q = integer strip input for a0 in range ...
#!/bin/python3 import sys def cats_and_a_mouse(x,y,z): if abs(x-z) < abs(y-z): return "Cat A" elif abs(x-z) > abs(y-z): return "Cat B" else: return "Mouse C" def main(): q = int(input().strip()) for a0 in range(q): x,y,z = map(int, input().strip().split(' ')) print(cats_and_a_mouse(x,y,...
Python
zaydzuhri_stack_edu_python
function factorial n begin if n == 0 begin return 1 end else begin return n * call factorial n - 1 end end function
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
Python
jtatman_500k
function test_is_event_tornado_no_caps self begin set this_flag = call _is_event_tornado EVENT_TYPE_STRING_TORNADO_NO_CAPS assert true this_flag end function
def test_is_event_tornado_no_caps(self): this_flag = storm_events_io._is_event_tornado( EVENT_TYPE_STRING_TORNADO_NO_CAPS) self.assertTrue(this_flag)
Python
nomic_cornstack_python_v1
function hook_factory mask begin function hook grads begin return grads * mask end function return hook end function
def hook_factory(mask): def hook(grads): return grads * mask return hook
Python
nomic_cornstack_python_v1
function get_rest_result_template self result command success_code begin set result = dict string result result ; string command command ; string success_code success_code comment 0 - OK, >0 - Error number return result end function
def get_rest_result_template(self, result, command, success_code): result = {"result" : result, "command" : command, "success_code": success_code} # 0 - OK, >0 - Error number return result
Python
nomic_cornstack_python_v1
function authenticate url account key by=string name expires=0 timestamp=none timeout=none request_type=string xml admin_auth=false use_password=false raise_on_error=false begin string Authenticate to the Zimbra server :param url: URL of Zimbra SOAP service :param account: The account to be authenticated against :param...
def authenticate(url, account, key, by='name', expires=0, timestamp=None, timeout=None, request_type="xml", admin_auth=False, use_password=False, raise_on_error=False): """ Authenticate to the Zimbra server :param url: URL of Zimbra SOAP service :param account: The accoun...
Python
jtatman_500k
function __init__ self inputs lon_centroid lat_centroid distance abs_mag r_physical begin comment Stolen from ugali/scratch/simulation/simulate_population.py. Look there for a more general function, comment which uses maglims, extinction, stuff like that comment Probably don't want to parse every time set s = call Sour...
def __init__(self, inputs, lon_centroid, lat_centroid, distance, abs_mag, r_physical): # Stolen from ugali/scratch/simulation/simulate_population.py. Look there for a more general function, # which uses maglims, extinction, stuff like that # Probably don't want to parse every time s = u...
Python
nomic_cornstack_python_v1
function __fill_conversion_tab self begin call __fill_left_side_of_conversion_tab call __fill_right_side_of_conversion_tab end function
def __fill_conversion_tab(self): self.__fill_left_side_of_conversion_tab() self.__fill_right_side_of_conversion_tab()
Python
nomic_cornstack_python_v1
set a = 10 set b = 45 set s = string hello i am s. s. chauhan set c = string hello comment create one list set l1 = list 10 20 30 comment print address of list 1 print string Address of list 1 call id l1 print string Check is 'A variale' mamber of list 1 a in l1 print string check is 'B variale' mamber of list 1 b in l...
a=10 b=45 s="hello i am s. s. chauhan" c="hello" l1=[10,20,30]# create one list print("Address of list 1",id(l1))#print address of list 1 print("Check is 'A variale' mamber of list 1 ",a in l1) print("check is 'B variale' mamber of list 1 ",b in l1) print("check is 'B variale' is not mamber of list 1 ",b not in...
Python
zaydzuhri_stack_edu_python
function appMass2id_list self mass decimal_places=2 begin set return_list = call _appMass2whatever mass decimal_places=decimal_places entry_key=string unimodID return return_list end function
def appMass2id_list(self, mass, decimal_places=2): return_list = self._appMass2whatever( mass, decimal_places=decimal_places, entry_key="unimodID" ) return return_list
Python
nomic_cornstack_python_v1
comment Message Box Code ###### from tkinter import * set root = call Tk title root string Message Box grid padx=10 pady=10 call mainloop
###### Message Box Code ###### from tkinter import * root = Tk() root.title('Message Box') Label(root, justify=LEFT, text=s).grid(padx=10, pady=10) root.mainloop()
Python
zaydzuhri_stack_edu_python
function getRGB self begin return tuple rgb at slice : 3 : end function
def getRGB(self): return tuple(self.rgb[:3])
Python
nomic_cornstack_python_v1
function shuffle *items begin set items = list items shuffle random items return items end function
def shuffle(*items): items = list(items) random.shuffle(items) return items
Python
nomic_cornstack_python_v1
function get_section_data_by_name self name begin if get sections_data name is none begin set sections_data at name = data call get_section_by_name name end return sections_data at name end function
def get_section_data_by_name(self, name): if self.sections_data.get(name) is None: self.sections_data[name] = self.elffile.get_section_by_name(name).data() return self.sections_data[name]
Python
nomic_cornstack_python_v1
function IGetSegments self Count=defaultNamedNotOptArg begin set ret = call InvokeTypes 3 LCID 1 tuple 9 0 tuple tuple 3 1 Count if ret is not none begin set ret = call Dispatch ret string IGetSegments string {83A33DBF-27C5-11CE-BFD4-00400513BB57} end return ret end function
def IGetSegments(self, Count=defaultNamedNotOptArg): ret = self._oleobj_.InvokeTypes(3, LCID, 1, (9, 0), ((3, 1),),Count ) if ret is not None: ret = Dispatch(ret, u'IGetSegments', '{83A33DBF-27C5-11CE-BFD4-00400513BB57}') return ret
Python
nomic_cornstack_python_v1
function name self begin pass end function
def name(self) -> str: pass
Python
nomic_cornstack_python_v1
function allow_relation self obj1 obj2 **hints begin if db_tablespace == string emarket or db_tablespace == string emarket begin return true end return none end function
def allow_relation(self, obj1, obj2, **hints): if obj1._meta.db_tablespace == 'emarket' or \ obj2._meta.db_tablespace == 'emarket': return True return None
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment !/usr/bin/python import re import time import urllib import base64 import hmac import hashlib import requests import xml.etree.ElementTree as ET from xml.etree import ElementTree as et import codecs import xml.etree.cElementTree as EF from datetime import date comment import bitly_...
# -*- coding: utf-8 -*- #!/usr/bin/python import re import time import urllib import base64 import hmac import hashlib import requests import xml.etree.ElementTree as ET from xml.etree import ElementTree as et import codecs import xml.etree.cElementTree as EF from datetime import date #import bitly_api def aws_signe...
Python
zaydzuhri_stack_edu_python
function time_shift_spectrogram spectrogram begin set nb_cols = shape at 1 set nb_shifts = random integer 0 nb_cols return call roll spectrogram nb_shifts axis=1 end function
def time_shift_spectrogram(spectrogram): nb_cols = spectrogram.shape[1] nb_shifts = np.random.randint(0, nb_cols) return np.roll(spectrogram, nb_shifts, axis=1)
Python
nomic_cornstack_python_v1
function index request begin set highlight_index = true return call render request string index.html context=dict string highlight_index highlight_index end function
def index(request): highlight_index = True return render( request, 'index.html', context={'highlight_index':highlight_index} )
Python
nomic_cornstack_python_v1
import numpy as np import math from newtonPoly import * set xData = array list 0.15 2.3 3.15 4.85 6.25 7.95 set yData = array list 4.79867 4.49013 4.2243 3.47313 2.66674 1.51909 set a = call coeffts xData yData print string x yInterp yExact print string ----------------------- for x in array range 0.0 8.1 0.5 begin set...
import numpy as np import math from newtonPoly import * xData = np.array([0.15,2.3,3.15,4.85,6.25,7.95]) yData = np.array([4.79867,4.49013,4.2243,3.47313,2.66674,1.51909]) a = coeffts(xData,yData) print(" x yInterp yExact") print("-----------------------") for x in np.arange(0.0,8.1,0.5): y = evalPoly(a, xData, x)...
Python
zaydzuhri_stack_edu_python
function header_len self begin if num_lines_header is none begin set Nheader = 0 with call _compression_safe_file_opener input_fname string r as f begin for tuple i l in enumerate f begin if l at slice 0 : length header_char : == header_char or l == string begin set Nheader = Nheader + 1 end else begin break end end ...
def header_len(self): if self.num_lines_header is None: Nheader = 0 with self._compression_safe_file_opener(self.input_fname, "r") as f: for i, l in enumerate(f): if (l[0 : len(self.header_char)] == self.header_char) or ( l == "...
Python
nomic_cornstack_python_v1
function lookup_path self path begin set tuple full_path stat_result = call lookup_path path if stat_result is none and _fallback begin return _fallback end return tuple full_path stat_result end function
def lookup_path(self, path: str) -> typing.Tuple[str, typing.Optional[os.stat_result]]: full_path, stat_result = super().lookup_path(path) if stat_result is None and self._fallback: return self._fallback return (full_path, stat_result)
Python
nomic_cornstack_python_v1
from django import forms from models import Classroom , Submission from django.core.exceptions import ValidationError class CreateClassForm extends ModelForm begin set name = call CharField max_length=50 set subject = call CharField max_length=50 class Meta begin set model = Classroom set fields = tuple string name str...
from django import forms from .models import Classroom, Submission from django.core.exceptions import ValidationError class CreateClassForm(forms.ModelForm): name = forms.CharField(max_length=50) subject = forms.CharField(max_length=50) class Meta: model = Classroom fields = ('name', 'subj...
Python
zaydzuhri_stack_edu_python
from y01082f import get_fullname print string Enter 'a' at any time to quit while true begin set first = input string Please give me a first name: if first == string a begin break end set last = input string Please geve me a last name: if last == string a begin break end set full_name = call get_fullname first last pri...
from y01082f import get_fullname print("Enter 'a' at any time to quit") while True: first = input("\nPlease give me a first name: ") if first == 'a': break last = input("\nPlease geve me a last name: ") if last == 'a': break full_name = get_fullname(first,last) print("\tNeatly fu...
Python
zaydzuhri_stack_edu_python
function sorter file1 file2 begin set pattern = string (\d+)(-(\d+))?\.mp3 try begin set file1_index = call groups at 2 or 0 set file2_index = call groups at 2 or 0 return if expression integer file1_index < integer file2_index then - 1 else 1 end except any begin return 0 end end function
def sorter(file1, file2): pattern = '(\d+)(-(\d+))?\.mp3' try: file1_index = re.search(pattern, file1).groups()[2] or 0 file2_index = re.search(pattern, file2).groups()[2] or 0 return -1 if int(file1_index) < int(file2_index) else 1 e...
Python
nomic_cornstack_python_v1
comment Initialize variables set prev1 = 0 set prev2 = 1 comment Iterate ten times for i in range 10 begin comment Print current Fibonacci number print prev1 comment Calculate next Fibonacci number set current = prev1 + prev2 comment Update variables set prev1 = prev2 set prev2 = current end
# Initialize variables prev1 = 0 prev2 = 1 # Iterate ten times for i in range(10): # Print current Fibonacci number print(prev1) # Calculate next Fibonacci number current = prev1 + prev2 # Update variables prev1 = prev2 prev2 = current
Python
jtatman_500k
class Node begin function __init__ self data begin set data = data set next = none end function end class set head = call Node 0 set current = head for i in range 1 51 begin set next = call Node 2 * i set current = next end set current = head while current != none begin print data set current = next end
class Node: def __init__(self, data): self.data = data self.next = None head = Node(0) current = head for i in range(1, 51): current.next = Node(2 * i) current = current.next current = head while current != None: print(current.data) current= current.next ...
Python
zaydzuhri_stack_edu_python
function shift self dx dy begin for shape in shapes begin call shift dx dy end end function
def shift(self, dx, dy): for shape in self.shapes: shape.shift(dx, dy)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python string index.py for indexing the data with VSM import sys import nltk import getopt import os import math import string from collections import OrderedDict from nltk.stem.porter import PorterStemmer set doc_dir = string set dict_file = string set postings_file = string set total_num_doc = 0 ...
#!/usr/bin/python ''' index.py for indexing the data with VSM ''' import sys import nltk import getopt import os import math import string from collections import OrderedDict from nltk.stem.porter import PorterStemmer doc_dir = "" dict_file = "" postings_file = "" total_num_doc = 0 doc_dict = {} doc_length = {} ...
Python
zaydzuhri_stack_edu_python
function draw_tool_template self begin comment add tool_template to the draw items list set item = call draw_item add item work_canvas 0 0 append draw_list item end function
def draw_tool_template(self): #add tool_template to the draw items list item = draw_item() item.add(self.work_canvas,0,0) self.draw_list.append(item)
Python
nomic_cornstack_python_v1
function _addLineSegment self ls begin set alreadyIncluded = false for myls in _lineSegments begin if call contains ls begin set alreadyIncluded = true break end end if not alreadyIncluded begin append _lineSegments ls end end function
def _addLineSegment(self, ls: LineSegment) -> None: alreadyIncluded = False for myls in self._lineSegments: if myls.contains(ls): alreadyIncluded = True break if not alreadyIncluded: self._lineSegments.append(ls)
Python
nomic_cornstack_python_v1
comment printowanie inta print 3 comment printowanie stringów print string heeej print string hooo comment printowanie floata print 3.14 comment print może dostać dowolnie dużo argumentów - wypisze je wszystkie, oddzielając spacjami print 3 4 5 12 comment uwaga, to jest string (bo ma cudzysłowy) print string 3 comment ...
# printowanie inta print(3) # printowanie stringów print("heeej") print('hooo') # printowanie floata print(3.14) # print może dostać dowolnie dużo argumentów - wypisze je wszystkie, oddzielając spacjami print(3, 4, 5, 12) # uwaga, to jest string (bo ma cudzysłowy) print("3") # proste działania arytmetyczne print(2...
Python
zaydzuhri_stack_edu_python
string Módulo Collections - Named Tuple # recap Tupla tupla = (1, 2, 3) print(tupla) Named Tuple -> são tuplas, diferenciadas, onde, especificamos um nome para a mesma e também parâmetros from collections import namedtuple comment Precisamos definir o nome e parâmetros comment Forma 1 - Declaração Named Tuple set cacho...
""" Módulo Collections - Named Tuple # recap Tupla tupla = (1, 2, 3) print(tupla) Named Tuple -> são tuplas, diferenciadas, onde, especificamos um nome para a mesma e também parâmetros """ from collections import namedtuple # Precisamos definir o nome e parâmetros # Forma 1 - Declaração Named Tuple cachorro = named...
Python
zaydzuhri_stack_edu_python
function _build_reverse_lookup_table self feature_col distance_matrix dist_type begin set tmp_reverse_lookup = dictionary set tmp_index_lookup = distance_matrix_labels at distance_matrix comment Build reverse lookup for tuple i k in enumerate feature_table at feature_col begin set tmp_key = tmp_index_lookup at k if cal...
def _build_reverse_lookup_table( self, feature_col: str, distance_matrix: str, *, dist_type: Literal["boolean", "numberic"], ) -> ReverseLookupTable: tmp_reverse_lookup = dict() tmp_index_lookup = self.distance_matrix_labels[distance_matrix] # Build r...
Python
nomic_cornstack_python_v1
function plot_movie pos begin set tuple fig ax = call subplots set title = call text 0.5 0.85 string bbox=dict string facecolor string w ; string alpha 0.5 ; string pad 5 transform=transAxes ha=string center call set_xlim - bounds bounds call set_ylim - bounds bounds set scat_f = scatter ax 0 0 c=string green s=2 set ...
def plot_movie(pos): fig, ax = plt.subplots() title = ax.text(0.5, 0.85, "", bbox={'facecolor': 'w', 'alpha': 0.5, 'pad': 5}, transform=ax.transAxes, ha="center") ax.set_xlim(-bounds, bounds) ax.set_ylim(-bounds, bounds) scat_f = ax.scatter(0, 0, c='green', s=2) anim_f...
Python
nomic_cornstack_python_v1
function _cheese_at self stool_index stool_height begin if 0 <= stool_height < length _stools at stool_index begin return _stools at stool_index at stool_height end else begin return none end end function
def _cheese_at(self, stool_index, stool_height): if 0 <= stool_height < len(self._stools[stool_index]): return self._stools[stool_index][stool_height] else: return None
Python
nomic_cornstack_python_v1