code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function onClose self begin call destroy end function
def onClose(self): self.destroy()
Python
nomic_cornstack_python_v1
from data_processing import * from visual_configuration import * class GradeBookVisualizer extends StudentInteractionMethods begin function __init__ self bias=string left begin string call __init__ bias=bias set visual_configuration = call VisualConfiguration end function function get_histogram self arr edges begin st...
from data_processing import * from visual_configuration import * class GradeBookVisualizer(StudentInteractionMethods): def __init__(self, bias='left'): """ """ super().__init__(bias=bias) self.visual_configuration = VisualConfiguration() def get_histogram(self, arr, edges): ...
Python
zaydzuhri_stack_edu_python
function make_manifest manifest config docs kwargs begin comment pylint: disable = R0912 set kwargs = copy kwargs set kwargs at string script_args = list string install set kwargs at string packages = list get kwargs string packages or tuple + list string _setup string _setup.py2 string _setup.py3 + list split get mani...
def make_manifest(manifest, config, docs, kwargs): # pylint: disable = R0912 kwargs = kwargs.copy() kwargs['script_args'] = ['install'] kwargs['packages'] = list(kwargs.get('packages') or ()) + [ '_setup', '_setup.py2', '_setup.py3', ] + list(manifest.get('packages.extra', '').split() or ())...
Python
nomic_cornstack_python_v1
function concatenate_matrices *matrices begin set output = call identity 4 for i in matrices begin set output = dot output i end return output end function
def concatenate_matrices(*matrices): output = np.identity(4) for i in matrices: output = np.dot(output, i) return output
Python
nomic_cornstack_python_v1
for _ in range n begin set tuple op num = split input set num = integer num if op == string & begin set zero = zero ? num set ones = ones ? num end else if op == string | begin set zero = zero ? num set ones = ones ? num end else begin set zero = zero ? num set ones = ones ? num end end set and_bits = 0 set or_bits = 0...
for _ in range(n): op, num = input().split() num = int(num) if op == '&': zero &= num ones &= num elif op == '|': zero |= num ones |= num else: zero ^= num ones ^= num and_bits = 0 or_bits = 0 xor_bits = 0 for i in range(10): z = (zero...
Python
jtatman_500k
set firstNumber = 5 set secondNumber = 10 print string The sum is: firstNumber + secondNumber
firstNumber = 5 secondNumber = 10 print("The sum is: ", firstNumber + secondNumber)
Python
flytech_python_25k
comment implemented using c950 Webinar 1 as reference (Tepe, 17 Nov. 2020) comment Initialization ------------------------------------------------------------------------------------------------------ class ChainingHashTable begin comment constructor comment includes optional initial capacity parameter comment assigns ...
# implemented using c950 Webinar 1 as reference (Tepe, 17 Nov. 2020) # Initialization ------------------------------------------------------------------------------------------------------ class ChainingHashTable: # constructor # includes optional initial capacity parameter # assigns all buckets w...
Python
zaydzuhri_stack_edu_python
function bread_restart2c part pparti kipic qi iur ntime ntime0 nppi noff nyp nx mx1 irc begin global i1 i2 set irc at 0 = 0 comment ions are moving if movion > 0 begin comment copy ordered ion data for OpenMP: updates pparti and kipic call mpmovin2p part pparti kipic nppi noff mx my mx1 irc comment sanity check for ion...
def bread_restart2c(part,pparti,kipic,qi,iur,ntime,ntime0,nppi,noff,nyp, nx,mx1,irc): global i1, i2 irc[0] = 0 # ions are moving if (in2.movion > 0): # copy ordered ion data for OpenMP: updates pparti and kipic mpush2.mpmovin2p(part,pparti,kipic,nppi,noff,in2.mx,in2.my,mx1, ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import sys
#!/usr/bin/env python import sys
Python
zaydzuhri_stack_edu_python
function to_larva self pipeline=true begin if pipeline begin call file_write call pipe_path string larva call build string a end else begin print call build end end function
def to_larva(self, pipeline=True) -> None: if pipeline: Utility.file_write(Utility.pipe_path("larva"), self.build(), "a") else: print(self.build())
Python
nomic_cornstack_python_v1
function set_interruption_point self grid_index tile_index during_acq=true begin set acq_interrupted = true set acq_interrupted_at = list grid_index tile_index if not during_acq begin comment Mark grids/tiles before interruption point as acquired set grids_acquired = list for g in range number_grids begin if g == grid...
def set_interruption_point(self, grid_index, tile_index, during_acq=True): self.acq_interrupted = True self.acq_interrupted_at = [grid_index, tile_index] if not during_acq: # Mark grids/tiles before interruption point as acquired self.grids_acquired = [] for g...
Python
nomic_cornstack_python_v1
function GetKeywords self begin return list FS_COMMANDS FS_STDLIB FS_FUNC FS_CLASS end function
def GetKeywords(self): return [FS_COMMANDS, FS_STDLIB, FS_FUNC, FS_CLASS]
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding=utf-8 import json import os import sys import time comment 进程池 from multiprocessing import Pool import config import requests from lxml import etree try begin import xml.etree.cElementTree as ET end except ImportError begin import xml.etree.ElementTree as ET end class TumblrS...
#!/usr/bin/env python # coding=utf-8 import json import os import sys import time from multiprocessing import Pool # 进程池 import config import requests from lxml import etree try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET class TumblrSpider(object): pro...
Python
zaydzuhri_stack_edu_python
function eval_integral self targets sources source_normal_x source_normal_y begin set C = 1 set dyad = 2 ^ array range - m C dtype=float set dyadic_int = insert np dyad 0 0.0 set npoints = 8 set ref_info = weights set ref_nodes = ref_info at tuple slice : : 0 set ref_weights = ref_info at tuple slice : : 2 set im...
def eval_integral(self, targets, sources, source_normal_x, source_normal_y): C = 1 dyad = 2 ** np.arange(-self.m, C, dtype=float) dyadic_int = np.insert(dyad, 0, 0.0) npoints = 8 ref_info = scp.legendre(npoints).weights ref_nodes = ref_info[:, 0] ref_weights = ref...
Python
nomic_cornstack_python_v1
function tryandconnect ipaddresses passwordsource successfullyconnectedclients begin try begin set client = call SSHClient call load_system_host_keys call set_missing_host_key_policy call AutoAddPolicy call connect ipaddresses password=passwordsource call exec_command string rm /root/ConnecttoCNC.py call exec_command s...
def tryandconnect(ipaddresses,passwordsource,successfullyconnectedclients): try: client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(ipaddresses,password=passwordsource) client.exec_command('rm /root/ConnecttoCNC.py') clie...
Python
nomic_cornstack_python_v1
function mutant_positions_and_data datasets=list dataset_formats=0 density_plots=true colors=none names=none maxes_per_base=none maxes_per_bin=none strands=none widths=none title=string bin_size=DEFAULT_BIN_SIZE chromosome_lengths=none interpolate=false NaN_color=string 0.6 total_plotline_width=0.6 condense_colorbars...
def mutant_positions_and_data(datasets=[], dataset_formats=0, density_plots=True, colors=None, names=None, maxes_per_base=None, maxes_per_bin=None, strands=None, widths=None, title='', bin_size=mutant_utilities.DEFAULT_BIN_SIZE, chromosome_lengths=None, inte...
Python
nomic_cornstack_python_v1
function find_anagrams words begin set anagram_dict = dict for word in words begin set sorted_word = join string sorted word if sorted_word not in anagram_dict begin set anagram_dict at sorted_word = list end append anagram_dict at sorted_word word end set anagram_lists = list for sorted_word in anagram_dict begin ...
def find_anagrams(words): anagram_dict = {} for word in words: sorted_word = ''.join(sorted(word)) if sorted_word not in anagram_dict: anagram_dict[sorted_word] = [] anagram_dict[sorted_word].append(word) anagram_lists = [] for sorted_word in anagram_dict: ...
Python
jtatman_500k
function get self requestCode begin set serverRequest = none if requestCode in requestTable begin set serverRequest = call end end function
def get(self, requestCode): serverRequest = None if requestCode in self.requestTable: serverRequest = globals()[self.requestTable[requestCode]]()
Python
nomic_cornstack_python_v1
function __init__ self config_file_path begin if not exists path config_file_path begin raise call IOError string Neo4j config file not exist end if not is file path config_file_path begin raise call IOError string Neo4j config path is not file end if not ends with config_file_path string .json begin raise call IOError...
def __init__(self, config_file_path): if not os.path.exists(config_file_path): raise IOError("Neo4j config file not exist") if not os.path.isfile(config_file_path): raise IOError("Neo4j config path is not file") if not config_file_path.endswith(".json"): raise...
Python
nomic_cornstack_python_v1
comment Project name : SPOJ: ENCAROC - Occurrences of a Character comment Author : Wojciech Raszka comment Date created : 2019-03-24 comment Description : comment Status : Accepted (23483741) comment Tags : python comment Comment : set sentence = input set letter = strip input print length sentence - length replace sen...
# Project name : SPOJ: ENCAROC - Occurrences of a Character # Author : Wojciech Raszka # Date created : 2019-03-24 # Description : # Status : Accepted (23483741) # Tags : python # Comment : sentence = input() letter = input().strip() print(len(sentence)- len(sentence.replace(letter, "")))
Python
zaydzuhri_stack_edu_python
import random set upper = 100 set lower = 0 set x = random integer lower upper set y = random integer lower upper set sum = x + y set avg = sum / 2 print string Thomas Bouranis print x print y print format string Sum = {} sum print format string Average = {} avg
import random upper = 100 lower = 0 x = random.randint(lower, upper) y = random.randint(lower, upper) sum = x + y avg = sum / 2 print("Thomas Bouranis") print(x) print(y) print("Sum = {}".format(sum)) print("Average = {}".format(avg))
Python
zaydzuhri_stack_edu_python
import cv2 import mediapipe as mp import time class HandDetector begin function __init__ self mode=false maxHands=2 detection_confidence=0.5 track_confidence=0.5 begin set mode = mode set maxHands = maxHands set detection_confidence = detection_confidence set track_confidence = track_confidence set mpHands = hands set ...
import cv2 import mediapipe as mp import time class HandDetector(): def __init__(self, mode=False, maxHands=2, detection_confidence=0.5, track_confidence=0.5): self.mode = mode self.maxHands = maxHands ...
Python
zaydzuhri_stack_edu_python
from urllib.request import urlopen from bs4 import BeautifulSoup import os function make_soup url begin set thepage = url open url set soupdata = call BeautifulSoup thepage string html.parser return soupdata end function set playerdatasaved = string set soup = call make_soup string https://fantasyfootballfirst.co.uk/p...
from urllib.request import urlopen from bs4 import BeautifulSoup import os def make_soup(url): thepage = urlopen(url) soupdata = BeautifulSoup(thepage, "html.parser") return soupdata playerdatasaved="" soup=make_soup("https://fantasyfootballfirst.co.uk/player-performance-1/players/ ") tablestats = ...
Python
zaydzuhri_stack_edu_python
comment 5. Escreva um programa em Python que leia dois arquivos_q5, a.txt e b.txt, como a seguir: Seu programa deve somar elemento por elemento de cada arquivo e imprimir o resultado na tela. Isto é, o primeiro elemento de a.txt deve ser somado ao primeiro elemento de b.txt, segundo elemento de a.txt deve ser somado ao...
# 5. Escreva um programa em Python que leia dois arquivos_q5, a.txt e b.txt, como a seguir: Seu programa deve somar elemento por elemento de cada arquivo e imprimir o resultado na tela. Isto é, o primeiro elemento de a.txt deve ser somado ao primeiro elemento de b.txt, segundo elemento de a.txt deve ser somado ao segun...
Python
zaydzuhri_stack_edu_python
comment Counting Bits comment https://leetcode.com/problems/counting-bits/description/ class Approch1 extends object begin function __init__ self n begin set n = n set matrix = list comprehension list comprehension 0 for col in range n + 1 for row in range n + 1 set array = list comprehension 0 for i in range n + 1 end...
#Counting Bits #https://leetcode.com/problems/counting-bits/description/ class Approch1(object): def __init__(self, n): self.n = n self.matrix = [[0 for col in range(n+1)] for row in range(n+1)] self.array = [0 for i in range(n+1)]
Python
zaydzuhri_stack_edu_python
function _collapse_tuple_dicts iterable begin set temp = dict for i in iterable begin update temp i end return temp end function
def _collapse_tuple_dicts(iterable): temp = {} for i in iterable: temp.update(i) return temp
Python
nomic_cornstack_python_v1
import os import pandas as pd function main begin set id_eng_text_mapping_csv_path = string ../otzovik_csvs_translated_merged/all_reviews.csv set output_dir = string ../otzovik_csvs_translated_merged/fold_4 if not exists path output_dir begin make directories output_dir end set output_fname = string test.csv set output...
import os import pandas as pd def main(): id_eng_text_mapping_csv_path = r"../otzovik_csvs_translated_merged/all_reviews.csv" output_dir = r"../otzovik_csvs_translated_merged/fold_4" if not os.path.exists(output_dir): os.makedirs(output_dir) output_fname = r"test.csv" output_path = os.path...
Python
zaydzuhri_stack_edu_python
if string s in cat begin print string Found an 's' in a cat if cat == string sheba begin print string I found sheba end else begin print string some other cat end end else begin print string a cat without 's' end
if 's' in cat: print("Found an 's' in a cat") if cat == 'sheba': print("I found sheba") else: print("some other cat") else: print("a cat without 's'")
Python
zaydzuhri_stack_edu_python
function _draw_selection_frame self cr x1 y1 x2 y2 begin call _draw_region_frame cr x1 y1 x2 y2 end function
def _draw_selection_frame(self, cr, x1, y1, x2, y2): self._draw_region_frame(cr, x1, y1, x2, y2)
Python
nomic_cornstack_python_v1
function activate_persistence fake_mac tarip interface the_lease_time my_ip server_mac server_id begin comment Loop keeps the persistence active while true begin comment Generate a new id for the "session" with the server set some_xid = call randrange 5234 none 3 comment Time to wait until sending a req to renew the bi...
def activate_persistence(fake_mac, tarip, interface, the_lease_time, my_ip, server_mac, server_id): while(True): # Loop keeps the persistence active some_xid=random.randrange(5234, None, 3) # Generate a new id for the "session" with the server time_to_wait=the_lease_time/2 # Time to wait until...
Python
nomic_cornstack_python_v1
function mir_left data begin return append np data data at tuple Ellipsis slice : : - 1 axis=- 1 end function
def mir_left(data): return np.append(data,data[...,::-1],axis=-1)
Python
nomic_cornstack_python_v1
function process_log_data spark input_data output_data begin set log_data = join path input_data string log_data/*/*/*.json set df = json read log_data set df = filter page == string NextSong set users_table = call dropDuplicates call parquet join path output_data string users.parquet mode=string overwrite print string...
def process_log_data(spark, input_data, output_data): log_data = os.path.join(input_data, 'log_data/*/*/*.json') df = spark.read.json(log_data) df = df.filter(df.page=='NextSong') users_table = df.select( F.col('userId').alias('user_id'), F.col('firstName').alias('first_name'...
Python
nomic_cornstack_python_v1
function on_state_change self name target=none description=none enabled=none event_bus=none event_pattern=none rule_name=none schedule=none targets=none begin set options = call RuleProps description=description enabled=enabled event_bus=event_bus event_pattern=event_pattern rule_name=rule_name schedule=schedule target...
def on_state_change( self, name: str, target: typing.Optional[aws_cdk.aws_events.IRuleTarget] = None, *, description: typing.Optional[str] = None, enabled: typing.Optional[bool] = None, event_bus: typing.Optional[aws_cdk.aws_events.IEventBus] = None, event...
Python
nomic_cornstack_python_v1
comment . ``magma_console()`` - A function that dumps you into an interactive command-line Magma session. comment . ``magma.new(obj)`` and alternatively ``magma(obj)`` - Creation of a Magma object from a Sage object ``obj``.
#. ``magma_console()`` - A function that dumps you into an interactive command-line Magma session. #. ``magma.new(obj)`` and alternatively ``magma(obj)`` - Creation of a Magma object from a Sage object ``obj``.
Python
zaydzuhri_stack_edu_python
function norm self norm=none sparse=false tol=0 maxiter=100000 begin if type in list string oper string super begin if norm is none or norm == string tr begin set vals = call sp_eigs data isherm vecs=false sparse=sparse tol=tol maxiter=maxiter return sum square root absolute vals ^ 2 end else if norm == string fro begi...
def norm(self, norm=None, sparse=False, tol=0, maxiter=100000): if self.type in ['oper', 'super']: if norm is None or norm == 'tr': vals = sp_eigs(self.data, self.isherm, vecs=False, sparse=sparse, tol=tol, maxiter=maxiter) return np.sum...
Python
nomic_cornstack_python_v1
function grab_image self begin set tuple _ camera_image = read camera with lock begin set image = camera_image end end function
def grab_image(self): _, camera_image = self.camera.read() with self.lock: self.image = camera_image
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment Muestra las puntuaciones de una pelicula comment Librerias importadas import webapp2 from webapp2_extras import jinja2 from webapp2_extras.users import users from model.puntuacion import Puntuacion from google.appengine.ext import ndb class PuntuacionShowallHandler extends RequestHandler b...
# coding: utf-8 # Muestra las puntuaciones de una pelicula #Librerias importadas import webapp2 from webapp2_extras import jinja2 from webapp2_extras.users import users from model.puntuacion import Puntuacion from google.appengine.ext import ndb class PuntuacionShowallHandler(webapp2.RequestHandler): #...
Python
zaydzuhri_stack_edu_python
function get_sound_output_dev self nIndex begin return call handle_to_object call call_sdk_function string PrlSrvCfg_GetSoundOutputDev handle nIndex end function
def get_sound_output_dev(self, nIndex): return handle_to_object(call_sdk_function('PrlSrvCfg_GetSoundOutputDev', self.handle, nIndex))
Python
nomic_cornstack_python_v1
string Test the filters added to the jinja loader. from tiddlyweb.fixups import unquote from tiddlywebplugins.templates import uri , format_modified , rfc3339 function test_uri begin set encoded_name = string aaa%25%E3%81%86%E3%81%8F%E3%81%99 set name = unquote encoded_name assert call uri name == encoded_name end func...
""" Test the filters added to the jinja loader. """ from tiddlyweb.fixups import unquote from tiddlywebplugins.templates import uri, format_modified, rfc3339 def test_uri(): encoded_name = 'aaa%25%E3%81%86%E3%81%8F%E3%81%99' name = unquote(encoded_name) assert uri(name) == encoded_name def test_format...
Python
zaydzuhri_stack_edu_python
comment Prende in input il nome dell'algoritmo di clustering e la tipologia di embedding comment Come risultato genera nella cartella relativa all'algoritmo di cluster scelto (in Result_1_General) comment le volte in cui ogni coppia è stata inserita all'interno dello stesso cluster comment Infine dopo aver generato un ...
#Prende in input il nome dell'algoritmo di clustering e la tipologia di embedding # Come risultato genera nella cartella relativa all'algoritmo di cluster scelto (in Result_1_General) # le volte in cui ogni coppia è stata inserita all'interno dello stesso cluster # Infine dopo aver generato un file .csv del tipo couple...
Python
zaydzuhri_stack_edu_python
function string_between s before after begin if before is not none begin set t = split s before assert length t > 1 msg string "before" argument is not in the string! set s = t at 1 end if after is not none begin set t = split s after assert length t > 1 msg string "after" argument is not in the string! set s = t at 0 ...
def string_between(s, before, after): if before is not None: t = s.split(before) assert len(t) > 1, '"before" argument is not in the string!' s = t[1] if after is not None: t = s.split(after) assert len(t) > 1, '"after" argument is not in the string!' s = t[0] ...
Python
nomic_cornstack_python_v1
comment specify economies in the order that they should appear in parameter list in-game (and also in docs) comment economies have a numeric ID which maps parameter values and avoids breaking savegames when this list changes comment !! ^ that doesn't appear to work, action 14 param doesn't seem to be able to abstract n...
# specify economies in the order that they should appear in parameter list in-game (and also in docs) # economies have a numeric ID which maps parameter values and avoids breaking savegames when this list changes # !! ^ that doesn't appear to work, action 14 param doesn't seem to be able to abstract name value from nam...
Python
zaydzuhri_stack_edu_python
string Created on Feb 16, 2015 Contact: pachlioptas@gmail.com Copyright notice: Copyright (c) 2015, Panagiotis Achlioptas You are free to use, change, or redistribute this code in any way you want for non-commercial purposes only. import time import math import smtplib import numpy as np function p message=string begin...
''' Created on Feb 16, 2015 Contact: pachlioptas@gmail.com Copyright notice: Copyright (c) 2015, Panagiotis Achlioptas You are free to use, change, or redistribute this code in any way you want for non-commercial purposes only. ''' import time import math import smtplib import numpy as np def p(message=""): ''...
Python
zaydzuhri_stack_edu_python
function is_empty self board begin return call get_player board == PLAYER_NONE end function
def is_empty(self, board: np.ndarray): return self.get_player(board) == PLAYER_NONE
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Nov 30 16:33:45 2017 @author: User string (a) Write a function that prints the elements of a list (b) Write a function that prints the elements of a list in reverse (c) Write your own implementation of the len function set lst = list 0 1 2 3 4 5 6 7 8 9 set empty = li...
# -*- coding: utf-8 -*- """ Created on Thu Nov 30 16:33:45 2017 @author: User """ ''' (a) Write a function that prints the elements of a list (b) Write a function that prints the elements of a list in reverse (c) Write your own implementation of the len function ''' lst = [0,1,2,3,4,5,6,7,8,9] empty = ...
Python
zaydzuhri_stack_edu_python
function set_max_output_buffer self *args begin return call ber_sink_b_sptr_set_max_output_buffer self *args end function
def set_max_output_buffer(self, *args): return _qtgui_swig.ber_sink_b_sptr_set_max_output_buffer(self, *args)
Python
nomic_cornstack_python_v1
function install self release_id begin string Install the local artifact into the remote release directory, optionally with a different name than the artifact had locally. If the directory for the given release ID does not exist on the remote system, it will be created. The directory will be created according to the st...
def install(self, release_id): """Install the local artifact into the remote release directory, optionally with a different name than the artifact had locally. If the directory for the given release ID does not exist on the remote system, it will be created. The directory will be create...
Python
jtatman_500k
string * Copyright 2020, Departamento de sistemas y Computación * Universidad de Los Andes * * * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the ...
""" * Copyright 2020, Departamento de sistemas y Computación * Universidad de Los Andes * * * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by ...
Python
zaydzuhri_stack_edu_python
import sys import re call reload sys call setdefaultencoding string utf-8 for line in stdin begin try begin set tuple article_id text = split call unicode strip line string 1 end except ValueError as e begin continue end set text = sub string ^\W+|\W+$ string text flags=UNICODE end
import sys import re reload(sys) sys.setdefaultencoding('utf-8') for line in sys.stdin: try: article_id, text = unicode(line.strip()).split('\t',1) except ValueError as e: continue text = re.sub("^\W+|\W+$", "", text, flags=re.UNICODE)
Python
zaydzuhri_stack_edu_python
function get_value char begin set capital = upper char if capital in string ABCDEFGHIJKLMNOPQRSTUVWXYZ begin return index string ABCDEFGHIJKLMNOPQRSTUVWXYZ capital + 1 end else begin return 1 end end function function encode string begin pass end function function main begin pass end function if __name__ == string __ma...
def get_value(char): capital = char.upper() if capital in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.index(capital) + 1 else: return 1 def encode(string): pass def main(): pass if __name__ == '__main__': main()
Python
zaydzuhri_stack_edu_python
function search_google_places latitude longitude name begin set location = call fmt_location latitude longitude set name = call fmt_name name set url_params = dict string name name ; string key GOOGLE_API_KEY ; string types string food ; string location location ; string radius 3200 set place_url = list set place_obje...
def search_google_places(latitude, longitude, name): location = fmt_location(latitude, longitude) name = fmt_name(name) url_params = { 'name': name, 'key': GOOGLE_API_KEY, 'types': 'food', 'location': location, 'radius': 3200, } place_url = [] place_objec...
Python
nomic_cornstack_python_v1
import sqlite3 import sys import os from flask import Flask , json , request , render_template from time import gmtime , strftime import random function json_response string begin return call response_class response=format string {} replace string string string ' string " mimetype=string application/json end function f...
import sqlite3 import sys import os from flask import Flask, json, request, render_template from time import gmtime, strftime import random def json_response(string): return app.response_class( response="{}".format(str(string).replace("'", '"')), mimetype='application/json' ) def response_al...
Python
zaydzuhri_stack_edu_python
import math class Vector2 begin function __init__ self x=0 y=0 begin set x = x set y = y end function function magnitude self begin return square root x ^ 2 + y ^ 2 end function function normalized self begin set m = call magnitude if m == 0 begin return self end return call Vector2 x / m y / m end function function cr...
import math class Vector2: def __init__(self, x=0, y=0): self.x=x self.y=y def magnitude(self): return math.sqrt( ((self.x)**2) + ((self.y)**2) ) def normalized(self): m = self.magnitude() if m == 0: return self return Vector2(self.x/m, self.y/m) ...
Python
zaydzuhri_stack_edu_python
set array = list 2 10 5 8 1 sort array print string The largest two integers are: print array at - 1 array at - 2
array = [2, 10, 5, 8, 1] array.sort() print("The largest two integers are:") print(array[-1], array[-2])
Python
flytech_python_25k
comment coding: utf-8 comment #Integrate and fire study for the Phase Response Curve comment __Goal:__ Assess the effect of flat and phase dependent response curves in the overall synchronization of groups of neurons receiving common inputs. comment Joao Couto - jpcouto@gmail.com comment ### Find the external current f...
# coding: utf-8 # #Integrate and fire study for the Phase Response Curve # __Goal:__ Assess the effect of flat and phase dependent response curves in the overall synchronization of groups of neurons receiving common inputs. # # Joao Couto - jpcouto@gmail.com # # ### Find the external current for 30Hz firing freque...
Python
zaydzuhri_stack_edu_python
function test_filter_set_element3 self begin set test_filter = call run_filter_from_model keyword filter_set_element3 assert equal 1 length test_filter assert equal set literal 13 test_filter end function
def test_filter_set_element3(self): test_filter = utils.run_filter_from_model(**self.test.filter_set_element3) self.assertEqual(1, len(test_filter)) self.assertEqual({13}, test_filter)
Python
nomic_cornstack_python_v1
function __attach_question_to_comment self comment row language begin set key_question = call build_translation_question dimension=dimension_description week=question_week if language == lang_english begin set question = __questions_json_file_en at key_question end else begin set question = __questions_json_file_de at ...
def __attach_question_to_comment(self, comment: str, row: list, language: str) -> str: key_question = build_translation_question(dimension=row.dimension_description, week=row.question_week) if language == cons.lang_english: question = self.__questions_json_file_en[key_question] else:...
Python
nomic_cornstack_python_v1
function crosscorr map mask begin set cross = zeros tuple length map length map at 0 for j in range length map begin for i in range length map at 0 begin if j >= i begin set A = 0 for k in range length map at 0 begin set A = A + mean np map at j at i at mask == 1 * map at j at k at mask == 1 end set cross at j at i = A...
def crosscorr(map, mask): cross = np.zeros((len(map), len(map[0]))) for j in range(len(map)): for i in range(len(map[0])): if j>=i: A = 0 for k in range(len(map[0])): A += np.mean(map[j][i][mask==1]*map[j][k][mask==1]) cros...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import Model from tensorflow.keras.layers import Input , Reshape , ConvLSTM2D , Dense , MaxPooling2D , Conv2D , Activation , Dropout , BatchNormalization , Conv2DTranspose , concatenate , LSTM , Bidirectional function plot_history net_histo...
import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Reshape, ConvLSTM2D, Dense, MaxPooling2D, Conv2D, Activation, \ Dropout, BatchNormalization, Conv2DTranspose, concatenate, LSTM, Bidirectional def plot_history(net_history): ...
Python
zaydzuhri_stack_edu_python
function find a b c begin comment a=1stside comment b=2ndside comment c=3rdside set count = 0 if a + b >= c begin set count = count + 1 end if a + c >= b begin set count = count + 1 end if b + c > a begin set count = count + 1 end if count >= 2 begin print string its a triangle!! end else begin print string its not a t...
def find(a,b,c): #a=1stside #b=2ndside #c=3rdside count=0 if(a+b>=c): count=count+1 if(a+c>=b): count=count+1 if(b+c>a): count=count+1 if(count>=2): print("its a triangle!!\n") else:print("its not a triangle!!\n") find(a=input(),b=input(),c=input())
Python
zaydzuhri_stack_edu_python
function draw_image self image begin try begin append _images call PhotoImage file=image + string .png end except TclError begin append _images call PhotoImage file=image + string .gif end return call create_image left_side + CARD_WIDTH // 2 top_side + CARD_HEIGHT // 2 image=_images at - 1 end function
def draw_image(self, image): try: self._images.append(tk.PhotoImage(file=image + ".png")) except tk.TclError: self._images.append(tk.PhotoImage(file=image + ".gif")) return self._canvas.create_image(self.left_side + (CARD_WIDTH // 2), ...
Python
nomic_cornstack_python_v1
function __init__ self df begin set df = df end function
def __init__(self, df): self.df = df
Python
nomic_cornstack_python_v1
function update_cv_stats self model begin set tuple cv_acc cv_loss outputs_dist targets_dist = call _get_cv_stats model call add_scalar string Loss/cv cv_loss step call add_scalar string Acc/cv cv_acc step call add_histogram string Outputs/cv outputs_dist step if _first_run begin call add_histogram string Outputs/cv ta...
def update_cv_stats(self, model: torch.nn) -> None: cv_acc, cv_loss, outputs_dist, targets_dist = self._get_cv_stats(model) self.writer.add_scalar("Loss/cv", cv_loss, self.step) self.writer.add_scalar("Acc/cv", cv_acc, self.step) self.writer.add_histogram("Outputs/cv", outputs_dist, self...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt function draw times algorithms name begin set x = range length times set rects1 = bar x height=times width=0.4 alpha=0.8 color=string red comment y轴取值范围 call ylim 0 130 y label name call xticks list comprehension index + 0.2 for index in x algorithms x label string Algorithm title plt st...
import matplotlib.pyplot as plt def draw(times, algorithms, name): x = range(len(times)) rects1 = plt.bar(x, height=times, width=0.4, alpha=0.8, color='red') plt.ylim(0, 130) # y轴取值范围 plt.ylabel(name) plt.xticks([index + 0.2 for index in x], algorithms) plt.xlabel("Alg...
Python
zaydzuhri_stack_edu_python
string Given a dictionary of elements: mydict = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5} print the sequence of elements in the following fashion: {'n':1,'w':2,'r':3,'ou':4,'iv':5} set mydict = dict string one 1 ; string two 2 ; string three 3 ; string four 4 ; string five 5 function doop mydict begin if length...
""" Given a dictionary of elements: mydict = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5} print the sequence of elements in the following fashion: {'n':1,'w':2,'r':3,'ou':4,'iv':5} """ mydict = {'one':1, 'two':2, ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import matplotlib.patches as patches import sys append path string . from spline_math import get_free_spline , get_hermite_spline comment GRAPH SETTINGS set fig = figure call set_window_title string Splines set ax = call add_subplot 111 call set_axisbelow true call set_aspect string equa...
import matplotlib.pyplot as plt import matplotlib.patches as patches import sys sys.path.append(".") from spline_math import get_free_spline, get_hermite_spline # GRAPH SETTINGS fig = plt.figure() fig.canvas.set_window_title('Splines') ax = fig.add_subplot(111) ax.set_axisbelow(True) ax.set_aspect('equal') plt.grid(T...
Python
zaydzuhri_stack_edu_python
function granger_causality self sample_dict begin set A_all = 0 set all_types = sample_dict at string Cs at tuple slice : : 0 set all_features = sample_dict at string FCs if all_features is none begin set all_features = call emb_event all_types end for m in range num_base begin set u_all = call all_types set A_tmp =...
def granger_causality(self, sample_dict: Dict): A_all = 0 all_types = sample_dict['Cs'][:, 0] all_features = sample_dict['FCs'] if all_features is None: all_features = self.emb_event(all_types) for m in range(self.num_base): u_all = self.basis[m](all_types...
Python
nomic_cornstack_python_v1
function __str__ self begin return string %r %r %r % tuple v end function
def __str__(self): return "%r %r %r" % tuple(self.v)
Python
nomic_cornstack_python_v1
comment N×N크기의 행렬로 표현되는 종이가 있다. comment 종이의 각 칸에는 -1, 0, 1의 세 값 중 하나가 저장되어 있다. comment 우리는 이 행렬을 적절한 크기로 자르려고 하는데, comment 이때 다음의 규칙에 따라 자르려고 한다. comment 1. 만약 종이가 모두 같은 수로 되어 있다면 이 종이를 그대로 사용한다. comment 2. (1)이 아닌 경우에는 종이를 같은 크기의 9개의 종이로 자르고, comment 각각의 잘린 종이에 대해서 (1)의 과정을 반복한다. comment 이와 같이 종이를 잘랐을 때, -1로만 채워진 종이의 ...
# N×N크기의 행렬로 표현되는 종이가 있다. # 종이의 각 칸에는 -1, 0, 1의 세 값 중 하나가 저장되어 있다. # 우리는 이 행렬을 적절한 크기로 자르려고 하는데, # 이때 다음의 규칙에 따라 자르려고 한다. # # 1. 만약 종이가 모두 같은 수로 되어 있다면 이 종이를 그대로 사용한다. # 2. (1)이 아닌 경우에는 종이를 같은 크기의 9개의 종이로 자르고, # 각각의 잘린 종이에 대해서 (1)의 과정을 반복한다. # 이와 같이 종이를 잘랐을 때, -1로만 채워진 종이의 개수, # 0으로만 채워진 종이의 개수, 1로만 채워진 종이의 개수를 구해내는 프로...
Python
zaydzuhri_stack_edu_python
comment Sam Cole comment This is the last in first out from Stack import Stack comment this is the menu set totalstock = stack set totalmoney = stack set profit = 0 set answer = 0 while answer != 4 begin print string Please type the number to select what you would like to do 1.buy stock 2.sell stock 3.see your profit 4...
# Sam Cole # This is the last in first out from Stack import Stack # this is the menu totalstock = Stack() totalmoney = Stack() profit = 0 answer = 0 while answer != 4: print("""Please type the number to select what you would like to do 1.buy stock 2.sell stock 3.see your profit...
Python
zaydzuhri_stack_edu_python
if BMI < 18.5 begin print string Too light end else if BMI > 18.5 and BMI < 25 begin print string Normal end else if BMI > 25 and BMI < 28 begin print string Overweight end else if BMI > 28 and BMI < 32 begin print string Too Fat end else if BMI > 32 begin print string Severe Obesity end else begin print string Wrong! ...
if BMI < 18.5: print('Too light') elif BMI > 18.5 and BMI <25: print('Normal') elif BMI > 25 and BMI <28: print('Overweight') elif BMI >28 and BMI < 32: print('Too Fat') elif BMI > 32: print('Severe Obesity') else: print('Wrong!')
Python
zaydzuhri_stack_edu_python
from selenium import webdriver import os import time from urllib.parse import unquote from selenium.webdriver.chrome.options import Options comment Create the CoinBot Class class LinkedInBot begin comment Create a constant that contains the default text for the message set BOT_BLOCK = dict string type string section ; ...
from selenium import webdriver import os import time from urllib.parse import unquote from selenium.webdriver.chrome.options import Options # Create the CoinBot Class class LinkedInBot: # Create a constant that contains the default text for the message BOT_BLOCK = { "type": "section", "text": ...
Python
zaydzuhri_stack_edu_python
from django.test import TestCase from models import Item comment Create your tests here. class TestHome extends TestCase begin comment Test to see if url is valid - i.e. returns 200. function test_root_is_valid_url self begin set resp = get client string / assert equal status_code 200 end function comment Test to see i...
from django.test import TestCase from .models import Item # Create your tests here. class TestHome(TestCase): # Test to see if url is valid - i.e. returns 200. def test_root_is_valid_url(self): resp = self.client.get("/") self.assertEqual(resp.status_code, 200) # Test to see if page used...
Python
zaydzuhri_stack_edu_python
function Rank A b begin set rank = true for i in range 0 length A begin set check_row = 0 for j in range 0 length A begin if A at i at j == 0 begin set check_row = check_row + 1 end end if check_row == length A begin set rank = false break end end comment note: checked function return rank end function
def Rank(A, b): rank = True for i in range(0, len(A)): check_row = 0 for j in range(0, len(A)): if A[i][j] == 0: check_row += 1 if check_row == len(A): rank = False break return rank #note: checked function
Python
nomic_cornstack_python_v1
function fit_gds_double_sided_skewed zi rho_zi zmax=400 plot=true verbose=true begin from lmfit import Parameters , Model , report_fit comment zi_filter = zi[rho_zi>0] comment rho_filter = rho_zi[rho_zi>0] set zi_filter = zi set rho_filter = rho_zi set params = parameters add params string z0 value=30 min=0 max=zmax va...
def fit_gds_double_sided_skewed(zi,rho_zi,zmax = 400,plot=True,verbose=True): from lmfit import Parameters, Model, report_fit # zi_filter = zi[rho_zi>0] # rho_filter = rho_zi[rho_zi>0] zi_filter = zi rho_filter = rho_zi params = Parameters() params.add('z0', value=30,min = 0, max = zmax,vary...
Python
nomic_cornstack_python_v1
comment len - Length of strings set greet = string hellooooooooooo print length greet print upper greet print capitalize greet print find greet string ll
# len - Length of strings greet = "hellooooooooooo" print(len(greet)) print(greet.upper()) print(greet.capitalize()) print(greet.find("ll"))
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python class A begin function __init__ self a begin set a = a end function function calc self begin for i in range a begin print i end end function end class set a = call A 10 call calc
#!/usr/bin/python class A: def __init__(self,a): self.a=a def calc(self): for i in range(self.a): print(i) a=A(10) a.calc()
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import os import pygame import sys import time comment 디렉토리 안 파일 목록 가져오기 set PATH_DIR = string /Users/ParkJinYoung/Desktop/cs/images comment state 변화 상수 set CHANGE_TIME = 7000 comment global variable set imgList = list set idxCurrImage = 0 set idxNextImage = 0 comment pygame 설정 call init ...
## # -*- coding: utf-8 -*- import os import pygame import sys import time #디렉토리 안 파일 목록 가져오기 PATH_DIR = '/Users/ParkJinYoung/Desktop/cs/images' #state 변화 상수 CHANGE_TIME = 7000 #global variable imgList = [] idxCurrImage = 0 idxNextImage = 0 #pygame 설정 pygame.init() DISPLAYSURF = pygame.display....
Python
zaydzuhri_stack_edu_python
from main import example try begin comment python 3 import tkinter as tk comment python 3 from tkinter import font as tkfont end except ImportError begin comment python 2 import Tkinter as tk comment python 2 import tkFont as tkfont end class PageFour extends Frame begin function __init__ self parent controller begin c...
from main import example try: import tkinter as tk # python 3 from tkinter import font as tkfont # python 3 except ImportError: import Tkinter as tk # python 2 import tkFont as tkfont # python 2 class PageFour(tk.Frame): def __init__(self, parent, controller): tk.Frame...
Python
zaydzuhri_stack_edu_python
function session_preparation self begin call _test_channel_read call set_base_prompt end function
def session_preparation(self): self._test_channel_read() self.set_base_prompt()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from tkinter import * function draw x1 y1 x2 y2 x3 y3 begin set tuple x1 y1 = tuple ox + x1 oy - y1 set tuple x2 y2 = tuple ox + x2 oy - y2 set tuple x3 y3 = tuple ox + x3 oy - y3 call create_polygon x1 y1 x2 y2 x3 y3 fill=string white outline=string black end function function shear x y b...
# -*- coding: utf-8 -*- from tkinter import * def draw(x1,y1,x2,y2,x3,y3): x1,y1=ox+x1,oy-y1 x2,y2=ox+x2,oy-y2 x3,y3=ox+x3,oy-y3 w.create_polygon(x1,y1,x2,y2,x3,y3,fill='white',outline='black') def shear(x,y): Sh_x= [[1, Shx, 0], [0, 1, 0], [0, 0, 1]] Sh_y= [[1, 0, 0], [Shy, 1, 0], [0, 0, 1]] ...
Python
zaydzuhri_stack_edu_python
function dense_activation_propagate a_prev w b activation begin set tuple z dense_cache = call dense_layer_propagate a_prev w b if activation == string sigmoid begin set tuple a activation_cache = sigmoid z end else if activation == string relu begin set tuple a activation_cache = relu z end else if activation == strin...
def dense_activation_propagate(a_prev, w, b, activation): z, dense_cache = dense_layer_propagate(a_prev, w, b) if activation == 'sigmoid': a, activation_cache = sigmoid(z) elif activation == 'relu': a, activation_cache = relu(z) elif activation == 'softmax': a, activation_cache ...
Python
nomic_cornstack_python_v1
function start self timeout=none root_object=none begin if _is_running begin return end if timeout begin set _timeout = timeout set _start_time = integer time end debug string [NURESTPushCenter] Starting push center on url %s ... % url set _is_running = true set __root_object = root_object from nurest_session import NU...
def start(self, timeout=None, root_object=None): if self._is_running: return if timeout: self._timeout = timeout self._start_time = int(time()) pushcenter_logger.debug("[NURESTPushCenter] Starting push center on url %s ..." % self.url) self._is_runn...
Python
nomic_cornstack_python_v1
function test_invite_to_team__user_openinvite self begin set member_status at string isMember = false set invite_body = dict string inviteeId userid with call object syn string get_membership_status return_value=member_status as patch_getmem ; call object syn string get_team_open_invitations return_value=list invite_bo...
def test_invite_to_team__user_openinvite(self): self.member_status["isMember"] = False invite_body = {"inviteeId": self.userid} with patch.object( self.syn, "get_membership_status", return_value=self.member_status ) as patch_getmem, patch.object( self.syn, "get_te...
Python
nomic_cornstack_python_v1
function cleanup target begin set dirs_to_clean = list join path target string image string modules join path target string image string repos join path target string repo for d in dirs_to_clean begin if exists path d begin debug string Removing dirty directory: '%s' % d remove tree d end end end function
def cleanup(target): dirs_to_clean = [os.path.join(target, 'image', 'modules'), os.path.join(target, 'image', 'repos'), os.path.join(target, 'repo')] for d in dirs_to_clean: if os.path.exists(d): logger.debug("Removing dirty directory: '%s'" % d) ...
Python
nomic_cornstack_python_v1
async function get self target begin return await call request method=string GET target=target end function
async def get(self, target): return await self.request( method="GET", target=target, )
Python
nomic_cornstack_python_v1
function configure_apispec app begin pass end function
def configure_apispec(app): pass
Python
nomic_cornstack_python_v1
comment 16. Write a Python program to convert a tuple to a dictionary. function zamiana krotka słownik begin for tuple a b in krotka begin append set default słownik a list b end return słownik end function set krotka = list tuple string Tola 10 tuple string Bolek 5 tuple string Lolek 3 set słownik = dict print call z...
# 16. Write a Python program to convert a tuple to a dictionary. def zamiana (krotka, słownik): for a, b in krotka: słownik.setdefault(a, []).append(b) return słownik krotka = [('Tola', 10), ('Bolek', 5), ('Lolek', 3)] słownik = {} print (zamiana (krotka, słownik))
Python
zaydzuhri_stack_edu_python
function MaybePrependToHeader header value begin set tuple header value = call _EncodeHeader header value function _MaybePrependToHeader request begin string Maybe prepends a value to a header on a request. set headers = headers set current_value = b'' for tuple hdr v in call iteritems headers begin if lower hdr == low...
def MaybePrependToHeader(header, value): header, value = _EncodeHeader(header, value) def _MaybePrependToHeader(request): """Maybe prepends a value to a header on a request.""" headers = request.headers current_value = b'' for hdr, v in six.iteritems(headers): if hdr.lower() == header.lower()...
Python
nomic_cornstack_python_v1
import string function vertical_histogram_of s begin string Display a vertical histogram of occurences of uppercase letters in strings. See also: https://www.codewars.com/kata/59cf0ba5d751dffef300001f set letter_count = dictionary comprehension letter : count s letter for letter in ascii_uppercase if letter in s set hi...
import string def vertical_histogram_of(s): """ Display a vertical histogram of occurences of uppercase letters in strings. See also: https://www.codewars.com/kata/59cf0ba5d751dffef300001f """ letter_count = {letter: s.count(letter) for letter in string.ascii_uppercase if letter in s} hist = "...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import scrapy class IndiaStatesSpider extends Spider begin set name = string india_states set allowed_domains = list string www.mohfw.gov.in set start_urls = list string http://www.mohfw.gov.in/ function parse self response begin set rows = call xpath string //table[@class='table table-str...
# -*- coding: utf-8 -*- import scrapy class IndiaStatesSpider(scrapy.Spider): name = 'india_states' allowed_domains = ['www.mohfw.gov.in'] start_urls = ['http://www.mohfw.gov.in/'] def parse(self, response): rows = response.xpath("//table[@class='table table-striped']/tbody/tr[position()<=33]...
Python
zaydzuhri_stack_edu_python
function getInterfaceVersion self begin set version = call dispatcher string getInterfaceVersion return version end function
def getInterfaceVersion(self): version = self.dispatcher( 'getInterfaceVersion' ) return version
Python
nomic_cornstack_python_v1
async function gImage self ctx query num=1 begin set imageKey = string set f = open string secrets.txt string r set imageKey = strip read lines f at 1 close f set webpage = string https://www.googleapis.com/customsearch/v1?cx=013629950505680552901%3Axac8ijijt08&searchType=image&key= + imageKey + string &q= + replace q...
async def gImage(self, ctx, query, num=1): imageKey = "" f = open("secrets.txt", "r") imageKey = f.readlines()[1].strip() f.close() webpage = "https://www.googleapis.com/customsearch/v1?cx=013629950505680552901%3Axac8ijijt08&searchType=image&key=" + imageKey + "&q=" + query....
Python
nomic_cornstack_python_v1
function has_object_permission self request view obj begin return operator == operator and now - created_at <= PARKINGS_TIME_EDITABLE end function
def has_object_permission(self, request, view, obj): return request.user.operator == obj.operator and (now() - obj.created_at) <= settings.PARKINGS_TIME_EDITABLE
Python
nomic_cornstack_python_v1
import torch class FullConnectNet extends Module begin function __init__ self input_size hidden_size num_classes begin call __init__ set layer1 = sequential linear input_size hidden_size relu inplace=true set layer2 = linear hidden_size num_classes end function function forward self x begin set out = call layer1 x set ...
import torch class FullConnectNet(torch.nn.Module): def __init__(self, input_size, hidden_size, num_classes): super(FullConnectNet, self).__init__() self.layer1 = torch.nn.Sequential( torch.nn.Linear(input_size, hidden_size), torch.nn.ReLU(inplace=True) ) ...
Python
zaydzuhri_stack_edu_python
import bisect set N = integer input set W = list comprehension integer input for i in range N set ds = list W at 0 for w in W at slice 1 : : begin set i = call bisect_left ds w if i == length ds begin append ds w end else begin set ds at i = w end end print length ds
import bisect N = int(input()) W = [int(input()) for i in range(N)] ds = [W[0]] for w in W[1:]: i = bisect.bisect_left(ds,w) if i == len(ds): ds.append(w) else: ds[i] = w print(len(ds))
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding=UTF8 string 生成静态iatacode与城市中文名、城市拼音的map import db import json import sys call reload sys call setdefaultencoding string utf-8 set wfile = open string city_dict string w set sql = string SELECT * FROM airport WHERE 1 set results = call QueryBySQL sql set dict1 = dict set dict...
#!/usr/bin/env python #coding=UTF8 ''' 生成静态iatacode与城市中文名、城市拼音的map ''' import db import json import sys reload(sys) sys.setdefaultencoding('utf-8') wfile = open('city_dict','w') sql = "SELECT * FROM airport WHERE 1" results = db.QueryBySQL(sql) dict1 = { } dict2 = { } dict3 = { } for result in results: ...
Python
zaydzuhri_stack_edu_python
function test_filter self begin set credentials = call Mock base_url=string set manager = manager string contacts credentials set tuple uri params method body headers singleobject = call _filter order=string LastName page=2 offset=5 since=call datetime 2014 8 10 15 14 46 Name=string John assert equal method string get ...
def test_filter(self): credentials = Mock(base_url="") manager = Manager('contacts', credentials) uri, params, method, body, headers, singleobject = manager._filter( order="LastName", page=2, offset=5, since=datetime.datetime(2014,...
Python
nomic_cornstack_python_v1
import sys import random from scipy.stats import spearmanr function sgRNA2ref raw_sgRNA_list sgRNA_DB sampling_num begin set sgRNA_num2count = dictionary set tmp_sgRNA_sampling = random choices raw_sgRNA_list k=sampling_num for tmp_sgRNA in tmp_sgRNA_sampling begin if tmp_sgRNA in sgRNA_DB begin set tmp_sgRNA_num = sgR...
import sys import random from scipy.stats import spearmanr def sgRNA2ref(raw_sgRNA_list, sgRNA_DB,sampling_num): sgRNA_num2count = dict() tmp_sgRNA_sampling = random.choices(raw_sgRNA_list, k = sampling_num) for tmp_sgRNA in tmp_sgRNA_sampling: if tmp_sgRNA in sgRNA_DB: tmp_sgRNA_num = ...
Python
zaydzuhri_stack_edu_python
function __le__ self other begin return if expression is instance other Multipoint then _points_set <= _points_set else NotImplemented end function
def __le__(self, other: Compound[Scalar]) -> bool: return (self._points_set <= other._points_set if isinstance(other, Multipoint) else NotImplemented)
Python
nomic_cornstack_python_v1