code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function get_profile raw_profile begin set profile = copy np raw_profile set profile at tuple slice : : 1 = profile at tuple slice : : 1 * 1.0 / sum profile at tuple slice : : 1 return profile end function
def get_profile(raw_profile): profile = np.copy(raw_profile) profile[:,1] *= 1.0/sum(profile[:,1]) return profile
Python
nomic_cornstack_python_v1
function get_friendliness self begin set trait = call get_friendliness name set friendliness = trait at 1 return friendliness end function
def get_friendliness(self): trait = self.traitDao.get_friendliness(self.name) friendliness = trait[1] return friendliness
Python
nomic_cornstack_python_v1
string 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 import csv with open string texts.csv string r as f begin set reader = reader f set texts = list reader end with open string calls.csv string r as f begin set reader = reader f set calls = list reader end comment def count_number(textfile,callfile): comment targ...
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) # def count_number(textfile,callfile): # target= set() # for ele1 in...
Python
zaydzuhri_stack_edu_python
function _update_tree force_dpid=none begin comment Get a spanning tree set tree = call _calc_spanning_tree debug string Spanning tree updated comment Connections born before this time are old enough that a complete comment discovery cycle should have completed (and, thus, all of their comment links should have been di...
def _update_tree(force_dpid=None): # Get a spanning tree tree = _calc_spanning_tree() log.debug("Spanning tree updated") # Connections born before this time are old enough that a complete # discovery cycle should have completed (and, thus, all of their # links should have been discovered). enable_time =...
Python
nomic_cornstack_python_v1
from visualization_msgs.msg import Marker from geometry_msgs.msg import Point function create_point x=0 y=0 z=0 begin set pt1 = call Point set x = x set y = y set z = z return pt1 end function string Points are in the form of [[px1,py1,pz1],[px2,py2,pz2]...], and has to be in the correct order for NOW. #TODO: add Conve...
from visualization_msgs.msg import Marker from geometry_msgs.msg import Point def create_point(x=0,y=0,z=0): pt1=Point() pt1.x = x pt1.y = y pt1.z = z return pt1 """ Points are in the form of [[px1,py1,pz1],[px2,py2,pz2]...], and has to be in the correct order for NOW. #TODO: add Convex Hull """ clas...
Python
zaydzuhri_stack_edu_python
function tokenize_lemmatize column min_word_len=2 begin set nlp = load spacy string en disable=list string tagger string parser string ner set docs = call tolist function token_filter token begin return not is_punct ? is_space and length text >= min_word_len end function set filtered_tokens = list for doc in call pipe...
def tokenize_lemmatize(column, min_word_len=2): nlp = spacy.load('en', disable=['tagger', 'parser', 'ner']) docs = column.tolist() def token_filter(token): return not (token.is_punct | token.is_space) and (len(token.text) >= min_word_len) filtered_tokens = [] for doc in nlp.pipe(docs): ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Apr 11 09:54:40 2019 @author: yael import numpy as np import pandas as pd import matplotlib.pyplot as plt comment 1. comment We are going along the instructions from the following link: comment http://machinelearningmastery.com/naive-baye...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 11 09:54:40 2019 @author: yael """ import numpy as np import pandas as pd import matplotlib.pyplot as plt #1. #We are going along the instructions from the following link: #http://machinelearningmastery.com/naive-bayes-classifier-scratch-python/ #...
Python
zaydzuhri_stack_edu_python
if szam begin 2 end print string ez a szam paros?
if szam : 2 print('ez a szam paros?')
Python
zaydzuhri_stack_edu_python
import ReservationModel as rm import ReservationView as rv import Lapangan as lp class ReservasiController begin function __init__ self begin set modeluser = call ReservasiModel set view = call ReservasiView set modelresv = call ReservasiLapangan end function function list self begin call printReservasiDetail call getN...
import ReservationModel as rm import ReservationView as rv import Lapangan as lp class ReservasiController: def __init__(self): self.modeluser = rm.ReservasiModel() self.view = rv.ReservasiView() self.modelresv = lp.ReservasiLapangan() def list(self): self.view.printReservasiDetail(self.modeluser.getNamaPem...
Python
zaydzuhri_stack_edu_python
function state self begin if is instance _state float begin return string round _state 2 end return _state end function
def state(self) -> str: if isinstance(self._state, float): return str(round(self._state, 2)) return self._state
Python
nomic_cornstack_python_v1
function compose_mail_json self msg begin set correo = dict try begin set correo at string From = call get_all string from list at 0 set correo at string Subject = call decode_header msg set texto = call get_body_mail msg set texto = sub string = string texto set urls_all = list set urls = find all string http[s]?:/...
def compose_mail_json(self, msg): correo = {} try: correo["From"] = msg.get_all("from", [])[0] correo["Subject"] = self.decode_header(msg) texto = self.get_body_mail(msg) texto = re.sub("=\r\n", "", texto) urls_all = [] urls = re.fi...
Python
nomic_cornstack_python_v1
function order_by cls *args begin return call order_by *args end function
def order_by(cls, *args): return cls.query.order_by(*args)
Python
nomic_cornstack_python_v1
class Solution extends object begin function addBinary self a b begin string This example demonstrates how to convert integer to binary and vice versa. :type a: str :type b: str :rtype: str return binary integer a 2 + integer b 2 at slice 2 : : end function end class print call addBinary string 100 string 001
class Solution(object): def addBinary(self, a, b): """ This example demonstrates how to convert integer to binary and vice versa. :type a: str :type b: str :rtype: str """ return bin(int(a, 2) + int(b, 2))[2:] print(Solution().addBinary("100", "001")...
Python
zaydzuhri_stack_edu_python
function _scroll_plot2 images names init_z begin set fig = figure figsize=tuple 12 6 set ax1 = call add_subplot 121 set ax2 = call add_subplot 122 sharex=ax1 sharey=ax1 set scroller = call Scroller list ax1 ax2 images names init_z call mpl_connect string scroll_event onscroll tight layout return scroller end function
def _scroll_plot2(images, names, init_z): fig = plt.figure(figsize=(12, 6)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122, sharex=ax1, sharey=ax1) scroller = Scroller([ax1, ax2], images, names, init_z) fig.canvas.mpl_connect('scroll_event', scroller.onscroll) fig.tight_layout() retur...
Python
nomic_cornstack_python_v1
from Errors.Exceptions import RepoError class Repository begin function __init__ self begin set _entities = list end function function add self elem begin if elem in _entities begin raise call RepoError string Id already exists! end append _entities elem end function function get_all self begin return _entities at sli...
from Errors.Exceptions import RepoError class Repository: def __init__(self): self._entities = [] def add(self, elem): if elem in self._entities: raise RepoError("Id already exists!\n") self._entities.append(elem) def get_all(self): return self._entities[:] ...
Python
zaydzuhri_stack_edu_python
function read_csv csv_file ext=string .csv format=none delete_empty_keys=false fieldnames=list rowlimit=100000000 numbers=false normalize_names=true unique_names=true verbosity=0 begin if not csv_file begin return end if is instance csv_file basestring begin comment truncate `csv_file` in case it is a string buffer co...
def read_csv(csv_file, ext='.csv', format=None, delete_empty_keys=False, fieldnames=[], rowlimit=100000000, numbers=False, normalize_names=True, unique_names=True, verbosity=0): if not csv_file: return if isinstance(csv_file, basestring): # truncate `csv_file` in case i...
Python
nomic_cornstack_python_v1
import math set sum = 0 for i in range 1000 begin set sum = sum + i ^ i end set sum = string sum
import math sum = 0 for i in range(1000): sum += i ** i sum = str(sum)
Python
zaydzuhri_stack_edu_python
function get_number_of_searches timeframe partner premium begin set timeframe_is = call get_date timeframe set result = count filter partner_id == partner return result end function
def get_number_of_searches(timeframe, partner, premium): timeframe_is = get_date(timeframe) result = (premium.filter(premium.keen.timestamp >= timeframe_is) .filter(premium.search_info.partner_id == partner) .count()) return result
Python
nomic_cornstack_python_v1
function _sense_pulse self is_space begin set start = now while is_active is is_space begin comment timed out, return nothing if call total_seconds >= MAX_PULSE_READ begin return none end if expression is_space then call off else call on end return call Pulse call total_seconds is_space end function
def _sense_pulse(self, is_space): start = datetime.now() while self.sensor.is_active is is_space: # timed out, return nothing if (datetime.now() - start).total_seconds() >= self.MAX_PULSE_READ: return None self.led.off() if is_space else self.led.on() ...
Python
nomic_cornstack_python_v1
function get_table_ddl self begin if not has attribute self string name or name == none begin raise call AttributeError string Table does not have a name end set ddl_strings = list string CREATE TABLE + name set in_columns = false set cols = list values columns sort cols for column in cols begin if in_columns begin app...
def get_table_ddl(self): if not hasattr(self, 'name') or self.name == None: raise AttributeError("Table does not have a name") ddl_strings = ["CREATE TABLE " + self.name] in_columns = False cols = list(self.columns.values()) cols.sort() for column in cols: ...
Python
nomic_cornstack_python_v1
function get_barcode_results_v2 barcode session begin debug string Exporting presence/absence results for < { barcode } > set results = call fetch_barcode_results session barcode return call jsonify results end function
def get_barcode_results_v2(barcode, session): LOG.debug(f"Exporting presence/absence results for <{barcode}>") results = datastore.fetch_barcode_results(session, barcode) return jsonify(results)
Python
nomic_cornstack_python_v1
function log_suppression self timestamp begin set repeats = repeats + 1 if timestamp > timestamp begin set timestamp = timestamp end save end function
def log_suppression(self, timestamp): self.repeats += 1 if timestamp > self.timestamp: self.timestamp = timestamp self.save()
Python
nomic_cornstack_python_v1
function __load_profiles self profiles_folder begin set __profiles = list comprehension join path profiles_folder x for x in next walk profiles_folder at 1 if length __profiles == 0 begin debug string No profiles available end end function
def __load_profiles(self, profiles_folder: str): self.__profiles = [os.path.join(profiles_folder, x) for x in next(os.walk(profiles_folder))[1]] if len(self.__profiles) == 0: logging.debug("No profiles available")
Python
nomic_cornstack_python_v1
string Question Description :- Merge Intervals Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10...
''' Question Description :- Merge Intervals Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] ...
Python
zaydzuhri_stack_edu_python
function SheetNext self begin return call InvokeTypes 20 LCID 1 tuple 24 0 tuple end function
def SheetNext(self): return self._oleobj_.InvokeTypes(20, LCID, 1, (24, 0), (),)
Python
nomic_cornstack_python_v1
function value_contains self value_contains begin set _value_contains = value_contains end function
def value_contains(self, value_contains): self._value_contains = value_contains
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 function main begin set T = integer input for t in range 1 T + 1 begin set N = integer input set V = list map int split input set W = list sorted V at slice : : 2 sorted V at slice 1 : : 2 set res = none for i in range N - 1 begin if W at i % 2 at i // 2 > W at i + 1 % 2 at i + 1 // 2 b...
#!/usr/bin/env python3 def main(): T = int(input()) for t in range(1,T+1): N = int(input()) V = list(map(int,input().split())) W = [sorted(V[::2]),sorted(V[1::2])] res = None for i in range(N-1): if W[i%2][i//2]>W[(i+1)%2][(i+1)//2]: res = i ...
Python
zaydzuhri_stack_edu_python
function _fetch_router_info self router_ids=none device_ids=none all_routers=false begin string Fetch router dict from the routing plugin. :param router_ids: List of router_ids of routers to fetch :param device_ids: List of device_ids whose routers to fetch :param all_routers: If True fetch all the routers for this age...
def _fetch_router_info(self, router_ids=None, device_ids=None, all_routers=False): """Fetch router dict from the routing plugin. :param router_ids: List of router_ids of routers to fetch :param device_ids: List of device_ids whose routers to fetch :param all_r...
Python
jtatman_500k
comment !/usr/bin/env python3 comment -*- conding: utf-8 -*- import sys from collections import namedtuple set TaxRateQuickDeductionItem = named tuple string TaxRateQuickDeductionItem list string start_point string tax_rete string qucik_deduction set TAX_RATE_START_POINT = 3500 set TAX_QUICK_LOOKUP_TABLE = list call Ta...
#!/usr/bin/env python3 # -*- conding: utf-8 -*- import sys from collections import namedtuple TaxRateQuickDeductionItem = namedtuple( 'TaxRateQuickDeductionItem', ['start_point','tax_rete','qucik_deduction'] ) TAX_RATE_START_POINT = 3500 TAX_QUICK_LOOKUP_TABLE = [ TaxRateQuickDeductionItem(80000,0.45,13...
Python
zaydzuhri_stack_edu_python
import pandas as pd from splinter import Browser from bs4 import BeautifulSoup as soup from datetime import datetime as dt function scrape_all begin comment Create executable path for chromedriver set executable_path = dict string executable_path string chromedriver.exe set browser = call Browser string chrome keyword ...
import pandas as pd from splinter import Browser from bs4 import BeautifulSoup as soup from datetime import datetime as dt def scrape_all(): # Create executable path for chromedriver executable_path = {'executable_path': 'chromedriver.exe'} browser = Browser('chrome', **executable_path, headless=True) ...
Python
zaydzuhri_stack_edu_python
from random import randint , randrange print random integer 0 10 comment range 0-99 print call randrange 100 comment a bal számot sosem generálja le print call randrange 0 6 + 1
from random import randint, randrange print(randint(0,10)) print(randrange(100)) # range 0-99 print(randrange(0,6)+ 1) # a bal számot sosem generálja le
Python
zaydzuhri_stack_edu_python
comment ********************************************************************************************************************** comment ****** Programação II - 2º Ciclo Jogos Digitais ****** comment ****** Programa: Usando como base o programa do Exercício - Lista de números aleatórios, adicione um código ****** comment...
# ********************************************************************************************************************** # ****** Programação II - 2º Ciclo Jogos Digitais ****** # ****** Programa: Usando como base o programa do Exercício - Lista de núm...
Python
zaydzuhri_stack_edu_python
import hmac , random set message = b'Hello,world!' set key = b'secret' set h = call new key message digestmod=string MD5 print h print hex digest h function hamc_md5 key s begin return hex digest call new encode key string utf-8 encode s string utf-8 digestmod=string MD5 end function class User extends object begin fun...
import hmac,random message=b'Hello,world!' key=b'secret' h=hmac.new(key,message,digestmod='MD5') print(h) print(h.hexdigest()) def hamc_md5(key,s): return hmac.new(key.encode('utf-8'),s.encode('utf-8'),digestmod='MD5').hexdigest() class User(object): def __init__(self,username,password): self.usernam...
Python
zaydzuhri_stack_edu_python
string Created on Thu Dec 10 22:51:52 2020 @author: yzaghir Imge Smouth (lissage) convolution(Convoluté) Convoluté = Qualifie une partie d'un végétal qui est enroulé autour d'un corps ou roulé sur lui même pour former un cornet. Exemple : Les premières petites feuilles convolutées de cette plante médicinale apparaissen...
""" Created on Thu Dec 10 22:51:52 2020 @author: yzaghir Imge Smouth (lissage) convolution(Convoluté) Convoluté = Qualifie une partie d'un végétal qui est enroulé autour d'un corps ou roulé sur lui même pour former un cornet. Exemple : Les premières petites feuilles convolutées de cette plante médicinale apparaiss...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Mar 9 19:53:19 2021 @author: hassa import time import numpy as np import matplotlib.pyplot as plt from math import * set wMax = 0.9 import sys import pandas as pd import random as rd set wMin = 0.2 from geneticalgorithm import geneticalgorithm as ga from opteval impor...
# -*- coding: utf-8 -*- """ Created on Tue Mar 9 19:53:19 2021 @author: hassa """ import time import numpy as np import matplotlib.pyplot as plt from math import * wMax = 0.9 import sys import pandas as pd import random as rd wMin = 0.2 from geneticalgorithm import geneticalgorithm as ga from opteval import benchm...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 from socketserver import ThreadingMixIn from http.server import BaseHTTPRequestHandler , HTTPServer import json import os import urllib class ThreadingHTTPServer extends ThreadingMixIn HTTPServer begin pass end class class Server extends BaseHTTPRequestHandler begin function do_GET self begin ...
#!/usr/bin/python3 from socketserver import ThreadingMixIn from http.server import BaseHTTPRequestHandler, HTTPServer import json import os import urllib class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass class Server(BaseHTTPRequestHandler): def do_GET(self): self.respond() def respon...
Python
zaydzuhri_stack_edu_python
function GetStorage self request context begin call set_code UNIMPLEMENTED call set_details string Method not implemented! raise call NotImplementedError string Method not implemented! end function
def GetStorage(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
Python
nomic_cornstack_python_v1
set s = string hello world print count s string + 1
s='hello world' print(s.count(' ')+1)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string ピヨ + ピヨ ---------- ヒヨコ x + x = y ヒピヨコ a = ヒ b = ピ c = ヨ d = コ for a in range 1 10 begin for b in range 1 10 begin for c in range 10 begin for d in range 10 begin set x = b * 10 + c set y = a * 100 + c * 10 + d if x * 2 == y and length set literal a b c d == 4 begin print format stri...
#!/usr/bin/env python3 """  ピヨ + ピヨ ---------- ヒヨコ x + x = y ヒピヨコ a = ヒ b = ピ c = ヨ d = コ """ for a in range(1,10): for b in range(1,10): for c in range(10): for d in range(10): x = b*10 + c y = a*100 + c*10 + d if x * 2 == y \ ...
Python
zaydzuhri_stack_edu_python
function humanList tf begin import re set matcher = compile string .*user_(\d+).* set all_tfs = call getFrameStrings set all_human_ids = list for frame_name in all_tfs begin set match = match frame_name if match is not none begin append all_human_ids call groups at 0 end end return all_human_ids end function
def humanList(tf): import re matcher = re.compile('.*user_(\\d+).*') all_tfs = tf.getFrameStrings() all_human_ids = [] for frame_name in all_tfs: match = matcher.match(frame_name) if match is not None: all_human_ids.append(match.groups()[0]) return all_hu...
Python
nomic_cornstack_python_v1
function _inverse_kinematics self position orientation begin set inverse_kinematics = call inverse_kinematics body_name eefID position=position orientation=orientation comment Replace the fingers coef by [0, 0] set inverse_kinematics = list inverse_kinematics at slice 0 : 6 : return inverse_kinematics end function
def _inverse_kinematics(self, position, orientation): inverse_kinematics = self.sim.inverse_kinematics( self.body_name, self.eefID, position=position, orientation=orientation ) # Replace the fingers coef by [0, 0] inverse_kinematics = list(inverse_kinematics[0:6]) return inverse_kinematics
Python
nomic_cornstack_python_v1
string def suma(valor_uno, valor_dos): return valor_uno + valor_dos set mi_funcion = lambda valor_uno valor_dos -> valor_uno + valor_dos set resultado = call mi_funcion 10 20 print resultado comment lambda + argumentos + accion a ejecutar (no es necesario indicar return) set formato = lambda sentencia -> format string ...
'''def suma(valor_uno, valor_dos): return valor_uno + valor_dos ''' mi_funcion = lambda valor_uno, valor_dos : valor_uno + valor_dos resultado = mi_funcion(10,20) print(resultado) # lambda + argumentos + accion a ejecutar (no es necesario indicar return) formato = lambda sentencia : '¿{}?'.format(sentencia) res...
Python
zaydzuhri_stack_edu_python
import datetime import tkinter as tk function round_time dt round_to begin set seconds = seconds set rounding = seconds + round_to / 2 // round_to * round_to return dt + time delta 0 rounding - seconds - microsecond end function function ct label begin function count begin set now = call round_time now round_to=1 set e...
import datetime import tkinter as tk def round_time(dt, round_to): seconds = (dt - dt.min).seconds rounding = (seconds + round_to / 2) // round_to * round_to return dt + datetime.timedelta(0, rounding - seconds, -dt.microsecond) def ct(label): def count(): now = round_time(datetime.datetime....
Python
zaydzuhri_stack_edu_python
function writeln self content begin Ellipsis end function
def writeln(self, content): ...
Python
nomic_cornstack_python_v1
function fitgaussianBG data guess begin set errorfunction = lambda p -> call ravel call call gaussianBG *p *np.indices(data.shape) - data set tuple p success = call leastsq errorfunction guess return p end function
def fitgaussianBG(data, guess): errorfunction = lambda p: np.ravel(gaussianBG(*p)(*np.indices(data.shape)) - data) p, success = optimize.leastsq(errorfunction, guess) return p
Python
nomic_cornstack_python_v1
comment Most of this code was provided in the DRL course, I modified the network structure to experiment with the solution import torch import torch.nn as nn import torch.nn.functional as F class QNetwork extends Module begin string Actor (Policy) Model. function __init__ self state_size=8 action_size=4 seed=0 begin st...
# Most of this code was provided in the DRL course, I modified the network structure to experiment with the solution import torch import torch.nn as nn import torch.nn.functional as F class QNetwork(nn.Module): """Actor (Policy) Model.""" def __init__(self, state_size=8, action_size=4, seed=0): """In...
Python
zaydzuhri_stack_edu_python
set x = - 2 assert x > 0 msg string Deu merda print x
x = -2 assert x > 0, "Deu merda" print(x)
Python
zaydzuhri_stack_edu_python
function get_requests self begin set d1 = call Division string Division 1 set d2 = call Division string Division 2 set user1 = normal_user set user2 = admin_user comment user1 can submit to division 1, user2 to division 2 comment user2 can review and pay out both divisions call Permission d1 submit user1 call Permissio...
def get_requests(self): d1 = Division('Division 1') d2 = Division('Division 2') user1 = self.normal_user user2 = self.admin_user # user1 can submit to division 1, user2 to division 2 # user2 can review and pay out both divisions Permission(d1, PermissionType.submi...
Python
nomic_cornstack_python_v1
class Student begin set no_of_l = 30 function __init__ self name roll begin set name = name set roll = roll end function function print_name self begin return string the name is { name } , role number is { roll } ans total number of leave is { no_of_l } end function decorator classmethod function change_l cls leave beg...
class Student: no_of_l = 30 def __init__(self, name , roll): self.name = name self.roll = roll def print_name(self): return f"the name is {self.name} , role number is {self.roll} ans total number of leave is {self.no_of_l}" @classmethod def change_l(cls , leave):...
Python
zaydzuhri_stack_edu_python
function get_linkage self symbol_table c begin if is_global and storage == STATIC begin set linkage = INTERNAL end else if storage == EXTERN begin set cur_linkage = call lookup_linkage identifier set linkage = cur_linkage or EXTERNAL end else if call is_function and not storage begin set linkage = EXTERNAL end else if ...
def get_linkage(self, symbol_table, c): if c.is_global and self.storage == DeclInfo.STATIC: linkage = symbol_table.INTERNAL elif self.storage == DeclInfo.EXTERN: cur_linkage = symbol_table.lookup_linkage(self.identifier) linkage = cur_linkage or symbol_table.EXTERNAL ...
Python
nomic_cornstack_python_v1
comment !/bin/python3 import sys function howManyGames p d m s begin set num_games = 0 while s >= 0 begin set s = s - p if p - d >= m begin set p = p - d end else begin set p = m end set num_games = num_games + 1 end return num_games - 1 end function if __name__ == string __main__ begin set tuple p d m s = split strip ...
#!/bin/python3 import sys def howManyGames(p, d, m, s): num_games = 0 while s >= 0: s -= p if p - d >= m: p -= d else: p = m num_games += 1 return num_games - 1 if __name__ == "__main__": p, d, m, s = input().strip().split(' ') p, d, m, s = ...
Python
zaydzuhri_stack_edu_python
function __init__ self copula data x0=none method=string ml verbose=1 optim_options=none begin set copula = copula set data = data set x0 = x0 set verbose = verbose set method = lower method comment default optim options is the first dictionary. We have set the default options for Nelder-Mead set options = call form_op...
def __init__(self, copula, data: np.ndarray, x0: np.ndarray = None, method: EstimationMethod = 'ml', verbose=1, optim_options: Optional[dict] = None): self.copula = copula self.data = data self.x0 = x0 self.verbose = verbose self.method = method.lower() ...
Python
nomic_cornstack_python_v1
import pandas set db = read csv string marks.csv db set y = db at string marks set x = db at string hrs shape type x set x = values type x set x = reshape x 4 1 type x shape x from sklearn.linear_model import LinearRegression set mind = linear regression fit mind x y predict mind list list 6
import pandas db = pandas.read_csv('marks.csv') db y = db["marks"] x = db['hrs'] x.shape type(x) x = x.values type(x) x = x.reshape(4,1) type(x) x.shape x from sklearn.linear_model import LinearRegression mind = LinearRegression() mind.fit( x, y) mind.predict([[ 6 ]] )
Python
zaydzuhri_stack_edu_python
function join self begin comment block until all tasks are done join queue comment stop workers for _ in async_femags begin put none end for async_femag in async_femags begin join async_femag end return list comprehension status for t in tasks end function
def join(self): # block until all tasks are done self.queue.join() # stop workers for _ in self.async_femags: self.queue.put(None) for async_femag in self.async_femags: async_femag.join() return [t.status for t in self.job.tasks]
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment from tkinter import * comment from tkinter import messagebox as msb comment import functools as ft comment # def resize(ev=None): comment # label.config(font='Helvetica -%d bold' % scale.get()) comment # comment # top = Tk() comment # top.geometry('250x...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # from tkinter import * # from tkinter import messagebox as msb # import functools as ft # # # def resize(ev=None): # # label.config(font='Helvetica -%d bold' % scale.get()) # # # # top = Tk() # # top.geometry('250x150') # # # # label = Label(top, text='Hello World!',...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- import os import json import pandas as pd import matplotlib.pyplot as plt class Cr2 begin string p='Precipitacion', q='Caudal', t='Temperatura', tmax='Temperatura max', tmin='Temperatura min' function __init__ self period var sourcefile begin set sources = call ope...
#!/usr/bin/python # -*- coding: utf-8 -*- import os import json import pandas as pd import matplotlib.pyplot as plt class Cr2: ''' p='Precipitacion', q='Caudal', t='Temperatura', tmax='Temperatura max', tmin='Temperatura min' ''' def __init__(self, period, var, sourcefile): sources = self....
Python
zaydzuhri_stack_edu_python
function at self begin return _at end function
def at(self): return self._at
Python
nomic_cornstack_python_v1
function parse_protocol_header stream begin set tuple prefix *version = call unpack string >5sBBB call _read stream 8 if prefix != b'AMQP\x00' begin raise call ValueError format string wrong protocol, expected b'AMQP', got {} prefix end return version end function
def parse_protocol_header(stream: BytesIO) -> Tuple[int, int, int]: prefix, *version = unpack('>5sBBB', _read(stream, 8)) if prefix != b'AMQP\x00': raise ValueError("wrong protocol, expected b'AMQP\x00', got {}".format( prefix )) return version
Python
nomic_cornstack_python_v1
function isPossibleSubsumer self begin comment self.prediction < cons.err_sub: (why does it work?) if action_cnt > theta_sub and error < err_sub begin return true end return false end function
def isPossibleSubsumer(self): if self.action_cnt > cons.theta_sub and self.error < cons.err_sub: #self.prediction < cons.err_sub: (why does it work?) return True return False
Python
nomic_cornstack_python_v1
function endof_new_service_attachment_date_epoch self endof_new_service_attachment_date_epoch begin set _endof_new_service_attachment_date_epoch = endof_new_service_attachment_date_epoch end function
def endof_new_service_attachment_date_epoch(self, endof_new_service_attachment_date_epoch): self._endof_new_service_attachment_date_epoch = endof_new_service_attachment_date_epoch
Python
nomic_cornstack_python_v1
function shape_wait begin comment 2 secs return call timed_wait 2000 press_events end function
def shape_wait(): return timed_wait(2000, press_events) # 2 secs
Python
nomic_cornstack_python_v1
function export_finn_onnx module input_shape export_path input_t=none torch_onnx_kwargs=dict begin if onnx is none or opt is none begin raise call ModuleNotFoundError string Installation of ONNX is required. end with no grad begin comment TODO maybe consider a deepcopy of the module first? set module = eval if input_t ...
def export_finn_onnx(module, input_shape, export_path, input_t = None, torch_onnx_kwargs = {}): if onnx is None or opt is None: raise ModuleNotFoundError("Installation of ONNX is required.") with torch.no_grad(): # TODO maybe consider a deepcopy of the module first? module = module....
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Jul 7 17:52:37 2021 @author: kazuk set mod = 10 ^ 9 + 7 set n = integer input set pair = list comprehension list map int split input for _ in range n comment dp[S] :ペアが決定している女性が集合Sで、その人数(i)までの男性が決まっているとき男性[i+1]のペアを決める通り数 set dp = list 0 * 1 ? n set dp at 0 = 1 for S i...
# -*- coding: utf-8 -*- """ Created on Wed Jul 7 17:52:37 2021 @author: kazuk """ mod = 10**9+7 n = int(input()) pair = [list(map(int, input().split())) for _ in range(n)] #dp[S] :ペアが決定している女性が集合Sで、その人数(i)までの男性が決まっているとき男性[i+1]のペアを決める通り数 dp = [0] * (1 << n) dp[0] = 1 for S in range(1<<n): #iは男性のi...
Python
zaydzuhri_stack_edu_python
function pgv self begin if INDEX_PGV is none begin raise NotImplementedError end else begin return call _resp INDEX_PGV * PGV_SCALE end end function
def pgv(self) -> float: if self.INDEX_PGV is None: raise NotImplementedError else: return self._resp(self.INDEX_PGV) * self.PGV_SCALE
Python
nomic_cornstack_python_v1
import json import uuid from typing import Any , Dict , Callable import pika from Core import settings from Core.Tools.Misc.ObjectSerializers import object_to_json class RabbitMqAdapter begin decorator classmethod function serialize_message cls data begin return call object_to_json data end function function __init__ s...
import json import uuid from typing import Any, Dict, Callable import pika from Core import settings from Core.Tools.Misc.ObjectSerializers import object_to_json class RabbitMqAdapter: @classmethod def serialize_message(cls, data: Any) -> Dict: return object_to_json(data) def __init__( ...
Python
zaydzuhri_stack_edu_python
function find_obviously_failed_sixtrack_submissions basedir begin set jobs = list for job in call get_all_jobs_in_base basedir begin try begin debug string job set track = call get_track_path jobname=job basedir=basedir set first_seed = call get_first_dir track / string simul set tunes = call get_first_dir first_seed ...
def find_obviously_failed_sixtrack_submissions(basedir: Path): jobs = [] for job in get_all_jobs_in_base(basedir): try: LOG.debug(str(job)) track = get_track_path(jobname=job, basedir=basedir) first_seed = get_first_dir(track) / "simul" tunes = get_...
Python
nomic_cornstack_python_v1
function get_valid_paths self path begin string There are some restrictions on the valid directory structures: 1. There can be only one vasp run in each directory. Nested directories are fine. 2. Directories designated "relax1", "relax2" are considered to be 2 parts of an aflow style run. 3. Directories containing vasp...
def get_valid_paths(self, path): """ There are some restrictions on the valid directory structures: 1. There can be only one vasp run in each directory. Nested directories are fine. 2. Directories designated "relax1", "relax2" are considered to be 2 parts of an afl...
Python
jtatman_500k
function get_coherence model token_lists measure=string c_v begin if method == string LDA begin set cm = call CoherenceModel model=ldamodel texts=token_lists corpus=corpus dictionary=dictionary coherence=measure end else begin set topics = call get_topic_words token_lists labels_ set cm = call CoherenceModel topics=top...
def get_coherence(model, token_lists, measure='c_v'): if model.method == 'LDA': cm = CoherenceModel(model=model.ldamodel, texts=token_lists, corpus=model.corpus, dictionary=model.dictionary, coherence=measure) else: topics = get_topic_words(token_lists, model.clu...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt from utils import read_data function plot proposed baseline num_transfer y_label file_name lines begin set fig = figure figsize=tuple 18 12 set ax = subplot 1 1 1 call tick_params axis=string both which=string major labelsize=36 for line in lines begin call axhline line lw=6 c=string lig...
import matplotlib.pyplot as plt from utils import read_data def plot(proposed, baseline, num_transfer, y_label, file_name, lines): fig = plt.figure(figsize=(18, 12)) ax = plt.subplot(1, 1, 1) ax.tick_params(axis='both', which='major', labelsize=36) for line in lines: ax.axhline(line, lw=6, c='...
Python
zaydzuhri_stack_edu_python
set str1 = string python is programming language set str2 = string A, B, C, D, E, F set str3 = string Python programming set str1_strip = strip str1 string language set str2_strip = strip str2 string , F print str1_strip print str2_strip print strip str3
str1 = "python is programming language"; str2 = "A, B, C, D, E, F" str3 = " Python programming " str1_strip = str1.strip("language") str2_strip = str2.strip(", F") print(str1_strip) print(str2_strip) print(str3.strip())
Python
zaydzuhri_stack_edu_python
for i in range 1 10 begin set d at 1 at i = 1 end for i in range 2 101 begin for k in range 10 begin if k == 0 begin set d at i at k = d at i - 1 at 1 end else if k == 9 begin set d at i at k = d at i - 1 at 8 end else begin set d at i at k = d at i - 1 at k - 1 + d at i - 1 at k + 1 end end end set n = integer input p...
for i in range(1, 10): d[1][i] = 1 for i in range(2, 101): for k in range(10): if k == 0: d[i][k] = d[i - 1][1] elif k == 9: d[i][k] = d[i - 1][8] else: d[i][k] = d[i - 1][k - 1] + d[i - 1][k + 1] n = int(input()) print(sum(d[n]) % 1000000000)
Python
zaydzuhri_stack_edu_python
function signature_abs self begin return call signature_abs self basepath end function
def signature_abs(self): return signature_abs(self, self.identifier.basepath)
Python
nomic_cornstack_python_v1
function test_auth_user_cant_login_again self begin call create_user call login_user username=string john password=string john123 set response = get client string /users/login follow_redirects=true assert equal status_code 200 assert in b'Welcome' data end function
def test_auth_user_cant_login_again(self) -> None: self.user_seeder.create_user() self.login_user(username='john', password='john123') response = self.client.get('/users/login', follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertIn(b'Welcome', response...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[ ]: string 测试案例 Input: num = "123", target = 6 Output: ["1+2+3", "1*2*3"] Input: num = "105", target = 5 Output: ["1*0+5","10-5"] Input: num = "00", target = 0 Output: ["0+0", "0-0", "0*0"] Input: num = "3456237490", target = 9191 Output: [] class Solution_1...
#!/usr/bin/env python # coding: utf-8 # In[ ]: """ 测试案例 Input: num = "123", target = 6 Output: ["1+2+3", "1*2*3"] Input: num = "105", target = 5 Output: ["1*0+5","10-5"] Input: num = "00", target = 0 Output: ["0+0", "0-0", "0*0"] Input: num = "3456237490", target = 9191 Output: [] """ class Solution_1: ...
Python
zaydzuhri_stack_edu_python
comment Definition for singly-linked list. class ListNode extends object begin function __init__ self x begin set val = x set next = none end function end class class Solution extends object begin function find_kth self head k begin string :type head: ListNode :type k: int :rtype ListNode return call ListNode - 1 end f...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def find_kth(self, head, k): """ :type head: ListNode :type k: int :rtype ListNode """ return ListNode(-1...
Python
zaydzuhri_stack_edu_python
async function test_light_turn_off hass light begin set entity_id = light at 1 set __fields__ at string set_light = call Mock set set_light = call AsyncMock await call async_call string light string turn_off dict ATTR_ENTITY_ID entity_id blocking=true call assert_called_once_with false end function
async def test_light_turn_off( hass: HomeAssistant, light: tuple[Light, str], ): entity_id = light[1] light[0].__fields__["set_light"] = Mock() light[0].set_light = AsyncMock() await hass.services.async_call( "light", "turn_off", {ATTR_ENTITY_ID: entity_id}, blo...
Python
nomic_cornstack_python_v1
function crop_center arr begin set shape = shape comment This tells us the point of highest intensity, which we will use as the center for inversion operations set center = call unravel_index argument maximum arr axis=none shape comment clip the largest possible cuboid putting the point of highest intensity at the cent...
def crop_center(arr): shape = arr.shape # This tells us the point of highest intensity, which we will use as the center for inversion operations center = np.unravel_index(np.argmax(arr, axis=None), shape) # clip the largest possible cuboid putting the point of highest intensity at the center princ...
Python
nomic_cornstack_python_v1
comment https://leetcode.com/problems/maximum-performance-of-a-team/ import heapq class Solution begin function maxPerformance self n speed efficiency k begin set d = list set mod = 1000000007 for i in range n begin set t = tuple efficiency at i speed at i append d t end sort d reverse=true set s = 0 set ans = 0 set q...
#https://leetcode.com/problems/maximum-performance-of-a-team/ import heapq class Solution: def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int: d=[] mod=1000000007 for i in range(n): t=(efficiency[i],speed[i]) d.append(...
Python
zaydzuhri_stack_edu_python
function generate_encrypting_keypair self gen_priv=true begin set ecies_keypair = call EncryptingKeypair if gen_priv begin call gen_privkey end return ecies_keypair end function
def generate_encrypting_keypair(self, gen_priv=True) -> keypairs.EncryptingKeypair: ecies_keypair = keypairs.EncryptingKeypair() if gen_priv: ecies_keypair.gen_privkey() return ecies_keypair
Python
nomic_cornstack_python_v1
import pymysql import numpy as np import pandas as pd from matplotlib import style from matplotlib import pyplot as plt set conexion = call connect host=string localhost user=string root password=string D1str3$$* database=string tarifas set miCursor = call cursor execute miCursor string SELECT zona_inyeccion, volume...
import pymysql import numpy as np import pandas as pd from matplotlib import style from matplotlib import pyplot as plt conexion = pymysql.connect(host = "localhost", user = "root", password = "D1str3$$*", database = "tarifas") miCursor = conexion.cursor() miCursor.execute("SELECT zona_inyeccion, volumetrica FROM s...
Python
zaydzuhri_stack_edu_python
string Demonstrate how to mock an object. function ask_for_value_and_convert_to_upper begin return upper strip input string Enter your name please end function
""" Demonstrate how to mock an object. """ def ask_for_value_and_convert_to_upper(): return input("Enter your name please").strip().upper()
Python
zaydzuhri_stack_edu_python
function delete self key begin if numItems == 0 begin return end if key in hashTable begin set QNode = hashTable at key call removeNode QNode pop hashTable key none set numItems = numItems - 1 end end function
def delete(self, key): if (self.numItems == 0): return if (key in self.hashTable): QNode = self.hashTable[key] self.DLLQueue.removeNode(QNode) self.hashTable.pop(key, None) self.numItems -= 1
Python
nomic_cornstack_python_v1
function _excitonic_reorg_energy self SS AG n begin comment SystemBathInteraction set sbi = call get_SystemBathInteraction comment CorrelationFunctionMatrix set cfm = CC set rg = 0.0 comment electronic states corresponding to single excited states set elst = where which_band == 1 at 0 for el1 in elst begin set reorg = ...
def _excitonic_reorg_energy(self, SS, AG, n): # SystemBathInteraction sbi = AG.get_SystemBathInteraction() # CorrelationFunctionMatrix cfm = sbi.CC rg = 0.0 # electronic states corresponding to single excited states elst = numpy.where(AG...
Python
nomic_cornstack_python_v1
import os import ast import traceback import time import sys import types import builtins import collections import astor import weakref from jsonify import jsonify , jsonify_print , jsonify_print_expr from datalayer import Analysis , Execution , FileEdit from router import send from import stdlib function now begin r...
import os import ast import traceback import time import sys import types import builtins import collections import astor import weakref from .jsonify import jsonify, jsonify_print, jsonify_print_expr from .datalayer import Analysis, Execution, FileEdit from .router import send from . import stdlib def now(): retu...
Python
jtatman_500k
import bike_db_access import kiosk_db_access import datetime comment Handles most of the logic of the bike rental program Bikes can be checked out comment from a kiosk if the kiosk is not empty. Bikes can be returned to a kiosk if comment the kiosk is not full. Bikes can also be in transit, meaning that the bike is com...
import bike_db_access import kiosk_db_access import datetime # Handles most of the logic of the bike rental program Bikes can be checked out # from a kiosk if the kiosk is not empty. Bikes can be returned to a kiosk if # the kiosk is not full. Bikes can also be in transit, meaning that the bike is # not at any kiosk ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5. set a = list 1 1 2 3 5 8 13 21 34 55 89 for item in a begin if item <= 5 begin print item end end
#!/usr/bin/env python3 """Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5.""" a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] for item in a: if item<=5: print(item)
Python
zaydzuhri_stack_edu_python
comment -*-coding:utf-8-*- import sys import pygame from missile import Missile comment 监听键被按下 function check_keydown_events event mySettings screen boat myMissiles begin if key == K_q begin exit end if key == K_UP begin set moving_up = true end if key == K_DOWN begin set moving_down = true end if key == K_RIGHT begin ...
#-*-coding:utf-8-*- import sys import pygame from missile import Missile #监听键被按下 def check_keydown_events(event, mySettings, screen, boat, myMissiles): if event.key == pygame.K_q: sys.exit() if event.key == pygame.K_UP: boat.moving_up = True if event.key == pygame.K_DOWN: boat.movi...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- from math import * comment TЕСТЫ: comment 0 0 2.83, 4 4 2.83, 0 4 1.18 - покрывают края, но не покрывают середину треугольника comment 0 0 2.83, 4 4 2.83, 0 4 2.83 - покрывают края и покрывают середину треугольника (Почти идеально ровно) comment 0 0 2.83, 4 4 2.83, 0 4 2.7 - покрывают края...
# -*- coding: utf-8 -*- from math import * # TЕСТЫ: # 0 0 2.83, 4 4 2.83, 0 4 1.18 - покрывают края, но не покрывают середину треугольника # 0 0 2.83, 4 4 2.83, 0 4 2.83 - покрывают края и покрывают середину треугольника (Почти идеально ровно) # 0 0 2.83, 4 4 2.83, 0 4 2.7 - покрывают края и чуть-чуть не покрывают с...
Python
zaydzuhri_stack_edu_python
string Oferujemy produkty marchew: 2.35, ziemniaki: 2.2, cebula: 1.8, ogorki: 4.0 Co chcesz kupic? Ile chcesz kupic? za marchew płacisz: set produkty = dict string marchew 2.35 ; string ziemniaki 2.2 ; string cebula 1.8 ; string ogorki 4.0 set stan = dict string marchew 100 ; string ziemniaki 10 ; string cebula 10 ; st...
""" Oferujemy produkty marchew: 2.35, ziemniaki: 2.2, cebula: 1.8, ogorki: 4.0 Co chcesz kupic? Ile chcesz kupic? za marchew płacisz: """ produkty = {"marchew" : 2.35, "ziemniaki" : 2.2, "cebula" : 1.8, "ogorki" : 4.0, } stan = { "marchew" : 100, "ziemniaki" : 10, ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np comment print(pd.__version__) comment import matplotlib as plt set city_names = call Series list string San Francisco string San Jose string Sacramento set population = call Series list 852469 1015785 485199 call DataFrame dict string City name city_names ; string Population popul...
import pandas as pd import numpy as np # print(pd.__version__) # import matplotlib as plt city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento']) population = pd.Series([852469, 1015785, 485199]) pd.DataFrame({ 'City name': city_names, 'Population': population }) #Data Frames! california_hou...
Python
zaydzuhri_stack_edu_python
import csv from nltk.tokenize import word_tokenize , sent_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer from nltk.corpus import state_union from nltk.tokenize import PunktSentenceTokenizer from nltk.corpus import wordnet from gensim import corpora function word_stemmer words begin set p...
import csv from nltk.tokenize import word_tokenize, sent_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer from nltk.corpus import state_union from nltk.tokenize import PunktSentenceTokenizer from nltk.corpus import wordnet from gensim import corpora def word_stemmer(words): ps = Port...
Python
zaydzuhri_stack_edu_python
function restart_with_reloader begin while true begin info string ***restarting with reloader*** set args = list executable + argv set new_environ = copy environ set new_environ at RUN_MAIN_ENV_KEY = string true set exit_code = call args env=new_environ if exit_code != 3 begin return exit_code end end end function
def restart_with_reloader(): while True: log.info("***restarting with reloader***") args = [sys.executable] + sys.argv new_environ = os.environ.copy() new_environ[RUN_MAIN_ENV_KEY] = 'true' exit_code = subprocess.call(args, env=new_environ) if exit_code != 3: ...
Python
nomic_cornstack_python_v1
function right_plant_left_lift self begin comment act on mask set a = 21 set b = 21 set c = 21 set d = 21 set mask_right_hip = list comprehension list comprehension list comprehension if expression action_index > 10 then 1 else 0 for action_index in range c for y in range b for x in range a set valid_actions at 2 = mas...
def right_plant_left_lift(self): # act on mask a = b = c = d = 21 self.mask_right_hip = [[[1 if action_index > 10 else 0 for action_index in range(c)] for y in range(b)] for x in range(a)] self.valid_actions[2] = self.mask_right_hip self.mask_left_hip = [1 if action_index <= 6 e...
Python
nomic_cornstack_python_v1
function get_content_by_segments self site path_segments pagination_segments begin pass end function
def get_content_by_segments(self, site, path_segments, pagination_segments): pass
Python
nomic_cornstack_python_v1
import json from urllib.request import urlopen string *** NOTE *** 1) https://ipstack.com 에서 IP주소에 대한 실제 주소를 알려주는 API를 제공 ㄴ 유료지만, 한달 1만회 이하의 사용량에 대해서는 무료! 2) 위 사이트에서 API 키를 발급받아서 ACCESS_KEY 변수에 저장할 것! function getCountry ipAddress begin set url = string http://api.ipstack.com/ + ipAddress set url = url + format string ...
import json from urllib.request import urlopen ''' *** NOTE *** 1) https://ipstack.com 에서 IP주소에 대한 실제 주소를 알려주는 API를 제공 ㄴ 유료지만, 한달 1만회 이하의 사용량에 대해서는 무료! 2) 위 사이트에서 API 키를 발급받아서 ACCESS_KEY 변수에 저장할 것! ''' def getCountry(ipAddress): url = 'http://api.ipstack.com/' + ipAddress url += '?access_key={}&format=1'.forma...
Python
zaydzuhri_stack_edu_python
function writeAttributes self *args begin return call FbcSpeciesPlugin_writeAttributes self *args end function
def writeAttributes(self, *args): return _libsbml.FbcSpeciesPlugin_writeAttributes(self, *args)
Python
nomic_cornstack_python_v1
function testDictMaybeContains self begin set ty = call Infer string if __random__: x = {"a": 1, "b": 2} else: x = {"b": 42j} if "a" in x: v1 = x["b"] if "a" not in x: v2 = x["b"] deep=false call assertTypesMatchPytd ty string from typing import Dict x = ... # type: Dict[str, int or complex] v1 = ... # type: int v2 = ....
def testDictMaybeContains(self): ty = self.Infer("""\ if __random__: x = {"a": 1, "b": 2} else: x = {"b": 42j} if "a" in x: v1 = x["b"] if "a" not in x: v2 = x["b"] """, deep=False) self.assertTypesMatchPytd(ty, """ from typing import Dict ...
Python
nomic_cornstack_python_v1
function device_uuid self device_uuid begin set _device_uuid = device_uuid end function
def device_uuid(self, device_uuid): self._device_uuid = device_uuid
Python
nomic_cornstack_python_v1
function write self stream begin comment write the data write StructBase self stream self end function
def write(self, stream): # write the data pyffi.object_models.xml.struct_.StructBase.write( self, stream, self)
Python
nomic_cornstack_python_v1
comment Game colors set SLEET = tuple 79 93 115 set HL = tuple 255 255 200 set WHITECOLOR = tuple 255 255 255 set GREY = tuple 128 128 128 comment Sizes set WINDOW_SIZE = tuple 700 700 set ARRAY = 20 set SPACE = 30 set PIECE = SPACE * 3 set BUTTON_SIZE = 25 comment Coordinates set tuple X1 Y1 = tuple 50 50 set PIECE_PO...
# Game colors SLEET = ( 79, 93, 115) HL = (255, 255, 200) WHITECOLOR = (255, 255, 255) GREY = (128, 128, 128) # Sizes WINDOW_SIZE = (700, 700) ARRAY = 20 SPACE = 30 PIECE = SPACE * 3 BUTTON_SIZE = 25 # Coordinates X1, Y1 = 50, 50 PIECE_POS = X1 + 3 TURN_SPACE = int(X1 + SPACE*7.5) TURN_HEIGHT...
Python
zaydzuhri_stack_edu_python