seq_id
stringlengths
4
11
text
stringlengths
113
2.92M
repo_name
stringlengths
4
125
sub_path
stringlengths
3
214
file_name
stringlengths
3
160
file_ext
stringclasses
18 values
file_size_in_byte
int64
113
2.92M
program_lang
stringclasses
1 value
lang
stringclasses
93 values
doc_type
stringclasses
1 value
stars
int64
0
179k
dataset
stringclasses
3 values
pt
stringclasses
78 values
36961636463
import os.path base_path = 'scispacy_pipeline_output/' #function to parse the scipacy output(the text files produced) def parse_output(n): cui_dict = {} for j in range(0,n): #select a patient text file path pat_path = base_path + "patient" +str(j) + ".txt" if os.path.is...
Sep905/pre-trained_wv_with_kb
conceptExtraction_entityLinking/parsing_scispacy_output.py
parsing_scispacy_output.py
py
3,761
python
en
code
0
github-code
36
29673546988
import boto3 import gzip import json import os from math import ceil from pymongo import MongoClient def load_file(filepath): documents = {} lines = open(filepath, 'r').read().splitlines() for line in lines: columns = line.split('\t') documents[columns[0]] = columns[1] return documents...
edgargaticaCU/DocumentMetadataAPI
data_checker.py
data_checker.py
py
3,767
python
en
code
0
github-code
36
41826934545
# import sqlite library import sqlite3 # create a database and make a connection. conn = sqlite3.connect("first.db") cursor = conn.cursor() sql = """UPDATE programs SET program_level = 'Master''s' WHERE program_name IN ('Anthropology', 'Biology')""" cursor.execute(sql) sql = """INSERT INTO students(student, id_prog...
Ngue-Um/DHRI-June2018-Courses-databases
scripts/challenge.py
challenge.py
py
430
python
en
code
0
github-code
36
70064817065
import jsonschema from API.validation import error_format class Validate_AddChannel(): def __init__(self, data): self.data = data self.schema = { "type": "object", "properties": { "name": {"type": "string"}, "type": {"type": "string"...
OStillman/ODACShows
API/validation/add_channel_validation.py
add_channel_validation.py
py
1,067
python
en
code
0
github-code
36
22453632625
import urllib from bs4 import BeautifulSoup import re def fetch(url): return urllib.urlopen(url).read() def extractss(data): regex = '\"storyboard\_spec\"\:.+' code = re.findall(regex,data)[0].split(',')[0] highestres = code.split('|')[-1] images = int(highestres.split('#')[2]) + 1 imagespersh...
karthiknrao/videocontext
videositecrawlers.py
videositecrawlers.py
py
1,042
python
en
code
0
github-code
36
71038363623
import collections import numpy as np from math import pi def log_gaussian_prob(obs, mu, sig): num = (obs - mu) ** 2 denum = 2 * sig ** 2 # norm = 1 / sqrt(2 * pi * sig ** 2) # prob = norm * exp(-num/denum) log_prob = (-num / denum) + 0.5 * (np.log(2) + np.log(pi) + 2 * np.log(sig)) return log_prob clas...
Xiaohong-Deng/algorithms
AIML/gaussianNaiveBayes/classifier.py
classifier.py
py
3,774
python
en
code
0
github-code
36
8451867993
from collections import deque from collections import namedtuple PairedTasks = namedtuple('PairedTasks', ('task_1', 'task_2')) def compute_task_assignment(task_durations: list): durations = deque(sorted(task_durations)) total_time = 0 while durations: total_time = max(total_time, durations.pople...
kashyapa/coding-problems
epi/revise-daily/6_greedy_algorithms/1_compute_optimum_task_assignment.py
1_compute_optimum_task_assignment.py
py
594
python
en
code
0
github-code
36
73290357865
import json import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt # 读取JSON文件 with open('./47_data.json') as f: data = json.load(f) # 将数据转换为NumPy数组 images = np.array(data) # 创建一个2x4的子图,用于显示8张图片 fig, axs = plt.subplots(2, 4) # 迭代显示每张图片 for i, ax in enumerate(axs.flatten()): ...
LazySheeeeep/Trustworthy_AI-Assignments
1/testing_images_showcase.py
testing_images_showcase.py
py
696
python
zh
code
0
github-code
36
4193791513
import pandas as pd import numpy as np # # series--->dataframe # d = {'one': pd.Series([1., 2., 3.], index=['a', 'b', 'c']), # 'two': pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])} # df = pd.DataFrame(d) # print(df) # print(df.index) # print(df.columns) # # index:行标签 columns:列标签 # # dict ---> dataframe # ...
Marcia0526/data_analyst
dataframe_demo.py
dataframe_demo.py
py
4,426
python
en
code
0
github-code
36
30466827827
class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: if not root: return [] path = [] res = [] self.dfs(root, path, res) return res def dfs(self, root, path, res): path.append(str(root.val)) # base case if not root.l...
dundunmao/LeetCode2019
257. binary tree paths.py
257. binary tree paths.py
py
3,061
python
en
code
0
github-code
36
27275697128
"""Very simple example using a pair of Lennard-Jones particles. This script has several pieces to pay attention to: - Importing the pieces from wepy to run a WExplore simulation. - Definition of a distance metric for this system and process. - Definition of the components used in the simulation: resampler, boundary...
ADicksonLab/wepy
info/examples/Lennard_Jones_Pair/source/we.py
we.py
py
7,753
python
en
code
44
github-code
36
21130491503
import psycopg2 from config import host, user, password, db_name try: # подключение к существующей БД connection = psycopg2.connect( host=host, user=user, password=password, database=db_name ) connection.autocommit = True # курсор для предоставления операций над БД ...
Tosic48/pizzeria
main2.py
main2.py
py
3,728
python
ru
code
0
github-code
36
9194727466
import unittest import torch import lightly class TestNestedImports(unittest.TestCase): def test_nested_imports(self): # active learning lightly.active_learning.agents.agent.ActiveLearningAgent lightly.active_learning.agents.ActiveLearningAgent lightly.active_learning.config.samp...
tibe97/thesis-self-supervised-learning
tests/imports/test_nested_imports.py
test_nested_imports.py
py
3,548
python
en
code
2
github-code
36
3955175218
# -*- coding: utf-8 -*- import argparse import os, sys import codecs from collections import Counter import json import numpy as np import torch import copy install_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) print(install_path) sys.path.append(install_path) i...
ZiJianZhao/Unaligned-SLU
dstc3/text/stat.py
stat.py
py
1,886
python
en
code
1
github-code
36
74328503143
import logging import pandas as pd from openfisca_ceq.tools.data import config_parser, year_by_country from openfisca_ceq.tools.data_ceq_correspondence import ( ceq_input_by_harmonized_variable, ceq_intermediate_by_harmonized_variable, data_by_model_weight_variable, model_by_data_id_variable, mo...
openfisca/openfisca-ceq
openfisca_ceq/tools/data/income_loader.py
income_loader.py
py
5,243
python
en
code
0
github-code
36
41896592263
import random words = ["skykreeper", "winterland", "starwars"] chosen_words = random.choice(words) stages=[''' <====> | | O | /|\ | / \ | | ============ ''', ''' <====> | | O | /|\ | / | | ============ ''', ''' <====> ...
Kumar6174/Hangman-Game-Using-Python
Hangman_Game.py
Hangman_Game.py
py
1,524
python
en
code
0
github-code
36
2861916089
''' В файле config.py располагаются изменяемые значения для необходимой настройки скрипта ''' # Для GUI-приложения # инфо о таблице, "БД" и шаблонах path_db = 'created_text_docs' path_db_bta = 'Созданные документы БТА' path_db_main_KS = f'{path_db}/Круглосуточный стационар' path_db_main_DS = f'{path_db}/Дневной стацион...
Spike2250/WoM
wom/settings/config.py
config.py
py
3,136
python
ru
code
0
github-code
36
35609459703
import streamlit as st import cv2 import time import sys import os import numpy as np import matplotlib.pyplot as plt from PIL import Image from streamlit_lottie import st_lottie # Initialize the parameters confThreshold = 0.2 #Confidence threshold nmsThreshold = 0.4 #Non-maximum suppression threshold inpWidth = 4...
nlkkumar/vehicle-class-yolov4
nlk-vehi-class-classification.py
nlk-vehi-class-classification.py
py
7,582
python
en
code
1
github-code
36
41646833738
import datetime, requests, csv, argparse class MarketwatchScraper(): def __init__(self, stock: str = "AAPL", timeout: int = 1) -> None: self.stock = stock self.timeout = timeout pass def scrape(self) -> None: self.saveToFile(self.getURLS()) def saveToFile(self, ...
chaarlottte/MarketWatch-Scraper
scrape.py
scrape.py
py
2,814
python
en
code
6
github-code
36
18252810201
from functools import lru_cache from typing import List class Solution: def maxCoins(self, nums: List[int]) -> int: @lru_cache(None) def dfs(l, r): if l > r: return 0 # if (l, r) in dic: # return dic[(l, r)] # dic[(l, r)] = 0 ...
hujienan/Jet-Algorithm
leetcode/312. Burst Balloons/index.py
index.py
py
797
python
en
code
0
github-code
36
23380020206
from tkinter import * class nutnhan: def __init__(self,master): frame=Frame(master) frame.pack() self.printbutton=Button(frame,text="print",command=self.printmassage) self.printbutton.pack() self.quitbutton=Button(frame,text="quit",command=frame.quit) self.quitbutton.pack() def printmassag...
nguyenbuitk/python-tutorial
03_LT/Game/Tkinter/tkinter 08 class.py
tkinter 08 class.py
py
401
python
en
code
0
github-code
36
34181109892
#tempurature range is 4-95 degrees C #we use a GEN2 tempurature module #tolerance on read about 5 degrees for heating (at least with IR thermometer) # can hold steady at a tempurature really well though would need to test more at differing tempurature #idling tempurature 55 C can hold within .5 C of tem...
MyersResearchGroup/OpenTrons_OT2_Protocols
temperature_module/tempurature_module.py
tempurature_module.py
py
1,122
python
en
code
0
github-code
36
16172950617
"""This script creates a regression test over metarl-TRPO and baselines-TRPO. Unlike metarl, baselines doesn't set max_path_length. It keeps steps the action until it's done. So we introduced tests.wrappers.AutoStopEnv wrapper to set done=True when it reaches max_path_length. We also need to change the metarl.tf.sampl...
icml2020submission6857/metarl
tests/benchmarks/metarl/tf/algos/test_benchmark_trpo.py
test_benchmark_trpo.py
py
12,332
python
en
code
2
github-code
36
29013837779
import pickle import math if __name__ == '__main__': with open('dict.txt', 'rb') as f: dict_ = pickle.load(f) data = [] with open('../NSL-KDD/KDDTrain+_20Percent.arff', 'r') as f: #KDDTest-21 KDDTrain+ KDDTest+ KDDTrain+_20Percent for line in f.readlines(): if line[0] != '@': ...
MrDuGitHub/NSL-KDD
code/norm.py
norm.py
py
3,451
python
en
code
0
github-code
36
33521363177
import os, re, importlib.util import LogManager from Module import Module from ModuleThreadHandler import ModuleThreadHandler, ThreadTask class ModuleRunner: def __init__(self, parent): self.parent = parent self.logger = LogManager.create_logger('MODULES') self.closing = False self.thread_handler ...
gregormaclaine/AutoHome
ModuleRunner.py
ModuleRunner.py
py
2,346
python
en
code
0
github-code
36
3095634142
import re from mparser import * from mlexer import * # if re.match(r'.+ while .+', "x = x + 1 if x < 10 while k == 0"): # print('MATCH') # else: # print('NO MATCH') lex = Lexer() par = Parser(lex) code = "x = x + 1 if x < 10 while y < 5" code = ''' while x > 5 x = 1 y = x - 1 end ''' code = ''' if x < 5 ...
ptq204/CS320-Ruby-lexer-parser
main.py
main.py
py
539
python
en
code
0
github-code
36
30452253568
import pandas as pd import requests from bs4 import BeautifulSoup u = 'https://www.amazon.in/OnePlus-Nord-Gray-128GB-Storage/product-reviews/B08695ZSP6/ref=cm_cr_arp_d_paging_btm_next_2?ie=UTF8&reviewerType=all_reviews&pageNumber=' def amazon(link,Number_of_pages): r={} allreview1 = pd.DataFrame(r)...
SHRIKAR5/Amazon-review-webscraping
amazon_review-webscraping.py
amazon_review-webscraping.py
py
2,060
python
en
code
0
github-code
36
496383977
from dagster_datadog import datadog_resource from dagster import ModeDefinition, execute_solid, solid from dagster.seven import mock @mock.patch('datadog.statsd.timing') @mock.patch('datadog.statsd.timed') @mock.patch('datadog.statsd.service_check') @mock.patch('datadog.statsd.set') @mock.patch('datadog.statsd.distr...
helloworld/continuous-dagster
deploy/dagster_modules/libraries/dagster-datadog/dagster_datadog_tests/test_resources.py
test_resources.py
py
2,747
python
en
code
2
github-code
36
5054088480
from abei.implements.service_basic import ServiceBasic from abei.implements.util import ( FileLikeWrapper, LazyProperty, ) from abei.interfaces import ( IProcedure, IProcedureLink, IProcedureFactory, IProcedureJointFactory, IProcedureBuilder, service_entry as _, ) from .procedure_joint_b...
mind-bricks/abei
abei/implements/procedure_builder.py
procedure_builder.py
py
8,029
python
en
code
0
github-code
36
29390462152
class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: graph = defaultdict(defaultdict) for (dividend, divisor), value in zip(equations, values): graph[dividend][divisor] = value graph[divisor][divide...
AnotherPianist/LeetCode
0399-evaluate-division/0399-evaluate-division.py
0399-evaluate-division.py
py
1,336
python
en
code
1
github-code
36
15991381065
import torch.nn as nn try: from .resnet import resnet50_v1b except: from resnet import resnet50_v1b import torch.nn.functional as F import torch class SegBaseModel(nn.Module): r"""Base Model for Semantic Segmentation Parameters ---------- backbone : string Pre-trained dilated backbone...
zyxu1996/Efficient-Transformer
models/danet.py
danet.py
py
7,495
python
en
code
67
github-code
36
74201126823
import re import os def get_ckpt_epoch( checkpoint_dir ): epochs_list = [0] for fname in os.listdir(checkpoint_dir): mtc = re.match( r'.*model\.(\d+)', fname ) if not mtc: continue epochs_list.append(int( mtc.groups()[0]) ) return max(epochs_list) def clear_old_ckpt( ...
cmranieri/flood-detection
src/ml_utils.py
ml_utils.py
py
673
python
en
code
0
github-code
36
13125376994
"""Implementation of Rectangle class""" class Rectangle: """A Rectangle. Args: width: width of rectangle height: height of rectangle Both should be positive numbers """ def __init__(self, width, height): self.width = width self.height = height def area(...
pawel123789/day7
1.py
1.py
py
495
python
en
code
0
github-code
36
31453786297
import os, sys, pygame class Animation: def __init__(self, names_files, cd_images, screen, width_screen, height_screen, sounds, colorkey=None, music=None): self.images = [] for elem in names_files: self.images.append(pygame.transform.scale(self.load_image(elem, colorkey=colorkey), (wid...
ScarletFlame611/1984-game
animation_comics.py
animation_comics.py
py
2,789
python
en
code
0
github-code
36
74873018984
from flask_wtf import Form from wtforms import StringField,BooleanField,PasswordField,IntegerField,SelectField from wtforms.validators import DataRequired, ValidationError from webapp.Models.db_basic import Session from webapp.Models.prod_cat import Prod_cat from webapp.Models.prod_sub_cat import Prod_sub_cat def lev...
kangnwh/Emall
webapp/viewrouting/admin/forms/category_forms.py
category_forms.py
py
2,511
python
en
code
1
github-code
36
38642289342
import nltk import pickle from utils import tokenize_document resume_file = open('../assets/resume.txt', 'r') resume = resume_file.read() resume_file.close() tokenizer = nltk.RegexpTokenizer(r'\w+') resume_tokenized = tokenize_document(resume, tokenizer) print(resume_tokenized) pickle.dump(resume_tokenized, open('../...
anishLearnsToCode/stop-words-removal
src/driver.py
driver.py
py
352
python
en
code
0
github-code
36
32480271471
from django.urls import include, path from rest_framework.routers import DefaultRouter from .views import (IngredientViewSet, LikedRecipeDetailView, RecipeViewSet, SubscribtionListView, SubscriptionDetailView, TagViewSet) v1_router = DefaultRouter() v1_router.register( 'tags', TagViewSet, ...
JCoffeeYP/foodgram-project-react
backend/cookbook/urls.py
urls.py
py
917
python
en
code
0
github-code
36
27016642063
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 1 17:38:34 2019 @author: Martín Márquez Cervantes """ print("UNion de las tres compuertas, aun por trabajar") import matplotlib.pyplot as plt import numpy as np class MyNeuron: #VAriable w global WG=0 xTestPredic=0 #entrenamie...
MarqCervMartin/RedesNeuronales
Laboratorio5/CompuertaAndOrNot.py
CompuertaAndOrNot.py
py
5,014
python
es
code
0
github-code
36
71845268583
import structmanager.sol200.output_codes as output_codes_SOL200 def constrain_buckling(panelcomp, eig=1.0): OUTC = output_codes_SOL200.OUTC eid = panelcomp.get_central_element().eid dcid = panelcomp.constraints['buckling'] # reading membrane force Nxx code_Nxx = OUTC['FORCE']['CQUAD4']['Membra...
compmech/structmanager
structmanager/optimization/sol200/elements2d/composite_panel/constraints.py
constraints.py
py
1,966
python
en
code
1
github-code
36
21683749340
#!/usr/bin/env python3 import os import re import click import json import logging import zipfile import portalocker import contextlib import traceback import imghdr import multiprocessing import functools import threading import time import sys import ctypes import psutil from pathlib import Path from functools impo...
poke1024/origami
origami/batch/core/processor.py
processor.py
py
16,273
python
en
code
69
github-code
36
33905718453
days_vacation = int(input()) left_money = 0 for day in range(1, days_vacation+1): max_money = 60 count_products = 0 if left_money > 0: max_money += left_money while max_money > 0: price_product = input() if price_product == "Day over": if max_money > 0: ...
IvayloSavov/Programming-basics
exams/27_28_July/trip_expenses.py
trip_expenses.py
py
836
python
en
code
0
github-code
36
22840734386
from urllib.request import urlopen import json def E(X): ''' :param X: [(xi, pi), ...] :return: int expected value of random variable X ''' return sum([e[0] * e[1] for e in X]) url = 'https://api.blockchain.info/charts/market-price?timespan=1year&format=json' http_file = urlopen(url) lines = ht...
naurlaunim/other
btc_calc.py
btc_calc.py
py
922
python
en
code
0
github-code
36
41554946028
# coding: utf8 # Create by Narata on 2018/4/10 import urllib.request import re def get_url_list(): url = 'http://www.budejie.com/video/' req = urllib.request.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Sa...
narata/spider
demo/video.py
video.py
py
663
python
en
code
0
github-code
36
18483593432
import random import numpy as np import matplotlib.pyplot as plt from PIL import Image, ImageFilter from torchvision import datasets, transforms class RandomGaussianBlur(object): def __call__(self, image): if random.random() < 0.5: image = image.filter(ImageFilter.GaussianBlur( ...
TWSFar/GhostNet-MNIST
datasets/mnist.py
mnist.py
py
1,738
python
en
code
5
github-code
36
8754323425
# -*- coding: utf-8 -*- # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import re from odoo import api, fields, models class OFCalculationHeatLossLine(models.Model): _name = 'of.calculation.heat.loss.line' _description = u"Appareils compatibles pour la déperdition de chaleur" calculation...
odof/openfire
of_calculation_heat_loss/models/of_calculation_heat_loss_line.py
of_calculation_heat_loss_line.py
py
1,369
python
en
code
3
github-code
36
1098578046
# # This file is part of the Robotic Observatory Control Kit (rockit) # # rockit is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ro...
warwick-one-metre/domed
rockit/dome/constants.py
constants.py
py
4,220
python
en
code
0
github-code
36
31638903937
import json import numpy as np import matplotlib.pyplot as plt def read_file(): # 读取数据 hero_list = json.load(open("./file/heroskin.json", 'r', encoding='utf-8')) hero_skin_data = hero_list["hero_skin_data"] return hero_skin_data def get_hero_skin_count(): hero_skin_data = read_file() # 所有英雄、皮...
N-Wind/League-of-Legends
hero/heroSkinLine.py
heroSkinLine.py
py
2,138
python
en
code
0
github-code
36
70767542184
from sokoban.fast_sokoban import extract_all_patterns import numpy as np class MinimalLocalForwardModel: def __init__(self, model, mask, span, remember_predictions=False): self.model = model self.mask = mask self.span = span self.remember_predictions = remember_predictions ...
ADockhorn/Active-Forward-Model-Learning
activestateexploration/simple_lfm.py
simple_lfm.py
py
2,206
python
en
code
0
github-code
36
23406422554
# -*- coding: utf-8 -*- import cottonformation as ctf from cottonformation.res import iam, awslambda # create a ``Template`` object to represent your cloudformation template tpl = ctf.Template( Description="Aws Lambda Versioning Example", ) iam_role_for_lambda = iam.Role( "IamRoleForLambdaExecution", rp_...
MacHu-GWU/Dev-Exp-Share
docs/source/01-AWS/01-All-AWS-Services-Root/01-Compute/02-AWS-Lambda-Root/05-Versioning/deploy.py
deploy.py
py
1,506
python
en
code
3
github-code
36
1316799012
# !pip install xlsxwriter import pandas as pd df = pd.DataFrame([{'foo':i,'bar':2*i,'baz':3*i} for i in range(76)]) writer = pd.ExcelWriter('sample_xl.xlsx',engine='xlsxwriter') # Convert the dataframe to an XlsxWriter Excel object. df.to_excel(writer, sheet_name='Sheet1') # Get the xlsxwriter workbook and worksheet...
rtahmasbi/Applications_Tempalete
P_ExcelWriter.py
P_ExcelWriter.py
py
1,569
python
en
code
0
github-code
36
17966322508
"""Config files """ import logging import os import sys from pathlib import Path import torch MAIN_PATH = Path(__file__).resolve().parents[1] DATA_PATH = MAIN_PATH / "data" DEPLOY_PATH = MAIN_PATH / "src" / "deploy" ARTIFACT_PATH = MAIN_PATH / "artifacts" DEVICE = torch.device("cuda") if torch.cuda.is_available() el...
benjaminlq/Image-Generation
src/config.py
config.py
py
1,838
python
en
code
0
github-code
36
34181502633
from typing import Dict, Optional, Type, Union, Callable, Any from types import TracebackType from functools import wraps from threading import Lock from qiskit_ibm_provider.utils.converters import hms_to_seconds from qiskit_ibm_runtime import QiskitRuntimeService from .runtime_job import RuntimeJob from .utils.resul...
Qiskit/qiskit-ibm-runtime
qiskit_ibm_runtime/session.py
session.py
py
11,847
python
en
code
106
github-code
36
177355358
def kerulet(r): pi = 3.14 return(2*r*pi) def terulet(r): pi = 3.14 return(r**2)*pi sugar = float(input("A kör sugara: ")) K = kerulet(sugar) T = terulet(sugar) print("A kör kerülete: {0} egység.".format(K)) print("A kör területe: {0} négyzetegység.".format(T))
martinez7200/progalapok
kor_kerulet.py
kor_kerulet.py
py
294
python
hu
code
0
github-code
36
26967199764
from flask import Flask, jsonify, request, make_response from functions import calculate_penalty,possession app = Flask(__name__) @app.route('/') def index(): return 'This is index page' @app.route('/penalties', methods={'POST'}) def getpenalities(): drug_class=request.form.get('drug_class') ...
Mubashar2014/penalties
main.py
main.py
py
899
python
en
code
0
github-code
36
7499185502
""" Created on Sat Oct 20 16:01:38 2018 @author: Varun """ import numpy as np import pandas as pd from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dropout, Flatten, Dense from keras import applications import shutil #reads in csv file df = pd.read...
varunvenkitachalam/GenderDetector_MachineLearning
UltimateGenderSplit.py
UltimateGenderSplit.py
py
3,040
python
en
code
0
github-code
36
70970697063
# -*- coding: utf-8 -*- """ Created on Fri Nov 27 07:57:10 2020 @author: KANNAN """ from flask import Flask, render_template, request import pandas as pd #import sklearn import pickle model = pickle.load(open("flight_rf.pkl", "rb")) app = Flask(__name__) @app.route('/') def home(): return r...
GuruYohesh/ML
Flight Fare Prediction/app.py
app.py
py
9,556
python
en
code
0
github-code
36
12487085880
""" Lists Basics - More Exercises Check your code: https://judge.softuni.bg/Contests/Practice/Index/1726#3 SUPyF2 Lists More Exercise - 04. Battle Ships Problem: You will be given a number n representing the number of rows of the field. On the next n lines you will receive each row of the field as a string wi...
SimeonTsvetanov/Coding-Lessons
SoftUni Lessons/Python Development/Python Fundamentals September 2019/Problems And Files/10 EXERCISE LISTS BASICS - Дата 4-ти октомври, 1430 - 1730/More Exercises/04. Battle Ships.py
04. Battle Ships.py
py
1,335
python
en
code
9
github-code
36
27053438479
import pytest from subarraySum import Solution @pytest.mark.parametrize("nums, k, expected", [ ([], 2, 0), ([1, 1, 1], 2, 2), ([1, 1, 1, 1], 2, 3) ]) def test_subarraySum(nums, k, expected): actual = Solution().subarraySum(nums, k) assert actual == expected
ikedaosushi/leetcode
problems/python/tests/test_subarraySum.py
test_subarraySum.py
py
280
python
en
code
1
github-code
36
3202338276
import numpy as np import sys import time sys.path.append("Interface/python/") from init import NeuronLayerBox import cv2 def rgb2gray(rgb): return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) if __name__ == '__main__': NLB=NeuronLayerBox(step_ms=1,model=1,spike=0,restore=0) input_src=[] img=cv2.i...
Megatron2032/NeuronLayerBox
NeuronLayerBox1.1/main.py
main.py
py
641
python
en
code
0
github-code
36
18297590625
import csv import json BATCH_ID='4574137' ROUND='1' with open('wrong_hit.txt'.format(BATCH_ID)) as f: wrong_hit = f.read().splitlines() # print(len(wrong_hit)) save_data = [] csv_columns = [] all = 0 wrong = 0 with open('csv/Batch_{}_batch_results{}.csv'.format(BATCH_ID, '_'+ROUND if ROUND != '0' else ''), n...
BernieZhu/Trashbot-Dataset
tools/review_batch.py
review_batch.py
py
2,552
python
en
code
0
github-code
36
9997089912
import sys import codecs def readFile(tweetFileName,classFileName) : classMap = dict() fin1 = codecs.open(tweetFileName) fin2 = codecs.open(classFileName) for inputline1 in fin1 : inputline1 = inputline1.strip('\r\n') inputline2 = fin2.next().strip('\r\n') if inputline2 not in classMap : classMap[inputli...
satheeshkumark/NLP
Sentiment_Analysis/scripts/formEqualDistribution.py
formEqualDistribution.py
py
905
python
en
code
0
github-code
36
17440403303
from tensorflow.keras import layers, models import glob import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from datetime import datetime width = 75 height = 100 channel = 1 def load_data(): images = np.array([]).reshape(0, height, width) labels = np.array([]) d...
NikolaBrodic/VehicleLicencePlateAndLogoRecognition
character_recognition_cnn.py
character_recognition_cnn.py
py
2,599
python
en
code
1
github-code
36
41551040241
import cv2 import os import numpy as np import json import mmcv from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon import matplotlib.pyplot as plt from glob import glob import ast from mmrotate.core import poly2obb_np def poly2obb_np_oc(poly): """Convert polygons to oriented ...
parkyongjun1/rotated_deformabledetr
AO2-DETR/tools/arirang_json_to_txt.py
arirang_json_to_txt.py
py
12,936
python
en
code
0
github-code
36
19848816787
import json no = 0 groups = 0 reserve = [] data = { "no": no, "groups": groups, "reserve": reserve } with open("data.json", "w") as f: json.dump(data, f) opend = open("./data.json","r") loaded = json.load(opend) print(loaded) print("no: ", loaded["no"], "groups: ", loaded["groups"])
hmjn023/dev-hmjn
js.py
js.py
py
318
python
en
code
1
github-code
36
19033935152
"""Module contains functionality that parses main page for RedHat vulnerabilities.""" import time import lxml import lxml.etree from selenium import webdriver from selenium.common.exceptions import WebDriverException, NoSuchElementException from selenium.webdriver.chrome.options import Options from cve_connector.vend...
CSIRT-MU/CRUSOE
crusoe_observe/cve-connector/cve_connector/vendor_cve/implementation/parsers/vendor_parsers/redhat_parsers/red_hat_main_page_parser.py
red_hat_main_page_parser.py
py
4,549
python
en
code
9
github-code
36
36538905715
import matplotlib.pyplot as plt from pymol import cmd from multiprocessing import Pool, cpu_count from tqdm import tqdm # Import tqdm for progress bar # Define a function to calculate RMSD for a single frame def calculate_rmsd(frame_number, object_1, reference_object): cmd.frame(frame_number) #cmd.align(objec...
raafik980/charmm-md-analysis-in-pymol
02_rmsd_vs_frame_parallel.py
02_rmsd_vs_frame_parallel.py
py
2,523
python
en
code
0
github-code
36
6795368681
from django.conf import settings from django.db.models import Q from django_filters import rest_framework as filters from ...models import Event class EventFilterSet(filters.FilterSet): category = filters.MultipleChoiceFilter( method='filter_category', label='Category', choices=settings...
tomasgarzon/exo-services
service-exo-events/event/api/filters/event.py
event.py
py
1,666
python
en
code
0
github-code
36
14551270733
from io import StringIO from itertools import chain from typing import Any, Dict, List, Union import simplejson as json from jubeatools import song as jbt from jubeatools.formats.filetypes import SongFile from jubeatools.utils import lcm from ..tools import make_memon_dumper from . import schema def _long_note_tai...
Stepland/jubeatools
jubeatools/formats/memon/v0/dump.py
dump.py
py
8,590
python
en
code
4
github-code
36
9507730487
# -*- coding: utf-8 -*- """ Created on Mon Jan 13 18:52:23 2020 @author: Hasnain Khan """ import numpy as np import cv2 from matplotlib import pyplot as plt # Convolv function for convolving the kernel with real image matrix def convolve_np(image, kernel): X_height = image.shape[0] X_width = im...
HasnainKhanNiazi/Convolutional-Kernels
Sobel_Operator.py
Sobel_Operator.py
py
1,479
python
en
code
1
github-code
36
29231023064
#!/bin/python import math import os import random import re import sys # Complete the workbook function below. def workbook(n, k, arr): pages = 0 problemsInPage = 0 specialProblems = 0 pageNumber = 1 listOfProblems = dict() chapterNumber = 1 for i in arr: pag...
rsundar/data-structures
hackerrank solutions/lisas-workbook.py
lisas-workbook.py
py
851
python
en
code
0
github-code
36
29632863333
import discord from discord.ext import commands from datetime import datetime from fun_config import * class Work(commands.Cog): def __init__(self, client: commands.Bot): self.client = client @commands.command() @commands.cooldown(1, 86400, commands.BucketType.user) async def sleep(self, ctx)...
Maghish/HoeX
cogs/work.py
work.py
py
835
python
en
code
1
github-code
36
15202662310
def swapFileData(): first=input("pls enter first file name:") second=input("pls enter second file name:") data_a=open(second.txt) data_b=open(first.txt) print(first) print(second) swapFileData()
siddhant15oo/pro-98
SwappingFile.py
SwappingFile.py
py
222
python
en
code
0
github-code
36
70721444264
import numpy as np import plotly.offline as ply import plotly.graph_objs as go from scipy import stats as st from scipy import signal as sg import source_localization as src file_name = "/home/dima/Projects/Touchdown/Data/test.bin" ch_total = 6 length = 2**15 + 100000 fs = 100e6 t_pulse_width = 100e-6 t_period = 200e-...
DimaZhu/libsource_localization
tests/test_specframewriter.py
test_specframewriter.py
py
2,935
python
en
code
0
github-code
36
29184316598
import sys import numpy as np import pyautogui import win32api, win32con, win32gui import cv2 import time import torch import time class_names = [ 'counter-terrorist', 'terrorist' ] opponent = 'terrorist' opponent_color = (255, 0, 0) ally_color = (0, 128, 255) model_path = 'best-640.pt' image_size = 640 scale_map = { ...
anaandjelic/soft-computing-project
aimbot.py
aimbot.py
py
3,412
python
en
code
1
github-code
36
14065650419
import sys input = sys.stdin.readline N = int(input()) T = [0] * N P = [0] * N for a in range(N): t, p = map(int, input().split()) T[a] = t P[a] = p dp =[0] * (N+1) for i in range(N): if T[i] <= N-i: dp[i+T[i]] = max(dp[i+T[i]], dp[i]+P[i]) dp[i+1] = max(dp[i+1], dp[i]) print(dp[-1])
yeon-june/BaekJoon
15486.py
15486.py
py
317
python
en
code
0
github-code
36
1369587477
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from models import Company def index(request): companies = Company.objects.all().order_by('name') paginator = Paginator(companies, 10) ...
avallete/ft_companysee
company/views.py
views.py
py
863
python
en
code
0
github-code
36
34988613077
with open('input.txt', 'r') as f: jolts = [int(line.strip()) for line in f.readlines()] sjolts = [0, *sorted(jolts), max(jolts) + 3] diffs = [b - a for a, b in zip(sjolts[:-1], sjolts[1:])] a = sum(d == 1 for d in diffs) b = sum(d == 3 for d in diffs) print(a*b)
JeroenMandersloot/aoc2020
day10/puzzle1.py
puzzle1.py
py
269
python
en
code
0
github-code
36
3587965918
import subprocess from platform import release from typing import List from libqtile import bar, layout, widget, hook from libqtile.config import Click, Drag, Group, Key, Screen from libqtile.lazy import lazy # defaults mod = "mod4" terminal = "termite" browser = "firefox" media = "stremio" fileManager = "nemo" game=...
TalkingPanda0/dotfiles
.config/qtile/qtile/config.py
config.py
py
7,903
python
en
code
0
github-code
36
11757705834
import numpy as np #Solving the first 10 exercises: #1.Write a NumPy program to get the numpy version and show numpy build configuration: def exercise1(): npVersion = np.__version__ print("The numpy version is",npVersion) #2. Write a NumPy program to get help on the add function def exercise2(): getHelpAddFun...
mauriciopssantos/NumpyExercises
NumpyBasics/exercise1to10.py
exercise1to10.py
py
3,750
python
en
code
0
github-code
36
43850231663
import pandas as pd import numpy as np def func23(): l= [1,34,5,100,2] l.sort(reverse=True) return l def listar(): xx=[1,2,3,4,5,6,7,8,9,10,11] return (list(filter(lambda x: x %2 ==0,xx))) def colors(): lista=[22,33,44,55,66] g=int(np.average(lista)) print(g) def arregloletra...
eloyina/answerpython
answers.py
answers.py
py
1,611
python
en
code
0
github-code
36
25813329582
from sys import stdin def cd(): collection = set() n = nums.pop() m = nums.pop() if (n == 0 and m == 0): return -1 s = 0 for _ in range(n): collection.add(nums.pop()) for _ in range(m): if nums.pop() in collection: s += 1 return s nums = list(m...
Anders-E/Kattis
cd/cd.py
cd.py
py
422
python
en
code
4
github-code
36
29265371613
import turtle import pandas # Everything about turtle screen = turtle.Screen() screen.title("U.S. states") image = "blank_states_img.gif" screen.addshape(image) turtle.shape(image) screen.setup(width=750, height=520) state_name = turtle.Turtle() state_name.hideturtle() state_name.penup() # Everything ab...
Sina-Eshrati/US-States-Game
main.py
main.py
py
1,427
python
en
code
0
github-code
36
19130481877
from datetime import datetime import json class Observation(): def __init__(self, observationTime, numericValue, stringValue, booleanValue, sensorId): self.observationTime = observationTime.strftime("%m/%d/%Y, %H:%M:%S") self.Value = numericValue self.valueString = stringValue self....
midcoreboot/RaspberryPiSensors
REC.py
REC.py
py
675
python
en
code
0
github-code
36
15419782961
#!/usr/bin/python3 # Dump memory of a process (Linux only). # Based on Giles's answer from # https://unix.stackexchange.com/questions/6267/how-to-re-load-all-running-applications-from-swap-space-into-ram/#6271 # # Error checking added by hackerb9. import ctypes, re, sys ## Partial interface to ptrace(2), only for PT...
hackerb9/memcat
memcat.py
memcat.py
py
2,573
python
en
code
10
github-code
36
30504364246
import numpy as np import cv2 from sklearn.cluster import KMeans import pdb from skimage.util import montage import matplotlib.pyplot as plt ''' K means clustering with 30 classes: 26 letters, 1 blank time, 1 double letter, 1 triple letter, 1 empty''' # gather images that have been labelled f = open('labels.txt') d...
meicholtz/scrabble
clustering.py
clustering.py
py
2,242
python
en
code
0
github-code
36
33149847347
import argparse import collections from datetime import datetime import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import numpy import sys import time import json import zenoh # --- Command line argument parsing --- --- --- --- --- --- parser = argparse.ArgumentParser( prog='z_plot', ...
eclipse-zenoh/zenoh-demos
plotting/zplot/z_plot.py
z_plot.py
py
2,515
python
en
code
27
github-code
36
20189362717
import argparse from pathlib import Path from os.path import basename, isfile, isdir, splitext import glob def _list_modules(folder_name): modules = glob.glob(str(Path(__file__).resolve().parent / folder_name / '*')) return list( splitext(basename(f))[0] for f in modules if (isfile(f) ...
patli96/COMP9517_20T1
pedestrian_monitor/console_arguments.py
console_arguments.py
py
4,198
python
en
code
1
github-code
36
38715734412
#!/usr/bin/env python3 import re gates = {} cache = {} def ev(gate_id): if gate_id not in cache: cache[gate_id] = gates[gate_id].evaluate() return cache[gate_id] class ConstantGate: def __init__(self, value): self.value = value def evaluate(self): if self.value.isnumeric(): ...
lvaughn/advent
2015/7/gates.py
gates.py
py
2,479
python
en
code
1
github-code
36
27550085200
import datetime from imap_tools import EmailAddress DATA = dict( subject='double_fields', from_='kaukinvk@yandex.ru', to=('aa@aa.ru', 'bb@aa.ru'), cc=('cc@aa.ru', 'dd@aa.ru'), bcc=('zz1@aa.ru', 'zz2@aa.ru'), reply_to=('foma1@company.ru', 'petr1@company.ru', 'foma2@company.ru', 'petr2@company.ru...
ikvk/imap_tools
tests/messages_data/double_fields.py
double_fields.py
py
1,917
python
en
code
608
github-code
36
32889657187
import math import os from pickle import FALSE, TRUE import nltk import string from nltk.stem import PorterStemmer import json import tkinter as tk from nltk import WordNetLemmatizer lemmatizer=WordNetLemmatizer() remove_punctuation_translator = str.maketrans(string.punctuation, ' '*len(string.punctuation)) def stopWor...
mustafabawani/Vector-Space-Model
ajeeb.py
ajeeb.py
py
4,976
python
en
code
0
github-code
36
23212333774
from django.test import TestCase from .models import User, Routine, RoutineContent, Task, Advice, Appointment, DayWeek from .get import * from datetime import datetime, timedelta # Create your tests here. class getsFunctionTestCase(TestCase): def setUp(self): user_a = User.objects.create_user(username='u...
eduardofcabrera/CS50-CalendarDay
day_day/tests.py
tests.py
py
6,307
python
en
code
0
github-code
36
38767218323
import streamlit as st import pandas as pd import openai import time import re openai.api_key = st.secrets["openai"] def txt(file): content = file.getvalue().decode('utf-8') documents = content.split("____________________________________________________________") # Removing any empty strings or ones that...
skacholia/AnnotateDemo
main.py
main.py
py
4,539
python
en
code
0
github-code
36
27648052145
from sqlalchemy import create_engine, text db_connection_string = "mysql+pymysql://zi6id5p25yfq60ih6t1y:pscale_pw_OG991jS2It86MJJqrCYvCmcJ5psfFaYkxyOLA9GoTwy@ap-south.connect.psdb.cloud/enantiomer?charset=utf8mb4" engine = create_engine(db_connection_string, connect_args={"ssl": { ...
ismaehl-2002/enantiomer-website-v2
database.py
database.py
py
579
python
en
code
1
github-code
36
24688793907
from typing import Sequence class NetStats: def __init__( self, net, input_shape: Sequence[int], backend: str = "torch", self_defined_imp_class = None ): if self_defined_imp_class is None: if backend == "torch": from reunn.implementation import torch_imp ...
AllenYolk/reusable-nn-code
reunn/stats.py
stats.py
py
954
python
en
code
1
github-code
36
29947905371
import requests class Test_new_joke(): """Создание новой шутки""" def __init__(self): pass def get_categories(self): """Получение категориb шуток""" url_categories = "https://api.chucknorris.io/jokes/categories" print("Получение категорий шуток по ссылке - " + url_categ...
Grassh-str/Test_api_ChuckNorris
api_chuck.py
api_chuck.py
py
2,399
python
ru
code
0
github-code
36
41772303500
import glob import json import subprocess from utils import PathUtils from plot_sim_results import plot_multiple_results EXP_CONFIGS = ['ring_local_config', 'ring_consensus_config'] if __name__ == '__main__': ring_configs = glob.glob(str(PathUtils.exp_configs_folder) + '/ring' + '/*.py') for...
matteobettini/Autonomous-Vehicles-Consensus-2021
run_experiments_ring.py
run_experiments_ring.py
py
1,084
python
en
code
0
github-code
36
26377040664
import ast import os from django.http import JsonResponse from django.shortcuts import render, HttpResponse from django.conf import settings import json import commons.helper # Create your views here. """ Google Map """ def map_hello_world(request): """ Renders a page with embedded Google map. Passes varia...
TAMUSA-nsf-project/django_smartmap
map/views.py
views.py
py
1,701
python
en
code
2
github-code
36
73435015143
import numpy import statsmodels.regression import statsmodels.tools import scipy.optimize as opti import scipy.interpolate as interp import scipy.signal as signal import matplotlib.pyplot as plt class PVP: def __init__(self, sampling_period=0.01): self.sampling_period = sampling_period self._kinem...
jgori-ouistiti/PVPlib
pvplib/core.py
core.py
py
24,949
python
en
code
0
github-code
36
71918398185
#! /bin/env python import sys particleSize = 0.02 if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " <scene txt file>") else: # Read the scene file scene = open(sys.argv[1]).readlines()[1:] particleString = '' for l in scene: loc = [float(x) for x in l.split()] particleS...
bryanpeele/PositionBasedFluids
frames/makeMitsubaFile.py
makeMitsubaFile.py
py
775
python
en
code
2
github-code
36
8024443031
""" You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up: Could you do this in-place? """ class Solution: # @param matrix, a list of lists of integers # @return a list of lists of integers def rotate(self, matrix): start = 0 end = l...
cyandterry/Python-Study
Ninja/Leetcode/48_Rotate_Image.py
48_Rotate_Image.py
py
1,071
python
en
code
62
github-code
36