code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment Adam Stevens, 2013--2021 comment Functions for calculating properties of galaxies in a general, pipelined manner. import numpy as np import math try begin from import galread as gr end except ValueError begin import galread as gr end from scipy import optimize as op from scipy import signal as ss from scipy im...
# Adam Stevens, 2013--2021 # Functions for calculating properties of galaxies in a general, pipelined manner. import numpy as np import math try: from . import galread as gr except ValueError: import galread as gr from scipy import optimize as op from scipy import signal as ss from scipy import interpolate fro...
Python
zaydzuhri_stack_edu_python
function get_edid self begin if not call has_edid begin raise call ResourceError string Connected monitor does not provide an EDID property end set EDID_ATOM = call intern_atom PROPERTY_RANDR_EDID set EDID_TYPE = 19 set EDID_LENGTH = 128 set edid_info = call xrandr_get_output_property _id EDID_ATOM EDID_TYPE 0 EDID_LEN...
def get_edid(self): if not self.has_edid(): raise ResourceError("Connected monitor does not provide an EDID property") EDID_ATOM = self.__display.intern_atom(PROPERTY_RANDR_EDID) EDID_TYPE = 19 EDID_LENGTH = 128 edid_info = self.__display.xrandr_get_output_property( ...
Python
nomic_cornstack_python_v1
comment author : babang/DreamHunter comment date : 4 january 2016 comment desc : program that convert decimal to romanian number import sys set test_cases = open argv at 1 string r comment I = 1 comment V = 5 comment X = 10 comment L = 50 comment C = 100 comment D = 500 comment M = 1000 function _roma num begin if num ...
# author : babang/DreamHunter # date : 4 january 2016 # desc : program that convert decimal to romanian number import sys test_cases = open(sys.argv[1], 'r') # I = 1 # V = 5 # X = 10 # L = 50 # C = 100 # D = 500 # M = 1000 def _roma(num): if num == 0: return '' elif num < 4: # code here return 'I'+_roma(n...
Python
zaydzuhri_stack_edu_python
function get_infoblox_mx_connection self begin return iblox_mx_records end function
def get_infoblox_mx_connection(self): return self.m_connection.iblox_mx_records
Python
nomic_cornstack_python_v1
function set_attr self key value begin if key in __property_meta begin set __dict__ at key = value end else if key == string error_code begin set error_code = value end else if key == string error_descr begin set error_descr = value end else if key == string invocation_result begin set invocation_result = value end els...
def set_attr(self, key, value): if key in self.__property_meta: self.__dict__[key] = value elif key == 'error_code': self.error_code = value elif key == 'error_descr': self.error_descr = value elif key == 'invocation_result': self.invocatio...
Python
nomic_cornstack_python_v1
function pop self begin if not s2 begin while s1 begin append s2 pop s1 end end return pop s2 end function
def pop(self): if not self.s2: while self.s1: self.s2.append(self.s1.pop()) return self.s2.pop()
Python
nomic_cornstack_python_v1
comment nopep8 - ignore N802 function tearDownClass cls begin release resources end function
def tearDownClass(cls): # nopep8 - ignore N802 cls.resources.release()
Python
nomic_cornstack_python_v1
function _p_qrs_tconst pattern pwave begin call BASIC_TCONST pattern pwave set obseq = obs_seq set idx = call get_step pwave set tnet = last_tnet comment Beat start call set_equal start start call add_constraint start end PW_DURATION if idx == 0 or not is instance obseq at idx - 1 QRS begin return end set qrs = obseq a...
def _p_qrs_tconst(pattern, pwave): BASIC_TCONST(pattern, pwave) obseq = pattern.obs_seq idx = pattern.get_step(pwave) tnet = pattern.last_tnet # Beat start tnet.set_equal(pwave.start, pattern.hypothesis.start) tnet.add_constraint(pwave.start, pwave.end, C.PW_DURATION) if idx == 0 or not ...
Python
nomic_cornstack_python_v1
function find_nearest a a0 begin set idx = argument minimum return flat at idx end function
def find_nearest(a, a0): idx = np.abs(a - a0).argmin() return a.flat[idx]
Python
nomic_cornstack_python_v1
class Solution begin function partition self head x begin comment 借助哨兵节点,可以不必单独考虑边界情况 set before = call ListNode 0 set before_head = call ListNode 0 set after = call ListNode 0 set after_head = call ListNode 0 while head begin if val < x begin set next = head set before = next end else begin set next = head set after =...
class Solution: def partition(self, head: ListNode, x: int) -> ListNode: ## 借助哨兵节点,可以不必单独考虑边界情况 before = before_head = ListNode(0) after = after_head = ListNode(0) while head: if head.val < x: before.next = head before = before.ne...
Python
zaydzuhri_stack_edu_python
function calculate_average numbers begin comment check if the list is empty if not numbers begin return 0 end return sum numbers / length numbers end function
def calculate_average(numbers): if not numbers: # check if the list is empty return 0 return sum(numbers) / len(numbers)
Python
greatdarklord_python_dataset
comment DijkstraAlgorithm import sys set input = readline set INF = integer 1000000000.0 set tuple n m = tuple 6 11 set start = 1 set graph = list comprehension list for i in range n + 1 set visited = list false * n + 1 set distance = list INF * n + 1 set graph = list list list tuple 2 2 tuple 3 3 tuple 4 1 list tupl...
#DijkstraAlgorithm import sys input = sys.stdin.readline INF = int(1e9) n, m = 6, 11 start = 1 graph = [[] for i in range(n+1)] visited = [False] * (n+1) distance = [INF] * (n+1) graph = [ [], [(2, 2), (3, 3), (4, 1)], [(3, 3), (4, 2)], [(2, 3), (6, 5)], [(3, 3), (5, 1)], [(3, 1), (6, 2)], ...
Python
zaydzuhri_stack_edu_python
import scrapy import re from CafeNervosa.items import SeasonItems comment need to figure out exactly how the pipeline module works comment the next big step is going to be going to the individual episode's page and scraping the description class EpisodeInformation extends Spider begin set name = string episodes set all...
import scrapy import re from CafeNervosa.items import SeasonItems #need to figure out exactly how the pipeline module works #the next big step is going to be going to the individual episode's page and scraping the description class EpisodeInformation(scrapy.Spider): name = 'episodes' allowed_domains =['frasieronline...
Python
zaydzuhri_stack_edu_python
function process_plot plot_data rgb_pool deepforest_model begin comment DeepForest prediction set rgb_sensor_path = call find_sensor_path bounds=total_bounds lookup_pool=rgb_pool sensor=string rgb set boxes = call predict_trees deepforest_model=deepforest_model rgb_path=rgb_sensor_path bounds=total_bounds comment Merge...
def process_plot(plot_data, rgb_pool, deepforest_model): #DeepForest prediction rgb_sensor_path = find_sensor_path(bounds=plot_data.total_bounds, lookup_pool=rgb_pool, sensor="rgb") boxes = predict_trees(deepforest_model=deepforest_model, rgb_path=rgb_sensor_path, bounds=plot_data.total_bounds) #Merge ...
Python
nomic_cornstack_python_v1
comment Print triangle of star("*") pattern in Python-13 set n = integer input if 1 <= n <= 100 begin for i in range n begin for j in range i + 1 begin print string * end=string end print end for i in range n - 1 begin for j in range n - 1 - i begin print string * end=string end print end end
# Print triangle of star("*") pattern in Python-13 n = int(input()) if (1 <= n <= 100): for i in range(n): for j in range(i+1): print("*", end='') print() for i in range(n-1): for j in range(n-1-i): print("*", end='') print()
Python
zaydzuhri_stack_edu_python
function input_fn params begin set batch_size = params at string batch_size set d = call TFRecordDataset input_file if is_training begin set d = repeat comment 3700 set d = shuffle d buffer_size=370 end set d = apply d call map_and_batch lambda record -> call _decode_record record name_to_features batch_size=batch_size...
def input_fn(params): batch_size = params["batch_size"] d = tf.data.TFRecordDataset(input_file) if is_training: d = d.repeat() d = d.shuffle(buffer_size=370) #3700 d = d.apply( tf.contrib.data.map_and_batch( lambda record: _dec...
Python
nomic_cornstack_python_v1
comment C - Tax Increase import math set tuple A B = map int split input set ans = string -1 for i in range 1 10 ^ 5 begin if floor i * 0.08 == A and floor i * 0.1 == B begin set ans = i break end end print ans
#C - Tax Increase import math A,B = map(int,input().split()) ans = '-1' for i in range(1,10**5): if math.floor(i * 0.08)== A and math.floor(i*0.1) == B: ans = i break print(ans)
Python
zaydzuhri_stack_edu_python
function topic request topic_id begin set posts = call order_by string created set posts = call mk_paginator request posts DJANGO_SIMPLE_FORUM_REPLIES_PER_PAGE set topic = get objects pk=topic_id set forums = all set forumid = forum_id return call render request string cms_forum/topic.html dict string posts posts ; str...
def topic(request, topic_id): posts = Post.objects.filter(topic=topic_id).order_by("created") posts = mk_paginator(request, posts, DJANGO_SIMPLE_FORUM_REPLIES_PER_PAGE) topic = Topic.objects.get(pk=topic_id) forums = Forum.objects.all() forumid = topic.forum_id return render(request, "cms_forum/...
Python
nomic_cornstack_python_v1
import numpy as np import cv2 set blue = call uint8 list list list 0 0 255 set hsvBlue = call cvtColor blue COLOR_BGR2HSV print hsvBlue set lowerLimit = tuple hsvBlue at 0 at 0 at 0 - 10 100 100 set upperLimit = tuple hsvBlue at 0 at 0 at 0 + 10 255 255 print string upper Limit print upperLimit print string Lower Limit...
import numpy as np import cv2 blue = np.uint8([[[0, 0, 255]]]) hsvBlue = cv2.cvtColor(blue, cv2.COLOR_BGR2HSV) print(hsvBlue) lowerLimit = hsvBlue[0][0][0] - 10, 100, 100 upperLimit = hsvBlue[0][0][0] + 10, 255, 255 print("upper Limit") print(upperLimit) print("Lower Limit") print(lowerLimit)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: import numpy as np import matplotlib.pyplot as plt import os import cv2 from tqdm import tqdm call run_line_magic string matplotlib string inline set DATADIR = string C:/lung ct project/dataset/LUNG set CATEGORIES = list string NORMAL string CANCER comme...
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import matplotlib.pyplot as plt import os import cv2 from tqdm import tqdm get_ipython().run_line_magic('matplotlib', 'inline') DATADIR = "C:/lung ct project/dataset/LUNG" CATEGORIES = ['NORMAL','CANCER'] for category in CATEGORIES: # do dogs and ...
Python
zaydzuhri_stack_edu_python
import csv function extract_test_results file_path begin set test_results = dict with open file_path string r as file begin set reader = reader file set headers = next reader for row in reader begin set test_name = row at index headers string Test Name set result = row at index headers string Result set test_results a...
import csv def extract_test_results(file_path): test_results = {} with open(file_path, 'r') as file: reader = csv.reader(file) headers = next(reader) for row in reader: test_name = row[headers.index("Test Name")] result = row[headers.index("Result")] ...
Python
jtatman_500k
function create_post self category begin pass end function
def create_post(self, category): pass
Python
nomic_cornstack_python_v1
function deallocateAllFlags self pluginName begin pass end function
def deallocateAllFlags(self, pluginName): pass
Python
nomic_cornstack_python_v1
import xlrd , sqlite3 comment 创建数据库( flora_name.db )并建立( ) function create_db begin set conn = call connect string flora_name.db print string Opened database successfully execute conn string CREATE TABLE FLORA_NAME (id INTEGER PRIMARY KEY,CPNI_CODE TEXT,FAMILY_LATIN_NAME TEXT,FAMILY_ZN_NAME TEXT,GENUS_NAME TEXT,GENUS_Z...
import xlrd,sqlite3 # 创建数据库( flora_name.db )并建立( ) def create_db(): conn = sqlite3.connect('flora_name.db') print("Opened database successfully") conn.execute("""CREATE TABLE FLORA_NAME (id INTEGER PRIMARY KEY,CPNI_CODE TEXT,FAMILY_LATIN_NAME TEXT,FAMILY_ZN_NAME TEXT,GENUS_NAME TEXT,GENUS_ZH_NAME TEXT,SP...
Python
zaydzuhri_stack_edu_python
from exceptions.CLI_Audio_Exception import CLI_Audio_File_Exception import os string Library class. Used to get song information from a given directory, and display information in a curses window, which is done through the FrontEnd. class Library begin string Constructor for the class. pageLength determines how long ea...
from exceptions.CLI_Audio_Exception import CLI_Audio_File_Exception import os """ Library class. Used to get song information from a given directory, and display information in a curses window, which is done through the FrontEnd. """ class Library: """ Constructor for the class. pageLength determines how long...
Python
zaydzuhri_stack_edu_python
function ssa_scan_tm_yaw tm_yaw_pos_list ssa_motor ssa_start ssa_end ssa_steps begin set txt1 = string ssa_scan_tm_yaw(tm_yaw_pos_list=tm_yaw_pos_list, ssa_motor= { name } , ssa_start= { ssa - start } , ssa_end= { ssa_end } , ssa_steps= { ssa_steps } ) set txt2 = string tm_yaw_pos_list = { tm_yaw_pos_list } set txt = s...
def ssa_scan_tm_yaw(tm_yaw_pos_list, ssa_motor, ssa_start, ssa_end, ssa_steps): txt1 = f"ssa_scan_tm_yaw(tm_yaw_pos_list=tm_yaw_pos_list, ssa_motor={ssa_motor.name}, ssa_start={ssa-start}, ssa_end={ssa_end}, ssa_steps={ssa_steps})" txt2 = f"tm_yaw_pos_list = {tm_yaw_pos_list}" txt = "## " + txt1 + "\n" + tx...
Python
nomic_cornstack_python_v1
function Gosper_Glider_Gun self begin set shift_down = 60 set shift_right = 140 call manual_update tuple 31 + shift_right 412 + shift_down call manual_update tuple 55 + shift_right 411 + shift_down call manual_update tuple 56 + shift_right 431 + shift_down call manual_update tuple 33 + shift_right 432 + shift_down call...
def Gosper_Glider_Gun(self): shift_down = 60 shift_right = 140 self.grid.manual_update((31 + shift_right, 412 + shift_down)) self.grid.manual_update((55 + shift_right, 411 + shift_down)) self.grid.manual_update((56 + shift_right, 431 + shift_down)) self.grid.manual_update...
Python
nomic_cornstack_python_v1
function solution n lost reserve begin set answer = 0 set clothes = dict for i in range 1 n + 1 begin set clothes at i = 1 end for j in range 1 n + 1 begin if j in reserve begin set clothes at j = clothes at j + 1 end if j in lost begin set clothes at j = clothes at j - 1 end end for m in range 1 n + 1 begin if clothe...
def solution(n, lost, reserve): answer = 0 clothes = {} for i in range(1,n+1): clothes[i] = 1 for j in range(1,n+1): if j in reserve: clothes[j] += 1 if j in lost: clothes[j] -= 1 for m in range(1, n+1): if clothes[m] == 0: if m-1 >...
Python
zaydzuhri_stack_edu_python
import requests from bs4 import BeautifulSoup import re import sys insert path 0 string C:\Users\user\github\FootballAnalysis\Database import InsertTBL from datetime import datetime function NationalityDB PlayerID Nationality begin set sql = string INSERT INTO NationalityTBL(PlayerID, Nationality) VALUES(?,?) set val =...
import requests from bs4 import BeautifulSoup import re import sys sys.path.insert(0, r"C:\Users\user\github\FootballAnalysis\Database") import InsertTBL from datetime import datetime def NationalityDB(PlayerID, Nationality): sql = '''INSERT INTO NationalityTBL(PlayerID, Nationality) VALUES(?,?)''...
Python
zaydzuhri_stack_edu_python
function role_changed self user old_role new_role stanza begin pass end function
def role_changed(self,user,old_role,new_role,stanza): pass
Python
nomic_cornstack_python_v1
comment noqa: E501 # noqa: E501 function __init__ self for_default=none div_phi_velocity=none div_phi_kinetic_energy=none div_phi_enthalpy=none div_phi_internal_energy=none div_phiv_pressure=none div_phi_turbulent_kinetic_energy=none div_nu_eff_dev_t_grad_velocity=none div_mu_eff_dev2_t_grad_velocity=none div_phi_omega...
def __init__(self, for_default=None, div_phi_velocity=None, div_phi_kinetic_energy=None, div_phi_enthalpy=None, div_phi_internal_energy=None, div_phiv_pressure=None, div_phi_turbulent_kinetic_energy=None, div_nu_eff_dev_t_grad_velocity=None, div_mu_eff_dev2_t_grad_velocity=None, div_phi_omega_dissipation_rate=None, div...
Python
nomic_cornstack_python_v1
function _zlambda_calc_pz self z_lambda wtvals maxrad maxmag slow=false begin set minlike = call _bracket_fn z_lambda comment 4 sigma set _zlambda_targval = minlike + 16 if not slow begin comment Fast mode comment for speed, just do one direction set z_lambda_hi = call minimize_scalar _delta_bracket_fn bracket=tuple z_...
def _zlambda_calc_pz(self, z_lambda, wtvals, maxrad, maxmag, slow=False): minlike = self._bracket_fn(z_lambda) # 4 sigma self._zlambda_targval=minlike+16 if not slow: # Fast mode # for speed, just do one direction z_lambda_hi = scipy.optimize.minimize...
Python
nomic_cornstack_python_v1
while a begin comment n = gcd(a,b)=b set tuple a b = tuple max a b % min a b min a b end comment result = a/gcd(a,b) * b/gcd(a,b) = a*b / gcd(a,b)**2 print c / b ^ 2
while a: a,b = max(a,b) % min(a,b), min(a,b) # n = gcd(a,b)=b print(c/b**2) # result = a/gcd(a,b) * b/gcd(a,b) = a*b / gcd(a,b)**2
Python
zaydzuhri_stack_edu_python
import tkinter as tk from _ast import Lambda import requests set HEIGHT = 500 set WIDTH = 600 set root = call Tk set canvas = call Canvas root height=HEIGHT width=WIDTH call pack comment e56c9986ec6c3c2f9a29b663d2035073 comment api.openweathermap.org/data/2.5/forecast?q={city name},{state code}&appid={your api key} fun...
import tkinter as tk from _ast import Lambda import requests HEIGHT = 500 WIDTH = 600 root = tk.Tk() canvas = tk.Canvas(root, height=HEIGHT, width = WIDTH) canvas.pack() #e56c9986ec6c3c2f9a29b663d2035073 #api.openweathermap.org/data/2.5/forecast?q={city name},{state code}&appid={your api key} def format_response(...
Python
zaydzuhri_stack_edu_python
import click import peewee decorator call command string remove decorator call option string --instructor is_flag=true help=string Is this person a TA or instructor (vs a student)? decorator call argument string user_id type=int nargs=- 1 required=true decorator pass_obj function cli db user_id instructor begin string ...
import click import peewee @click.command('remove') @click.option('--instructor', is_flag=True, help='Is this person a TA or instructor (vs a student)?') @click.argument('user_id', type=int, nargs=-1, required=True) @click.pass_obj def cli(db, user_id, instructor): """Remove a student or instructor/...
Python
zaydzuhri_stack_edu_python
function _create cls model_class *args **kwargs begin for k in keys kwargs begin if k in call relationships begin set rel_key = format string {}_id k set kwargs at rel_key = string id end end set obj = call _create model_class *args keyword kwargs save obj return obj end function
def _create(cls, model_class, *args, **kwargs): for k in kwargs.keys(): if k in model_class.relationships(): rel_key = '{}_id'.format(k) kwargs[rel_key] = str(kwargs[k].id) obj = super(BaseFactory, cls)._create(model_class, *args, **kwargs) obj.save(ob...
Python
nomic_cornstack_python_v1
import sys from euler_util import fibonacci function main begin set i = 0 while length string call fibonacci i < 1000 begin set i = i + 1 end print i - 1 return 0 end function if __name__ == string __main__ begin exit call main end
import sys from euler_util import fibonacci def main(): i = 0 while len(str(fibonacci(i))) < 1000: i += 1 print(i - 1) return 0 if __name__ == "__main__": sys.exit(main())
Python
zaydzuhri_stack_edu_python
from pymongo import MongoClient import pickle import pandas as pd from configparser import ConfigParser import src.data.aws_ec2_functions as aws from collections import defaultdict set config = config parser read config string config.ini comment Make sure AWS Ec2 Instance is running and get public IP address set instan...
from pymongo import MongoClient import pickle import pandas as pd from configparser import ConfigParser import src.data.aws_ec2_functions as aws from collections import defaultdict config = ConfigParser() config.read('config.ini') # Make sure AWS Ec2 Instance is running and get public IP address instance = aws.fetch_...
Python
zaydzuhri_stack_edu_python
import pygame from uos import UOS class Carrot begin set image = none decorator classmethod function create_image cls begin set h = call get_height - 3 set w = call width string set image = call Surface tuple w h set image = call convert_alpha call fill color end function function __init__ self carrot=none begin if ima...
import pygame from ..uos import UOS class Carrot: image = None @classmethod def create_image(cls): h = UOS.text.font.get_height() - 3 w = UOS.text.width(' ') cls.image = pygame.Surface((w, h)) cls.image = cls.image.convert_alpha() cls.image.fill(UOS.color.color) ...
Python
zaydzuhri_stack_edu_python
function __eq__ self other begin return __name == __name end function
def __eq__(self, other): return self.__name == other.__name
Python
nomic_cornstack_python_v1
function _pinned begin set result = if expression call this_thread_is_pinned then string pinned else string not pinned return call HttpResponse result content_type=string text/plain end function
def _pinned(): result = "pinned" if this_thread_is_pinned() else "not pinned" return HttpResponse(result, content_type="text/plain")
Python
nomic_cornstack_python_v1
function sort_events self begin call MIDI_Sort id end function
def sort_events(self): RPR.MIDI_Sort(self.id)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment # 1.จงเขียนโปรแกรม คำนวณอายุ โดยให้ผู้ใช้งานป้อนข้อมูลปีเกิดผ่านทางคีย์บอร์ด กำหนดให้ภายในโปรแกรม ต้องมีการใช้ฟังก์ชันแปลงชนิดข้อมูลก่อนนำไปคำนวณ comment In[1]: set a = 2562 set b = call flot input set c = call flot a - b set d = print c comment # 2.จงเขียนโปรแ...
#!/usr/bin/env python # coding: utf-8 # # 1.จงเขียนโปรแกรม คำนวณอายุ โดยให้ผู้ใช้งานป้อนข้อมูลปีเกิดผ่านทางคีย์บอร์ด กำหนดให้ภายในโปรแกรม ต้องมีการใช้ฟังก์ชันแปลงชนิดข้อมูลก่อนนำไปคำนวณ # In[1]: a=2562 b=flot(input) c=flot(a-b) d=print(c) # # 2.จงเขียนโปรแกรมคำนวณการซื้อสินค้า 3อย่าง โดยรับราคาสินค้าจากผู้ใช้ผ่าน...
Python
zaydzuhri_stack_edu_python
function predict_labels self x decode=string posterior begin assert decode in decode msg format string decode `{}` is not valid decode if decode is string posterior begin return call posterior_decode x end if decode is string viterbi begin return call viterbi_decode x end end function
def predict_labels(self, x: list, decode="posterior"): assert decode in self.decode, "decode `{}` is not valid".format(decode) if decode is 'posterior': return self.posterior_decode(x) if decode is 'viterbi': return self.viterbi_decode(x)
Python
nomic_cornstack_python_v1
function add_import self qname package exists=false begin set alias = none set name = call local_name qname if exists begin set module = split package string . at - 1 set alias = string { module } : { name } set aliases at qname = alias end append imports call Import name=name source=package alias=alias end function
def add_import(self, qname: str, package: str, exists: bool = False): alias = None name = local_name(qname) if exists: module = package.split(".")[-1] alias = f"{module}:{name}" self.aliases[qname] = alias self.imports.append(Import(name=name, source=...
Python
nomic_cornstack_python_v1
function verify_ip ip_addr begin set result = false try begin debug string Validating IP '%s' is properly formatted and within allowed networks. ip_addr comment Strict is set to false to allow host address checks set version = version set global_nets = if expression version == 4 then IPV4_ALLOWED else IPV6_ALLOWED comm...
def verify_ip(ip_addr): result = False try: log.debug( "Validating IP '%s' is properly formatted and within allowed " "networks.", ip_addr ) # Strict is set to false to allow host address checks version = ip_network(ip_addr, strict=False).v...
Python
nomic_cornstack_python_v1
function generate_presigned_url ClientMethod=none Params=none ExpiresIn=none HttpMethod=none begin pass end function
def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None, HttpMethod=None): pass
Python
nomic_cornstack_python_v1
function installable self begin return false end function
def installable(self): return False
Python
nomic_cornstack_python_v1
import config import datetime from geopy.geocoders import Nominatim import tweepy function unique list1 begin set list_set = set list1 set unique_list = list list_set return unique_list end function function countries handle begin try begin set userHandle = handle set auth = call OAuthHandler consumer_key consumer_secr...
import config import datetime from geopy.geocoders import Nominatim import tweepy def unique(list1): list_set = set(list1) unique_list = (list(list_set)) return unique_list def countries(handle): try: userHandle = handle auth = tweepy.OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_acc...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python string This script runs the autoTestingScript_lag.py script with differing amounts of lag Differing amounts of lag are between 40 and 640, step starts at 80 then doubles each run until hitting 640 import subprocess import time import sys import winsound comment Script Process comment Holds proc...
#!/usr/bin/python ''' This script runs the autoTestingScript_lag.py script with differing amounts of lag Differing amounts of lag are between 40 and 640, step starts at 80 then doubles each run until hitting 640 ''' import subprocess import time import sys import winsound # Script Process script = None # Holds ...
Python
zaydzuhri_stack_edu_python
function close self begin pass end function
def close(self): pass
Python
nomic_cornstack_python_v1
string (1) Problem https://practice.geeksforgeeks.org/problems/non-repeating-character/0 (2) Example string: lhello answe: h (3) Idea 1. count characters 2. and then loop through the string and print the first charcter which has count 1 string complete the function non_repeat() return the first non repeating character ...
""" (1) Problem https://practice.geeksforgeeks.org/problems/non-repeating-character/0 (2) Example string: lhello answe: h (3) Idea 1. count characters 2. and then loop through the string and print the first charcter which has count 1 """ """ complete the function non_repeat() return the first...
Python
zaydzuhri_stack_edu_python
from flask_api import FlaskAPI from config.env import app_env from app.utils.slackhelper import SlackHelper from flask import request , jsonify from app.actions import Actions from re import match function create_app config_name begin set app = call FlaskAPI __name__ instance_relative_config=false call from_object app_...
from flask_api import FlaskAPI from config.env import app_env from app.utils.slackhelper import SlackHelper from flask import request, jsonify from app.actions import Actions from re import match def create_app(config_name): app = FlaskAPI(__name__, instance_relative_config = False) app.config.from_object(app_...
Python
zaydzuhri_stack_edu_python
import time function sleeper begin while true begin set num = input string please enter how long to wait: -> try begin set num = decimal num end except any begin print string please enter in a number. continue end print format string Before: {} call ctime sleep num print format string After: {} call ctime end end funct...
import time def sleeper(): while True: num = input("please enter how long to wait: -> ") try: num = float(num) except: print("please enter in a number. \n") continue print('Before: {}'.format( time.ctime())) time.sleep(num) print(...
Python
zaydzuhri_stack_edu_python
import os print get current directory print list directory print list directory string C:\Users\150987\Documents\Workspace import shutil comment shutil.move('practice.txt','C:\\Users\\150987\\Documents') comment Deletes the file permanently! comment os.unlink('C:\\Users\\150987\\Documents\\example.txt') comment Deletes...
import os print(os.getcwd()) print(os.listdir()) print(os.listdir('C:\\Users\\150987\\Documents\\Workspace')) import shutil # shutil.move('practice.txt','C:\\Users\\150987\\Documents') # Deletes the file permanently! # os.unlink('C:\\Users\\150987\\Documents\\example.txt') # Deletes an entire folder permanently! #...
Python
zaydzuhri_stack_edu_python
function __file__ self begin return __file__ end function
def __file__(self): return __file__
Python
nomic_cornstack_python_v1
function write_html_to_file all_html output_file begin with open output_file string w as openedfile begin write openedfile all_html end end function
def write_html_to_file(all_html, output_file): with open(output_file, 'w') as openedfile: openedfile.write(all_html)
Python
nomic_cornstack_python_v1
function build_dataset_manual_annot df dest_path begin set f = open dest_path string w set data = string for tuple idx row in call iterrows begin set comment = row at string comments_processed set data = data + comment + string end write f data end function
def build_dataset_manual_annot(df, dest_path): f = open(dest_path, 'w') data = '' for idx, row in df.iterrows(): comment = row['comments_processed'] data += comment + '\n' f.write(data)
Python
nomic_cornstack_python_v1
function test_add_tag_none_dict begin set r = call full 2 false set single_cube = call DagmcFile test_env at string single_cube set single_cube_query = call DagmcQuery single_cube set tag_eh = call add_tag string test_tag MB_TYPE_INTEGER try begin comment try to get tag by expected name set tag_out = call tag_get_handl...
def test_add_tag_none_dict(): r = np.full(2, False) single_cube = df.DagmcFile(test_env['single_cube']) single_cube_query = dq.DagmcQuery(single_cube) tag_eh = single_cube_query.add_tag('test_tag', types.MB_TYPE_INTEGER) try: # try to get tag by expected name tag_out = single_cube._m...
Python
nomic_cornstack_python_v1
function select1_hook tag keywords begin set prev = v set current = v set now = call get_timestamp_now set u at string str_atime = now if prev is none begin return end if call isDirty begin if has attribute prev string prev_body begin if b != prev_body begin set u at string str_mtime = now set prev_body = b end end els...
def select1_hook(tag, keywords): prev = keywords['old_p'].v current = keywords['new_p'].v now = get_timestamp_now() current.u['str_atime'] = now if prev is None: return if prev.isDirty(): if hasattr(prev, 'prev_body'): if prev.b != prev.prev_body: pre...
Python
nomic_cornstack_python_v1
from config import db , uuid4_for_str class Comment extends Model begin set __tablename__ = string comments set id = call Column call String 36 primary_key=true default=uuid4_for_str set user_id = call Column call String 255 call ForeignKey string users.id set room_id = call Column call String 36 call ForeignKey string...
from .config import db, uuid4_for_str class Comment(db.Model): __tablename__ = 'comments' id = db.Column(db.String(36), primary_key=True, default=uuid4_for_str) user_id = db.Column(db.String(255), db.ForeignKey('users.id')) room_id = db.Column(db.String(36), db.ForeignKey('rooms.id')) content = d...
Python
zaydzuhri_stack_edu_python
import sys set t = integer argv at 1 set P = integer argv at 2 set r = integer argv at 3 import math print string the value is P * power e r * t
import sys t=int(sys.argv[1]) P=int(sys.argv[2]) r=int(sys.argv[3]) import math print('the value is', P*math.pow(math.e,r*t))
Python
zaydzuhri_stack_edu_python
comment description: This server program will handle the request sent from client, comment and call the corresponding function of the input choice sent, comment after it get the returned value from the corresponding function, comment it sends the returned value back to client. comment The server program will use multit...
# description: This server program will handle the request sent from client, # and call the corresponding function of the input choice sent, # after it get the returned value from the corresponding function, # it sends the returned value back to client. # The server...
Python
zaydzuhri_stack_edu_python
from enum import Enum from collections import OrderedDict from itertools import chain , cycle , product import random import uuid string Player State tracked with OrderedDict <- this also describes turn info round of betting? dealer whose turn is it? comment order of play: comment the gamebot is tracking no games and t...
from enum import Enum from collections import OrderedDict from itertools import chain, cycle, product import random import uuid """ Player State tracked with OrderedDict <- this also describes turn info round of betting? dealer whose turn is it? """ ##order of play: ##the gamebot is tracking no games and tracking no ...
Python
zaydzuhri_stack_edu_python
function build_input_data sentences labels vocabulary begin set x = array list comprehension list comprehension vocabulary at word for word in sentence for sentence in sentences set y = array labels return list x y end function
def build_input_data(sentences, labels, vocabulary): x = np.array([[vocabulary[word] for word in sentence] for sentence in sentences]) y = np.array(labels) return [x, y]
Python
nomic_cornstack_python_v1
comment COMP90024 Assignment 2 comment Team: 48 comment City: Melbourne comment Members: Wenqi Sun(928630), Yunlu Wen(869338), Fei Zhou(972547) comment Pei-Yun Sun(667816), Yiming Zhang(889262) import json import argparse from db import TweetStore import os import subprocess import sys comment json files set JSON_PATH ...
# COMP90024 Assignment 2 # Team: 48 # City: Melbourne # Members: Wenqi Sun(928630), Yunlu Wen(869338), Fei Zhou(972547) # Pei-Yun Sun(667816), Yiming Zhang(889262) import json import argparse from db import TweetStore import os import subprocess import sys # json files JSON_PATH = "json_files/" DATA_PATH = "/mnt/twi...
Python
zaydzuhri_stack_edu_python
import datetime import random from django.core.management import BaseCommand from Services.models import Project , ProjectSkill , Skill class Command extends BaseCommand begin set help = string Add a project function handle self *args **options begin print format string available projects: {} count all print string cre...
import datetime import random from django.core.management import BaseCommand from Services.models import Project, ProjectSkill, Skill class Command(BaseCommand): help = "Add a project" def handle(self, *args, **options): print("available projects: {}".format(Project.objects.all().count())) ...
Python
zaydzuhri_stack_edu_python
function total_sent self total_sent begin set _total_sent = total_sent end function
def total_sent(self, total_sent): self._total_sent = total_sent
Python
nomic_cornstack_python_v1
comment Fib Series using recurssion set fib_series = list comment Prints the nth term function fib x begin string assumes x an int >= 0 returns Fibonacci of x if x == 0 or x == 1 begin return 1 end else begin return call fib x - 1 + call fib x - 2 end end function comment Calls the function set x = integer input strin...
# Fib Series using recurssion fib_series = [] # Prints the nth term def fib(x): """assumes x an int >= 0 returns Fibonacci of x""" if x == 0 or x == 1: return 1 else: return fib(x-1) + fib(x-2) # Calls the function x = int(input("Please enter a number \n")) fib(x) # Prints al...
Python
zaydzuhri_stack_edu_python
import csv import math import decimal as dec import scipy.stats comment Modify Parameters Here ######### comment file parameter set exact_dir_path = string Exact_Result_Directory/ set est_dir_path = string Estimation_Result_Directory/ set mode = string sec set time_interval = string 30s set pcap = list string trace_1.p...
import csv import math import decimal as dec import scipy.stats ######### Modify Parameters Here ######### # file parameter exact_dir_path = 'Exact_Result_Directory/' est_dir_path = 'Estimation_Result_Directory/' mode = 'sec' time_interval = '30s' pcap = ['trace_1.pcap'] # statistic parameter output_file_name = 'Outp...
Python
zaydzuhri_stack_edu_python
function color_select color offset_y=1 begin comment Draw the edge box set section_width = 11 set box_height = 3 set box_top = string ╭ + join string ┬ list string ─ * section_width * 4 + string ╮ set box_mid = string │ + join string │ list string * section_width * 4 + string │ set box_bot = string ╰ + join string ┴ l...
def color_select(color: Color, offset_y=1): # Draw the edge box section_width = 11 box_height = 3 box_top = "╭" + "┬".join(["─" * section_width] * 4) + "╮" box_mid = "│" + "│".join([" " * section_width] * 4) + "│" box_bot = "╰" + "┴".join(["─" * section_width] * 4) + "╯" draw( TRANS...
Python
nomic_cornstack_python_v1
function put request obj_id begin string Updates the content of a comment :param obj_id: ID of comment object :type obj_id: int :returns: json set res = call Result set c = get objects pk=obj_id set data = PUT or loads body at string body set content = get data string comment none if content begin set comment = content...
def put(request, obj_id): """Updates the content of a comment :param obj_id: ID of comment object :type obj_id: int :returns: json """ res = Result() c = Comment.objects.get(pk=obj_id) data = request.PUT or json.loads(request.body)['body'] content = data.get('comment', None) if c...
Python
jtatman_500k
function selection_sort_min_version arr begin comment No need to sort if arr is none begin return arr end set n = length arr if n <= 1 begin return arr end comment i - range in order comment j - range out of order for i in range 0 n begin set min_index = i set j = i + 1 comment select min element in range[j, n) while j...
def selection_sort_min_version(arr): # No need to sort if arr is None: return arr n = len(arr) if n <= 1: return arr # i - range in order # j - range out of order for i in range(0, n): min_index = i j = i + 1 ...
Python
nomic_cornstack_python_v1
function get_wlst_flattened_folder_info_for_location self location begin set _method_name = string get_wlst_flattened_folder_info_for_location call entering call to_string location class_name=_class_name method_name=_method_name set result = none set folder_dict = call __get_dictionary_for_location location false set f...
def get_wlst_flattened_folder_info_for_location(self, location): _method_name = 'get_wlst_flattened_folder_info_for_location' _logger.entering(str_helper.to_string(location), class_name=_class_name, method_name=_method_name) result = None folder_dict = self.__get_dictionary_for_locatio...
Python
nomic_cornstack_python_v1
comment 列表 comment 3-1 将一些朋友的姓名存储在一个列表中,并将其命名为names 。依次访问该列表中的每个元素,从而将每个朋友的姓名都打印出来。 set name = list string 孙俊 string 计俊涛 string 董鹏 string 赵权 print name at 0 + string , + string 你好! print name at 1 + string , + string 你好! print name at 2 + string , + string 你好! print name at 3 + string , + string 你好! comment 3-3 想想你喜欢的通...
# 列表 # 3-1 将一些朋友的姓名存储在一个列表中,并将其命名为names 。依次访问该列表中的每个元素,从而将每个朋友的姓名都打印出来。 name = ['孙俊','计俊涛','董鹏','赵权'] print(name[0] + ',' + '你好!') print(name[1] + ',' + '你好!') print(name[2] + ',' + '你好!') print(name[3] + ',' + '你好!') # 3-3 想想你喜欢的通勤方式,如骑摩托车或开汽车,并创建一个包含多种通勤方式的列表。 car = ['bick','bus','plane','moto',] print('I would li...
Python
zaydzuhri_stack_edu_python
function writer_wrapper writer *args **kwargs begin global threads_running threads_running_max set threads_running = threads_running + 1 set threads_running_max = max threads_running_max threads_running info string staring new thread %s (%s running) call getName threads_running writer *args keyword kwargs set threads_r...
def writer_wrapper(writer, *args, **kwargs): global threads_running, threads_running_max threads_running += 1 threads_running_max = max(threads_running_max, threads_running) logging.info("staring new thread %s (%s running)", threading.current_thread().getName(), threads_running) writer(*args, **k...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 #标准注释,保证.py文件可在unix系统上运行 comment -*- coding: utf-8 -*- #标准注释,表示.py文件都用标准UTF-8编码 comment 'a test module' # 模块的文档注释,任何模块代码的第一个字符串都被视为模块的文档注释 import os print string current directory is : get current directory set path = absolute path path __file__ print string full path of current file is : ...
#!/usr/bin/env python3 #标准注释,保证.py文件可在unix系统上运行 # -*- coding: utf-8 -*- #标准注释,表示.py文件都用标准UTF-8编码 # 'a test module' # 模块的文档注释,任何模块代码的第一个字符串都被视为模块的文档注释 import os print('current directory is : ',os.getcwd()) path = os.path.abspath(__file__) print('full p...
Python
zaydzuhri_stack_edu_python
function rpcexec self payload begin debug dumps payload set query = post url json=payload proxies=call proxies comment pragma: no cover if status_code != 200 begin raise call HttpInvalidStatusCode format string Status code returned: {} status_code end return text end function
def rpcexec(self, payload): log.debug(json.dumps(payload)) query = requests.post(self.url, json=payload, proxies=self.proxies()) if query.status_code != 200: # pragma: no cover raise HttpInvalidStatusCode( "Status code returned: {}".format(query.status_code) ...
Python
nomic_cornstack_python_v1
function get_day_of_week date begin set tuple year month day = map int split date string - if month <= 2 begin set month = month + 12 set year = year - 1 end set q = day set m = month set K = year % 100 set J = year // 100 set h = q + 13 * m + 1 // 5 + K + K // 4 + J // 4 - 2 * J % 7 set days_of_week = list string Satu...
def get_day_of_week(date): year, month, day = map(int, date.split("-")) if month <= 2: month += 12 year -= 1 q = day m = month K = year % 100 J = year // 100 h = (q + (13*(m+1)//5) + K + (K//4) + (J//4) - 2*J) % 7 days_of_week = ["Saturday", "Sunday", "Monday", "Tuesd...
Python
jtatman_500k
function select_word begin return words at call randrange length words end function
def select_word(): return words[randrange(len(words))]
Python
nomic_cornstack_python_v1
function get6 begin with open string data6 string r as f begin set lines = read lines f set data = list for l in lines begin set p = split l append data dict string height integer p at 0 ; string weight integer p at 1 end end return data end function function get10 begin with open string data10 string r as f begin set...
def get6(): with open("data6","r") as f: lines=f.readlines() data=[] for l in lines: p=l.split() data.append({"height":int(p[0]),"weight":int(p[1])}) return data def get10(): with open("data10","r")as f: lines=f.readlines() data=[] for...
Python
zaydzuhri_stack_edu_python
comment https://www.spoj.com/problems/GSS1/ comment https://www.geeksforgeeks.org/maximum-subarray-sum-given-range/ from collections import defaultdict class Node begin function __init__ self begin comment setting up values to negative infinity set max_subarray_sum = - 10 ^ 7 set max_prefix_sum = - 10 ^ 7 set max_suffi...
#https://www.spoj.com/problems/GSS1/ #https://www.geeksforgeeks.org/maximum-subarray-sum-given-range/ from collections import defaultdict class Node: def __init__(self): #setting up values to negative infinity self.max_subarray_sum=-10**7 self.max_prefix_sum=-10**7 self.max_suffix_sum=-10**7 self.total_su...
Python
zaydzuhri_stack_edu_python
function test_delete_nonexistent_user_results_in_404 self begin set params = params set params at string user-name = string no-such-user-is-here-on-server-go-away set tuple response body = call request params set err = get response string x-booster-error string assert equal status 404 assert true find err string does n...
def test_delete_nonexistent_user_results_in_404(self): params = self.params params['user-name'] = "no-such-user-is-here-on-server-go-away" response, body = self.booster.request(params) err = response.get("x-booster-error", "") self.assertEqual(response.status, 404) self.a...
Python
nomic_cornstack_python_v1
import numpy as np from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from hyperopt import fmin , tpe , space_eval , STATUS_OK , Trials from lightgbm import LGBMClassifier class HyperparametersTuner begin function __init__ self fixed_hyperparameters search_space max_evaluatio...
import numpy as np from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from hyperopt import fmin, tpe, space_eval, STATUS_OK, Trials from lightgbm import LGBMClassifier class HyperparametersTuner: def __init__(self, fixed_hyperparameters, search_space, max_evaluations): ...
Python
zaydzuhri_stack_edu_python
function policy_title self begin return get properties string PolicyTitle none end function
def policy_title(self): return self.properties.get("PolicyTitle", None)
Python
nomic_cornstack_python_v1
function diff a1 a2 begin set total = a1 - a2 print string difference total return total end function set total = diff 30 10 print string out total
def diff(a1,a2): total=a1-a2 print("difference",total) return total total=diff(30,10) print("out",total)
Python
zaydzuhri_stack_edu_python
function remove_duplicates array begin set unique_array = list for num in array begin if num not in unique_array begin append unique_array num end end return unique_array end function function remove_duplicates array begin set unique_array = list set unique_set = set for num in array begin if num not in unique_set be...
def remove_duplicates(array): unique_array = [] for num in array: if num not in unique_array: unique_array.append(num) return unique_array def remove_duplicates(array): unique_array = [] unique_set = set() for num in array: if num not in unique_set: uniq...
Python
jtatman_500k
import os import time for i in range 10 begin call system string make sleep 1 end
import os import time for i in range(10): os.system("make") time.sleep(1)
Python
zaydzuhri_stack_edu_python
function get_fruits items begin set fruits = list set fruit_names = list string apple string banana string grapes for item in items begin if lower item in fruit_names begin append fruits item end end return fruits end function
def get_fruits(items): fruits = [] fruit_names = ["apple", "banana", "grapes"] for item in items: if item.lower() in fruit_names: fruits.append(item) return fruits
Python
jtatman_500k
function mostrar_pasos y begin set contador = 0 while y != 1 begin if y % 2 == 0 begin set y = y / 2 end else begin set y = y * 3 + 1 end set contador = contador + 1 print contador string y end end function function contar_pasos y begin return end function
def mostrar_pasos(y:int): contador=0 while y!=1: if y%2==0: y=y/2 else: y=y*3+1 contador=contador+1 print(contador,' ',y) def contar_pasos(y:int): return
Python
zaydzuhri_stack_edu_python
function start self begin set is_killswitch_on = true start navigation end function
def start(self): self.is_killswitch_on = True self.navigation.start()
Python
nomic_cornstack_python_v1
function do_setup self context begin call connect self context end function
def do_setup(self, context): self.plugin.connect(self, context)
Python
nomic_cornstack_python_v1
function verbs self word=string begin set cond1 = call alphabet word set cond2 = length word >= 6 set cond3 = word at slice - 1 : : in bar_letters return cond1 and cond2 and cond3 end function
def verbs(self, word: str = "") -> bool: cond1 = self.alphabet(word) cond2 = len(word) >= 6 cond3 = word[-1:] in self.bar_letters return cond1 and cond2 and cond3
Python
nomic_cornstack_python_v1
comment tuple with on element comment t=2 set t = tuple 2 print type t comment tuple unpacking set t4 = tuple 2 4 string hai 5 set tuple a b c d = t4 print a print b print c print d
#tuple with on element t=2, #t=2 print(type(t)) #tuple unpacking t4=2,4,'hai',5 a,b,c,d=t4 print(a) print(b) print(c) print(d)
Python
zaydzuhri_stack_edu_python
function solve begin set tuple N M = map int split input set S = list input at slice : : - 1 set ans_l = list set i = 0 while i < N begin for j in range M 0 - 1 begin if i + j > N begin continue end if integer S at i + j == 0 begin append ans_l j set i = i + j break end if j == 1 begin print - 1 exit end end end set...
def solve(): N, M = map(int, input().split()) S = list(input())[::-1] ans_l = [] i = 0 while i < N: for j in range(M, 0, -1): if i + j > N: continue if int(S[i+j]) == 0: ans_l.append(j) i += j break ...
Python
zaydzuhri_stack_edu_python
import sys insert path 0 string ../ from BST import BST from unittest import TestCase class TestBST extends TestCase begin function setUp self begin set list1 = list 3 2 1 5 6 7 comment Creating the BST1 set BST1 = call BST dtype=int key=4 for val in list1 begin set BST1 = insert BST1 val end end function function test...
import sys sys.path.insert(0, '../') from BST import BST from unittest import TestCase class TestBST(TestCase): def setUp(self): self.list1 = [3, 2, 1, 5, 6, 7] # Creating the BST1 self.BST1 = BST(dtype=int, key=4) for val in self.list1: self.BST1 = self.BST1.inser...
Python
zaydzuhri_stack_edu_python
comment https://adventofcode.com/2020/day/12 comment Action N means to move north by the given value. comment Action S means to move south by the given value. comment Action E means to move east by the given value. comment Action W means to move west by the given value. comment Action L means to turn left the given num...
# https://adventofcode.com/2020/day/12 # Action N means to move north by the given value. # Action S means to move south by the given value. # Action E means to move east by the given value. # Action W means to move west by the given value. # Action L means to turn left the given number of degrees. # Action R means to...
Python
zaydzuhri_stack_edu_python
function search_element lst element begin comment Check if the list is empty if length lst == 0 begin return - 1 end comment Iterate through the list for i in range length lst begin comment Check if the current element is equal to the target element if lst at i == element begin return i end end comment If the element i...
def search_element(lst, element): # Check if the list is empty if len(lst) == 0: return -1 # Iterate through the list for i in range(len(lst)): # Check if the current element is equal to the target element if lst[i] == element: return i # If the element ...
Python
jtatman_500k
function make_states_map self begin set sparql = string SELECT ?item ?iso WHERE { ?item wdt:P300 ?value . ?item wdt:P17 wd:Q408 . BIND(REPLACE(?value, 'AU-', '', 'i') AS ?iso) } set data = call make_select_wdqs_query sparql string item string iso set states = dictionary for tuple k v in items data begin set states at v...
def make_states_map(self): sparql = ( "SELECT ?item ?iso " "WHERE " "{ " "?item wdt:P300 ?value . " "?item wdt:P17 wd:Q408 . " "BIND(REPLACE(?value, 'AU-', '', 'i') AS ?iso) " "}" ) data = wdqs.make_select_wdqs_q...
Python
nomic_cornstack_python_v1
function check_trial_length data **_ begin comment NaN values are usually ignored so replace them with Inf so they fail the threshold set metric = call nan_to_num data at string feedback_times - data at string goCue_times nan=inf set passed = metric < 60.1 ? metric > 0 assert shape at 0 == length metric == length passe...
def check_trial_length(data, **_): # NaN values are usually ignored so replace them with Inf so they fail the threshold metric = np.nan_to_num(data["feedback_times"] - data["goCue_times"], nan=np.inf) passed = (metric < 60.1) & (metric > 0) assert data["intervals"].shape[0] == len(metric) == len(passed)...
Python
nomic_cornstack_python_v1