code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function permutation_to_matrix permutation
begin
set perm_matrix = zeros tuple shape at 0 shape at 0 dtype=float32
set perm_matrix at tuple permutation array range shape at 0 = 1
return perm_matrix
end function | def permutation_to_matrix(permutation):
perm_matrix = np.zeros((permutation.shape[0], permutation.shape[0]), dtype=np.float32)
perm_matrix[permutation, np.arange(permutation.shape[0])] = 1
return perm_matrix | Python | nomic_cornstack_python_v1 |
function get_broadcasts self ids=none statuses=none before=none after=none pager=none
begin
set params = call _build_params id=ids status=statuses before=before after=after
return call deserialize_list call _get_multiple string broadcasts params pager
end function | def get_broadcasts(self, ids=None, statuses=None, before=None, after=None, pager=None):
params = self._build_params(id=ids, status=statuses, before=before, after=after)
return Broadcast.deserialize_list(self._get_multiple('broadcasts', params, pager)) | Python | nomic_cornstack_python_v1 |
function gbk_demo
begin
comment 使用gbk编码
set data = encode string 百度一下 string GBK
comment 使用utf-8编码
set u_data = encode string 百度一下 string utf-8
print string gkb编码: data
print string utf-8编码: u_data
set res_data = decode data string GBK
set res_udata = decode u_data string utf-8
print string 使用GBK解码: res_data
print stri... | def gbk_demo():
data = "百度一下".encode("GBK") #使用gbk编码
u_data = "百度一下".encode("utf-8") #使用utf-8编码
print("gkb编码:",data)
print("utf-8编码:",u_data)
res_data = data.decode("GBK")
res_udata = u_data.decode("utf-8")
print("使用GBK解码:", res_data)
print("使用utf-8解码:", res_udata)
gbk_demo()
import ... | Python | zaydzuhri_stack_edu_python |
from database import readyDatabase , insertOne , updateOne , removeOne , findOne , findAll
from flask import Flask , url_for , request , json , jsonify
set app = call Flask __name__
decorator call route string /
function api_root
begin
if string name in args
begin
return string Hello + args at string name
end
else
begi... | from database import readyDatabase, insertOne, updateOne, removeOne, findOne, findAll
from flask import Flask, url_for, request, json, jsonify
app = Flask(__name__)
@app.route('/')
def api_root():
if 'name' in request.args:
return 'Hello ' + request.args['name']
else:
return 'Wrong-End Point'
... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function minPathSum self grid
begin
set m = length grid
set n = length grid at 0
set A = list list 0 * n * m
for i in range m
begin
for j in range n
begin
if i == 0 and j == 0
begin
set A at i at j = grid at i at j
end
else
if i == 0
begin
set A at i at j = A at i at j - 1 + grid at i at j
end
else... | class Solution:
def minPathSum(self, grid):
m = len(grid)
n = len(grid[0])
A = [[0] * n] * m
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
A[i][j] = grid[i][j]
elif i == 0:
A[i][j] = A... | Python | zaydzuhri_stack_edu_python |
comment @lc app=leetcode id=1291 lang=python3
comment [1291] Sequential Digits
comment https://leetcode.com/problems/sequential-digits/description/
comment algorithms
comment Medium (53.35%)
comment Likes: 302
comment Dislikes: 35
comment Total Accepted: 19.3K
comment Total Submissions: 34.4K
comment Testcase Example: ... | #
# @lc app=leetcode id=1291 lang=python3
#
# [1291] Sequential Digits
#
# https://leetcode.com/problems/sequential-digits/description/
#
# algorithms
# Medium (53.35%)
# Likes: 302
# Dislikes: 35
# Total Accepted: 19.3K
# Total Submissions: 34.4K
# Testcase Example: '100\n300'
#
# An integer has sequential digi... | Python | zaydzuhri_stack_edu_python |
function prefix cls name
begin
string Create a new TreeModel where class attribute names are prefixed with ``name``
set attrs = dictionary list comprehension tuple name + attr value for tuple attr value in call get_attrs
return call TreeModelMeta join string _ list name __name__ tuple TreeModel attrs
end function | def prefix(cls, name):
"""
Create a new TreeModel where class attribute
names are prefixed with ``name``
"""
attrs = dict([(name + attr, value) for attr, value in cls.get_attrs()])
return TreeModelMeta(
'_'.join([name, cls.__name__]),
(TreeModel,),... | Python | jtatman_500k |
function from_data cls data
begin
set user = call from_data data at string user
set raw_scopes = data at string raw_scopes
set scopes = set
for scope in raw_scopes
begin
set scope = get Oauth2Scope scope
add scopes scope
end
set expires = call timestamp_to_datetime data at string date
set application = call from_data d... | def from_data(cls, data):
user = User.from_data(data['user'])
raw_scopes = data['raw_scopes']
scopes = set()
for scope in raw_scopes:
scope = Oauth2Scope.get(scope)
scopes.add(scope)
expires = timestamp_to_datetime(data['date'])
... | Python | nomic_cornstack_python_v1 |
function validar_administrador
begin
set res = false
set usuario = input string Ingrese nombre de usuario administrador:
set password = input string Ingrese password de usuario administrador:
for i in range length USUARIOS_ADMINISTRADORES
begin
if usuario == USUARIOS_ADMINISTRADORES at i
begin
if password == PASSWORDS_... | def validar_administrador():
res = False
usuario = input("Ingrese nombre de usuario administrador: ")
password = input("Ingrese password de usuario administrador: ")
for i in range(len(USUARIOS_ADMINISTRADORES)):
if(usuario == USUARIOS_ADMINISTRADORES[i]):
if(password == PASSWORD... | Python | zaydzuhri_stack_edu_python |
function gen_factors value
begin
for n in range 2 value + 1
begin
if value == 1
begin
break
end
while value % n == 0
begin
yield n
set value = value // n
end
end
end function | def gen_factors(value: int) -> iter:
for n in range(2, value + 1):
if value == 1:
break
while value % n == 0:
yield n
value //= n | Python | nomic_cornstack_python_v1 |
function _vpr_arch_array xml delegate array hierarchy=none
begin
set position = if expression hierarchy is not none then call hierarchical_position hierarchy else call Position 0 0
for tuple pos instance in call iteritems element_instances
begin
set pos = pos + position
if is_tile
begin
set fasm_prefix = join string c... | def _vpr_arch_array(xml, delegate, array, hierarchy = None):
position = hierarchical_position(hierarchy) if hierarchy is not None else Position(0, 0)
for pos, instance in iteritems(array.element_instances):
pos += position
if instance.module_class.is_tile:
fasm_prefix = '\n'.join(del... | Python | nomic_cornstack_python_v1 |
import math
function create_line point1 point2
begin
set dx = point2 at 0 - point1 at 0
set dy = point2 at 1 - point1 at 1
set m = dy / dx
set b = point2 at 1 - m * point2 at 0
if point1 at 0 > point2 at 0
begin
return list m b list point2 at 0 point1 at 0
end
else
begin
return list m b list point1 at 0 point2 at 0
end... | import math
def create_line(point1, point2):
dx = point2[0] - point1[0]
dy = point2[1] - point1[1]
m = dy/dx
b = point2[1] - m * point2[0]
if point1[0] > point2[0]:
return [m, b, [point2[0], point1[0]]]
else:
return [m, b, [point1[0], point2[0]]]
def highest_point(arr):
k = 0
high = arr[0][1]
for i in ra... | Python | zaydzuhri_stack_edu_python |
import requests
set MY_LAT = 38.785809
set MY_LONG = - 77.187248
set response = get requests url=string http://api.open-notify.org/iss-now.json
print json response
set parameters = dict string lat MY_LAT ; string lng MY_LONG ; string formatted 0
set response2 = get requests string https://api.sunrise-sunset.org/json pa... | import requests
MY_LAT = 38.785809
MY_LONG = -77.187248
response = requests.get(url="http://api.open-notify.org/iss-now.json")
print(response.json())
parameters = {
"lat":MY_LAT,
"lng":MY_LONG,
"formatted":0
}
response2 = requests.get("https://api.sunrise-sunset.org/json", params=parameters)
response2.... | Python | zaydzuhri_stack_edu_python |
function insert self x
begin
set stack = call find_position x
assert stack msg string Method find_position should return at least one element.
set position_found = call popleft
if value == x
begin
comment Element already exists
return
end
set created_node = call insert_after x
comment if lucky, keep adding element in a... | def insert(self, x):
stack = self.find_position(x)
assert stack, "Method find_position should return at least one element."
position_found = stack.popleft()
if position_found.value == x:
# Element already exists
return
created_node =... | Python | nomic_cornstack_python_v1 |
from serial import Serial
import matplotlib.pyplot as pyplt
import matplotlib.animation as animation
import numpy as np
import threading
set SERIAL_DATA = list 0.0 * 64
function im_setup
begin
set tuple fig axis = call subplots
set serial_data_2d = reshape np SERIAL_DATA tuple 8 8
set im = image show serial_data_2d int... | from serial import Serial
import matplotlib.pyplot as pyplt
import matplotlib.animation as animation
import numpy as np
import threading
SERIAL_DATA = [0.0] * 64
def im_setup():
fig, axis = pyplt.subplots()
serial_data_2d = np.reshape(SERIAL_DATA, (8, 8))
im = axis.imshow(serial_data_2d, interpolation='n... | Python | zaydzuhri_stack_edu_python |
function create_network self name=none
begin
set network = call Network self name=name
add _networks network
return network
end function | def create_network(self, *, name: t.Optional[str] = None) -> Network:
network = Network(self, name=name)
self._networks.add(network)
return network | Python | nomic_cornstack_python_v1 |
function cphaseshift00 control target angle
begin
return call Instruction call CPhaseShift00 angle target=list control target
end function | def cphaseshift00(control: QubitInput, target: QubitInput, angle: float) -> Instruction:
return Instruction(CPhaseShift00(angle), target=[control, target]) | Python | nomic_cornstack_python_v1 |
function reset_timer self
begin
return random integer 10 20 / PROJECTILE_FIRE_RATE
end function | def reset_timer(self) -> int:
return random.randint(10, 20) / constants.PROJECTILE_FIRE_RATE | Python | nomic_cornstack_python_v1 |
import random
set boxes = list string string string string string string string string string
set HUMAN = string X
set COMPUTER = string 0
set first_player = HUMAN
set turn = 1
set winning_combos = list list 0 1 2 list 3 4 5 list 6 7 8 list 0 3 6 list 1 4 7 list 2 5 8 list 0 4 8 list 2 4 6
function print_board... | import random
boxes = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ]
HUMAN = 'X'
COMPUTER = '0'
first_player = HUMAN
turn = 1
winning_combos = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6],
[1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]
def print_board(initial=False):
print(('''
{} |... | Python | zaydzuhri_stack_edu_python |
import re
comment 先compile(如果没有重复使用同一个正则,也不能节省时间)
comment 再finditer,既节省时间又节省空间
set com = compile string \d+
set ret = call finditer string agksak018as093
for i in ret
begin
print call group
end | import re
# 先compile(如果没有重复使用同一个正则,也不能节省时间)
# 再finditer,既节省时间又节省空间
com = re.compile('\d+')
ret = com.finditer('agksak018as093')
for i in ret:
print(i.group())
| Python | zaydzuhri_stack_edu_python |
from django.shortcuts import render
import io
from django.http import FileResponse
from reportlab.pdfgen import canvas
import datetime
function registroPdf request queryset
begin
set buffer = call BytesIO
set p = call Canvas buffer
call setLineWidth 0.3
set today = today
set solicitador = string Mr. Krabs
call drawStri... | from django.shortcuts import render
import io
from django.http import FileResponse
from reportlab.pdfgen import canvas
import datetime
def registroPdf(request, queryset):
buffer = io.BytesIO()
p = canvas.Canvas(buffer)
p.setLineWidth(.3)
today = datetime.date.today()
solicitador = "Mr. Krabs"
... | Python | zaydzuhri_stack_edu_python |
function get_s3_url self
begin
if s3_key and s3_bucket
begin
return string https://s3.amazonaws.com/ + s3_bucket + string / + s3_key
end
else
begin
return none
end
end function | def get_s3_url(self):
if (self.s3_key) and (self.s3_bucket):
return "https://s3.amazonaws.com/" + self.s3_bucket + "/" + self.s3_key
else:
return None | Python | nomic_cornstack_python_v1 |
if input == real_dk
begin
print string Hi, David Kim
end
else
if input == real_tk
begin
print string Hi, tekdk__39
end
else
begin
print string ACCESS DENIED !!
end | if input == real_dk:
print("Hi, David Kim")
elif input == real_tk:
print("Hi, tekdk__39")
else:
print("ACCESS DENIED !!")
| Python | zaydzuhri_stack_edu_python |
function Patch self request global_params=none
begin
set config = call GetMethodConfig string Patch
return call _RunMethod config request global_params=global_params
end function | def Patch(self, request, global_params=None):
config = self.GetMethodConfig('Patch')
return self._RunMethod(
config, request, global_params=global_params) | Python | nomic_cornstack_python_v1 |
function _get_urls self
begin
set usable_urls = list
set urls = _tweet at string entities at string urls
for url in urls
begin
set usable_url = url at string expanded_url
comment trimming
set usable_url = replace usable_url string string
append usable_urls usable_url
end
return usable_urls
end function | def _get_urls(self):
usable_urls = list()
urls = self._tweet['entities']['urls']
for url in urls:
usable_url = url['expanded_url']
usable_url = usable_url.replace(" ","") # trimming
usable_urls.append(usable_url)
return usable_urls | Python | nomic_cornstack_python_v1 |
function MaxRadFromSeqAndLaws self *args
begin
return call ChFiDS_FilSpine_MaxRadFromSeqAndLaws self *args
end function | def MaxRadFromSeqAndLaws(self, *args):
return _ChFiDS.ChFiDS_FilSpine_MaxRadFromSeqAndLaws(self, *args) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Apr 23 22:27:38 2020 @author: TaeHyun Hwang
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate , optimize
set I_t_china = load np string C:\Users\yalhl\sir_model\taehyun\I_t_china.npy
set R_t_china = load np string C:\Users\yalhl\sir_model\... | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 22:27:38 2020
@author: TaeHyun Hwang
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate, optimize
I_t_china = np.load(r'C:\Users\yalhl\sir_model\taehyun\I_t_china.npy')
R_t_china = np.load(r'C:\Users\yalhl\sir_model\taehyun... | Python | zaydzuhri_stack_edu_python |
comment Mit hilfe von Flo #####
set Moved_Up_stop1 = true
set Moved_Down_stop1 = true
set Moved_Left_stop1 = true
set Moved_Right_stop1 = true
function Move_Up_stop player_y display_height
begin
global Moved_Up_stop1
set Moved_Up_stop1 = true
if player_y < display_height - 80 and player_y > display_height - 160
begin
r... | ##### Mit hilfe von Flo #####
Moved_Up_stop1 = True
Moved_Down_stop1 = True
Moved_Left_stop1 = True
Moved_Right_stop1 = True
def Move_Up_stop(player_y, display_height):
global Moved_Up_stop1
Moved_Up_stop1 = True
if player_y < (display_height-80) and player_y > (display_height-160):
return(player_... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string @author: Roy
import numpy as np
from sklearn.model_selection import train_test_split
function train_test df size
begin
set df_col = array columns
set x = df at df_col at slice 1 : :
set y = df at df_col at 0
set tuple x_train x_test y_train y_test = train test split x y test_size=... | # -*- coding: utf-8 -*-
"""
@author: Roy
"""
import numpy as np
from sklearn.model_selection import train_test_split
def train_test(df, size):
df_col = np.array(df.columns)
x = df[df_col[1:]]
y = df[df_col[0]]
x_train, x_test, y_train, y_test = train_test_split(x, y,
... | Python | zaydzuhri_stack_edu_python |
function checksum file
begin
function check id
begin
set mem = dict
for letter in id
begin
set mem at letter = get mem letter 0 + 1
end
set two = 0
set three = 0
for tuple k v in items mem
begin
if v == 2
begin
set two = 1
end
else
if v == 3
begin
set three = 1
end
end
return tuple two three
end function
set twos = 0
... | def checksum(file):
def check(id):
mem = {}
for letter in id:
mem[letter] = mem.get(letter, 0) + 1
two = 0
three = 0
for k, v in mem.items():
if v == 2:
two = 1
elif v == 3:
three = 1
return two, thr... | Python | zaydzuhri_stack_edu_python |
function get_settings
begin
return call Settings
end function | def get_settings():
return config.Settings() | Python | nomic_cornstack_python_v1 |
from telegram.ext import Updater , CommandHandler
function start update context
begin
call reply_text string Hello!
end function
set updater = call Updater string YOUR_TOKEN use_context=true
set dp = dispatcher
call add_handler call CommandHandler string start start
call start_polling
call idle | from telegram.ext import Updater, CommandHandler
def start(update, context):
update.message.reply_text('Hello!')
updater = Updater('YOUR_TOKEN', use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler('start', start))
updater.start_polling()
updater.idle()
| Python | flytech_python_25k |
function attributeClass self attribute
begin
pass
end function | def attributeClass(self, attribute):
pass | Python | nomic_cornstack_python_v1 |
string https://programmers.co.kr/learn/courses/30/lessons/12918 풀이 : 문자열이 숫자로 이루어져 있는지, 문자열 길이가 4, 6 과 같은지 비교한 후 모두 True일 때 True를, 아닐 경우 False를 반환합니다.
function solution s
begin
return call isnumeric and length s in tuple 4 6
end function
set s = string a234
print call solution s | '''
https://programmers.co.kr/learn/courses/30/lessons/12918
풀이 : 문자열이 숫자로 이루어져 있는지, 문자열 길이가 4, 6 과 같은지 비교한 후 모두 True일 때 True를, 아닐 경우 False를 반환합니다.
'''
def solution(s):
return s.isnumeric() and len(s) in (4, 6)
s = "a234"
print(solution(s)) | Python | zaydzuhri_stack_edu_python |
function hit self char
begin
raise NotImplementedError
end function | def hit(self, char):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
import itertools
set nums = list string 0 string 1 string 2 string 3 string 4 string 5 string 6 string 7 string 8 string 9
set num = 0
for perm in permutations nums
begin
set num = num + 1
if num == 1000000
begin
print join string perm
break
end
end | import itertools
nums = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
num = 0
for perm in itertools.permutations(nums):
num += 1
if num == 1000000:
print("".join(perm))
break
| Python | zaydzuhri_stack_edu_python |
from PIL import ImageGrab
import pyautogui as pag
import time
import random
comment 퀘스트 순간이동 좌표 893, 216 900 223
comment 917, 112 / 935, 147
function left_dailyquest x1 x2 y1 y2
begin
sleep uniform 3.5 4.5
call click uniform 907 929 uniform 47 62 1 uniform 0.3 0.6
sleep uniform 3.5 4.5
comment 메뉴(좌)
call click uniform ... | from PIL import ImageGrab
import pyautogui as pag
import time
import random
# 퀘스트 순간이동 좌표 893, 216 900 223
# 917, 112 / 935, 147
def left_dailyquest(x1, x2, y1, y2):
time.sleep(random.uniform(3.5, 4.5))
pag.click(random.uniform(907, 929), random.uniform(47, 62), 1, random.uniform(0.3, 0.6))
time.sleep(rand... | Python | zaydzuhri_stack_edu_python |
function get_subdict indict phrase
begin
set subdict = dict
for key in indict
begin
if phrase in key
begin
set subdict at key = indict at key
end
end
return subdict
end function | def get_subdict(indict, phrase):
subdict = {}
for key in indict:
if phrase in key:
subdict[key] = indict[key]
return subdict | Python | nomic_cornstack_python_v1 |
function endpoint self
begin
if not has attribute self string _endpoint
begin
set _endpoint = call create_endpoint dmd
end
return _endpoint
end function | def endpoint(self):
if not hasattr(self, '_endpoint'):
self._endpoint = create_endpoint(self.dmd)
return self._endpoint | Python | nomic_cornstack_python_v1 |
function test_cart_coupon_delete self
begin
pass
end function | def test_cart_coupon_delete(self):
pass | Python | nomic_cornstack_python_v1 |
function mut self
begin
for tuple src piece in items self
begin
comment Pieces of opposite color don't get to move
if color != tomove
begin
continue
end
yield from call mut src self
end
end function | def mut(self):
for src, piece in self.items():
# Pieces of opposite color don't get to move
if piece.color != self.tomove:
continue
yield from piece.mut(src, self) | Python | nomic_cornstack_python_v1 |
function FeatureCircularPattern self Num=defaultNamedNotOptArg Spacing=defaultNamedNotOptArg FlipDir=defaultNamedNotOptArg DName=defaultNamedNotOptArg
begin
set ret = call InvokeTypes 40 LCID 1 tuple 9 0 tuple tuple 3 1 tuple 5 1 tuple 11 1 tuple 8 1 Num Spacing FlipDir DName
if ret is not none
begin
set ret = call Dis... | def FeatureCircularPattern(self, Num=defaultNamedNotOptArg, Spacing=defaultNamedNotOptArg, FlipDir=defaultNamedNotOptArg, DName=defaultNamedNotOptArg):
ret = self._oleobj_.InvokeTypes(40, LCID, 1, (9, 0), ((3, 1), (5, 1), (11, 1), (8, 1)),Num
, Spacing, FlipDir, DName)
if ret is not None:
ret = Dispatch(ret, ... | Python | nomic_cornstack_python_v1 |
import main
function get_int_data text
begin
while true
begin
set data_to_check = input text
try
begin
set data_to_check = integer data_to_check
return data_to_check
end
except ValueError
begin
print string That's now even a digit
end
end
end function
function caloric_formula
begin
set weight = call get_int_data string... | import main
def get_int_data(text):
while True:
data_to_check = input(text)
try:
data_to_check = int(data_to_check)
return data_to_check
except ValueError:
print("That's now even a digit")
def caloric_formula():
weight = get_int_data('How much is y... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine , func
from flask import Flask , jsonify
comment Database Setup
set engine = call create_engine string sqlite:///hawaii.sqlite
comment reflect an existing database... | import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#################################################
# Database Setup
#################################################
eng... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import pygame , math
from pygame.locals import *
call init
set screenHeight = 768
set screenWidth = 1024
set screen = call set_mode tuple screenWidth screenHeight
set clock = call Clock
class Bar
begin
function __init__ self screen pos variable color barName maxPop=1.0
begin
set maxPop = m... | #!/usr/bin/env python3
import pygame,math
from pygame.locals import *
pygame.init()
screenHeight = 768
screenWidth = 1024
screen = pygame.display.set_mode((screenWidth,screenHeight))
clock = pygame.time.Clock()
class Bar():
def __init__(self,screen,pos,variable,color,barName,maxPop=1.0):
self.ma... | Python | zaydzuhri_stack_edu_python |
import os
import torch
from torch.nn import functional as F
import torch.nn as nn
import torchvision.transforms as transforms
import copy
import tqdm
import matplotlib.pyplot as plt
class VAE_NOVELTY extends Module
begin
function __init__ self
begin
call __init__
set fc1 = linear 30 10
set fc21 = linear 10 2
set fc22 =... | import os
import torch
from torch.nn import functional as F
import torch.nn as nn
import torchvision.transforms as transforms
import copy
import tqdm
import matplotlib.pyplot as plt
class VAE_NOVELTY(nn.Module) :
def __init__(self) :
super(VAE_NOVELTY,self).__init__()
self.fc1 = nn.Linear(30, 10)
... | Python | zaydzuhri_stack_edu_python |
function moments_3d data_in sc_pot=0 no_unit_conversion=false
begin
set data = deep copy data_in
set charge = data at string charge
set mass = data at string mass
set energy = data at string energy
set energy at energy < 0.1 = 0.1
set de = data at string denergy
set de_e = de / energy
set e_inf = energy + charge * sc_p... | def moments_3d(data_in, sc_pot=0, no_unit_conversion=False):
data = deepcopy(data_in)
charge = data['charge']
mass = data['mass']
energy = data['energy']
energy[energy < 0.1] = 0.1
de = data['denergy']
de_e = de/energy
e_inf = energy + charge*sc_pot
e_inf[e_inf < 0] = 0.0
# ... | Python | nomic_cornstack_python_v1 |
comment for keys, values in word_dictonary.items():
comment print("{} is {}".format(keys, values))
comment # print(word_dictonary)
for values in word_dictonary
begin
print values
end | # for keys, values in word_dictonary.items():
# print("{} is {}".format(keys, values))
# # print(word_dictonary)
for values in word_dictonary:
print(values) | Python | zaydzuhri_stack_edu_python |
function _build_elements self
begin
set etypes = list mass elements_spring elements_shell elements_solid
comment self.crod, self.conrod, self.ctube,
comment self.cbar, self.cbeam,
comment self.cshear,
for etype in etypes
begin
call build
end
end function | def _build_elements(self):
etypes = [
#self.crod, self.conrod, self.ctube,
#self.cbar, self.cbeam,
#self.cshear,
self.mass,
self.elements_spring,
self.elements_shell,
self.elements_solid,
]
for etype in etypes:
... | Python | nomic_cornstack_python_v1 |
function save_final_config self configuration
begin
set filename = string transpose- + string max begin 1 + string _ + string max end 1 + string _ + string max nruns 1 + string format time time string -%Y%m%d-%H%M%S + string .json
print string Optimal block size written to + filename + string : data
call save_to_file d... | def save_final_config(self, configuration):
filename = (
"transpose-" + str(max(self.args.begin, 1)) +
"_" + str(max(self.args.end, 1)) +
"_" + str(max(self.args.nruns, 1)) +
time.strftime("-%Y%m%d-%H%M%S") + ".json")
print("Optimal block size written to... | Python | nomic_cornstack_python_v1 |
import timeit
function v28 max_num=1001
begin
set sum_diagonales = list 1
set rows = list
for k in range 1 max_num + 1 2
begin
append rows k
end
comment print(rows)
for i in range 1 length rows
begin
for j in range 0 4
begin
if j == 0
begin
set num = rows at i - 2
set verschoben = sum_diagonales at length sum_diagonal... | import timeit
def v28(max_num=1001):
sum_diagonales=[1]
rows=[]
for k in range(1,max_num+1,2):
rows.append(k)
#print(rows)
for i in range(1,len(rows)):
for j in range(0,4):
if j==0:
num=rows[i]-2
verschoben=sum_diagonales[len(s... | Python | zaydzuhri_stack_edu_python |
function train self data_iterator
begin
set history = none
set optimizer = call get_optimizer master_optimizer
set model = call model_from_json json custom_objects
compile optimizer=optimizer loss=master_loss metrics=master_metrics
call set_weights value
set tuple feature_iterator label_iterator = tee data_iterator 2
s... | def train(self, data_iterator):
history = None
optimizer = get_optimizer(self.master_optimizer)
self.model = model_from_json(self.json, self.custom_objects)
self.model.compile(optimizer=optimizer,
loss=self.master_loss, metrics=self.master_metrics)
self... | Python | nomic_cornstack_python_v1 |
import argparse
import shutil
import pandas as pd
import spacy
from nltk import sent_tokenize
from pandas import DataFrame
from scispacy.linking import EntityLinker
from tqdm import tqdm
from pathlib import Path
from urllib.request import urlretrieve
from random import shuffle
function download_quora_data output_dir
be... | import argparse
import shutil
import pandas as pd
import spacy
from nltk import sent_tokenize
from pandas import DataFrame
from scispacy.linking import EntityLinker
from tqdm import tqdm
from pathlib import Path
from urllib.request import urlretrieve
from random import shuffle
def download_quora_data(output_dir: Path... | Python | zaydzuhri_stack_edu_python |
function add_clause self clause
begin
comment TODO: Do some simplifications, and check whether clause contains p
comment and -p at the same time.
if not is instance clause Clause
begin
set clause = call Clause clause learned=false
end
if length clause == 0
begin
comment Clause is guaranteed to be false under the curren... | def add_clause(self, clause):
# TODO: Do some simplifications, and check whether clause contains p
# and -p at the same time.
if not isinstance(clause, Clause):
clause = Clause(clause, learned=False)
if len(clause) == 0:
# Clause is guaranteed to be false under ... | Python | nomic_cornstack_python_v1 |
function write_hskmem contents file_name=call mktemp string HskMem.bin
begin
if not length contents == 512 or not all generator expression type x is int for x in contents
begin
raise exception string Housekeeping memory should be a list of + format string integers of length 512, was of length {length}: {contents} lengt... | def write_hskmem(contents, file_name=tempfile.mktemp('HskMem.bin')):
if not len(contents) == 512 or \
not all(type(x) is int for x in contents):
raise Exception("Housekeeping memory should be a list of " +
"integers of length 512, was of length {length}:\n{contents}".form... | Python | nomic_cornstack_python_v1 |
comment https://projecteuler.net/problem=10
set x = 2
set list_of_primes = list
while x < 2000000
begin
if all generator expression x % prime for prime in list_of_primes
begin
append list_of_primes x
print x
end
set x = x + 1
end
print sum list_of_primes | #https://projecteuler.net/problem=10
x = 2
list_of_primes = []
while x < 2000000:
if all(x % prime for prime in list_of_primes):
list_of_primes.append(x)
print(x)
x += 1
print(sum(list_of_primes))
| Python | zaydzuhri_stack_edu_python |
comment ------------------------------------------------------------------------
comment mcw-pls functions with numba
comment by: valeria fonseca diaz
comment supervisors: Wouter Saeys, Bart De Ketelaere
comment ------------------------------------------------------------------------
import numpy as np
import numba
dec... | # ------------------------------------------------------------------------
# mcw-pls functions with numba
# by: valeria fonseca diaz
# supervisors: Wouter Saeys, Bart De Ketelaere
# ------------------------------------------------------------------------
import numpy as np
import numba
... | Python | zaydzuhri_stack_edu_python |
string View module for handling requests about games
from django.core.exceptions import ValidationError
from rest_framework import status
from django.http import HttpResponseServerError
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import serializers
from r... | """View module for handling requests about games"""
from django.core.exceptions import ValidationError
from rest_framework import status
from django.http import HttpResponseServerError
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import serializers
from re... | Python | zaydzuhri_stack_edu_python |
function read_defines_for_active_iids self
begin
if defines_for_iids
begin
call push_scope
set active_iids = call get_active_iids
for tuple iid defines_for_iid in items defines_for_iids
begin
if iid in active_iids
begin
call read_yaml_from_node defines_for_iid
end
end
end
end function | def read_defines_for_active_iids(self):
if self.items_table.defines_for_iids:
config_vars.push_scope()
active_iids = self.items_table.get_active_iids()
for iid, defines_for_iid in self.items_table.defines_for_iids.items():
if iid in active_iids:
... | Python | nomic_cornstack_python_v1 |
function Connect self ap interface=none passkey=none connect_timeout=none connect_attempt_timeout=none dhcp_timeout=none
begin
if not is instance ap AccessPoint
begin
raise call WiFiError string Expected AccessPoint for ap argument: %s % ap
end
set interface = call _ValidateInterface interface
set conn = call _NewConne... | def Connect(self, ap, interface=None, passkey=None,
connect_timeout=None, connect_attempt_timeout=None,
dhcp_timeout=None):
if not isinstance(ap, AccessPoint):
raise WiFiError('Expected AccessPoint for ap argument: %s' % ap)
interface = self._ValidateInterface(interface)
co... | Python | nomic_cornstack_python_v1 |
string 中央値 2 4 4 3 2 3 4 4 真ん中の2つの値を取り出す ⇨
set N = integer input
set Xs = list map int split input
set X_sort = sorted Xs
set M1 = X_sort at N // 2 - 1
set M2 = X_sort at N // 2
comment print(X_sort,M1,M2)
for x in Xs
begin
if x <= M1
begin
print M2
end
else
begin
print M1
end
end | """
中央値
2 4 4 3
2 3 4 4
真ん中の2つの値を取り出す
⇨
"""
N = int(input())
Xs = list(map(int, input().split()))
X_sort = sorted(Xs)
M1 = X_sort[N//2-1]
M2 = X_sort[N//2]
# print(X_sort,M1,M2)
for x in Xs:
if x <= M1:
print(M2)
else:
print(M1)
| Python | zaydzuhri_stack_edu_python |
for i in idx
begin
print find data i end=string
end | for i in idx:
print(data.find(i), end=' ')
| Python | zaydzuhri_stack_edu_python |
function save_times self time_metrics_path algorithm_name
begin
set df_time_cv = call DataFrame dict string cv_times times_cv
set df_time_train = call DataFrame dict string train_time time_train
to csv df_time_cv join path time_metrics_path algorithm_name + string _time_cv.xlsx index=false
to csv df_time_train join pat... | def save_times(self, time_metrics_path, algorithm_name):
df_time_cv = pd.DataFrame({'cv_times': self.times_cv})
df_time_train = pd.DataFrame({'train_time': self.time_train})
df_time_cv.to_csv(os.path.join(time_metrics_path, algorithm_name + '_time_cv.xlsx'), index=False)
df_time_train.t... | Python | nomic_cornstack_python_v1 |
function test_immutable_param self name opt_class only_child_vars
begin
set opt : PersistentSolver = call opt_class only_child_vars=only_child_vars
if not call available
begin
raise SkipTest
end
set m = call ConcreteModel
set x = variance pe
set y = variance pe
set a1 = call Param mutable=true
set a2 = call Param initi... | def test_immutable_param(
self, name: str, opt_class: Type[PersistentSolver], only_child_vars
):
opt: PersistentSolver = opt_class(only_child_vars=only_child_vars)
if not opt.available():
raise unittest.SkipTest
m = pe.ConcreteModel()
m.x = pe.Var()
m.y = ... | Python | nomic_cornstack_python_v1 |
import math
import turtle
import time
comment Starting a Working Screen
set ws = call Screen
comment initializing a turtle instance
set geekyTurtle = call Turtle
call bgcolor string black
call fillcolor string white
comment and why? when this is working
title turtle string Geometric Figures
call fillcolor string red
ca... | import math
import turtle
import time
# Starting a Working Screen
ws = turtle.Screen()
# initializing a turtle instance
geekyTurtle = turtle.Turtle()
turtle.bgcolor("black")
turtle.fillcolor("white")
turtle.title("Geometric Figures") # and why? when this is working
turtle.fillcolor("red")
turtle.pensize(5)
turtle.pe... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @Time : 2019/11/27 15:19
comment @Author : liuhuiling
import turtle
from turtle import *
string turtle库的使用,python标准库,无需再次安装
string turtle.setup(width,height,startx,starty) width,height窗体宽高;startx,starty窗体在屏幕中位置 turtle.setup(800,400,0,0) 窗体出现在屏幕左上方 turtl... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/27 15:19
# @Author : liuhuiling
import turtle
from turtle import *
'''turtle库的使用,python标准库,无需再次安装'''
'''
turtle.setup(width,height,startx,starty)
width,height窗体宽高;startx,starty窗体在屏幕中位置
turtle.setup(800,400,0,0) 窗体出现在屏幕左上方
turtle.setup(800... | Python | zaydzuhri_stack_edu_python |
while name
begin
set newname = input string Volgende naam:
if newname
begin
if newname in names
begin
set names at newname = names at newname + 1
end
else
begin
set names at newname = 1
end
end
else
begin
set name = false
end
end
for tuple i e in items names
begin
if e == 1
begin
print format string er is een student m... | while name:
newname = input('Volgende naam: ')
if newname:
if newname in names:
names[newname] += 1
else:
names[newname] = 1
else:
name = False
for i, e in names.items():
if e == 1:
print('er is een student met de naam: {0}'.format(i))
else:
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Jan 30 14:00:12 2017 @author: jesse
import numpy as np
from matplotlib import pyplot as plt
class BinFile
begin
function __init__ self filename
begin
set totalChannels = 8
set filename = filename
set dataType = string <d
set data = list 0
end function
comment filename... | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 30 14:00:12 2017
@author: jesse
"""
import numpy as np
from matplotlib import pyplot as plt
class BinFile:
def __init__(self, filename):
self.totalChannels = 8
self.filename = filename
self.dataType = '<d'
self.data = [0]
... | Python | zaydzuhri_stack_edu_python |
function run self current_time
begin
raise call NotImplementedError string The run() method must be implemented by each class subclassing Event
end function | def run(self, current_time):
raise NotImplementedError("The run() method must be implemented by "
"each class subclassing Event") | Python | nomic_cornstack_python_v1 |
function validate_usage self key_usage extended_key_usage=none extended_optional=false
begin
string Validates the certificate path and that the certificate is valid for the key usage and extended key usage purposes specified. :param key_usage: A set of unicode strings of the required key usage purposes. Valid values in... | def validate_usage(self, key_usage, extended_key_usage=None, extended_optional=False):
"""
Validates the certificate path and that the certificate is valid for
the key usage and extended key usage purposes specified.
:param key_usage:
A set of unicode strings of the required... | Python | jtatman_500k |
function print_solution manager routing solution data
begin
print format string Objective: {} miles call ObjectiveValue
set index = start routing 0
set plan_output = string Route for vehicle 0:
set route_distance = 0
while not call IsEnd index
begin
set plan_output = plan_output + data at string adress at index + strin... | def print_solution(manager, routing, solution,data):
print('Objective: {} miles'.format(solution.ObjectiveValue()))
index = routing.Start(0)
plan_output = 'Route for vehicle 0:\n'
route_distance = 0
while not routing.IsEnd(index):
plan_output += data['adress'][index]+"-->"
pre... | Python | nomic_cornstack_python_v1 |
comment From Quick Sort in Wikipedia
function quicksort lst lo hi
begin
if lo < hi
begin
set p = call partition lst lo hi
call quicksort lst lo p
call quicksort lst p + 1 hi
end
return lst
end function
function partition lst lo hi
begin
set pivot = lst at hi - 1
set i = lo - 1
for j in range lo hi
begin
if lst at j < p... | # From Quick Sort in Wikipedia
def quicksort(lst, lo, hi):
if lo < hi:
p = partition(lst, lo, hi)
quicksort(lst, lo, p)
quicksort(lst, p + 1, hi)
return lst
def partition(lst, lo, hi):
pivot = lst[hi - 1]
i = lo - 1
for j in range(lo, hi):
if lst[j]... | Python | zaydzuhri_stack_edu_python |
function find_duplicates self
begin
set fnames = list call list_images dirname
set hashes = default dictionary list
print string Finding Duplicates Now!
for image in fnames
begin
with open image as img
begin
set temp_hash = call average_hash img hash_size
if temp_hash in hashes
begin
print format string Duplicate {} fo... | def find_duplicates(self):
fnames = list(paths.list_images(self.dirname))
hashes = defaultdict(list)
print("Finding Duplicates Now!\n")
for image in fnames:
with Image.open(image) as img:
temp_hash = imagehash.average_hash(img, self.hash_size)
... | Python | nomic_cornstack_python_v1 |
function edge_form cls v1 v2 *args **kwargs
begin
return call DirectedEdge tuple list v1 v2 *args keyword kwargs
end function | def edge_form(cls, v1: Vertex, v2: Vertex, *args, **kwargs):
return DirectedEdge(tuple([v1, v2]), *args, **kwargs) | Python | nomic_cornstack_python_v1 |
function evaluate_memo_position current_num memo_dict
begin
global counter
set counter = counter + 1
comment enter code here
return string lost
end function | def evaluate_memo_position(current_num, memo_dict):
global counter
counter += 1
# enter code here
return "lost" | Python | nomic_cornstack_python_v1 |
function _create_map self
begin
set condition = lambda x obj -> x at 0 != string _ and has attribute obj string __call__ and __doc__ is not none and string opcode in __doc__
set to_opcode = lambda x -> replace upper x string __ string +
set _map = default dictionary lambda -> nop
set _extra = set
set _missing = set
se... | def _create_map(self):
condition = lambda x, obj: (
x[0] != "_" and hasattr(obj, "__call__") and
obj.__doc__ is not None and "opcode" in obj.__doc__)
to_opcode = lambda x: x.upper().replace("__", "+")
self._map = defaultdict(lambda: self.nop)
self._extra = set()
... | Python | nomic_cornstack_python_v1 |
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QApplication , QDockWidget , QHBoxLayout , QListWidget , QMainWindow , QTextEdit , QTreeView
string 1. The model is a collection of functions TODO 1. How to allow adding functions from the UI 2. Writing the model to source
class... | import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import (
QApplication,
QDockWidget,
QHBoxLayout,
QListWidget,
QMainWindow,
QTextEdit,
QTreeView
)
"""
1. The model is a collection of functions
TODO
1. How to allow adding functions from the UI
2. Writi... | Python | zaydzuhri_stack_edu_python |
comment import packages
import torch
import torch.nn as nn
from torch.utils.data import Dataset , DataLoader
from tqdm.notebook import tqdm , trange
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
comment hyperparameters
set batch_size = 1
set hidden_layers = 32
set learning... | ## import packages
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from tqdm.notebook import tqdm, trange
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
## hyperparameters
batch_size = 1
hidden_layers = 32
learning_rate = 0.... | Python | zaydzuhri_stack_edu_python |
comment 函数的注意事项:1、函数名不能相同2、变量名不能和函数名相同
function show
begin
print string 好爽啊
end function
function show msg
begin
print msg
end function
show string d | # 函数的注意事项:1、函数名不能相同2、变量名不能和函数名相同
def show():
print("好爽啊")
def show(msg):
print(msg)
show('d') | Python | zaydzuhri_stack_edu_python |
comment A comparison of methods of calculating the Fibonacci numbers
comment using naive recursion, memoization and a bottom-up approach
comment Naive recursion approach
function fib n
begin
if n == 1 or n == 2
begin
return 1
end
else
begin
return call fib n - 1 + call fib n - 2
end
end function
comment Momoize functio... | # A comparison of methods of calculating the Fibonacci numbers
# using naive recursion, memoization and a bottom-up approach
# Naive recursion approach
def fib(n):
if n == 1 or n ==2:
return 1
else:
return fib(n-1) + fib(n-2)
# Momoize function
def fib_memo(n, M = {1:1, 2:1}):
if n in M.ke... | Python | zaydzuhri_stack_edu_python |
function _transpiled_circuits self
begin
set has_custom_transpile_option = not call issubset set literal string basis_gates string optimization_level or get transpile_options string optimization_level 1 != 1
set has_no_undirected_2q_basis = call _get_basis_gates is none
if num_qubits > 2 or has_custom_transpile_option ... | def _transpiled_circuits(self) -> List[QuantumCircuit]:
has_custom_transpile_option = (
not set(vars(self.transpile_options)).issubset({"basis_gates", "optimization_level"})
or self.transpile_options.get("optimization_level", 1) != 1
)
has_no_undirected_2q_basis = self._g... | Python | nomic_cornstack_python_v1 |
string 7. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, равнобедренным или равносторонним.
set SIDE_A = integer input string Введите длину отрезка А:
se... | """
7. По длинам трех отрезков, введенных пользователем,
определить возможность существования треугольника,
составленного из этих отрезков. Если такой треугольник существует,
то определить, является ли он разносторонним, равнобедренным или равносторонним.
"""
SIDE_A = int(input("Введите длину отрезка А: "))
SIDE_B = i... | Python | zaydzuhri_stack_edu_python |
function get_logger logname
begin
set logger = call getLogger logname
set formater = call Formatter fmt=string %(asctime)s - %(filename)s : %(levelname)-5s :: %(message)s datefmt=string %m/%d/%Y %H:%M:%S
comment filename='./log.log',
comment filemode='a',
set stream_hdlr = call StreamHandler
call setFormatter formater
... | def get_logger(logname: str):
logger = logging.getLogger(logname)
formater = logging.Formatter(
fmt='%(asctime)s - %(filename)s : %(levelname)-5s :: %(message)s',
# filename='./log.log',
# filemode='a',
datefmt='%m/%d/%Y %H:%M:%S')
stream_hdlr = logging.StreamHandler()
st... | Python | nomic_cornstack_python_v1 |
function _from_catalog self
begin
if version < 90300
begin
return
end
for trig in call fetch
begin
set enabled = enable_modes at enabled
set self at call key = trig
end
end function | def _from_catalog(self):
if self.dbconn.version < 90300:
return
for trig in self.fetch():
trig.enabled = self.enable_modes[trig.enabled]
self[trig.key()] = trig | Python | nomic_cornstack_python_v1 |
function get_vgg_model self
begin
comment Load our model. We load pretrained VGG, trained on imagenet data
set vgg_model = call VGG19 include_top=false weights=string imagenet
set trainable = false
comment Get output layers corresponding to style and content layers
set style_outputs = list comprehension output for name... | def get_vgg_model(self):
# Load our model. We load pretrained VGG, trained on imagenet data
self.vgg_model = tf.keras.applications.vgg19.VGG19(
include_top=False, weights='imagenet')
self.vgg_model.trainable = False
# Get output layers corresponding to style and content layer... | Python | nomic_cornstack_python_v1 |
function set_names zma name_dct
begin
set orig_vma = call var_ zma
set vma = call set_names orig_vma name_dct
set name_mat = call name_matrix vma
set name_dct = dictionary zip call ravel call name_matrix orig_vma call ravel name_mat
set val_dct = dictionary comprehension name_dct at orig_name : val for tuple orig_name ... | def set_names(zma, name_dct):
orig_vma = var_(zma)
vma = _v_.set_names(orig_vma, name_dct)
name_mat = _v_.name_matrix(vma)
name_dct = dict(zip(numpy.ravel(_v_.name_matrix(orig_vma)),
numpy.ravel(name_mat)))
val_dct = {name_dct[orig_name]: val
for orig_name, va... | Python | nomic_cornstack_python_v1 |
function Run cmd stdout=DefaultStdoutHandler stderr=DefaultStderrHandler **kwargs
begin
with call PerfTimer string Commands
begin
if showCommands
begin
call Command join string generator expression quote s for s in cmd
end
set output = list
set errors = list
set shared = call _sharedStreamProcessingData
function _st... | def Run(cmd, stdout=DefaultStdoutHandler, stderr=DefaultStderrHandler, **kwargs):
with perf_timer.PerfTimer("Commands"):
if shared_globals.showCommands:
log.Command(" ".join(quote(s) for s in cmd))
output = []
errors = []
shared = _sharedStreamProcessingData()
def _streamOutput(pipe, outlist, callback):... | Python | nomic_cornstack_python_v1 |
comment 文件db的内容为:{"count":1}
comment 注意一定要用双引号,不然json无法识别
from multiprocessing import Process , Lock
import time , json , random
import os
from json import JSONDecodeError
function search
begin
set dic = load json open join path directory name path absolute path path __file__ string db.txt
print string [43m剩余票数%s[0m ... | #文件db的内容为:{"count":1}
#注意一定要用双引号,不然json无法识别
from multiprocessing import Process,Lock
import time,json,random
import os
from json import JSONDecodeError
def search():
dic=json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)),'db.txt')))
print('\033[43m剩余票数%s\033[0m' %dic['count'])
d... | Python | zaydzuhri_stack_edu_python |
comment -*- coding = utf-8 -*-
comment @Time : 2021/8/25 21:25
comment @Author : ghan
comment @File : spider.py
import socket
function main
begin
comment 1、创建tcp套接字 dgram-udp stream-tcp
set tcp_socket = call socket AF_INET SOCK_STREAM
comment 2、链接服务器
comment tcp_socket.connect("192.168.22.1",8080)
set server_ip = input... | #-*- coding = utf-8 -*-
#@Time : 2021/8/25 21:25
#@Author : ghan
#@File : spider.py
import socket
def main():
#1、创建tcp套接字 dgram-udp stream-tcp
tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#2、链接服务器
# tcp_socket.connect("192.168.22.1",8080)
server_ip = input("请输入要链接的... | Python | zaydzuhri_stack_edu_python |
function inject_or self base_cls settings=none default=none
begin
if not _active
begin
raise call ProfileSessionInactiveError
end
return call inject_or base_cls settings default
end function | def inject_or(
self,
base_cls: Type[InjectType],
settings: Mapping[str, object] = None,
default: Optional[InjectType] = None,
) -> Optional[InjectType]:
if not self._active:
raise ProfileSessionInactiveError()
return self._context.inject_or(base_cls, setti... | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
set w = call Variable call random_normal list 3 2 stddev=1
set x = call placeholder float32 shape=tuple 1 3 name=string input
set y = matrix multiply x w
set sess = call Session
run call global_variables_initializer
print run y feed_dict=dict x list list 1 2 3 | import tensorflow as tf
w = tf.Variable(tf.random_normal([3, 2], stddev=1))
x = tf.placeholder(tf.float32, shape=(1, 3), name="input")
y = tf.matmul(x, w)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(y, feed_dict={x: [[1, 2, 3]]}))
| Python | zaydzuhri_stack_edu_python |
function setUp self
begin
print string --------------------------NEXT-TEST----------------------------------------------
set chrome_options = options
set binary_location = string /usr/bin/chromium-browser
call add_argument string --headless
set driver = call Chrome executable_path=string /home/ryanpurchase288_rp/chrome... | def setUp(self):
print("--------------------------NEXT-TEST----------------------------------------------")
chrome_options = Options()
chrome_options.binary_location = "/usr/bin/chromium-browser"
chrome_options.add_argument("--headless")
self.driver = webdriver.Chrome(executable_... | Python | nomic_cornstack_python_v1 |
function __str__ self
begin
return title
end function | def __str__(self):
return self.title | Python | nomic_cornstack_python_v1 |
import sys
comment sys.stdin.readline() 로 해주면 출력초과
set input = readline
function cases first length
begin
if length == 6
begin
for i in range k
begin
if check at i == 1
begin
print nums at i end=string
end
end
print
end
for i in range first k
begin
set check at i = 1
call cases i + 1 length + 1
set check at i = 0
end
e... | import sys
input = sys.stdin.readline # sys.stdin.readline() 로 해주면 출력초과
def cases(first,length):
if(length == 6):
for i in range(k):
if(check[i] == 1):
print(nums[i],end=' ')
print()
for i in range(first,k):
check[i] = 1
cases(i+1,length+1)
... | Python | zaydzuhri_stack_edu_python |
string network.py Represents a neural network (collection of layers) Roujia Zhong & Luhang Sun CS343: Neural Networks Project 3: Convolutional Neural Networks
import numpy as np
import layer
import optimizer
import accelerated_layer
seed 0
class Network
begin
string Represents a neural network with some number of layer... | '''network.py
Represents a neural network (collection of layers)
Roujia Zhong & Luhang Sun
CS343: Neural Networks
Project 3: Convolutional Neural Networks
'''
import numpy as np
import layer
import optimizer
import accelerated_layer
np.random.seed(0)
class Network():
'''Represents a neural network with some num... | Python | zaydzuhri_stack_edu_python |
function get_seeds_from_mask mask image_json_pair
begin
set label_positions = call get_label_positions
set cuts = call get_cuts_for_image mask label_positions
comment get coordinate & append to seeds
set seeds = call get_pixel_coordinates_of_edges_in_cuts cuts label_positions
return seeds
end function | def get_seeds_from_mask(mask, image_json_pair):
label_positions = image_json_pair.get_label_positions()
cuts = get_cuts_for_image(mask, label_positions)
# get coordinate & append to seeds
seeds = get_pixel_coordinates_of_edges_in_cuts(cuts, label_positions)
return seeds | Python | nomic_cornstack_python_v1 |
async function done self awaitable
begin
call abort_due_to_other
set result = await awaitable
call _become_current
return result
end function | async def done(self, awaitable: Awaitable) -> Any:
self.abort_due_to_other()
result = await awaitable
self._become_current()
return result | Python | nomic_cornstack_python_v1 |
function _detect self
begin
set tuple img_10 img_11 positions = call detect_f img_01 keyword detect_kwargs
end function | def _detect(self):
self.img_10, self.img_11, positions = \
self.detect_f(self.img_01, **self.detect_kwargs) | Python | nomic_cornstack_python_v1 |
function set_data self addr data_dump
begin
string Update any data range (most likely use is the data segments of loaded objects)
set data = call _read_data data_dump
info string Set data from 0x%x to %#x addr addr + length data
call _write addr data
end function | def set_data(self, addr, data_dump):
"""
Update any data range (most likely use is the data segments of loaded objects)
"""
data = self._read_data(data_dump)
l.info("Set data from 0x%x to %#x", addr, addr+len(data))
self._write(addr, data) | Python | jtatman_500k |
comment Ask user for favourite team
set favouriteTeam = input string What is your favourite hockey team?
comment Make input all lower case for if statement check
comment favouriteTeam = favouriteTeam.lower()
if lower favouriteTeam == string senators
begin
print string Yeah Go Sens Go
print string nice man
end
print str... | #Ask user for favourite team
favouriteTeam = input("What is your favourite hockey team?")
#Make input all lower case for if statement check
#favouriteTeam = favouriteTeam.lower()
if favouriteTeam.lower() == "senators" :
print("Yeah Go Sens Go")
print("nice man")
print("It's ok if you do not like hockey") | 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.