code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
from sys import argv from os.path import exists set tuple script from_file to_file = argv print string Copying from { from_file } to { to_file } The input file is { length indata } bytes long Ready, hit RETURN to continue, CTRL-C to abort. input write open to_file string w open read from_file print string Alright, all ...
from sys import argv from os.path import exists script, from_file, to_file = argv print(f"Copying from {from_file} to {to_file}\nThe input file is {len(indata)} bytes long\nReady, hit RETURN to continue, CTRL-C to abort.") input() open(to_file, 'w').write(open(from_file.read())) print("Alright, all done.")
Python
zaydzuhri_stack_edu_python
function get_top_tracks api country location=none begin set params = dict string method string geo.getTopTracks ; string country country if location is not none begin update params dict string location location end set data = find call _fetch_data params string toptracks return list comprehension call Track api name=fi...
def get_top_tracks(api, country, location = None): params = {'method': 'geo.getTopTracks', 'country': country} if location is not None: params.update({'location': location}) data = api._fetch_data(params).find('toptracks') return [ Track( ...
Python
nomic_cornstack_python_v1
while true begin set nums = input string enter space separated nums set int_nums = list map str split nums set cleaned = list comprehension integer x for x in int_nums if is digit x set Sum = Sum + sum cleaned print Sum if string ~ in nums begin break end end
while True: nums = input("enter space separated nums") int_nums = list(map(str, nums.split())) cleaned = [int(x) for x in int_nums if x.isdigit()] Sum = Sum + sum(cleaned) print(Sum) if '~' in nums: break
Python
zaydzuhri_stack_edu_python
string Task You are given the shape of the array in the form of space-separated integers, each integer representing the size of different dimensions, your task is to print an array of the given shape and integer type using the tools numpy.zeros and numpy.ones. Input Format A single line containing the space-separated i...
""" Task You are given the shape of the array in the form of space-separated integers, each integer representing the size of different dimensions, your task is to print an array of the given shape and integer type using the tools numpy.zeros and numpy.ones. Input Format A single line containing the space-separ...
Python
zaydzuhri_stack_edu_python
function fft2 a s=none axes=tuple - 2 - 1 norm=none begin return call fftn a=a s=s axes=axes norm=norm end function
def fft2( a: ndarray, s: Union[Sequence[int], None] = None, axes: Sequence[int] = (-2, -1), norm: Union[str, None] = None, ) -> ndarray: return fftn(a=a, s=s, axes=axes, norm=norm)
Python
nomic_cornstack_python_v1
function reboot_self self begin set restart_arguments = list argv insert restart_arguments 0 string call execv executable restart_arguments exit end function
def reboot_self(self): restart_arguments = list(sys.argv) restart_arguments.insert(0, '') execv(sys.executable, restart_arguments) sys.exit()
Python
nomic_cornstack_python_v1
function testLoginForms self begin set tuple password nick avatar = users at 0 set response = get app string / comment there is a form with the id 'loginform' set loginform = forms at string loginform assert is not none loginform string no form with id loginform in the page comment login form action should be /login as...
def testLoginForms(self): (password, nick, avatar) = self.users[0] response = self.app.get('/') # there is a form with the id 'loginform' loginform = response.forms['loginform'] self.assertIsNotNone(loginform, "no form with id loginform in the page") # login form acti...
Python
nomic_cornstack_python_v1
function Login params=none title=none begin set p = call Page call content string <!DOCTYPE html> with call html begin with head p begin with title p begin call content string pgui - Login end with call link dict string href string static/lib/bootstrap/bootstrap-3.3.4-dist/css/bootstrap.css ; string rel string styleshe...
def Login(params=None, title=None): p = Page() p.content('<!DOCTYPE html>') with p.html(): with p.head(): with p.title(): p.content('pgui - Login') with p.link({'href': 'static/lib/bootstrap/bootstrap-3.3.4-dist/css/bootstrap.css', 'rel': 'stylesheet'}): pass ...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt comment 绘制饼图 set labels = list string Python string Javascript string C++ string Java string PHP set values = list 26 17 21 29 11 set spaces = list 0.05 0.01 0.01 0.01 0.01 set colors = list string dodgerblue string orangered string limegreen string violet string gold ...
import numpy as np import matplotlib.pyplot as plt # 绘制饼图 labels = ['Python', 'Javascript', 'C++', 'Java', 'PHP'] values = [26, 17, 21, 29, 11] spaces = [0.05, 0.01, 0.01, 0.01, 0.01] colors = ['dodgerblue', 'orangered', 'limegreen', 'violet', 'gold'] plt.figure("Pie", facecolor="lightgray") plt.t...
Python
zaydzuhri_stack_edu_python
comment The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. comment Find the sum of all the primes below two million. comment The page has been left unattended for too long and that link/button is no longer active. Please refresh the page.
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # Find the sum of all the primes below two million. # The page has been left unattended for too long and that link/button is no longer active. Please refresh the page.
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup import requests , json , re set urlToScrape = string http://www.cnbc.com set response = get requests urlToScrape timeout=5 set content = call BeautifulSoup content string html.parser function get_top_news_headline obj begin set a_tags = find all find obj string div dict string id string Ma...
from bs4 import BeautifulSoup import requests, json, re urlToScrape = "http://www.cnbc.com" response = requests.get(urlToScrape, timeout=5) content = BeautifulSoup(response.content, "html.parser") def get_top_news_headline(obj): a_tags = obj.find('div', {'id':'MainContent'}).find_all('a', {'href':re.compile('.*cn...
Python
zaydzuhri_stack_edu_python
function tiered_successdf df group begin string Create a dataframe for success by profit tier. set df at string count = 1 comment Create columns that track success. set loc at tuple loc at tuple slice : : string profit >= 100000000 string BB = true set loc at tuple loc at tuple slice : : string profit >= 10000000...
def tiered_successdf(df,group): """Create a dataframe for success by profit tier.""" df['count']=1 #Create columns that track success. df.loc[df.loc[:,'profit'] >= 100000000, 'BB']=True df.loc[(df.loc[:,'profit'] >= 10000000) &(df.loc[:,'profit'] <100...
Python
zaydzuhri_stack_edu_python
function call_top_interface_args_with_func_def self node begin comment call container is used to scope parameters set call_con_name = call call_container_name node comment create argument and parameter variables comment argument variables are inputs to the top interface comment paramter variables are outputs of the top...
def call_top_interface_args_with_func_def(self, node: AnnCastCall): # call container is used to scope parameters call_con_name = call_container_name(node) # create argument and parameter variables # argument variables are inputs to the top interface # paramter variables are outp...
Python
nomic_cornstack_python_v1
function fac1 n begin assert n >= 0 if n == 0 or n == 1 begin return 1 end set prod = 1 for i in range 2 n + 1 begin set prod = prod * i end return prod end function
def fac1(n): assert n >= 0 if n == 0 or n == 1: return 1 prod = 1 for i in range(2,n+1): prod = prod*i return prod
Python
nomic_cornstack_python_v1
function get_species_annotation_dic csv_file begin string Takes as input the binary information about species annotation from Species_Annotation_fake.csv (OrtAn results) and transforms it into a dictionary where to each species is assigned a list of the KOs present in the species genome :param csv_file: str - path to S...
def get_species_annotation_dic(csv_file): ''' Takes as input the binary information about species annotation from Species_Annotation_fake.csv (OrtAn results) and transforms it into a dictionary where to each species is assigned a list of the KOs present in the species genome :param csv_file: str...
Python
zaydzuhri_stack_edu_python
function next self begin try begin set ret = next self end except StopIteration begin set __fullcache = true raise end append __itercache ret return ret end function
def next(self): try: ret = PymongoCursor.next(self) except StopIteration: self.__fullcache = True raise self.__itercache.append(ret) return ret
Python
nomic_cornstack_python_v1
function rest_to_html_ajax request begin if method != string GET and not call is_ajax begin raise Http404 end set data = dict string success false try begin set rest_text = GET at string rest_text set source = GET at string source end except KeyError begin raise Http404 end set start_time = time try begin set html_text...
def rest_to_html_ajax(request): if request.method != 'GET' and not request.is_ajax(): raise Http404 data = {'success': False} try: rest_text = request.GET['rest_text'] source = request.GET['source'] except KeyError: raise Http404 start_time = time.time() try: ...
Python
nomic_cornstack_python_v1
function login_attempt_record self field_data ip_id success=0 begin set hash = call quick_hash field_data set attempt_id = call sql string INSERT INTO login_attempts (field_data, ip_id, success) VALUES (%s, %s, %s) hash ip_id integer success end function
def login_attempt_record(self, field_data, ip_id, success=0): hash = quick_hash(field_data) attempt_id = self.sql('INSERT INTO login_attempts (field_data, ip_id, success) VALUES (%s, %s, %s)', hash, ip_id, int(success))
Python
nomic_cornstack_python_v1
function get_user_data self key default=none begin if not is instance _user_data dict begin return default end return get _user_data key end function
def get_user_data(self, key, default=None): if not isinstance(self._user_data, dict): return default return self._user_data.get(key)
Python
nomic_cornstack_python_v1
function solve heads legs begin set error_msg = string No solution set chicken_count = 0 set rabbit_count = 0 if legs % 2 != 0 or heads == 0 or heads > legs begin print error_msg end else begin set rabbit_count = integer legs - 2 * heads / 2 set chicken_count = integer heads - rabbit_count print chicken_count rabbit_co...
def solve(heads,legs): error_msg="No solution" chicken_count=0 rabbit_count=0 if legs%2!=0 or heads==0 or heads>legs: print(error_msg) else: rabbit_count=int((legs-(2*heads))/2) chicken_count=int(heads-rabbit_count) print(chicken_count,rabbit_count) solve(35...
Python
zaydzuhri_stack_edu_python
import random from generators.abstractgenerator import AbstractGenerator class ItemListingGenerator extends AbstractGenerator begin function __init__ self listingIds itemIds currencyIds begin call super call __init__ set listingIds = listingIds set itemIds = itemIds set currencyIds = currencyIds set pickedListingIds = ...
import random from generators.abstractgenerator import AbstractGenerator class ItemListingGenerator(AbstractGenerator): def __init__(self, listingIds: list, itemIds: list, currencyIds: list): super() super().__init__() self.listingIds = listingIds self.itemIds = itemIds s...
Python
zaydzuhri_stack_edu_python
from flask import Flask , render_template set app = call Flask __name__ decorator call route string / function index begin return string 안녕하세요!!!! end function decorator call route string /dictionary/<string:word> function dictionary word begin set word_dict = dict string apple string 사과 ; string banana string 바나나 ; st...
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return '안녕하세요!!!!' @app.route("/dictionary/<string:word>") def dictionary(word): word_dict = {'apple':'사과', 'banana':'바나나', 'orange':'오렌지', 'grape':'포도'} return render_template('dict.html', word = word, word_dict =...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.feature_extraction.text import CountVectorizer from sklearn import model_selection , preprocessing from sklearn.metrics import log_loss from sklearn.linear_model import LogisticRegression from sklearn.model_selecti...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.feature_extraction.text import CountVectorizer from sklearn import model_selection, preprocessing from sklearn.metrics import log_loss from sklearn.linear_model import LogisticRegression from sklearn.model_selectio...
Python
zaydzuhri_stack_edu_python
import random set menu = list string ピクミン string チャッピー string コガネモチ string ヘビガラス string オオパンモドキ string アメボウズ set plice = list 200 240 330 400 300 1 set money = random integer 1000 2000 while true begin if length menu == 0 begin print string すべて売り切れました break end else if money < min plice begin print string もう一番安いメニューすら買...
import random menu = ['ピクミン','チャッピー','コガネモチ', 'ヘビガラス','オオパンモドキ','アメボウズ'] plice = [200,240,330,400,300,1] money = random.randint(1000,2000) while True: if len(menu) == 0: print('すべて売り切れました') break elif money < min(plice): print('もう一番安いメニューすら買えなくなってしまったようです') break else...
Python
zaydzuhri_stack_edu_python
comment implement knn classification and regression import arff import numpy as np import math from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold class KNN_Classification begin comment Read data from file and preprocess functi...
# # implement knn classification and regression # import arff import numpy as np import math from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold class KNN_Classification: # # Read data from file and preprocess #...
Python
zaydzuhri_stack_edu_python
function update_velocity self begin set vel = call vel_func set theta = uniform 0 2 * pi set velocity = vel * call V cos theta sin theta set wait = false end function
def update_velocity(self): vel = self.vel_func() theta = random.uniform(0, 2 * math.pi) self.velocity = vel * V(math.cos(theta), math.sin(theta)) self.wait = False
Python
nomic_cornstack_python_v1
function events_today begin set event_list = call get_events 0 set event_embed = call create_event_embed true return tuple event_embed event_list end function
def events_today() -> (discord.Embed, List[List[Event]]): event_list = get_events(0) event_embed = create_event_embed(True) return event_embed, event_list
Python
nomic_cornstack_python_v1
function _load_local_state_dict self state_dict *args begin with call state_dict_type self LOCAL_STATE_DICT begin return load state dict self state_dict *args end end function
def _load_local_state_dict( self, state_dict: Mapping[str, Any], *args, ) -> NamedTuple: with self.state_dict_type(self, StateDictType.LOCAL_STATE_DICT): return self.load_state_dict(state_dict, *args)
Python
nomic_cornstack_python_v1
for i in range integer input begin set n = integer input set l = list comprehension integer i for i in split input sort l set c = 0 if length l == 1 begin print string YES break end for i in range n - 1 begin if absolute l at i - l at i + 1 <= 1 begin set c = c + 1 end else begin set c = 0 break end end if c == 0 begin...
for i in range(int(input())): n=int(input()) l=[int(i) for i in input().split()] l.sort() c=0 if(len(l)==1): print("YES") break for i in range(n-1): if abs(l[i]-l[i+1])<=1: c+=1 else: c=0 break if c==0: print("NO") ...
Python
zaydzuhri_stack_edu_python
function get_base_path filepath begin return directory name path filepath end function
def get_base_path(filepath): return os.path.dirname(filepath)
Python
nomic_cornstack_python_v1
from mymodules import merge import sys import os try begin import cPickle as pickle end except any begin import pickle end comment Code for boolean_query in python. set indexfolder = string ./index/ if not exists path indexfolder + string index.index begin print string No index exists. Please create index first! exit e...
from mymodules import merge import sys import os try : import cPickle as pickle except: import pickle #Code for boolean_query in python. indexfolder = './index/' if not os.path.exists(indexfolder + 'index.index'): print ("No index exists. Please create index first!") sys.exit() index = pickle.load(...
Python
zaydzuhri_stack_edu_python
comment Ability to view user anyone's user profile, comment and modify a user's own profile comment (name, email, handle, and profile photo) comment user_profile comment user_profile_setname comment user_profile_setemail comment user_profile_sethandle from auth import auth_register from user import * from error import ...
# Ability to view user anyone's user profile, # and modify a user's own profile # (name, email, handle, and profile photo) # user_profile # user_profile_setname # user_profile_setemail # user_profile_sethandle from auth import auth_register from user import * from error import InputError import pytest import re de...
Python
zaydzuhri_stack_edu_python
class Poly begin function __init__ self liste begin set liste = liste end function function __str__ self begin set liste = list set us = 0 for i in liste at slice : : - 1 begin if us == 0 begin append liste string i set us = us + 1 continue end if type i == int begin append liste string i + string * + string x^ + st...
class Poly: def __init__(self, liste): self.liste = liste def __str__(self): liste = [] us = 0 for i in self.liste[::-1]: if us==0: liste.append(str(i)) ...
Python
zaydzuhri_stack_edu_python
for i in range 1 101 begin set t0 = i set t1 = i * 100 set t2 = i * 100 * 100 append A t0 append B t1 append C t2 end set tuple d n = map int split input if d == 0 begin if n == 100 begin print 101 end else begin print A at n - 1 end end else if d == 1 begin if n == 100 begin print 100 * 101 end else begin print B at n...
for i in range(1,101): t0 = i t1 = i*100 t2 = i*100*100 A.append(t0) B.append(t1) C.append(t2) d,n = map(int,input().split()) if d == 0: if n == 100: print(101) else: print(A[n-1]) elif d == 1: if n == 100: print(100*101) else: print(B[n-1]) else...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import rss_metrics as rss set colors = dict Safe string g ; LongitudinallyDangerous string y ; LaterallyDangerous string m ; Dangerous string r ; Proper string g ; ImproperLongitudinal string r ; ImproperLateral string r ; ImproperBoth string r set labels = dict Safe string Safe ; Longit...
import matplotlib.pyplot as plt import rss_metrics as rss colors = { rss.Dangerous.Safe: 'g', rss.Dangerous.LongitudinallyDangerous: 'y', rss.Dangerous.LaterallyDangerous: 'm', rss.Dangerous.Dangerous: 'r', rss.Response.Proper: 'g', rss.Response.ImproperLongitudinal: 'r', rss.Response.Impro...
Python
zaydzuhri_stack_edu_python
comment -*- coding: UTF-8 -*- import matplotlib.pyplot as plt import tensorflow as tf import numpy as np set c = call truncated_normal shape=list 2 2 mean=0 stddev=1 with call Session as sess begin set m = run c end
# -*- coding: UTF-8 -*- import matplotlib.pyplot as plt import tensorflow as tf import numpy as np c = tf.truncated_normal(shape=[2, 2], mean=0, stddev=1) with tf.Session() as sess: m = sess.run(c)
Python
zaydzuhri_stack_edu_python
function conv_to_annualised_rate sr begin return call expm1 sr end function
def conv_to_annualised_rate(sr): return np.expm1(sr)
Python
nomic_cornstack_python_v1
import csv import numpy as np import pandas import pickle import pylab as plt import random import time from functools import wraps from matplotlib.font_manager import FontProperties from pybrain.structure import FeedForwardNetwork , LinearLayer , SigmoidLayer from pybrain.structure import TanhLayer , FullConnection fr...
import csv import numpy as np import pandas import pickle import pylab as plt import random import time from functools import wraps from matplotlib.font_manager import FontProperties from pybrain.structure import FeedForwardNetwork, LinearLayer, SigmoidLayer from pybrain.structure import TanhLayer, FullConnection from ...
Python
zaydzuhri_stack_edu_python
string These tests only run properly if you have an active google api key set to the environment variable API_KEY='your_api_key' import os from google_distance.get_travel_times import GoogleDistance from google_distance.data_classes import Driving set API_KEY = call getenv string API_KEY function test_sync_run_basic be...
""" These tests only run properly if you have an active google api key set to the environment variable API_KEY='your_api_key' """ import os from google_distance.get_travel_times import GoogleDistance from google_distance.data_classes import Driving API_KEY = os.getenv('API_KEY') def test_sync_run_basic(): dist =...
Python
zaydzuhri_stack_edu_python
import string function remove_punctuation text begin comment convert punctuation chars into a string set punctuation_chars = join string punctuation comment iterate through input text and replace punctuation chars with an empty string for char in punctuation_chars begin if char in text begin set text = replace text ch...
import string def remove_punctuation(text): #convert punctuation chars into a string punctuation_chars = ''.join(string.punctuation) #iterate through input text and replace punctuation chars with an empty string for char in punctuation_chars: if char in text: text = text.replac...
Python
jtatman_500k
comment -*- coding: utf-8 -*- import pkgutil import importlib from datetime import datetime , date , time from numbers import Number from decimal import Decimal from flask import Blueprint function register_blueprints app module_prefix package_path begin string Register all Blueprint instances on the specified Flask ap...
# -*- coding: utf-8 -*- import pkgutil import importlib from datetime import datetime, date, time from numbers import Number from decimal import Decimal from flask import Blueprint def register_blueprints(app, module_prefix, package_path): """Register all Blueprint instances on the specified Flask application fo...
Python
zaydzuhri_stack_edu_python
function check_if_two_hsp_ranges_overlap lists begin set x = set range lists at 0 at 0 lists at 0 at 1 set y = set range lists at 1 at 0 lists at 1 at 1 set intersect = intersection x y set overlap = false if length list intersect > 0 begin set overlap = true end return overlap end function
def check_if_two_hsp_ranges_overlap(lists): x = set(range(lists[0][0], lists[0][1])) y = set(range(lists[1][0], lists[1][1])) intersect = x.intersection(y) overlap = False if len(list(intersect)) > 0: overlap = True return overlap
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string Mostrar en pantalla la cantidad de vocales que existe en una frase dada por el usuario. function vocales frase begin set vocal = list string a string e string i string o string u set lista = list for i in frase begin if i in vocal begin append lista i e...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Mostrar en pantalla la cantidad de vocales que existe en una frase dada por el usuario.""" def vocales(frase): vocal = ['a','e','i','o','u'] lista = [] for i in frase: if i in vocal: lista.append(i) return lista def main(): print("\tEjerccio 13") print() ...
Python
zaydzuhri_stack_edu_python
from flask_sqlalchemy import SQLAlchemy from flask import Flask , request , jsonify from flask_cors import CORS from os import environ comment docker is being used for all microservices set app = call Flask __name__ call CORS app set config at string SQLALCHEMY_DATABASE_URI = get environ string dbURL comment add the ab...
from flask_sqlalchemy import SQLAlchemy from flask import Flask, request, jsonify from flask_cors import CORS from os import environ # docker is being used for all microservices app = Flask(__name__) CORS(app) app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('dbURL') # add the above code if docker is used ap...
Python
zaydzuhri_stack_edu_python
function mail_jet_send self begin set mailjet = call Client auth=tuple api_key api_secret version=string v3.1 comment Build the data object ## set data = dict string Messages list dict string From dict string Email frm ; string Name string Service Account ; string To list dict string Email toemail ; string Name string ...
def mail_jet_send(self): mailjet = Client(auth=(self.api_key, self.api_secret), version='v3.1') ## Build the data object ## data = { 'Messages': [ { "From": { "Email": self.frm, "Name": "Service Acco...
Python
nomic_cornstack_python_v1
comment there are 35 different arc labels, thus |T| = 35 * 2 +1 comment output size = 71 comment hidden size = 100 comment input size: d_words * n_words + d_pos * n_pos comment input words: comment leftmost/rightmost children of the top two words on the stack(not includes buffer)(4) comment if no children inputs equals...
# there are 35 different arc labels, thus |T| = 35 * 2 +1 # output size = 71 # hidden size = 100 # input size: d_words * n_words + d_pos * n_pos # input words: # leftmost/rightmost children of the top two words on the stack(not includes buffer)(4) # if no children inputs equals to 0 # top 2 words on the stack ...
Python
zaydzuhri_stack_edu_python
comment python.exe -m pip install google-api-python-client comment !/usr/bin/python comment This sample executes a search request for the specified search term. comment Sample usage: comment python search.py --q=surfing --max-results=10 comment NOTE: To use the sample, you must provide a developer key obtained comment ...
# python.exe -m pip install google-api-python-client #!/usr/bin/python # This sample executes a search request for the specified search term. # Sample usage: # python search.py --q=surfing --max-results=10 # NOTE: To use the sample, you must provide a developer key obtained # in the Google APIs Console. Search...
Python
zaydzuhri_stack_edu_python
class Point begin function __init__ self i x y begin set i = i set x = x set y = y end function function dist_to self other begin return x - x ^ 2 + y - y ^ 2 ^ 0.5 end function end class set N = integer input set points = list for i in range N begin set tuple x y = map float split input append points call Point i x y...
class Point: def __init__(self, i, x, y): self.i = i self.x = x self.y = y def dist_to(self, other): return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5 N = int(input()) points = [] for i in range(N): x, y = map(float, input().split()) points.append(Point(i, x, ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 import os set _DEEPLEVELS = 5 set data = dict set ranking = dict set listSorted = list function getFile begin global data set sfile = open string poiclicks.txt string r set filebuffer = read sfile close sfile for entry in split filebuffer string begin if find entry string > - 1 begin set tu...
#!/usr/bin/python3 import os _DEEPLEVELS = 5 data = {} ranking = {} listSorted = [] def getFile(): global data sfile = open("poiclicks.txt", "r") filebuffer = sfile.read() sfile.close() for entry in filebuffer.split("\n"): if entry.find(" ") > -1: click, pois = entry.split(" ", 1) else: click, pois = (en...
Python
zaydzuhri_stack_edu_python
function __init__ self tracking_uri=none log_package=true files_to_log=none begin call __init__ set log_package = log_package set files_to_log = files_to_log call set_tracking_uri tracking_uri end function
def __init__( self, tracking_uri: str = None, log_package: bool = True, files_to_log: List[str] = None, ): super().__init__() self.log_package = log_package self.files_to_log = files_to_log mlflow.set_tracking_uri(tracking_uri)
Python
nomic_cornstack_python_v1
function merge_embeddings xdf cat emb w verbose begin if verbose begin print string embeddings category: '%s' embeddings shape %s % tuple cat call shape w end if cat not in list columns begin print string categorical variable '%s' not found in data-frame % cat print type xdf call shape xdf list columns exit 1 end comme...
def merge_embeddings(xdf, cat, emb, w, verbose): if verbose: print("embeddings category: '%s' embeddings shape %s" % (cat, np.shape(w))) if cat not in list(xdf.columns): print("categorical variable '%s' not found in data-frame" % cat) print(type(xdf), np.shape(xdf), list(xdf.columns)) ...
Python
nomic_cornstack_python_v1
from typing import List comment Sliding window. Time: O(n). Space: O(1) class Solution begin function minSubArrayLen self s nums begin set tuple start total min_length = tuple 0 0 0 for tuple i n in enumerate nums begin set total = total + n while total >= s begin set min_length = if expression min_length > 0 then min ...
from typing import List # Sliding window. Time: O(n). Space: O(1) class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: start, total, min_length = 0, 0, 0 for i, n in enumerate(nums): total += n while total >= s: min_length = min(min_leng...
Python
zaydzuhri_stack_edu_python
from math import gcd function problem005 n begin string Returns the smallest integer divisible by {1,..,n} set multiple = 1 for i in range 2 n + 1 begin set multiple = multiple * i // call gcd i multiple end return multiple end function if __name__ == string __main__ begin print call problem005 20 end
from math import gcd def problem005(n): ''' Returns the smallest integer divisible by {1,..,n} ''' multiple = 1 for i in range(2, n + 1): multiple = multiple * i // gcd(i, multiple) return multiple if __name__ == "__main__": print(problem005(20))
Python
zaydzuhri_stack_edu_python
class Item begin function __init__ self item_id name price item_type quantity date_inventory_added monthly_sales=0 begin set item_id = item_id set name = name set price = price set item_type = item_type set quantity = quantity set date_inventory_added = date_inventory_added set monthly_sales = monthly_sales end functio...
class Item: def __init__(self, item_id, name, price, item_type, quantity, date_inventory_added, monthly_sales=0): self.item_id = item_id self.name = name self.price = price self.item_type = item_type self.quantity = quantity self.date_inventory_added = date_inv...
Python
zaydzuhri_stack_edu_python
function export_course_to_directory course_id root_dir begin set store = call modulestore set course = call get_course course_id if course is none begin raise call CommandError string Invalid course_id end set course_name = replace call to_deprecated_string string / string - call export_to_xml store none id root_dir co...
def export_course_to_directory(course_id, root_dir): store = modulestore() course = store.get_course(course_id) if course is None: raise CommandError("Invalid course_id") course_name = course.id.to_deprecated_string().replace('/', '-') export_to_xml(store, None, course.id, root_dir, ...
Python
nomic_cornstack_python_v1
function error_f self start_dates end_dates begin set scores = list for tuple start_date end_date in zip start_dates end_dates begin set population = pop_dict at start_date set trend = call Trend clean_df population country province=province start_date=start_date end_date=end_date call analyse append scores call rmsle ...
def error_f(self, start_dates, end_dates): scores = list() for (start_date, end_date) in zip(start_dates, end_dates): population = self.pop_dict[start_date] trend = Trend( self.clean_df, population, self.country, province=self.province, start_date=...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pylab as plt import padasip as pa comment from sin_data import sin_data comment sin_data() comment creation of data set N = 500 comment input matrix set x = call normal 0 1 tuple N 4 comment noise set v = call normal 0 0.1 N print x comment print (v) comment target set d = 2 * x at ...
import numpy as np import matplotlib.pylab as plt import padasip as pa #from sin_data import sin_data #sin_data() # creation of data N = 500 x = np.random.normal(0, 1, (N, 4)) # input matrix v = np.random.normal(0, 0.1, N) # noise print (x) #print (v) d = 2*x[:] + 0.1*x[:,1] - 4*x[:,2] + 0.5*x[:,3] + v # target f = ...
Python
zaydzuhri_stack_edu_python
function install_katello_agent begin call print_generic string Installing the Katello agent call call_yum string install string katello-agent call enable_service string goferd call exec_service string goferd string restart end function
def install_katello_agent(): print_generic("Installing the Katello agent") call_yum("install", "katello-agent") enable_service("goferd") exec_service("goferd", "restart")
Python
nomic_cornstack_python_v1
function mute_contact token contact duration customerid=none begin set acc_contacts = call get_all token customerid if is instance duration int begin set submit_duration = call create_timestamp duration end else begin set submit_duration = duration end for tuple k v in items acc_contacts begin if k == contact begin for...
def mute_contact(token, contact, duration, customerid=None): acc_contacts = get_all(token, customerid) if isinstance(duration, int): submit_duration = _utils.create_timestamp(duration) else: submit_duration = duration for k, v in acc_...
Python
nomic_cornstack_python_v1
function comments self comments begin set _comments = comments end function
def comments(self, comments): self._comments = comments
Python
nomic_cornstack_python_v1
function get_europepmc_metadata url begin comment <meta content="http://europepmc.org/articles/PMC2819787?pdf=render" name="citation_pdf_url"/> comment <meta content="10.3390/ijerph7010269" name="citation_doi"/> comment <meta content="Int J Environ Res Public Health" name="citation_journal_abbrev"/> set response = text...
def get_europepmc_metadata (url): # <meta content="http://europepmc.org/articles/PMC2819787?pdf=render" name="citation_pdf_url"/> # <meta content="10.3390/ijerph7010269" name="citation_doi"/> # <meta content="Int J Environ Res Public Health" name="citation_journal_abbrev"/> response = requests.get(url...
Python
nomic_cornstack_python_v1
comment tworzenie klucza do sortowania function sorting x begin comment nie dziel przez 0 dla nieważkich płynów; takie płyny są nieskończenie wartościowe w stosunku do swojej masy if x at 1 == 0 begin return inf end return x at 0 / x at 1 end function function knapsack A k begin set w = 0.0 set v = 0.0 sort A key=sorti...
def sorting(x): # tworzenie klucza do sortowania if x[1] == 0: return inf # nie dziel przez 0 dla nieważkich płynów; takie płyny są nieskończenie wartościowe w stosunku do swojej masy return x[0]/x[1] def knapsack(A, k): w = 0.0 v = 0.0 A.sort(key = sorting, reverse = True) for x...
Python
zaydzuhri_stack_edu_python
from collections import Counter function canDistribute nums quantity begin set counts = counter nums set values = list values counts sort quantity reverse=true function dfs index values begin if index == length quantity begin return true end for i in range length values begin if values at i >= quantity at index begin s...
from collections import Counter def canDistribute(nums, quantity): counts = Counter(nums) values = list(counts.values()) quantity.sort(reverse=True) def dfs(index, values): if index == len(quantity): return True for i in range(len(values)): if values[i] >= quant...
Python
jtatman_500k
function rename self old_path new_path begin call rename_file old_path new_path call rename_all_checkpoints old_path new_path end function
def rename(self, old_path, new_path): self.rename_file(old_path, new_path) self.checkpoints.rename_all_checkpoints(old_path, new_path)
Python
nomic_cornstack_python_v1
function new_page self cls **kwargs begin set signature = signature __init__ set filtered_kwargs = dictionary comprehension key : value for tuple key value in items kwargs if key in parameters return call cls browser keyword filtered_kwargs end function
def new_page(self, cls, **kwargs): signature = inspect.signature(cls.__init__) filtered_kwargs = {key: value for key, value in kwargs.items() if key in signature.parameters} return cls(self.browser, **filtered_kwargs)
Python
nomic_cornstack_python_v1
import numpy as np import numpy.linalg as npla import time import matplotlib.pyplot as plt comment size of the matrix to be calculated set SIZE = list 10 50 100 1000 comment create list set cpu_time_numpy = list set cpu_time_mycode = list comment define seed seed 10 comment loop over the size for size in SIZE begin c...
import numpy as np import numpy.linalg as npla import time import matplotlib.pyplot as plt # size of the matrix to be calculated SIZE = [10,50,100,1000] # create list cpu_time_numpy = [] cpu_time_mycode = [] # define seed np.random.seed(10) # loop over the size for size in SIZE : # create the system A = np.ran...
Python
zaydzuhri_stack_edu_python
from random import choice import os set deluxe_dice = list list string A string A string A string F string R string S list string A string A string E string E string E string E list string A string A string F string I string R string S list string A string D string E string N string N string N list string A string E st...
from random import choice import os deluxe_dice = [ ["A", "A", "A", "F", "R", "S"], ["A", "A", "E", "E", "E", "E"], ["A", "A", "F", "I", "R", "S"], ["A", "D", "E", "N", "N", "N"], ["A", "E", "E", "E", "E", "M"], ["A", "E", "E", "G", "M", "U"], ["A", "E", "G", "M", "N", "N"], ["A", "F", ...
Python
zaydzuhri_stack_edu_python
function run server_class=HTTPServer handler_class=CPUUsageHandler begin set server_address = tuple HOST PORT set httpd = call server_class server_address handler_class end function
def run(server_class=HTTPServer, handler_class=CPUUsageHandler): server_address = (settings.HOST, settings.PORT) httpd = server_class(server_address, handler_class)
Python
nomic_cornstack_python_v1
function test_put self begin set cache = call LRUCache 5 assert 0 == size put 1 string aaa assert 1 == size end function
def test_put(self): cache = LRUCache(5) assert 0 == cache.size cache.put(1, 'aaa') assert 1 == cache.size
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import itertools import sys import math from functools import lru_cache comment 1?? comment n = int(input()) comment ?????2?? from queue import Queue set tuple n a b = list map int split input set ll = list comprehension list comprehension - 1 for i in range 401 for j in range 401 comment ...
# -*- coding: utf-8 -*- import itertools import sys import math from functools import lru_cache # 1?? # n = int(input()) # ?????2?? from queue import Queue n, a, b = list(map(int, input().split())) ll = [[-1 for i in range(401)] for j in range(401)] # queue = Queue() ll[0][0] = 0 for i in range(n...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 import sys , csv , math set codesFile = open string ../04c_euclidean/stampsBritannia.csv string r set codes = reader codesFile delimiter=string ; comment header call __next__ set sites = list set listCodes = list for code in codes begin set idSite = code at 0 set nameSite = code at 1 set xSite...
#!/usr/bin/python3 import sys,csv, math codesFile = open('../04c_euclidean/stampsBritannia.csv', 'r') codes = csv.reader(codesFile, delimiter=';') # header codes.__next__() sites = list() listCodes = list() for code in codes: idSite = code[0] nameSite = code[1] xSite = code[2] ySite = code[3] st...
Python
zaydzuhri_stack_edu_python
string This script process 3DIRCA dataset. The end result is some niftis with only liver and lesion labels (e.g., label01.nii) Label values: 0,1,2 for bg,liver,lesion resp. Usage : cd into the directory of the IRCA dataset (usually folder named 3Dircadb1) then run the script : python /path/to/irca_to_nii.python from ma...
""" This script process 3DIRCA dataset. The end result is some niftis with only liver and lesion labels (e.g., label01.nii) Label values: 0,1,2 for bg,liver,lesion resp. Usage : cd into the directory of the IRCA dataset (usually folder named 3Dircadb1) then run the script : python /path/to/irca_to_nii.python """ fr...
Python
zaydzuhri_stack_edu_python
import time call clock set ijk_table = dict tuple string 1 string 1 string 1 ; tuple string -1 string 1 string -1 ; tuple string 1 string i string i ; tuple string -1 string i string -i ; tuple string 1 string j string j ; tuple string -1 string j string -j ; tuple string 1 string k string k ; tuple string -1 string k ...
import time time.clock() ijk_table = { ('1','1') : '1', ('-1','1') : '-1', ('1','i') : 'i', ('-1','i') : '-i', ('1','j') : 'j', ('-1','j') : '-j', ('1','k') : 'k', ('-1','k') : '-k', ('i','1') : 'i', ('-i','1') : '-i', ('i','i') : '-1', ('-i','i') : '1', ('i','j') : 'k', ('-i','...
Python
zaydzuhri_stack_edu_python
from DBbridge.ConsultasCassandra import ConsultasCassandra from ProcesadoresTexto.LimpiadorTweets import LimpiadorTweets from Config.Conf import Conf import luigi class GenerateTextByLang extends Task begin string GenerateTextByLang genera un fichero de texto con los tweets con un sentimiento definido (positivo o negat...
from DBbridge.ConsultasCassandra import ConsultasCassandra from ProcesadoresTexto.LimpiadorTweets import LimpiadorTweets from Config.Conf import Conf import luigi class GenerateTextByLang(luigi.Task): """ GenerateTextByLang genera un fichero de texto con los tweets con un sentimiento definido (positivo o negativ...
Python
zaydzuhri_stack_edu_python
comment Combination of a given length import itertools comment list of which combination is to be found set li = list string 23 string 97 string 26 string 27 comment length of combinations set r = 3 list call combinations li r comment OUTPUT list tuple string 23 string 97 string 26 tuple string 23 string 97 string 27 t...
#Combination of a given length import itertools li = ['23', '97', '26', '27'] #list of which combination is to be found r = 3 #length of combinations list(itertools.combinations(li,r)) #OUTPUT [('23', '97', '26'), ('23', '97', '27'), ('23', '26', '27'), ('97', '26', '27')] #All possible combinations except null com...
Python
zaydzuhri_stack_edu_python
string anova.py Learning what anova does import math import numpy as np from matplotlib import pyplot as plt import statsmodels.stats.anova as anova from scipy.stats import t , ttest_1samp from scipy.optimize import minimize from scipy.special import gamma from scipy.misc import factorial comment understanding gamma fu...
''' anova.py Learning what anova does ''' import math import numpy as np from matplotlib import pyplot as plt import statsmodels.stats.anova as anova from scipy.stats import t, ttest_1samp from scipy.optimize import minimize from scipy.special import gamma from scipy.misc import factorial # understanding gamma func...
Python
zaydzuhri_stack_edu_python
import sys from textprocessing import * function wrap begin if length argv == 3 begin set file = open argv at 2 string r end if length argv == 2 begin set file = stdin end set width = integer argv at 1 set line = read line file while line begin set tuple line1 line = call wrap_on line width end end function
import sys from textprocessing import * def wrap(): if len( sys.argv ) == 3: file = open(sys.argv[2],'r') if len( sys.argv ) == 2: file = sys.stdin width = int(sys.argv[1]) line = file.readline() while line: line1,line = wrap_on(line,width)
Python
zaydzuhri_stack_edu_python
comment message = "我是齐天大圣" comment for item in message: comment print(item) set num = input string 请输入多位数: set count = 0 for item in num begin set count = count + integer item end print count
# message = "我是齐天大圣" # for item in message: # print(item) # num = input("请输入多位数:") count = 0 for item in num: count += int(item) print(count)
Python
zaydzuhri_stack_edu_python
function step self closure=none begin set loss = none if closure is not none begin with enable grad begin set loss = call closure end end for group in param_groups begin set grads = list set states = list set exp_avg = list set exp_avg_sq = list set params_with_grad = list for p in group at string params begin if ...
def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: grads = [] states = [] exp_avg = [] exp_avg_sq = [] params_with_gr...
Python
nomic_cornstack_python_v1
function addRcpt self rcpt esmtpAdd=string begin if esmtpAdd begin if not SMFIF_ADDRCPT_PAR ? _opts ? _mtaopts begin print string Add recipient par called without the proper opts set return end set req = SMFIR_ADDRCPT_PAR + rcpt + b'\x00' + esmtpAdd + b'\x00' set req = call pack_uint32 length req + req end else begin i...
def addRcpt(self , rcpt , esmtpAdd=''): if esmtpAdd: if not SMFIF_ADDRCPT_PAR & self._opts & self._mtaopts: print('Add recipient par called without the proper opts set') return req = SMFIR_ADDRCPT_PAR + rcpt + b'\0' + esmtpAdd + b'\0' req = pac...
Python
nomic_cornstack_python_v1
function random_colors N bright=true begin set brightness = if expression bright then 1.0 else 0.7 set hsv = list comprehension tuple i / N 1 brightness for i in range N set colors = list map lambda c -> call hsv_to_rgb *c hsv shuffle random colors return colors end function
def random_colors(N, bright=True): brightness = 1.0 if bright else 0.7 hsv = [(i / N, 1, brightness) for i in range(N)] colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv)) random.shuffle(colors) return colors
Python
nomic_cornstack_python_v1
function object_id self begin return get pulumi self string object_id end function
def object_id(self) -> pulumi.Output[str]: return pulumi.get(self, "object_id")
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python string Run Sextractor on simulated files and compare with known positions. import subprocess import os import os.path import re import numpy as np import numpy.lib.recfunctions as rec import pylab import pyfits import csv_parse import fvmapping function run_sex filename begin string Run sex...
#!/usr/bin/env python """ Run Sextractor on simulated files and compare with known positions. """ import subprocess import os import os.path import re import numpy as np import numpy.lib.recfunctions as rec import pylab import pyfits import csv_parse import fvmapping def run_sex(filename): """ Run sextracto...
Python
zaydzuhri_stack_edu_python
async function _create_new_migration app_config auto=false begin set _id = string format time now string %Y-%m-%dT%H:%M:%S comment Originally we just used the _id as the filename, but colons aren't comment supported in Windows, so we need to sanitize it. We don't want to comment change the _id format though, as it woul...
async def _create_new_migration(app_config: AppConfig, auto=False) -> None: _id = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") # Originally we just used the _id as the filename, but colons aren't # supported in Windows, so we need to sanitize it. We don't want to # change the _id format though...
Python
nomic_cornstack_python_v1
comment Autostereogram Generator from PIL import Image , ImageDraw import noise import random class stereogram extends object begin set mu = 1 / 3.0 function __init__ self depth_map pattern=none DPI=75 verbose=true begin set DPI = DPI set eye_separation = integer round 2.5 * DPI 0 comment self.eye_separation = 2.5*DPI ...
## Autostereogram Generator from PIL import Image, ImageDraw import noise import random class stereogram(object): mu = (1/3.) def __init__(self,depth_map,pattern=None,DPI=75,verbose=True): self.DPI = DPI self.eye_separation = int(round(2.5*DPI,0)) #self.eye_separation = 2.5*DPI ...
Python
zaydzuhri_stack_edu_python
function maximum self begin return get properties string maximum end function
def maximum(self): return self.properties.get('maximum')
Python
nomic_cornstack_python_v1
function clean_cmdline cmdline begin return replace replace cmdline string string \r string string \n end function
def clean_cmdline(cmdline): return cmdline.replace('\r', '\\r').replace('\n', '\\n')
Python
nomic_cornstack_python_v1
from unittest import TestCase import unittest from power_of_two import Solution class TestSolution extends TestCase begin function test_powerOfTwoCase1 self begin set sol = call Solution assert equal call isPowerOfTwo 1 true assert equal call isPowerOfTwo - 16 false end function end class if __name__ == string __main__...
from unittest import TestCase import unittest from power_of_two import Solution class TestSolution(TestCase): def test_powerOfTwoCase1(self): sol = Solution() self.assertEqual(sol.isPowerOfTwo(1), True) self.assertEqual(sol.isPowerOfTwo(-16), False) if __name__ == '__main__': unittest....
Python
zaydzuhri_stack_edu_python
function test_report_with_verbose self begin comment Setup set key_phrases = list string Generating\sreport\s\.\.\. string \(1/2\)\sEvaluating\sColumn\sShapes string \(2/2\)\sEvaluating\sColumn\sPair\sTrends string Overall\sQuality\sScore:\s80\.51% string Properties: string -\sColumn\sShapes:\s81\.56% string -\sColumn\...
def test_report_with_verbose(self): # Setup key_phrases = [ r'Generating\sreport\s\.\.\.', r'\(1/2\)\sEvaluating\sColumn\sShapes', r'\(2/2\)\sEvaluating\sColumn\sPair\sTrends', r'Overall\sQuality\sScore:\s80\.51%', r'Properties:', r...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import cgi , cgitb , os call enable set form = call FieldStorage
#!/usr/bin/python import cgi,cgitb,os cgitb.enable() form=cgi.FieldStorage()
Python
zaydzuhri_stack_edu_python
from collections import defaultdict with open string ../input/day1.txt string r as inputFile begin set data = list comprehension integer x for x in read lines inputFile end set sums = default dictionary list comment Part 1 for first in data begin for second in data at slice 1 : : begin if first == second begin contin...
from collections import defaultdict with open("../input/day1.txt", 'r') as inputFile: data = [int(x) for x in inputFile.readlines()] sums = defaultdict(list) # Part 1 for first in data: for second in data[1:]: if first == second: continue sums[first+second].append((first, second)) assert(len(...
Python
zaydzuhri_stack_edu_python
import csv import os import math import loss_rate_functions as func comment This will be to calculate the loss rate in the effects of M comment Need to write the following to a csv file comment Loss of L Diff. H - L comment 500 0 - 1 0 - 1 0 - 1 comment Directory where results are stored set pathTo = string /home/mario...
import csv import os import math import loss_rate_functions as func #This will be to calculate the loss rate in the effects of M #Need to write the following to a csv file # Loss of L Diff. H - L # 500 0 - 1 0 - 1 0 - 1 #Directory where results are stored pathTo = "/home/mario/Documents/res...
Python
zaydzuhri_stack_edu_python
import logging import logging.config import uuid from typing import Any , Dict , MutableMapping , Tuple class ContextLoggingAdapter extends LoggerAdapter begin string Include a contextual identifier for grouping related log entries In an environment where logs from multiple sources are intertwined/aggregated with log o...
import logging import logging.config import uuid from typing import Any, Dict, MutableMapping, Tuple class ContextLoggingAdapter(logging.LoggerAdapter): """ Include a contextual identifier for grouping related log entries In an environment where logs from multiple sources are intertwined/aggregated ...
Python
zaydzuhri_stack_edu_python
set message = string This is a string print message set message = string This is also a string print message
message = "This is a string" print(message) message = 'This is also a string' print (message)
Python
zaydzuhri_stack_edu_python
function lastChar cursor n=1 begin if call atBlockStart begin return string end else begin set cur_tmp = call QTextCursor cursor call clearSelection for i in range n - 1 begin call movePosition Left MoveAnchor if call atBlockStart begin return string end end call movePosition Left KeepAnchor set text = call selectedT...
def lastChar(cursor,n=1): if cursor.atBlockStart(): return '\n' else : cur_tmp=QtGui.QTextCursor(cursor) cur_tmp.clearSelection() for i in range(n-1): cur_tmp.movePosition(QtGui.QTextCursor.Left, QtGui.QTextCursor.MoveAnchor) if cur_tmp.atBlockStart(): return '\n' cur_tmp.mov...
Python
nomic_cornstack_python_v1
string First attempt at using boosted decision trees to predict Instructions on installing xgboost: http://xgboost.readthedocs.org/en/latest/python/python_intro.html import csv import gc import numpy import numpy.random as rand import xgboost import to_output import sklearn.feature_selection as select comment read the ...
""" First attempt at using boosted decision trees to predict Instructions on installing xgboost: http://xgboost.readthedocs.org/en/latest/python/python_intro.html """ import csv import gc import numpy import numpy.random as rand import xgboost import to_output import sklearn.feature_selection as select #read the csv ...
Python
zaydzuhri_stack_edu_python
function test_ma_email_s_mailem self begin set zakaznik = call Zakaznici email=string neco@neco.cz call assertIs call ma_email true end function
def test_ma_email_s_mailem(self): zakaznik = Zakaznici(email="neco@neco.cz") self.assertIs(zakaznik.ma_email(), True)
Python
nomic_cornstack_python_v1
function build_sparse_model symbolic_description properties=none begin if not undefined_constants_are_graph_preserving begin raise call StormError string Program still contains undefined constants end if properties begin set formulae = list comprehension if expression is instance prop Property then raw_formula else pro...
def build_sparse_model(symbolic_description, properties=None): if not symbolic_description.undefined_constants_are_graph_preserving: raise StormError("Program still contains undefined constants") if properties: formulae = [(prop.raw_formula if isinstance(prop, Property) else prop) for prop in p...
Python
nomic_cornstack_python_v1
string Test that the manifest file is correctly structured and refers to schemas that exist. from pathlib import Path import asdf import pytest import yaml set RESOURCES_ROOT = parent / string resources decorator call parametrize string manifest_path glob RESOURCES_ROOT / string manifests string **/*.yaml function test...
""" Test that the manifest file is correctly structured and refers to schemas that exist. """ from pathlib import Path import asdf import pytest import yaml RESOURCES_ROOT = Path(__file__).absolute().parent.parent / "resources" @pytest.mark.parametrize("manifest_path", (RESOURCES_ROOT / "manifests").glob("**/*.yam...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt import sys append path string ../../scripts from virialcoeffs import VirialCoeffs set prefix = string ../../2020_03_19/raw_data_processing/raw_data/ set tcut = 1000000 set fp = 0 set tuple fig axarr = call subplots 2 sharex=true set rhos = list string 0.05 string 0.1 s...
import numpy as np import matplotlib.pyplot as plt import sys sys.path.append('../../scripts') from virialcoeffs import VirialCoeffs prefix = '../../2020_03_19/raw_data_processing/raw_data/' tcut = 1000000 fp = 0 fig,axarr = plt.subplots(2,sharex=True) rhos = ['0.05','0.1','0.2','0.4'] rhonums = np.array(rhos,...
Python
zaydzuhri_stack_edu_python