code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function writeSingleFITS data wcs output template clobber=true verbose=true begin string Write out a simple FITS file given a numpy array and the name of another FITS file to use as a template for the output image header. set tuple outname outextn = call parseFilename output set tuple outextname outextver = call parseE...
def writeSingleFITS(data,wcs,output,template,clobber=True,verbose=True): """ Write out a simple FITS file given a numpy array and the name of another FITS file to use as a template for the output image header. """ outname,outextn = fileutil.parseFilename(output) outextname,outextver = fileutil.parse...
Python
jtatman_500k
from typing import Any from itertools import zip_longest from core.dsl import types from core.dsl.functions import get_function_spec from core.dsl.exceptions import SemanticException function parse_block block begin comment Evaluate map result to list so we can do comment type validation at script creation and not on r...
from typing import Any from itertools import zip_longest from core.dsl import types from core.dsl.functions import get_function_spec from core.dsl.exceptions import SemanticException def parse_block(block: types.Block): # Evaluate map result to list so we can do # type validation at script creation and not ...
Python
zaydzuhri_stack_edu_python
import os import numpy as np import torch from PIL import Image function load_keypoint_annotations path img_w img_h begin string Loads keypoints in annotation file at 'path' Returns keypoints set keypoints = list with open path string r as file begin for row in file begin set tuple x y _ = split row append keypoints l...
import os import numpy as np import torch from PIL import Image def load_keypoint_annotations(path, img_w, img_h): """ Loads keypoints in annotation file at 'path' Returns keypoints """ keypoints = [] with open(path, 'r') as file: for row in file: x, y , _ = row.spli...
Python
zaydzuhri_stack_edu_python
function register_signals self begin print string Plugin "%s" registered as "%s" % tuple __name__ name end function
def register_signals(self): print("Plugin \"%s\" registered as \"%s\"" % (self.__class__.__name__, self.__class__.Meta.name))
Python
nomic_cornstack_python_v1
function obj_create self bundle request=none **kwargs begin set obj = call object_class for tuple key value in items kwargs begin set attribute obj key value end set bundle = call full_hydrate bundle comment Save FKs just in case. call save_related bundle comment Save the SimulationModel object. save comment Trigger th...
def obj_create(self, bundle, request=None, **kwargs): bundle.obj = self._meta.object_class() for key, value in kwargs.items(): setattr(bundle.obj, key, value) bundle = self.full_hydrate(bundle) # Save FKs just in case. self.save_related(bundle) ...
Python
nomic_cornstack_python_v1
while i > 0 begin set fatorial = i * fatorial print format string x {} i end=string set i = i - 1 end print format string = {} fatorial
while i > 0: fatorial = i * fatorial print(' x {}'.format(i), end='') i -= 1 print(' = {}'.format(fatorial))
Python
zaydzuhri_stack_edu_python
function ComputeBranchName self begin call chdir_to_ffmpeg_home set branch_name = call output_or_error list string git string rev-parse string --abbrev-ref string HEAD call SetBranchName string branch_name end function
def ComputeBranchName(self): self.chdir_to_ffmpeg_home() branch_name = shell.output_or_error( ["git", "rev-parse", "--abbrev-ref", "HEAD"]) self.SetBranchName(str(branch_name))
Python
nomic_cornstack_python_v1
function bound_decorator self function begin if not is instance function Callable begin return none end function decorator *args **kwargs begin return call function self *args keyword kwargs end function return decorator end function
def bound_decorator(self, function): if not isinstance(function, Callable): return None def decorator(*args, **kwargs): return function(self, *args, **kwargs) return decorator
Python
nomic_cornstack_python_v1
function decode_var_len_uint8 br begin if call read_bits 1 begin set nbits = call read_bits 3 if nbits == 0 begin return 1 end return call read_bits nbits + 1 ? nbits end return 0 end function
def decode_var_len_uint8(br): if br.read_bits(1): nbits = br.read_bits(3) if nbits == 0: return 1 return br.read_bits(nbits) + (1 << nbits) return 0
Python
nomic_cornstack_python_v1
string loop through the grid and only check for item that has building in it (value = 1) save the cordinate of the checked item into hashmap by add_to_hash() function. The add_to_has function numberOfStores rows column grid begin comment WRITE YOUR CODE HERE function add_to_hash i j begin set hashmap at string i + stri...
""" loop through the grid and only check for item that has building in it (value = 1) save the cordinate of the checked item into hashmap by add_to_hash() function. The add_to_has """ def numberOfStores(rows, column, grid): # WRITE YOUR CODE HERE def add_to_hash(i, j): hashmap[str(i)+":"+str(j)] = 1 ...
Python
zaydzuhri_stack_edu_python
comment code taken from https://dash.plot.ly/datatable/dropdowns comment (version 1.9.1) pip install dash==1.9.1 import dash import dash_html_components as html import dash_table import pandas as pd from collections import OrderedDict comment We will cover all 3 DataTable Dropdown options: comment 1. per-Column Dropdow...
#code taken from https://dash.plot.ly/datatable/dropdowns import dash #(version 1.9.1) pip install dash==1.9.1 import dash_html_components as html import dash_table import pandas as pd from collections import OrderedDict # We will cover all 3 DataTable Dropdown options: # 1. per-Column Dropdowns (you choose column) # ...
Python
zaydzuhri_stack_edu_python
function partition L low high begin set pivot = L at high set i = low - 1 for j in range low high begin if L at j < pivot begin set i = i + 1 set tuple L at i L at j = tuple L at j L at i print L end end set tuple L at i + 1 L at high = tuple L at high L at i + 1 return i + 1 end function function quick_sort L low high...
def partition(L,low,high): pivot = L[high] i = low - 1 for j in range(low,high): if L[j]<pivot: i +=1 L[i],L[j] = L[j],L[i] print(L) L[i+1],L[high] = L[high],L[i+1] return i+1 def quick_sort(L,low,high): if low>=high: return ...
Python
zaydzuhri_stack_edu_python
function satisfies_upload_id_policy ptinfo begin if ID_POLICY_UPLOAD_TOKENIZED is none begin return false end return call satisfies_id_policy ID_POLICY_UPLOAD_TOKENIZED ptinfo end function
def satisfies_upload_id_policy(ptinfo): if ID_POLICY_UPLOAD_TOKENIZED is None: return False return satisfies_id_policy(ID_POLICY_UPLOAD_TOKENIZED, ptinfo)
Python
nomic_cornstack_python_v1
string Exceptions module. from typing import Optional class ProviderUnavailable extends Exception begin string Class to represent an when a provider is not working. set message = string Provider not working function __init__ self message=none begin if message begin set message = message end end function end class
"""Exceptions module.""" from typing import Optional class ProviderUnavailable(Exception): """Class to represent an when a provider is not working.""" message = 'Provider not working' def __init__(self, message: Optional[str] = None) -> None: if message: self.message = message
Python
zaydzuhri_stack_edu_python
function get_url self item begin set portal_properties = call get_tool name=string portal_properties set use_view_action = call getProperty string typesUseViewActionInListings tuple comment First we get the url for the item itself set url = call absolute_url if portal_type in use_view_action begin set url = url + strin...
def get_url(self, item): portal_properties = api.portal.get_tool(name='portal_properties') use_view_action = portal_properties.site_properties.getProperty( 'typesUseViewActionInListings', ()) # First we get the url for the item itself url = item.absolute_url() if item...
Python
nomic_cornstack_python_v1
function delete_subsite self subsite_id=string begin call retire subsite_id Subsite end function
def delete_subsite(self, subsite_id=''): self.RR2.retire(subsite_id, RT.Subsite)
Python
nomic_cornstack_python_v1
function transform self X y=none begin return dot X T end function
def transform(self, X, y=None): return np.dot(X, self.maps_.T)
Python
nomic_cornstack_python_v1
import glob , os , time_reader , crontab_manager , ConfigParser set config = config parser read config string ./config set FILE_DIR = get config string Directory string RECORDING_DIR change directory FILE_DIR string Sort and import all news into a list set news_list = list for news_file in sorted glob glob string *.ts...
import glob, os, time_reader, crontab_manager, ConfigParser config = ConfigParser.ConfigParser() config.read('./config') FILE_DIR = config.get('Directory', 'RECORDING_DIR') os.chdir(FILE_DIR) ''' Sort and import all news into a list ''' news_list = [] for news_file in sorted(glob.glob("*.ts")): news_list.append(...
Python
zaydzuhri_stack_edu_python
function train_model training_data validation_data hparams begin set tuple Adj X y = training_data set batch_size = hparams at string batch_size set epochs = hparams at string epoch set learning_rate = hparams at string learning_rate set lossfile = hparams at string lossfile set checkpoint = hparams at string checkpoin...
def train_model(training_data, validation_data, hparams): Adj, X, y = training_data batch_size = hparams["batch_size"] epochs = hparams["epoch"] learning_rate = hparams["learning_rate"] lossfile = hparams["lossfile"] checkpoint = hparams["checkpoint"] model = Net(learning_rate=learning_rate)...
Python
nomic_cornstack_python_v1
for i in range - 1000 1001 begin if i < 0 begin comment Make sure the number is positive for the algorithm set i = - i end set square = 0 for j in range i begin comment Add the number to itself for 'i' times to calculate the square set square = square + i end if i < 0 begin comment Convert the square back to negative i...
for i in range(-1000, 1001): if i < 0: i = -i # Make sure the number is positive for the algorithm square = 0 for j in range(i): square += i # Add the number to itself for 'i' times to calculate the square if i < 0: square = -square # Convert the square back to n...
Python
greatdarklord_python_dataset
function is_valid_email email begin try begin set split = split email string @ assert length split == 2 set domain = split at 1 assert string . in domain end except AssertionError begin return false end return true end function
def is_valid_email(email): try: split = email.split('@') assert len(split) == 2 domain = split[1] assert '.' in domain except AssertionError: return False return True
Python
nomic_cornstack_python_v1
function calc_fiability self include_other_felt=true include_heavy_appliance=false aggregate=false filter_floors=false begin set emails = call get_prop_values string email set felt_indexes = call calc_felt_index include_other_felt set motion_indexes = call filled 0 set reaction_indexes = call filled 0 set stand_indexes...
def calc_fiability(self, include_other_felt=True, include_heavy_appliance=False, aggregate=False, filter_floors=False): emails = self.get_prop_values('email') felt_indexes = self.calc_felt_index(include_other_felt) motion_indexes = self.calc_motion_index().filled(0) reaction_indexes = self.calc_react...
Python
nomic_cornstack_python_v1
function a begin set x = integer input string 请输入数字 set y = integer input string 请输入数字 for i in range x y begin for h in range 1 i + 1 begin print string %d*%d=%d % tuple x y x * y end=string end print string end end function while true begin call a end
def a(): x = int(input("请输入数字")) y = int(input("请输入数字")) for i in range(x,y): for h in range(1,i+1): print("%d*%d=%d\t"%(x,y,x*y),end = "") print("") while True: a()
Python
zaydzuhri_stack_edu_python
comment This program takes picture using picamera, and delete files older than 14 days. import picamera from datetime import datetime import os , time set camera = call PiCamera set resolution = tuple 512 384 comment adapted from http://blog.rackspacecloudreview.com/86-freebie-python-chron-to-delete-files-older-than-x/
# This program takes picture using picamera, and delete files older than 14 days. import picamera from datetime import datetime import os, time camera = picamera.PiCamera() camera.resolution = (512,384) # adapted from http://blog.rackspacecloudreview.com/86-freebie-python-chron-to-delete-files-older-than-x/
Python
zaydzuhri_stack_edu_python
function SignatureHashLegacy self script inIdx hashtype begin from script import FindAndDelete , CScript , OP_CODESEPARATOR set HASH_ONE = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' if inIdx >= length vin begin return tuple HASH_ON...
def SignatureHashLegacy(self, script, inIdx, hashtype): from .script import FindAndDelete, CScript, OP_CODESEPARATOR HASH_ONE = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' if inIdx >= len(self.vin): ...
Python
nomic_cornstack_python_v1
function addNote self note begin if type note is str begin if note == string sample begin set note = call getNotes top=1 return note at 0 end else begin raise exception string note must be a dictionary with valid + string fields, or the string 'sample' to + string request a sample object end end else if type note is di...
def addNote(self, note): if type(note) is str: if note == 'sample': note = self.getNotes(top=1) return note[0] else: raise Exception('note must be a dictionary with valid' + ' fields, or the string \'sample\'...
Python
nomic_cornstack_python_v1
function seasons df filtered_df begin comment now calc cumulative stats set filtered at string gpg = cumulative sum group by filtered string team_id at string goals - filtered at string goals / call cumcount set filtered at string win_per = cumulative sum group by filtered string team_id at string won - filtered at str...
def seasons(df, filtered_df): # now calc cumulative stats filtered['gpg'] = (filtered.groupby('team_id')['goals'].cumsum() - filtered['goals']) / filtered.groupby('team_id').cumcount() filtered['win_per'] = (filtered.groupby('team_id')['won'].cumsum() - filtered['won']) / filtered.groupby('t...
Python
zaydzuhri_stack_edu_python
comment Some more if statements set banned_users = list string andrew string carolina string david set user = string marie if user not in banned_users begin print title user + string , you can post a response if you wish. end set car = string subaru print string Is car == 'subaru'? I predict True print car == string su...
# Some more if statements banned_users = ['andrew','carolina','david'] user = 'marie' if user not in banned_users: print(user.title()+", you can post a response if you wish.") car = 'subaru' print("Is car == 'subaru'? I predict True") print(car == 'subaru') print("Is car == 'audi'? I predict false") print(car == '...
Python
zaydzuhri_stack_edu_python
function main begin set qnt = integer input set dic = list for i in range qnt begin set pok = input if pok not in dic begin append dic pok end end print format string Falta(m) {} pomekon(s). 151 - length dic end function if __name__ == string __main__ begin call main end
def main(): qnt = int(input()) dic = [] for i in range(qnt): pok = input() if pok not in dic: dic.append(pok) print("Falta(m) {} pomekon(s).".format(151 - len(dic))) if __name__ == '__main__': main()
Python
zaydzuhri_stack_edu_python
function _get_image_blob roidb scale_inds begin set num_images = length roidb set processed_ims = list set im_scales = list for i in range num_images begin set im = call imread roidb at i at string image if roidb at i at string flipped begin set im = im at tuple slice : : slice : : - 1 slice : : end set targe...
def _get_image_blob(roidb, scale_inds): num_images = len(roidb) processed_ims = [] im_scales = [] for i in range(num_images): im = cv2.imread(roidb[i]['image']) if roidb[i]['flipped']: im = im[:, ::-1, :] target_size = cfg.TRAIN.SCALES[scale_inds[i]] im, im_sc...
Python
nomic_cornstack_python_v1
function project self begin return get pulumi self string project end function
def project(self) -> pulumi.Output[str]: return pulumi.get(self, "project")
Python
nomic_cornstack_python_v1
function get_global_stiffness_matrix self begin set s = sin set c = cos set matrix_helper = list c ^ 2 c * s - c ^ 2 - c * s c * s s ^ 2 - c * s - s ^ 2 - c ^ 2 - c * s c ^ 2 c * s - c * s - s ^ 2 c * s s ^ 2 return youngs_modulus * area / call get_length * reshape array matrix_helper dtype=float64 4 4 end function
def get_global_stiffness_matrix(self) -> NDArray[np.float64]: s = self.sin() c = self.cos() matrix_helper = [ c ** 2, c * s, -(c ** 2), -c * s, c * s, s ** 2, -c * s, -(s ** 2), -(c ** 2)...
Python
nomic_cornstack_python_v1
function upload request begin comment return render(request, 'upload.html') comment print(request.FILES) if FILES == dict begin return call render request string simple_upload.html end else begin method == string POST and FILES at string myfile set myfile = FILES at string myfile set fs = call FileSystemStorage set fi...
def upload(request): # return render(request, 'upload.html') # print(request.FILES) if request.FILES == {}: return render(request, 'simple_upload.html') else: request.method == "POST" and request.FILES['myfile'] myfile = request.FILES['myfile'] fs = FileSystemStorage() ...
Python
nomic_cornstack_python_v1
from tkinter import * from com.kthread import KThread import time from threading import Timer class UpdateThread extends KThread begin function __init__ self func *args begin call __init__ self set func = func set args = args end function function run self begin comment ser = serial.Serial('COM1',9600) comment while Tr...
from tkinter import * from com.kthread import KThread import time from threading import Timer class UpdateThread(KThread): def __init__(self,func,*args): KThread.__init__(self) self.func=func self.args=args def run(self): #ser = serial.Serial('COM1',9600) ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 function magic_string begin set counter = get attribute magic_string string counter 0 + 1 return join string , list comprehension string Holberton for i in range counter end function
#!/usr/bin/python3 def magic_string(): magic_string.counter = getattr(magic_string, "counter", 0) + 1 return ", ".join(["Holberton" for i in range(magic_string.counter)])
Python
zaydzuhri_stack_edu_python
function calcula_fibonacci n begin set lista = list 0 * n if n == 1 begin return list 1 end else if n == 2 begin return list 1 1 end else begin for i in range 2 n - 1 begin set lista at 0 = 1 set lista at 1 = 1 append lista lista at i - 1 + lista at i - 2 end return lista end end function
def calcula_fibonacci(n): lista=[0]*n if n==1: return [1] elif n==2: return[1,1] else: for i in range(2,n-1): lista[0]=1 lista[1]=1 lista.append(lista[i-1]+lista[i-2]) return lista
Python
zaydzuhri_stack_edu_python
function test_abundant_sequence_20th_term self begin set term_20 = call nth_abundant 19 set excepted_output = 90 call assertEquals term_20 excepted_output end function
def test_abundant_sequence_20th_term(self): term_20 = nth_abundant(19) excepted_output = 90 self.assertEquals(term_20, excepted_output)
Python
nomic_cornstack_python_v1
function index_queryset self **kwargs begin return filter status__name=string Finished end function
def index_queryset(self, **kwargs): return self.get_model().objects.filter(status__name="Finished")
Python
nomic_cornstack_python_v1
import random set Coin = list 0 1 comment 0 for Heads set i = random choice Coin set l = 10 set n = list 0 * l for j in range l begin set count = 1 while i != 0 begin set i = random choice Coin set count = count + 1 end set i = random choice Coin set n at j = count end comment print(count) comment Prob for heads set P ...
import random Coin = [0,1] i = random.choice(Coin) # 0 for Heads l=10 n = [0]*l for j in range(l): count = 1 while (i != 0): i = random.choice(Coin) count = count + 1 i = random.choice(Coin) n[j] = count #print(count) P = 0.7 # Prob for heads x = 2 d = 1 # P[X > x+d...
Python
zaydzuhri_stack_edu_python
function getDefaultCity begin set city = first filter by query session City default=1 return city or none end function
def getDefaultCity(): city = db.session.query(City).filter_by(default=1).first() return city or None
Python
nomic_cornstack_python_v1
from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import Pipeline from sklearn.linear_model import SGDClassifier from sklearn.model_selection import GridSearchCV comment create sc...
from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import Pipeline from sklearn.linear_model import SGDClassifier from sklearn.model_selection import GridSearchCV #create scikit ...
Python
zaydzuhri_stack_edu_python
import requests from getpass import getpass from mechanicalsoup import Browser import sys set LOGIN_URL = string http://www.kaggle.com/account/login set COMPETITION_PAGE = string https://www.kaggle.com/c/%s/data set CHUNK_SIZE = 512 * 1024 set BAR_LENGTH = 80 class PyKaggler begin function __init__ self begin set userS...
import requests from getpass import getpass from mechanicalsoup import Browser import sys LOGIN_URL = "http://www.kaggle.com/account/login" COMPETITION_PAGE = "https://www.kaggle.com/c/%s/data" CHUNK_SIZE = 512 * 1024 BAR_LENGTH = 80 class PyKaggler(): def __init__(self): self.userSession = None def...
Python
zaydzuhri_stack_edu_python
function test_compress_2 self begin set text = string abcdefdeabc set actual = compress text set expected = bytearray list 3 + bytearray b'abcdef' + bytearray list 0 32 + bytearray list 0 113 assert equal actual expected end function
def test_compress_2(self): text = 'abcdefdeabc' actual = LZ77.compress(text) expected = bytearray([3]) + bytearray(b'abcdef')\ + bytearray([0, 32]) + bytearray([0, 113]) self.assertEqual(actual, expected)
Python
nomic_cornstack_python_v1
function gridTraveler_without_memoization m n begin comment Base cases if m == 1 and n == 1 begin return 1 end if m == 0 or n == 0 begin return 0 end comment down - reduce rows, right - reduce columns return call gridTraveler_without_memoization m - 1 n + call gridTraveler_without_memoization m n - 1 end function
def gridTraveler_without_memoization(m, n): # Base cases if (m == 1 and n == 1): return 1 if (m == 0 or n == 0): return 0 # down - reduce rows, right - reduce columns return gridTraveler_without_memoization(m - 1, n) + gridTraveler_without_memoization(m, n - 1)
Python
nomic_cornstack_python_v1
function createSecondaryShape self shape_id type property begin comment if requirements for target node are listed, then need a shape for it set shape_info = dict string targetType string sh:ObjectsOf ; string target property ; string properties list ; string mandatory true call add_shapeInfo shape_id shape_info comme...
def createSecondaryShape(self, shape_id, type, property): # if requirements for target node are listed, then need a shape for it shape_info = { "targetType": "sh:ObjectsOf", "target": property, "properties": [], "mandatory": True, } self.ap...
Python
nomic_cornstack_python_v1
import sys function convert_gff line annotation begin set converted = list comment get seqname append converted line at 1 comment get source append converted string LipoP comment get feature append converted string ab-initio comment get start and end position set start_and_end = split split line at 1 string : at 1 str...
import sys def convert_gff(line, annotation): converted = [] #get seqname converted.append(line[1]) # get source converted.append('LipoP') #get feature converted.append('ab-initio') # get start and end position start_and_end = line[1].split(':')[1].split('-') start = start_a...
Python
zaydzuhri_stack_edu_python
function add_edge graph source target begin if source not in graph begin set graph at source = list end if target not in graph begin set graph at target = list end append graph at source target end function
def add_edge(graph, source, target): if source not in graph: graph[source] = [] if target not in graph: graph[target] = [] graph[source].append(target)
Python
nomic_cornstack_python_v1
import itertools import os set f = open string independent.txt string r set n = integer split read line f at 0 set rest = read f set lines = call splitlines set edges = list comprehension tuple map int split line for line in lines set clauses = list set colors = range 1 4 set color_names = none if length colors == 3 b...
import itertools import os f=open("independent.txt","r") n=int((f.readline()).split()[0]) rest=f.read() lines=rest.splitlines() edges=[tuple(map(int,line.split())) for line in lines] clauses=[] colors=range(1,4) color_names=None if len(colors)==3: color_names=["Red","Green","Blue"] def varnum(i,j): assert(i in ...
Python
zaydzuhri_stack_edu_python
function set_root_value root value begin set root at 0 = value end function
def set_root_value(root, value): root[0] = value
Python
nomic_cornstack_python_v1
if edad >= 18 begin print string Es mayor de edad end else if edad == 17 begin print string El próximo año será mayor de edad end else begin print string Es menor de edad end
if edad >= 18: print("Es mayor de edad") elif edad == 17: print("El próximo año será mayor de edad") else: print("Es menor de edad")
Python
zaydzuhri_stack_edu_python
function InitializePopulation nDISP nNTypes nPopulationSize nTray begin set population = list for i in range nPopulationSize begin set nSubTray = nTray set genome = list for k in range nNTypes begin set nRandVector = call GenerateRandVector nTray nDISP for j in range nDISP begin set genome at j at k = nRandVector end...
def InitializePopulation(nDISP, nNTypes, nPopulationSize, nTray): population = [] for i in range(nPopulationSize): nSubTray = nTray genome = [] for k in range(nNTypes): nRandVector = GenerateRandVector(nTray, nDISP) for j in range(nDISP): genome[j][k] = nRandVector population.append(genome) re...
Python
nomic_cornstack_python_v1
function testNonDefinedChannelsDimension self module_info use_bias begin set tuple module num_input_dims module_kwargs = module_info set conv_mod = call module use_bias=use_bias keyword module_kwargs set inputs = call placeholder float32 tuple 10 * num_input_dims + 1 + tuple none set err = string Number of input channe...
def testNonDefinedChannelsDimension(self, module_info, use_bias): module, num_input_dims, module_kwargs = module_info conv_mod = module(use_bias=use_bias, **module_kwargs) inputs = tf.placeholder(tf.float32, (10,) * (num_input_dims + 1) + (None,)) err = "Number of input channels" with self.assertRa...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sat Dec 29 22:55:41 2018 @author: fourn import project2_language_model as lm import project2_utils as utils import numpy as np from keras.models import load_model import pickle from sklearn import cross_validation , svm import io import os function data_load path begin se...
# -*- coding: utf-8 -*- """ Created on Sat Dec 29 22:55:41 2018 @author: fourn """ import project2_language_model as lm import project2_utils as utils import numpy as np from keras.models import load_model import pickle from sklearn import cross_validation, svm import io import os def data_load(path): file =...
Python
zaydzuhri_stack_edu_python
function é_hipotenusa num begin set i = 0 set j = 0 set hipotenusa = false while i < num and not hipotenusa begin while j < num begin if power num 2 == power i 2 + power j 2 begin set hipotenusa = true end set j = j + 1 end set i = i + 1 set j = 0 end return hipotenusa end function function soma_hipotenusas num begin s...
def é_hipotenusa(num:int): i = 0 j= 0 hipotenusa = False while (i < num and not hipotenusa): while j < num: if(pow(num,2)==pow(i,2)+pow(j,2)): hipotenusa = True j+=1 i+=1 j = 0 return hipotenusa def soma_hipotenusas(num:int): i = 1...
Python
zaydzuhri_stack_edu_python
function __init__ self parent filename begin set parent = parent set filename = filename set path_waypoints = list set segment_lookup = dict string off_road curb ; string path path ; string lane_marking_white lane_marking_white ; string lane_marking_yellow_dashed lane_marking_yellow_dashed set lines = loads read open ...
def __init__( self, parent: 'KRoadProcess', filename: str, ): self.parent = parent self.filename = filename self.path_waypoints = [] segment_lookup = { 'off_road': EntityType.curb, 'path': EntityType.path, 'lane...
Python
nomic_cornstack_python_v1
function translate bbox x_offset=0 y_offset=0 begin set bbox = copy bbox set bbox at tuple slice : : slice : 2 : = bbox at tuple slice : : slice : 2 : + tuple x_offset y_offset set bbox at tuple slice : : slice 2 : 4 : = bbox at tuple slice : : slice 2 : 4 : + tuple x_offset y_offset return bbox end f...
def translate(bbox, x_offset=0, y_offset=0): bbox = bbox.copy() bbox[:, :2] += (x_offset, y_offset) bbox[:, 2:4] += (x_offset, y_offset) return bbox
Python
nomic_cornstack_python_v1
function from_json self json_content begin set data = loads json_content set entity = call Client set id_client = data at string id_client set nom = data at string nom set prenom = data at string prenom set tel = data at string tel set addresse = data at string addresse set pays = data at string pays set zipcode = data...
def from_json(self, json_content: str): data = json.loads(json_content) entity = Client() entity.id_client = data['id_client'] entity.nom = data['nom'] entity.prenom = data['prenom'] entity.tel = data['tel'] entity.addresse = data['addresse'] entity.pays =...
Python
nomic_cornstack_python_v1
function __query self query params=string headers=dictionary content_type=string application/json method=string POST begin if is instance params str begin set data = encode params string utf8 end else begin set data = params end if __connection is none begin set __connection = call HTTPConnection __host __port end set...
def __query(self, query, params='', headers=dict(), content_type='application/json', method='POST'): if isinstance(params, str): data = params.encode('utf8') else: data = params if self.__connection is None: self.__connection = http.client.HTTPConnection(self._...
Python
nomic_cornstack_python_v1
function print_table setx begin for sets in setx begin for i in sets begin for x in i begin print x end=string end end print end end function
def print_table(setx): for sets in setx: for i in sets: for x in i: print(x,end=' ') print()
Python
nomic_cornstack_python_v1
function count_upper_case_letters string begin set count = 0 for char in string begin if ordinal char >= 65 and ordinal char <= 90 begin set count = count + 1 end end return count end function function count_upper_case_letters string begin if length string == 0 begin return 0 end set count = 0 for char in string begin ...
def count_upper_case_letters(string): count = 0 for char in string: if ord(char) >= 65 and ord(char) <= 90: count += 1 return count def count_upper_case_letters(string): if len(string) == 0: return 0 count = 0 for char in string: if ord(char) >= 65 and ord(...
Python
jtatman_500k
async function get_jedy chat_id state begin set data = await call get_data if string bot not in data begin set new_bot = call AquaBalanceBot chat_id await call update_data bot=new_bot return new_bot end return data at string bot end function
async def get_jedy(chat_id, state: FSMContext): data = await state.get_data() if 'bot' not in data: new_bot = AquaBalanceBot(chat_id) await state.update_data(bot=new_bot) return new_bot return data['bot']
Python
nomic_cornstack_python_v1
function get_valid_points self begin set valid_data_points = list _data_points at 0 set num_rows = length _data_points comment valid_head contains the last valid point comment current_head contains the current index to check set valid_head = 0 set current_head = 1 while current_head < num_rows begin set start_data_poin...
def get_valid_points(self) -> List[DataPoint]: valid_data_points = [self._data_points[0]] num_rows = len(self._data_points) # valid_head contains the last valid point # current_head contains the current index to check valid_head = 0 current_head = 1 while (curre...
Python
nomic_cornstack_python_v1
function getCurrency self currency_id begin set response = get requests string https://www.coinexchange.io/api/v1/getcurrency?currency_id= + currency_id return json response end function
def getCurrency(self, currency_id): response = requests.get('https://www.coinexchange.io/api/v1/getcurrency?currency_id=' + currency_id) return (response.json())
Python
nomic_cornstack_python_v1
function test_returns_validating_observer self begin call call SpecificationObserverWrapper observer dict string message tuple string launch-servers ; string num_servers 2 assert equal e list dict string message tuple string Launching {num_servers} servers ; string num_servers 2 ; string otter_msg_type string launch-se...
def test_returns_validating_observer(self): SpecificationObserverWrapper(self.observer)( {'message': ("launch-servers",), "num_servers": 2}) self.assertEqual( self.e, [{'message': ('Launching {num_servers} servers', ), 'num_servers': 2, 'ot...
Python
nomic_cornstack_python_v1
comment The code below is based on Fig.15.19 in John Guttag's book.### import random from varStdDevCV import variance , stdDev , CV import matplotlib.pyplot as plt function flip numFlips begin string Assumes numFlips to be a positive int. set heads = 0 for i in range numFlips begin if random choice tuple string H strin...
###The code below is based on Fig.15.19 in John Guttag's book.### import random from varStdDevCV import variance,stdDev,CV import matplotlib.pyplot as plt def flip(numFlips): """Assumes numFlips to be a positive int.""" heads=0 for i in range(numFlips): if random.choice(('H','T'))=='H': ...
Python
zaydzuhri_stack_edu_python
comment Day 1 Exercise function do_math begin string Create code within this function definition to do calculations below: What is 2 + 2? What is 10 / 3? What if I want integer division of 10 / 3? How do I compute 2 powers 10? (should be 1024) Write code to show your answers of those questions. There is no return value...
# Day 1 Exercise def do_math(): """ Create code within this function definition to do calculations below: What is 2 + 2? What is 10 / 3? What if I want integer division of 10 / 3? How do I compute 2 powers 10? (should be 1024) Write code to show your answers of those questions. ...
Python
zaydzuhri_stack_edu_python
function dropTables t=none begin set tablelist = if expression t == none then keys else list t set conn = call getConnection try begin set cur = call cursor for table in keys tables begin set query = string DROP TABLE IF EXISTS %s; % table execute cur query commit conn end end except Exception as ex begin print string ...
def dropTables(t=None): tablelist = tables.keys if t == None else [t] conn = getConnection() try: cur = conn.cursor() for table in tables.keys(): query = "DROP TABLE IF EXISTS %s;" % table cur.execute(query) conn.commit() except Exception as ex: print("Failed to drop tables:" ) ...
Python
nomic_cornstack_python_v1
function opts_shared cmd_func begin return reduce lambda _f opt_func -> call opt_func _f list opt_hostname opt_use_regex opt_log opt_log_level cmd_func end function
def opts_shared(cmd_func): return reduce( lambda _f, opt_func: opt_func(_f), [ opt_hostname, opt_use_regex, opt_log, opt_log_level], cmd_func)
Python
nomic_cornstack_python_v1
function get_hidden_values self input begin set result = call activation dot input W + b return result end function
def get_hidden_values(self, input): result=self.activation(T.dot(input, self.W) + self.b) return result
Python
nomic_cornstack_python_v1
import fileReader import montecarlo import betting import scraper import time comment FILENAME = 'nba-games.txt' set FILENAME = string nfl-games.txt function main begin set lines = list append lines call makeLines FILENAME string Los Angeles Rams string Green Bay Packers append lines call makeLines FILENAME string Bal...
import fileReader import montecarlo import betting import scraper import time # FILENAME = 'nba-games.txt' FILENAME = 'nfl-games.txt' def main(): lines = [] lines.append(betting.makeLines(FILENAME, 'Los Angeles Rams', 'Green Bay Packers')) lines.append(betting.makeLines(FILENAME, 'Baltimore Ravens', 'Buff...
Python
zaydzuhri_stack_edu_python
function show self trans id deleted=string False **kwd begin set deleted = call string_as_bool deleted try begin comment user is requesting data about themselves if id == string current begin comment ...and is anonymous - return usage and quota (if any) if not user begin set item = call anon_user_api_value trans return...
def show( self, trans, id, deleted='False', **kwd ): deleted = util.string_as_bool( deleted ) try: # user is requesting data about themselves if id == "current": # ...and is anonymous - return usage and quota (if any) if not trans.user: ...
Python
nomic_cornstack_python_v1
from time import time from aima.csp import CSP comment Variable list set timeandplace = list set classrooms = list string TP51 string SP34 string K3 set timeslots = list 9 10 11 12 1 2 3 4 set classes = list string MT101 string MT102 string MT103 string MT104 string MT105 string MT106 string MT107 string MT201 string ...
from time import time from aima.csp import CSP #Variable list timeandplace = [] classrooms = ["TP51", "SP34", "K3"] timeslots = [9,10,11,12,1,2,3,4] classes = ["MT101","MT102","MT103","MT104","MT105","MT106","MT107","MT201","MT202","MT203","MT204","MT205","MT206","MT301","MT302","MT303","MT304","MT401","MT402","MT403...
Python
zaydzuhri_stack_edu_python
comment from scipy.sparse import hstack, vstack, csr_matrix, save_npz, load_npz, coo_matrix comment A = coo_matrix([[1, 2], [3, 4]]) comment B = [5, 6] comment print(A) comment print() comment A = vstack((A, B)) comment print(A) import numpy as np from scipy.sparse import csr_matrix import csv import pandas set m = arr...
# from scipy.sparse import hstack, vstack, csr_matrix, save_npz, load_npz, coo_matrix # A = coo_matrix([[1, 2], [3, 4]]) # B = [5, 6] # print(A) # print() # A = vstack((A, B)) # print(A) import numpy as np from scipy.sparse import csr_matrix import csv import pandas m = np.array([[1,2,3],[4,5,6],[7,8,9]]) m = csr_matr...
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup from requests import get import json from DataFormatting.FormatText import FormatSentence from DataFormatting import VenueClass comment Array to store all Venues of type VenueClass set allVenues = list function extractVenue tag venue begin print string --Huone-- comment extract link into ...
from bs4 import BeautifulSoup from requests import get import json from DataFormatting.FormatText import FormatSentence from DataFormatting import VenueClass allVenues = [] # Array to store all Venues of type VenueClass def extractVenue(tag, venue): print("--Huone--") # extract link into the venue ven...
Python
zaydzuhri_stack_edu_python
function version self begin return get pulumi self string version end function
def version(self) -> str: return pulumi.get(self, "version")
Python
nomic_cornstack_python_v1
for i in range n - 1 begin set ans = ans + a at n - 1 - i + 1 // 2 end print ans
for i in range(n-1): ans+=a[n-1-(i+1)//2] print(ans)
Python
zaydzuhri_stack_edu_python
function word_iter self set_name=none character=false begin if set_name is none begin set data_set = train_set + dev_set end else if set_name == string train begin set data_set = train_set end else if set_name == string dev begin set data_set = dev_set end else begin raise call NotImplementedError format string No data...
def word_iter(self, set_name=None, character=False): if set_name is None: data_set = self.train_set + self.dev_set elif set_name == "train": data_set = self.train_set elif set_name == "dev": data_set = self.dev_set else: raise NotImplemente...
Python
nomic_cornstack_python_v1
function pytest_generate_tests metafunc begin try begin set func_arg_list = parameterize_dict at __name__ end except tuple AttributeError KeyError begin return end set arg_names = sorted func_arg_list at 0 call parametrize arg_names list comprehension list comprehension func_args at name for name in arg_names for func_...
def pytest_generate_tests(metafunc): try: func_arg_list = metafunc.cls.parameterize_dict[metafunc.function.__name__] except (AttributeError, KeyError): return arg_names = sorted(func_arg_list[0]) metafunc.parametrize( arg_names, [[func_args[name] for name in arg_names] fo...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python string Lambda Function that simulates a single Neuron for both forward and backward propogation. If the state is `forward` then the function simulates forward propogation for `X` to the `Cost`. If the state is backward, then the function calculates the gradient of the derivative of the activati...
#!/usr/bin/python """ Lambda Function that simulates a single Neuron for both forward and backward propogation. If the state is `forward` then the function simulates forward propogation for `X` to the `Cost`. If the state is backward, then the function calculates the gradient of the derivative of the activation functi...
Python
zaydzuhri_stack_edu_python
function test_image_url self begin set img_url = string http://www.ndftz.com/nickelanddime.png set read = parse ReadUrl img_url assert true status == 200 string The status is 200: + string status assert true content is none string Content should be none: end function
def test_image_url(self): img_url = 'http://www.ndftz.com/nickelanddime.png' read = ReadUrl.parse(img_url) self.assertTrue( read.status == 200, "The status is 200: " + str(read.status)) self.assertTrue( read.content is None, "Content should be none: ")
Python
nomic_cornstack_python_v1
import math from typing import List function read_file file_path begin with open file_path string r encoding=string UTF-8 as f begin return read f end end function function parse dim_list begin return list comprehension list comprehension integer dim for dim in split line string x for line in call splitlines end functi...
import math from typing import List def read_file(file_path): with open(file_path, 'r', encoding="UTF-8") as f: return f.read() def parse(dim_list): return [[int(dim) for dim in line.split('x')] for line in dim_list.splitlines()] def part_one(dim_list: List) -> int: return sum(calc_area(dim) f...
Python
zaydzuhri_stack_edu_python
import pandas as pd set data = read csv string fishdata/fish_clean.csv set stocks = group by data string stockid function getStock stockid begin print string stockid in getStock stockid set group = call get_group stockid comment print("group.columns", group.columns) set df = concat list year group at string U/Umsytouse...
import pandas as pd data = pd.read_csv('fishdata/fish_clean.csv') stocks = data.groupby('stockid') def getStock(stockid): print("stockid in getStock", stockid) group = stocks.get_group(stockid) # print("group.columns", group.columns) df = pd.concat([group.year, group['U/Umsytouse'], group['B/Bmsytouse']],...
Python
zaydzuhri_stack_edu_python
function check_cal_version list_of_flts cal_versions begin set good_flts = list set bad_flts = list for flt in list_of_flts begin set hdulist = open flt set hdr = header close end end function
def check_cal_version(list_of_flts,cal_versions): good_flts = [] bad_flts=[] for flt in list_of_flts: hdulist=fits.open(flt) hdr=hdulist[0].header hdulist.close
Python
nomic_cornstack_python_v1
import collections class Solution extends object begin comment Exceed the time limit function wordBreak3 self s wordDict begin string :type s: str :type wordDict: List[str] :rtype: bool if length s == 0 begin return true end set returnVal = false for i in range 1 length s + 1 begin set word = s at slice : i : if s at...
import collections class Solution(object): # Exceed the time limit def wordBreak3(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: bool """ if len(s) == 0: return True returnVal = False for i in range(1, len(s) + ...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf from tensorflow.python.ops import array_ops , math_ops function _centered arr newshape begin comment Return the center newshape portion of the array. set currshape = call shape arr at slice - 3 : : set startind = currshape - newshape // 2 set endind = startind + newshape return arr at tuple El...
import tensorflow as tf from tensorflow.python.ops import array_ops, math_ops def _centered(arr, newshape): # Return the center newshape portion of the array. currshape = tf.shape(arr)[-3:] startind = (currshape - newshape) // 2 endind = startind + newshape return arr[..., startind[0]:endind[0], st...
Python
zaydzuhri_stack_edu_python
comment pragma: no cover function get_token self begin return tuple get session string access_token string end function
def get_token(self): # pragma: no cover return (session.get("access_token"), "")
Python
nomic_cornstack_python_v1
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt function visualize_correlation data_df start_date end_date begin comment Filter the dataframe based on the date range set filtered_df = data_df at data_df at string date >= start_date ? data_df at string date <= end_date comment Create a scatter ...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt def visualize_correlation(data_df, start_date, end_date): # Filter the dataframe based on the date range filtered_df = data_df[(data_df['date'] >= start_date) & (data_df['date'] <= end_date)] # Create a scatter plot with color ...
Python
jtatman_500k
function readfile self writeToFile begin for file in filenames begin set all_page = list if string AI in file begin set prefix = AI_pre set target = string AI end else begin set prefix = Not_AI_pre set target = string Not end set category = split split file string , at 0 string _ at 0 print string = * 20 + format stri...
def readfile(self,writeToFile): for file in self.filenames: all_page = [] if "AI" in file: prefix = self.AI_pre target = "AI" else: prefix = self.Not_AI_pre target = "Not" category = file.split(',')[0...
Python
nomic_cornstack_python_v1
function get_borders self begin set borders = list if flipped begin for i in range 4 begin append borders mirrored_borders at - rotation + i % 4 end end else begin for i in range 4 begin append borders borders at - rotation + i % 4 end end return borders end function
def get_borders(self): borders = [] if self.flipped: for i in range(4): borders.append(self.mirrored_borders[(-self.rotation + i) % 4]) else: for i in range(4): borders.append(self.borders[(-self.rotation + i) % 4]) return borders
Python
nomic_cornstack_python_v1
string Convex Hull Points from Coderbyte January 2021 Jakub Kazimierski import sys function orientation point_I point_II point_III begin string To find orientation of ordered triplet (point_I, point_II, point_III). The function returns following values 0 --> point_I, point_II and point_III are colinear 1 --> Clockwise ...
''' Convex Hull Points from Coderbyte January 2021 Jakub Kazimierski ''' import sys def orientation(point_I, point_II, point_III): ''' To find orientation of ordered triplet (point_I, point_II, point_III). The function returns following values 0 --> point_I, point_II and point_III are...
Python
zaydzuhri_stack_edu_python
function rank test begin set dizi = test set dizi2 = list for i in range 0 length dizi begin for j in range 0 length dizi begin if dizi at i + 1 == dizi at j begin print string * dizi at i string sayısı index dizi dizi at i string . indiste ve kendisinden büyük ardışığı olan dizi at j string sayısı ise index dizi dizi...
def rank(test): dizi = test dizi2=[] for i in range(0,len(dizi)): for j in range(0,len(dizi)): if(dizi[i]+1==dizi[j]): print("* ",dizi[i], " sayısı ",dizi.index(dizi[i]),". indiste ve kendisinden büyük ardışığı olan ", dizi[j]," sayısı ise ",dizi.index(dizi[j]),". indi...
Python
zaydzuhri_stack_edu_python
function _storage_init self begin if not initialized begin call init _py3_wrapper end end function
def _storage_init(self): if not self._storage.initialized: self._storage.init(self._module._py3_wrapper)
Python
nomic_cornstack_python_v1
import pandas as pd function count_unique_subjects teacher begin set df = reset index call nunique rename columns=dict string subject_id string cnt inplace=true return df end function
import pandas as pd def count_unique_subjects(teacher: pd.DataFrame) -> pd.DataFrame: df = teacher.groupby("teacher_id")["subject_id"].nunique().reset_index() df.rename(columns={"subject_id": "cnt"}, inplace=True) return df
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment Google Code Jam - 2017 comment Round1A - Problem A - Alphabet Cake comment Joaquin Derrac - carrdelling@gmail.com import sys function fill_columnwise r c grid begin set remaining = true set advancing = true while remaining and advancing begin set remaining = false set advancing = fa...
#!/usr/bin/env python ################################################################################ # # Google Code Jam - 2017 # # Round1A - Problem A - Alphabet Cake # # Joaquin Derrac - carrdelling@gmail.com # ################################################################################ import sys def fill_...
Python
zaydzuhri_stack_edu_python
function _compute_msms system lmax average=false wl=false begin set voro = call compute system=system set op = call Steinhardt l=list range lmax + 1 average=average weighted=true wl=wl wl_normalize=wl call compute system neighbors=nlist return particle_order end function
def _compute_msms(system, lmax, average=False, wl=False): voro = freud.locality.Voronoi().compute(system=system) op = freud.order.Steinhardt( l=list(range(lmax + 1)), average=average, weighted=True, wl=wl, wl_normalize=wl ) op.compute(system, neighbors=voro.nlist) return op.particle_order
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import numpy as np import sys from numpy import linalg as LA comment To convert string to dictionnary import json , ast comment =================================================== comment Nouveaux programmes: import LagrangeInterpolation as LI import LagrangePolynomial import string commen...
# -*- coding: utf-8 -*- import numpy as np import sys from numpy import linalg as LA import json, ast ### To convert string to dictionnary ###=================================================== ### Nouveaux programmes: import LagrangeInterpolation as LI import LagrangePolynomial import string ##=====================Exa...
Python
zaydzuhri_stack_edu_python
import random set clearanceScale = dict 0 string No Access ; 1 string Level 1 Clearance ; 2 string Level 2 Clearance ; 3 string Level 3 Clearance ; 4 string Level 4 Clearance ; 5 string Top Level Clearance class Silph begin set clearance = 0 set login1 = false end class
import random clearanceScale = {0: 'No Access', 1: 'Level 1 Clearance', 2: 'Level 2 Clearance',3: 'Level 3 Clearance', 4: 'Level 4 Clearance', 5: 'Top Level Clearance'} class Silph: clearance = 0 login1 = False
Python
zaydzuhri_stack_edu_python
function documento begin pass end function
def documento(): pass
Python
nomic_cornstack_python_v1
function compute matrix missing_val begin set vals = list comprehension matrix at r at c for r in keys matrix for c in matrix at r if matrix at r at c != missing_val return call Stats min vals max vals sum vals / length vals end function
def compute(matrix, missing_val): vals = [matrix[r][c] for r in matrix.keys() for c in matrix[r] if matrix[r][c] != missing_val] return Stats(min(vals), max(vals), sum(vals)/len(vals))
Python
nomic_cornstack_python_v1
function __rejectCookie self cookie cookieDomain begin if not __loaded begin call __load end if __acceptCookies == AcceptNever begin set res = call __isOnDomainList __exceptionsAllow cookieDomain if not res begin return true end end if __acceptCookies == AcceptAlways begin set res = call __isOnDomainList __exceptionsBl...
def __rejectCookie(self, cookie, cookieDomain): if not self.__loaded: self.__load() if self.__acceptCookies == self.AcceptNever: res = self.__isOnDomainList(self.__exceptionsAllow, cookieDomain) if not res: return True if self...
Python
nomic_cornstack_python_v1