code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
string 在控制台依次提示用户输入:姓名、公司、职位、电话、电子邮箱 set name = input string 请输入姓名: set company = input string 请输入公司: set title = input string 请输入职位: set phone = input string 请输入电话: set email = input string 请输入邮箱 print string * * 50 print company print print string %s(%s) % tuple name title print print string 电话: %s % phone print stri...
""" 在控制台依次提示用户输入:姓名、公司、职位、电话、电子邮箱 """ name = input("请输入姓名:") company = input("请输入公司:") title = input("请输入职位:") phone = input("请输入电话:") email = input("请输入邮箱") print("*" * 50) print(company) print() print("%s(%s)"%(name, title)) print() print("电话: %s"% phone) print("邮箱: %s"% email) print("*" * 50)
Python
zaydzuhri_stack_edu_python
function get_new self begin set counter = counter + 1 if counter == next_wearher_show begin comment Set the next interval to show the weather set next_wearher_show = integer random * 10 + 5 comment Fether the dutch weather map set data = read url open KNMI_URL comment Write weather map to disk set fh = open string /tmp...
def get_new(self): self.counter += 1 if self.counter == self.next_wearher_show: # Set the next interval to show the weather next_wearher_show = int(random.random()*10) + 5 # Fether the dutch weather map data = urllib.urlopen(KNMI_URL).read() ...
Python
nomic_cornstack_python_v1
from pyproj import Transformer function WGStoTM2 lon lat begin set transformer = call from_crs string epsg:4326 string epsg:3826 set tuple lon_tm2 lat_tm2 = transform transformer lat lon return list lon_tm2 lat_tm2 end function comment 請分別輸入經度及緯度,將輸出一個list為TWD97TM2的座標([0]為經度方向,[1]為緯度方向)
from pyproj import Transformer def WGStoTM2(lon,lat): transformer = Transformer.from_crs("epsg:4326","epsg:3826") lon_tm2,lat_tm2=transformer.transform(lat,lon) return [lon_tm2,lat_tm2] # 請分別輸入經度及緯度,將輸出一個list為TWD97TM2的座標([0]為經度方向,[1]為緯度方向)
Python
zaydzuhri_stack_edu_python
function pixels pix_width fov_width pos_ang num_pix begin comment Convert to radians set pos_ang = pos_ang * pi / 180.0 set limit = pix_width * num_pix - 1 / fov_width / 2.0 comment Define 1D grid set x = linear space - limit limit num_pix comment Return 2D grid set tuple xx yy = call meshgrid x x comment Rotate coordi...
def pixels(pix_width, fov_width, pos_ang, num_pix): # Convert to radians pos_ang = pos_ang * np.pi / 180.0 limit = (pix_width * (num_pix - 1)) / (fov_width / 2.0) # Define 1D grid x = np.linspace(- limit, limit, num_pix) # Return 2D grid xx, yy = np.meshgrid(x, x) # Rotate coordinate...
Python
nomic_cornstack_python_v1
import sys import os from Core import itemsWorker from Core.safeCast import safeCast from Games.gessNum import gesNum from Games.RPG import rpg set rwd = call dirBuild argv at 0 get current directory true change directory rwd call saveInfo string Старт rwd if length argv >= 2 begin set command = argv at 1 end else begi...
import sys import os from Core import itemsWorker from Core.safeCast import safeCast from Games.gessNum import gesNum from Games.RPG import rpg rwd = itemsWorker.dirBuild((sys.argv[0]), os.getcwd(), True) os.chdir(rwd) itemsWorker.saveInfo('Старт', rwd) if len(sys.argv) >= 2: command = sys.argv[1] else: comm...
Python
zaydzuhri_stack_edu_python
function __init__ self savFileName ioUtf8=false ioLocale=none begin call setlocale LC_ALL string set savFileName = savFileName if name == string nt begin set libc = call LoadLibrary string msvcrt end else begin set libc = call LoadLibrary call find_library string c end set spssio = call loadLibrary set wholeCaseIn = sp...
def __init__(self, savFileName, ioUtf8=False, ioLocale=None): locale.setlocale(locale.LC_ALL, "") self.savFileName = savFileName if os.name == 'nt': self.libc = cdll.LoadLibrary('msvcrt') else: self.libc = cdll.LoadLibrary(ctypes.util.find_library('c')) se...
Python
nomic_cornstack_python_v1
function makeHadamard n d begin return list comprehension list comprehension if expression d at string r%dc%d % tuple i j then 1 else 0 for j in range n for i in range n end function
def makeHadamard(n, d): return [[1 if d["r%dc%d" % (i, j)] else 0 for j in range(n)] for i in range(n)]
Python
nomic_cornstack_python_v1
function __IASS_helper self inh ass begin set list_of_iass_relation = list if inh is none or ass is none begin info string There are no IASS relations end else begin for parent_and_child in inh begin set parent = get attrib string ci set child = get attrib string cj for relation in ass begin if child == get attrib stri...
def __IASS_helper(self, inh, ass): list_of_iass_relation = list() if inh is None or ass is None: logger.info("There are no IASS relations") else: for parent_and_child in inh: parent = parent_and_child.attrib.get("ci") child = parent_...
Python
nomic_cornstack_python_v1
set minutos = integer input string Dame los minutos en los que caminará el caracol: set vel_car = 5.7 set vel_min = 5.7 * 60 set vel_total = vel_min * minutos / 10 print vel_total
minutos= int(input("Dame los minutos en los que caminará el caracol: " )) vel_car = 5.7 vel_min = (5.7*60) vel_total = (vel_min*minutos)/10 print(vel_total)
Python
zaydzuhri_stack_edu_python
from sklearn.ensemble import RandomForestClassifier class RandomForest begin string Random forest classifier function __init__ self no_trees=100 begin set classifier = random forest classifier n_estimators=no_trees end function function fit self X y begin string Method to fit the model. Parameters: X : 2d numpy array o...
from sklearn.ensemble import RandomForestClassifier class RandomForest(): """ Random forest classifier """ def __init__(self, no_trees = 100): self.classifier = RandomForestClassifier(n_estimators = no_trees) def fit(self, X, y): """ Method to fit the model. ...
Python
zaydzuhri_stack_edu_python
function depth args begin set p = call OptionParser __doc__ call add_option string --chrinfo help=string Comma-separated mappings between seqid, color, new_name call add_option string --titleinfo help=string Comma-separated titles mappings between filename, title call add_option string --maxdepth default=100 type=strin...
def depth(args): p = OptionParser(depth.__doc__) p.add_option( "--chrinfo", help="Comma-separated mappings between seqid, color, new_name" ) p.add_option( "--titleinfo", help="Comma-separated titles mappings between filename, title", ) p.add_option("--maxdepth", default=1...
Python
nomic_cornstack_python_v1
function get_password_hash password begin return call hash password end function
def get_password_hash(password: str) -> str: return pwd_context.hash(password)
Python
nomic_cornstack_python_v1
from extractor import Extractor from bs4 import BeautifulSoup class Reuters extends Extractor begin function extractArticle self article begin set soup = call BeautifulSoup html set articleImageContainer = find soup id=string articleImage if articleImageContainer begin set string image attrs at string src end set artic...
from extractor import Extractor from bs4 import BeautifulSoup class Reuters(Extractor): def extractArticle(self, article): soup = BeautifulSoup(article.html) articleImageContainer = soup.find(id='articleImage') if articleImageContainer: article.set('image', articleImageContain...
Python
zaydzuhri_stack_edu_python
comment 29 de Marzo. Lunes comment G es una Constante comment Función ptencia pow(base, exponente) comment Operador ** 10 ** -8 set G = 6.673 * power 10 - 8 set m1 = decimal input string Ingrese la masa del cuerpo 1: set m2 = decimal input string Ingrese la masa del cuerpo 2: comment Distancia entre los cuerpos. set d ...
# 29 de Marzo. Lunes # G es una Constante # Función ptencia pow(base, exponente) # Operador ** 10 ** -8 G = 6.673 * pow(10, -8) m1 = float(input(' Ingrese la masa del cuerpo 1: ')) m2 = float(input(' Ingrese la masa del cuerpo 2: ')) # Distancia entre los cuerpos. d = float(input('Ingrese la distancia ')) # Process #...
Python
zaydzuhri_stack_edu_python
function get_images input_file_path output_path begin if not exists input_file_path begin raise call FileNotFoundError input_file_path end if not exists output_path begin raise call NotADirectoryError output_path end set faulty_lines = list with open input_file_path as infile begin for line in infile begin set url = s...
def get_images(input_file_path, output_path): if not exists(input_file_path): raise FileNotFoundError(input_file_path) if not exists(output_path): raise NotADirectoryError(output_path) faulty_lines = [] with open(input_file_path) as infile: for line in infile: url = ...
Python
nomic_cornstack_python_v1
class Solution begin function subarraySum self nums k begin set count = 0 set total = 0 set hash_map = dict 0 1 for num in nums begin set total = total + num if total - k in hash_map begin set count = count + hash_map at total - k end if total in hash_map begin set hash_map at total = hash_map at total + 1 end else beg...
class Solution: def subarraySum(self, nums, k: int) -> int: count = 0 total = 0 hash_map = {0: 1} for num in nums: total += num if total - k in hash_map: count += hash_map[total - k] if total in hash_map: hash_map[total] += 1 else: hash_map[total] = 1 return count
Python
zaydzuhri_stack_edu_python
set n = string input set n1 = n at slice : : - 1 print n1
n=str(input()) n1=n[: : -1] print(n1)
Python
zaydzuhri_stack_edu_python
function testUnicode self begin set base_name = call utf8 string ààà朋友你好abc123𐀀𐀀 set timestamp = time set contact_id_lookup = dictionary function _CreateContact index begin set name = base_name + string index set identity_key = string Email:%s % name return call CreateFromKeywords 100 list tuple identity_key none ...
def testUnicode(self): base_name = escape.utf8(u'ààà朋友你好abc123\U00010000\U00010000\x00\x01\b\n\t ') timestamp = time.time() contact_id_lookup = dict() def _CreateContact(index): name = base_name + str(index) identity_key = 'Email:%s' % name return Contact.CreateFromKeywords(10...
Python
nomic_cornstack_python_v1
function create_keystone_db self *args **kwargs begin return execute _create_keystone_db *args keyword kwargs end function
def create_keystone_db(self, *args, **kwargs): return execute(self._create_keystone_db, *args, **kwargs)
Python
nomic_cornstack_python_v1
while true begin if i == n - 1 begin append s c break end if l at i != l at i + 1 begin append s c set c = 0 end set c = c + 1 set i = i + 1 end set ans = 0 for i in s begin set ans = ans + i // 2 end print ans
while True: if i==n-1: s.append(c) break if l[i]!=l[i+1]: s.append(c) c=0 c+=1 i+=1 ans=0 for i in s: ans+=i//2 print(ans)
Python
zaydzuhri_stack_edu_python
function draw_strat_sample self T n excl_idxs=none begin if n == 0 begin return array list dtype=uint end comment TODO: this only works if excl_idxs=None if size == n begin return array range n end if n == 1 begin set idxs_all_non_excl = call setdiff1d array range size excl_idxs assume_unique=true return array list ra...
def draw_strat_sample(self, T, n, excl_idxs=None): if n == 0: return np.array([], dtype=np.uint) if T.size == n: # TODO: this only works if excl_idxs=None return np.arange(n) if n == 1: idxs_all_non_excl = np.setdiff1d( np.arange(T.size), e...
Python
nomic_cornstack_python_v1
function _init_loan begin comment principal loan amount of loan comment 7959.30 set amount = decimal input string Enter the principal amount of the loan: comment interest rate of loan comment 0.0505 set interest_rate = decimal input string Enter the interest rate of the loan: comment frequency of payments set freq = in...
def _init_loan() -> pl.Loan: # principal loan amount of loan amount = float(input("Enter the principal amount of the loan: ")) # 7959.30 # interest rate of loan interest_rate = float(input("Enter the interest rate of the loan: ")) # 0.0505 # frequency of payments freq = int(input("Enter the nu...
Python
nomic_cornstack_python_v1
function _find_impl cls role interface begin string Find relation implementation based on its role and interface. set module = call _relation_module role interface if not module begin return none end return call _find_subclass module end function
def _find_impl(cls, role, interface): """ Find relation implementation based on its role and interface. """ module = _relation_module(role, interface) if not module: return None return cls._find_subclass(module)
Python
jtatman_500k
function _predict_proba self X begin set preds = call _predict X set n_instances = length preds if has attribute self string n_clusters and n_clusters is not none begin set n_clusters = n_clusters end else begin set n_clusters = max preds + 1 end set dists = zeros tuple shape at 0 n_clusters for i in range n_instances ...
def _predict_proba(self, X): preds = self._predict(X) n_instances = len(preds) if hasattr(self, "n_clusters") and self.n_clusters is not None: n_clusters = self.n_clusters else: n_clusters = max(preds) + 1 dists = np.zeros((X.shape[0], n_clusters)) ...
Python
nomic_cornstack_python_v1
function get self datetime file_name x target_column target_value analysis_type is_actuals begin set data = call read_file file_name set data = call bin_continuous_cols data target_column set tuple f ax = call subplots figsize=tuple 15 11 if analysis_type != string continuous begin set target_value = call convert_conti...
def get(self, datetime, file_name, x, target_column, target_value, analysis_type, is_actuals): data = file_service.read_file(file_name) data = influencers_service.bin_continuous_cols(data, target_column) f, ax = plt.subplots(figsize=(15, 11)) if analysis_type != 'continuous': ...
Python
nomic_cornstack_python_v1
function f x y begin return x + y end function print f dist 10 20
def f(x,y): return x + y print(f(10,20))
Python
zaydzuhri_stack_edu_python
function get_target self begin set conversions_dict = dict for i in range 16 begin set conversions_dict at i = _conversions at i end set _target = list comprehension decimal init_target at i * conversions_dict at i for i in range 16 set reference_total_1 = sum list comprehension _reference at i at 1 for i in elements ...
def get_target(self): conversions_dict = {} for i in range(16): conversions_dict[i] = self._conversions[i] self._target = [float(self.init_target[i])*conversions_dict[i] for i in range(16)] reference_total_1 = np.sum([self._reference[i][1] for i in self.elements]) ref...
Python
nomic_cornstack_python_v1
function get_relation_list self begin return keys relation_distribution_map end function
def get_relation_list(self): return self.relation_distribution_map.keys()
Python
nomic_cornstack_python_v1
function init_auto_update self begin comment this maps the key (combo-box-index) to the auto-update-interval value comment where (-1) means, no key set combobox_interval_mapping = dict 0 1 ; 1 2 ; 2 7 ; 3 14 call set_active 0 comment update_days = apt_pkg.Config.FindI(softwareproperties.CONF_MAP["autoupdate"]) call app...
def init_auto_update(self): # this maps the key (combo-box-index) to the auto-update-interval value # where (-1) means, no key self.combobox_interval_mapping = { 0 : 1, 1 : 2, 2 : 7, 3 : 14 }...
Python
nomic_cornstack_python_v1
function enclosing_box_aligned corners1 corners2 begin comment (B, N) set x1_max = max corners1 at tuple Ellipsis 0 dim=2 at 0 comment (B, N) set x1_min = min corners1 at tuple Ellipsis 0 dim=2 at 0 set y1_max = max corners1 at tuple Ellipsis 1 dim=2 at 0 set y1_min = min corners1 at tuple Ellipsis 1 dim=2 at 0 comment...
def enclosing_box_aligned(corners1:torch.Tensor, corners2:torch.Tensor): x1_max = torch.max(corners1[..., 0], dim=2)[0] # (B, N) x1_min = torch.min(corners1[..., 0], dim=2)[0] # (B, N) y1_max = torch.max(corners1[..., 1], dim=2)[0] y1_min = torch.min(corners1[..., 1], dim=2)[0] x2_max =...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import math from datetime import datetime from sklearn.linear_model import LinearRegression import streamlit as st set df = read csv string ipl.csv set df = drop df labels=list string mid string batsman string bowler string striker string non-striker axis=1 set consistent_team = l...
import pandas as pd import numpy as np import math from datetime import datetime from sklearn.linear_model import LinearRegression import streamlit as st df=pd.read_csv('ipl.csv') df=df.drop(labels=['mid','batsman','bowler','striker','non-striker'],axis=1) consistent_team=['Kolkata Knight Riders','Chennai Super King...
Python
zaydzuhri_stack_edu_python
function build self begin comment print('ntimes=%s nelements=%s ntotal=%s' % (self.ntimes, self.nelements, self.ntotal)) comment print('self.IDs', self.data) set itime = 0 set ielement = 0 set itotal = 0 assert ntimes > 0 msg string ntimes=%s % ntimes assert nelements > 0 msg string nelements=%s % nelements assert ntot...
def build(self): #print('ntimes=%s nelements=%s ntotal=%s' % (self.ntimes, self.nelements, self.ntotal)) #print('self.IDs', self.data) self.itime = 0 self.ielement = 0 self.itotal = 0 assert self.ntimes > 0, 'ntimes=%s' % self.ntimes assert self.nelements > 0, 'n...
Python
nomic_cornstack_python_v1
function infocus request id begin set template = call get_template string infocus.html try begin set topic = get objects id=id set serialized_topic = call TopicNestedSerializer topic set topic_json = call render data end except ObjectDoesNotExist begin return call HttpResponse string This topic doesn't exists! end set ...
def infocus(request, id): template = loader.get_template('infocus.html') try: topic = Topic.objects.get(id=id) serialized_topic = TopicNestedSerializer(topic) topic_json = JSONRenderer().render(serialized_topic.data) except ObjectDoesNotExist: return HttpResponse("This topic ...
Python
nomic_cornstack_python_v1
while true begin set num = integer input string enter any number and keep on going! if you want to stop enter '0' if num == 0 begin break end else begin append numbers num end end set highest = numbers at 0 set i = 1 while i < length numbers begin if numbers at i > highest begin set highest = numbers at i end set i = i...
while True: num = int(input("enter any number and keep on going! if you want to stop enter '0'")) if num==0: break else: numbers.append(num) highest = numbers[0] i=1 while i<len(numbers): if numbers[i]>highest: highest=numbers[i] i=i+1 print("the highest is ",highest)
Python
zaydzuhri_stack_edu_python
import numpy set i_list = list map int split input set arr1 = array i_list set changed_array = reshape numpy arr1 tuple 3 3 print changed_array
import numpy i_list = list(map(int, input().split())) arr1 = numpy.array(i_list) changed_array = numpy.reshape(arr1, (3,3)) print(changed_array)
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment .NET の API を使って文字列の一部を変換するサンプル import clr from System import * from System.IO import * from System.Text.RegularExpressions import * set data = call ReadAllText string data.txt set regex = call Regex string //@@@StartPos.*?//@@@EndPos Singleline set data_new = replace regex data string //@@...
# coding: utf-8 # # .NET の API を使って文字列の一部を変換するサンプル import clr from System import * from System.IO import * from System.Text.RegularExpressions import * data = File.ReadAllText("data.txt") regex = Regex("//@@@StartPos.*?//@@@EndPos", RegexOptions.Singleline) data_new = regex.Replace(data, "//@@@StartPos\ntest\n//@@@...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3.9 from collections import Counter from bs4 import BeautifulSoup from argparse import ArgumentParser from data.synonyms import construct_with_synonyms , replace_with_synonym function filter_alpha text begin string Filter out nonalpha characters from string return join string list comprehension...
#!/usr/bin/python3.9 from collections import Counter from bs4 import BeautifulSoup from argparse import ArgumentParser from data.synonyms import construct_with_synonyms, replace_with_synonym def filter_alpha(text: str) -> str: '''Filter out nonalpha characters from string ''' return ''.join([c for c in t...
Python
zaydzuhri_stack_edu_python
from read_config import read_config from operator import itemgetter from copy import deepcopy import math import random set qValues = dict set epsilon = 0.0 function ValidLocation new_position begin set config = call read_config set goal = config at string goal set rows = config at string map_size at 0 set cols = conf...
from read_config import read_config from operator import itemgetter from copy import deepcopy import math import random qValues = {} epsilon = 0.0 def ValidLocation(new_position): config = read_config() goal = config['goal'] rows = config['map_size'][0] cols = config['map_size'][1] walls = config...
Python
zaydzuhri_stack_edu_python
comment MergeStockPriceData.py comment Sai Madhuri Yerramsetti comment October 7, 2020 comment Student Number: 0677671 comment Import packages import pandas as pd import os comment Function to read and merge the ctock market data function read_and_merge_data file_dir begin set filepath_list = list comment make a list ...
# MergeStockPriceData.py # Sai Madhuri Yerramsetti # October 7, 2020 # Student Number: 0677671 # Import packages import pandas as pd import os # Function to read and merge the ctock market data def read_and_merge_data(file_dir): filepath_list = [] # make a list of csv files list in th...
Python
zaydzuhri_stack_edu_python
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense , Conv2D , MaxPooling2D , Flatten , Dropout , Activation class SudokuNet begin decorator staticmethod function build width height depth classes begin set input_shape = tuple height width depth set model = sequential add model conv ...
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense,Conv2D,MaxPooling2D,Flatten,Dropout,Activation class SudokuNet: @staticmethod def build(width,height,depth,classes): input_shape = (height,width,depth) model = Sequential() model.add(Conv2D(32,(5...
Python
zaydzuhri_stack_edu_python
function OnAddCards self addedcards begin string Called when a card is inserted. Adds a smart card to the smartcards tree. set parentnode = root for cardtoadd in addedcards begin set childCard = call AppendItem parentnode call toHexString atr call SetItemText childCard call toHexString atr call SetPyData childCard card...
def OnAddCards(self, addedcards): """Called when a card is inserted. Adds a smart card to the smartcards tree.""" parentnode = self.root for cardtoadd in addedcards: childCard = self.AppendItem(parentnode, toHexString(cardtoadd.atr)) self.SetItemText(childCard, to...
Python
jtatman_500k
import time , signal , sys import Adafruit_ADS1x15 comment Globals comment Vector of read voltages set voltVector = list comment Classes and Methods comment Functions function signal_handler signal frame begin print string You pressed Ctrl+C! exit 0 end function call signal SIGINT signal_handler comment print 'Press C...
import time, signal, sys import Adafruit_ADS1x15 ######################### # Globals ######################### voltVector = [] # Vector of read voltages ######################### # Classes and Methods ######################### ######################### # Functions ######################### def signal_handler(sign...
Python
zaydzuhri_stack_edu_python
from time import clock from StandardFunctions import genprimes set t0 = call clock set primes = call genprimes 500000 print format string Prime gen time: {} call clock - t0 set flag = true for tuple n p in enumerate primes begin set n = n + 1 if n % 2 == 0 begin continue end set r = 2 * p * n % p * p if r > 10 ^ 10 beg...
from time import clock from StandardFunctions import genprimes t0 = clock() primes = genprimes(500000) print("Prime gen time: {}".format(clock() - t0)) flag = True for n, p in enumerate(primes): n += 1 if n % 2 == 0: continue r = (2 * p * n) % (p * p) if r > 10 ** 10: ...
Python
zaydzuhri_stack_edu_python
function process self event begin if event_type == string created begin with open src_path string rb as photo begin call tweet CONFIG call get_random_tweet_quote photo=photo end move src_path IMAGE_PROCESSED_PATH end end function
def process(self, event): if event.event_type == 'created': with open(event.src_path, 'rb') as photo: tweet(CONFIG, get_random_tweet_quote(), photo=photo) shutil.move(event.src_path, IMAGE_PROCESSED_PATH)
Python
nomic_cornstack_python_v1
function copy_file_node user host identity_file local_path remote_path begin set ssh_client = call get_ssh_client user=user host=host identity_file=identity_file with ssh_client begin set remote_dir = directory name posixpath remote_path try begin call ssh_check_output client=ssh_client command=format string test -d {p...
def copy_file_node( *, user: str, host: str, identity_file: str, local_path: str, remote_path: str): ssh_client = get_ssh_client( user=user, host=host, identity_file=identity_file) with ssh_client: remote_dir = posixpath.dirname(re...
Python
nomic_cornstack_python_v1
function numericalize self phonemes begin set ids = list comprehension call lookup item for item in phonemes if item in stoi return ids end function
def numericalize(self, phonemes): ids = [ self.vocab.lookup(item) for item in phonemes if item in self.vocab.stoi ] return ids
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 2021/2/9 下午1:59 comment @Author : jt_hou comment @Email : 949241101@qq.com comment @File : util.py from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardSca...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/2/9 下午1:59 # @Author : jt_hou # @Email : 949241101@qq.com # @File : util.py from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler def load_data(): "...
Python
zaydzuhri_stack_edu_python
function contains argList argState begin for item in argList begin if m == m and c == c and b == b begin return true end end return false end function
def contains(argList, argState): for item in argList: if (item.m == argState.m and item.c == argState.c and item.b == argState.b): return True return False
Python
nomic_cornstack_python_v1
comment coding:utf-8 import time import threading set __author__ = string xudazhou set k1 = string v1 function run_thread begin comment 全局变量 k1 可以传进来 print string thread %s is running %s % tuple name k1 end function if __name__ == string __main__ begin print string thread %s is begin % name set t = thread target=run_th...
# coding:utf-8 import time import threading __author__ = 'xudazhou' k1 = "v1" def run_thread(): # 全局变量 k1 可以传进来 print("thread %s is running %s" % (threading.current_thread().name, k1)) if __name__ == "__main__": print("thread %s is begin" % threading.current_thread().name) t = threading.Thread(tar...
Python
zaydzuhri_stack_edu_python
from tkinter import * import random import numpy as np import pandas as pd from tkinter import messagebox from tkinter import filedialog import serial comment Settings set root = call Tk comment Size of window call geometry string 950x400 comment Not resizable call resizable 0 0 call configure background=string khaki t...
from tkinter import * import random import numpy as np import pandas as pd from tkinter import messagebox from tkinter import filedialog import serial ##Settings root = Tk() root.geometry("950x400") #Size of window root.resizable(0,0) #Not resizable root.configure(background="khaki") root.title("Glove data ...
Python
zaydzuhri_stack_edu_python
import cv2 import os import numpy as np from random import shuffle from tqdm import tqdm import tflearn from tflearn.layers.conv import conv_2d , max_pool_2d from tflearn.layers.core import input_data , dropout , fully_connected from tflearn.layers.estimator import regression import pandas as pd from csv import writer ...
import cv2 import os import numpy as np from random import shuffle from tqdm import tqdm import tflearn from tflearn.layers.conv import conv_2d, max_pool_2d from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression import pandas as pd from csv import ...
Python
zaydzuhri_stack_edu_python
string Implemente a função incomodam(n) que devolve uma string contendo "incomodam " (a palavra seguida de um espaço) n vezes. Se n não for um inteiro estritamente positivo, a função deve devolver uma string vazia. Essa função deve ser implementada utilizando recursão. Utilizando a função acima, implemente a função ele...
""" Implemente a função incomodam(n) que devolve uma string contendo "incomodam " (a palavra seguida de um espaço) n vezes. Se n não for um inteiro estritamente positivo, a função deve devolver uma string vazia. Essa função deve ser implementada utilizando recursão. Utilizando a função acima, implemente a função ele...
Python
zaydzuhri_stack_edu_python
from os import system from models import Product , Department , Invoice , session , Admin from getpass import getpass from adminMenu import * comment create_dept = Department(name="Cosmetic") comment session.add(create_dept) comment session.commit() comment vaseline = Product( comment name="Vaseline", comment price=100...
from os import system from models import Product, Department, Invoice, session,Admin from getpass import getpass from adminMenu import * # # create_dept = Department(name="Cosmetic") # session.add(create_dept) # session.commit() # # vaseline = Product( # name="Vaseline", # price=100, # discount=...
Python
zaydzuhri_stack_edu_python
comment Star Database from orbtools import * comment ------------------------------------------------------------------------------- comment Magnitude to luminosity (x Sun) conversion comment ------------------------------------------------------------------------------- function mag2L mag begin return 10 ^ 4.85 - mag ...
################################################################################ # # Star Database # ################################################################################ from orbtools import * #------------------------------------------------------------------------------- # Magnitude to luminosity (x Sun...
Python
zaydzuhri_stack_edu_python
function discriminator_block in_filters out_filters normalization=true begin set layers = list conv 2d in_filters out_filters 4 stride=2 padding=1 if normalization begin append layers instance norm 2d out_filters end append layers leaky relu 0.2 inplace=true return layers end function
def discriminator_block(in_filters, out_filters, normalization=True): layers = [nn.Conv2d(in_filters, out_filters, 4, stride=2, padding=1)] if normalization: layers.append(nn.InstanceNorm2d(out_filters)) layers.append(nn.LeakyReLU(0.2, inplace=True)) retur...
Python
nomic_cornstack_python_v1
comment Prepare epression for calculation. comment For it, delete all spaces, and give negative numbers good form. import re from shared import * from errors import * function prepare_expression expression begin if length expression >= 0 begin set wrong_functions = call is_good expression if wrong_functions begin raise...
#Prepare epression for calculation. #For it, delete all spaces, and give negative numbers good form. import re from shared import * from errors import * def prepare_expression(expression): if len(expression) >= 0: wrong_functions = is_good(expression) if wrong_functions: raise Unknown...
Python
zaydzuhri_stack_edu_python
comment Write a function called hide_and_seek. The function should comment have no parameters and return no value; instead, when comment called, it should just print the numbers from 1 through 10, comment follow by the text "Ready or not, here I come!". Each comment number and the message at the end should be on its ow...
# Write a function called hide_and_seek. The function should # have no parameters and return no value; instead, when # called, it should just print the numbers from 1 through 10, # follow by the text "Ready or not, here I come!". Each # number and the message at the end should be on its own # line. # # Then, call the f...
Python
zaydzuhri_stack_edu_python
function __init__ self samples_per_cls no_of_classes gamma=2 beta=0.9999 use_gpu=true loss_type=string focal begin call __init__ set samples_per_cls = samples_per_cls set no_of_classes = no_of_classes set gamma = gamma set beta = beta set use_gpu = use_gpu set loss_type = loss_type end function
def __init__(self, samples_per_cls, no_of_classes, gamma=2, beta=0.9999, use_gpu=True, loss_type='focal'): super(CBFocalLoss, self).__init__() self.samples_per_cls = samples_per_cls self.no_of_classes = no_of_classes self.gamma = gamma self.beta = beta self.use_gpu = use_...
Python
nomic_cornstack_python_v1
comment 类变量和实例变量的查找顺序 class Student begin comment 学生总人数 set sum = 0 comment 类变量 set name = string 七月 set age = 0 function __init__ self name age begin comment 正确的实例变量表示方式,实例变量名仍然为name、age。 set name = name comment self代表的就是实例对象本身; set age = age end function end class set student1 = call Student string 石敢当 6 print name p...
#类变量和实例变量的查找顺序 class Student(): sum = 0 #学生总人数 name = '七月' #类变量 age = 0 def __init__(self,name,age): self.name = name #正确的实例变量表示方式,实例变量名仍然为name、age。 self.age = age #self代表的就是实例对象本身; student1 = Student('石敢当',6) print(student1.name) print(Student.name) #用一个...
Python
zaydzuhri_stack_edu_python
function test_connect rgd begin assert connected is true end function
def test_connect(rgd): assert rgd.connected is True
Python
nomic_cornstack_python_v1
import sys class RobotCommand begin set _robot = 0 function __init__ self begin set _robot = 0 end function function setRobot self robot begin set _robot = robot end function function doCommand self begin print string Commande vide file=stderr end function end class
import sys class RobotCommand: _robot = 0 def __init__(self): _robot = 0 def setRobot(self, robot): self._robot = robot def doCommand(self): print("Commande vide", file=sys.stderr)
Python
zaydzuhri_stack_edu_python
function _conf self **kwargs begin call _conf title=string spotu end function
def _conf(self, **kwargs): super()._conf(title='spotu')
Python
nomic_cornstack_python_v1
class Solution begin function singleNumber self nums begin set res = 0 for num in nums begin set res = res ? num end return res end function end class if __name__ == string __main__ begin set im = list 2 2 1 print call singleNumber im end
class Solution: def singleNumber(self, nums): res = 0 for num in nums: res ^= num return res if __name__ == '__main__': im = [2,2,1] print(Solution().singleNumber(im))
Python
zaydzuhri_stack_edu_python
comment Ian Letourneau comment 4/25/2018 comment A script that takes parameters and returns values at nth point in either a fibonacci or lucas sequence function fibonacci n begin string A function to return the nth number in the Fibonacci sequence if not n begin return 0 end else if n == 1 begin return 1 end else begin...
## Ian Letourneau ## 4/25/2018 ## A script that takes parameters and returns values at nth point in either a fibonacci or lucas sequence def fibonacci(n): """A function to return the nth number in the Fibonacci sequence""" if not n: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) ...
Python
zaydzuhri_stack_edu_python
function test_show_combined_abc self begin set client = call Client comment Create three tunes to go into database comment with abc text set tune1 = call TuneFactory name=string Tune 1 tune_type=call TuneTypeFactory tune_type_char=string reel set abctune1 = call ABCTuneFactory tune=tune1 set abctune1peice1 = call ABCTu...
def test_show_combined_abc(self): client = Client() # Create three tunes to go into database # with abc text tune1 = factories.TuneFactory( name = "Tune 1", tune_type = factories.TuneTypeFactory( tune_type_char = "reel" ) ) ...
Python
nomic_cornstack_python_v1
import cv2 import numpy as np set img = call imread string puppy.jpg set tuple height width _ = call shape img comment calculate the average color of each row of our image set avg_color_per_row = call average img axis=0 comment calculate the averages of our rows set avg_colors = call average avg_color_per_row axis=0 co...
import cv2 import numpy as np img = cv2.imread('puppy.jpg') height, width, _ = np.shape(img) # calculate the average color of each row of our image avg_color_per_row = np.average(img, axis=0) # calculate the averages of our rows avg_colors = np.average(avg_color_per_row, axis=0) # avg_color is a tuple in BGR order ...
Python
zaydzuhri_stack_edu_python
from c2 import People class Man extends People begin set sum = 0 function __init__ self work name age begin call __init__ name age comment super(Man, self).__init__(name, age) comment People.__init__(self, name, age) # 父类构造函数调用时写入self的变量也写入了子类的self中 comment name和age通过父类写入self set work = work end function comment 注意要传入s...
from c2 import People class Man(People): sum = 0 def __init__(self, work, name, age): super().__init__(name, age) # super(Man, self).__init__(name, age) # People.__init__(self, name, age) # 父类构造函数调用时写入self的变量也写入了子类的self中 self.work = work # name和age通过父类写入self def print_demo(s...
Python
zaydzuhri_stack_edu_python
function _reset_journal self begin try begin if _journal begin close _journal end set _journal = none set _poll = none comment open the journal, limiting it to read logs since boot set _journal = reader path=_journal_path call this_boot comment add any filters for match in _matches begin call add_match match end commen...
def _reset_journal(self): try: if self._journal: self._journal.close() self._journal = None self._poll = None # open the journal, limiting it to read logs since boot self._journal = journal.Reader(path=self._journal_path) ...
Python
nomic_cornstack_python_v1
import time , sys , os comment Defines person's age & name class person begin function __init__ self begin set name = string set age = 0 end function end class set your = call person comment Ask for name function name questionName begin set inputName = string while not is alpha inputName begin for x in questionName b...
import time, sys, os # Defines person's age & name class person(): def __init__(self): self.name = '' self.age = 0 your = person() # Ask for name def name(questionName): inputName = '' while not inputName.isalpha(): for x in questionName: sys.stdout.write(x) sys.stdout.flush() ...
Python
zaydzuhri_stack_edu_python
function test_new_create_resgate_successful self begin set payload = dict string value 500 ; string user user set response = post RESGATE_URL payload assert equal status_code HTTP_201_CREATED end function
def test_new_create_resgate_successful(self): payload = { 'value': 500, 'user': self.user } response = self.client.post(RESGATE_URL, payload) self.assertEqual(response.status_code, status.HTTP_201_CREATED)
Python
nomic_cornstack_python_v1
function cached_value compute name typ=string pkl override=false debug=none begin set debug = debug or lambda msg -> none if not DISABLE_CACHING and not override and call is_cached name typ begin debug format string Loading cached '{}'... name try begin set result = call load_cache name typ debug string ...done. return...
def cached_value(compute, name, typ="pkl", override=False, debug=None): debug = debug or (lambda msg: None) if not DISABLE_CACHING and not override and is_cached(name, typ): debug("Loading cached '{}'...".format(name)) try: result = load_cache(name, typ) debug("...done.") return result ...
Python
nomic_cornstack_python_v1
import numpy as np from pymatrix import Matrix from pymatrix import Spmatrix from pymatrix import Operation import random class FeatureMatrix extends Matrix begin decorator staticmethod function create_rotation_matrix dimension p q theta rou=3 begin set matrix_origin = call diagonal call Spmatrix dimension 1 set matrix...
import numpy as np from pymatrix import Matrix from pymatrix import Spmatrix from pymatrix import Operation import random class FeatureMatrix(Matrix): @staticmethod def create_rotation_matrix(dimension, p, q, theta, rou=3): matrix_origin = Spmatrix.diagonal(Spmatrix(), dimension, 1) matrix_ori...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import pandas as pd import matplotlib.pylab as plt set data = read csv string data1.csv comment print(data.head()) comment print(data.dtypes) comment training set set X = data at string Input / 200 set Y = data at string Output comment plot the graph comment plt.plot(X,Y) set m = length X ...
# -*- coding: utf-8 -*- import pandas as pd import matplotlib.pylab as plt data = pd.read_csv("data1.csv") #print(data.head()) #print(data.dtypes) # training set X = data['Input']/200 Y = data['Output'] # plot the graph # plt.plot(X,Y) m = len(X) t0 = 0 t1 = 0 alpha = 0.001 def calc_hx(t0, t1, X): hx = [] ...
Python
zaydzuhri_stack_edu_python
from collections import Counter class Solution extends object begin function topKFrequent self nums k begin string :type nums: List[int] :type k: int :rtype: List[int] set elemDict = dict for elem in nums begin if elem not in elemDict begin set elemDict at elem = 1 end else begin set elemDict at elem = elemDict at ele...
from collections import Counter class Solution(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ elemDict = {} for elem in nums: if elem not in elemDict: elemDict[elem] = 1 ...
Python
zaydzuhri_stack_edu_python
function _minimax_decision gameState begin comment The built in `max()` function can be used as argmax! return max call get_legal_moves key=lambda m -> call min_value call forecast_move m end function
def _minimax_decision(gameState): # The built in `max()` function can be used as argmax! return max(gameState.get_legal_moves(), key=lambda m: min_value(gameState.forecast_move(m)))
Python
nomic_cornstack_python_v1
function mirror self begin set screen_width = call get_width set screen_height = call get_height if centerx < 0 and vx < 0 begin set centerx = screen_width end if centerx > screen_width begin set centerx = 0 end if centery < 0 and vy < 0 begin set centery = 0 end if centery > screen_height and vy > 0 begin set centery ...
def mirror(self): screen_width = self.game.screen.get_width() screen_height = self.game.screen.get_height() if self.rect.centerx < 0 and self.vx < 0: self.rect.centerx = screen_width if self.rect.centerx > screen_width: self.rect.centerx = 0 if s...
Python
nomic_cornstack_python_v1
comment coding: utf-8 import numpy as np import scipy.special import matplotlib.pyplot as plt comment 神经网络类定义 class nerualNetwork begin comment 初始化神经网络 function __init__ self inputNodes hiddenNodes outputNodes learningRate begin comment 设置神经网络输入层、隐藏层、输出层节点数量 set iNodes = inputNodes set hNodes = hiddenNodes set oNodes =...
# coding: utf-8 import numpy as np import scipy.special import matplotlib.pyplot as plt # 神经网络类定义 class nerualNetwork: # 初始化神经网络 def __init__(self, inputNodes, hiddenNodes, outputNodes, learningRate): # 设置神经网络输入层、隐藏层、输出层节点数量 self.iNodes = inputNodes self.hNodes = hiddenNo...
Python
zaydzuhri_stack_edu_python
function solve t=none begin set prob = _models at 0 return call solve t end function
def solve(t=None): prob = _models[0] return prob.solve(t)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Date : 2016-10-26 09:32:58 comment @Author : luckcul (tyfdream@gmail.com) comment @Version : 2.7.12 class Solution extends object begin set mark = list 0 * 11 function find self k begin set cou = 0 for i in range 1 11 begin if mark at i == 0 begin set ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-10-26 09:32:58 # @Author : luckcul (tyfdream@gmail.com) # @Version : 2.7.12 class Solution(object): mark = [0]*11 def find(self, k): cou = 0 for i in range(1, 11): if self.mark[i] == 0: cou += 1 ...
Python
zaydzuhri_stack_edu_python
function compare self other begin comment Nothing to do as name comparison will catch differences return list end function
def compare(self, other): # Nothing to do as name comparison will catch differences return []
Python
nomic_cornstack_python_v1
function _attribute_names self begin set non_callables = list comprehension member at 0 for member in get members self lambda x -> not callable x set attribute_names = list comprehension name for name in non_callables if call _is_public name return attribute_names end function
def _attribute_names(self) -> List[str]: non_callables = [ member[0] for member in inspect.getmembers(self, lambda x: not callable(x)) ] attribute_names = [name for name in non_callables if self._is_public(name)] return attribute_names
Python
nomic_cornstack_python_v1
function GetBasenameFromMojoApp url begin set index = reverse find url string / return if expression index != - 1 then url at slice index + 1 : : else url end function
def GetBasenameFromMojoApp(url): index = url.rfind('/') return url[(index + 1):] if index != -1 else url
Python
nomic_cornstack_python_v1
function normalize_crosscut xcut begin comment Normalize return xcut / 4 * call nanstd xcut at call isfinite xcut end function
def normalize_crosscut(xcut): # Normalize return xcut / (4 * np.nanstd(xcut[np.isfinite(xcut)]))
Python
nomic_cornstack_python_v1
function validate_choice choice func_dict begin try begin set func = func_dict at upper choice end except any begin comment raise ValueError(f"Invalid Selection. Got: {choice}.") info string Invalid Selction. Got: { choice } if active_user is not none begin call logged_in_main active_user end else begin call main end e...
def validate_choice(choice, func_dict): try: func = func_dict[choice.upper()] except: #raise ValueError(f"Invalid Selection. Got: {choice}.") logger.info(f"Invalid Selction. Got: {choice}") if active_user is not None: logged_in_main(active_user) else: ...
Python
nomic_cornstack_python_v1
function first self begin string Return the first result. If there are no results, raises :exc:`~bloop.exceptions.ConstraintViolation`. :return: The first result. :raises bloop.exceptions.ConstraintViolation: No results. call reset set value = next self none if value is none begin raise call ConstraintViolation format ...
def first(self): """Return the first result. If there are no results, raises :exc:`~bloop.exceptions.ConstraintViolation`. :return: The first result. :raises bloop.exceptions.ConstraintViolation: No results. """ self.reset() value = next(self, None) if value is ...
Python
jtatman_500k
function read_an_object target_file begin with open target_file string rb as backup_file begin set pick = call Unpickler backup_file return load pick end end function
def read_an_object(target_file): with open(target_file, "rb") as backup_file: pick = pickle.Unpickler(backup_file) return pick.load()
Python
nomic_cornstack_python_v1
function validate_user self user_id begin raise NotImplementedError end function
def validate_user(self, user_id: int): raise NotImplementedError
Python
nomic_cornstack_python_v1
function create_carbon_dioxide_level_sensor_service begin set service = call FakeService string public.hap.service.sensor.carbon-dioxide set cur_state = call add_characteristic string carbon-dioxide.level set value = 0 return service end function
def create_carbon_dioxide_level_sensor_service(): service = FakeService("public.hap.service.sensor.carbon-dioxide") cur_state = service.add_characteristic("carbon-dioxide.level") cur_state.value = 0 return service
Python
nomic_cornstack_python_v1
function batchseeds args begin from jcvi.formats.pdf import cat set xargs = args at slice 1 : : set p = call OptionParser __doc__ set tuple opts args iopts = call add_seeds_options p args if length args != 1 begin exit not call print_help end set tuple folder = args set folder = right strip folder string / set outdir...
def batchseeds(args): from jcvi.formats.pdf import cat xargs = args[1:] p = OptionParser(batchseeds.__doc__) opts, args, iopts = add_seeds_options(p, args) if len(args) != 1: sys.exit(not p.print_help()) (folder,) = args folder = folder.rstrip("/") outdir = folder + "-debug" ...
Python
nomic_cornstack_python_v1
from selenium import webdriver from selenium.webdriver.common.by import By import time import logging call basicConfig level=INFO format=string %(asctime)s - %(levelname)s - %(funcName)s : %(message)s datefmt=string %H:%M:%S filename=string autentificare_log file.log class LogareCont extends object begin function __ini...
from selenium import webdriver from selenium.webdriver.common.by import By import time import logging logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(funcName)s : %(message)s", datefmt= "%H:%M:%S", filename="autentificare...
Python
zaydzuhri_stack_edu_python
function get_best_state self begin return best_state end function
def get_best_state(self): return self.best_state
Python
nomic_cornstack_python_v1
function add_dihedral_restraint self i j k l exp_Jcoupling model_Jcoupling=none equivalency_index=none karplus_key=string Karplus_HH begin comment if the modeled Jcoupling value is not specified, compute it from the comment angle corresponding to the conformation, and the Karplus relation if model_Jcoupling == none beg...
def add_dihedral_restraint(self, i, j, k, l, exp_Jcoupling, model_Jcoupling=None, equivalency_index=None, karplus_key="Karplus_HH"): # if the modeled Jcoupling value is not specified, compute it from the # angle corresponding to the conformation, and the Karplus relation...
Python
nomic_cornstack_python_v1
function test_load_permissions_on_identity_loaded app begin call InvenioAccess app with call test_request_context begin call send call _get_current_object identity=call AnonymousIdentity assert provides == set literal any_user end with call test_request_context begin set user = call create_test_user string test@example...
def test_load_permissions_on_identity_loaded(app): InvenioAccess(app) with app.test_request_context(): identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity()) assert g.identity.provides == {any_user} with app.test_request_context...
Python
nomic_cornstack_python_v1
for t in range integer input begin set J = set input set S = list input set gems = 0 for i in J begin set gems = gems + count S i end print gems end
for t in range(int(input())): J = set(input()) S = list(input()) gems = 0 for i in J: gems += S.count(i) print(gems)
Python
zaydzuhri_stack_edu_python
import numpy as np comment pos def metric function random_wishart nmod begin set vars = list comprehension 1.0 / decimal nmod ^ 1.0 / 2.0 for i in range nmod + 2 comment A = np.array([np.random.normal(loc = 0, scale = vars[pp],size = nmod )for pp in range(nmod)]) set A00 = call normal loc=0 scale=vars at nmod + 1 set A...
import numpy as np def random_wishart(nmod): # pos def metric vars = [1./np.float(nmod)**(1./2.) for i in range(nmod + 2)] #A = np.array([np.random.normal(loc = 0, scale = vars[pp],size = nmod )for pp in range(nmod)]) A00 = np.random.normal(loc = 0, scale = vars[nmod + 1]) A0a = np.array(np.random.nor...
Python
zaydzuhri_stack_edu_python
function test_auto_search_double cls begin call setup_mmp_data_for_mms name string SMILES string ID string PIC50 3 0.50001 call generate_store_mmp_series sgl_or_dbl_or_both=string double comment print cls.test_mmp_series_object.series_df.to_csv() set result_df = call auto_search 5 3 strict_ordering=true comment print(r...
def test_auto_search_double(cls): cls.test_mmp_series_object.setup_mmp_data_for_mms(cls.temp_file_input_csv_double.name, 'SMILES', 'ID', 'PIC50', 3, 0.50001) cls.test_mmp_series_object.ge...
Python
nomic_cornstack_python_v1
function decode_simulation_run xml nsmap begin set decodings = list tuple string cim_info false decode_cim_info string self::cim:simulationRun tuple string date_range false decode_closed_date_range string child::cim:dateRange/cim:closedDateRange tuple string date_range false decode_open_date_range string child::cim:dat...
def decode_simulation_run(xml, nsmap): decodings = [ ('cim_info', False, decode_cim_info, 'self::cim:simulationRun'), ('date_range', False, decode_closed_date_range, 'child::cim:dateRange/cim:closedDateRange'), ('date_range', False, decode_open_date_range, 'child::cim:dateRange/cim:openDateR...
Python
nomic_cornstack_python_v1
import requests import string import random function rand_str begin return join string generator expression random choice digits for _ in range 10 end function function register begin set uname = call rand_str set pwd = call rand_str post string http://pwnable.org:2333/user/register data=dict string username uname ; s...
import requests import string import random def rand_str(): return ''.join(random.choice(string.digits) for _ in range(10)) def register(): uname = rand_str() pwd = rand_str() requests.post("http://pwnable.org:2333/user/register", data={'username':uname, 'password':pwd}) return uname, pwd def log...
Python
zaydzuhri_stack_edu_python
string Q.4 Python program for fibonacci numbers set n = integer input string Enter a no= set tuple n1 n2 = tuple 0 1 set count = 0 comment l1=[] if n <= 0 begin print string Invalid, please enter a positive integger end else if n == 1 begin print string Fabonacci sequence upto n string : print n1 end else begin print s...
'''Q.4 Python program for fibonacci numbers''' n=int(input("Enter a no= ")) n1, n2 = 0, 1 count = 0 # l1=[] if n <= 0: print("Invalid, please enter a positive integger") elif n == 1: print("Fabonacci sequence upto", n,":") print(n1) else: print("Fabonacci sseries upto", n,":") while count < n: ...
Python
zaydzuhri_stack_edu_python
comment 单分支: set name = string 赵志强 if name == string 赵志强 begin print string 老单身狗%s % name end comment 双分支: set girl_friend = string if girl_friend begin print string 恭喜啊,居然有女朋友了 end else begin print string 求求你快恋爱吧.%s. % name end comment 多分支: string 判断成绩档次小程序 90-100 A 80-89 B 60-79 C 40-59 D 0 -39 E 程序启动,用户输入成绩,根据成绩打印等...
#单分支: name = '赵志强' if name=='赵志强': print('老单身狗%s'%name) #双分支: girl_friend = '' if girl_friend: print('恭喜啊,居然有女朋友了') else: print('求求你快恋爱吧.%s.'%name) #多分支: ''' 判断成绩档次小程序 90-100 A 80-89 B 60-79 C 40-59 D 0 -39 E 程序启动,用户输入成绩,根据成绩打印等级 ''' score = int(input('请输入你的成绩:')) if 90<= score <= 100: print('A') elif 79<s...
Python
zaydzuhri_stack_edu_python