code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function rotate_perturbation_point_cloud batch_data angle_sigma=0.06 angle_clip=0.18 begin set rotated_data = zeros shape dtype=float32 for k in call xrange shape at 0 begin set angles = call clip angle_sigma * randn 3 - angle_clip angle_clip set Rx = array list list 1 0 0 list 0 cos angles at 0 - sin angles at 0 list ...
def rotate_perturbation_point_cloud(batch_data, angle_sigma=0.06, angle_clip=0.18): rotated_data = np.zeros(batch_data.shape, dtype=np.float32) for k in xrange(batch_data.shape[0]): angles = np.clip(angle_sigma*np.random.randn(3), -angle_clip, angle_clip) Rx = np.array([[1,0,0], ...
Python
nomic_cornstack_python_v1
function build_config packname version log=call getLogger string build_config begin set cfg = first filter version=version if cfg is not none begin info string Found config in cache. return cfg end info string Packing config into a prepackaged mod set cp = join path MODPACKPATH packname string config set cz = join path...
def build_config(packname, version, log=logging.getLogger("build_config")): cfg = ModCache.objects.all().filter(modInfo__name=packname+"_config").filter(version=version).first() if cfg is not None: log.info("Found config in cache.") return cfg log.info("Packing config into a prepackaged mod"...
Python
nomic_cornstack_python_v1
for i in a begin if i in b begin print i end end
for i in a: if i in b: print(i)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment Regex Substitution comment In[ ]: comment SOLUZIONE VISTA NELLA SEDE DISCUSSION from sys import stdin import re set n = input print sub string (?<= )(&&|\|\|)(?= ) lambda x -> if expression call group == string && then string and else string or read stdin comme...
#!/usr/bin/env python # coding: utf-8 # Regex Substitution # In[ ]: #SOLUZIONE VISTA NELLA SEDE DISCUSSION from sys import stdin import re n = input() print(re.sub( r"(?<= )(&&|\|\|)(?= )", lambda x: "and" if x.group()=="&&" else "or", stdin.read())) # Matrix Script # # In[ ]: #SOLUZIONE VISTA NELLA SEDE DISC...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu May 6 17:50:59 2021 Converts the longest UTR sequences to substrings of length k @author: Mattias Wassbjer set kmers = string comment Loops through both seqences for i in range 2 begin set seq = 3 + i * 2 set readpath = string UTR data/seq + string seq + string /long...
# -*- coding: utf-8 -*- """ Created on Thu May 6 17:50:59 2021 Converts the longest UTR sequences to substrings of length k @author: Mattias Wassbjer """ kmers = "" for i in range(2): # Loops through both seqences seq = 3 + (i*2) readpath = "UTR data/seq" + str(seq) + "/longest/longest_UTRs_seq...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment Recursivelly finds the factorial of a number supplied from command line import sys function fact n begin comment base case if n <= 1 begin return 1 end else begin comment recursive case return n * call fact n - 1 end end function comment input set num = integer argv at 1 comment functio...
#!/usr/bin/python # Recursivelly finds the factorial of a number supplied from command line import sys def fact(n): if n<=1: # base case return 1 else: # recursive case return n * fact(n-1) num=int(sys.argv[1]) # input result= fact(num) # function call
Python
zaydzuhri_stack_edu_python
function _sort_by_coreid cpu begin return tuple integer core integer thread end function
def _sort_by_coreid(cpu): return (int(cpu.core), int(cpu.thread))
Python
nomic_cornstack_python_v1
function exitStatus self code begin comment /* Macros for constructing status values. */ comment #define __W_EXITCODE(ret, sig) ((ret) << 8 | (sig)) set status = code ? 8 ? 0 comment Sanity check assert true call WIFEXITED status assert equal call WEXITSTATUS status code assert false call WIFSIGNALED status return stat...
def exitStatus(self, code): # /* Macros for constructing status values. */ # #define __W_EXITCODE(ret, sig) ((ret) << 8 | (sig)) status = (code << 8) | 0 # Sanity check self.assertTrue(os.WIFEXITED(status)) self.assertEqual(os.WEXITSTATUS(status), code) self.as...
Python
nomic_cornstack_python_v1
function haploid self begin if random integer 0 1 == 0 begin return sequence_A end return sequence_B end function
def haploid(self): if randint(0, 1) == 0: return self.sequence_A return self.sequence_B
Python
nomic_cornstack_python_v1
function Veloc k begin return k / 3.6 end function set k = decimal input string Digite o valor correspondente à medida em km/h: print string %f km/h correspondem a %f m/s. % tuple k call Veloc k
def Veloc(k): return k / 3.6 k = float(input("Digite o valor correspondente à medida em km/h: ")) print("%f km/h correspondem a %f m/s." % (k, Veloc(k)))
Python
zaydzuhri_stack_edu_python
function dump_memory self path begin with open path string wb as file begin for byte in memory begin write file bytes list byte end end info format string Dumped memory into {} path end function
def dump_memory(self, path): with open(path, 'wb') as file: for byte in self.memory: file.write(bytes([byte])) logger.info("Dumped memory into {}".format(path))
Python
nomic_cornstack_python_v1
comment template matching import cv2 import numpy as np comment reading in the image set img_rgb = call imread string Terre.jpg comment converting to grayscale set img_gray = call cvtColor img_rgb COLOR_BGR2GRAY comment reading the template to be matched. set template = call imread string Terre2.jpg 0 set tuple w h = s...
# template matching import cv2 import numpy as np # reading in the image img_rgb = cv2.imread('Terre.jpg') # converting to grayscale img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) # reading the template to be matched. template = cv2.imread('Terre2.jpg', 0) w, h = template.shape[::-1] # threshold option, where...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt comment 用来正常显示中文 set rcParams at string font.sans-serif = list string Arial Unicode MS comment 用来正常显示负号 set rcParams at string axes.unicode_minus = false set labels = tuple string 财经15% string 社会30% string 体育15% string 科技10% string 其它30% set sizes = list 15 30 15 10 30 comment 突出第2项 set ...
import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] # 用来正常显示中文 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 labels = '财经15%', '社会30%', '体育15%', '科技10%', '其它30%' sizes = [15, 30, 15, 10, 30] explode = (0, 0.1, 0, 0, 0) # 突出第2项 fig1, ax1 = plt.subplots() pie = ax1.pie(size...
Python
zaydzuhri_stack_edu_python
comment 1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив, comment заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный comment и отсортированный массивы. Сортировка должна быть реализована в виде функции. comment По возможности доработайте алгоритм (сделайте ег...
# 1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив, # заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный # и отсортированный массивы. Сортировка должна быть реализована в виде функции. # По возможности доработайте алгоритм (сделайте его умнее). import random...
Python
zaydzuhri_stack_edu_python
function test_roundtrip self begin call add_column string max_pitch string maximum pitch for this phoneme. NaN for unvoiced for tuple i p in enumerate string abcdefghijkl begin call add_interval label=p start_time=decimal i stop_time=decimal i + 1 max_pitch=i ^ 2 end call add_interval label=string abc next_tier=list 0 ...
def test_roundtrip(self): phonemes.add_column('max_pitch', 'maximum pitch for this phoneme. NaN for unvoiced') for i, p in enumerate('abcdefghijkl'): phonemes.add_interval(label=p, start_time=float(i), stop_time=float(i + 1), max_pitch=i ** 2) syllables.add_interval(label='abc', n...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python2 from nltk.stem import PorterStemmer from nltk.corpus import stopwords set ps = call PorterStemmer comment pre processing import pandas as pd from pymongo import MongoClient import pprint function _connect_mongo host port username password db begin string A util for making a connection to mongo...
#!/usr/bin/python2 from nltk.stem import PorterStemmer from nltk.corpus import stopwords ps = PorterStemmer() # pre processing import pandas as pd from pymongo import MongoClient import pprint def _connect_mongo(host, port, username, password, db): """ A util for making a connection to mongo """ ...
Python
zaydzuhri_stack_edu_python
import re import numpy as np from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score import matplotlib.pyplot as plt comment 预编译正则表达式,提取数据:省,市,维度,经度 set p = compile string (\w+)\s(\w+)\s北纬(\d+\.?\d+)\s东经(\d+\.?\d+) comment 保存读取的数据 set x = list comment 读取文件 set f = open string cities.txt encodin...
import re import numpy as np from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score import matplotlib.pyplot as plt #预编译正则表达式,提取数据:省,市,维度,经度 p = re.compile(r"(\w+)\s(\w+)\s北纬(\d+\.?\d+)\s东经(\d+\.?\d+)") #保存读取的数据 x = [] #读取文件 f = open("cities.txt",encoding="utf-8") # 逐行读取 l = f.readline() while ...
Python
zaydzuhri_stack_edu_python
function search self chemsys=none energy_above_hull=none equilibrium_reaction_energy=none formation_energy=none formula=none is_stable=none material_ids=none num_elements=none thermo_ids=none thermo_types=none total_energy=none uncorrected_energy=none sort_fields=none num_chunks=none chunk_size=1000 all_fields=true fie...
def search( self, chemsys: str | list[str] | None = None, energy_above_hull: tuple[float, float] | None = None, equilibrium_reaction_energy: tuple[float, float] | None = None, formation_energy: tuple[float, float] | None = None, formula: str | list[str] | None = None, ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Script d'extraction des data Chat (bleu HB & vert BNP) import numpy as np import pandas as pd import xlrd import csv import os import re import nltk from collections import defaultdict set com = list set q1 = list set q2 = list set lmoy = list set l...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Script d'extraction des data Chat (bleu HB & vert BNP) """ import numpy as np import pandas as pd import xlrd import csv import os import re import nltk from collections import defaultdict com=[] q1=[] q2=[] lmoy=[] l=0 fileCompt=0 for root, dirs, file...
Python
zaydzuhri_stack_edu_python
function split_cigar cigar i consumed begin set tuple middle_op middle_length = cigar at i assert consumed <= middle_length if consumed > 0 begin set left = cigar at slice : i : + list tuple middle_op consumed end else begin set left = cigar at slice : i : end if consumed < middle_length begin set right = list tupl...
def split_cigar(cigar, i, consumed): middle_op, middle_length = cigar[i] assert consumed <= middle_length if consumed > 0: left = cigar[:i] + [(middle_op, consumed)] else: left = cigar[:i] if consumed < middle_length: right = [(middle_op, middle_length-consumed)] + cigar[i+1:] else: right = ciga...
Python
nomic_cornstack_python_v1
function simple_interest p r t begin return p * r * t / 100 end function set p = decimal input string enter the principal amount : set r = decimal input string enter the rate of interest : set t = decimal input string enter the time period : set y = call simple_interest p r t print string simple_interest of principal a...
def simple_interest(p,r,t): return p*r*t/100 p=float(input("enter the principal amount :")) r =float(input("enter the rate of interest :")) t=float(input("enter the time period :")) y=simple_interest(p,r,t) print("simple_interest of principal amount :",y)
Python
zaydzuhri_stack_edu_python
function _predictions2text self predictions begin set y = list comprehension if expression ex > 0.5 then string Insult else string Non-insult for ex in predictions return y end function
def _predictions2text(self, predictions): y = ['Insult' if ex > 0.5 else 'Non-insult' for ex in predictions] return y
Python
nomic_cornstack_python_v1
function make_upstream_request self begin string Return request object for calling the upstream set url = call upstream_url uri return call HTTPRequest url method=method headers=headers body=if expression body then body else none end function
def make_upstream_request(self): "Return request object for calling the upstream" url = self.upstream_url(self.request.uri) return tornado.httpclient.HTTPRequest(url, method=self.request.method, headers=self.request.headers, body=self.request.body if self.requ...
Python
jtatman_500k
function getType self begin return type end function
def getType(self): return self.type
Python
nomic_cornstack_python_v1
function test_payment_request_online_banking_with_credit session client jwt app begin set token = call create_jwt call get_claims role=value token_header set headers = dict string Authorization string Bearer { token } ; string content-type string application/json set rv = post string /api/v1/accounts data=dumps call ge...
def test_payment_request_online_banking_with_credit(session, client, jwt, app): token = jwt.create_jwt(get_claims(role=Role.SYSTEM.value), token_header) headers = {'Authorization': f'Bearer {token}', 'content-type': 'application/json'} rv = client.post('/api/v1/accounts', data=json.dum...
Python
nomic_cornstack_python_v1
function n_possibilities self row_zb col_zb begin return sum possible at row_zb at col_zb end function
def n_possibilities(self, row_zb: int, col_zb: int) -> int: return sum(self.possible[row_zb][col_zb])
Python
nomic_cornstack_python_v1
from tkinter import * from blinker import signal class PartInfoFrame extends Frame begin function __init__ self master begin call __init__ self master bd=1 relief=string sunken set part_name = call Label self text=string Part name: grid row=0 column=0 sticky=string w set part_name = call Label self text=string grid row...
from tkinter import * from blinker import signal class PartInfoFrame(Frame): def __init__(self, master): Frame.__init__(self, master, bd=1, relief='sunken') self.part_name = Label(self, text='Part name:') self.part_name.grid(row=0, column=0, sticky='w') self.part_name = Label(self...
Python
zaydzuhri_stack_edu_python
comment Return True if the input string is palindrome function is_palindrome x begin set left = 0 set right = length x - 1 while right > left begin if not x at left == x at right begin return false end set left = left + 1 set right = right - 1 end return true end function comment True print call is_palindrome string ab...
# Return True if the input string is palindrome def is_palindrome(x): left = 0 right = len(x)-1 while right > left: if not x[left] == x[right]: return False left += 1 right -= 1 return True print(is_palindrome("abccba")) # True print(is_palindrome("abcbca")) # F...
Python
zaydzuhri_stack_edu_python
import argparse import re string Try it like this. $ python3 regex.py --needle "tiger" --haystack "I am looking for a tiger in the jungle" set parser = call ArgumentParser comment parser.add_argument("echo", help="enable echo with this positional parameter") comment arguments are treated as strings, convert to number c...
import argparse import re """ Try it like this. $ python3 regex.py --needle "tiger" --haystack "I am looking for a tiger in the jungle" """ parser = argparse.ArgumentParser() # parser.add_argument("echo", help="enable echo with this positional parameter") # arguments are treated as strings, convert to number # par...
Python
zaydzuhri_stack_edu_python
function load_data datafile baseline reference basis_key percentile_cutoff=0.0 E0=none begin set no_energy = false if baseline + string /energy in datafile begin set data_base = datafile at baseline + string /energy set data_ref = datafile at reference + string /energy end else begin set data_base = array list 0 set da...
def load_data(datafile, baseline, reference, basis_key, percentile_cutoff=0.0, E0=None): no_energy = False if baseline + '/energy' in datafile: data_base = datafile[baseline + '/energy'] data_ref = datafile[reference + '/energy'] else: data_base = np.array([0]) data_ref = np....
Python
nomic_cornstack_python_v1
comment Write two lines of code below, each assigning a value to a variable set day = 20 set year = 2020 comment Now write a print statement using .format() to print out a sentence and the comment values of both of the variables print format string Today's date is {a} - July - {b} a=day b=year
# Write two lines of code below, each assigning a value to a variable day = 20 year = 2020 # Now write a print statement using .format() to print out a sentence and the # values of both of the variables print('Today\'s date is {a} - July - {b}'.format(a = day, b = year))
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd from datetime import * comment Fix dates that are one day off function fix_dates d wrong begin if d in wrong begin comment return to yesterday return d - time delta days=1 end else begin return d end end function comment Fix the week column in allscores_201X data function fix_week...
import numpy as np import pandas as pd from datetime import * ####################################################################################### def fix_dates(d, wrong): #Fix dates that are one day off if d in wrong: return d - timedelta(days=1) #return to yesterday else: return d def fi...
Python
zaydzuhri_stack_edu_python
comment 다음 순열 comment 순열의 순서는 오름차순에서 내림차순 순서로 간다 set n = integer input set data = list map int split input string set length = length data set k = - 1 comment 1. data[i] < data[i+1]을 만족하는 i의 최댓값을 구한다. for i in range length - 1 begin if data at i < data at i + 1 begin set k = i end end comment k = -1 이면 이미 내림차순으로 정렬되어 있...
# 다음 순열 # 순열의 순서는 오름차순에서 내림차순 순서로 간다 n = int(input()) data = list(map(int, input().split(' '))) length = len(data) k = -1 # 1. data[i] < data[i+1]을 만족하는 i의 최댓값을 구한다. for i in range(length-1): if data[i] < data[i+1]: k = i # k = -1 이면 이미 내림차순으로 정렬되어 있는 것이다. if k == -1: print(-1) else: # 2. 인덱스 k 이...
Python
zaydzuhri_stack_edu_python
from django.test import TestCase from api.models import Review from django.utils import timezone from django.contrib.auth.models import User from rest_framework.test import APIClient from django.urls import reverse comment models test class ReviewTest extends TestCase begin function create_review self title=string only...
from django.test import TestCase from api.models import Review from django.utils import timezone from django.contrib.auth.models import User from rest_framework.test import APIClient from django.urls import reverse # models test class ReviewTest(TestCase): def create_review(self, title="only a test", summary="...
Python
zaydzuhri_stack_edu_python
function get resource_name id opts=none create_time=none db_cluster_id=none group_name=none group_type=none node_num=none update_time=none user=none begin set opts = merge opts call ResourceOptions id=id set __props__ = call __new__ _ResourceGroupState set __dict__ at string create_time = create_time set __dict__ at st...
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, create_time: Optional[pulumi.Input[str]] = None, db_cluster_id: Optional[pulumi.Input[str]] = None, group_name: Optional[pulumi.Input[str]] = None, gr...
Python
nomic_cornstack_python_v1
function autoPrioritySC self val=string True **kwargs begin pass end function
def autoPrioritySC(self, val='True', **kwargs): pass
Python
nomic_cornstack_python_v1
function insert_conf begin set conf_raw = call get_json set config = dictionary set res = dict if string name not in conf_raw begin raise call ConfError string 'name' must be specified in configuration end comment First check if such configuration already exists try begin call unprotected_get_module_conf conf_raw at s...
def insert_conf(): conf_raw = request.get_json() config = dict() res = {} if 'name' not in conf_raw: raise ConfError("'name' must be specified in configuration") # First check if such configuration already exists try: unprotected_get_module_conf(conf_raw['name']) except Co...
Python
nomic_cornstack_python_v1
function _get_self_bounds self begin if not embed begin raise call ValueError string Cannot compute bounds of non-embedded GeoJSON. end set data = loads data if string features not in keys data begin comment Catch case when GeoJSON is just a single Feature or a geometry. if not is instance data dict and string geometry...
def _get_self_bounds(self): if not self.embed: raise ValueError('Cannot compute bounds of non-embedded GeoJSON.') data = json.loads(self.data) if 'features' not in data.keys(): # Catch case when GeoJSON is just a single Feature or a geometry. if not (isinstan...
Python
nomic_cornstack_python_v1
from PySide.QtGui import * from PySide.QtCore import * import sys set __appname__ = string Eight Video class Program extends QDialog begin function __init__ self parent=none begin call __init__ parent set openButton = call QPushButton string Open set saveButton = call QPushButton string Save set dirButton = call QPushB...
from PySide.QtGui import * from PySide.QtCore import * import sys __appname__ = "Eight Video" class Program(QDialog): def __init__(self, parent=None): super(Program, self).__init__(parent) openButton = QPushButton("Open") saveButton = QPushButton("Save") dirButton = QPushButton("...
Python
zaydzuhri_stack_edu_python
function _get_info self data begin set feature_dtypes = dtypes set missing_values = call _get_missing_values data print string = * 200 print format string {:25} {:25} {:25} {:25} upper string Feature Name upper string Data Format upper string # of Missing Values upper string Samples comment Displays feature name, data ...
def _get_info(self, data): feature_dtypes = data.dtypes self.missing_values = self._get_missing_values ( data ) print ( "=" * 200 ) print ( "{:25} {:25} {:25} {:25}".format ( "Feature Name".upper (), "Data Format".upper (), ...
Python
nomic_cornstack_python_v1
function _prune self begin comment Find the nodes to keep comment The leaf should have the maximum score, and comment this score should be sufficiently large. call validate comment Keep the root set all_keeps = list set leaves = call findLeaves for leaf in leaves begin set path = call findPathToRoot set cur_leaf = lea...
def _prune(self): # Find the nodes to keep # The leaf should have the maximum score, and # this score should be sufficiently large. self.validate() all_keeps = [] # Keep the root leaves = self.findLeaves() for leaf in leaves: path = leaf.findPathToRoot() cur_leaf = leaf ke...
Python
nomic_cornstack_python_v1
function solve x begin if length x > 10 begin print format string {}{}{} x at 0 string length x at slice 2 : : x at - 1 end else begin print x end end function if __name__ == string __main__ begin set x = integer input set z = list for i in range x begin set y = input call solve y end end
def solve(x): if len(x) > 10: print("{}{}{}".format(x[0], str(len(x[2:])), x[-1])) else: print(x) if __name__ == "__main__": x = int(input()) z = [] for i in range(x): y = input() solve(y)
Python
zaydzuhri_stack_edu_python
import sys function main argv begin for param in argv begin print string Olá param end end function if __name__ == string __main__ begin call main argv end
import sys def main(argv): for param in argv: print("Olá", param) if __name__ == "__main__": main(sys.argv)
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn import torch.nn.functional as F comment from get_data import* class CNN_net extends Module begin function __init__ self vocab n_filters filter_sizes embedding_dim=100 begin call __init__ set embedding = call from_pretrained vectors comment two convolutional layers 5x100 set conv1 = co...
import torch import torch.nn as nn import torch.nn.functional as F #from get_data import* class CNN_net(nn.Module): def __init__(self, vocab, n_filters, filter_sizes, embedding_dim = 100): super(CNN_net, self).__init__() self.embedding = nn.Embedding.from_pretrained(vocab.vectors) # two con...
Python
zaydzuhri_stack_edu_python
import pygame import os set BASEPATH = real path path join path get current directory directory name path __file__ call init set myfont = call SysFont string Arial 15 class Hexagon begin function __init__ self position index matrix_pos begin set position = position set resource = none set number = none set index = inde...
import pygame import os BASEPATH = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) pygame.font.init() myfont = pygame.font.SysFont('Arial', 15) class Hexagon: def __init__(self, position, index, matrix_pos): self.position = position self.resource = None ...
Python
zaydzuhri_stack_edu_python
import io import math import datetime import sys import time from collections import defaultdict comment Declare a list to hold the relevant data set donor_data = list comment median_by_zip_data = [] comment Declare two dictionaries for the purpose of grouping set group_data_by_CMTE_ID_and_date = default dictionary li...
import io import math import datetime import sys import time from collections import defaultdict # Declare a list to hold the relevant data donor_data = [] #median_by_zip_data = [] #Declare two dictionaries for the purpose of grouping group_data_by_CMTE_ID_and_date = defaultdict(list) group_data_by_CMTE_ID_and_zip_c...
Python
zaydzuhri_stack_edu_python
function RecycleIfNecessary self begin if _processed_symbols_count >= ADDR2LINE_RECYCLE_LIMIT begin call _RestartAddr2LineProcess end end function
def RecycleIfNecessary(self): if self._processed_symbols_count >= ADDR2LINE_RECYCLE_LIMIT: self._RestartAddr2LineProcess()
Python
nomic_cornstack_python_v1
function authenticate cls username password begin set user = first filter by query username=username if user and call check_password_hash password password begin return user end else begin return false end end function
def authenticate(cls, username, password): user = User.query.filter_by(username=username).first() if user and bcrypt.check_password_hash(user.password, password): return user else: return False
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- class Solution begin function FindNumbersWithSum self array tsum begin comment write code here set d = dict set result = list for i in array begin if tsum - i in d begin if length result > 0 begin if tsum - i * i < result at 0 * result at 1 begin set tuple result at 0 result at 1 = tuple ...
# -*- coding:utf-8 -*- class Solution: def FindNumbersWithSum(self, array, tsum): # write code here d = {} result = [] for i in array: if tsum - i in d: if len(result) > 0: if (tsum - i) * i < result[0] * result[1]: ...
Python
zaydzuhri_stack_edu_python
string %prog [options] vers Convert the original fits files for the aardvark sims to an indexed columns database vers is the originating version, e.g. aardvark_v0.5d Will read from {vers}_truth and write to {vers}_truth.cols import os import sys import glob import numpy import esutil as eu from shapesim.dessim import f...
""" %prog [options] vers Convert the original fits files for the aardvark sims to an indexed columns database vers is the originating version, e.g. aardvark_v0.5d Will read from {vers}_truth and write to {vers}_truth.cols """ import os import sys import glob import numpy import esutil as eu from shapesim.des...
Python
zaydzuhri_stack_edu_python
function GetModifiableTransform self begin return call itkTransformMeshFilterMF3MF3TF33_GetModifiableTransform self end function
def GetModifiableTransform(self) -> "itkTransformF33 *": return _itkTransformMeshFilterPython.itkTransformMeshFilterMF3MF3TF33_GetModifiableTransform(self)
Python
nomic_cornstack_python_v1
from gtts import gTTS from playsound import playsound import tkinter as Tk from tkinter import font import os set m = call Tk title m string Text to Speech call geometry string 300x200 set language = string en function start begin set text = get enter set val = call gTTS text=text lang=language slow=false save string m...
from gtts import gTTS from playsound import playsound import tkinter as Tk from tkinter import font import os m=Tk.Tk() m.title("Text to Speech") m.geometry("300x200") language="en" def start(): text=enter.get() val=gTTS(text=text,lang=language,slow=False) val.save("myfiles.mp3") playsound("myfiles.m...
Python
zaydzuhri_stack_edu_python
from shorten import app from flask import request , redirect import redis , uuid , re , shortuuid , json set rconn = call Redis host=string localhost port=6379 db=0 set url_regex = compile string ^(?:http|ftp)s?://(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|localhost|\d{1,3}\.\d{1,3...
from shorten import app from flask import request,redirect import redis,uuid,re,shortuuid,json rconn = redis.Redis(host='localhost', port=6379, db=0) url_regex = re.compile( r'^(?:http|ftp)s?://' r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' r'localhost|' ...
Python
zaydzuhri_stack_edu_python
function email_user self subject message from_email=none begin call send_mail subject message from_email list email end function
def email_user(self, subject, message, from_email=None): send_mail(subject, message, from_email, [self.email])
Python
nomic_cornstack_python_v1
import math function main begin with open string data/day12.txt as f begin set directions = list comprehension tuple line at 0 integer line at slice 1 : : for line in read lines f end call part1 directions call part2 directions end function function part1 directions begin set position = tuple 0 0 set orientation = 0 f...
import math def main(): with open("data/day12.txt") as f: directions = [(line[0], int(line[1:])) for line in f.readlines()] part1(directions) part2(directions) def part1(directions): position = (0, 0) orientation = 0 for command, amount in directions: if command == "W": ...
Python
zaydzuhri_stack_edu_python
function local_cost_delta proc_assignment process machine begin set moving_cost = process_moving_costs at process set total_cost = moving_cost set machineload_cost_old = list 0 * call __len__ set machineload_cost_new = list 0 * call __len__ set process_cost = process_requirements at process comment processes in the old...
def local_cost_delta(proc_assignment, process, machine): moving_cost = proc_assignment.process_moving_costs[process] total_cost = moving_cost machineload_cost_old = [0] * proc_assignment.machine_capacities[0].__len__() machineload_cost_new = [0] * proc_assignment.machine_capacities[0].__len__() process_cost = p...
Python
nomic_cornstack_python_v1
function _test begin import doctest print string launching doctest comment module test call testmod report=true print string done (ideally no line between launching and done was printed, however slight deviations are possible) end function
def _test(): import doctest print('launching doctest') doctest.testmod(report=True) # module test print("""done (ideally no line between launching and done was printed, however slight deviations are possible)""")
Python
nomic_cornstack_python_v1
while x < 10 begin print string * end=string set x = x + 1 end print format string {:=^20} string practice 1 set x = 0 while x ^ 3 <= 10000 begin set x = x + 1 end print x
while x < 10: print("*", end="") x += 1 print("{:=^20}".format(" practice 1 ")) x = 0 while x**3 <= 10000: x += 1 print(x)
Python
zaydzuhri_stack_edu_python
function parse_mp_url mp_url begin set parts = call urlsplit mp_url if not starts with netloc string code.launchpad.net begin print string Error parsing url, should be of the formhttps://code.launchpad.net/~<author.name>/<project.name>/<branch.name>/+merge/<id> exit 2 end set tuple branch_name merge_id = split path str...
def parse_mp_url(mp_url): parts = urlparse.urlsplit(mp_url) if not parts.netloc.startswith('code.launchpad.net'): print('Error parsing url, should be of the form' 'https://code.launchpad.net/~<author.name>/<project.name>/<branch.name>/+merge/<id>') sys.exit(2) branch_name, mer...
Python
nomic_cornstack_python_v1
function mimaga_filter self genes classes begin set genes_T = transpose genes set tuple train_set test_set train_classes test_classes = train test split genes_T classes test_size=0.33 set filtered_indexes = call _mim_filter transpose train_set set index_map = dictionary zip list comprehension i for i in range _mim_size...
def mimaga_filter(self, genes, classes): genes_T = genes.transpose() train_set, test_set, train_classes, test_classes = train_test_split(genes_T, classes, test_size=0.33) filtered_indexes = self._mim_filter(train_set.transpose()) index_map = dict(zip([i for i in range(self._mim_size)], f...
Python
nomic_cornstack_python_v1
class PrimeNumberIterator begin function __init__ self begin set current = 1 end function function __iter__ self begin return self end function function __next__ self begin set current = current + 1 while true begin if current > 10 begin raise StopIteration end else if call is_prime current begin set prime_number = cur...
class PrimeNumberIterator: def __init__(self): self.current = 1 def __iter__(self): return self def __next__(self): self.current += 1 while True: if self.current > 10: raise StopIteration elif self.is_prime(self.current): ...
Python
jtatman_500k
import pandas as pd import numpy as np comment import data sets to be merged set sf_categories = read csv open string data/eventbrite_SF_categories.csv set sf_subcats = read csv open string data/eventbrite_SF_subcats.csv set sea_categories = read csv open string data/eventbrite_Seattle_categories.csv set sea_subcats = ...
import pandas as pd import numpy as np # import data sets to be merged sf_categories = pd.read_csv(open('data/eventbrite_SF_categories.csv')) sf_subcats = pd.read_csv(open('data/eventbrite_SF_subcats.csv')) sea_categories = pd.read_csv(open('data/eventbrite_Seattle_categories.csv')) sea_subcats = pd.read_csv(open('dat...
Python
zaydzuhri_stack_edu_python
string Created on May 14, 2017 @author: Nate import math as m import matplotlib.pyplot as plt import numpy as np function productSum xList yList begin set i = 0 set sum = 0 while i < length xList begin set sum = sum + xList at i * yList at i set i = i + 1 end return sum end function function barOf list begin return sum...
''' Created on May 14, 2017 @author: Nate ''' import math as m import matplotlib.pyplot as plt import numpy as np def productSum(xList, yList): i = 0 sum = 0 while i < len(xList): sum += xList[i] * yList[i] i += 1 return sum def barOf(list): return sum(list) / len(list) def sampl...
Python
zaydzuhri_stack_edu_python
import math set conv = decimal input string 1 para convertir de Grados a Radianes, 2 para convertir de Radianes a Grados if conv == 1 begin set inp = decimal input string Ingresa los Grados set final = inp * pi / 180 print string %f Grados son %f Radianes % tuple inp final end else begin set inp = decimal input string ...
import math conv = float(input("1 para convertir de Grados a Radianes, 2 para convertir de Radianes a Grados\n")) if conv == 1: inp = float(input("Ingresa los Grados\n")) final = inp*math.pi/180 print("%f Grados son %f Radianes"%(inp, final)) else: inp = float(input("Ingresa los Radianes\n")) final = inp...
Python
zaydzuhri_stack_edu_python
function count_occurrences string begin set count = 0 for char in string begin if lower char == string a or lower char == string á begin set count = count + 1 end end return count end function
def count_occurrences(string): count = 0 for char in string: if char.lower() == 'a' or char.lower() == 'á': count += 1 return count
Python
jtatman_500k
function test_content_type_4_login_not_json self begin set rv = post string /api/v1/auth/login content_type=string text data=dumps dictionary dict string status string register assert equal status_code 202 assert in string "message": "Content-type must be in json" string data end function
def test_content_type_4_login_not_json(self): rv = self.client.post( '/api/v1/auth/login', content_type="text", data=json.dumps(dict({'status': 'register'})) ) self.assertEqual(rv.status_code, 202) self.assertIn('"message": "Content-type must be in jso...
Python
nomic_cornstack_python_v1
function build_graph self graph_id begin if graph_id == 1 begin clear graph_icnet for transporter in transporters_icnet begin call add_node id end for cargo_owner in cargo_owners begin call add_node 100000 + id end for bid_icnet in bids_icnet begin if call has_edge transporter_id 100000 + cargo_owner_id begin set graph...
def build_graph(self, graph_id): if graph_id == 1: self.graph_icnet.clear() for transporter in self.transporters_icnet: self.graph_icnet.add_node(transporter.id) for cargo_owner in self.cargo_owners: self.graph_icnet.add_node(100000 + cargo_ow...
Python
nomic_cornstack_python_v1
comment Bryan Ventura Ortiz Using Python Variable set name = input string what is your name? print string ------------- print string .:: + string name + string ::. print string -------------
#Bryan Ventura Ortiz Using Python Variable name = input("what is your name?") print("-------------") print(".::" + str(name) + "::.") print("-------------")
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun Sep 15 22:48:43 2019 @author: ROHAN BHOSALE import numpy as np import sys append path string .. comment It's kk to import whatever you want from the local util module if you would like: comment from util.X import ... function filter_2d im kernel begin set M = shape at...
# -*- coding: utf-8 -*- """ Created on Sun Sep 15 22:48:43 2019 @author: ROHAN BHOSALE """ import numpy as np import sys sys.path.append('..') #It's kk to import whatever you want from the local util module if you would like: #from util.X import ... def filter_2d(im, kernel): M = kernel.shape[0] N = kernel...
Python
zaydzuhri_stack_edu_python
function contained_by self other begin return call call op string <@ other end function
def contained_by(self, other): return self.expr.op('<@')(other)
Python
nomic_cornstack_python_v1
string ~~~~~~~~~~~~~~~~~~~ getContinuumFlux.py ~~~~~~~~~~~~~~~~~~~ From `agpy <http://code.google.com/p/agpy/source/browse/trunk/agpy/cubes.py>`_, contains functions to perform various transformations on data cubes and their headers. from astropy.extern.six.moves import xrange from numpy import sqrt , repeat , indices ...
""" ~~~~~~~~~~~~~~~~~~~ getContinuumFlux.py ~~~~~~~~~~~~~~~~~~~ From `agpy <http://code.google.com/p/agpy/source/browse/trunk/agpy/cubes.py>`_, contains functions to perform various transformations on data cubes and their headers. """ from astropy.extern.six.moves import xrange from numpy import sqrt,repea...
Python
zaydzuhri_stack_edu_python
from classes.game import Person , Bcolors from classes.magic import Spell from classes.inventory import Item comment Creating Some Black Magic set fire = call Spell string Fire 10 100 string Black set thunder = call Spell string Thunder 10 100 string Black set blizzard = call Spell string Blizzard 10 100 string Black s...
from classes.game import Person, Bcolors from classes.magic import Spell from classes.inventory import Item # Creating Some Black Magic fire = Spell('Fire', 10, 100, 'Black') thunder = Spell('Thunder', 10, 100, 'Black') blizzard = Spell('Blizzard', 10, 100, 'Black') quack = Spell('Quack', 20, 200, 'Black') meteor = Sp...
Python
zaydzuhri_stack_edu_python
function get_child self value begin return __children at value end function
def get_child(self, value): return self.__children[value]
Python
nomic_cornstack_python_v1
function agent_intents self begin string Returns a list of intent json objects set endpoint = call _intent_uri comment should be list of dicts set intents = call _get endpoint comment if error: intents = {status: {error}} if is instance intents dict begin raise exception intents at string status end return list compreh...
def agent_intents(self): """Returns a list of intent json objects""" endpoint = self._intent_uri() intents = self._get(endpoint) # should be list of dicts if isinstance(intents, dict): # if error: intents = {status: {error}} raise Exception(intents["status"]) retur...
Python
jtatman_500k
function test_rider__no_resources_access self begin call visit assert loaded is false end function
def test_rider__no_resources_access(self) -> None: self.resources.visit() assert self.resources.sidebar.loaded is False
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python comment coding:utf-8 import os , sys import pexpect comment 实现的还有问题 comment 用pexpect执行ssh,查看远程uptime和df -h看硬盘状况 function ssh_cmd ip user passwd cmd begin set ssh = call spawn string ssh %s@%s "%s" % tuple user ip cmd comment ssh.logfile=sys.stdout set r = string try begin while 1 begin co...
#! /usr/bin/env python # coding:utf-8 import os, sys import pexpect # 实现的还有问题 # 用pexpect执行ssh,查看远程uptime和df -h看硬盘状况 def ssh_cmd(ip, user, passwd, cmd): ssh = pexpect.spawn('ssh %s@%s "%s"' % (user, ip, cmd)) #ssh.logfile=sys.stdout r = '' try: while 1: #i = ssh.expect(['password: ...
Python
zaydzuhri_stack_edu_python
class Vehicle begin function __init__ self make model year begin set make = make set model = model set year = year end function function start self begin pass end function end class class Car extends Vehicle begin function start self begin print string Starting { make } { model } ... end function end class class Truck ...
class Vehicle: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def start(self): pass class Car(Vehicle): def start(self): print(f"Starting {self.make} {self.model}...") class Truck(Vehicle): def start(self): p...
Python
jtatman_500k
function allocate_office self new_id_no begin set zero = 0 if length rooms is zero begin set msg = string The system has no available rooms return msg end set vacant_offices = list for room in rooms begin if room in keys offices and length offices at room < 6 begin append vacant_offices room end end if length vacant_o...
def allocate_office(self, new_id_no): zero = 0 if len(self.rooms) is zero: msg = "The system has no available rooms" return msg vacant_offices = [] for room in self.rooms: if room in self.offices.keys() and len(self.offices[room]) < 6: ...
Python
nomic_cornstack_python_v1
function ln_likelihood_floored self x begin set outputs = call run_stack x root=string objective return max LOCAL_LIKELIHOOD_FLOOR outputs at string value end function
def ln_likelihood_floored(self, x): outputs = self.run_stack(x, root='objective') return max(LOCAL_LIKELIHOOD_FLOOR, outputs['value'])
Python
nomic_cornstack_python_v1
function convert_mac_address self outside_address begin set outside_address = get _macfix__result outside_address outside_address return call convert_mac_address outside_address end function
def convert_mac_address(self, outside_address): outside_address = self._macfix__result.get(outside_address, outside_address) return super(MacFix, self).convert_mac_address(outside_address)
Python
nomic_cornstack_python_v1
function __init__ self object_id tag position_x position_y tetronimo_type object_factory settings input_manager collision_box sprite_images begin comment Call the inherited class constructor. call __init__ object_id tag position_x position_y collision_box sprite_images comment Checks if the tetronimo is falling. set is...
def __init__(self, object_id, tag, position_x, position_y, tetronimo_type, \ object_factory, settings, input_manager, collision_box, sprite_images): # Call the inherited class constructor. super(TetronimoFalling, self).__init__(object_id, tag, position_x, position_y, \ collision_box, sprite_images) ...
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment In[1]: import numpy as np import pandas as pd comment In[9]: class CalList extends object begin function __init__ self begin set tpr_list_cal = list set fpr_list_cal = list set BER_list_cal = list set f1_score_list_cal = list end function function list_append self Precall f1_score BER ...
# coding: utf-8 # In[1]: import numpy as np import pandas as pd # In[9]: class CalList (object): def __init__ (self): self.tpr_list_cal = [] self.fpr_list_cal = [] self.BER_list_cal = [] self.f1_score_list_cal = [] def list_append (self,Precall,f1_score,BER,F...
Python
zaydzuhri_stack_edu_python
function read_scanID self begin comment PROTECTED REGION ID(CspSubElementSubarray.scanID_read) ENABLED START # return scan_id end function comment PROTECTED REGION END # // CspSubElementSubarray.scanID_read
def read_scanID(self): # PROTECTED REGION ID(CspSubElementSubarray.scanID_read) ENABLED START # return self.component_manager.scan_id # PROTECTED REGION END # // CspSubElementSubarray.scanID_read
Python
nomic_cornstack_python_v1
comment !/bin/python if 1 < 2 begin print 1 < 2 end function fun begin return 0 end function set x = integer input string please input : if x >= 90 begin print string A end else if x < 60 begin print string B end else begin print string C end print 1 and 1 print 1 or 1 set var1 = 100 if var1 begin print string 1 - if 表...
# !/bin/python if 1 < 2: print(1 < 2) def fun(): return 0 x = int(input("please input :")) if x >= 90: print("A") elif x < 60: print("B") else: print("C") print(1 and 1) print(1 or 1) var1 = 100 if var1: print("1 - if 表达式条件为 true") print(var1) var2 = 0 if var2: print("2 - if 表达式...
Python
zaydzuhri_stack_edu_python
function median X **kwargs begin set m = median X axis=0 set m = reshape array m - 1 return m end function
def median(X,**kwargs): m = np.median(X,axis=0) m = np.array(m).reshape(-1) return m
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 import unittest class TestSquareClass extends TestCase begin function test_squareSub self begin set s1 = call Square 3 assert true is subclass square Rectangle end function end class
#!/usr/bin/python3 import unittest class TestSquareClass(unittest.TestCase): def test_squareSub(self): s1 = Square(3) self.assertTrue(issubclass(square, Rectangle))
Python
zaydzuhri_stack_edu_python
function get_ask_stories hn limit=2 begin set ask_stories = list comprehension call get_item story_id for story_id in call ask_stories limit=limit write stdout string Got the ask stories return ask_stories end function
def get_ask_stories(hn, limit=2): ask_stories = [hn.get_item(story_id) for story_id in hn.ask_stories(limit=limit)] sys.stdout.write("Got the ask stories\n") return ask_stories
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python2 from sys import argv , stdout , stderr from getopt import getopt , GetoptError from lpltk.LaunchpadService import LaunchpadService import re comment error comment Print strings to standard out preceded by "error:". function error out begin write stderr string ** Error: %s % out flush stder...
#!/usr/bin/env python2 # from sys import argv, stdout, stderr from getopt import getopt, GetoptError from lpltk.LaunchpadService import LaunchpadService import re # error # # Print strings to standard out preceded by "error:". # def error(out): ...
Python
zaydzuhri_stack_edu_python
function test_wait_for_event_finished self client begin call register_uri GET string https://localhost/account/events/123 responses=list call Response body=dumps call body_event_status string started call Response body=dumps call body_event_status string started call Response body=dumps call body_event_status string fi...
def test_wait_for_event_finished( self, client, ): httpretty.register_uri( httpretty.GET, "https://localhost/account/events/123", responses=[ httpretty.Response( body=json.dumps(self.body_event_status("started")), ...
Python
nomic_cornstack_python_v1
function do_type self _ begin if length args < 1 begin print string USAGE: %s type % argv at 0 file=stderr return 1 end set f = named temporary file mode=string w+ write f CXX_HEADER + string int main() { std::cout << type_name<decltype(%s)>() << std::endl; } % args at 0 flush f execute f end function
def do_type(self, _): if len(self.args) < 1: print("USAGE: %s type" % sys.argv[0], file=sys.stderr) return 1 f = tempfile.NamedTemporaryFile(mode="w+") f.write( CXX_HEADER + "int main() { std::cout << type_name<decltype(%s)>() << std::endl; }" ...
Python
nomic_cornstack_python_v1
function set_dynamics_to_user_function self update_function begin set _update_method = update_function end function
def set_dynamics_to_user_function(self, update_function): self._update_method = update_function
Python
nomic_cornstack_python_v1
import phe as paillier import json function storeKeys begin string This function is intended to create the both public and private key. set tuple public_key private_key = call generate_paillier_keypair set keys = dict set keys at string public_key = dict string n n set keys at string private_key = dict string p p ; st...
import phe as paillier import json def storeKeys(): '''This function is intended to create the both public and private key.''' public_key, private_key = paillier.generate_paillier_keypair() keys = {} keys['public_key'] = {'n': public_key.n} keys['private_key'] = {'p': private_key.p, 'q': private_...
Python
zaydzuhri_stack_edu_python
function unicodeToAscii s begin return join string generator expression c for c in call normalize string NFD s if call category c != string Mn end function
def unicodeToAscii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' )
Python
nomic_cornstack_python_v1
function acs_ethnicity_demographics self begin return dict string White 0.438 ; string Hispanic 0.236 ; string Asian 0.17 ; string Black 0.109 ; string Native Hawaiian/Pacific Islander 0.013 ; string American Indian/Alaska Native 0.015 ; string Multi-Race 0.065 end function
def acs_ethnicity_demographics(self) -> Dict[str, float]: return {'White': 0.438, 'Hispanic': 0.236, 'Asian': 0.170, 'Black': 0.109, 'Native Hawaiian/Pacific Islander': 0.013, 'American Indian/Alaska Native': 0.015, 'Multi-Race': 0.065}
Python
nomic_cornstack_python_v1
function success_rate_minimum_hosts self begin return get pulumi self string success_rate_minimum_hosts end function
def success_rate_minimum_hosts(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "success_rate_minimum_hosts")
Python
nomic_cornstack_python_v1
function __init__ self integration_layer begin set __integration_layer = integration_layer set __node_group_repository = call NodeGroupRepository end function
def __init__(self, integration_layer): self.__integration_layer = integration_layer self.__node_group_repository = NodeGroupRepository()
Python
nomic_cornstack_python_v1
function __init__ self Wn_roll=0.0 Zeta_roll=0.0 Wn_course=0.0 Zeta_course=0.0 Wn_sideslip=0.0 Zeta_sideslip=0.0 Wn_pitch=0.0 Zeta_pitch=0.0 Wn_altitude=0.0 Zeta_altitude=0.0 Wn_SpeedfromThrottle=0.0 Zeta_SpeedfromThrottle=0.0 Wn_SpeedfromElevator=0.0 Zeta_SpeedfromElevator=0.0 begin comment tuning knobs for lateral co...
def __init__(self, Wn_roll = 0.0, Zeta_roll = 0.0, Wn_course = 0.0, Zeta_course = 0.0, Wn_sideslip = 0.0, Zeta_sideslip = 0.0, Wn_pitch = 0.0, Zeta_pitch = 0.0, Wn_altitude = 0.0 , Zeta_altitude = 0.0, Wn_SpeedfromThrottle = 0.0, Zeta_SpeedfromThrottle = 0.0, Wn_SpeedfromElevator = 0.0, Zeta_SpeedfromElevator = 0.0): ...
Python
nomic_cornstack_python_v1
function get self api begin if length api == 0 begin print string ERROR: API is not specified return end comment invoke set url = endpoint + api comment print("%s: URL=%s" % (sys._getframe().f_code.co_name, url)) set req = get requests url if status_code != 200 begin print string ERROR: error occurred in invoking, errc...
def get(self, api): if len(api) == 0: print("ERROR: API is not specified") return # invoke url = self.endpoint + api # print("%s: URL=%s" % (sys._getframe().f_code.co_name, url)) req = requests.get(url) if req.status_code != 200: print("ERROR: error occurred in invoking, errcd=%d\n" % req.status_c...
Python
nomic_cornstack_python_v1
function get_mutations test_subject=none begin set test_subject = get form string data set output = list if get form string suite == string mythril begin set output = list comprehension call get_mythril x at string code x at string mutation for x in call apply_mutation test_subject end if get form string suite == stri...
def get_mutations(test_subject=None): test_subject = request.form.get('data') output = [] if request.form.get('suite') == 'mythril': output = [get_mythril(x['code'], x['mutation']) for x in apply_mutation(test_subject)] if request.form.get('suite') == 'oyente': output = [get_oyente(x['code'], x['mutation']...
Python
nomic_cornstack_python_v1
async function setsilence self ctx minutes begin if minutes < 0 begin await call say string Minutes must be positive return end set set default numbers id dictionary at string silence = minutes * 60 await call say string Successfully set the silence end function
async def setsilence(self, ctx, minutes: float): if minutes < 0: await self.bot.say("Minutes must be positive") return self.numbers.setdefault(ctx.message.server.id, dict())['silence'] = minutes * 60 await self.bot.say("Successfully set the silence")
Python
nomic_cornstack_python_v1