code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function _pyscf_molecule_object basis labels coords begin set mol = call Mole atom=zip labels coords unit=string bohr basis=basis call build return mol end function
def _pyscf_molecule_object(basis, labels, coords): mol = pyscf.gto.Mole(atom=zip(labels, coords), unit="bohr", basis=basis) mol.build() return mol
Python
nomic_cornstack_python_v1
from import db from marshmallow import Schema class Base extends Base begin set __abstract__ = true set __schema__ = Schema function save self begin add session self end function function delete self begin delete self end function function update self data begin for tuple key value in items data begin set attribute se...
from . import db from marshmallow import Schema class Base(db.Base): __abstract__ = True __schema__ = Schema def save(self): db.session.add(self) def delete(self): db.session.delete(self) def update(self, data): for key, value in data.items(): setattr(self, k...
Python
zaydzuhri_stack_edu_python
comment apply.py class Apply begin function next self driver sleep begin try begin comment jump next step set next_btn = call find_element_by_css_selector string [aria-label="Ir al siguiente paso"] call click print string clicked next step sleep call ran try begin comment jump next step set next_btn = call find_element...
#apply.py class Apply: def next(self,driver,sleep): try: #jump next step next_btn = self.driver.find_element_by_css_selector('[aria-label="Ir al siguiente paso"]') next_btn.click() print('clicked next step') sleep(self.ran()) ...
Python
zaydzuhri_stack_edu_python
function get_telnet_probe target begin set tn = call Telnet set messages = list set response = string try begin open target at string host port=target at string port timeout=20 append messages string Telnet Connection Established set port_status = string open try begin write tn encode string 123 string ascii + b'\n' s...
def get_telnet_probe(target): tn = telnetlib.Telnet() messages = list() response = "" try: tn.open(target['host'], port=target['port'], timeout=20) messages.append("Telnet Connection Established") port_status = "open" try: tn.write("123".encode('ascii') + b"\n...
Python
nomic_cornstack_python_v1
function func string begin set myDict = dict set alphabet = string abcdefghijklmnopqrstuvwxyz for k in alphabet begin set myDict at k = 0 end for k in string begin if k in keys myDict begin set myDict at k = 1 end end return myDict end function print call func string python is beautiful
def func(string): myDict={} alphabet='abcdefghijklmnopqrstuvwxyz' for k in alphabet: myDict[k]=0 for k in string: if k in myDict.keys(): myDict[k] = 1 return myDict print(func('python is beautiful'))
Python
zaydzuhri_stack_edu_python
comment dz-botnet client.py comment Basic client program. import os import socket import time set SERVER_ADDR = string set SERVER_PORT = 80 function main begin comment Every minute, poll the server for new commands. while true begin comment Initialize the socket. set c = call socket AF_INET SOCK_STREAM call connect tu...
# dz-botnet client.py # Basic client program. import os import socket import time SERVER_ADDR = '' SERVER_PORT = 80 def main(): # Every minute, poll the server for new commands. while True: # Initialize the socket. c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) c.connect((SE...
Python
zaydzuhri_stack_edu_python
function reorderedAttribute self index begin pass end function
def reorderedAttribute(self, index): pass
Python
nomic_cornstack_python_v1
function calcDeriv v d begin for i in range 0 length v begin append d i * v at i end end function comment --------------------------------------------------- function imprime d begin for i in range 1 length d begin print string { d at i } end end function comment --------------------------------------------------- func...
def calcDeriv(v, d): for i in range(0, len(v)): d.append(i*v[i]) #--------------------------------------------------- def imprime(d): for i in range(1, len(d)): print(f"{d[i]:.4f}") #--------------------------------------------------- def main(): res = [] vet = list(map(float, input(...
Python
zaydzuhri_stack_edu_python
function next self begin if __next < 7 begin set day = first + __next set __next = __next + 1 end else begin set __next = 0 raise StopIteration end return day end function
def next(self): if self.__next < 7: day = self.first + self.__next self.__next += 1 else: self.__next = 0 raise StopIteration return day
Python
nomic_cornstack_python_v1
function num_tokens self index begin return max generator expression s at index for s in sizes end function
def num_tokens(self, index): return max(s[index] for s in self.sizes)
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from scipy.stats import laplace , norm from scipy.stats import gaussian_kde from scipy.spatial.distance import squareform , pdist , cdist function sq_distances X Y=none begin assert ndim == 2 if Y is none begin set sq_dists = call squareform pd...
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from scipy.stats import laplace, norm from scipy.stats import gaussian_kde from scipy.spatial.distance import squareform, pdist, cdist def sq_distances(X,Y=None): assert(X.ndim==2) if Y is None: sq_dists = squareform(pdist(X, m...
Python
zaydzuhri_stack_edu_python
function __eq__ self other begin if not is instance other EarningsHistoryItemPool begin return false end return __dict__ == __dict__ end function
def __eq__(self, other): if not isinstance(other, EarningsHistoryItemPool): return False return self.__dict__ == other.__dict__
Python
nomic_cornstack_python_v1
function magic_iter *args **kwargs begin if stage == 0 begin if string startafter in kwargs begin assert equal kwargs at string startafter none end set stage = 1 return iterate call make_items list 1 2 3 end else if stage == 1 begin assert equal kwargs at string startafter 3 set stage = 0 set metadata = dict string sta...
def magic_iter(*args, **kwargs): if magic_iter.stage == 0: if 'startafter' in kwargs: self.assertEqual(kwargs['startafter'], None) magic_iter.stage = 1 return iter(make_items([1, 2, 3])) elif magic_iter.stage == 1: ...
Python
nomic_cornstack_python_v1
function queryset_to_csv self begin set csv_data = list set custom_fields = list comment Start with the column headers set headers = copy csv_headers comment Add custom field headers, if any if has attribute model string get_custom_fields begin for custom_field in call get_custom_fields begin append headers name appe...
def queryset_to_csv(self): csv_data = [] custom_fields = [] # Start with the column headers headers = self.queryset.model.csv_headers.copy() # Add custom field headers, if any if hasattr(self.queryset.model, 'get_custom_fields'): for custom_field in self.que...
Python
nomic_cornstack_python_v1
function _process_raw_wicker_sample self raw_wicker_sample begin comment Lots of annotations require an ontology table, so we process those first set ontology_table = call _create_ontology_table raw_wicker_sample if ontology_table is none begin set _ontology_table = ontology_table end else begin comment Make sure the o...
def _process_raw_wicker_sample(self, raw_wicker_sample: Dict[str, Any]) -> Dict[str, Dict[str, Any]]: # Lots of annotations require an ontology table, so we process those first ontology_table = self._create_ontology_table(raw_wicker_sample) if self.ontology_table is None: self._onto...
Python
nomic_cornstack_python_v1
function modify_cell_zoom self cell_dimension begin call change_cell_dimension cell_dimension call _refresh_current_tab end function
def modify_cell_zoom(self, cell_dimension: CellDimension) -> None: self.config.change_cell_dimension(cell_dimension) self._refresh_current_tab()
Python
nomic_cornstack_python_v1
function init_csrt_tracker self begin return call TrackerCSRT_create end function
def init_csrt_tracker(self) -> _Tracker: return cv2.TrackerCSRT_create()
Python
nomic_cornstack_python_v1
from abc import ABC , abstractmethod class Shape extends ABC begin decorator abstractmethod function accept self visitor begin pass end function end class class Circle extends Shape begin function __init__ self x y radius begin set x = x set y = y set radius = radius end function function accept self visitor begin retu...
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def accept(self, visitor): pass class Circle(Shape): def __init__(self, x, y, radius): self.x = x self.y = y self.radius = radius def accept(self, visitor): return visitor.visit_circ...
Python
zaydzuhri_stack_edu_python
from common_grader import CommonGrader import io import numpy as np import h5py as h5 set files = dict function calc_score truth ans begin set n = length truth if length ans != n begin raise call ValueError format string Answer table must have {} rows. n end if not all truth at string SphereId == ans at string SphereI...
from common_grader import CommonGrader import io import numpy as np import h5py as h5 files = {} def calc_score(truth, ans): n = len(truth) if len(ans) != n: raise ValueError("Answer table must have {} rows.".format(n)) if not np.all(truth["SphereId"] == ans["SphereId"]): raise ValueErro...
Python
zaydzuhri_stack_edu_python
for i in range a a + k begin if i < a or i > b begin continue end print i end for i in range b - k + 1 b + 1 begin if a <= i and i <= a + k - 1 begin continue end if i < a or i > b begin continue end print i end
for i in range(a, a + k): if(i < a or i > b): continue print(i) for i in range(b - k + 1, b + 1): if (a <= i and i <= a + k - 1): continue if(i < a or i > b): continue print(i)
Python
zaydzuhri_stack_edu_python
function create_mask test_data test_length begin set test_mask = zeros tuple shape at 0 shape at 1 dtype=string float for i in range length test_length begin set test_mask at tuple i slice : test_length at i : = 1.0 end return test_mask end function
def create_mask( test_data, test_length): test_mask = np.zeros((test_data.shape[0], test_data.shape[1]), dtype='float') for i in range(len(test_length)): test_mask[i, :test_length[i]] = 1.0 return test_mask
Python
nomic_cornstack_python_v1
function buildGrid s p begin comment Add null character to beginning of each of the strings. set s = string # + s set p = string # + p comment Length of both strings. set Ls = length s set Lp = length p comment Initialize grid with all zeros. set G = list for i in range Lp begin set G = G + list list 0 * Ls end commen...
def buildGrid(s: str, p: str): # Add null character to beginning of each of the strings. s = '#' + s p = '#' + p # Length of both strings. Ls = len(s) Lp = len(p) # Initialize grid with all zeros. G = [] for i in range(Lp): G += [[0] * Ls] # Fill in first row (vs null str...
Python
nomic_cornstack_python_v1
import numpy as np from global_utils import * string A class version of the memory network. Basically everything in network.py in a class. This class deviates from the memory network presented in the paper to only satisfy the needs of our project Author: Jason Yim, Jay Miller string For testing individual routes class ...
import numpy as np from global_utils import * """ A class version of the memory network. Basically everything in network.py in a class. This class deviates from the memory network presented in the paper to only satisfy the needs of our project Author: Jason Yim, Jay Miller """ """ For testing individual routes """ ...
Python
zaydzuhri_stack_edu_python
function to_nullable_array value begin string Converts value into array object. Single values are converted into arrays with a single element. :param value: the value to convert. :return: array object or None when value is None. comment Shortcuts if value == none begin return none end if type value == list begin return...
def to_nullable_array(value): """ Converts value into array object. Single values are converted into arrays with a single element. :param value: the value to convert. :return: array object or None when value is None. """ # Shortcuts if value == None: ...
Python
jtatman_500k
function _rel_tex_path self skin base begin return replace string call relpath skin base string / string \ end function
def _rel_tex_path(self, skin, base): return str(os.path.relpath(skin, base)).replace('/', '\\')
Python
nomic_cornstack_python_v1
function validate_pid self actual begin call validate_int string PIDs actual 2 50000 end function
def validate_pid(self, actual): self.validate_int("PIDs", actual, 2, 50000)
Python
nomic_cornstack_python_v1
function get_object self img begin set objectType = string none set colourProb = ones tuple 3 / 3.0 set distance = 0.0 set angle = 0.0 set patternFound = false comment patternFound, corners = self.get_corners(img) call get_corners img if patternFound begin comment Determine if the object is horizontal or vertical set d...
def get_object(self, img): objectType = 'none' colourProb = np.ones((3,)) / 3.0 distance = 0.0 angle = 0.0 self.patternFound = False #patternFound, corners = self.get_corners(img) self.get_corners(img) if (self.patternFound): ...
Python
nomic_cornstack_python_v1
from steg import * import cv2 import numpy as np from PIL import Image import pytest set IMG_DIR = string ./test/ function test_compare_empty_images begin set img_array_1 = zeros tuple 1 1 3 uint8 set img_array_2 = zeros tuple 1 1 3 uint8 assert call array_equal img_array_1 img_array_2 end function function test_compar...
from steg import * import cv2 import numpy as np from PIL import Image import pytest IMG_DIR = './test/' def test_compare_empty_images(): img_array_1= np.zeros((1,1,3), np.uint8) img_array_2 = np.zeros((1,1,3), np.uint8) assert np.array_equal(img_array_1, img_array_2) def test_compare_same_images(): ...
Python
zaydzuhri_stack_edu_python
function add_field self table new_field new_field_type begin set table = lower table append additional_fields string ALTER TABLE { table } ADD COLUMN { table } _ { new_field } { upper new_field_type } ; end function
def add_field(self, table, new_field, new_field_type): table = table.lower() self.additional_fields.append(f'ALTER TABLE {table} ADD COLUMN {table}_{new_field} {new_field_type.upper()};\n')
Python
nomic_cornstack_python_v1
function check_len number begin if length number == 15 and number at 0 + number at 1 in tuple string 34 string 37 begin set card = string AMEX end else if any list length number == 16 length number == 13 and number at 0 == string 4 begin set card = string VISA end else if length number == 16 begin set card = string MAS...
def check_len(number): if len(number) == 15 and number[0]+number[1] in ("34", "37"): card = "AMEX" elif any([len(number) == 16, len(number) == 13]) and number[0] == "4": card = "VISA" elif len(number) == 16: card = "MASTERCARD" else: card = "INVALID" return card
Python
nomic_cornstack_python_v1
string This scripts demonstrates how to use the 'argparse' library to parse command line arguments comment this is how you import the relevant class from the argparse library from argparse import ArgumentParser comment here we define three functions, all of which take arguments function say_hello name begin print strin...
""" This scripts demonstrates how to use the 'argparse' library to parse command line arguments """ # this is how you import the relevant class from the argparse library from argparse import ArgumentParser # here we define three functions, all of which take arguments def say_hello(name): print(f"Hey, {name}, ho...
Python
zaydzuhri_stack_edu_python
function __enter__ self begin call wlr_seat_keyboard_start_grab _ptr _ptr return self end function
def __enter__(self) -> KeyboardGrab: lib.wlr_seat_keyboard_start_grab(self._seat._ptr, self._ptr) return self
Python
nomic_cornstack_python_v1
function _generateTags self tags_path begin set tags = call loadtxt tags_path return tags end function
def _generateTags(self, tags_path): tags = np.loadtxt(tags_path) return tags
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import sys function fix N begin for i in range length N - 1 begin if N at i > N at i + 1 begin break end end for else begin return N end for j in call xrange i - 1 - 1 - 1 begin if N at j != N at i begin break end end for else begin set j = - 1 end set j = j + 1 set N at j = N at j - 1 for k in...
#!/usr/bin/python import sys def fix(N): for i in range(len(N)-1): if N[i] > N[i+1]: break else: return N for j in xrange(i-1, -1, -1): if N[j] != N[i]: break else: j = -1 j += 1 N[j] -= 1 for k in range(j+1, len(N)): N[k] = 9 return N def calc(N): N = fix(N) re...
Python
zaydzuhri_stack_edu_python
function time_usage name=string begin comment print ("In time_usage runID = {}".format(runID)) set start = time yield set end = time set elapsed_seconds = decimal string %.10f % end - start info string %s: Time Taken (seconds): %s name elapsed_seconds end function
def time_usage(name=""): # print ("In time_usage runID = {}".format(runID)) start = time.time() yield end = time.time() elapsed_seconds = float("%.10f" % (end - start)) logging.info('%s: Time Taken (seconds): %s', name, elapsed_seconds)
Python
nomic_cornstack_python_v1
function test_overall_report_banner begin assert length overall_data at string banner_report at string data == 8 end function
def test_overall_report_banner(): assert (len(overall_data['banner_report']['data']) == 8)
Python
nomic_cornstack_python_v1
class Dequene begin class Node begin function __init__ self elem next=none prev=none begin set elem = elem set next = next set prev = prev end function end class function __init__ self __head=none __tail=none __length=0 begin set __head = __head set __tail = __tail set __length = __length end function function __is__em...
class Dequene (): class Node : def __init__(self,elem,next = None,prev = None): self.elem = elem self.next = next self.prev = prev def __init__(self,__head = None,__tail = None,__length = 0): self.__head = __head self.__tail = __tail s...
Python
zaydzuhri_stack_edu_python
from matplotlib import pyplot as plt import csv from collections import Counter comment import pandas as pd string Here We are importing data as a Csv file to visualize. We should use horizontal bar when comparing many objects. NOte------------Pandas open csv as column wise dictionary and csv open csv as row wise dicti...
from matplotlib import pyplot as plt import csv from collections import Counter # import pandas as pd """ Here We are importing data as a Csv file to visualize. We should use horizontal bar when comparing many objects. NOte------------Pandas open csv as column wise dictionary and csv open csv as row wise dictionary "...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import sys import datetime from db.datastore import DataStore import pdb class DB begin set _commands_ = dict string set 0 ; string get 1 ; string unset 2 ; string numequalto 3 ; string begin 4 ; string rollback 5 ; string commit 6 ; string end 7 ; string exit 8 function __init__ self begin...
#!/usr/bin/env python import sys import datetime from db.datastore import DataStore import pdb class DB: _commands_ = { 'set':0, 'get':1, 'unset':2, 'numequalto':3, 'begin':4, 'rollback':5, 'commit':6,...
Python
zaydzuhri_stack_edu_python
class Soldier begin function __init__ self name begin set name = name end function end class class Guns begin function __init__ self begin set bullets = 30 end function function AK47 self begin print string Soldier { title name } is ready to shoot print string { title name } is ordered to shoot: print string AK47 Makes...
class Soldier: def __init__(self, name): self.name = name class Guns: def __init__(self): self.bullets = 30 def AK47(self): print(f'Soldier {self.name.title()} is ready to shoot') print(f'{self.name.title()} is ordered to shoot:') print('AK47 Makes a sound:...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python comment -*- coding: utf-8 -*- import urllib import urllib2 import threading import os string download a file or something else use a thread to download with http function downloadfile downloadinfo begin if downloadinfo at string filename == string or downloadinfo at string filename is non...
#! /usr/bin/env python # -*- coding: utf-8 -*- import urllib import urllib2 import threading import os """\ download a file or something else use a thread to download with http """ def downloadfile(downloadinfo): if downloadinfo['filename'] == "" or downloadinfo['filename'] is None: downloadinfo['filename']...
Python
zaydzuhri_stack_edu_python
comment -*- coidng: utf-8 -*- import random set fenc = string cp1252 with open string rt-polaritydata/rt-polarity.pos encoding=fenc as f begin set p_data = list comprehension string +1 + d for d in f end with open string rt-polaritydata/rt-polarity.neg encoding=fenc as f begin set n_data = list comprehension string -1 ...
# -*- coidng: utf-8 -*- import random fenc="cp1252" with open("rt-polaritydata/rt-polarity.pos", encoding=fenc) as f: p_data = ["+1 " + d for d in f] with open("rt-polaritydata/rt-polarity.neg", encoding=fenc) as f: n_data = ["-1 " + d for d in f] p_data.extend(n_data) random.shuffle(p_data) with open("sen...
Python
zaydzuhri_stack_edu_python
function test_home_page self begin set request = get factory string / set response = index request assert equal status_code 200 end function
def test_home_page(self): request = self.factory.get('/') response = index(request) self.assertEqual(response.status_code, 200)
Python
nomic_cornstack_python_v1
string Posts views comment Django from django.http import HttpResponse comment Utilities from datetime import datetime set posts = list dict string name string Vía Láctea ; string user string C. Vander ; string timestamp string format time now string %b %dth, %Y - %H:%M hrs ; string picture string https://picsum.photos...
""" Posts views """ #Django from django.http import HttpResponse #Utilities from datetime import datetime posts = [ { 'name': 'Vía Láctea', 'user': 'C. Vander', 'timestamp': datetime.now().strftime('%b %dth, %Y - %H:%M hrs'), 'picture': 'https://picsum.photos/200/200/?image=903', }, ...
Python
zaydzuhri_stack_edu_python
function save_embedding self begin print string Saving the embedding. set out = concatenate list M Q axis=1 set out = concatenate list reshape array range shape at 0 - 1 1 out axis=1 set out = call DataFrame out columns=list string id + list comprehension string X_ + string dim for dim in range dimensions * 2 to csv ou...
def save_embedding(self): print("Saving the embedding.") self.out = np.concatenate([self.M, self.Q],axis=1) self.out = np.concatenate([np.array(range(self.X.shape[0])).reshape(-1,1),self.out],axis=1) self.out = pd.DataFrame(self.out,columns = ["id"] + [ "X_"+str(dim) for dim in range(sel...
Python
nomic_cornstack_python_v1
function getSusedia row col znak begin set susedia = set comment hlada ich vo vsetkych smeroch for tuple i j in list tuple - 1 1 tuple - 1 0 tuple 0 1 tuple 1 0 tuple 1 - 1 tuple 0 - 1 begin if row + i in range pocet_riadkov and col + j in range pocet_stlpcov begin comment ak je na susednej pozicii rovnaky znak if valu...
def getSusedia(row, col, znak): susedia = set() for i, j in [(-1, 1), (-1, 0), (0, 1), (1, 0), (1, -1), (0, -1)]: #hlada ich vo vsetkych smeroch if (row + i) in range(pocet_riadkov) and \ (col + j) in range(pocet_stlpcov): if values[row + i][col + j] == znak: ...
Python
nomic_cornstack_python_v1
function parse_count_tracking self fp cursor table begin pass end function
def parse_count_tracking(self, fp, cursor, table): pass
Python
nomic_cornstack_python_v1
function calculate data data_top begin set tuple size intensity age = tuple array list data at string Size array list data at string Intensity iat at tuple 1 0 set tuple size_avg intensity_avg = tuple call average size call average intensity return tuple size_avg intensity_avg age end function
def calculate(data, data_top): size, intensity, age = np.array([data["Size"]]), np.array([data["Intensity"]]), data_top.iat[1,0] size_avg, intensity_avg = np.average(size), np.average(intensity) return size_avg, intensity_avg, age
Python
nomic_cornstack_python_v1
function can_first_player_win m n begin if m == 1 and n == 1 begin return string The Second Player (F2) can ensure a win (First player has no moves) end else begin return string The First Player (F1) can ensure a win end end function comment Test cases comment Expected: The Second Player can ensure a win print call can...
def can_first_player_win(m: int, n: int) -> str: if m == 1 and n == 1: return "The Second Player (F2) can ensure a win (First player has no moves)" else: return "The First Player (F1) can ensure a win" # Test cases print(can_first_player_win(1, 1)) # Expected: The Second Player can ensure a wi...
Python
dbands_pythonMath
from tkinter import * set window = call Tk comment keydown function function click begin set entered_text = get e1 end function comment Coin label set l1 = call Label window text=string Coin width=10 grid row=0 column=0 comment price label set l2 = call Label window text=string Price width=10 grid row=0 column=1 set li...
from tkinter import * window = Tk() #keydown function def click(): entered_text=e1.get() #Coin label l1 = Label(window, text="Coin",width=10) l1.grid(row=0,column=0) #price label l2 = Label(window, text="Price", width=10) l2.grid(row=0,column=1) list1=Listbox(window, height=1, width=5) list1.grid(row=1,column=0...
Python
zaydzuhri_stack_edu_python
for _ in range input begin set n = input set tuple r t = tuple string string set tuple c p = tuple 0 0 for i in range n begin set s = strip call raw_input if r == string begin set r = s end if r == s begin set c = c + 1 end else begin set t = s set p = p + 1 end end end
for _ in range (input()) : n = input() r, t = "", "" c, p = 0, 0 for i in range (n) : s = raw_input().strip() if r == "" : r = s if r == s : c += 1 else : t = s p += 1
Python
zaydzuhri_stack_edu_python
function __init__ self rate=none tag_list=list favorite=none new=none begin set rate = if expression rate is none or rate >= 0 and rate <= 10 then rate else if expression rate < 0 then 1 else 10 set tag_list = if expression tag_list then tag_list else list set favorite = favorite set new = new end function
def __init__(self, rate=None, tag_list=[], favorite=None, new=None): self.rate = rate if (rate is None or (rate >= 0 and rate <= 10)) else 1 if rate < 0 else 10 self.tag_list = tag_list if tag_list else [] self.favorite = favorite self.new = new
Python
nomic_cornstack_python_v1
function write self fp begin try begin set default_section_items = items self NOSECTION call remove_section NOSECTION for tuple key value in default_section_items begin write fp format string {0} = {1} key value end end comment fp.write("\n") except NoSectionError begin pass end write RawConfigParser self fp call add_s...
def write(self, fp): try: default_section_items = self.items(NOSECTION) self.remove_section(NOSECTION) for (key, value) in default_section_items: fp.write("{0} = {1}\n".format(key, value)) # fp.write("\n") except ConfigParser.NoS...
Python
nomic_cornstack_python_v1
function find_max_min numbers begin set max_num = decimal string -inf set min_num = decimal string inf for num in numbers begin if num > max_num begin set max_num = num end else if num < min_num begin set min_num = num end end return tuple max_num min_num end function
def find_max_min(numbers): max_num = float("-inf") min_num = float("inf") for num in numbers: if num > max_num: max_num = num elif num < min_num: min_num = num return (max_num, min_num)
Python
flytech_python_25k
function __init__ self settings begin call __init__ set embed_size = embed_dim set context_size = context_dim set rnn_layers = rnn_layers set rnn_kind = rnn set input_size = vocab_size set cuda = cuda set gradient_clip = gradient_clip set seqlen = msg_len set num_classes = length call get_classes settings set bidirecti...
def __init__(self, settings): super(WordRnn, self).__init__() self.embed_size = settings.embed_dim self.context_size = settings.context_dim self.rnn_layers = settings.rnn_layers self.rnn_kind = settings.rnn self.input_size = settings.vocab_size self.cuda = settin...
Python
nomic_cornstack_python_v1
class MinhaClasse begin comment membro_cls pertence ao escopo da classe e nao a instancia set membro_cls = 50 function __init__ self begin set membro_inst = - 10 end function function func self begin print membro_inst print membro_cls print membro_cls end function end class set i1 = call MinhaClasse set i2 = call Minha...
class MinhaClasse: #membro_cls pertence ao escopo da classe e nao a instancia membro_cls = 50 def __init__(self): self.membro_inst = -10 def func(self): print(self.membro_inst) print(self.membro_cls) print(MinhaClasse.membro_cls) i1 = MinhaClasse() i2 = MinhaClasse() pr...
Python
zaydzuhri_stack_edu_python
function home request begin set context_dict = dict set employee = first filter user=user comment context_dict = { comment context_helper.get_emp_info(employee) comment } comment print (context_dict) update context_dict call get_emp_info employee return call render request string home.html context_dict end function
def home(request): context_dict = {} employee = models.Teacher.objects.filter( user=request.user ).first() # context_dict = { # context_helper.get_emp_info(employee) # } # print (context_dict) context_dict.update(context_helper.get_emp_info(employee)) return render(request, "home.html", context_dict)
Python
nomic_cornstack_python_v1
function test_record_purchase self begin set student1 = call UserFactory save set student2 = call UserFactory save set params_cc = dict string card_accountNumber string 1234 ; string card_cardType string 001 ; string billTo_firstName first_name set params_nocc = dict string card_accountNumber string ; string card_card...
def test_record_purchase(self): student1 = UserFactory() student1.save() student2 = UserFactory() student2.save() params_cc = {'card_accountNumber': '1234', 'card_cardType': '001', 'billTo_firstName': student1.first_name} params_nocc = {'card_accountNumber': '', 'ca...
Python
nomic_cornstack_python_v1
comment -------------------------------------------------------------------------------------- # comment Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. comment -----------------------------------------------------------------------------...
# -------------------------------------------------------------------------------------- # # Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. # -------------------------------------------------------------------------------------- # def...
Python
zaydzuhri_stack_edu_python
from typing import List class Solution begin function twoSum self nums target begin string :type nums: List[int] :type target: int :rtype: List[int] set h = dict for tuple i num in enumerate nums begin set n = target - num if n not in h begin set h at num = i end else begin return list h at n i end end end function en...
from typing import List class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ h = {} for i, num in enumerate(nums): n = target - num if n not in h: h[num] = i...
Python
zaydzuhri_stack_edu_python
function test_update_device_config_invalid_data hass test_client begin with call object config string SECTIONS list string zwave begin yield from call async_setup_component hass string config dict end set client = yield from call test_client app set resp = yield from post string /api/config/zwave/device_config/hello.be...
def test_update_device_config_invalid_data(hass, test_client): with patch.object(config, 'SECTIONS', ['zwave']): yield from async_setup_component(hass, 'config', {}) client = yield from test_client(hass.http.app) resp = yield from client.post( '/api/config/zwave/device_config/hello.beer', ...
Python
nomic_cornstack_python_v1
comment -> List[SecureMessage]: function split self members begin raise NotImplemented end function
def split(self, members: List[ID]): # -> List[SecureMessage]: raise NotImplemented
Python
nomic_cornstack_python_v1
function value self begin string Return this type's value. Returns: object: The value of an enum, bitmask, etc. if call isenum begin if is instance _value enum_ref begin return value end return _value end else if call is_bitmask begin return bitmask end else begin return _value end end function
def value(self): """Return this type's value. Returns: object: The value of an enum, bitmask, etc. """ if self.isenum(): if isinstance(self._value, self.enum_ref): return self._value.value return self._value elif self.is_bitma...
Python
jtatman_500k
function dominant_freqs E begin set nfft = 2 ^ 11 set fft = fft E axis=0 n=nfft set fft = fft at slice 0 : nfft // 2 : set fft = absolute fft ^ 2 set freq = call fftfreq nfft set freq = freq at slice 0 : nfft // 2 : set freqs = freq at argument maximum axis=0 return freqs end function
def dominant_freqs(E): nfft = 2 ** 11 fft = np.fft.fft(E, axis=0, n=nfft) fft = fft[0:nfft // 2] fft = np.abs(fft)**2 freq = np.fft.fftfreq(nfft) freq = freq[0:nfft // 2] freqs = freq[fft.argmax(axis=0)] return freqs
Python
nomic_cornstack_python_v1
print string Hello World!
print("Hello World!")
Python
jtatman_500k
function test_set_molecule_database_w_descriptor_property_from_csv self begin set properties = call normal size=length test_smiles set n_features = 20 set features = call normal size=tuple length test_smiles n_features set csv_fpath = call smiles_seq_to_xl_or_csv ftype=string csv property_seq=properties feature_arr=fea...
def test_set_molecule_database_w_descriptor_property_from_csv(self): properties = np.random.normal(size=len(self.test_smiles)) n_features = 20 features = np.random.normal(size=(len(self.test_smiles), n_features)) csv_fpath = self.smiles_seq_to_xl_or_csv( ftype="csv", property...
Python
nomic_cornstack_python_v1
comment dsa import threading import time import requests import cv2 import numpy as np class VideoReceiver begin string Main class handling connections and detection threads set imgs = dict set urls = list set video_sources = list set recv_threads = list set proccessed_images = dict set number_of_eyes = dict set ...
#dsa import threading import time import requests import cv2 import numpy as np class VideoReceiver: """Main class handling connections and detection threads""" imgs = {} urls = [] video_sources = [] recv_threads = [] proccessed_images = {} number_of_eyes = {} stop_event = threading.E...
Python
zaydzuhri_stack_edu_python
function updateMessages self parameters begin return end function
def updateMessages(self, parameters): return
Python
nomic_cornstack_python_v1
function example_config temp_config_paths begin call generate_static_config static return temp_config_paths end function
def example_config( temp_config_paths: submanager.models.config.ConfigPaths, ) -> submanager.models.config.ConfigPaths: submanager.config.static.generate_static_config(temp_config_paths.static) return temp_config_paths
Python
nomic_cornstack_python_v1
comment utility functions are mostly adapted from Ali Taylan Cemgil's notes and codes import numpy as np comment random number generator for given probabilities with inverse transform sampling function randgen prob val_list=list begin set N = length prob set values = list if length val_list == 0 begin set values = ran...
#utility functions are mostly adapted from Ali Taylan Cemgil's notes and codes import numpy as np #random number generator for given probabilities with inverse transform sampling def randgen(prob, val_list=[]): N = len(prob) values = [] if len(val_list) == 0: values = range(N) else: val...
Python
zaydzuhri_stack_edu_python
function test_generator begin set fname = call get_generator_filename set f = call EdfReader fname return f end function
def test_generator(): fname = get_generator_filename() f = pyedflib.EdfReader(fname) return f
Python
nomic_cornstack_python_v1
function check_single_value board done_cells i j begin comment Check if list element is the only possibility in its row for k in board at i at j begin set count = 1 for l in range n begin if k in board at i at l and l != j begin set count = count + 1 end end if count == 1 begin set board at i at j = list k append done_...
def check_single_value(board, done_cells, i, j): # Check if list element is the only possibility in its row for k in board[i][j]: count = 1 for l in range(n): if k in board[i][l] and l!=j: count += 1 if count == 1: board[i][j] = [k] don...
Python
nomic_cornstack_python_v1
import numpy as np import imageio as io import os.path comment Animates successive frames of seam removal as saved by SeamCarving.cpp comment Assumes frames are enumerated [1..n] in the folder 'data/output/' comment Garrett Johnston & Thanh Nguyen, CS73 20F set im_path = string data/output/ set images = list set i = 1...
import numpy as np import imageio as io import os.path # Animates successive frames of seam removal as saved by SeamCarving.cpp # Assumes frames are enumerated [1..n] in the folder 'data/output/' # # Garrett Johnston & Thanh Nguyen, CS73 20F im_path = 'data/output/' images = [] i = 1 path = im_path + str(i) + '.p...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 function safe_function fct *args begin import sys try begin return *fct end except exception as urrego begin write stderr format string Exception: urrego return false end end function
#!/usr/bin/python3 def safe_function(fct, *args): import sys try: return *fct except exception as urrego: sys.stderr.write("Exception:\n".format(urrego)) return False
Python
zaydzuhri_stack_edu_python
import sys import functions print argv if string --help in argv begin print string this is our super helpful help message end if length argv at slice 1 : : >= 2 begin print call add_strings argv at 1 argv at 2 end print string a line print string next line print string another line call add_strings argv at 1 argv at 2...
import sys import functions print(sys.argv) if "--help" in sys.argv: print("this is our super helpful help message") if len(sys.argv[1:]) >= 2: print(functions.add_strings(sys.argv[1], sys.argv[2])) print("a line") print("next line") print("another line") functions.add_strings(sys.argv[1], sys.argv[2]) pr...
Python
zaydzuhri_stack_edu_python
function flat self begin if parent != self begin yield self end for i in children begin for j in call flat begin yield j end end end function
def flat(self): if self.parent != self: yield self for i in self.children: for j in i.flat(): yield j
Python
nomic_cornstack_python_v1
comment !/bin/python3 import math import os import random import re import sys comment https://www.hackerrank.com/challenges/ctci-bubble-sort/problem comment Complete the countSwaps function below. function countSwaps a begin set a_len = length a set num_swaps = 0 for x in range a_len - 1 begin for y in range a_len - x...
#!/bin/python3 import math import os import random import re import sys # https://www.hackerrank.com/challenges/ctci-bubble-sort/problem # Complete the countSwaps function below. def countSwaps(a): a_len=len(a) num_swaps=0 for x in range(a_len-1): for y in range(a_len-x-1): if a[y]>a[y...
Python
zaydzuhri_stack_edu_python
function supervised_predict model X_test labels n_words=10 output_format=string df begin set proba = call predict_proba X_test set proba_df = call DataFrame 0 index=index columns=labels for tuple i c in enumerate columns begin set loc at tuple slice : : c = list zip *proba[i] at 1 end set Y_pred = call DataFrame 0 i...
def supervised_predict(model, X_test, labels, n_words=10, output_format="df"): proba = model.predict_proba(X_test) proba_df = pd.DataFrame(0, index=X_test.index, columns=labels) for i, c in enumerate(proba_df.columns): proba_df.loc[:,c] = ...
Python
nomic_cornstack_python_v1
import cherrypy import json import math class MovieController extends object begin set data = dict comment Get all of the moveis from teh database function get_movies_from_db self database=string movies.dat begin set openfile = open database string r+ set movie_dict = dict for line in openfile begin comment Split the...
import cherrypy import json import math class MovieController(object): data = {} # Get all of the moveis from teh database def get_movies_from_db(self, database="movies.dat"): openfile = open(database, 'r+') movie_dict = {} for line in openfile: # Split them on the '::' movie_info = line.rstrip('\n')...
Python
zaydzuhri_stack_edu_python
import numpy as np import RungeKuttaFehlberg as RKF import numpy as np import math as m import sys import matplotlib.pyplot as plt from matplotlib import animation , rc import time from numpy import sqrt comment Jorda comment km set diameter_ekvator = 12756.28 comment km set poldiameter = 12713.56 comment kg set masse_...
import numpy as np import RungeKuttaFehlberg as RKF import numpy as np import math as m import sys import matplotlib.pyplot as plt from matplotlib import animation, rc import time from numpy import sqrt #Jorda diameter_ekvator = 12756.28 #km poldiameter = 12713.56 #km masse_Jorda = 5.9736*10**24 #kg rotasjonsperio...
Python
zaydzuhri_stack_edu_python
function skill_information begin set client = call client string iot-data region_name=string us-west-2 set session_attributes = dict set card_title = string Welcome set should_end_session = true set reprompt_text = none if call is_online begin set speech_output = string The coffee machine is offline. end else begin ca...
def skill_information(): client = boto3.client('iot-data', region_name='us-west-2') session_attributes = {} card_title = "Welcome" should_end_session = True reprompt_text = None if(is_online()): speech_output = "The coffee machine is offline." else: client.publ...
Python
nomic_cornstack_python_v1
class Hotel begin set hotel_type = string Budget and Value Hotels function __init__ self visitors_per_year=none number_of_rooms=none star_rating=none name_of_hotel=string New hotel price_uah_per_day=none country=string New country begin set visitors_per_year = visitors_per_year set number_of_rooms = number_of_rooms set...
class Hotel: hotel_type = "Budget and Value Hotels" def __init__(self, visitors_per_year=None, number_of_rooms=None, star_rating=None, name_of_hotel="New hotel", price_uah_per_day=None, country="New country", ): self.visitors_per_year = visitors_per_year self.number_of_ro...
Python
zaydzuhri_stack_edu_python
comment ChiPy Code function collect_natural_patches num_patches=100000 patch_width=8 begin string collects image patches the natural images are from a specific folder of 13 .tiff files set max_tries = num_patches * 50 set image_width = 200 comment the first patch number accepted from an image set img_first_patch = 0 co...
# ChiPy Code def collect_natural_patches(num_patches = 100000, patch_width = 8): """ collects image patches the natural images are from a specific folder of 13 .tiff files""" max_tries = num_patches * 50 image_width = 200 img_first_patch = 0 # the first patch number accepted from an image img_first_tr...
Python
zaydzuhri_stack_edu_python
class Stack begin function __init__ self begin set items = list end function function push self item begin append items item end function function pop self begin return pop items end function function peek self begin return items at length items - 1 end function function size self begin return length items end functio...
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def isEmpty(self): return self.items == []
Python
iamtarun_python_18k_alpaca
async function added self begin set more = true comment Make sure waiting on event_added is done by one coroutine at a time. comment Multiple might be waiting and if there is only one event in the queue comment they would all otherwise be triggered async_with event_added_lock begin await wait event_added async_with loc...
async def added(self) -> Tuple[bool, List[Any]]: more = True # Make sure waiting on event_added is done by one coroutine at a time. # Multiple might be waiting and if there is only one event in the queue # they would all otherwise be triggered async with self.parent.event_added_l...
Python
nomic_cornstack_python_v1
function predict parameters X begin comment Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold. set tuple predictions cache = call forward_propagation X parameters return predictions end function
def predict(parameters, X): # Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold. predictions, cache = forward_propagation(X, parameters) return predictions
Python
nomic_cornstack_python_v1
function slot_owns_changed self orderbook _dummy begin comment Fix MtGox satoshi bug for order in owns begin if volume == 1e-08 * COIN begin debug string [s]Satoshi! %s: %s: %s @ %s order id: %s % tuple string status string typ call base2str volume call quote2str price string oid call cancel oid end end call check_trad...
def slot_owns_changed(self, orderbook, _dummy): # Fix MtGox satoshi bug for order in orderbook.owns: if order.volume == 0.00000001 * COIN: self.debug("[s]Satoshi! %s: %s: %s @ %s order id: %s" % (str(order.status), str(order.typ), self.gox.base2str(order.volume), self.gox.q...
Python
nomic_cornstack_python_v1
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None comment 思路: 从root dfs改变各个节点的值,并用set存储 class FindElements begin function __init__ self root begin set memo = set function dfs node curv begin if node b...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 思路: 从root dfs改变各个节点的值,并用set存储 class FindElements: def __init__(self, root): self.memo = set() def dfs(node, curv): if node...
Python
zaydzuhri_stack_edu_python
string Created on 14. lip 2018. @author: Filip import cv2 from LSB import LSB print set stego = input string From what image do you like to retrieve message? set key = input string Which key should be used? set nova = call imread stego print string Opened image named + stego + string . set poruka = call LSB_dohvati nov...
''' Created on 14. lip 2018. @author: Filip ''' import cv2 from LSB import LSB print() stego = input("From what image do you like to retrieve message? ") key = input("Which key should be used? " ) nova=cv2.imread(stego) print("Opened image named " + stego +".") poruka=LSB.LSB_dohvati(nova, key = int(key)) print("...
Python
zaydzuhri_stack_edu_python
import sys set a = 0 set b = 5
import sys a = 0 b = 5
Python
zaydzuhri_stack_edu_python
function _sent_by self origin cable begin call _assoc SENT_BY_TYPE SENDER_TYPE origin CABLE_TYPE cable end function
def _sent_by(self, origin, cable): self._assoc(psis.SENT_BY_TYPE, psis.SENDER_TYPE, origin, psis.CABLE_TYPE, cable)
Python
nomic_cornstack_python_v1
import dash from dash.dependencies import Input , Output , State import dash_core_components as dcc import dash_html_components as html from datetime import datetime as dt from dash_html_components.Img import Img from dash.exceptions import PreventUpdate import yfinance as yf import pandas as pd import plotly.graph_obj...
import dash from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html from datetime import datetime as dt from dash_html_components.Img import Img from dash.exceptions import PreventUpdate import yfinance as yf import pandas as pd import plotly....
Python
zaydzuhri_stack_edu_python
function create_about_window self begin set about = string Kuray is a cross-platform application for measuring audio systems. With it, you can obtain amplitude and phase responses from a loudspeaker. It is still in a very early stage of development. You can follow its progress on github:<br><a href='http://github.com/P...
def create_about_window(self): about = ("Kuray is a cross-platform application for measuring audio " "systems. With it, you can obtain amplitude and phase " "responses from a loudspeaker. It is still in a very early " "stage of development. You can follow its ...
Python
nomic_cornstack_python_v1
function end_to_end_latency_improved path task_results n=1 e_0=0 **kwargs begin set lmax = 0 set lmin = 0 set lmax = call _event_exit_path path task_results length tasks - 1 n - 1 e_0 - e_0 for t in tasks begin if is instance t Task and t in task_results begin comment sum up best-case response times set lmin = lmin + b...
def end_to_end_latency_improved(path, task_results, n=1, e_0=0, **kwargs): lmax = 0 lmin = 0 lmax = _event_exit_path(path, task_results, len(path.tasks) - 1, n - 1, e_0) - e_0 for t in path.tasks: if isinstance(t, model.Task) and t in task_results: # sum up best-case response times ...
Python
nomic_cornstack_python_v1
comment 1878. Get Biggest Three Rhombus Sums in a Grid comment add the line but not edge only function getBiggestThree grid begin set tuple rows cols = tuple length grid length grid at 0 set result = set for i in range rows begin for j in range cols begin add result grid at i at j set length = min i rows - 1 - i j cols...
#1878. Get Biggest Three Rhombus Sums in a Grid # add the line but not edge only def getBiggestThree(grid): rows, cols = len(grid),len(grid[0]) result = set() for i in range(rows): for j in range(cols): result.add(grid[i][j]) length = min(i, rows - 1 - i , j , cols - 1 - j) ...
Python
zaydzuhri_stack_edu_python
for i in range 1 1001 begin append fact fact at - 1 * i end if X % D != 0 or Y % D != 0 begin print 0 end else begin set X = absolute X // D set Y = absolute Y // D if X + Y > N or X + Y + N % 2 != 0 begin print 0 end else begin set ans = 0 for a in range N - X + Y // 2 + 1 begin set b = N - X + Y // 2 - a set ans = an...
for i in range(1, 1001): fact.append(fact[-1] * i) if X % D != 0 or Y % D != 0: print(0) else: X = abs(X//D) Y = abs(Y//D) if X + Y > N or (X+Y+N) % 2 != 0: print(0) else: ans = 0 for a in range((N-(X+Y))//2+1): b = (N-(X+Y))//2 - a ...
Python
zaydzuhri_stack_edu_python
function CallbackChecker call begin call set_sender id 0 set vk = call API call Session call get_data id at 1 if data at slice : 15 : == string write_to_friend begin set reciever_id = integer data at slice 16 : : call set_status id 2 reciever_id set user = get users user_ids=reciever_id name_case=string dat v=string...
def CallbackChecker(call): db.set_sender(call.message.chat.id, 0) vk = API(Session(db.get_data(call.message.chat.id)[1])) if call.data[:15] == 'write_to_friend': reciever_id = int(call.data[16:]) db.set_status(call.from_user.id, 2, reciever_id) user = vk.users.get(user_ids = reciever...
Python
nomic_cornstack_python_v1
set num = integer input string Please input num: print string 加密前的数字是:%d % num set a = num // 1000 set b = num % 1000 // 100 set c = num % 100 // 10 set d = num % 10 set a = a + 5 % 10 set b = b + 5 % 10 set c = c + 5 % 10 set d = d + 5 % 10 set n_num = d * 1000 + c * 100 + b * 10 + a print string 加密后的数字是:%d % n_num se...
num=int(input("Please input num:")) print("加密前的数字是:%d"%num) a=num//1000 b=num%1000//100 c=num%100//10 d=num%10 a=(a+5)%10 b=(b+5)%10 c=(c+5)%10 d=(d+5)%10 n_num=d*1000+c*100+b*10+a print("加密后的数字是:%d"%n_num) a=n_num//1000 b=n_num%1000//100 c=n_num%100//10 d=n_num%10 a=(a+5)%10 b=(b+5)%10 c=(c+5)%10 d=(d+5)%10 pre_num=d*...
Python
zaydzuhri_stack_edu_python
import decimal import borse.bitcoin_api import borse.utility function is_valid_numeric_type numeric precision begin if not is instance numeric str begin return false end try begin set value = call Decimal numeric end except InvalidOperation begin return false end return call decimal_has_correct_precision value precisio...
import decimal import borse.bitcoin_api import borse.utility def is_valid_numeric_type(numeric, precision): if not isinstance(numeric, str): return False try: value = decimal.Decimal(numeric) except decimal.InvalidOperation: return False return borse.utility.decimal_has_correct_...
Python
zaydzuhri_stack_edu_python
from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.tree import DecisionTree from pyspark import SparkConf , SparkContext from numpy import array comment Boilerplate Spark stuff: set conf = call setAppName string SparkDecisionTree set sc = call SparkContext conf=conf comment 수정 comment Some functions t...
from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.tree import DecisionTree from pyspark import SparkConf, SparkContext from numpy import array # Boilerplate Spark stuff: conf = SparkConf().setMaster("local").setAppName("SparkDecisionTree") sc = SparkContext(conf = conf) ## 수정 # Some functions that c...
Python
zaydzuhri_stack_edu_python