code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function add_grover_without_ancilla_1_0 qc register begin if length list register != 2 begin raise call ValueError string Need QuantumRegister with exactly 2 qubits, but got { length list register } instead. end comment Mix states initially call h register comment Repeat Grover iteration just once call _add_grover_step...
def add_grover_without_ancilla_1_0(qc: QuantumCircuit, register: QuantumRegister) -> None: if len(list(register)) != 2: raise ValueError(f"Need QuantumRegister with exactly 2 qubits, but got {len(list(register))} instead.") qc.h(register) # Mix states initially _add_grover_step_without_ancilla_1_0...
Python
nomic_cornstack_python_v1
function calculate_flour_per_pound begin comment Total flour (*3 bags of 8 cups each) comment 24 cups set total_flour = 3 * 8 comment Total pasta made with 1 additional rack needed means making 12 pounds set pounds_of_pasta = 12 comment Calculate cups of flour needed per pound of pasta set cups_per_pound = total_flour ...
def calculate_flour_per_pound(): # Total flour (*3 bags of 8 cups each) total_flour = 3 * 8 # 24 cups # Total pasta made with 1 additional rack needed means making 12 pounds pounds_of_pasta = 12 # Calculate cups of flour needed per pound of pasta cups_per_pound = total_flour / pounds_of_pasta...
Python
dbands_pythonMath
function plans request template=none begin try begin set plans = get requests TASK_ENGINE_URL + string /plans set plans = json set data = dict string plans plans at string plans end except any begin set data = dict string error string Error retrieving plans. Check the connection to the task engine. end return call rend...
def plans(request, template=None): try: plans = requests.get(settings.TASK_ENGINE_URL + '/plans') plans = plans.json data = {"plans":plans['plans']} except: data = {"error":"Error retrieving plans. Check the connection to the task engine."} return render(request, template, da...
Python
nomic_cornstack_python_v1
function is_dotted self begin return _dotted end function
def is_dotted(self) -> bool: return self._dotted
Python
nomic_cornstack_python_v1
string Foundations Problems from CodeWars. You might know some pretty large perfect squares. But what about the NEXT one? Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also a...
"""Foundations Problems from CodeWars. You might know some pretty large perfect squares. But what about the NEXT one? Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. Recall that an integral perfect square is an integer n such that sqrt(n) is also an ...
Python
zaydzuhri_stack_edu_python
import sys import pandas as pd import analyze_mosquito_data_lib as mosquito_lib set filename = argv at 1
import sys import pandas as pd import analyze_mosquito_data_lib as mosquito_lib filename = sys.argv[1]
Python
zaydzuhri_stack_edu_python
function letterCount word begin set word = lower word set letterCountDict = dict for l in word begin if l in letterCountDict begin set letterCountDict at l = letterCountDict at l + 1 end else begin set letterCountDict at l = 1 end end return letterCountDict end function print call letterCount word
def letterCount(word): word = word.lower() letterCountDict = {} for l in word: if(l in letterCountDict): letterCountDict[l] += 1 else: letterCountDict[l] = 1 return letterCountDict print(letterCount(word))
Python
zaydzuhri_stack_edu_python
comment !usr/bin/python set num1 = eval input string Enter 1st number: set num2 = eval input string Enter 2nd number: set num3 = eval input string Enter 3rd number: if num1 < num2 and num1 < num3 begin print num1 string is smallest among three end else if num2 < num3 begin print num2 string is smallest among three end ...
#!usr/bin/python num1 = eval(input("Enter 1st number:\n")) num2 = eval(input("Enter 2nd number:\n")) num3 = eval(input("Enter 3rd number:\n")) if(num1 < num2 and num1 < num3): print(num1 ,"is smallest among three\n") elif(num2 < num3): print(num2 ,"is smallest among three\n") else: print(num3, "is smalles...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Mar 28 16:16:31 2019 @author: siddh import string import os import nltk import pickle from collections import Counter class Vocabulary extends object begin string Simple vocabulary wrapper. function __init__ self begin set word2idx = dict set idx2word = dict set idx...
# -*- coding: utf-8 -*- """ Created on Thu Mar 28 16:16:31 2019 @author: siddh """ import string import os import nltk import pickle from collections import Counter class Vocabulary(object): """Simple vocabulary wrapper.""" def __init__(self): self.word2idx = {} self.idx2word = {} sel...
Python
zaydzuhri_stack_edu_python
function interpolate_bad im mask begin set tuple nrows ncols = shape for col in range ncols begin set last_good = 0 set have_good = false for row in range nrows begin if mask at tuple row col > 0 begin comment we hit a bad value if have_good begin comment we have a good value to continue set im at tuple row col = last_...
def interpolate_bad(im, mask): nrows,ncols = im.shape for col in range(ncols): last_good=0 have_good=False for row in range(nrows): if mask[row,col] > 0: # we hit a bad value if have_good: # we have a good value to continue...
Python
nomic_cornstack_python_v1
function std_deviation self begin return standard deviation np scores end function
def std_deviation(self): return np.std(self.scores)
Python
nomic_cornstack_python_v1
set number = integer input string Podaj liczbe: set divisors = list comprehension div for div in range 1 number + 1 if number % div == 0 print string Divisors of { number } : { divisors }
number = int(input("Podaj liczbe: ")) divisors = [div for div in range(1,number+1) if number % div == 0] print(f"Divisors of {number}: {divisors}")
Python
zaydzuhri_stack_edu_python
comment Memoization dictionary set memo = dict function factorial n begin comment Check for invalid inputs if not is instance n int or n < 0 begin raise call ValueError string Invalid input. Input must be a non-negative integer. end comment Base case if n == 0 or n == 1 begin return 1 end comment Check if the factoria...
# Memoization dictionary memo = {} def factorial(n): # Check for invalid inputs if not isinstance(n, int) or n < 0: raise ValueError("Invalid input. Input must be a non-negative integer.") # Base case if n == 0 or n == 1: return 1 # Check if the factorial is already calculated ...
Python
greatdarklord_python_dataset
function register_module_level_strings self begin set module = call get_module set ast_module = call get_ast for token in ast_module begin set typ = type if starts with string typ string Token.Literal.String begin set triple_quotes = tuple string """ string ''' if starts with text triple_quotes begin call _bookmark_lin...
def register_module_level_strings(self): module = self.get_module() ast_module = module.get_ast() for token in ast_module: typ = token.type if str(typ).startswith('Token.Literal.String'): triple_quotes = ('"""', "'''") if token.text.startsw...
Python
nomic_cornstack_python_v1
function import_imdb_multi_graph self weights begin from IMDb_data_preparation_E2V import MoviesGraph set weights_dict = dict string movies_edges weights at 0 ; string labels_edges weights at 1 set dict_paths = dict string cast string data_set/IMDb title_principals.csv ; string genre string data_set/IMDb movies.csv set...
def import_imdb_multi_graph(self, weights): from IMDb_data_preparation_E2V import MoviesGraph weights_dict = {'movies_edges': weights[0], 'labels_edges': weights[1]} dict_paths = {'cast': 'data_set/IMDb title_principals.csv', 'genre': 'data_set/IMDb movies.csv'} imdb = MoviesGraph(dict_p...
Python
nomic_cornstack_python_v1
function step_writer trajectory_out out_queue n_procs begin set write_counter = 0 while write_counter < n_procs begin comment time out in 30 minutes if nothing is written set msg = get out_queue comment start_time = time.time() if is instance msg str begin set write_counter = write_counter + 1 end else begin set atoms_...
def step_writer(trajectory_out, out_queue, n_procs): write_counter = 0 while write_counter < n_procs: msg = out_queue.get() # time out in 30 minutes if nothing is written # start_time = time.time() if isinstance(msg, str): writ...
Python
nomic_cornstack_python_v1
comment !/usr/python3 comment Nikki Benoit comment Aug 14 2019 15:57:22.5722 MST comment Encrypt using permutation cipher and then decrypt import string import numpy comment Get plaintext and key set plaintext = upper string Mary had a little lamb, its fleece as white as snow. Everywhere that Mary went, the lamb was su...
#!/usr/python3 # # Nikki Benoit # Aug 14 2019 15:57:22.5722 MST # ##################################### # Encrypt using permutation cipher and then decrypt ##################################### import string import numpy # Get plaintext and key plaintext = "Mary had a little lamb, its fleece as white as ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment 함수의 정의와 호출 function suhyun x begin set result = x * 2 return result end function print call suhyun 100
#-*- coding: utf-8 -*- # 함수의 정의와 호출 def suhyun(x): result = x * 2 return result print(suhyun(100))
Python
zaydzuhri_stack_edu_python
import boto3 import json function saveOrder begin set f = open string orders.json string a set sqs = call client string sqs set response = call receive_message QueueUrl=string https://sqs.us-east-1.amazonaws.com/292274580527/cc406_team3 comment If the response is empty, close the file and return if response == none beg...
import boto3 import json def saveOrder(): f = open("orders.json", 'a') sqs = boto3.client('sqs') response = sqs.receive_message( QueueUrl='https://sqs.us-east-1.amazonaws.com/292274580527/cc406_team3' ) # If the response is empty, close the file and return if response == None: ...
Python
zaydzuhri_stack_edu_python
function parameters self begin return get pulumi self string parameters end function
def parameters(self) -> Optional[Mapping[str, 'outputs.ParameterSpecificationResponse']]: return pulumi.get(self, "parameters")
Python
nomic_cornstack_python_v1
import boto3 function get_all_regions begin set client = call client string ec2 set regions = list comprehension region at string RegionName for region in call describe_regions at string Regions return regions end function function get_rds_instances region begin set client = call client string rds region_name=region se...
import boto3 def get_all_regions(): client = boto3.client('ec2') regions = [region['RegionName'] for region in client.describe_regions()['Regions']] return regions def get_rds_instances(region): client = boto3.client('rds',region_name=region) response = client.describe_db_instances() insta...
Python
zaydzuhri_stack_edu_python
function db cls begin return get attribute db __name__ end function
def db(cls): return getattr(db, cls.__name__)
Python
nomic_cornstack_python_v1
function amend_basket_quantity request order_id product_id increment new_value=none ajax=true begin set userprofile = call get_profile set order = call get_object_or_404 Order id=order_id set Product = call get_product_model set increment = integer increment set new_value = new_value and integer new_value set product =...
def amend_basket_quantity(request, order_id, product_id, increment, new_value=None, ajax=True): userprofile = request.user.get_profile() order = get_object_or_404(Order, id=order_id) Product = order.get_product_model() increment=int(increment) new_value = new_value and int(new_value) produc...
Python
nomic_cornstack_python_v1
function on_recv self callback begin raise call NotImplementedError string abstract method was called end function
def on_recv(self, callback): raise NotImplementedError("abstract method was called")
Python
nomic_cornstack_python_v1
comment funciones para cargar y manipular imagenes import Image comment funciones numericas (arrays, matrices, etc.) import numpy as np comment funciones para representacion grafica import matplotlib.pyplot as plt set img = open string ./img.png comment img.show()
import Image # funciones para cargar y manipular imagenes import numpy as np # funciones numericas (arrays, matrices, etc.) import matplotlib.pyplot as plt # funciones para representacion grafica img = Image.open("./img.png") # img.show()
Python
zaydzuhri_stack_edu_python
function test_default_cleaning_style currency_df begin set result = call currency_column_to_numeric string d_col set expected = call DataFrame dict string a_col list string 24.56 string - string (12.12) string 1,000,000 ; string d_col list nan nan 1.23 - 1000 call assert_frame_equal result expected end function
def test_default_cleaning_style(currency_df): result = currency_df.currency_column_to_numeric( "d_col", ) expected = pd.DataFrame( { "a_col": [" 24.56", "-", "(12.12)", "1,000,000"], "d_col": [np.nan, np.nan, 1.23, -1_000], } ) assert_frame_equal(resul...
Python
nomic_cornstack_python_v1
string Compute the short-time coherence function as proposed by Michaels. from packages import utkit , scihdf , utils import pandas as pd import numpy as np from scipy.signal import fftconvolve function compute_coherence s1 s2 width overlap begin comment align signal s1 with s2 set s1 = call s1 index set time_ = index ...
""" Compute the short-time coherence function as proposed by Michaels. """ from packages import utkit, scihdf, utils import pandas as pd import numpy as np from scipy.signal import fftconvolve def compute_coherence(s1, s2, width, overlap): # align signal s1 with s2 s1 = s1(s2.index) time_ = s1.index[0] ...
Python
zaydzuhri_stack_edu_python
function scale_transform x lower upper begin comment default value of center set offset = lower + upper * 0.5 comment return normalized tensor return 2 * x - offset / upper - lower end function
def scale_transform(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) -> torch.Tensor: # default value of center offset = (lower + upper) * 0.5 # return normalized tensor return 2 * (x - offset) / (upper - lower)
Python
nomic_cornstack_python_v1
import serial import serial.rs485 import time function openSerial sPort sBaudrate sParity sStopbits sBytesize sTimeout begin set ser = call Serial port=sPort baudrate=sBaudrate parity=sParity stopbits=sStopbits bytesize=sBytesize timeout=sTimeout return ser end function function closeSerial ser begin close ser end func...
import serial import serial.rs485 import time def openSerial(sPort, sBaudrate, sParity, sStopbits, sBytesize, sTimeout) : ser = serial.Serial( port = sPort, baudrate = sBaudrate, parity = sParity, stopbits = sStopbits, bytesize = sBytesize, timeout = sTimeout ) ...
Python
zaydzuhri_stack_edu_python
import heapq set listEx = list 8 5 2 9 5 6 3 comment Via min Heap function heapSort arr begin set temp = list while length arr > 0 begin call heapify arr append temp call heappop arr end return temp end function print call heapSort listEx
import heapq listEx = [8, 5, 2, 9, 5, 6,3] # Via min Heap def heapSort(arr): temp = [] while len(arr) > 0: heapq.heapify(arr) temp.append(heapq.heappop(arr)) return temp print(heapSort(listEx))
Python
zaydzuhri_stack_edu_python
function calculate_overlaps_masks self masks1 masks2 begin comment If either set of masks is empty return empty result if shape at 0 == 0 or shape at 0 == 0 begin return zeros tuple shape at 0 shape at - 1 end comment flatten masks and compute their areas set masks1 = as type reshape np masks1 > 0.5 tuple - 1 shape at ...
def calculate_overlaps_masks(self, masks1, masks2): # If either set of masks is empty return empty result if masks1.shape[0] == 0 or masks2.shape[0] == 0: return np.zeros((masks1.shape[0], masks2.shape[-1])) # flatten masks and compute their areas masks1 = np.reshape(masks1 > .5, (-1, ...
Python
nomic_cornstack_python_v1
function get_piece_centric_features self board begin set features = list set pieces = list string p1 string p2 string p3 string p4 string p5 string p6 string p7 string p8 string n1 string n2 string b1 string b2 string r1 string r2 string q string k string P1 string P2 string P3 string P4 string P5 string P6 string P7 ...
def get_piece_centric_features(self, board): features = [] pieces = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'n1', 'n2', 'b1', 'b2', 'r1', 'r2', 'q', 'k', 'P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'N1', 'N2', 'B1', 'B2', 'R1', 'R2', 'Q', 'K'] positions = self.ge...
Python
nomic_cornstack_python_v1
function __init__ __self__ create_source=none source_uri=none begin if create_source is not none begin set __self__ string create_source create_source end if source_uri is not none begin set __self__ string source_uri source_uri end end function
def __init__(__self__, *, create_source: Optional[str] = None, source_uri: Optional[str] = None): if create_source is not None: pulumi.set(__self__, "create_source", create_source) if source_uri is not None: pulumi.set(__self__, "source_uri", sou...
Python
nomic_cornstack_python_v1
if Second >= 60 begin set Second = Second - 60 set Minute = Minute + 1 end comment 분 set Minute = Minute + needTime % 60 set needTime = needTime // 60 if Minute >= 60 begin set Minute = Minute - 60 set Hour = Hour + 1 end set Hour = Hour + needTime % 24 if Hour >= 24 begin set Hour = Hour - 24 end print Hour Minute Sec...
if Second >= 60: Second -= 60 Minute += 1 Minute += needTime % 60 #분 needTime //= 60 if Minute >= 60: Minute -= 60 Hour += 1 Hour += needTime % 24 if Hour >= 24: Hour -= 24 print(Hour, Minute, Second)
Python
zaydzuhri_stack_edu_python
function help begin set text = string ATEMPO %s v2 USAGE: %s project [project [project]]... Directories: Only projects in the 'flame_%s' directory will be written to tape. % tuple upper ARCH_TYPE base name path argv at 0 ARCH_TYPE end function
def help(): text = """ ATEMPO %s v2 USAGE: %s project [project [project]]... Directories: Only projects in the 'flame_%s' directory will be written to tape. \n""" % (ARCH_TYPE.upper(),os.path.basename(sys.argv[0]),ARCH_TYPE)
Python
nomic_cornstack_python_v1
function getOrderTitle self media begin set formatted_title = call getTranslatedTitle set parent_collector = call getParentCollector if parent_collector begin set media_media = call getMedia set media_category = call getCategory set episode = call getEpisode set track = call getTrack set volume = call getVolume set par...
def getOrderTitle(self, media): formatted_title = self.getTranslatedTitle() parent_collector = media.getParentCollector() if parent_collector: media_media = media.control.getMedia() media_category = media.control.getCategory() episode = m...
Python
nomic_cornstack_python_v1
function sample_gaussian cov=200.0 population_size=1000 sample_size=500 seed=none begin seed seed comment set mean as 0, doesn't really matter set population = list comprehension integer i for i in call normal 0 cov population_size set sample = population at slice : sample_size : return dict string sample sample ; st...
def sample_gaussian(cov=200.0, population_size=1000, sample_size=500, seed=None): np.random.seed(seed) population = [int(i) for i in np.random.normal(0, cov, population_size)] # set mean as 0, doesn't really matter sample = population[:sample_size] return {"sample": sample, "sample_distinct":...
Python
nomic_cornstack_python_v1
from kmeans import * from numpy import * if __name__ == string __main__ begin string with open("seeds_dataset.txt") as f: dataset = [[float(x) for x in line.split(' ') if x != ''] for line in f] for i in dataset: del i[-1] print i file = open("seeds", 'w+') for tuple in dataset: s = ','.join(str(s) for s in tuple) file...
from kmeans import * from numpy import * if __name__ =='__main__': ''' with open("seeds_dataset.txt") as f: dataset = [[float(x) for x in line.split('\t') if x != ''] for line in f] for i in dataset: del i[-1] print i file = open("seeds", 'w+') for tuple in dataset: ...
Python
zaydzuhri_stack_edu_python
function test_init begin clear metadata with raises ValueError begin get metadata list string alice string bob end get metadata end function
def test_init(): metadata.clear() with pytest.raises(ValueError): metadata.get(['alice', 'bob']) metadata.get()
Python
nomic_cornstack_python_v1
from game.myclass import Game from game.rlutil import get_state , get_actions from config import ACTIONS , ACTION_SIZE comment LR接口类 # class Agent extends object begin string 只可以在player 1进行训练,player 2/3可以random,规则或rl的val_net function __init__ self player=1 models=list string rl string random string random begin set gam...
from game.myclass import Game from game.rlutil import get_state, get_actions from config import ACTIONS,ACTION_SIZE ############################################ # LR接口类 # ############################################ class Agent(object): """ 只可以在player 1进行训练,player...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver import datetime import time function login_func username password begin set driver = call Chrome get driver string http://thc-game.com set mail_field = call find_element_by_name string thclogin_name call send_keys username set pass_field = call find_element_by_name string thclogin_pass ca...
from selenium import webdriver import datetime import time def login_func(username, password): driver = webdriver.Chrome() driver.get('http://thc-game.com') mail_field = driver.find_element_by_name("thclogin_name") mail_field.send_keys(username) pass_field = driver.find_element_by_name("thclogin_...
Python
zaydzuhri_stack_edu_python
function multiplicar_por multiplicador begin function multi multiplicando begin return multiplicando * multiplicador end function return multi end function set multiplicar_por_10 = call multiplicar_por 10 print call multiplicar_por_10 1 print call multiplicar_por_10 2 set multiplicar_por_5 = call multiplicar_por 5 prin...
def multiplicar_por(multiplicador): def multi(multiplicando): return multiplicando * multiplicador return multi multiplicar_por_10 = multiplicar_por(10) print(multiplicar_por_10(1)) print(multiplicar_por_10(2)) multiplicar_por_5 = multiplicar_por(5) print(multiplicar_por_5(1)) print(multiplicar_por_5(...
Python
zaydzuhri_stack_edu_python
function search sudoku_map begin if sudoku_map is false begin comment Failed earlier return false end if all generator expression length sudoku_map at s == 1 for s in squares begin comment solved return sudoku_map end comment choose the unfilled square with the fewest choices set tuple choices square = min generator ex...
def search(sudoku_map): if sudoku_map is False: return False ## Failed earlier if all(len(sudoku_map[s]) == 1 for s in squares): return sudoku_map ## solved ## choose the unfilled square with the fewest choices choices, square = min((len(sudoku_map[s]...
Python
nomic_cornstack_python_v1
function cudaGetDevice begin string Get current CUDA device. Return the identifying number of the device currently used to process CUDA operations. Returns ------- dev : int Device number. set dev = call c_int set status = call cudaGetDevice call byref dev call cudaCheckStatus status return value end function
def cudaGetDevice(): """ Get current CUDA device. Return the identifying number of the device currently used to process CUDA operations. Returns ------- dev : int Device number. """ dev = ctypes.c_int() status = _libcudart.cudaGetDevice(ctypes.byref(dev)) cudaChec...
Python
jtatman_500k
function __init__ __self__ assessment_count=none extended_details=none group_count=none begin if assessment_count is not none begin set __self__ string assessment_count assessment_count end if extended_details is not none begin set __self__ string extended_details extended_details end if group_count is not none begin s...
def __init__(__self__, *, assessment_count: Optional[pulumi.Input[int]] = None, extended_details: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, group_count: Optional[pulumi.Input[int]] = None): if assessment_count is not None: pulu...
Python
nomic_cornstack_python_v1
function exists self connection=none begin if connection is none begin set connection = connection end set database = call lookup connection call database_name return database is not none end function
def exists(self, connection=None): if connection is None: connection = self.connection database = Database.lookup(connection, self.database_name()) return database is not None
Python
nomic_cornstack_python_v1
function test_get_range_empty self begin set queryset = call Mock set return_value = none set dimension = call QuantitativeDimension key=string shares name=string Count of shares description=string Count of shares field_name=string shared_count set tuple min_val max_val = call get_range queryset assert is none min_val ...
def test_get_range_empty(self): queryset = mock.Mock() queryset.aggregate.return_value = None dimension = models.QuantitativeDimension( key='shares', name='Count of shares', description='Count of shares', field_name='shared_count', ) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import rospy from ackermann_msgs.msg import AckermannDriveStamped from sensor_msgs.msg import LaserScan import std_msgs import math set PID_KP_LEFT = 0.9 set PID_KP_RIGHT = 1.3 set PID_KD = 0 class wall_follow begin function __init__ self begin call Subscriber string /scan LaserScan laser_c...
#!/usr/bin/env python import rospy from ackermann_msgs.msg import AckermannDriveStamped from sensor_msgs.msg import LaserScan import std_msgs import math PID_KP_LEFT = 0.9 PID_KP_RIGHT = 1.3 PID_KD = 0 class wall_follow: def __init__(self): rospy.Subscriber('/scan', LaserScan, self.laser_callback, queue_...
Python
zaydzuhri_stack_edu_python
function runAskLeoIDDialog self begin set d = call swingAskLeoID return run modal=true end function
def runAskLeoIDDialog(self): d = leoSwingDialog.swingAskLeoID() return d.run(modal=True)
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt import scipy.optimize function func x begin return x at 0 ^ 3 + x at 1 ^ 3 - 3 * x at 0 * x at 1 end function function method_rosenbrock_step func=func learning_rate=0.1 * ones 2 max_iter=10000 x0=array list 8 9 alpha=3 beta=- 0.5 e0=call eye 2 dim=2 begin set xi = lis...
import numpy as np import matplotlib.pyplot as plt import scipy.optimize def func(x): return x[0]**3 + x[1]**3 - 3 * x[0] * x[1] def method_rosenbrock_step(func=func, learning_rate=0.1*np.ones(2), max_iter=10000, x0=np.array([8, 9...
Python
zaydzuhri_stack_edu_python
function scope self begin return get pulumi self string scope end function
def scope(self) -> pulumi.Output[str]: return pulumi.get(self, "scope")
Python
nomic_cornstack_python_v1
function reconnect self begin comment This is the old connection IOLoop instance, stop its ioloop call stop if not _closing begin comment Create a new connection set _connection = call connect comment There is now a new connection, needs a new ioloop to run start ioloop end end function
def reconnect(self): # This is the old connection IOLoop instance, stop its ioloop self._connection.ioloop.stop() if not self._closing: # Create a new connection self._connection = self.connect() # There is now a new connection, needs a new ioloop to run ...
Python
nomic_cornstack_python_v1
function mode_scan_worker host port begin set answer = string comment id = "{}:{}".format(host, port) comment print("thread for {} started".format(id)) call setdefaulttimeout 10 if call inet_aton string host begin try begin set tuple answer alias addr = call gethostbyaddr string host end comment print(answer) except B...
def mode_scan_worker(host, port): answer = '' #id = "{}:{}".format(host, port) #print("thread for {} started".format(id)) setdefaulttimeout(10) if inet_aton(str(host)): try: (answer, alias, addr) = gethostbyaddr(str(host)) #print(answer) except BaseException: ...
Python
nomic_cornstack_python_v1
from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.config import Config from kivy.graphics import Color ...
from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.config import Config from kivy.graphics impor...
Python
zaydzuhri_stack_edu_python
function exact_match_candidates self begin return list list PROTEIN_INSERTION list GENE PROTEIN_SUBSTITUTION PROTEIN_INSERTION list PROTEIN_INSERTION GENE list GENE PROTEIN_INSERTION list HGVS PROTEIN_INSERTION list REFERENCE_SEQUENCE PROTEIN_INSERTION list LOCUS_REFERENCE_GENOMIC PROTEIN_INSERTION end function comment...
def exact_match_candidates(self) -> List[List[TokenType]]: return [ [TokenType.PROTEIN_INSERTION], [TokenType.GENE, TokenType.PROTEIN_SUBSTITUTION, TokenType.PROTEIN_INSERTION], # noqa: E501 [TokenType.PROTEIN_INSERTION, TokenType.GENE], [TokenType.GENE, TokenTyp...
Python
nomic_cornstack_python_v1
function GetNorm self begin return call itkVectorUS6_GetNorm self end function
def GetNorm(self) -> "double": return _itkVectorPython.itkVectorUS6_GetNorm(self)
Python
nomic_cornstack_python_v1
set nucleya = string Fuck That Shit!!! print capitalize nucleya print call swapcase print length nucleya print replace nucleya string Fuck string Coitus print count nucleya string h print starts with nucleya string Fuck print ends with nucleya string zz print split nucleya print find nucleya string z print index nucley...
nucleya = 'Fuck That Shit!!!' print(nucleya.capitalize()) print(nucleya.swapcase()) print(len(nucleya)) print(nucleya.replace('Fuck', 'Coitus')) print(nucleya.count('h')) print(nucleya.startswith('Fuck')) print(nucleya.endswith('zz')) print(nucleya.split()) print(nucleya.find('z')) print(nucleya.index('!')) print(nucl...
Python
zaydzuhri_stack_edu_python
comment https://dmoj.ca/problem/ccc98s1 set N = integer input for i in range N begin set cuteee = split input string for cuteeeeeeeeeee in cuteee begin if length cuteeeeeeeeeee == 4 begin print string **** end=string end else begin print cuteeeeeeeeeee end=string end end print end
# https://dmoj.ca/problem/ccc98s1 N = int(input()) for i in range(N): cuteee = input().split(' ') for cuteeeeeeeeeee in cuteee: if len(cuteeeeeeeeeee) == 4: print('****', end=' ') else: print(cuteeeeeeeeeee, end=' ') print()
Python
zaydzuhri_stack_edu_python
from django.db import models from django.utils import timezone import datetime comment Create your models here. class Question extends Model begin set question_text = call CharField max_length=200 set pub_date = call DateTimeField string datepublished function __str__ self begin return string Question: { question_text ...
from django.db import models from django.utils import timezone import datetime # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('datepublished') def __str__(self): return f"Question: {self.question_text} Publ...
Python
zaydzuhri_stack_edu_python
function get_search begin set holder = input string input somethin?: set data = open string some.txt string r comment save each line in data_list set data_list = read lines data close data set found = false end function
def get_search(): holder = input("input somethin?:") data = open('some.txt', 'r') data_list = data.readlines() # save each line in data_list data.close() found = False #
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 string Advent of Code 2015, Day 17, Part 1 function get_combination_count containers capacity begin string Calculate the number of container combinations that exactly total the required capacity. :param containers: list of container sizes to consider :param capacity: required capacity :return: numb...
# coding=utf-8 """Advent of Code 2015, Day 17, Part 1""" def get_combination_count(containers, capacity): """ Calculate the number of container combinations that exactly total the required capacity. :param containers: list of container sizes to consider :param capacity: required capacity :return: ...
Python
zaydzuhri_stack_edu_python
import sys import cv2 import numpy as np comment I reproduced a research paper about color harmonization in this python script. comment Due to time limitation, not every detail is commented. comment To understand the code: 1. please read this paper first:https://igl.ethz.ch/projects/color-harmonization/harmonization.pd...
import sys import cv2 import numpy as np # I reproduced a research paper about color harmonization in this python script. # Due to time limitation, not every detail is commented. # To understand the code: 1. please read this paper first:https://igl.ethz.ch/projects/color-harmonization/harmonization.pdf # To understand ...
Python
zaydzuhri_stack_edu_python
class Item begin function __init__ self weight value begin set weight = weight set value = value end function end class
class Item: def __init__( self, weight: float, value: float ): self.weight = weight self.value = value
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import csv import sys import pandas as pd import numpy as np from requests_html import HTMLSession set link = string http://www.smdg.org/smdg-code-lists/ set base = string http://www.smdg.org set session = call HTMLSession import logging call basicConfig format=string %(asctime)s %(message)...
#!/usr/bin/env python import csv import sys import pandas as pd import numpy as np from requests_html import HTMLSession link = "http://www.smdg.org/smdg-code-lists/" base = "http://www.smdg.org" session = HTMLSession() import logging logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- import json import logging import unittest import re from datetime import datetime import requests comment Unittest tests order. comment https://stackoverflow.com/questions/4095319/unittest-tests-order#comment120033036_22317851 set sortTestMethodsUsing = lambd...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import logging import unittest import re from datetime import datetime import requests # Unittest tests order. # https://stackoverflow.com/questions/4095319/unittest-tests-order#comment120033036_22317851 unittest.TestLoader.sortTestMethodsUsing = lambda *args...
Python
zaydzuhri_stack_edu_python
function from_dict cls dikt begin return call deserialize_model dikt cls end function
def from_dict(cls, dikt) -> 'CreateElection': return util.deserialize_model(dikt, cls)
Python
nomic_cornstack_python_v1
function gen_output_file_path obj_kind obj_name template root_dir begin comment keep the directory structure from the templates dir, comment relative to the template key set common_path = join path root_dir obj_kind set rel_path = call relpath template common_path set file_path = join path obj_name rel_path comment cre...
def gen_output_file_path(obj_kind, obj_name, template, root_dir): # keep the directory structure from the templates dir, # relative to the template key common_path = os.path.join(root_dir, obj_kind) rel_path = os.path.relpath(template, common_path) file_path = os.path.join(obj_name, rel_path) ...
Python
nomic_cornstack_python_v1
function verif_valid_from_bag list_models X_val reality cut=0.5 begin set bag_scores = list for model in list_models begin set pred_score = call predict_proba X_val at tuple slice : : 1 append bag_scores call tolist end set bag_scores = transpose call DataFrame bag_scores comment bag_scores = np.asmatrix(bag_scores...
def verif_valid_from_bag(list_models, X_val, reality, cut=0.5): bag_scores = [] for model in list_models: pred_score = model.predict_proba(X_val)[:,1] bag_scores.append(pred_score.tolist()) bag_scores = pd.DataFrame(bag_scores).transpose() #bag_scores = np.asmatrix(bag_scores)[:,0:5] ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import optparse , sys , os import bleu comment ../toy/train.cn comment os.path.join("data", "test.en") set optparser = call OptionParser comment optparser.add_option("-r", "--reference", dest="reference", default="../toy/train.en", help="English reference sentences") call add_option string ...
#!/usr/bin/env python import optparse, sys, os import bleu # ../toy/train.cn # os.path.join("data", "test.en") optparser = optparse.OptionParser() #optparser.add_option("-r", "--reference", dest="reference", default="../toy/train.en", help="English reference sentences") optparser.add_option("-r", "--reference", dest="...
Python
zaydzuhri_stack_edu_python
function get_diff list_a list_b begin set diff = list_a for i in list_b begin if i in list_a begin remove diff i end end return diff end function
def get_diff(list_a, list_b): diff = list_a for i in list_b: if i in list_a: diff.remove(i) return diff
Python
flytech_python_25k
function fib max begin set tuple f1 f2 = tuple 0 1 while f1 < max begin yield f1 set tuple f1 f2 = tuple f2 f1 + f2 end end function print sum filter lambda n -> n % 2 == 0 call fib 4000000
def fib(max): f1, f2 = 0, 1 while f1 < max: yield f1 f1, f2 = f2, f1 + f2 print(sum(filter(lambda n: n % 2 == 0, fib(4000000))))
Python
zaydzuhri_stack_edu_python
import math set x1 = integer input string Digite o número correspondente à coordenada x do primeiro ponto: set y1 = integer input string Digite o número correspondente à coordenada y do primeiro ponto: set x2 = integer input string Digite o número correspondente à coordenada x do segundo ponto: set y2 = integer input s...
import math x1 = int(input('Digite o número correspondente à coordenada x do primeiro ponto: ')) y1 = int(input('Digite o número correspondente à coordenada y do primeiro ponto: ')) x2 = int(input('Digite o número correspondente à coordenada x do segundo ponto: ')) y2 = int(input('Digite o número correspondente à coor...
Python
zaydzuhri_stack_edu_python
from unittest import TestCase from back.effects import EffectFactory , ActionFactory class TestEffectFactory extends TestCase begin function setUp self begin set eff_fact = call EffectFactory end function function test_add_to_pool self begin call add_to_pool string explodes_01 10 130 call add_to_pool string explodes_04...
from unittest import TestCase from back.effects import EffectFactory, ActionFactory class TestEffectFactory(TestCase): def setUp(self): self.eff_fact = EffectFactory() def test_add_to_pool(self): self.eff_fact.add_to_pool('explodes_01', 10, 130) self.eff_fact.add_to_pool('explodes_04...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 from machine_state import MachineState , MachineCommand set _state_table = dict STOPPED dict START STARTED ; STARTED dict COLLECT COLLECTING ; STOP STOPPED ; COLLECTING dict PROCESS PROCESSING ; STOP STOPPED ; PROCESSING dict STOP STOPPED function get_next_state current_state command begin...
#!/usr/bin/env python3 from machine_state import MachineState, MachineCommand _state_table = { MachineState.STOPPED: { MachineCommand.START: MachineState.STARTED }, MachineState.STARTED: { MachineCommand.COLLECT: MachineState.COLLECTING, MachineCommand.STOP: MachineState.STOPPED }, MachineState.COLLECTING: { Machin...
Python
zaydzuhri_stack_edu_python
function _to_datetime struct_time begin try begin return call fromtimestamp call mktime struct_time end except TypeError begin return none end end function
def _to_datetime(struct_time): try: return datetime.fromtimestamp(mktime(struct_time)) except TypeError: return None
Python
nomic_cornstack_python_v1
function evaluate self category method *args begin assert is instance category integer_types and 0 <= category < __N msg string Invalid `category' %s/%s % tuple category type category return evaluate __readers at category method *args end function
def evaluate ( self , category , method , *args ) : assert isinstance ( category , integer_types ) and 0 <= category < self.__N, \ "Invalid `category' %s/%s" % ( category , type ( category ) ) return self.__readers[ category ].evaluate ( method , *args )
Python
nomic_cornstack_python_v1
function test_student_answer_feedback_is_presented_8304 self begin set test_updates at string name = string t1.55.008 + co_name at slice 4 : : set test_updates at string tags = list string t1 string t1.55 string t1.55.008 string 8304 set test_updates at string passed = false comment Test steps and verification assert...
def test_student_answer_feedback_is_presented_8304(self): self.ps.test_updates['name'] = 't1.55.008' \ + inspect.currentframe().f_code.co_name[4:] self.ps.test_updates['tags'] = ['t1', 't1.55', 't1.55.008', '8304'] self.ps.test_updates['passed'] = False # Test steps and veri...
Python
nomic_cornstack_python_v1
string Simple script used to download the previous years masters data Can be adapted to different months data easily (I hope) from urllib.request import urlretrieve set file_names = list for i in range 50 begin append file_names call zfill 12 end print string Requesting the following files: print file_names for file_n...
""" Simple script used to download the previous years masters data Can be adapted to different months data easily (I hope) """ from urllib.request import urlretrieve file_names = [] for i in range(50): file_names.append(str(i).zfill(12)) print("Requesting the following files: ") print(file_names) for file_name...
Python
zaydzuhri_stack_edu_python
function _maybe_pubsub_notify_now result_summary request begin assert not call in_transaction assert is instance result_summary TaskResultSummary msg result_summary assert is instance request TaskRequest msg request if state in STATES_NOT_RUNNING and pubsub_topic begin set task_id = call pack_result_summary_key key try...
def _maybe_pubsub_notify_now(result_summary, request): assert not ndb.in_transaction() assert isinstance( result_summary, task_result.TaskResultSummary), result_summary assert isinstance(request, task_request.TaskRequest), request if (result_summary.state in task_result.State.STATES_NOT_RUNNING and ...
Python
nomic_cornstack_python_v1
function zplot area=0.95 two_tailed=true align_right=false begin comment create plot object set fig = figure figsize=tuple 12 6 set ax = call subplots comment create normal distribution set norm = norm comment create data points to plot set x = linear space - 5 5 1000 set y = call pdf x plot x y comment code to fill ar...
def zplot(area=0.95, two_tailed=True, align_right=False): # create plot object fig = plt.figure(figsize=(12, 6)) ax = fig.subplots() # create normal distribution norm = scs.norm() # create data points to plot x = np.linspace(-5, 5, 1000) y = norm.pdf(x) ax.plot(x, y) # code to ...
Python
nomic_cornstack_python_v1
function evaluate_random_function f x y begin if f at 0 == string x begin return call X x y end else if f at 0 == string y begin return call Y x y end else if f at 0 == string sin_pi begin return call sin_pi call evaluate_random_function f at 1 x y end else if f at 0 == string cos_pi begin return call cos_pi call evalu...
def evaluate_random_function(f, x, y): if (f[0]=='x'): return X(x,y) elif (f[0]=='y'): return Y(x,y) elif (f[0]=='sin_pi'): return sin_pi(evaluate_random_function(f[1],x,y)) elif (f[0]=='cos_pi'): return cos_pi(evaluate_random_function(f[1],x,y)) elif (f[0]=='times'):...
Python
nomic_cornstack_python_v1
function SearchGroup self pattern filter=string none begin return call SearchGroup filter pattern end function
def SearchGroup(self, pattern, filter="none"): return self.get_iface().SearchGroup(filter, pattern)
Python
nomic_cornstack_python_v1
function max_results self max_results begin set _max_results = max_results end function
def max_results(self, max_results): self._max_results = max_results
Python
nomic_cornstack_python_v1
function analyze_weekly feature_matrix config data_path begin if config at string model_name == string XGBoost begin print string XGBoost is used end else if config at string model_name == string RandomForestClassifier begin print string RandomForestClassifier is used end if config at string late_fusion_flag begin prin...
def analyze_weekly(feature_matrix, config, data_path): if config['model_name'] == 'XGBoost': print("XGBoost is used") elif config['model_name'] == 'RandomForestClassifier': print("RandomForestClassifier is used") if config['late_fusion_flag']: print("Late fusion is used") else: ...
Python
nomic_cornstack_python_v1
function compute_B_prob_using_part_prob data probs weight_column=string N_sig_sw event_id_column=string event_id signB_column=string signB sign_part_column=string signTrack normed_signs=false begin set tuple result_event_id data_ids = unique values return_inverse=true set log_probs = log probs - log 1 - probs set sign_...
def compute_B_prob_using_part_prob(data, probs, weight_column='N_sig_sw', event_id_column='event_id', signB_column='signB', sign_part_column='signTrack', normed_signs=False): result_event_id, data_ids = numpy.unique(data[event_id_column].values, return_inverse=True) log_probs ...
Python
nomic_cornstack_python_v1
string Play with Sequences and Subsequence Problem statement Rick is Professor at Zing University. He teaches Maths there. One day he was teaching Sequence, suddenly he came up on a problem, which was taking alot of time.Cody being a Coder, decided to solve the problem using code, so he just put his mobile out , opened...
''' Play with Sequences and Subsequence Problem statement Rick is Professor at Zing University. He teaches Maths there. One day he was teaching Sequence, suddenly he came up on a problem, which was taking alot of time.Cody being a Coder, decided to solve the problem using code, so he just put his mobile out , opened th...
Python
zaydzuhri_stack_edu_python
function process_inventory self ctx begin if not call load_data string cli_show_inventory begin return end set inventory_output = call load_data string cli_show_inventory at 0 set inventory_data = call parse_inventory_output inventory_output set chassis_indices = list for idx in call xrange 0 length inventory_data beg...
def process_inventory(self, ctx): if not ctx.load_data('cli_show_inventory'): return inventory_output = ctx.load_data('cli_show_inventory')[0] inventory_data = self.parse_inventory_output(inventory_output) chassis_indices = [] for idx in xrange(0, len(inventory_dat...
Python
nomic_cornstack_python_v1
function string_in_operation_output sensitive_or_insensitive value environment begin set case_sensitive = sensitive_or_insensitive == string sensitive call check_value_in_operation_output value environment case_sensitive end function
def string_in_operation_output(sensitive_or_insensitive, value, environment): case_sensitive = sensitive_or_insensitive == 'sensitive' check_value_in_operation_output(value, environment, case_sensitive)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: UTF-8 -*- string date: 2018/02/09 10:51:21 下午 CST @author :kkwang import pandas as pd from collections import Counter import matplotlib.pyplot as plt import os import numpy as np import seaborn as sns set filepath = string /Users/kkwang/mywork/gene_array_matrix_csv clas...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ date: 2018/02/09 10:51:21 下午 CST @author :kkwang """ import pandas as pd from collections import Counter import matplotlib.pyplot as plt import os import numpy as np import seaborn as sns filepath='/Users/kkwang/mywork/gene_array_matrix_csv' class brainspanwork(obje...
Python
zaydzuhri_stack_edu_python
function check_high_score self begin if score > high_score begin set high_score = score call prep_high_score with open saved_data_filename as f begin set data_to_be_saved = load json f set data_to_be_saved at string high_score = score end with open saved_data_filename string w as f begin dump data_to_be_saved f end end...
def check_high_score(self): if self.stats.score > self.stats.high_score: self.stats.high_score = self.stats.score self.prep_high_score() with open(self.stats.saved_data_filename) as f: data_to_be_saved = json.load(f) data_to_be_saved["high_scor...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment MyDailyLog comment Author: Alvin D. Morris comment email: alvin.morris@gmail.com comment Command line utility for keeping track of daily productivity. import os import datetime class MyDailyLog begin function __init__ self begin set MDLFolder = call getenv string HOME + string /Dropbox/...
#!/usr/bin/python ################################################################# # MyDailyLog # Author: Alvin D. Morris # email: alvin.morris@gmail.com # # Command line utility for keeping track of daily productivity. ################################################################# import os import datetime clas...
Python
zaydzuhri_stack_edu_python
function calculate_triangle_perimeter side1 side2 side3 begin comment Check if side lengths are valid if side1 <= 0 or side2 <= 0 or side3 <= 0 begin return - 1 end if side1 + side2 <= side3 or side2 + side3 <= side1 or side1 + side3 <= side2 begin return - 1 end comment Calculate perimeter set perimeter = side1 + side...
def calculate_triangle_perimeter(side1, side2, side3): # Check if side lengths are valid if side1 <= 0 or side2 <= 0 or side3 <= 0: return -1 if (side1 + side2) <= side3 or (side2 + side3) <= side1 or (side1 + side3) <= side2: return -1 # Calculate perimeter perimeter = side1 + side...
Python
jtatman_500k
function add_todo_input self begin set stats = call get_stats set color_map = color_map set contexts = sorted list keys get stats PROPERTY_CONTEXTS dict set projects = sorted list keys get stats PROPERTY_PROJECTS dict set attributes = sorted list keys get stats PROPERTY_ATTRIBUTES dict set col = dict string prj get col...
def add_todo_input(self): stats=self.get_stats() color_map=self.config.color_map contexts=sorted(list(stats.get(Todo.PROPERTY_CONTEXTS,{}).keys())) projects=sorted(list(stats.get(Todo.PROPERTY_PROJECTS,{}).keys())) attributes=sorted(list(stats.get(Todo.PROPERTY_ATTRIBUTES,{}).key...
Python
nomic_cornstack_python_v1
function ignored_columns self begin return get _parms string ignored_columns end function
def ignored_columns(self): return self._parms.get("ignored_columns")
Python
nomic_cornstack_python_v1
comment minMove.py comment 5251. [파이썬 S/W 문제해결 구현] 7일차 - 최소 이동 거리 comment 방향 그래프: 방향이 잘못됐음, 출발지랑 도착지로 해야 함 string A도시에는 E개의 일방통행 도로 구간이 있으며, 각 구간이 만나는 연결지점에는 0부터 N번까지의 번호가 붙어있다. 구간의 시작과 끝의 연결 지점 번호, 구간의 길이가 주어질 때, 0번 지점에서 N번 지점까지 이동하는데 걸리는 최소한의 거리가 얼마인지 출력하는 프로그램을 만드시오. 모든 연결 지점을 거쳐가야 하는 것은 아니다. 그림은 입력인 N=2, E=3, 시작과 끝...
# minMove.py # 5251. [파이썬 S/W 문제해결 구현] 7일차 - 최소 이동 거리 # 방향 그래프: 방향이 잘못됐음, 출발지랑 도착지로 해야 함 ''' A도시에는 E개의 일방통행 도로 구간이 있으며, 각 구간이 만나는 연결지점에는 0부터 N번까지의 번호가 붙어있다. 구간의 시작과 끝의 연결 지점 번호, 구간의 길이가 주어질 때, 0번 지점에서 N번 지점까지 이동하는데 걸리는 최소한의 거리가 얼마인지 출력하는 프로그램을 만드시오. 모든 연결 지점을 거쳐가야 하는 것은 아니다. 그림은 입력인 N=2, E=3, 시작과 끝 지점, 구간 거리가 아래와...
Python
zaydzuhri_stack_edu_python
import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB comment Load the data set data = read csv string movie_reviews.csv comment Extract the reviews and the labels set reviews = call tolist set labels = call tolist comment Transform the reviews to ...
import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB # Load the data data = pd.read_csv('movie_reviews.csv') # Extract the reviews and the labels reviews = data.text.tolist() labels = data.label.tolist() # Transform the reviews to a numerical ...
Python
jtatman_500k
set x = 3 + 2 set y = 5 - 7 print string I will now count my chickens: print string Hens 30 print string Roosters 97 print string Now I will count the eggs: print 7 print string It is true that, 3 + 2 < 5 -7? print 3 + 2 < 5 - 7 print string What is 3 + 2? + string x print string What is 5 - 7? + string y print string ...
x = 3 + 2 y = 5 - 7 print("I will now count my chickens:") print("Hens 30") print("Roosters 97") print("Now I will count the eggs:") print(7) print("It is true that, 3 + 2 < 5 -7?") print(3 + 2 < 5 - 7) print("What is 3 + 2? " + str(x)) print("What is 5 - 7? " + str(y)) print("Oh, that's why it's False") print("How ab...
Python
zaydzuhri_stack_edu_python
import torch from torch import Tensor function feature_align raw_feature P ns_t ori_size device=none begin string Perform feature align from the raw feature map. :param raw_feature: raw feature map :param P: point set containing point coordinates :param ns_t: number of exact points in the point set :param ori_size: siz...
import torch from torch import Tensor def feature_align(raw_feature: Tensor, P: Tensor, ns_t: Tensor, ori_size: tuple, device=None): """ Perform feature align from the raw feature map. :param raw_feature: raw feature map :param P: point set containing point coordinates :param ns_t: number...
Python
zaydzuhri_stack_edu_python
import sys import numpy set INFINITY = maxint function print_neatly words M begin string >>> print_neatly(["Dhawal", "loves", "to", "code"],10) (72, 'Dhawal\nloves to\ncode') >>> print_neatly(["Dhawal", "loves", "cricket", "and", "football"],15) (91, 'Dhawal loves\ncricket and\nfootball') set word_length = length words...
import sys import numpy INFINITY = sys.maxint def print_neatly(words, M): """ >>> print_neatly(["Dhawal", "loves", "to", "code"],10) (72, 'Dhawal\\nloves to\\ncode') >>> print_neatly(["Dhawal", "loves", "cricket", "and", "football"],15) (91, 'Dhawal loves\\ncricket and\\nfootball') """ wo...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string This script is written to normalize the mutation description. Author: chenyanpeng@dnastories Date : 2020-05-08 import re import sys import json import argparse function parse_args argv begin set parser = call ArgumentParser description=__doc__ formatter_class=RawDescriptionHelpForma...
#!/usr/bin/env python3 ''' This script is written to normalize the mutation description. Author: chenyanpeng@dnastories Date : 2020-05-08 ''' import re import sys import json import argparse def parse_args(argv): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argp...
Python
zaydzuhri_stack_edu_python