code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
string User dialog
comment Qt4 modules
from PyQt4 import QtGui
from PyQt4 import QtCore
comment Generated UI module
from lider.ui_user import Ui_dialogUser
class DialogUser extends QDialog Ui_dialogUser
begin
string Dialog for users. Usage: dialog = DialogUser(... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User dialog
"""
# Qt4 modules
from PyQt4 import QtGui
from PyQt4 import QtCore
# Generated UI module
from lider.ui_user import Ui_dialogUser
class DialogUser(QtGui.QDialog, Ui_dialogUser):
"""
Dialog for users.
Usage:
dialog = D... | Python | zaydzuhri_stack_edu_python |
function replace self pool_top_score
begin
if minimizing
begin
return pool_top_score < elite_score
end
else
begin
return pool_top_score > elite_score
end
end function | def replace(self, pool_top_score):
if self.minimizing:
return pool_top_score < self.elite_score
else:
return pool_top_score > self.elite_score | Python | nomic_cornstack_python_v1 |
import streamlit as st
import mysql.connector
from mysql.connector import Error
function run_insert
begin
set title = call text_input string 책의 제목을 입력하세요
set author_fname = call text_input string 작가의 이름을 입력하세요
set author_lname = call text_input string 작가의 성씨를 입력하세요
set released_year = call number_input string 출판년도를 입력하... | import streamlit as st
import mysql.connector
from mysql.connector import Error
def run_insert():
title = st.text_input('책의 제목을 입력하세요')
author_fname = st.text_input('작가의 이름을 입력하세요')
author_lname = st.text_input('작가의 성씨를 입력하세요')
released_year = st.number_input('출판년도를 입력하세요',0)
stock_quantity = st.n... | Python | zaydzuhri_stack_edu_python |
function test_negative_exponents
begin
with raises ValueError
begin
call power 1 - 1
end
end function | def test_negative_exponents():
with raises(ValueError):
power(1, -1) | Python | nomic_cornstack_python_v1 |
function tfilterstr2query filters
begin
set query = list
for f in filters
begin
if f at 0 in list string > string <
begin
if f at 1 == string =
begin
set op = f at slice : 2 :
set f1 = f at slice 2 : :
end
else
begin
set op = f at 0
set f1 = f at slice 1 : :
end
end
else
begin
set op = string =
set f1 = f
end
tr... | def tfilterstr2query(filters):
query = []
for f in filters:
if f[0] in ['>', '<']:
if f[1] == '=':
op = f[:2]
f1 = f[2:]
else:
op = f[0]
f1 = f[1:]
else:
op = '='
f1 = f
try:... | Python | nomic_cornstack_python_v1 |
from pymongo import MongoClient
import datetime
set client = call MongoClient
set db = client at string pymongo_test
set collection = db at string stuff
set a = dict string station string KUSA ; string start call utcnow ; string question string do you like ketchup? ; string options list string yes string no string must... | from pymongo import MongoClient
import datetime
client = MongoClient()
db = client['pymongo_test']
collection = db['stuff']
a = {
'station': 'KUSA',
'start': datetime.datetime.utcnow(),
'question': "do you like ketchup?",
'options': [
'yes',
'no',
'mustard'
]
}
print("ins... | Python | zaydzuhri_stack_edu_python |
comment 리스트의 복사
comment a 리스트 요소를 a2 리스트로 복사(저장)
set a = list 1 2 3 4 5 6
set a2 = list
for i in a
begin
append a2 i
end
print a2
comment a 리스트의 홀수를 a3리스트에 저장
set a3 = list
for i in a
begin
if i % 2 == 1
begin
append a3 i
end
end
print a3 | #리스트의 복사
#a 리스트 요소를 a2 리스트로 복사(저장)
a = [1,2,3,4,5,6]
a2 = []
for i in a:
a2.append(i)
print(a2)
#a 리스트의 홀수를 a3리스트에 저장
a3 = []
for i in a:
if i % 2 == 1:
a3.append(i)
print(a3)
| Python | zaydzuhri_stack_edu_python |
function remote_tag tag
begin
set url = string %s/git/refs/tags % call get_github_api_url
for result in json get requests url
begin
try
begin
if result at string ref == string refs/tags/%s % tag
begin
return result
end
end
except TypeError
begin
return
end
end
end function | def remote_tag(tag):
url = "%s/git/refs/tags" % get_github_api_url()
for result in requests.get(url).json():
try:
if result["ref"] == "refs/tags/%s" % tag:
return result
except TypeError:
return | Python | nomic_cornstack_python_v1 |
function get self
begin
if call getSolenoid forwardHandle
begin
return kForward
end
if call getSolenoid reverseHandle
begin
return kReverse
end
return kOff
end function | def get(self):
if hal.getSolenoid(self.forwardHandle):
return self.Value.kForward
if hal.getSolenoid(self.reverseHandle):
return self.Value.kReverse
return self.Value.kOff | Python | nomic_cornstack_python_v1 |
function consolidate_stats dict_of_seqs stats_key=none sep=string ,
begin
if is instance dict_of_seqs dict
begin
set stats = dict_of_seqs at stats_key
set keys = call joined_seq sorted list comprehension k for k in dict_of_seqs if k is not stats_key sep=none
set joined_key = call joined_seq keys sep=sep
set result = di... | def consolidate_stats(dict_of_seqs, stats_key=None, sep=','):
if isinstance(dict_of_seqs, dict):
stats = dict_of_seqs[stats_key]
keys = joined_seq(sorted([k for k in dict_of_seqs if k is not stats_key]), sep=None)
joined_key = joined_seq(keys, sep=sep)
result = {stats_key: [], joined... | Python | nomic_cornstack_python_v1 |
string Loads data from Bittrex. @author: Tobias Carryer
from cryptotrader.librariesrequired.bittrex.bittrex import Bittrex
import time
from threading import Thread
from bittrex_ignore import BittrexSecret
class BittrexPipeline extends object
begin
function __init__ self on_market_summary poll_time=15 minor_currency=str... | '''
Loads data from Bittrex.
@author: Tobias Carryer
'''
from cryptotrader.librariesrequired.bittrex.bittrex import Bittrex
import time
from threading import Thread
from bittrex_ignore import BittrexSecret
class BittrexPipeline(object):
def __init__(self, on_market_summary, poll_time=15, minor_currency="BTC"):
... | Python | zaydzuhri_stack_edu_python |
string 17.Print the first 100 odd numbers
set n = input string enter up to which range do you required odd numbers:
set lt = generator expression i for i in range 1 n if i % 2 != 0 | """
17.Print the first 100 odd numbers
"""
n=input("enter up to which range do you required odd numbers:")
lt=(i for i in range(1,n) if i%2!=0) | Python | zaydzuhri_stack_edu_python |
import tkinter
from tkinter import *
import math
import wave
import numpy as np
import matplotlib.pyplot as plot
import pyaudio
import struct
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import scipy.io.wavfile
from tkinter import filedialog as fd
comment --------... | import tkinter
from tkinter import *
import math
import wave
import numpy as np
import matplotlib.pyplot as plot
import pyaudio
import struct
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import scipy.io.wavfile
from tkinter import filedialog as fd
#--------------... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function isHappy self n
begin
string :type n: int :rtype: bool
set newset = set
while n != 1
begin
set temp = 0
for char in string n
begin
set temp = temp + integer char ^ 2
end
if temp in newset
begin
return false
end
else
begin
add newset temp
end
set n = temp
end
return true
end function
end cla... | class Solution:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
newset = set()
while n != 1 :
temp = 0
for char in str(n):
temp += int(char)**2
if temp in newset:
return False
el... | Python | zaydzuhri_stack_edu_python |
function export_privkey self password
begin
try
begin
set address = call get_addresses at 0
set priv = call export_private_key address password=password
if - 1 != find priv string :
begin
set priv = split priv string : at 1
end
return priv
end
except BaseException as e
begin
raise e
end
end function | def export_privkey(self, password):
try:
address = self.wallet.get_addresses()[0]
priv = self.wallet.export_private_key(address, password=password)
if -1 != priv.find(":"):
priv = priv.split(":")[1]
return priv
except BaseException as e:
... | Python | nomic_cornstack_python_v1 |
class Math
begin
decorator staticmethod
function add5 x
begin
return x + 5
end function
end class
print call add5 5 | class Math:
@staticmethod
def add5(x):
return x + 5
print(Math.add5(5)) | Python | zaydzuhri_stack_edu_python |
string 1、train.csv文中,包含了台湾包含台湾丰原地区240天的气象观测资料(取每个月前20天 的数据做训练集,12月X20天=240天,每月后10天数据用于测试,对学生不可见) 2、每天的监测时间点为0时,1时......到23时,共24个时间节点。 3、每天的检测指标包括CO、NO、PM2.5、PM10等气体浓度,是否降雨、刮风等气象信息,共计18项 为了便于测试预测模型。 使用连续8天的气象观测数据,来预测第9天的PM2.5含量。根据李宏毅老师采用热成像法和散点图法对观测数据分析,可以得知 PM2.5、PM10、SO2与PM2.5的预测存在着较大联系,因此将使用这三种属性来预测第9天的PM2.5值。
import... | '''
1、train.csv文中,包含了台湾包含台湾丰原地区240天的气象观测资料(取每个月前20天
的数据做训练集,12月X20天=240天,每月后10天数据用于测试,对学生不可见)
2、每天的监测时间点为0时,1时......到23时,共24个时间节点。
3、每天的检测指标包括CO、NO、PM2.5、PM10等气体浓度,是否降雨、刮风等气象信息,共计18项
为了便于测试预测模型。
使用连续8天的气象观测数据,来预测第9天的PM2.5含量。根据李宏毅老师采用热成像法和散点图法对观测数据分析,可以得知
PM2.5、PM10、SO2与PM2.5的预测存在着较大联系,因此将使用... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
from typing import List
from stock_utils import qfq , stock_kline_day
function full_feature_cols featue_cols steps
begin
set result = list
for step in range 1 steps + 1
begin
for col in featue_cols
begin
append result format string {0}_{1} col step
end
end
return result
end funct... | import pandas as pd
import numpy as np
from typing import List
from stock_utils import qfq, stock_kline_day
def full_feature_cols(featue_cols: List[str], steps: int) -> List[str]:
result = []
for step in range(1, steps + 1):
for col in featue_cols:
result.append("{0}_{1}".format(col, step)... | Python | zaydzuhri_stack_edu_python |
function __repr__ self
begin
return call to_str
end function | def __repr__(self):
return self.to_str() | Python | nomic_cornstack_python_v1 |
function draw self screen
begin
comment Background drawing code can be put here
comment Draw all the sprite lists that we have
call draw screen
call draw screen
end function | def draw(self, screen):
# Background drawing code can be put here
# Draw all the sprite lists that we have
self.platform_list.draw(screen)
self.enemy_list.draw(screen) | Python | nomic_cornstack_python_v1 |
string 创建微信登录页面PO 1. 通讯录页面 返回通讯录页面对象 2. 添加成员页面 返回添加成员页面对象
from selenium.webdriver.common.by import By
from weixin_combat2.page.add_member_page import AddMemberPage
from weixin_combat2.page.base_page import BasePage
from weixin_combat2.page.contact_page import ContactPage
comment 继承BasePage类,复用webdriver对象、查找元素方法
class M... | """
创建微信登录页面PO
1. 通讯录页面
返回通讯录页面对象
2. 添加成员页面
返回添加成员页面对象
"""
from selenium.webdriver.common.by import By
from weixin_combat2.page.add_member_page import AddMemberPage
from weixin_combat2.page.base_page import BasePage
from weixin_combat2.page.contact_page import ContactPage
# 继承BasePage类,复用webdriver对象、查找元素方法
cla... | Python | zaydzuhri_stack_edu_python |
import os
from argparse import ArgumentDefaultsHelpFormatter , ArgumentParser
from collections import defaultdict
from glob import glob
from pandas import read_csv
function get_prefix results
begin
string
if split path results at 1 == string topic-keys.txt
begin
return split path split path results at 0 at 1
end
else
... | import os
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
from collections import defaultdict
from glob import glob
from pandas import read_csv
def get_prefix(results):
"""
"""
if os.path.split(results)[1] == 'topic-keys.txt':
return os.path.split(os.path.split(results)[0])[1]
... | Python | zaydzuhri_stack_edu_python |
class Rectangle
begin
function __init__ self height width
begin
set height = height
set width = width
end function
end class
set rect1 = call Rectangle 20 60
set rect2 = call Rectangle 50 40
print height * width
print height * width | class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width
rect1 = Rectangle(20, 60)
rect2 = Rectangle(50, 40)
print(rect1.height * rect1.width)
print(rect2.height * rect2.width) | Python | zaydzuhri_stack_edu_python |
class Node extends object
begin
function __init__ self data next=none
begin
string Instantiates a Node with default next of None
set data = data
set next = next
end function
end class
class TwoWayNode extends Node
begin
function __init__ self data previous=none next=none
begin
call __init__ self data next
set previous ... | class Node(object):
def __init__(self, data, next=None):
"""Instantiates a Node with default next of None"""
self.data = data
self.next = next
class TwoWayNode(Node):
def __init__(self, data, previous=None, next=None):
Node.__init__(self, data, next)
self.previous = p... | Python | zaydzuhri_stack_edu_python |
comment list_len = len(name_list)
comment print("There are %d elements in this list" % list_len)
comment There are 5 elements in this list
comment count
comment count = name_list.count("jack")
comment print("jack has appeared %d time in this list" % count)
comment jack has appeared 2 time in this list
comment # remove
... | # list_len = len(name_list)
# print("There are %d elements in this list" % list_len)
#
# There are 5 elements in this list
# count
# count = name_list.count("jack")
# print("jack has appeared %d time in this list" % count)
#
# jack has appeared 2 time in this list
#
# # remove
# name_list.remove("linda")
#
# print... | Python | zaydzuhri_stack_edu_python |
for line in in_file
begin
set line = strip line string
set fields = split line string
set tuple rank boyname girlname = fields
comment Add (name,rank) in dictionary 'dict'
if boyname not in dict
begin
set dict at boyname = rank
end
if girlname not in dict
begin
set dict at girlname = rank
end
end
comment Print data sor... | for line in in_file:
line = line.strip('\n')
fields = line.split(' ')
(rank, boyname, girlname) = fields
# Add (name,rank) in dictionary 'dict'
if boyname not in dict:
dict[boyname] = rank
if girlname not in dict:
dict[girlname] = rank
# Print data sorted by name in alphabetica... | Python | zaydzuhri_stack_edu_python |
comment https://www.kaggle.com/neelkudu28/covid-19-visualizations-predictions-forecasting ---- Covid Predictions used for Polynomial regression and Holt prediction
comment https://www.kaggle.com/saga21/covid-global-forecast-sir-model-ml-regressions ----- Covid predictions used for Linear Lagged prediction model
import ... | #### https://www.kaggle.com/neelkudu28/covid-19-visualizations-predictions-forecasting ---- Covid Predictions used for Polynomial regression and Holt prediction
## https://www.kaggle.com/saga21/covid-global-forecast-sir-model-ml-regressions ----- Covid predictions used for Linear Lagged prediction model
import warni... | Python | zaydzuhri_stack_edu_python |
import math
set X = integer input
set ans = 100
set c = integer 0
while ans < X
begin
set ans = ans + floor ans * 0.01
set c = c + 1
end
print c | import math
X = int(input())
ans = 100
c = int(0)
while ans < X:
ans += math.floor(ans*0.01)
c += 1
print(c) | Python | zaydzuhri_stack_edu_python |
function timestamp2isoformat timestamp
begin
set date = call fromtimestamp timestamp
return call isoformat
end function | def timestamp2isoformat(timestamp):
date = datetime.fromtimestamp(timestamp)
return date.isoformat() | Python | nomic_cornstack_python_v1 |
function show_images self data vis_name=string images png_name=none normalize=false height=none max_samples=512 attention=false
begin
if is instance data Tensor
begin
if dim data != 4
begin
return none
end
comment pytorch tensor
set data = cpu data
if attention
begin
set data = power 0.5
end
comment adjust range to 0-1... | def show_images(self, data, vis_name: str = "images", png_name: str = None,
normalize: bool = False, height: int = None,
max_samples: int = 512, attention: bool = False):
if isinstance(data, torch.Tensor):
if data.dim() != 4:
return None
... | Python | nomic_cornstack_python_v1 |
string L_I_S Longest Increasing Subsequence Given a sequence, find the length of the longest increasing subsequence from a given sequence . The longest increasing subsequence means to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subs... | """
L_I_S
Longest Increasing Subsequence
Given a sequence, find the length of the longest increasing
subsequence from a given sequence .
The longest increasing subsequence means to find a subsequence
of a given sequence in which the subsequence's elements are in sorted order,
lowest to highest, and in which the subs... | Python | zaydzuhri_stack_edu_python |
import csv
from datetime import datetime
import logging
import os.path
import urllib.request
from ico_data_crawler.initial_coin_offering import ICO
class CoindeskSource
begin
set csv_import_address = string https://s3.amazonaws.com/media.coindesk.com/ico-tracker-charts/CoinDesk+ICO+Database+-+Blockchain+ICOs.csv
set no... | import csv
from datetime import datetime
import logging
import os.path
import urllib.request
from ico_data_crawler.initial_coin_offering import ICO
class CoindeskSource:
csv_import_address = "https://s3.amazonaws.com/media.coindesk.com/ico-tracker-charts/CoinDesk+ICO+Database+-+Blockchain+ICOs.csv"
now = dat... | Python | zaydzuhri_stack_edu_python |
function startup self
begin
if initialize_mp
begin
call initialize_multiprocessing
end
call startup_run
call startup_finish
end function | def startup(self):
if self.initialize_mp:
self.initialize_multiprocessing()
self.startup_run()
self.startup_finish() | Python | nomic_cornstack_python_v1 |
import sys
set input = readline
class UnionFind
begin
function __init__ self n
begin
set parent = list - 1 * n
set cnt = n
end function
function root self x
begin
if parent at x < 0
begin
return x
end
else
begin
set parent at x = call root parent at x
return parent at x
end
end function
function merge self x y
begin
se... | import sys
input = sys.stdin.readline
class UnionFind:
def __init__(self, n):
self.parent = [-1] * n
self.cnt = n
def root(self, x):
if self.parent[x] < 0:
return x
else:
self.parent[x] = self.root(self.parent[x])
return self.parent[x]
... | Python | jtatman_500k |
function get_types_by_authority self authority
begin
comment osid.type.TypeList
return
end function | def get_types_by_authority(self, authority):
return # osid.type.TypeList | Python | nomic_cornstack_python_v1 |
function set_verbosity self verbosity=none log_type=none
begin
try
begin
set int_level = integer verbosity
end
except ValueError
begin
if upper string verbosity in keys levels
begin
set level = levels at upper string verbosity
end
else
begin
return false
end
end
try else
begin
if 1 <= int_level <= 5
begin
set _levels =... | def set_verbosity(self, verbosity=None, log_type=None):
try:
int_level = int(verbosity)
except ValueError:
if str(verbosity).upper() in self.levels.keys():
level = self.levels[str(verbosity).upper()]
else:
return False
else:
... | Python | nomic_cornstack_python_v1 |
function test_user_get_solves
begin
set app = call create_ctfd
with call app_context
begin
call register_user app
set client = call login_as_user app
set r = get client string /solves
assert status_code == 200
end
end function | def test_user_get_solves():
app = create_ctfd()
with app.app_context():
register_user(app)
client = login_as_user(app)
r = client.get('/solves')
assert r.status_code == 200 | Python | nomic_cornstack_python_v1 |
function current_step self
begin
return current_step
end function | def current_step(self):
return self.dialog.current_step | Python | nomic_cornstack_python_v1 |
function plot_ECGs_for_object_data_set_g_NaL self
begin
set experiment_dir = root_dir + sep + experiment_dir
set plotter = call PlotECGs experiment_dir
set normal_dir_name = string run_5
set normal_legend = string $I_{Kr} = 0.15$
set modified_dir_name = string run_6
set modified_legend = string $I_{Kr} = 0.0$
call load... | def plot_ECGs_for_object_data_set_g_NaL(self):
experiment_dir = self.root_dir + os.sep + self.experiment_dir
plotter = ECG_plots.PlotECGs(experiment_dir)
plotter.normal_dir_name = "run_5"
plotter.normal_legend = "$I_{Kr} = 0.15$"
plotter.modified_dir_name = "run_6"
plotte... | Python | nomic_cornstack_python_v1 |
comment print(max(id))
comment print(min(id))
comment print(max(names))
comment print(min(names))
comment print(tuple(names))
comment print(list(names))
comment print(cmp(names,state))
comment print(names+students)
comment print(len(names))#finding the length of string
comment print(state*4)
comment # del names[3]
comm... | # print(max(id))
# print(min(id))
# print(max(names))
# print(min(names))
# print(tuple(names))
# print(list(names))
# print(cmp(names,state))
# print(names+students)
# print(len(names))#finding the length of string
# print(state*4)
# # del names[3]
# # #names.remove("siddu")
# # # print(names)
# # names.pop(1)
# # pri... | Python | zaydzuhri_stack_edu_python |
from math import sqrt
function producePrimes num
begin
set numbers_types = tuple int float complex
if is instance num numbers_types
begin
if num >= 3
begin
set prime_list = list
append prime_list 2
set nextPrime = 3
while nextPrime < num
begin
set isPrime = true
set sqrt_value = square root nextPrime
set sample_range ... | from math import sqrt
def producePrimes(num):
numbers_types = (int, float, complex)
if isinstance(num, numbers_types):
if num >= 3:
prime_list = []
prime_list.append(2)
nextPrime = 3
while nextPrime < num:
isPrime = True
sq... | Python | zaydzuhri_stack_edu_python |
import sys
from PyQt5 import uic , QtWidgets
comment Nombre del archivo aquí.
set qtCreatorFile = string PE3_ParImpar.ui
set tuple Ui_MainWindow QtBaseClass = call loadUiType qtCreatorFile
class MyApp extends QMainWindow Ui_MainWindow
begin
function __init__ self
begin
call __init__ self
call __init__ self
call setupUi... | import sys
from PyQt5 import uic, QtWidgets
qtCreatorFile = "PE3_ParImpar.ui" # Nombre del archivo aquí.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
Ui_MainWindow.__init__(s... | Python | zaydzuhri_stack_edu_python |
function end_request self
begin
set thread = call currentThread
if get __thread_map thread - 1 >= 0
begin
set sock_number = pop __thread_map thread
set __thread_count at sock_number = __thread_count at sock_number - 1
end
end function | def end_request(self):
thread = threading.currentThread()
if self.__thread_map.get(thread, -1) >= 0:
sock_number = self.__thread_map.pop(thread)
self.__thread_count[sock_number] -= 1 | Python | nomic_cornstack_python_v1 |
comment 1) Сгенерировать dict() из списка ключей ниже по формуле
comment (key : key* key). keys = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
set keys = list 1 2 3 4 5 6 7 8 9 10
function dict_generator keys
begin
set dict = dict
for key in keys
begin
set dict at key = key * key
end
return dict
end function
print call dict_genera... | # 1) Сгенерировать dict() из списка ключей ниже по формуле
# (key : key* key).
keys = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
keys = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def dict_generator(keys):
dict={}
for key in keys:
dict[key] = key * key
return dict
print(dict_generator(keys))
# 2)Сгенерировать массив(l... | Python | zaydzuhri_stack_edu_python |
function __init__ self rank suit
begin
set rank = rank
set suit = suit
end function | def __init__(self, rank, suit):
self.rank = rank
self.suit = suit | Python | nomic_cornstack_python_v1 |
class Vertex
begin
string An individual vertex in the graph. :slots: id: The identifier for this vertex (user defined, typically a string) :slots: connectedTo: A dictionary of adjacent neighbors, where the key is the neighbor (Vertex), and the value is the edge cost (int)
set __slots__ = tuple string id string connecte... | class Vertex:
"""
An individual vertex in the graph.
:slots: id: The identifier for this vertex (user defined, typically
a string)
:slots: connectedTo: A dictionary of adjacent neighbors, where the key is
the neighbor (Vertex), and the value is the edge cost (int)
"""
__slots... | Python | zaydzuhri_stack_edu_python |
function load_labels_as_index label_filename
begin
set labels = list comprehension right strip line string for line in open label_filename encoding=string utf-8
return index pd labels
end function | def load_labels_as_index(label_filename):
labels = [line.rstrip('\n') for line in open(label_filename, encoding='utf-8')]
return pd.Index(labels) | Python | nomic_cornstack_python_v1 |
comment modeling road network of indian cities
import networkx as nx
import matplotlib.pyplot as plt
import random as rand
comment undirected
set G = call Graph
comment G = nx.DiGraph() #directed
set city_set = list string mumbai string delhi string banglore string chennai
for city in city_set
begin
call add_node city
... | # modeling road network of indian cities
import networkx as nx
import matplotlib.pyplot as plt
import random as rand
G = nx.Graph() #undirected
# G = nx.DiGraph() #directed
city_set = ['mumbai', 'delhi','banglore','chennai']
for city in city_set:
G.add_node(city)
costs = [x ** 2 for x in range(10)] | Python | zaydzuhri_stack_edu_python |
function mousePressEvent self event
begin
string Creates the mouse event for dragging or activating this tab. :param event | <QtCore.QMousePressEvent>
set _moveItemStarted = false
set rect = call QRect 0 0 12 call height
comment drag the tab off
if not _locked and call contains call pos
begin
set tabbar = call parent
s... | def mousePressEvent(self, event):
"""
Creates the mouse event for dragging or activating this tab.
:param event | <QtCore.QMousePressEvent>
"""
self._moveItemStarted = False
rect = QtCore.QRect(0, 0, 12, self.height())
# drag the tab off
if not self... | Python | jtatman_500k |
function deleteDeviceManagementRequest self requestId
begin
set mgmtRequests = mgmtSingleRequest % tuple host requestId
set r = delete mgmtRequests auth=credentials verify=verify
set status = status_code
if status == 204
begin
debug string Request status cleared
return true
end
else
comment 403 and 404 error code needs... | def deleteDeviceManagementRequest(self, requestId):
mgmtRequests = ApiClient.mgmtSingleRequest % (self.host, requestId)
r = requests.delete(mgmtRequests, auth=self.credentials, verify=self.verify)
status = r.status_code
if status == 204:
self.logger.debug("Request status cleared")
return True
#403 and ... | Python | nomic_cornstack_python_v1 |
from Util.RoomUtil import *
from Objects.Trigger import *
from os import chdir
change directory string ..
comment CREATE START ROOM.
comment NORTH: OPEN EXIT LEADING TO THE HALLWAY
set start_room = call create_room room_name=string Missing Flag Room description=string A well lit room surrounded with decorations. In the... | from Util.RoomUtil import *
from Objects.Trigger import *
from os import chdir
chdir("..")
# CREATE START ROOM.
# NORTH: OPEN EXIT LEADING TO THE HALLWAY
start_room = create_room(room_name="Missing Flag Room",
description="A well lit room surrounded with decorations.\n"
... | Python | zaydzuhri_stack_edu_python |
function name self
begin
return _name
end function | def name(self):
return self._name | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
set data = read csv string C:\Users\NA26035\OneDrive - Trinseo\Desktop\Udacity\Github_projects\ABC-XYZ-data_2.csv sep=string ;
function ABC_analysis df
begin
comment groupby customre and Product
set grouped_df = sum
comment sorted with highest reven... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv(r'C:\Users\NA26035\OneDrive - Trinseo\Desktop\Udacity\Github_projects\ABC-XYZ-data_2.csv',sep =';')
def ABC_analysis(df):
# groupby customre and Product
grouped_df = df.groupby(by=['CustomerID', 'Prod']).sum()
... | Python | zaydzuhri_stack_edu_python |
function conjugate self
begin
return call Quaternion - w x y z
end function | def conjugate(self):
return Quaternion(-self.w, self.x, self.y, self.z) | Python | nomic_cornstack_python_v1 |
function load_data_should_proceed env allow_prod
begin
return call permit_load_data envname=env allow_prod=allow_prod orchestrated_app=string cgap
end function | def load_data_should_proceed(env, allow_prod):
return permit_load_data(envname=env, allow_prod=allow_prod, orchestrated_app='cgap') | Python | nomic_cornstack_python_v1 |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pprint.pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
comment This program uses the writelines method to save a list of strings
comment to a file
function main
begin
comment Create a list
set cities = list string New York string Boston string Atlanta string Dallas
comment Open / create a file to write to
set outfile = open string cities.txt string w
comment Write the list... | # This program uses the writelines method to save a list of strings
# to a file
def main():
# Create a list
cities = ['New York', 'Boston', 'Atlanta', 'Dallas']
# Open / create a file to write to
outfile = open('cities.txt', 'w')
# Write the list to the file
outfile.writelines(citi... | Python | zaydzuhri_stack_edu_python |
function ppo self symbol interval=string daily series_type=string close data_format=string csv fast=12 slow=26
begin
assert interval in intervals
assert series_type in series_types
assert data_format in data_formats
set params = dict string function string PPO ; string symbol upper symbol ; string interval interval ; s... | def ppo(self,
symbol: str,
interval: str="daily",
series_type: str="close",
data_format: str="csv",
fast: int=12,
slow: int=26):
assert(interval in intervals)
assert(series_type in series_types)
assert(data_format in data_fo... | Python | nomic_cornstack_python_v1 |
function get_templates_dirs self
begin
return list call resource_filename __name__ string templates
end function | def get_templates_dirs(self):
return [resource_filename(__name__, 'templates')] | Python | nomic_cornstack_python_v1 |
function backup_remote handle file_dir file_name hostname protocol=string scp username=none password=string preserve_pooled_values=false remove_from_ucsc=false timeout=600
begin
call _backup handle file_dir=file_dir file_name=file_name remote_enabled=true hostname=hostname protocol=protocol username=username password=... | def backup_remote(handle, file_dir, file_name, hostname,
protocol="scp", username=None, password="",
preserve_pooled_values=False,
remove_from_ucsc=False,
timeout=600):
_backup(handle, file_dir=file_dir, file_name=file_name,
remote_... | Python | nomic_cornstack_python_v1 |
with open file_name string r encoding=string utf_8 as f
begin
print tell f
print seek f 6
print read f
print tell f
print seek f 9
print read f
print seek f 0 2
print type read f
end
with open file_name string ab as f
begin
print tell f
print seek f 0
print seek f 12
print seek f 24 1
print seek f - 12 1
print seek f -... | with open(file_name, 'r', encoding='utf_8') as f:
print(f.tell())
print(f.seek(6))
print(f.read())
print(f.tell())
print(f.seek(9))
print(f.read())
print(f.seek(0, 2))
print(type(f.read()))
with open(file_name, 'ab') as f:
print(f.tell())
print(f.seek(0))
print(f.seek(12))
... | Python | zaydzuhri_stack_edu_python |
while t > 0
begin
set t = t - 86400 - integer a at i
set i = i + 1
end
print i | while t > 0:
t-=(86400-int(a[i]))
i += 1
print(i)
| Python | jtatman_500k |
function _infer_dihedral a2 a3=none
begin
comment assume bond-like
if a3 is none
begin
set bond = a2
set tuple a2 a3 = tuple a1 a2
end
set a1 = call _pick_atom a2 a3
set a4 = call _pick_atom a3 a2
return tuple a1 a2 a3 a4
end function | def _infer_dihedral(a2, a3=None):
if a3 is None: # assume bond-like
bond = a2
a2, a3 = bond.a1, bond.a2
a1 = _pick_atom(a2, a3)
a4 = _pick_atom(a3, a2)
return a1, a2, a3, a4 | Python | nomic_cornstack_python_v1 |
function update_from_model_change self oldmodel newmodel tile
begin
string Update various internal variables from a model update from oldmodel to newmodel for the tile `tile`
set _loglikelihood = _loglikelihood - call _calc_loglikelihood oldmodel tile=tile
set _loglikelihood = _loglikelihood + call _calc_loglikelihood ... | def update_from_model_change(self, oldmodel, newmodel, tile):
"""
Update various internal variables from a model update from oldmodel to
newmodel for the tile `tile`
"""
self._loglikelihood -= self._calc_loglikelihood(oldmodel, tile=tile)
self._loglikelihood += self._calc... | Python | jtatman_500k |
function get_median data band=string blue
begin
set band_idx = PLANET_BANDS at band
set dn = call ReadAsArray
return dn at tuple integer shape at 1 / 2 integer shape at 0 / 2
end function
comment return np.nanmedian(dn[dn > 0]) | def get_median(data, band='blue'):
band_idx = PLANET_BANDS[band]
dn = data.GetRasterBand(band_idx).ReadAsArray()
return dn[int(dn.shape[1]/2), int(dn.shape[0]/2)]
#return np.nanmedian(dn[dn > 0]) | Python | nomic_cornstack_python_v1 |
comment 单语句实现if-else功能
comment 输入两个整数,比较大小,输出较大的数
set a = input string 请输入第1个整数:
set b = input string 请输入第2个整数:
set a = integer a
set b = integer b
comment 如果a>b成立,取得if前面表达式a的值,然后赋值给x
comment 否则,取得else后面表达式b的值,然后赋值给x
set x = if expression a > b then a else b
print string 较大的数是%d % x | #单语句实现if-else功能
#输入两个整数,比较大小,输出较大的数
a=input("请输入第1个整数:")
b=input("请输入第2个整数:")
a=int(a)
b=int(b)
#如果a>b成立,取得if前面表达式a的值,然后赋值给x
#否则,取得else后面表达式b的值,然后赋值给x
x=(a if a>b else b)
print("较大的数是%d"%x)
| Python | zaydzuhri_stack_edu_python |
function iterifs physical=true
begin
string Iterate over all the interfaces in the system. If physical is true, then return only real physical interfaces (not 'lo', etc).
set net_files = list directory SYSFS_NET_PATH
set interfaces = set
set virtual = set
for d in net_files
begin
set path = join path SYSFS_NET_PATH d
i... | def iterifs(physical=True):
''' Iterate over all the interfaces in the system. If physical is
true, then return only real physical interfaces (not 'lo', etc).'''
net_files = os.listdir(SYSFS_NET_PATH)
interfaces = set()
virtual = set()
for d in net_files:
path = os.path.join(SYSFS_NE... | Python | jtatman_500k |
comment ADE Global Health 2016 ####
import argparse
import importlib
class Results extends object
begin
comment """
comment >>> a=Results(bloodBlobDetection "prototype1NumMask.png maskSquare.png 12")
comment >>> a.handleResults()
comment {1: ['negative', 1], 2: ['positive', 5], 3: ['negative', 1], 4: ['negative', 1], 5... | ####### ADE Global Health 2016 ####
import argparse
import importlib
class Results(object):
# """
# >>> a=Results(bloodBlobDetection "prototype1NumMask.png maskSquare.png 12")
# >>> a.handleResults()
# {1: ['negative', 1], 2: ['positive', 5], 3: ['negative', 1], 4: ['negative', 1], 5: ['negative', 1], 6: ... | Python | zaydzuhri_stack_edu_python |
from lib.Singleton import Singleton
from lib import debounce
import json
import logging
from pathlib import Path
from types import MappingProxyType
from lib.observables import ObservableDict
set logger = call getLogger string Settings
function update_settings_paths settings
begin
set updated = dict
set home_path = str... | from lib.Singleton import Singleton
from lib import debounce
import json
import logging
from pathlib import Path
from types import MappingProxyType
from lib.observables import ObservableDict
logger = logging.getLogger('Settings')
def update_settings_paths(settings):
updated = {}
home_path = str(Path.home())
... | Python | zaydzuhri_stack_edu_python |
import math
while true
begin
set number = integer input string Enter number to find squareroot:
set result = square root number
print string The square root of + string number + string is: + string result
set user_input = string Do you want to contiune:
if user_input == string no
begin
break
end
end
set end = input str... | import math
while True:
number = int(input("Enter number to find squareroot: "))
result = math.sqrt(number)
print("The square root of " + str(number) + "is: " + str(result))
user_input=("Do you want to contiune: ")
if(user_input=="no"):
break
end=input("")
| Python | zaydzuhri_stack_edu_python |
from datetime import date
import mysql.connector
import requests
from bs4 import BeautifulSoup as BS
set hoy = today
set hoy = string hoy
comment Abro conexion con la base de datos
while true
begin
set host_1 = input string Ingrese el nombre del "host":
set database_1 = input string Ingrese el nombre de la "database":
... | from datetime import date
import mysql.connector
import requests
from bs4 import BeautifulSoup as BS
hoy = date.today()
hoy = str(hoy)
#Abro conexion con la base de datos
while True:
host_1 = input('Ingrese el nombre del "host": ')
database_1 = input('Ingrese el nombre de la "database": ')
user_1 = in... | Python | zaydzuhri_stack_edu_python |
import urllib
import xml.etree.ElementTree as ET
set url = call raw_input string Enter location: | import urllib
import xml.etree.ElementTree as ET
url = raw_input("Enter location: ") | Python | zaydzuhri_stack_edu_python |
import os , argparse
from subprocess import call
comment directory where the TXL rule files are located
set TXL_RULES_DIR = string ./txl/rules/
function run_all_examples in_dir
begin
comment set output directory (inside current src directory)
set out_dir = in_dir + string out/
comment clear out out directory
call strin... | import os, argparse
from subprocess import call
# directory where the TXL rule files are located
TXL_RULES_DIR = "./txl/rules/"
def run_all_examples(in_dir):
# set output directory (inside current src directory)
out_dir = in_dir + "out/"
# clear out out directory
call("rm -rf " + out_dir + "*", shel... | Python | zaydzuhri_stack_edu_python |
function bisect self t t_in_left=false
begin
set tuple left right = tuple call ValIterOrderedDict call ValIterOrderedDict
for tuple name var in items self
begin
set tuple left at name right at name = call bisect t t_in_left
end
if is_aligned
begin
set left = call TimeSeries left check_aligned=false
set right = call Tim... | def bisect(self, t: float, t_in_left: bool = False):
left, right = ValIterOrderedDict(), ValIterOrderedDict()
for name, var in self.items():
left[name], right[name] = var.bisect(t, t_in_left)
if self.is_aligned:
left = TimeSeries(left, check_aligned=False)
rig... | Python | nomic_cornstack_python_v1 |
function to_dict self
begin
set result = dict
for tuple attr _ in call iteritems openapi_types
begin
set value = get attribute self attr
if is instance value list
begin
set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value
end
else
if has attribute value ... | def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
... | Python | nomic_cornstack_python_v1 |
function depool self server
begin
assert pooled
if call canDepool
begin
call removeServer server
discard pooledDownServers server
end
else
begin
add pooledDownServers server
end
end function | def depool(self, server):
assert server.pooled
if self.canDepool():
self.lvsservice.removeServer(server)
self.pooledDownServers.discard(server)
else:
self.pooledDownServers.add(server) | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import input_data
import numpy as np
import model
import os
comment 从测试集中选取一张图片
function get_one_image train
begin
set files = list directory train
set n = length files
set ind = random integer 0 n
set img_dir = join path... | #coding=utf-8
import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import input_data
import numpy as np
import model
import os
#从测试集中选取一张图片
def get_one_image(train):
files = os.listdir(train)
n = len(files)
ind = np.random.randint(0,n)
img_dir = os.path... | Python | zaydzuhri_stack_edu_python |
function forward_gap self x
begin
comment output of avg pool is expected to be 128-d
set x = call avg_pool2d x shape at 2
set x = view x shape at 0 - 1
assert shape at 1 == 128
return x
end function | def forward_gap(self, x):
# output of avg pool is expected to be 128-d
x = F.avg_pool2d(x, x.shape[2])
x = x.view(x.shape[0], -1)
assert x.shape[1] == 128
return x | Python | nomic_cornstack_python_v1 |
function account initial_balance
begin
function deposit amount
begin
set dispatch at string balance = dispatch at string balance + amount
return dispatch at string balance
end function
function withdraw amount
begin
if amount > dispatch at string balance
begin
return string Insufficient funds
end
set dispatch at string... | def account(initial_balance):
def deposit(amount):
dispatch['balance'] += amount
return dispatch['balance']
def withdraw(amount):
if amount > dispatch['balance']:
return 'Insufficient funds'
dispatch['balance'] -= amount
return dispatch['balance']
dispatch... | Python | zaydzuhri_stack_edu_python |
while fib <= 4000000
begin
if fib % 2 == 0
begin
set ergebnis = ergebnis + fib
end
set alt = neu
set neu = fib
set fib = alt + neu
end
print ergebnis | while fib <= 4000000:
if fib % 2 == 0:
ergebnis += fib
alt = neu
neu = fib
fib = alt + neu
print(ergebnis)
| Python | zaydzuhri_stack_edu_python |
set motorcycles = list string honda string yamaha string suzuki
print motorcycles
set motorcycles at 0 = string ducati
print motorcycles
insert motorcycles 0 string harley
print motorcycles
del motorcycles at 3
print motorcycles
set popped_motorcycles = pop motorcycles 2
print motorcycles
print popped_motorcycles | motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
motorcycles.insert(0,'harley')
print(motorcycles)
del motorcycles[3]
print(motorcycles)
popped_motorcycles=motorcycles.pop(2)
print(motorcycles)
print(popped_motorcycles) | Python | zaydzuhri_stack_edu_python |
function _queue_sleep self task
begin
set length = params at string delay
if not is instance length int
begin
error format string delay is not an int: {} type params at string delay
raise ValueError
end
while true
begin
if call update_queued
begin
call _process_queue task
end
if length > 0
begin
sleep 1
set length = le... | def _queue_sleep(self, task):
length = task.params["delay"]
if not isinstance(length, int):
logger.error("delay is not an int: {}".format(type(task.params["delay"])))
raise ValueError
while True:
if task.scanq.update_queued():
self._process_q... | Python | nomic_cornstack_python_v1 |
from DynamicAlgorithms import *
import unittest
class DynamicTest extends TestCase
begin
function test_min_edit_distance self
begin
set inputs = tuple list list string string hi 2 list list string hey string 3 list list string geek string gesek 1 list list string sunday string saturday 3
assert true all generator exp... | from DynamicAlgorithms import *
import unittest
class DynamicTest(unittest.TestCase):
def test_min_edit_distance(self):
inputs = ([['', 'hi'], 2], [['hey', ''], 3], [['geek', 'gesek'], 1],
[['sunday', 'saturday'], 3])
self.assertTrue(all(min_edit_distance(*i[0]) == i[1] for i in i... | Python | zaydzuhri_stack_edu_python |
function _racat_contains_ cat item
begin
return is instance item string_types and call isValidLabel item or is instance item integer_types and call isValidIndex item
end function | def _racat_contains_ ( cat , item ) :
return ( isinstance ( item , string_types ) and cat.isValidLabel ( item ) ) or \
( isinstance ( item , integer_types ) and cat.isValidIndex ( item ) ) | Python | nomic_cornstack_python_v1 |
function draw self surface bgd=none
begin
comment speedups
set _orig_clip = call get_clip
set _clip = _clip
if _clip is none
begin
set _clip = _orig_clip
end
set _surf = surface
set _surf_rect = call get_rect
set _sprites = _spritelist
set _old_rect = spritedict
set _update = lostsprites
set _update_append = append
set... | def draw(self, surface, bgd=None):
# speedups
_orig_clip = surface.get_clip()
_clip = self._clip
if _clip is None:
_clip = _orig_clip
_surf = surface
_surf_rect = _surf.get_rect()
_sprites = self._spritelist
_old_rect = self... | Python | nomic_cornstack_python_v1 |
function train self
begin
raise NotImplementedError
end function | def train(self):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function post_answer payload
begin
print string payload: payload
set question_id = get payload string id
set response = query client KeyConditionExpression=call eq question_id
set item = response at string Items at 0
print type item
print string item: item
for answer in payload at string answers
begin
set votes = get i... | def post_answer(payload):
print("payload: \n", payload)
question_id = payload.get("id")
response = client.query(
KeyConditionExpression=Key('id').eq(question_id)
)
item = response['Items'][0]
print(type(item))
print("item: \n", item)
for answer in payload["answers"]:
... | Python | nomic_cornstack_python_v1 |
comment Copyright (c) 2018, Lawrence Livermore National Security, LLC.
comment Produced at the Lawrence Livermore National Laboratory
comment Written by K. Humbird (humbird1@llnl.gov), L. Peterson (peterson76@llnl.gov).
comment LLNL-CODE-754815
comment All rights reserved.
comment This file is part of DJINN.
comment Fo... | ###############################################################################
# Copyright (c) 2018, Lawrence Livermore National Security, LLC.
#
# Produced at the Lawrence Livermore National Laboratory
#
# Written by K. Humbird (humbird1@llnl.gov), L. Peterson (peterson76@llnl.gov).
#
# LLNL-CODE-754815
#
# All righ... | Python | zaydzuhri_stack_edu_python |
function main global_config **settings
begin
set config = call Configurator root_factory=root_factory settings=settings
call includeme config
set jsengine = call Bundle string app/vendor/jquery-1.8.2.js string app/vendor/bootstrap-2.3.0/js/bootstrap.js string app/vendor/handlebars-1.0.0-rc.3.js string app/vendor/ember-... | def main(global_config, **settings):
config = Configurator(root_factory=root_factory, settings=settings)
includeme(config)
jsengine = Bundle('app/vendor/jquery-1.8.2.js',
'app/vendor/bootstrap-2.3.0/js/bootstrap.js',
'app/vendor/handlebars-1.0.0-rc.3.js',
'app/vendor/emb... | Python | nomic_cornstack_python_v1 |
from newsapi import NewsApiClient
class News
begin
function __init__ self
begin
set newsapi = call NewsApiClient api_key=string f86096b6f36d449eb740af2501bb3748
set title = string The top 3 news headlines I have include: <break time="500ms"/>
set headlines = join string <break time="800ms"/> call get_articles
set messa... | from newsapi import NewsApiClient
class News:
def __init__(self):
self.newsapi = NewsApiClient(api_key='f86096b6f36d449eb740af2501bb3748')
title = "The top 3 news headlines I have include: \n<break time=\"500ms\"/>"
headlines = "\n<break time=\"800ms\"/>".join(self.get_articles())
... | Python | zaydzuhri_stack_edu_python |
function __init__ __self__ delivery_pipeline_id release_id rollout_id target_id annotations=none description=none etag=none labels=none location=none name=none project=none request_id=none starting_phase_id=none
begin
set __self__ string delivery_pipeline_id delivery_pipeline_id
set __self__ string release_id release_i... | def __init__(__self__, *,
delivery_pipeline_id: pulumi.Input[str],
release_id: pulumi.Input[str],
rollout_id: pulumi.Input[str],
target_id: pulumi.Input[str],
annotations: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,... | Python | nomic_cornstack_python_v1 |
function print self
begin
raise call NotImplementedError string Printing of BoundsList is not ready yet
end function | def print(self):
raise NotImplementedError("Printing of BoundsList is not ready yet") | Python | nomic_cornstack_python_v1 |
function make_checkpoint_folder base_dir expid=none extra=string
begin
comment make a "root" dir to store all checkpoints
comment homedir = os.getenv("HOME")
comment base_dir = homedir+"/GPVAE_checkpoints/"
if expid is not none
begin
set base_dir = base_dir + string / + expid + string /
end
if not exists path base_dir
... | def make_checkpoint_folder(base_dir, expid=None, extra=""):
# make a "root" dir to store all checkpoints
# homedir = os.getenv("HOME")
# base_dir = homedir+"/GPVAE_checkpoints/"
if expid is not None:
base_dir = base_dir + "/" + expid + "/"
if not os.path.exists(base_dir):
os.maked... | Python | nomic_cornstack_python_v1 |
function elements_sequence cls
begin
return list string id string extension string modifierExtension string additiveCodeableConcept string additiveReference
end function | def elements_sequence(cls):
return [
"id",
"extension",
"modifierExtension",
"additiveCodeableConcept",
"additiveReference",
] | Python | nomic_cornstack_python_v1 |
function creat_npy
begin
set train_p = load np string ./processed_data/train/raw/train_p.npy
set train_u = load np string ./processed_data/train/raw/train_u.npy
comment shuffle
shuffle random train_u
shuffle random train_p
comment spy instances, replace the label of spies, now spies are marked as 0
set spy = train_p at... | def creat_npy():
train_p = np.load("./processed_data/train/raw/train_p.npy")
train_u = np.load("./processed_data/train/raw/train_u.npy")
np.random.shuffle(train_u) # shuffle
np.random.shuffle(train_p)
# spy instances, replace the label of spies, now spies are marked as 0
spy = train_p[: int(_s... | Python | nomic_cornstack_python_v1 |
tuple string R8,U5,L5,D3 U7,R6,D4,L4
tuple string R75,D30,R83,U83,L12,D49,R71,U7,L72 U62,R66,U55,R34,D71,R55,D58,R83
string R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51 U98,R91,D20,R16,D67,R40,U7,R15,U6,R7 | '''R8,U5,L5,D3
U7,R6,D4,L4''',
'''R75,D30,R83,U83,L12,D49,R71,U7,L72
U62,R66,U55,R34,D71,R55,D58,R83''',
'''R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51
U98,R91,D20,R16,D67,R40,U7,R15,U6,R7''' | Python | zaydzuhri_stack_edu_python |
from node import *
class Connection
begin
function __init__ self startNode endNode connections
begin
if call decisionCount != shape at 0
begin
raise call AttributeError string Dimension 1 of connections incorrect
end
if call decisionCount != shape at 1
begin
raise call AttributeError string Dimension 2 of connections i... | from node import *
class Connection:
def __init__(self,startNode,endNode,connections:np.ndarray):
if startNode.decisionCount()!=connections.shape[0]:
raise AttributeError("Dimension 1 of connections incorrect")
if endNode.decisionCount()!=connections.shape[1]:
raise Attribute... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Oct 11 15:30:09 2017 @author: kvapil98
function get_orf dna
begin
string this func gets orf strating with ATG end in but dont include stop codon
set cod = - 3
while cod < length dna
begin
set cod = cod + 3
set codon = dna at slice cod : cod + 3 :
if codon in list str... | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 11 15:30:09 2017
@author: kvapil98
"""
def get_orf(dna):
'''this func gets orf strating with ATG end in but dont include stop codon'''
cod = -3
while cod < len(dna):
cod +=3
codon = dna[cod:cod+3]
if codon in ['TGA','TAG','TAA']:
... | Python | zaydzuhri_stack_edu_python |
function store_model_outputs self
begin
set scenario = latest_scenario
assert scenario msg string No model has been run
set model = model
set out_df = call DataFrame outputs columns=compartment_names
set derived_output_df = call from_dict derived_outputs
call store_database derived_output_df table_name=string derived_o... | def store_model_outputs(self):
scenario = self.latest_scenario
assert scenario, "No model has been run"
model = scenario.model
out_df = pd.DataFrame(model.outputs, columns=model.compartment_names)
derived_output_df = pd.DataFrame.from_dict(model.derived_outputs)
store_dat... | Python | nomic_cornstack_python_v1 |
string Problem 7 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number?
import math
set number = 5
comment prime_number - Начинаем поиск простых чисел с 3
comment x - тройка второе по счету простое число. х - хранит порядковый номер просто... | """
Problem 7
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
import math
number = 5
# prime_number - Начинаем поиск простых чисел с 3
# x - тройка второе по счету простое число. х - хранит порядковый номер простого числа
... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.