code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get_instance_el evaluator instance var is_class_var=false
begin
if is instance var Name
begin
set parent = call get_instance_el evaluator instance parent is_class_var
return call InstanceName var parent
end
else
comment PATCH: compiled objects can be None
if var is none
begin
return var
end
else
if type != str... | def get_instance_el(evaluator, instance, var, is_class_var=False):
if isinstance(var, tree.Name):
parent = get_instance_el(evaluator, instance, var.parent,
is_class_var)
return InstanceName(var, parent)
# PATCH: compiled ob... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string Some variations for labeling images
function drop_polygons polys p=0.5
begin
string Randomly drop a fraction of polygons from a multipoly
set subpolys = list
for i in range length polys
begin
if random < p
begin
append subpolys polys at i
end
end
return call MultiPolygon subpolys
en... | #!/usr/bin/env python
"""
Some variations for labeling images
"""
def drop_polygons(polys, p=0.5):
"""
Randomly drop a fraction of polygons from a multipoly
"""
subpolys = []
for i in range(len(polys)):
if np.random.random() < p:
subpolys.append(polys[i])
return shapely.ge... | Python | zaydzuhri_stack_edu_python |
function test_blogpost_belongs_to_app self
begin
call configure_fixtures
set blogpost = call Blogpost title=string title body=string body app=none
end function | def test_blogpost_belongs_to_app(self):
self.configure_fixtures()
blogpost = Blogpost(title='title', body="body", app=None) | Python | nomic_cornstack_python_v1 |
class Player extends object
begin
set game_state_attributes = list string id string playerName string time string scarabs string roundsWon string sarcophagiCaptured
function __init__ self game id playerName time scarabs roundsWon sarcophagiCaptured
begin
set game = game
set id = id
set playerName = playerName
set time ... | class Player(object):
game_state_attributes = ['id', 'playerName', 'time', 'scarabs', 'roundsWon', 'sarcophagiCaptured']
def __init__(self, game, id, playerName, time, scarabs, roundsWon, sarcophagiCaptured):
self.game = game
self.id = id
self.playerName = playerName
self.time = time
self.scarab... | Python | zaydzuhri_stack_edu_python |
import math
comment Teto
print ceil 10.5
comment Piso
print floor 10.5
comment Fatorial
print call factorial 3
comment Potencia
comment Retorna valor float
print power 5 2
comment Não necessariamente retorna float
print 5 ^ 2
comment Raiz quadrada
print square root 4
comment Maior divisor comum (MDC)
print call gcd 5 2... | import math
# Teto
print(math.ceil(10.5))
# Piso
print(math.floor(10.5))
# Fatorial
print(math.factorial(3))
# Potencia
print(math.pow(5, 2)) # Retorna valor float
print(5**2) # Não necessariamente retorna float
# Raiz quadrada
print(math.sqrt(4))
# Maior divisor comum (MDC)
print(math.gcd(5, 20))
| Python | zaydzuhri_stack_edu_python |
function _reader path password prompt
begin
string Read PDF and decrypt if encrypted.
set pdf = if expression not is instance path PdfFileReader then call PdfFileReader path else path
comment Check that PDF is encrypted
if isEncrypted
begin
comment Check that password is none
if not password
begin
call decrypt string
c... | def _reader(path, password, prompt):
"""Read PDF and decrypt if encrypted."""
pdf = PdfFileReader(path) if not isinstance(path, PdfFileReader) else path
# Check that PDF is encrypted
if pdf.isEncrypted:
# Check that password is none
if not password:
... | Python | jtatman_500k |
function form_SequenceOfStringsWithSequenceWidgetOptions request
begin
set schema = call Structure
add schema string myList call Sequence call String
set form = call Form schema string form
set widget = call SequenceDefault min_start_fields=1 min_empty_start_fields=0 batch_add_count=5
return form
end function | def form_SequenceOfStringsWithSequenceWidgetOptions(request):
schema = schemaish.Structure()
schema.add( 'myList', schemaish.Sequence( schemaish.String() ))
form = formish.Form(schema, 'form')
form['myList'].widget = formish.SequenceDefault(min_start_fields=1,min_empty_start_fields=0, batch_add_count=5... | Python | nomic_cornstack_python_v1 |
function entity_guid self
begin
return get pulumi self string entity_guid
end function | def entity_guid(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "entity_guid") | Python | nomic_cornstack_python_v1 |
function Residuals Sc R LH CHT
begin
return call R_Star_Model call E_Star Sc CHT LH - call R_Star Sc R LH
end function | def Residuals(Sc, R, LH, CHT):
return R_Star_Model(E_Star(Sc,CHT,LH)) - R_Star(Sc, R, LH) | Python | nomic_cornstack_python_v1 |
function _post self *args **kwargs
begin
return call pdcch_interleaver_sptr__post self *args keyword kwargs
end function | def _post(self, *args, **kwargs):
return _my_lte_swig.pdcch_interleaver_sptr__post(self, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
from tkinter import Tk , Canvas , BOTH , Frame , Label , GROOVE , LEFT , TOP , NW , FLAT , Button , CENTER , Spinbox
import ClientParams
class Gui
begin
function __init__ self
begin
set window = call _create_window
set waiting_room = call _create_waiting_room_visualisation
set waiting_room_canvas = call _create_waiting... | from tkinter import Tk, Canvas, BOTH, Frame, Label, GROOVE, LEFT, TOP, NW, FLAT, Button, CENTER, Spinbox
import ClientParams
class Gui:
def __init__(self):
self.window = self._create_window()
self.waiting_room = self._create_waiting_room_visualisation()
self.waiting_room_canvas = self._cre... | Python | zaydzuhri_stack_edu_python |
string Given an array of strings, return another array containing all of its longest strings.
function allLongestStrings inputArray
begin
set m = max generator expression length s for s in inputArray
set longest = list comprehension s for s in inputArray if length s == m
return longest
end function | """Given an array of strings, return another array containing all of its longest strings."""
def allLongestStrings(inputArray):
m = max(len(s) for s in inputArray)
longest = [s for s in inputArray if len(s) == m]
return longest
| Python | zaydzuhri_stack_edu_python |
function make_list elements
begin
if is instance elements tuple list tuple
begin
return elements
end
else
begin
return list elements
end
end function | def make_list( elements ):
if isinstance(elements, (list, tuple)):
return elements
else:
return [elements] | Python | nomic_cornstack_python_v1 |
import string
function CheckWord password
begin
set tuple rule1 rule2 rule3 rule4 = tuple true true true true
if length password < 10
begin
rule1 == false
end
set tuple uppercase lowercase punctuation numerical = tuple 0 0 0 0
for character in password
begin
if is upper character == true
begin
set uppercase = uppercase... | import string
def CheckWord(password):
rule1, rule2, rule3, rule4 = True, True, True, True
if(len(password) < 10):
rule1 == False
uppercase, lowercase, punctuation, numerical = 0, 0, 0, 0
for character in password:
if(character.isupper() == True):
uppercase += 1
elif(... | Python | zaydzuhri_stack_edu_python |
for number in my_list
begin
if number % 2 == 0
begin
print string number + string is even
end
else
begin
print string number + string is odd
end
end | for number in my_list:
if number % 2 == 0:
print (str(number) + ' is even' )
else:
print(str(number) + ' is odd')
| Python | zaydzuhri_stack_edu_python |
class MaxHeap
begin
function __init__ self
begin
set heap = list
end function
function insert self value
begin
append heap value
call _siftUp length heap - 1
end function
function deleteMax self
begin
if length heap == 0
begin
raise call IndexError string Priority queue is empty
end
set max_value = heap at 0
set last_... | class MaxHeap:
def __init__(self):
self.heap = []
def insert(self, value):
self.heap.append(value)
self._siftUp(len(self.heap) - 1)
def deleteMax(self):
if len(self.heap) == 0:
raise IndexError("Priority queue is empty")
max_value = self... | Python | jtatman_500k |
string 1st step Get Scores Regular year txt Format: homeIndex homeScore awayIndex awayScore
import pandas as pd
import numpy as np
from util import teamToIndex
from os import walk
from os import path
set myPath = string ./Data/
for tuple dirpath dirnames filenames in walk myPath
begin
if dirpath == myPath
begin
continu... | '''
1st step
Get Scores Regular year txt
Format:
homeIndex homeScore awayIndex awayScore
'''
import pandas as pd
import numpy as np
from util import teamToIndex
from os import walk
from os import path
myPath = './Data/'
for (dirpath, dirnames, filenames) in walk(myPath):
if (dirpath == myPath):
continue
slash... | Python | zaydzuhri_stack_edu_python |
import pygame
from network import Network
from game import Game
set tuple WIDTH HEIGHT = tuple 800 800
set WINDOW = call set_mode tuple WIDTH HEIGHT
call set_caption string Tic Tac Toe
set WHITE = tuple 255 255 255
set BLACK = tuple 0 0 0
set GREY = tuple 255 240 240
set BEIGE = tuple 249 243 221
set RED = tuple 255 0 ... | import pygame
from network import Network
from game import Game
WIDTH,HEIGHT = 800,800
WINDOW = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Tic Tac Toe")
WHITE = (255,255,255)
BLACK = (0,0,0)
GREY = (255,240,240)
BEIGE = (249,243,221)
RED = (255,0,0)
BLUE = (0,0,255)
cols,rows = 3,3
pygame.font... | Python | zaydzuhri_stack_edu_python |
import pygame
from settings import Settings
from ship import Ship
from Alien import Alien
import game_functions as gf
from pygame.sprite import Group
from game_states import GameStates
from button import Button
from scoreboard import Scoreboard
function run_game
begin
call init
set ai_settings = call Settings
set scree... | import pygame
from settings import Settings
from ship import Ship
from Alien import Alien
import game_functions as gf
from pygame.sprite import Group
from game_states import GameStates
from button import Button
from scoreboard import Scoreboard
def run_game():
pygame.init()
ai_settings=Settings()
sc... | Python | zaydzuhri_stack_edu_python |
function test_pydotprint_profile
begin
comment Skip test if pydot is not available.
if not pydot_imported
begin
raise call SkipTest string pydot not available
end
set A = call matrix
set f = call function list A A + 1 mode=string ProfileMode
call pydotprint f print_output_file=false
end function | def test_pydotprint_profile():
# Skip test if pydot is not available.
if not theano.printing.pydot_imported:
raise SkipTest('pydot not available')
A = tensor.matrix()
f = theano.function([A], A + 1, mode='ProfileMode')
theano.printing.pydotprint(f, print_output_file=False) | Python | nomic_cornstack_python_v1 |
function fit_latent_network_given_A x0 loc_sampler N_samples=1000
begin
set x = x0
set smpls = list x0
end function | def fit_latent_network_given_A(x0, loc_sampler, N_samples=1000):
x = x0
smpls = [x0] | Python | nomic_cornstack_python_v1 |
import time
import datetime
import re
import numpy as np
from numpy import argmax
import pandas as pd
from sklearn.model_selection import train_test_split , StratifiedKFold
from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_extraction.text import TfidfVectorizer , CountVectorizer
from sklearn.prepr... | import time
import datetime
import re
import numpy as np
from numpy import argmax
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.preproc... | Python | zaydzuhri_stack_edu_python |
class Customer
begin
function __init__ self name account_number balance
begin
set name = name
set account_number = account_number
set balance = balance
end function
function get_balance self
begin
return balance
end function
function deposit self amount
begin
set balance = balance + amount
end function
function withdra... | class Customer:
def __init__(self, name, account_number, balance):
self.name = name
self.account_number = account_number
self.balance = balance
def get_balance(self):
return self.balance
def deposit(self, amount):
self.balance += amount
def withdraw... | Python | jtatman_500k |
comment Вычислите |x|+x**5, если x=−2.
import math
set x = - 2
print call fabs x + x ^ 5 | #Вычислите |x|+x**5, если x=−2.
import math
x = -2
print (math.fabs(x) + x ** 5)
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string Building a model with Keras
import tensorflow.keras as K
function build_model nx layers activations lambtha keep_prob
begin
string Function that that builds a neural network with the Keras library Arguments: - nx is the number of input features to the network - layers is a list cont... | #!/usr/bin/env python3
"""
Building a model with Keras
"""
import tensorflow.keras as K
def build_model(nx, layers, activations, lambtha, keep_prob):
"""
Function that that builds a neural network with the Keras library
Arguments:
- nx is the number of input features to the network
- layers is... | Python | zaydzuhri_stack_edu_python |
function __iter__ self
begin
return deep copy self
end function | def __iter__(self) -> 'Dictionary':
return copy.deepcopy(self) | Python | nomic_cornstack_python_v1 |
function GetQueryTerm
begin
set random_index = call randrange 0 length COMMON_TERM_LIST
set common_term = COMMON_TERM_LIST at random_index
set term_length = random integer MIN_TERM_LENGTH MAX_TERM_LENGTH
set random_list = list
for j in range term_length
begin
append random_list character ordinal string a + random inte... | def GetQueryTerm():
random_index = random.randrange(0, len(COMMON_TERM_LIST))
common_term = COMMON_TERM_LIST[random_index]
term_length = random.randint(MIN_TERM_LENGTH, MAX_TERM_LENGTH)
random_list = []
for j in range(term_length):
random_list.append(chr(ord("a") + random.randint(0, 25)))
random_term = ... | Python | nomic_cornstack_python_v1 |
function test_pytest_unconfigure mocked_config
begin
set _reporter = call Mock
set unregister = call Mock
call pytest_unconfigure mocked_config
assert not has attribute mocked_config string _reporter
end function | def test_pytest_unconfigure(mocked_config):
mocked_config._reporter = mock.Mock()
mocked_config.pluginmanager.unregister = mock.Mock()
pytest_unconfigure(mocked_config)
assert not hasattr(mocked_config, '_reporter') | Python | nomic_cornstack_python_v1 |
function __init__ __self__ server type annotations=none authentication_type=none connect_via=none description=none encrypted_credential=none parameters=none password=none user_name=none
begin
set __self__ string server server
set __self__ string type string SapHana
if annotations is not none
begin
set __self__ string a... | def __init__(__self__, *,
server: Any,
type: str,
annotations: Optional[Sequence[Any]] = None,
authentication_type: Optional[str] = None,
connect_via: Optional['outputs.IntegrationRuntimeReferenceResponse'] = None,
des... | Python | nomic_cornstack_python_v1 |
while num <= 10
begin
print num
set num = num + 1
end
set loop_condition = true
while loop_condition
begin
print string Loop Condition keeps: %s % loop_condition
set loop_condition = false
end
for i in range 1 11
begin
print i
end
set bookshelf = list string The Effective Engineer string The 4 hours work week string Ze... | while num <= 10:
print(num)
num += 1
loop_condition = True
while loop_condition:
print("Loop Condition keeps: %s" % (loop_condition))
loop_condition = False
for i in range(1, 11):
print(i)
bookshelf = [
"The Effective Engineer",
"The 4 hours work week",
"Zero to One",
"Lean... | Python | zaydzuhri_stack_edu_python |
async function appsetup self ctx
begin
comment Need to add predictions it appears Red has already included this in documentation.
comment redbot.core.utils.predicates
set junior_member = get roles name=string eh Junior Member
set volunteers = get roles name=string Volunteer App
set channel = get text_channels name=stri... | async def appsetup(self, ctx: commands.Context):
# Need to add predictions it appears Red has already included this in documentation.
#redbot.core.utils.predicates
junior_member = get(
ctx.guild.roles, name='eh Junior Member'
)
volunteers = get(
ctx.guild.roles, name=... | Python | nomic_cornstack_python_v1 |
function get_cell_arguments self data default=none
begin
set active = true
set onchange = none
set readonly = false
set value = string
if default is not none
begin
update data default
end
if string active in data
begin
set active = data at string active
end
if string readonly in data
begin
set readonly = data at strin... | def get_cell_arguments(self, data, default=None):
active = True
onchange = None
readonly = False
value = ""
if default is not None:
data.update(default)
if "active" in data:
active = data["active"]
if "readonly" in data:
readonl... | Python | nomic_cornstack_python_v1 |
import ConfigReader
import random
import math
class Actor
begin
function __init__ self config
begin
set eligibility_decay_rate = actor_eligibility_decay_rate
set discount_factor = actor_discount_factor
set learning_rate = actor_learning_rate
set epsilon = initial_epsilon
set config = config
set state_value_map = dict
... | import ConfigReader
import random
import math
class Actor:
def __init__(self, config: ConfigReader):
self.eligibility_decay_rate = config.actor_eligibility_decay_rate
self.discount_factor = config.actor_discount_factor
self.learning_rate = config.actor_learning_rate
self.epsilon = config.initial_epsi... | Python | zaydzuhri_stack_edu_python |
function length self
begin
return length
end function | def length(self):
return pyvista.Box(self.bounds).length | Python | nomic_cornstack_python_v1 |
comment Construct the dataset
from data_load import FacialKeypointsDataset , Rescale , RandomCrop , Normalize , ToTensor
import matplotlib.pyplot as plt
import numpy as np
import torch
import matplotlib.image as mpimg
from torchvision import transforms
comment from visualize import show_keypoints
function show_keypoint... | # Construct the dataset
from data_load import FacialKeypointsDataset, Rescale, RandomCrop, Normalize, ToTensor
import matplotlib.pyplot as plt
import numpy as np
import torch
import matplotlib.image as mpimg
from torchvision import transforms
#from visualize import show_keypoints
def show_keypoints(image, key_p... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
function triple x
begin
return x * 3
end function
function square x
begin
return x ^ 2
end function
function main
begin
for i in range 1 11
begin
set tripleValue = call triple i
set squareValue = call square i
if squareValue > tripleValue
begin
break
end
else
begin
print string triple( { i... | #!/usr/bin/env python3
def triple(x):
return x*3
def square(x):
return x**2
def main():
for i in range(1, 11):
tripleValue = triple(i)
squareValue = square(i)
if (squareValue > tripleValue):
break
else:
print(f"triple({i})=={tripleValue} square({i}... | Python | zaydzuhri_stack_edu_python |
comment https://leetcode.com/problems/random-pick-index
comment https://leetcode.com/problems/random-pick-index/discuss/597400/Python-O(1)-and-Sampling
from collections import defaultdict
from typing import List
import random
comment runtime; 440ms, 8.04%
comment memory; 23.6MB, 33.33%
class Solution
begin
function __i... | # https://leetcode.com/problems/random-pick-index
# https://leetcode.com/problems/random-pick-index/discuss/597400/Python-O(1)-and-Sampling
from collections import defaultdict
from typing import List
import random
# runtime; 440ms, 8.04%
# memory; 23.6MB, 33.33%
class Solution:
def __init__(self, nums... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
class Solution
begin
function canConstruct self ransomNote magazine
begin
set ransom_note_map = default dictionary int
for char in ransomNote
begin
set ransom_note_map at char = ransom_note_map at char + 1
end
for char in magazine
begin
if char in ransom_note_map and ransom_note_map ... | from collections import defaultdict
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ransom_note_map = defaultdict(int)
for char in ransomNote:
ransom_note_map[char] += 1
for char in magazine:
if char in ransom_note_map and ran... | Python | zaydzuhri_stack_edu_python |
import sys
from random import randrange
print string Ahoj, vitej ve hre oko bere.
set hodnota = 0
while hodnota < 21
begin
print string Tvuj soucet bodu je: hodnota
set odpoved = input string Chces otocit kartu?
if odpoved == string ano
begin
set karta = call randrange 2 11
print string Tvoje hodnota je: karta
set hodn... | import sys
from random import randrange
print("Ahoj, vitej ve hre oko bere.")
hodnota = 0
while hodnota < 21:
print("Tvuj soucet bodu je:",hodnota)
odpoved = input("Chces otocit kartu?")
if odpoved == "ano":
karta = randrange(2, 11)
print("Tvoje hodnota je:", karta)
hodnota = hodnot... | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
set c = call Client
set response = get c string /
set content = content
end function | def setUp(self):
c = Client()
self.response = c.get('/')
self.content = self.response.content | Python | nomic_cornstack_python_v1 |
function start_pressing self
begin
if is_running == false and are_user_values_correct == true
begin
set is_running = true
set t = thread target=press_the_key
start t
set label_state at string text = string ON
set label_state at string fg = string red
set button_start at string state = string disabled
set spinbox_delay ... | def start_pressing(self):
if self.is_running == False and self.are_user_values_correct == True:
self.is_running = True
self.t = threading.Thread(target = self.press_the_key)
self.t.start()
self.label_state['text'] = 'ON'
self.label_state['fg'] = 'red'... | Python | nomic_cornstack_python_v1 |
function set_absolute_position self position
begin
set cmd_position = reference_position + position
if delayed_execution is true
begin
put tuple cmd_position true
set ready = true
end
else
begin
if running
begin
comment Driver is already moving, return False
comment so the parser can return a byte_nak
return false
end
... | def set_absolute_position(self, position):
cmd_position = self.reference_position + position
if self.delayed_execution is True:
self.position_queue.put((cmd_position, True))
self.ready = True
else:
if self.running:
# Driver is already moving, r... | Python | nomic_cornstack_python_v1 |
string Example usage: >>> json_loads_byteified('{"Hello": "World"}') {'Hello': 'World'} >>> json_loads_byteified('"I am a top-level string"') 'I am a top-level string' >>> json_loads_byteified('7') 7 >>> json_loads_byteified('["I am inside a list"]') ['I am inside a list'] >>> json_loads_byteified('[[[[[[[["I am inside... | """
Example usage:
>>> json_loads_byteified('{"Hello": "World"}')
{'Hello': 'World'}
>>> json_loads_byteified('"I am a top-level string"')
'I am a top-level string'
>>> json_loads_byteified('7')
7
>>> json_loads_byteified('["I am inside a list"]')
['I am inside a list']
>>> json_loads_byteified('[[[[[[[["I am inside a... | Python | zaydzuhri_stack_edu_python |
comment Write a program that prompts the user to enter an integer for
comment today’s day of the week (Sunday is 0, Monday is 1, ..., and Saturday is 6). Also
comment prompt the user to enter the number of days after today for a future day and display the future day of the week.
set today = eval input string Enter toda... | #Write a program that prompts the user to enter an integer for
#today’s day of the week (Sunday is 0, Monday is 1, ..., and Saturday is 6). Also
#prompt the user to enter the number of days after today for a future day and display the future day of the week.
today = eval(input("Enter today day (0-6 with 0 Being Su... | Python | zaydzuhri_stack_edu_python |
function get_input_from_file self file
begin
set cls = __class__
set input_objs = dictionary comprehension attr : get call with_input input_arguments file for attr in input
return input_objs
end function | def get_input_from_file(self, file):
cls = self.__class__
input_objs = {
attr: getattr(cls, attr).with_input(self.input_arguments).get(file)
for attr in cls.input()
}
return input_objs | Python | nomic_cornstack_python_v1 |
comment Fixed my error with the graph element https://kobkrit.com/tensor-something-is-not-an-element-of-this-graph-error-in-keras-on-flask-web-server-4173a8fe15e1
import keras as kr
comment import flask
comment import render template which will display the HTML in the browser
comment import request will contain all the... | # Fixed my error with the graph element https://kobkrit.com/tensor-something-is-not-an-element-of-this-graph-error-in-keras-on-flask-web-server-4173a8fe15e1
import keras as kr
# import flask
# import render template which will display the HTML in the browser
# import request will contain all the data that is sent from ... | Python | zaydzuhri_stack_edu_python |
comment Bibliotek for å utføre tråding
import threading
comment Sleep funksjonen tilgjengelig
import time
comment Bibliotek for UDP/TCP_IP
import socket
comment Bibliotek for seriell kommunikasjon
import serial
comment Bibliotek for bruk av I2C i Python
import smbus
comment Bibliotek for numpy matriser
import numpy as ... | import threading # Bibliotek for å utføre tråding
import time # Sleep funksjonen tilgjengelig
import socket # Bibliotek for UDP/TCP_IP
import serial # Bibliotek for seriell kommunikasjon
import smbus # Bibliotek for bruk av I2C i Python
import numpy as np # Bibliotek for numpy matriser
import RPi.GPIO as GPIO # Klargjø... | Python | zaydzuhri_stack_edu_python |
function get_scaling_model
begin
return call from_data call generated_params list list
end function | def get_scaling_model():
return KBScalingModel.from_data(generated_params(), [], []) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
from flask import Flask
call setmode BOARD
call setwarnings false
setup GPIO 38 OUT
setup GPIO 40 IN
comment -----------------------
comment Trig => 38
comment Echo => 40
function Ultrasonic
begin
call output 38 HIGH
sleep 0.0015
call output 38 LOW
set t... | # -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
from flask import Flask
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(38,GPIO.OUT)
GPIO.setup(40,GPIO.IN)
#-----------------------
#Trig => 38
#Echo => 40
def Ultrasonic():
GPIO.output(38,GPIO.HIGH)
time.sleep(0.0015)
GPIO.output(... | Python | zaydzuhri_stack_edu_python |
import itertools
import pprint
import sys
import time
from math import log
import nltk
import string
import numpy
from sklearn.feature_extraction.text import TfidfVectorizer , _document_frequency
from project_ex2 import getDataFromDir , calcMetrics , merge , mergeDict
call set_printoptions threshold=maxsize
function fi... | import itertools
import pprint
import sys
import time
from math import log
import nltk
import string
import numpy
from sklearn.feature_extraction.text import TfidfVectorizer, _document_frequency
from project_ex2 import getDataFromDir, calcMetrics, merge, mergeDict
numpy.set_printoptions(threshold=sys.maxsize)
de... | Python | zaydzuhri_stack_edu_python |
function add_chat
begin
set form = call ChatRoomForm form
if method == string POST and call validate
begin
set title = data
set participants = data
set participant_list = split participants string ,
set participant_list at slice : : = list comprehension replace p string string for p in participant_list
comment user... | def add_chat():
form = ChatRoomForm(request.form)
if request.method == 'POST' and form.validate():
title = form.title.data
participants = form.participants.data
participant_list = participants.split(",")
participant_list[:] = [p.replace(' ', '') for p in participant_list]
... | Python | nomic_cornstack_python_v1 |
string 一个类可以是另一个类的属性 枪是士兵的一个属性
class Gun
begin
string 枪
function __init__ self model bullet_count=10
begin
string :param model: 枪型号 :param bullet_count: 子弹数,默认为10
set model = model
comment 子弹数量
set bullet_count = bullet_count
end function
function add_bullet self bullet_num
begin
string 添加子弹 :param bullet_num:子弹数
set b... | """
一个类可以是另一个类的属性
枪是士兵的一个属性
"""
class Gun:
"""
枪
"""
def __init__(self, model, bullet_count=10):
"""
:param model: 枪型号
:param bullet_count: 子弹数,默认为10
"""
self.model = model
self.bullet_count = bullet_count # 子弹数量
def add_bullet(self, bullet_n... | Python | zaydzuhri_stack_edu_python |
string "
class Pair extends object
begin
function __init__ self fst snd
begin
call __init__
set fst = fst
set snd = snd
end function
end class
function foo bar
begin
pass
end function
set x = call Pair 1 2
set xDict = variables x
set xDict at string trd = 3
print trd | """"
"""
class Pair(object):
def __init__(self, fst, snd) -> None:
super().__init__()
self.fst = fst
self.snd = snd
def foo(bar):
pass
x = Pair(1,2)
xDict = vars(x)
xDict["trd"] = 3
print(x.trd)
| Python | zaydzuhri_stack_edu_python |
function generate_freq_report text
begin
comment to store the word frequencies
set words = dict
set text = lower text
set text = replace text string string
set text = split text string
for word in text
begin
if word in words
begin
set words at word = words at word + 1
end
else
begin
set words at word = 1
end
end
retu... | def generate_freq_report(text):
words = {} # to store the word frequencies
text = text.lower()
text = text.replace('\n', ' ')
text = text.split(' ')
for word in text:
if word in words:
words[word] += 1
else:
words[word] = 1
return words | Python | jtatman_500k |
class Soap
begin
function __init__ self name ingredients
begin
set name = name
set ingredients = ingredients
end function
function check_ingredient self ingredient_name
begin
for ingredient in ingredients
begin
if lower ingredient at string name == lower ingredient_name
begin
return tuple ingredient at string name ingr... | class Soap:
def __init__(self, name, ingredients):
self.name = name
self.ingredients = ingredients
def check_ingredient(self, ingredient_name):
for ingredient in self.ingredients:
if ingredient['name'].lower() == ingredient_name.lower():
return (i... | Python | jtatman_500k |
function _neighbours_have_different_color self vertice_name vertice_color child
begin
for neighbour in call _get_neighbours vertice_name
begin
if neighbour in child and vertice_color == child at neighbour
begin
return false
end
end
return true
end function | def _neighbours_have_different_color(self, vertice_name, vertice_color, child):
for neighbour in self.graph._get_neighbours(vertice_name):
if neighbour in child and vertice_color == child[neighbour]:
return False
return True | Python | nomic_cornstack_python_v1 |
function putvarboundslice self first_ last_ bkx_ blx_ bux_
begin
set _bkx_minlength = last_ - first_
if last_ - first_ > 0 and bkx_ is not none and length bkx_ != last_ - first_
begin
raise call ValueError string Array argument bkx is not long enough: Is %d, expected %d % tuple length bkx_ last_ - first_
end
if bkx_ is... | def putvarboundslice(self,first_,last_,bkx_,blx_,bux_):
_bkx_minlength = ((last_) - (first_))
if ((last_) - (first_)) > 0 and bkx_ is not None and len(bkx_) != ((last_) - (first_)):
raise ValueError("Array argument bkx is not long enough: Is %d, expected %d" % (len(bkx_),((last_) - (first_))))
if bkx_... | Python | nomic_cornstack_python_v1 |
function accordian list_1
begin
set list_2 = list
for i in range length list_1 - 1
begin
set diff = absolute list_1 at i - list_1 at i + 1
append list_2 diff
end
print list_2
comment increase_decrease(list_2)
comment def increase_decrease(list_2):
comment valid =True
comment for i in range(len(list_2)-1):
comment if l... | def accordian(list_1):
list_2 = []
for i in range(len(list_1)-1):
diff = abs(list_1[i] - list_1[i+1])
list_2.append(diff)
print(list_2)
# increase_decrease(list_2)
# def increase_decrease(list_2):
# valid =True
# for i in range(len(list_2)-1):
# if list_2[i] < list_2[i+1... | Python | zaydzuhri_stack_edu_python |
import unittest
from game import stack , Board
class GameSetupTests extends TestCase
begin
function test_start self
begin
set board = call Board
assert true length stacks 12
end function
end class
class StackingTests extends TestCase
begin
function setUp self
begin
set board = call Board
end function
function test_stac... | import unittest
from game import stack, Board
class GameSetupTests(unittest.TestCase):
def test_start(self):
board = Board()
self.assertTrue(len(board.stacks), 12)
class StackingTests(unittest.TestCase):
def setUp(self):
self.board = Board()
def test_stack_one_red_on_one_blue(... | Python | zaydzuhri_stack_edu_python |
function pod self
begin
return table at tuple 0 0 / table at tuple 0 0 + table at tuple 1 0
end function | def pod(self):
return self.table[0, 0] / (self.table[0, 0] + self.table[1, 0]) | Python | nomic_cornstack_python_v1 |
function info msg
begin
write stdout string %s[ INFO ]%s %s % tuple GREEN RESET msg
end function | def info(msg):
sys.stdout.write('%s[ INFO ]%s %s\n' % (colors.GREEN, colors.RESET , msg)) | Python | nomic_cornstack_python_v1 |
function _read_from_socket self
begin
string Read data from the socket. :rtype: bytes
if not use_ssl
begin
if not socket
begin
raise error string connection/socket error
end
return call recv MAX_FRAME_SIZE
end
with _rd_lock
begin
if not socket
begin
raise error string connection/socket error
end
return read socket MAX_... | def _read_from_socket(self):
"""Read data from the socket.
:rtype: bytes
"""
if not self.use_ssl:
if not self.socket:
raise socket.error('connection/socket error')
return self.socket.recv(MAX_FRAME_SIZE)
with self._rd_lock:
if... | Python | jtatman_500k |
class Node
begin
function __init__ self data
begin
set data = data
set prev = none
set next = none
end function
end class
class DoublyLinkedList
begin
function __init__ self
begin
set head = none
set tail = none
end function
function insert_at_beginning self data
begin
set new_node = call Node data
if head is none
begi... | class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_at_beginning(self, data):
new_node = Node(data)
if self.head is None:
... | Python | jtatman_500k |
function _ls_solver A B warm_start=none
begin
comment TODO - do conjugate gradient if n is too large
return T
end function | def _ls_solver(A, B, warm_start=None):
# TODO - do conjugate gradient if n is too large
return np.linalg.lstsq(A.T, B.T)[0].T | Python | nomic_cornstack_python_v1 |
import twint
function twintfunc ticker dates=list
begin
set tweet_dict = dict
for i in range length dates - 2
begin
comment Configure
set c = call Config
set Limit = 20
set Popular_tweets = true
set Store_object = true
set Hide_output = true
set Search = string $ + ticker
set Since = dates at i
set Until = dates at i ... | import twint
def twintfunc(ticker, dates=[]):
tweet_dict = {}
for i in range(len(dates) - 2):
# Configure
c = twint.Config()
c.Limit = 20
c.Popular_tweets = True
c.Store_object = True
c.Hide_output = True
c.Search = "$" + ticker
c.Since = dates[... | Python | zaydzuhri_stack_edu_python |
comment Coded By: Evan Kanter - University of Toronto Schools
comment CCC 2017 Problem #1 - Quadrant Selection
set x = integer input
set y = integer input
if x > 0 and y > 0
begin
print 1
end
if x < 0 < y
begin
print 2
end
if x < 0 and y < 0
begin
print 3
end
if x > 0 > y
begin
print 4
end | # Coded By: Evan Kanter - University of Toronto Schools
# CCC 2017 Problem #1 - Quadrant Selection
x=int(input())
y=int(input())
if x>0 and y>0:
print(1)
if x < 0 < y:
print(2)
if x<0 and y<0:
print(3)
if x > 0 > y:
print (4)
| Python | zaydzuhri_stack_edu_python |
import random
set target = tuple 100 62.137
set ratio = random
set alpha = 1e-05
for i in range 100
begin
set tuple x y = tuple target at 0 target at 1
print ratio
set derivative = 2 * ratio * x ^ 2 - 2 * x * y
set delta_ratio = - alpha * derivative
set ratio = ratio + delta_ratio
end | import random
target = (100, 62.137)
ratio = random.random()
alpha = 0.00001
for i in range(100):
x, y = target[0], target[1]
print(ratio)
derivative = 2 * ratio * x ** 2 - 2 * x * y
delta_ratio = - alpha * derivative
ratio = ratio + delta_ratio
| Python | zaydzuhri_stack_edu_python |
function main
begin
comment Controlling the loop
set another = string y
comment Opening the coffee.txt in append mode
set coffee_file = open string coffee.txt string a
comment Add records to the file
while another == string y or another == string Y
begin
comment Get the coffee record data
print string Enter the followi... | def main():
# Controlling the loop
another = 'y'
# Opening the coffee.txt in append mode
coffee_file = open('coffee.txt', 'a')
# Add records to the file
while another == 'y' or another == 'Y':
# Get the coffee record data
print('Enter the following coffee data: ')
descr... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
class SimplePublisher
begin
function __init__ self
begin
call init_node string circles_node
call on_shutdown on_shutdown
call loginfo string circles_node has been started
set pub = call Publisher string /cmd_vel Twist queue_size=10
set rate =... | #!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
class SimplePublisher:
def __init__(self):
rospy.init_node('circles_node')
rospy.on_shutdown(self.on_shutdown)
rospy.loginfo('circles_node has been started')
self.pub = rospy.Publisher("/cmd_vel", Twist, queue_... | Python | zaydzuhri_stack_edu_python |
function __init__ self db
begin
set db = db
try
begin
set client = call StrictRedis connection_pool=blocking_pool
set pipe = pipeline transaction=false
end
except ConnectionError as e
begin
error format string Could not connect to Redis server. {} e
raise call SpatialDBError format string Could not connect to Redis ser... | def __init__(self, db):
self.db = db
try:
self.client = redis.StrictRedis(connection_pool=RedisPool.blocking_pool)
self.pipe = self.client.pipeline(transaction=False)
except redis.ConnectionError as e:
logger.error("Could not connect to Redis server. {}".format(e))
raise Spatial... | Python | nomic_cornstack_python_v1 |
for i in range 0 n
begin
set ele = integer input string enter elements:
append lst ele
end
print string input list1= lst
set lst1 = list
for j in lst
begin
if j > 0
begin
append lst1 j
end
end
print string output list2= lst1 | for i in range(0,n):
ele = int(input("enter elements: "))
lst.append(ele)
print("input list1=" ,lst)
lst1=[]
for j in lst:
if j>0:
lst1.append(j)
print("output list2=" ,lst1)
| Python | zaydzuhri_stack_edu_python |
function is_perfect n
begin
set sum = 0
for i in range 1 n
begin
if n % i == 0
begin
set sum = sum + i
end
end
return sum == n
end function | def is_perfect(n):
sum = 0
for i in range(1, n):
if (n % i == 0):
sum += i
return sum == n
| Python | flytech_python_25k |
function GetObjectMetadata self bucket_name object_name generation=none provider=none fields=none
begin
set projection = full
if generation
begin
set generation = call long generation
end
set apitools_request = call StorageObjectsGetRequest bucket=bucket_name object=object_name projection=projection generation=generati... | def GetObjectMetadata(self, bucket_name, object_name, generation=None,
provider=None, fields=None):
projection = (apitools_messages.StorageObjectsGetRequest
.ProjectionValueValuesEnum.full)
if generation:
generation = long(generation)
apitools_request = apit... | Python | nomic_cornstack_python_v1 |
comment 键值对形式出现
comment 键是不能重复的,而值是可以重复的
comment 键key是不可变得,也就无法修改,而值是可以变可以修改的,可以是任何对象
set NASDAQ_code = dict string BIDU string Baidu ; string SINA string Sina ; string YOKU string Youku
print NASDAQ_code at string SINA
comment add
set NASDAQ_code at string TEST = string test
print NASDAQ_code
update NASDAQ_code dict s... | # 键值对形式出现
# 键是不能重复的,而值是可以重复的
# 键key是不可变得,也就无法修改,而值是可以变可以修改的,可以是任何对象
NASDAQ_code = {
'BIDU':'Baidu',
'SINA':'Sina',
'YOKU':'Youku'
}
print(NASDAQ_code['SINA'])
# add
NASDAQ_code['TEST'] = 'test';
print(NASDAQ_code)
NASDAQ_code.update({'FB':'Facebook','TSLA':'Tetla'})
print(NASDAQ_code)
del NASDAQ_code['FB']
print(NASDAQ... | Python | zaydzuhri_stack_edu_python |
comment --- Part Two ---
comment Of course, that would be the message - if you hadn't agreed to use a modified repetition code instead.
comment In this modified code, the sender instead transmits what looks like random data, but for each character,
comment the character they actually want to send is slightly less likel... | # --- Part Two ---
# Of course, that would be the message - if you hadn't agreed to use a modified repetition code instead.
#
# In this modified code, the sender instead transmits what looks like random data, but for each character,
# the character they actually want to send is slightly less likely than the others. Eve... | Python | zaydzuhri_stack_edu_python |
from game_methods import *
from text_parser import *
from scroll_print import *
function main
begin
comment Run the starting menu of the game and start, load, or exit the game
set starting_selection = call starting_menu
if starting_selection == string start
begin
comment need to add Ranger and Wizard class to initializ... | from game_methods import *
from text_parser import *
from scroll_print import *
def main():
# Run the starting menu of the game and start, load, or exit the game
starting_selection = starting_menu()
if starting_selection == "start":
# need to add Ranger and Wizard class to initialize
... | Python | zaydzuhri_stack_edu_python |
comment !usr/bin/python
comment author noiz
import os
import sys
import time
set w = string [90;1m
set m = string [91;1m
set h = string [92;1m
set k = string [93;1m
set b = string [94;1m
set p = string [95;1m
set a = string [96;1m
set s = string [97;1m
function noiz x
begin
set w = dict string w 90 ; string m 3... | #!usr/bin/python
#author noiz
import os
import sys
import time
w = "\033[90;1m"
m = "\033[91;1m"
h = "\033[92;1m"
k = "\033[93;1m"
b = "\033[94;1m"
p = "\033[95;1m"
a = "\033[96;1m"
s = "\033[97;1m"
def noiz(x):
w = {'w':90, 'm':31, 'h':32, 'k':33, 'b':34, 'p':35, 'a':96, 's':97}
for i in w:
... | Python | zaydzuhri_stack_edu_python |
function training model train_loader optimizer device writer epoch iterator
begin
train model
set running_loss = 0.0
set numBatches = length train_loader
set final = false
set start = true
comment define start time
set start_time = time
comment For each batch
for tuple i data in enumerate train_loader 0
begin
set data ... | def training(model, train_loader, optimizer, device, writer, epoch, iterator):
model.train()
running_loss = 0.0
numBatches = len(train_loader)
final = False
start = True
# define start time
start_time = time.time()
# For each batch
for i, data in enumerate(train_loader... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment _*_coding:utf-8_*_
comment __author__:FLS
comment 1.xml 格式
comment xml 转为字典或者字典转为xml
comment import dicttoxml
comment from xml.dom.minidom import parseString
comment import os
comment d=[20,'name',
comment {'name':'bill','age':20,'salary':2000},
comment {'name':'fls','age':30,'sala... | # !/usr/bin/env python3
# _*_coding:utf-8_*_
# __author__:FLS
# 1.xml 格式
# xml 转为字典或者字典转为xml
#
# import dicttoxml
# from xml.dom.minidom import parseString
# import os
#
# d=[20,'name',
# {'name':'bill','age':20,'salary':2000},
# {'name':'fls','age':30,'salary':3000},
# {'name':'john','age':40,'salary':400... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
set a = list 1 2 3
set b = list string a string b string c
for tuple i j in zip b a
begin
print format string {0} is {1} i j
end | #!/usr/bin/env python3
a = [1, 2, 3]
b = ["a", "b", "c"]
for i, j in zip(b, a):
print("{0} is {1}".format(i, j)) | Python | zaydzuhri_stack_edu_python |
from prettytable import PrettyTable
set t = call PrettyTable list string Name string Age
call add_row list string Alice 24
call add_row list string Bob 19
print t
set x = call PrettyTable list string City name string Area string Population string Annual Rainfall
set sortby = string Population
set reversesort = true
set... | from prettytable import PrettyTable
t = PrettyTable(['Name', 'Age'])
t.add_row(['Alice', 24])
t.add_row(['Bob', 19])
print(t)
x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
x.sortby = "Population"
x.reversesort = True
x.int_format["Area"] = "04d"
x.float_format = "6.1f"
x.align["City name"] = "... | Python | zaydzuhri_stack_edu_python |
for words in ans
begin
comment 리스트 안의 요소들을 문자열로 한꺼번에 출력해주는 '*'
print *words
end | for words in ans:
#리스트 안의 요소들을 문자열로 한꺼번에 출력해주는 '*'
print(*words) | Python | zaydzuhri_stack_edu_python |
import datetime
comment Private Functions ##
function get_format_from_raw raw cursor
begin
set result = list comprehension dictionary line for line in list comprehension zip list comprehension column at 0 for column in description row for row in raw at 0
return result
end function
function get_format_from_raw_full raw ... | import datetime
#######################
## Private Functions ##
#######################
def get_format_from_raw(raw, cursor):
result = [dict(line) for line in [zip([column[0] for column in cursor.description], row) for row in raw]][0]
return result
def get_format_from_raw_full(raw, cursor):
resul... | Python | zaydzuhri_stack_edu_python |
function find_classes cls cutoff_class=none
begin
set cutoff_class = cutoff_class or Interface
set module = modules at __name__
for tuple ni vi in get members module isclass
begin
if is subclass vi cutoff_class and vi is not cutoff_class
begin
yield vi
end
end
end function | def find_classes(cls, cutoff_class=None):
cutoff_class = cutoff_class or Interface
module = sys.modules[__name__]
for ni, vi in inspect.getmembers(module, inspect.isclass):
if issubclass(vi, cutoff_class) and vi is not cutoff_class:
yield vi | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment coding:utf-8
comment https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/32/trees-and-graphs/85/
comment 中序遍历二叉树
comment 给定一个二叉树,返回它的中序 遍历。
comment 示例:
comment 输入: [1,null,2,3]
comment 1
comment \
comment 2
comment /
comment 3
comment 输出: [1,3,2]
comment 进阶: 递归... | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/32/trees-and-graphs/85/
# 中序遍历二叉树
# 给定一个二叉树,返回它的中序 遍历。
# 示例:
# 输入: [1,null,2,3]
# 1
# \
# 2
# /
# 3
# 输出: [1,3,2]
# 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
# https://blog.csdn.net/qq_17550379/article/... | Python | zaydzuhri_stack_edu_python |
comment Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
comment This program is free software; you can redistribute it and/or
comment modify it under the terms of the GNU General Public License as
comment published by the Free Software Foundation; version 2 of the
comment License.
comment This pr... | # Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; version 2 of the
# License.
#
# This program is distributed in t... | Python | zaydzuhri_stack_edu_python |
from geopy.geocoders import Nominatim
set geolocator = call Nominatim
set location = reverse geolocator string 40.75011063,-73.99389648
print address | from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.reverse("40.75011063,-73.99389648")
print(location.address) | Python | zaydzuhri_stack_edu_python |
import estudio01 as es
class Descifrador
begin
function __init__ self nombre
begin
set nombre = nombre
set suma = 0
with open nombre string r as archivo
begin
set lineas = read lines archivo
set codigo = string
set texto = replace join string lineas string string
set i = 0
end
end function
function lectura_archivo s... | import estudio01 as es
class Descifrador:
def __init__(self, nombre):
self.nombre = nombre
self.suma=0
with open(self.nombre, "r") as self.archivo:
lineas = self.archivo.readlines()
self.codigo = ''
self.texto = "".join(lineas).replace('\n', '')
... | Python | zaydzuhri_stack_edu_python |
import shutil
import os
import re
import sys
from tkinter import *
from tkinter import filedialog
set window = call Tk
title window string File Organization
function find_file_directory data_path stringendswith
begin
set file_directory = list
for tuple root dirs files in walk data_path
begin
for file in files
begin
if... | import shutil
import os
import re
import sys
from tkinter import *
from tkinter import filedialog
window = Tk()
window.title('File Organization')
def find_file_directory(data_path, stringendswith):
file_directory = []
for root, dirs, files in os.walk(data_path):
for file in files:
if file... | Python | zaydzuhri_stack_edu_python |
function loadConverters self
begin
set dir = string share/addons/codeGeneration/converters
set converters = list comprehension f for f in list directory dir if is file join dir f
set converterList = call get_model
clear converterList
set diagramName = lower name
set id = 0
set __converterRoots = list
for converter in ... | def loadConverters(self):
dir = "share/addons/codeGeneration/converters"
converters = [ f for f in listdir(dir) if isfile(join(dir,f)) ]
converterList = self.__gtkBuilder.get_object("converters").get_model()
converterList.clear()
diagramName = self.__i.current_diagram.type.n... | Python | nomic_cornstack_python_v1 |
from multiprocessing import Process
class Worker extends Process
begin
function __init__ self dp_state
begin
call __init__
set dp_state = dp_state
end function
function run self
begin
set state = dp_state
set task = call get_task
while task is not none
begin
set pid = pid
call add_running_task pid task
print string Tas... | from multiprocessing import Process
class Worker(Process):
def __init__(self, dp_state):
super().__init__()
self.dp_state = dp_state
def run(self):
state = self.dp_state
task = state.get_task()
while task is not None:
task.pid = self.pid
stat... | Python | zaydzuhri_stack_edu_python |
function hit self
begin
call deal string player
if value > 21
begin
call post_hand call serialize - 1
set hand_ongoing = false
set profit = - hand_pot / 2
set hand_pot = 0
set hand_done_msg = string Bust
call display bet_str player_bal hand_pot
end
if hand_ongoing == false
begin
run _window
end
else
if value == 21
begi... | def hit(self):
self.deal('player')
if self.player_hand.value > 21:
post_hand(self.serialize(-1))
self.hand_ongoing = False
profit = -self.hand_pot / 2
self.hand_pot = 0
hand_done_msg = 'Bust'
self._view.display(self.bet_str, self.pl... | Python | nomic_cornstack_python_v1 |
function add_embeddings self
begin
with device string /cpu:0
begin
with call variable_scope string Embedding_Layer
begin
set embeddings = call Variable initial_embeddings name=string Embeddings
comment (N,S,D)
set input_embeddings = call embedding_lookup embeddings inputs_placeholder
comment (N,S,D)
set question_embedd... | def add_embeddings(self):
with tf.device('/cpu:0'):
with tf.variable_scope('Embedding_Layer'):
embeddings = tf.Variable(self.initial_embeddings,name = 'Embeddings')
self.input_embeddings = tf.nn.embedding_lookup(embeddings, self.inputs_placeholder) #(N,S,D)
... | Python | nomic_cornstack_python_v1 |
function get_rated_map self
begin
if not _rated_map
begin
set _rated_map = call rate_game_map _game_map _start_bot_position get _game_map at _start_bot_position string orientation
end
return _rated_map
end function | def get_rated_map(self):
if not self._rated_map:
self._rated_map = self.rate_game_map(
self._game_map,
self._start_bot_position,
self._game_map[self._start_bot_position].get('orientation')
)
return self._rated_map | Python | nomic_cornstack_python_v1 |
function _decode_image self row_image
begin
set length = integer image_size ^ 2
set red = reshape row_image at slice : length : 32 32
set green = reshape row_image at slice length : length * 2 : 32 32
set blue = reshape row_image at slice length * 2 : : 32 32
return stack list red green blue axis=2
end function | def _decode_image(self, row_image):
length = int(self.image_size ** 2)
red = row_image[:length].reshape(32, 32)
green = row_image[length:length * 2].reshape(32, 32)
blue = row_image[length * 2:].reshape(32, 32)
return np.stack([red, green, blue], axis=2) | Python | nomic_cornstack_python_v1 |
function sortBinaryArray arr n
begin
sort arr
return arr
end function
set arr = list 1 1 0 0 0 1 1 1 0 1
set n = length arr
call sortBinaryArray arr n
for i in range n
begin
print arr at i end=string
end | def sortBinaryArray(arr,n):
arr.sort()
return arr
arr = [1,1,0,0,0,1,1,1,0,1]
n = len(arr)
sortBinaryArray(arr,n)
for i in range(n):
print(arr[i],end=" ") | Python | zaydzuhri_stack_edu_python |
function test_GmailEmailMsg_should_raise_SMTPAuthenticationError
begin
set injector = call Injector
call bind string gmailAccount to=string do-not-reply@bitpostage.net
call bind string gmailPassword to=string this is another test password wrong
call register injector
set gmail = call GmailEmailMsg
set temp = call Gmail... | def test_GmailEmailMsg_should_raise_SMTPAuthenticationError():
injector = inject.Injector()
injector.bind( "gmailAccount", to="do-not-reply@bitpostage.net" )
injector.bind( "gmailPassword", to="this is another test password wrong" )
inject.register( injector )
gmail = GmailEmailMsg()
temp = GmailEmailTemplate()... | Python | nomic_cornstack_python_v1 |
function get_complex_representation points
begin
set len_n = length points
set y_s = array points dtype=complex_
set w_comp = call e_complex_pow 2 * pi / len_n
comment Fourier-Matrix
set f_matrix = array list comprehension list comprehension w_comp ^ j * k for j in range len_n for k in range - len_n - 1 // 2 len_n - 1 ... | def get_complex_representation(points: ArrayLike) -> np.ndarray:
len_n = len(points)
y_s = np.array(points, dtype=np.complex_)
w_comp = e_complex_pow(2 * np.pi / len_n)
# Fourier-Matrix
f_matrix = np.array(
[
[w_comp ** (j * k) for j in range(len_n)]
for k in range(... | Python | nomic_cornstack_python_v1 |
function kg2e_interaction h_mean h_var r_mean r_var t_mean t_var similarity=string KL exact=true
begin
return call h=call GaussianDistribution mean=h_mean diagonal_covariance=h_var r=call GaussianDistribution mean=r_mean diagonal_covariance=r_var t=call GaussianDistribution mean=t_mean diagonal_covariance=t_var exact=e... | def kg2e_interaction(
h_mean: torch.FloatTensor,
h_var: torch.FloatTensor,
r_mean: torch.FloatTensor,
r_var: torch.FloatTensor,
t_mean: torch.FloatTensor,
t_var: torch.FloatTensor,
similarity: str = "KL",
exact: bool = True,
) -> torch.FloatTensor:
return KG2E_SIMILARITIES[similarity... | Python | nomic_cornstack_python_v1 |
function _compute_gradient_ao_values self pos
begin
set tuple xyz r = call _process_position pos
set tuple R dR = call radial r bas_n bas_exp xyz=xyz derivative=list 0 1 sum_grad=false
set tuple Y dY = call harmonics xyz derivative=list 0 1 sum_grad=false
return call _gradient_kernel R dR Y dY
end function | def _compute_gradient_ao_values(self, pos):
xyz, r = self._process_position(pos)
R, dR = self.radial(r, self.bas_n,
self.bas_exp, xyz=xyz,
derivative=[0, 1],
sum_grad=False)
Y, dY = self.harmonics(xyz, derivati... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.